]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
8280e22afbd63d13df0f42903ec7d16b6287e47b
[openldap] / libraries / libmdb / 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-2012 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 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/param.h>
38 #ifdef _WIN32
39 #include <windows.h>
40 #else
41 #include <sys/uio.h>
42 #include <sys/mman.h>
43 #ifdef HAVE_SYS_FILE_H
44 #include <sys/file.h>
45 #endif
46 #include <fcntl.h>
47 #endif
48
49 #include <assert.h>
50 #include <errno.h>
51 #include <limits.h>
52 #include <stddef.h>
53 #include <inttypes.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <time.h>
58 #include <unistd.h>
59
60 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
61 #include <resolv.h>     /* defines BYTE_ORDER on HPUX and Solaris */
62 #endif
63
64 #ifndef _WIN32
65 #include <pthread.h>
66 #ifdef __APPLE__
67 #include <semaphore.h>
68 #endif
69 #endif
70
71 #ifdef USE_VALGRIND
72 #include <valgrind/memcheck.h>
73 #define VGMEMP_CREATE(h,r,z)    VALGRIND_CREATE_MEMPOOL(h,r,z)
74 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
75 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
76 #define VGMEMP_DESTROY(h)       VALGRIND_DESTROY_MEMPOOL(h)
77 #define VGMEMP_DEFINED(a,s)     VALGRIND_MAKE_MEM_DEFINED(a,s)
78 #else
79 #define VGMEMP_CREATE(h,r,z)
80 #define VGMEMP_ALLOC(h,a,s)
81 #define VGMEMP_FREE(h,a)
82 #define VGMEMP_DESTROY(h)
83 #define VGMEMP_DEFINED(a,s)
84 #endif
85
86 #ifndef BYTE_ORDER
87 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
88 /* Solaris just defines one or the other */
89 #  define LITTLE_ENDIAN 1234
90 #  define BIG_ENDIAN    4321
91 #  ifdef _LITTLE_ENDIAN
92 #   define BYTE_ORDER  LITTLE_ENDIAN
93 #  else
94 #   define BYTE_ORDER  BIG_ENDIAN
95 #  endif
96 # else
97 #  define BYTE_ORDER   __BYTE_ORDER
98 # endif
99 #endif
100
101 #ifndef LITTLE_ENDIAN
102 #define LITTLE_ENDIAN   __LITTLE_ENDIAN
103 #endif
104 #ifndef BIG_ENDIAN
105 #define BIG_ENDIAN      __BIG_ENDIAN
106 #endif
107
108 #if defined(__i386) || defined(__x86_64)
109 #define MISALIGNED_OK   1
110 #endif
111
112 #include "mdb.h"
113 #include "midl.h"
114
115 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
116 # error "Unknown or unsupported endianness (BYTE_ORDER)"
117 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
118 # error "Two's complement, reasonably sized integer types, please"
119 #endif
120
121 /** @defgroup internal  MDB Internals
122  *      @{
123  */
124 /** @defgroup compat    Windows Compatibility Macros
125  *      A bunch of macros to minimize the amount of platform-specific ifdefs
126  *      needed throughout the rest of the code. When the features this library
127  *      needs are similar enough to POSIX to be hidden in a one-or-two line
128  *      replacement, this macro approach is used.
129  *      @{
130  */
131 #ifdef _WIN32
132 #define pthread_t       DWORD
133 #define pthread_mutex_t HANDLE
134 #define pthread_key_t   DWORD
135 #define pthread_self()  GetCurrentThreadId()
136 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
137 #define pthread_key_delete(x)   TlsFree(x)
138 #define pthread_getspecific(x)  TlsGetValue(x)
139 #define pthread_setspecific(x,y)        TlsSetValue(x,y)
140 #define pthread_mutex_unlock(x) ReleaseMutex(x)
141 #define pthread_mutex_lock(x)   WaitForSingleObject(x, INFINITE)
142 #define LOCK_MUTEX_R(env)       pthread_mutex_lock((env)->me_rmutex)
143 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock((env)->me_rmutex)
144 #define LOCK_MUTEX_W(env)       pthread_mutex_lock((env)->me_wmutex)
145 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock((env)->me_wmutex)
146 #define getpid()        GetCurrentProcessId()
147 #define fdatasync(fd)   (!FlushFileBuffers(fd))
148 #define ErrCode()       GetLastError()
149 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
150 #define close(fd)       CloseHandle(fd)
151 #define munmap(ptr,len) UnmapViewOfFile(ptr)
152 #else
153 #ifdef __APPLE__
154 #define LOCK_MUTEX_R(env)       sem_wait((env)->me_rmutex)
155 #define UNLOCK_MUTEX_R(env)     sem_post((env)->me_rmutex)
156 #define LOCK_MUTEX_W(env)       sem_wait((env)->me_wmutex)
157 #define UNLOCK_MUTEX_W(env)     sem_post((env)->me_wmutex)
158 #define fdatasync(fd)   fsync(fd)
159 #else
160 #ifdef ANDROID
161 #define fdatasync(fd)   fsync(fd)
162 #endif
163         /** Lock the reader mutex.
164          */
165 #define LOCK_MUTEX_R(env)       pthread_mutex_lock(&(env)->me_txns->mti_mutex)
166         /** Unlock the reader mutex.
167          */
168 #define UNLOCK_MUTEX_R(env)     pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
169
170         /** Lock the writer mutex.
171          *      Only a single write transaction is allowed at a time. Other writers
172          *      will block waiting for this mutex.
173          */
174 #define LOCK_MUTEX_W(env)       pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
175         /** Unlock the writer mutex.
176          */
177 #define UNLOCK_MUTEX_W(env)     pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
178 #endif  /* __APPLE__ */
179
180         /** Get the error code for the last failed system function.
181          */
182 #define ErrCode()       errno
183
184         /** An abstraction for a file handle.
185          *      On POSIX systems file handles are small integers. On Windows
186          *      they're opaque pointers.
187          */
188 #define HANDLE  int
189
190         /**     A value for an invalid file handle.
191          *      Mainly used to initialize file variables and signify that they are
192          *      unused.
193          */
194 #define INVALID_HANDLE_VALUE    (-1)
195
196         /** Get the size of a memory page for the system.
197          *      This is the basic size that the platform's memory manager uses, and is
198          *      fundamental to the use of memory-mapped files.
199          */
200 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
201 #endif
202
203 #if defined(_WIN32) || defined(__APPLE__)
204 #define MNAME_LEN       32
205 #else
206 #define MNAME_LEN       (sizeof(pthread_mutex_t))
207 #endif
208
209 /** @} */
210
211 #ifndef _WIN32
212 /**     A flag for opening a file and requesting synchronous data writes.
213  *      This is only used when writing a meta page. It's not strictly needed;
214  *      we could just do a normal write and then immediately perform a flush.
215  *      But if this flag is available it saves us an extra system call.
216  *
217  *      @note If O_DSYNC is undefined but exists in /usr/include,
218  * preferably set some compiler flag to get the definition.
219  * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
220  */
221 #ifndef MDB_DSYNC
222 # define MDB_DSYNC      O_DSYNC
223 #endif
224 #endif
225
226 /** Function for flushing the data of a file. Define this to fsync
227  *      if fdatasync() is not supported.
228  */
229 #ifndef MDB_FDATASYNC
230 # define MDB_FDATASYNC  fdatasync
231 #endif
232
233         /** A page number in the database.
234          *      Note that 64 bit page numbers are overkill, since pages themselves
235          *      already represent 12-13 bits of addressable memory, and the OS will
236          *      always limit applications to a maximum of 63 bits of address space.
237          *
238          *      @note In the #MDB_node structure, we only store 48 bits of this value,
239          *      which thus limits us to only 60 bits of addressable data.
240          */
241 typedef ID      pgno_t;
242
243         /** A transaction ID.
244          *      See struct MDB_txn.mt_txnid for details.
245          */
246 typedef ID      txnid_t;
247
248 /** @defgroup debug     Debug Macros
249  *      @{
250  */
251 #ifndef MDB_DEBUG
252         /**     Enable debug output.
253          *      Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
254          *      read from and written to the database (used for free space management).
255          */
256 #define MDB_DEBUG 0
257 #endif
258
259 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
260 # define DPRINTF        (void)  /* Vararg macros may be unsupported */
261 #elif MDB_DEBUG
262 static int mdb_debug;
263 static txnid_t mdb_debug_start;
264
265         /**     Print a debug message with printf formatting. */
266 # define DPRINTF(fmt, ...)      /**< Requires 2 or more args */ \
267         ((void) ((mdb_debug) && \
268          fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
269 #else
270 # define DPRINTF(fmt, ...)      ((void) 0)
271 #endif
272         /**     Print a debug string.
273          *      The string is printed literally, with no format processing.
274          */
275 #define DPUTS(arg)      DPRINTF("%s", arg)
276 /** @} */
277
278         /** A default memory page size.
279          *      The actual size is platform-dependent, but we use this for
280          *      boot-strapping. We probably should not be using this any more.
281          *      The #GET_PAGESIZE() macro is used to get the actual size.
282          *
283          *      Note that we don't currently support Huge pages. On Linux,
284          *      regular data files cannot use Huge pages, and in general
285          *      Huge pages aren't actually pageable. We rely on the OS
286          *      demand-pager to read our data and page it out when memory
287          *      pressure from other processes is high. So until OSs have
288          *      actual paging support for Huge pages, they're not viable.
289          */
290 #define MDB_PAGESIZE     4096
291
292         /** The minimum number of keys required in a database page.
293          *      Setting this to a larger value will place a smaller bound on the
294          *      maximum size of a data item. Data items larger than this size will
295          *      be pushed into overflow pages instead of being stored directly in
296          *      the B-tree node. This value used to default to 4. With a page size
297          *      of 4096 bytes that meant that any item larger than 1024 bytes would
298          *      go into an overflow page. That also meant that on average 2-3KB of
299          *      each overflow page was wasted space. The value cannot be lower than
300          *      2 because then there would no longer be a tree structure. With this
301          *      value, items larger than 2KB will go into overflow pages, and on
302          *      average only 1KB will be wasted.
303          */
304 #define MDB_MINKEYS      2
305
306         /**     A stamp that identifies a file as an MDB file.
307          *      There's nothing special about this value other than that it is easily
308          *      recognizable, and it will reflect any byte order mismatches.
309          */
310 #define MDB_MAGIC        0xBEEFC0DE
311
312         /**     The version number for a database's file format. */
313 #define MDB_VERSION      1
314
315         /**     The maximum size of a key in the database.
316          *      While data items have essentially unbounded size, we require that
317          *      keys all fit onto a regular page. This limit could be raised a bit
318          *      further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
319          */
320 #define MAXKEYSIZE       511
321
322 #if MDB_DEBUG
323         /**     A key buffer.
324          *      @ingroup debug
325          *      This is used for printing a hex dump of a key's contents.
326          */
327 #define DKBUF   char kbuf[(MAXKEYSIZE*2+1)]
328         /**     Display a key in hex.
329          *      @ingroup debug
330          *      Invoke a function to display a key in hex.
331          */
332 #define DKEY(x) mdb_dkey(x, kbuf)
333 #else
334 #define DKBUF   typedef int dummy_kbuf  /* so we can put ';' after */
335 #define DKEY(x) 0
336 #endif
337
338 /**     @defgroup lazylock      Lazy Locking
339  *      Macros for locks that aren't actually needed.
340  *      The DB view is always consistent because all writes are wrapped in
341  *      the wmutex. Finer-grained locks aren't necessary.
342  *      @{
343  */
344 #ifndef LAZY_LOCKS
345         /**     Use lazy locking. I.e., don't lock these accesses at all. */
346 #define LAZY_LOCKS      1
347 #endif
348 #if     LAZY_LOCKS
349         /** Grab the reader lock */
350 #define LAZY_MUTEX_LOCK(x)
351         /** Release the reader lock */
352 #define LAZY_MUTEX_UNLOCK(x)
353         /** Release the DB table reader/writer lock */
354 #define LAZY_RWLOCK_UNLOCK(x)
355         /** Grab the DB table write lock */
356 #define LAZY_RWLOCK_WRLOCK(x)
357         /** Grab the DB table read lock */
358 #define LAZY_RWLOCK_RDLOCK(x)
359         /** Declare the DB table rwlock.  Should not be followed by ';'. */
360 #define LAZY_RWLOCK_DEF(x)
361         /** Initialize the DB table rwlock */
362 #define LAZY_RWLOCK_INIT(x,y)
363         /**     Destroy the DB table rwlock */
364 #define LAZY_RWLOCK_DESTROY(x)
365 #else
366 #define LAZY_MUTEX_LOCK(x)              pthread_mutex_lock(x)
367 #define LAZY_MUTEX_UNLOCK(x)    pthread_mutex_unlock(x)
368 #define LAZY_RWLOCK_UNLOCK(x)   pthread_rwlock_unlock(x)
369 #define LAZY_RWLOCK_WRLOCK(x)   pthread_rwlock_wrlock(x)
370 #define LAZY_RWLOCK_RDLOCK(x)   pthread_rwlock_rdlock(x)
371 #define LAZY_RWLOCK_DEF(x)              pthread_rwlock_t        x;
372 #define LAZY_RWLOCK_INIT(x,y)   pthread_rwlock_init(x,y)
373 #define LAZY_RWLOCK_DESTROY(x)  pthread_rwlock_destroy(x)
374 #endif
375 /** @} */
376
377         /** An invalid page number.
378          *      Mainly used to denote an empty tree.
379          */
380 #define P_INVALID        (~0UL)
381
382         /** Test if a flag \b f is set in a flag word \b w. */
383 #define F_ISSET(w, f)    (((w) & (f)) == (f))
384
385         /**     Used for offsets within a single page.
386          *      Since memory pages are typically 4 or 8KB in size, 12-13 bits,
387          *      this is plenty.
388          */
389 typedef uint16_t         indx_t;
390
391         /**     Default size of memory map.
392          *      This is certainly too small for any actual applications. Apps should always set
393          *      the size explicitly using #mdb_env_set_mapsize().
394          */
395 #define DEFAULT_MAPSIZE 1048576
396
397 /**     @defgroup readers       Reader Lock Table
398  *      Readers don't acquire any locks for their data access. Instead, they
399  *      simply record their transaction ID in the reader table. The reader
400  *      mutex is needed just to find an empty slot in the reader table. The
401  *      slot's address is saved in thread-specific data so that subsequent read
402  *      transactions started by the same thread need no further locking to proceed.
403  *
404  *      Since the database uses multi-version concurrency control, readers don't
405  *      actually need any locking. This table is used to keep track of which
406  *      readers are using data from which old transactions, so that we'll know
407  *      when a particular old transaction is no longer in use. Old transactions
408  *      that have discarded any data pages can then have those pages reclaimed
409  *      for use by a later write transaction.
410  *
411  *      The lock table is constructed such that reader slots are aligned with the
412  *      processor's cache line size. Any slot is only ever used by one thread.
413  *      This alignment guarantees that there will be no contention or cache
414  *      thrashing as threads update their own slot info, and also eliminates
415  *      any need for locking when accessing a slot.
416  *
417  *      A writer thread will scan every slot in the table to determine the oldest
418  *      outstanding reader transaction. Any freed pages older than this will be
419  *      reclaimed by the writer. The writer doesn't use any locks when scanning
420  *      this table. This means that there's no guarantee that the writer will
421  *      see the most up-to-date reader info, but that's not required for correct
422  *      operation - all we need is to know the upper bound on the oldest reader,
423  *      we don't care at all about the newest reader. So the only consequence of
424  *      reading stale information here is that old pages might hang around a
425  *      while longer before being reclaimed. That's actually good anyway, because
426  *      the longer we delay reclaiming old pages, the more likely it is that a
427  *      string of contiguous pages can be found after coalescing old pages from
428  *      many old transactions together.
429  *
430  *      @todo We don't actually do such coalescing yet, we grab pages from one
431  *      old transaction at a time.
432  *      @{
433  */
434         /**     Number of slots in the reader table.
435          *      This value was chosen somewhat arbitrarily. 126 readers plus a
436          *      couple mutexes fit exactly into 8KB on my development machine.
437          *      Applications should set the table size using #mdb_env_set_maxreaders().
438          */
439 #define DEFAULT_READERS 126
440
441         /**     The size of a CPU cache line in bytes. We want our lock structures
442          *      aligned to this size to avoid false cache line sharing in the
443          *      lock table.
444          *      This value works for most CPUs. For Itanium this should be 128.
445          */
446 #ifndef CACHELINE
447 #define CACHELINE       64
448 #endif
449
450         /**     The information we store in a single slot of the reader table.
451          *      In addition to a transaction ID, we also record the process and
452          *      thread ID that owns a slot, so that we can detect stale information,
453          *      e.g. threads or processes that went away without cleaning up.
454          *      @note We currently don't check for stale records. We simply re-init
455          *      the table when we know that we're the only process opening the
456          *      lock file.
457          */
458 typedef struct MDB_rxbody {
459         /**     The current Transaction ID when this transaction began.
460          *      Multiple readers that start at the same time will probably have the
461          *      same ID here. Again, it's not important to exclude them from
462          *      anything; all we need to know is which version of the DB they
463          *      started from so we can avoid overwriting any data used in that
464          *      particular version.
465          */
466         txnid_t         mrb_txnid;
467         /** The process ID of the process owning this reader txn. */
468         pid_t           mrb_pid;
469         /** The thread ID of the thread owning this txn. */
470         pthread_t       mrb_tid;
471 } MDB_rxbody;
472
473         /** The actual reader record, with cacheline padding. */
474 typedef struct MDB_reader {
475         union {
476                 MDB_rxbody mrx;
477                 /** shorthand for mrb_txnid */
478 #define mr_txnid        mru.mrx.mrb_txnid
479 #define mr_pid  mru.mrx.mrb_pid
480 #define mr_tid  mru.mrx.mrb_tid
481                 /** cache line alignment */
482                 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
483         } mru;
484 } MDB_reader;
485
486         /** The header for the reader table.
487          *      The table resides in a memory-mapped file. (This is a different file
488          *      than is used for the main database.)
489          *
490          *      For POSIX the actual mutexes reside in the shared memory of this
491          *      mapped file. On Windows, mutexes are named objects allocated by the
492          *      kernel; we store the mutex names in this mapped file so that other
493          *      processes can grab them. This same approach is also used on
494          *      MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
495          *      process-shared POSIX mutexes. For these cases where a named object
496          *      is used, the object name is derived from a 64 bit FNV hash of the
497          *      environment pathname. As such, naming collisions are extremely
498          *      unlikely. If a collision occurs, the results are unpredictable.
499          */
500 typedef struct MDB_txbody {
501                 /** Stamp identifying this as an MDB file. It must be set
502                  *      to #MDB_MAGIC. */
503         uint32_t        mtb_magic;
504                 /** Version number of this lock file. Must be set to #MDB_VERSION. */
505         uint32_t        mtb_version;
506 #if defined(_WIN32) || defined(__APPLE__)
507         char    mtb_rmname[MNAME_LEN];
508 #else
509                 /** Mutex protecting access to this table.
510                  *      This is the reader lock that #LOCK_MUTEX_R acquires.
511                  */
512         pthread_mutex_t mtb_mutex;
513 #endif
514 #if MDB_VERSION == 1
515                 /**     The ID of the last transaction committed to the database.
516                  *      This is recorded here only for convenience; the value can always
517                  *      be determined by reading the main database meta pages.
518                  *
519                  *      Value is unused, but maintained for backwards compatibility.
520                  *      Drop this or mtb_me_toggle when changing MDB_VERSION.
521                  *      (Reading both should have been done atomically.)
522                  */
523         txnid_t         mtb_txnid;
524 #endif
525                 /** The number of slots that have been used in the reader table.
526                  *      This always records the maximum count, it is not decremented
527                  *      when readers release their slots.
528                  */
529         unsigned        mtb_numreaders;
530                 /**     The ID of the most recent meta page in the database.
531                  *      This is recorded here only for convenience; the value can always
532                  *      be determined by reading the main database meta pages.
533                  */
534         uint32_t        mtb_me_toggle;
535 } MDB_txbody;
536
537         /** The actual reader table definition. */
538 typedef struct MDB_txninfo {
539         union {
540                 MDB_txbody mtb;
541 #define mti_magic       mt1.mtb.mtb_magic
542 #define mti_version     mt1.mtb.mtb_version
543 #define mti_mutex       mt1.mtb.mtb_mutex
544 #define mti_rmname      mt1.mtb.mtb_rmname
545 #if MDB_VERSION == 1
546 #define mti_txnid       mt1.mtb.mtb_txnid
547 #endif
548 #define mti_numreaders  mt1.mtb.mtb_numreaders
549 #define mti_me_toggle   mt1.mtb.mtb_me_toggle
550                 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
551         } mt1;
552         union {
553 #if defined(_WIN32) || defined(__APPLE__)
554                 char mt2_wmname[MNAME_LEN];
555 #define mti_wmname      mt2.mt2_wmname
556 #else
557                 pthread_mutex_t mt2_wmutex;
558 #define mti_wmutex      mt2.mt2_wmutex
559 #endif
560                 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
561         } mt2;
562         MDB_reader      mti_readers[1];
563 } MDB_txninfo;
564 /** @} */
565
566 /** Common header for all page types.
567  * Overflow records occupy a number of contiguous pages with no
568  * headers on any page after the first.
569  */
570 typedef struct MDB_page {
571 #define mp_pgno mp_p.p_pgno
572 #define mp_next mp_p.p_next
573         union {
574                 pgno_t          p_pgno; /**< page number */
575                 void *          p_next; /**< for in-memory list of freed structs */
576         } mp_p;
577         uint16_t        mp_pad;
578 /**     @defgroup mdb_page      Page Flags
579  *      @ingroup internal
580  *      Flags for the page headers.
581  *      @{
582  */
583 #define P_BRANCH         0x01           /**< branch page */
584 #define P_LEAF           0x02           /**< leaf page */
585 #define P_OVERFLOW       0x04           /**< overflow page */
586 #define P_META           0x08           /**< meta page */
587 #define P_DIRTY          0x10           /**< dirty page */
588 #define P_LEAF2          0x20           /**< for #MDB_DUPFIXED records */
589 #define P_SUBP           0x40           /**< for #MDB_DUPSORT sub-pages */
590 /** @} */
591         uint16_t        mp_flags;               /**< @ref mdb_page */
592 #define mp_lower        mp_pb.pb.pb_lower
593 #define mp_upper        mp_pb.pb.pb_upper
594 #define mp_pages        mp_pb.pb_pages
595         union {
596                 struct {
597                         indx_t          pb_lower;               /**< lower bound of free space */
598                         indx_t          pb_upper;               /**< upper bound of free space */
599                 } pb;
600                 uint32_t        pb_pages;       /**< number of overflow pages */
601         } mp_pb;
602         indx_t          mp_ptrs[1];             /**< dynamic size */
603 } MDB_page;
604
605         /** Size of the page header, excluding dynamic data at the end */
606 #define PAGEHDRSZ        ((unsigned) offsetof(MDB_page, mp_ptrs))
607
608         /** Address of first usable data byte in a page, after the header */
609 #define METADATA(p)      ((void *)((char *)(p) + PAGEHDRSZ))
610
611         /** Number of nodes on a page */
612 #define NUMKEYS(p)       (((p)->mp_lower - PAGEHDRSZ) >> 1)
613
614         /** The amount of space remaining in the page */
615 #define SIZELEFT(p)      (indx_t)((p)->mp_upper - (p)->mp_lower)
616
617         /** The percentage of space used in the page, in tenths of a percent. */
618 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
619                                 ((env)->me_psize - PAGEHDRSZ))
620         /** The minimum page fill factor, in tenths of a percent.
621          *      Pages emptier than this are candidates for merging.
622          */
623 #define FILL_THRESHOLD   250
624
625         /** Test if a page is a leaf page */
626 #define IS_LEAF(p)       F_ISSET((p)->mp_flags, P_LEAF)
627         /** Test if a page is a LEAF2 page */
628 #define IS_LEAF2(p)      F_ISSET((p)->mp_flags, P_LEAF2)
629         /** Test if a page is a branch page */
630 #define IS_BRANCH(p)     F_ISSET((p)->mp_flags, P_BRANCH)
631         /** Test if a page is an overflow page */
632 #define IS_OVERFLOW(p)   F_ISSET((p)->mp_flags, P_OVERFLOW)
633         /** Test if a page is a sub page */
634 #define IS_SUBP(p)       F_ISSET((p)->mp_flags, P_SUBP)
635
636         /** The number of overflow pages needed to store the given size. */
637 #define OVPAGES(size, psize)    ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
638
639         /** Header for a single key/data pair within a page.
640          * We guarantee 2-byte alignment for nodes.
641          */
642 typedef struct MDB_node {
643         /** lo and hi are used for data size on leaf nodes and for
644          * child pgno on branch nodes. On 64 bit platforms, flags
645          * is also used for pgno. (Branch nodes have no flags).
646          * They are in host byte order in case that lets some
647          * accesses be optimized into a 32-bit word access.
648          */
649 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
650 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
651         unsigned short  mn_offset[2];   /**< storage for #mn_lo and #mn_hi */
652 /** @defgroup mdb_node Node Flags
653  *      @ingroup internal
654  *      Flags for node headers.
655  *      @{
656  */
657 #define F_BIGDATA        0x01                   /**< data put on overflow page */
658 #define F_SUBDATA        0x02                   /**< data is a sub-database */
659 #define F_DUPDATA        0x04                   /**< data has duplicates */
660
661 /** valid flags for #mdb_node_add() */
662 #define NODE_ADD_FLAGS  (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
663
664 /** @} */
665         unsigned short  mn_flags;               /**< @ref mdb_node */
666         unsigned short  mn_ksize;               /**< key size */
667         char            mn_data[1];                     /**< key and data are appended here */
668 } MDB_node;
669
670         /** Size of the node header, excluding dynamic data at the end */
671 #define NODESIZE         offsetof(MDB_node, mn_data)
672
673         /** Bit position of top word in page number, for shifting mn_flags */
674 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
675
676         /** Size of a node in a branch page with a given key.
677          *      This is just the node header plus the key, there is no data.
678          */
679 #define INDXSIZE(k)      (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
680
681         /** Size of a node in a leaf page with a given key and data.
682          *      This is node header plus key plus data size.
683          */
684 #define LEAFSIZE(k, d)   (NODESIZE + (k)->mv_size + (d)->mv_size)
685
686         /** Address of node \b i in page \b p */
687 #define NODEPTR(p, i)    ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
688
689         /** Address of the key for the node */
690 #define NODEKEY(node)    (void *)((node)->mn_data)
691
692         /** Address of the data for a node */
693 #define NODEDATA(node)   (void *)((char *)(node)->mn_data + (node)->mn_ksize)
694
695         /** Get the page number pointed to by a branch node */
696 #define NODEPGNO(node) \
697         ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
698          (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
699         /** Set the page number in a branch node */
700 #define SETPGNO(node,pgno)      do { \
701         (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
702         if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
703
704         /** Get the size of the data in a leaf node */
705 #define NODEDSZ(node)    ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
706         /** Set the size of the data for a leaf node */
707 #define SETDSZ(node,size)       do { \
708         (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
709         /** The size of a key in a node */
710 #define NODEKSZ(node)    ((node)->mn_ksize)
711
712         /** Copy a page number from src to dst */
713 #ifdef MISALIGNED_OK
714 #define COPY_PGNO(dst,src)      dst = src
715 #else
716 #if SIZE_MAX > 4294967295UL
717 #define COPY_PGNO(dst,src)      do { \
718         unsigned short *s, *d;  \
719         s = (unsigned short *)&(src);   \
720         d = (unsigned short *)&(dst);   \
721         *d++ = *s++;    \
722         *d++ = *s++;    \
723         *d++ = *s++;    \
724         *d = *s;        \
725 } while (0)
726 #else
727 #define COPY_PGNO(dst,src)      do { \
728         unsigned short *s, *d;  \
729         s = (unsigned short *)&(src);   \
730         d = (unsigned short *)&(dst);   \
731         *d++ = *s++;    \
732         *d = *s;        \
733 } while (0)
734 #endif
735 #endif
736         /** The address of a key in a LEAF2 page.
737          *      LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
738          *      There are no node headers, keys are stored contiguously.
739          */
740 #define LEAF2KEY(p, i, ks)      ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
741
742         /** Set the \b node's key into \b key, if requested. */
743 #define MDB_SET_KEY(node, key)  { if ((key) != NULL) { \
744         (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
745
746         /** Information about a single database in the environment. */
747 typedef struct MDB_db {
748         uint32_t        md_pad;         /**< also ksize for LEAF2 pages */
749         uint16_t        md_flags;       /**< @ref mdb_open */
750         uint16_t        md_depth;       /**< depth of this tree */
751         pgno_t          md_branch_pages;        /**< number of internal pages */
752         pgno_t          md_leaf_pages;          /**< number of leaf pages */
753         pgno_t          md_overflow_pages;      /**< number of overflow pages */
754         size_t          md_entries;             /**< number of data items */
755         pgno_t          md_root;                /**< the root page of this tree */
756 } MDB_db;
757
758         /** Handle for the DB used to track free pages. */
759 #define FREE_DBI        0
760         /** Handle for the default DB. */
761 #define MAIN_DBI        1
762
763         /** Meta page content. */
764 typedef struct MDB_meta {
765                 /** Stamp identifying this as an MDB file. It must be set
766                  *      to #MDB_MAGIC. */
767         uint32_t        mm_magic;
768                 /** Version number of this lock file. Must be set to #MDB_VERSION. */
769         uint32_t        mm_version;
770         void            *mm_address;            /**< address for fixed mapping */
771         size_t          mm_mapsize;                     /**< size of mmap region */
772         MDB_db          mm_dbs[2];                      /**< first is free space, 2nd is main db */
773         /** The size of pages used in this DB */
774 #define mm_psize        mm_dbs[0].md_pad
775         /** Any persistent environment flags. @ref mdb_env */
776 #define mm_flags        mm_dbs[0].md_flags
777         pgno_t          mm_last_pg;                     /**< last used page in file */
778         txnid_t         mm_txnid;                       /**< txnid that committed this page */
779 } MDB_meta;
780
781         /** Buffer for a stack-allocated dirty page.
782          *      The members define size and alignment, and silence type
783          *      aliasing warnings.  They are not used directly; that could
784          *      mean incorrectly using several union members in parallel.
785          */
786 typedef union MDB_pagebuf {
787         char            mb_raw[MDB_PAGESIZE];
788         MDB_page        mb_page;
789         struct {
790                 char            mm_pad[PAGEHDRSZ];
791                 MDB_meta        mm_meta;
792         } mb_metabuf;
793 } MDB_pagebuf;
794
795         /** Auxiliary DB info.
796          *      The information here is mostly static/read-only. There is
797          *      only a single copy of this record in the environment.
798          */
799 typedef struct MDB_dbx {
800         MDB_val         md_name;                /**< name of the database */
801         MDB_cmp_func    *md_cmp;        /**< function for comparing keys */
802         MDB_cmp_func    *md_dcmp;       /**< function for comparing data items */
803         MDB_rel_func    *md_rel;        /**< user relocate function */
804         void            *md_relctx;             /**< user-provided context for md_rel */
805 } MDB_dbx;
806
807         /** A database transaction.
808          *      Every operation requires a transaction handle.
809          */
810 struct MDB_txn {
811         MDB_txn         *mt_parent;             /**< parent of a nested txn */
812         MDB_txn         *mt_child;              /**< nested txn under this txn */
813         pgno_t          mt_next_pgno;   /**< next unallocated page */
814         /** The ID of this transaction. IDs are integers incrementing from 1.
815          *      Only committed write transactions increment the ID. If a transaction
816          *      aborts, the ID may be re-used by the next writer.
817          */
818         txnid_t         mt_txnid;
819         MDB_env         *mt_env;                /**< the DB environment */
820         /** The list of pages that became unused during this transaction.
821          */
822         IDL                     mt_free_pgs;
823         union {
824                 ID2L    dirty_list;     /**< modified pages */
825                 MDB_reader      *reader;        /**< this thread's slot in the reader table */
826         } mt_u;
827         /** Array of records for each DB known in the environment. */
828         MDB_dbx         *mt_dbxs;
829         /** Array of MDB_db records for each known DB */
830         MDB_db          *mt_dbs;
831 /** @defgroup mt_dbflag Transaction DB Flags
832  *      @ingroup internal
833  * @{
834  */
835 #define DB_DIRTY        0x01            /**< DB was written in this txn */
836 #define DB_STALE        0x02            /**< DB record is older than txnID */
837 /** @} */
838         /** Array of cursors for each DB */
839         MDB_cursor      **mt_cursors;
840         /** Array of flags for each DB */
841         unsigned char   *mt_dbflags;
842         /**     Number of DB records in use. This number only ever increments;
843          *      we don't decrement it when individual DB handles are closed.
844          */
845         MDB_dbi         mt_numdbs;
846
847 /** @defgroup mdb_txn   Transaction Flags
848  *      @ingroup internal
849  *      @{
850  */
851 #define MDB_TXN_RDONLY          0x01            /**< read-only transaction */
852 #define MDB_TXN_ERROR           0x02            /**< an error has occurred */
853 /** @} */
854         unsigned int    mt_flags;               /**< @ref mdb_txn */
855         /** Tracks which of the two meta pages was used at the start
856          *      of this transaction.
857          */
858         unsigned int    mt_toggle;
859 };
860
861 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
862  * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
863  * raise this on a 64 bit machine.
864  */
865 #define CURSOR_STACK             32
866
867 struct MDB_xcursor;
868
869         /** Cursors are used for all DB operations */
870 struct MDB_cursor {
871         /** Next cursor on this DB in this txn */
872         MDB_cursor      *mc_next;
873         /** Original cursor if this is a shadow */
874         MDB_cursor      *mc_orig;
875         /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
876         struct MDB_xcursor      *mc_xcursor;
877         /** The transaction that owns this cursor */
878         MDB_txn         *mc_txn;
879         /** The database handle this cursor operates on */
880         MDB_dbi         mc_dbi;
881         /** The database record for this cursor */
882         MDB_db          *mc_db;
883         /** The database auxiliary record for this cursor */
884         MDB_dbx         *mc_dbx;
885         /** The @ref mt_dbflag for this database */
886         unsigned char   *mc_dbflag;
887         unsigned short  mc_snum;        /**< number of pushed pages */
888         unsigned short  mc_top;         /**< index of top page, normally mc_snum-1 */
889 /** @defgroup mdb_cursor        Cursor Flags
890  *      @ingroup internal
891  *      Cursor state flags.
892  *      @{
893  */
894 #define C_INITIALIZED   0x01    /**< cursor has been initialized and is valid */
895 #define C_EOF   0x02                    /**< No more data */
896 #define C_SUB   0x04                    /**< Cursor is a sub-cursor */
897 #define C_SHADOW        0x08            /**< Cursor is a dup from a parent txn */
898 #define C_ALLOCD        0x10            /**< Cursor was malloc'd */
899 /** @} */
900         unsigned int    mc_flags;       /**< @ref mdb_cursor */
901         MDB_page        *mc_pg[CURSOR_STACK];   /**< stack of pushed pages */
902         indx_t          mc_ki[CURSOR_STACK];    /**< stack of page indices */
903 };
904
905         /** Context for sorted-dup records.
906          *      We could have gone to a fully recursive design, with arbitrarily
907          *      deep nesting of sub-databases. But for now we only handle these
908          *      levels - main DB, optional sub-DB, sorted-duplicate DB.
909          */
910 typedef struct MDB_xcursor {
911         /** A sub-cursor for traversing the Dup DB */
912         MDB_cursor mx_cursor;
913         /** The database record for this Dup DB */
914         MDB_db  mx_db;
915         /**     The auxiliary DB record for this Dup DB */
916         MDB_dbx mx_dbx;
917         /** The @ref mt_dbflag for this Dup DB */
918         unsigned char mx_dbflag;
919 } MDB_xcursor;
920
921         /** A set of pages freed by an earlier transaction. */
922 typedef struct MDB_oldpages {
923         /** Usually we only read one record from the FREEDB at a time, but
924          *      in case we read more, this will chain them together.
925          */
926         struct MDB_oldpages *mo_next;
927         /**     The ID of the transaction in which these pages were freed. */
928         txnid_t         mo_txnid;
929         /** An #IDL of the pages */
930         pgno_t          mo_pages[1];    /* dynamic */
931 } MDB_oldpages;
932
933         /** The database environment. */
934 struct MDB_env {
935         HANDLE          me_fd;          /**< The main data file */
936         HANDLE          me_lfd;         /**< The lock file */
937         HANDLE          me_mfd;                 /**< just for writing the meta pages */
938         /** Failed to update the meta page. Probably an I/O error. */
939 #define MDB_FATAL_ERROR 0x80000000U
940         uint32_t        me_flags;               /**< @ref mdb_env */
941         uint32_t        me_extrapad;    /**< unused for now */
942         unsigned int    me_maxreaders;  /**< size of the reader table */
943         MDB_dbi         me_numdbs;              /**< number of DBs opened */
944         MDB_dbi         me_maxdbs;              /**< size of the DB table */
945         char            *me_path;               /**< path to the DB files */
946         char            *me_map;                /**< the memory map of the data file */
947         MDB_txninfo     *me_txns;               /**< the memory map of the lock file */
948         MDB_meta        *me_metas[2];   /**< pointers to the two meta pages */
949         MDB_txn         *me_txn;                /**< current write transaction */
950         size_t          me_mapsize;             /**< size of the data memory map */
951         off_t           me_size;                /**< current file size */
952         pgno_t          me_maxpg;               /**< me_mapsize / me_psize */
953         unsigned int    me_psize;       /**< size of a page, from #GET_PAGESIZE */
954         unsigned int    me_db_toggle;   /**< which DB table is current */
955         txnid_t         me_wtxnid;              /**< ID of last txn we committed */
956         txnid_t         me_pgfirst;             /**< ID of first old page record we used */
957         txnid_t         me_pglast;              /**< ID of last old page record we used */
958         MDB_dbx         *me_dbxs;               /**< array of static DB info */
959         MDB_db          *me_dbs[2];             /**< two arrays of MDB_db info */
960         MDB_oldpages *me_pghead;        /**< list of old page records */
961         pthread_key_t   me_txkey;       /**< thread-key for readers */
962         MDB_page        *me_dpages;             /**< list of malloc'd blocks for re-use */
963         /** IDL of pages that became unused in a write txn */
964         IDL                     me_free_pgs;
965         /** ID2L of pages that were written during a write txn */
966         ID2                     me_dirty_list[MDB_IDL_UM_SIZE];
967         /** rwlock for the DB tables, if #LAZY_LOCKS is false */
968         LAZY_RWLOCK_DEF(me_dblock)
969 #ifdef _WIN32
970         HANDLE          me_rmutex;              /* Windows mutexes don't reside in shared mem */
971         HANDLE          me_wmutex;
972 #endif
973 #ifdef __APPLE__
974         sem_t           *me_rmutex;             /* Apple doesn't support shared mutexes */
975         sem_t           *me_wmutex;
976 #endif
977 };
978         /** max number of pages to commit in one writev() call */
979 #define MDB_COMMIT_PAGES         64
980 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
981 #undef MDB_COMMIT_PAGES
982 #define MDB_COMMIT_PAGES        IOV_MAX
983 #endif
984
985 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
986 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
987 static int              mdb_page_touch(MDB_cursor *mc);
988
989 static int  mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
990 static int  mdb_page_search_root(MDB_cursor *mc,
991                             MDB_val *key, int modify);
992 static int  mdb_page_search(MDB_cursor *mc,
993                             MDB_val *key, int modify);
994 static int      mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
995 static int      mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
996                                 pgno_t newpgno, unsigned int nflags);
997
998 static int  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
999 static int  mdb_env_read_meta(MDB_env *env, int *which);
1000 static int  mdb_env_write_meta(MDB_txn *txn);
1001
1002 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1003 static int  mdb_node_add(MDB_cursor *mc, indx_t indx,
1004                             MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1005 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1006 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1007 static int      mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1008 static int  mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1009 static size_t   mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1010 static size_t   mdb_branch_size(MDB_env *env, MDB_val *key);
1011
1012 static int      mdb_rebalance(MDB_cursor *mc);
1013 static int      mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
1014
1015 static void     mdb_cursor_pop(MDB_cursor *mc);
1016 static int      mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1017
1018 static int      mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1019 static int      mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1020 static int      mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1021 static int      mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1022 static int      mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1023                                 int *exactp);
1024 static int      mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1025 static int      mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1026
1027 static void     mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1028 static void     mdb_xcursor_init0(MDB_cursor *mc);
1029 static void     mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1030
1031 static int      mdb_drop0(MDB_cursor *mc, int subs);
1032 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1033
1034 /** @cond */
1035 static MDB_cmp_func     mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1036 /** @endcond */
1037
1038 #ifdef _WIN32
1039 static SECURITY_DESCRIPTOR mdb_null_sd;
1040 static SECURITY_ATTRIBUTES mdb_all_sa;
1041 static int mdb_sec_inited;
1042 #endif
1043
1044 /** Return the library version info. */
1045 char *
1046 mdb_version(int *major, int *minor, int *patch)
1047 {
1048         if (major) *major = MDB_VERSION_MAJOR;
1049         if (minor) *minor = MDB_VERSION_MINOR;
1050         if (patch) *patch = MDB_VERSION_PATCH;
1051         return MDB_VERSION_STRING;
1052 }
1053
1054 /** Table of descriptions for MDB @ref errors */
1055 static char *const mdb_errstr[] = {
1056         "MDB_KEYEXIST: Key/data pair already exists",
1057         "MDB_NOTFOUND: No matching key/data pair found",
1058         "MDB_PAGE_NOTFOUND: Requested page not found",
1059         "MDB_CORRUPTED: Located page was wrong type",
1060         "MDB_PANIC: Update of meta page failed",
1061         "MDB_VERSION_MISMATCH: Database environment version mismatch"
1062 };
1063
1064 char *
1065 mdb_strerror(int err)
1066 {
1067         if (!err)
1068                 return ("Successful return: 0");
1069
1070         if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
1071                 return mdb_errstr[err - MDB_KEYEXIST];
1072
1073         return strerror(err);
1074 }
1075
1076 #if MDB_DEBUG
1077 /** Display a key in hexadecimal and return the address of the result.
1078  * @param[in] key the key to display
1079  * @param[in] buf the buffer to write into. Should always be #DKBUF.
1080  * @return The key in hexadecimal form.
1081  */
1082 char *
1083 mdb_dkey(MDB_val *key, char *buf)
1084 {
1085         char *ptr = buf;
1086         unsigned char *c = key->mv_data;
1087         unsigned int i;
1088         if (key->mv_size > MAXKEYSIZE)
1089                 return "MAXKEYSIZE";
1090         /* may want to make this a dynamic check: if the key is mostly
1091          * printable characters, print it as-is instead of converting to hex.
1092          */
1093 #if 1
1094         buf[0] = '\0';
1095         for (i=0; i<key->mv_size; i++)
1096                 ptr += sprintf(ptr, "%02x", *c++);
1097 #else
1098         sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1099 #endif
1100         return buf;
1101 }
1102
1103 /** Display all the keys in the page. */
1104 static void
1105 mdb_page_keys(MDB_page *mp)
1106 {
1107         MDB_node *node;
1108         unsigned int i, nkeys;
1109         MDB_val key;
1110         DKBUF;
1111
1112         nkeys = NUMKEYS(mp);
1113         DPRINTF("numkeys %d", nkeys);
1114         for (i=0; i<nkeys; i++) {
1115                 node = NODEPTR(mp, i);
1116                 key.mv_size = node->mn_ksize;
1117                 key.mv_data = node->mn_data;
1118                 DPRINTF("key %d: %s", i, DKEY(&key));
1119         }
1120 }
1121 #endif
1122
1123 #if MDB_DEBUG > 2
1124 /** Count all the pages in each DB and in the freelist
1125  *  and make sure it matches the actual number of pages
1126  *  being used.
1127  */
1128 static void mdb_audit(MDB_txn *txn)
1129 {
1130         MDB_cursor mc;
1131         MDB_val key, data;
1132         int rc, i;
1133         ID freecount, count;
1134
1135         freecount = 0;
1136         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1137         while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1138                 freecount += *(ID *)data.mv_data;
1139         freecount += txn->mt_dbs[0].md_branch_pages + txn->mt_dbs[0].md_leaf_pages +
1140                 txn->mt_dbs[0].md_overflow_pages;
1141
1142         count = 0;
1143         for (i = 0; i<txn->mt_numdbs; i++) {
1144                 count += txn->mt_dbs[i].md_branch_pages +
1145                         txn->mt_dbs[i].md_leaf_pages +
1146                         txn->mt_dbs[i].md_overflow_pages;
1147                 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1148                         MDB_xcursor mx;
1149                         mdb_cursor_init(&mc, txn, i, &mx);
1150                         mdb_page_search(&mc, NULL, 0);
1151                         do {
1152                                 int j;
1153                                 MDB_page *mp;
1154                                 mp = mc.mc_pg[mc.mc_top];
1155                                 for (j=0; j<NUMKEYS(mp); j++) {
1156                                         MDB_node *leaf = NODEPTR(mp, j);
1157                                         if (leaf->mn_flags & F_SUBDATA) {
1158                                                 MDB_db db;
1159                                                 memcpy(&db, NODEDATA(leaf), sizeof(db));
1160                                                 count += db.md_branch_pages + db.md_leaf_pages +
1161                                                         db.md_overflow_pages;
1162                                         }
1163                                 }
1164                         }
1165                         while (mdb_cursor_sibling(&mc, 1) == 0);
1166                 }
1167         }
1168         assert(freecount + count + 2 >= txn->mt_next_pgno - 1);
1169 }
1170 #endif
1171
1172 int
1173 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1174 {
1175         return txn->mt_dbxs[dbi].md_cmp(a, b);
1176 }
1177
1178 int
1179 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1180 {
1181         if (txn->mt_dbxs[dbi].md_dcmp)
1182                 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1183         else
1184                 return EINVAL;  /* too bad you can't distinguish this from a valid result */
1185 }
1186
1187 /** Allocate a single page.
1188  * Re-use old malloc'd pages first, otherwise just malloc.
1189  */
1190 static MDB_page *
1191 mdb_page_malloc(MDB_cursor *mc) {
1192         MDB_page *ret;
1193         size_t sz = mc->mc_txn->mt_env->me_psize;
1194         if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1195                 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1196                 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1197                 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1198         } else if ((ret = malloc(sz)) != NULL) {
1199                 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1200         }
1201         return ret;
1202 }
1203
1204 /** Allocate pages for writing.
1205  * If there are free pages available from older transactions, they
1206  * will be re-used first. Otherwise a new page will be allocated.
1207  * @param[in] mc cursor A cursor handle identifying the transaction and
1208  *      database for which we are allocating.
1209  * @param[in] num the number of pages to allocate.
1210  * @return Address of the allocated page(s). Requests for multiple pages
1211  *  will always be satisfied by a single contiguous chunk of memory.
1212  */
1213 static MDB_page *
1214 mdb_page_alloc(MDB_cursor *mc, int num)
1215 {
1216         MDB_txn *txn = mc->mc_txn;
1217         MDB_page *np;
1218         pgno_t pgno = P_INVALID;
1219         ID2 mid;
1220
1221         if (txn->mt_txnid > 2) {
1222
1223                 if (!txn->mt_env->me_pghead &&
1224                         txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1225                         /* See if there's anything in the free DB */
1226                         MDB_cursor m2;
1227                         MDB_node *leaf;
1228                         MDB_val data;
1229                         txnid_t *kptr, oldest, last;
1230
1231                         mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1232                         if (!txn->mt_env->me_pgfirst) {
1233                                 mdb_page_search(&m2, NULL, 0);
1234                                 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1235                                 kptr = (txnid_t *)NODEKEY(leaf);
1236                                 last = *kptr;
1237                         } else {
1238                                 MDB_val key;
1239                                 int rc, exact;
1240 again:
1241                                 exact = 0;
1242                                 last = txn->mt_env->me_pglast + 1;
1243                                 leaf = NULL;
1244                                 key.mv_data = &last;
1245                                 key.mv_size = sizeof(last);
1246                                 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1247                                 if (rc)
1248                                         goto none;
1249                                 last = *(txnid_t *)key.mv_data;
1250                         }
1251
1252                         {
1253                                 unsigned int i;
1254                                 oldest = txn->mt_txnid - 1;
1255                                 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1256                                         txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1257                                         if (mr && mr < oldest)
1258                                                 oldest = mr;
1259                                 }
1260                         }
1261
1262                         if (oldest > last) {
1263                                 /* It's usable, grab it.
1264                                  */
1265                                 MDB_oldpages *mop;
1266                                 pgno_t *idl;
1267
1268                                 if (!txn->mt_env->me_pgfirst) {
1269                                         mdb_node_read(txn, leaf, &data);
1270                                 }
1271                                 txn->mt_env->me_pglast = last;
1272                                 if (!txn->mt_env->me_pgfirst)
1273                                         txn->mt_env->me_pgfirst = last;
1274                                 idl = (ID *) data.mv_data;
1275                                 /* We might have a zero-length IDL due to freelist growth
1276                                  * during a prior commit
1277                                  */
1278                                 if (!idl[0]) goto again;
1279                                 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1280                                 mop->mo_next = txn->mt_env->me_pghead;
1281                                 mop->mo_txnid = last;
1282                                 txn->mt_env->me_pghead = mop;
1283                                 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1284
1285 #if MDB_DEBUG > 1
1286                                 {
1287                                         unsigned int i;
1288                                         DPRINTF("IDL read txn %zu root %zu num %zu",
1289                                                 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1290                                         for (i=0; i<idl[0]; i++) {
1291                                                 DPRINTF("IDL %zu", idl[i+1]);
1292                                         }
1293                                 }
1294 #endif
1295                         }
1296                 }
1297 none:
1298                 if (txn->mt_env->me_pghead) {
1299                         MDB_oldpages *mop = txn->mt_env->me_pghead;
1300                         if (num > 1) {
1301                                 /* FIXME: For now, always use fresh pages. We
1302                                  * really ought to search the free list for a
1303                                  * contiguous range.
1304                                  */
1305                                 ;
1306                         } else {
1307                                 /* peel pages off tail, so we only have to truncate the list */
1308                                 pgno = MDB_IDL_LAST(mop->mo_pages);
1309                                 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1310                                         mop->mo_pages[2]++;
1311                                         if (mop->mo_pages[2] > mop->mo_pages[1])
1312                                                 mop->mo_pages[0] = 0;
1313                                 } else {
1314                                         mop->mo_pages[0]--;
1315                                 }
1316                                 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1317                                         txn->mt_env->me_pghead = mop->mo_next;
1318                                         free(mop);
1319                                 }
1320                         }
1321                 }
1322         }
1323
1324         if (pgno == P_INVALID) {
1325                 /* DB size is maxed out */
1326                 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1327                         DPUTS("DB size maxed out");
1328                         return NULL;
1329                 }
1330         }
1331         if (txn->mt_env->me_dpages && num == 1) {
1332                 np = txn->mt_env->me_dpages;
1333                 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1334                 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1335                 txn->mt_env->me_dpages = np->mp_next;
1336         } else {
1337                 size_t sz = txn->mt_env->me_psize * num;
1338                 if ((np = malloc(sz)) == NULL)
1339                         return NULL;
1340                 VGMEMP_ALLOC(txn->mt_env, np, sz);
1341         }
1342         if (pgno == P_INVALID) {
1343                 np->mp_pgno = txn->mt_next_pgno;
1344                 txn->mt_next_pgno += num;
1345         } else {
1346                 np->mp_pgno = pgno;
1347         }
1348         mid.mid = np->mp_pgno;
1349         mid.mptr = np;
1350         mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1351
1352         return np;
1353 }
1354
1355 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1356  * @param[in] mc cursor pointing to the page to be touched
1357  * @return 0 on success, non-zero on failure.
1358  */
1359 static int
1360 mdb_page_touch(MDB_cursor *mc)
1361 {
1362         MDB_page *mp = mc->mc_pg[mc->mc_top];
1363         pgno_t  pgno;
1364
1365         if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1366                 MDB_page *np;
1367                 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1368                         return ENOMEM;
1369                 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1370                 assert(mp->mp_pgno != np->mp_pgno);
1371                 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1372                 pgno = np->mp_pgno;
1373                 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1374                 mp = np;
1375                 mp->mp_pgno = pgno;
1376                 mp->mp_flags |= P_DIRTY;
1377
1378 finish:
1379                 /* Adjust other cursors pointing to mp */
1380                 if (mc->mc_flags & C_SUB) {
1381                         MDB_cursor *m2, *m3;
1382                         MDB_dbi dbi = mc->mc_dbi-1;
1383
1384                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1385                                 if (m2 == mc) continue;
1386                                 m3 = &m2->mc_xcursor->mx_cursor;
1387                                 if (m3->mc_snum < mc->mc_snum) continue;
1388                                 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1389                                         m3->mc_pg[mc->mc_top] = mp;
1390                                 }
1391                         }
1392                 } else {
1393                         MDB_cursor *m2;
1394
1395                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1396                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1397                                 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1398                                         m2->mc_pg[mc->mc_top] = mp;
1399                                 }
1400                         }
1401                 }
1402                 mc->mc_pg[mc->mc_top] = mp;
1403                 /** If this page has a parent, update the parent to point to
1404                  * this new page.
1405                  */
1406                 if (mc->mc_top)
1407                         SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1408                 else
1409                         mc->mc_db->md_root = mp->mp_pgno;
1410         } else if (mc->mc_txn->mt_parent) {
1411                 MDB_page *np;
1412                 ID2 mid;
1413                 /* If txn has a parent, make sure the page is in our
1414                  * dirty list.
1415                  */
1416                 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1417                         unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1418                         if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1419                                 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1420                                 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1421                                         mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1422                                         mc->mc_pg[mc->mc_top] = mp;
1423                                 }
1424                                 return 0;
1425                         }
1426                 }
1427                 /* No - copy it */
1428                 np = mdb_page_malloc(mc);
1429                 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1430                 mid.mid = np->mp_pgno;
1431                 mid.mptr = np;
1432                 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1433                 mp = np;
1434                 goto finish;
1435         }
1436         return 0;
1437 }
1438
1439 int
1440 mdb_env_sync(MDB_env *env, int force)
1441 {
1442         int rc = 0;
1443         if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1444                 if (MDB_FDATASYNC(env->me_fd))
1445                         rc = ErrCode();
1446         }
1447         return rc;
1448 }
1449
1450 /** Make shadow copies of all of parent txn's cursors */
1451 static int
1452 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1453 {
1454         MDB_cursor *mc, *m2;
1455         unsigned int i, j, size;
1456
1457         for (i=0;i<src->mt_numdbs; i++) {
1458                 if (src->mt_cursors[i]) {
1459                         size = sizeof(MDB_cursor);
1460                         if (src->mt_cursors[i]->mc_xcursor)
1461                                 size += sizeof(MDB_xcursor);
1462                         for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1463                                 mc = malloc(size);
1464                                 if (!mc)
1465                                         return ENOMEM;
1466                                 mc->mc_orig = m2;
1467                                 mc->mc_txn = dst;
1468                                 mc->mc_dbi = i;
1469                                 mc->mc_db = &dst->mt_dbs[i];
1470                                 mc->mc_dbx = m2->mc_dbx;
1471                                 mc->mc_dbflag = &dst->mt_dbflags[i];
1472                                 mc->mc_snum = m2->mc_snum;
1473                                 mc->mc_top = m2->mc_top;
1474                                 mc->mc_flags = m2->mc_flags | C_SHADOW;
1475                                 for (j=0; j<mc->mc_snum; j++) {
1476                                         mc->mc_pg[j] = m2->mc_pg[j];
1477                                         mc->mc_ki[j] = m2->mc_ki[j];
1478                                 }
1479                                 if (m2->mc_xcursor) {
1480                                         MDB_xcursor *mx, *mx2;
1481                                         mx = (MDB_xcursor *)(mc+1);
1482                                         mc->mc_xcursor = mx;
1483                                         mx2 = m2->mc_xcursor;
1484                                         mx->mx_db = mx2->mx_db;
1485                                         mx->mx_dbx = mx2->mx_dbx;
1486                                         mx->mx_dbflag = mx2->mx_dbflag;
1487                                         mx->mx_cursor.mc_txn = dst;
1488                                         mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1489                                         mx->mx_cursor.mc_db = &mx->mx_db;
1490                                         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1491                                         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1492                                         mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1493                                         mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1494                                         mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1495                                         for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1496                                                 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1497                                                 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1498                                         }
1499                                 } else {
1500                                         mc->mc_xcursor = NULL;
1501                                 }
1502                                 mc->mc_next = dst->mt_cursors[i];
1503                                 dst->mt_cursors[i] = mc;
1504                         }
1505                 }
1506         }
1507         return MDB_SUCCESS;
1508 }
1509
1510 /** Merge shadow cursors back into parent's */
1511 static void
1512 mdb_cursor_merge(MDB_txn *txn)
1513 {
1514         MDB_dbi i;
1515         for (i=0; i<txn->mt_numdbs; i++) {
1516                 if (txn->mt_cursors[i]) {
1517                         MDB_cursor *mc;
1518                         while ((mc = txn->mt_cursors[i])) {
1519                                 txn->mt_cursors[i] = mc->mc_next;
1520                                 if (mc->mc_flags & C_SHADOW) {
1521                                         MDB_cursor *m2 = mc->mc_orig;
1522                                         unsigned int j;
1523                                         m2->mc_snum = mc->mc_snum;
1524                                         m2->mc_top = mc->mc_top;
1525                                         for (j=0; j<mc->mc_snum; j++) {
1526                                                 m2->mc_pg[j] = mc->mc_pg[j];
1527                                                 m2->mc_ki[j] = mc->mc_ki[j];
1528                                         }
1529                                 }
1530                                 if (mc->mc_flags & C_ALLOCD)
1531                                         free(mc);
1532                         }
1533                 }
1534         }
1535 }
1536
1537 static void
1538 mdb_txn_reset0(MDB_txn *txn);
1539
1540 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1541  * @param[in] txn the transaction handle to initialize
1542  * @return 0 on success, non-zero on failure. This can only
1543  * fail for read-only transactions, and then only if the
1544  * reader table is full.
1545  */
1546 static int
1547 mdb_txn_renew0(MDB_txn *txn)
1548 {
1549         MDB_env *env = txn->mt_env;
1550         char mt_dbflag = 0;
1551
1552         if (txn->mt_flags & MDB_TXN_RDONLY) {
1553                 MDB_reader *r = pthread_getspecific(env->me_txkey);
1554                 if (!r) {
1555                         unsigned int i;
1556                         pid_t pid = getpid();
1557                         pthread_t tid = pthread_self();
1558
1559                         LOCK_MUTEX_R(env);
1560                         for (i=0; i<env->me_txns->mti_numreaders; i++)
1561                                 if (env->me_txns->mti_readers[i].mr_pid == 0)
1562                                         break;
1563                         if (i == env->me_maxreaders) {
1564                                 UNLOCK_MUTEX_R(env);
1565                                 return ENOMEM;
1566                         }
1567                         env->me_txns->mti_readers[i].mr_pid = pid;
1568                         env->me_txns->mti_readers[i].mr_tid = tid;
1569                         if (i >= env->me_txns->mti_numreaders)
1570                                 env->me_txns->mti_numreaders = i+1;
1571                         UNLOCK_MUTEX_R(env);
1572                         r = &env->me_txns->mti_readers[i];
1573                         pthread_setspecific(env->me_txkey, r);
1574                 }
1575                 txn->mt_toggle = env->me_txns->mti_me_toggle;
1576                 txn->mt_txnid = r->mr_txnid = env->me_metas[txn->mt_toggle]->mm_txnid;
1577
1578                 /* This happens if a different process was the
1579                  * last writer to the DB.
1580                  */
1581                 if (env->me_wtxnid < txn->mt_txnid)
1582                         mt_dbflag = DB_STALE;
1583                 txn->mt_u.reader = r;
1584         } else {
1585                 LOCK_MUTEX_W(env);
1586
1587                 txn->mt_toggle = env->me_txns->mti_me_toggle;
1588                 txn->mt_txnid = env->me_metas[txn->mt_toggle]->mm_txnid;
1589                 if (env->me_wtxnid < txn->mt_txnid)
1590                         mt_dbflag = DB_STALE;
1591                 txn->mt_txnid++;
1592 #if MDB_DEBUG
1593                 if (txn->mt_txnid == mdb_debug_start)
1594                         mdb_debug = 1;
1595 #endif
1596                 txn->mt_u.dirty_list = env->me_dirty_list;
1597                 txn->mt_u.dirty_list[0].mid = 0;
1598                 txn->mt_free_pgs = env->me_free_pgs;
1599                 txn->mt_free_pgs[0] = 0;
1600                 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1601                 env->me_txn = txn;
1602         }
1603
1604         /* Copy the DB arrays */
1605         LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1606         txn->mt_numdbs = env->me_numdbs;
1607         txn->mt_dbxs = env->me_dbxs;    /* mostly static anyway */
1608         memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1609         if (txn->mt_numdbs > 2)
1610                 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1611                         (txn->mt_numdbs - 2) * sizeof(MDB_db));
1612         LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1613
1614         memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1615
1616         return MDB_SUCCESS;
1617 }
1618
1619 int
1620 mdb_txn_renew(MDB_txn *txn)
1621 {
1622         int rc;
1623
1624         if (!txn)
1625                 return EINVAL;
1626
1627         if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1628                 DPUTS("environment had fatal error, must shutdown!");
1629                 return MDB_PANIC;
1630         }
1631
1632         rc = mdb_txn_renew0(txn);
1633         if (rc == MDB_SUCCESS) {
1634                 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1635                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1636                         (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1637         }
1638         return rc;
1639 }
1640
1641 int
1642 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1643 {
1644         MDB_txn *txn;
1645         int rc, size;
1646
1647         if (env->me_flags & MDB_FATAL_ERROR) {
1648                 DPUTS("environment had fatal error, must shutdown!");
1649                 return MDB_PANIC;
1650         }
1651         if (parent) {
1652                 /* parent already has an active child txn */
1653                 if (parent->mt_child) {
1654                         return EINVAL;
1655                 }
1656         }
1657         size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1658         if (!(flags & MDB_RDONLY))
1659                 size += env->me_maxdbs * sizeof(MDB_cursor *);
1660
1661         if ((txn = calloc(1, size)) == NULL) {
1662                 DPRINTF("calloc: %s", strerror(ErrCode()));
1663                 return ENOMEM;
1664         }
1665         txn->mt_dbs = (MDB_db *)(txn+1);
1666         if (flags & MDB_RDONLY) {
1667                 txn->mt_flags |= MDB_TXN_RDONLY;
1668                 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1669         } else {
1670                 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1671                 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1672         }
1673         txn->mt_env = env;
1674
1675         if (parent) {
1676                 txn->mt_free_pgs = mdb_midl_alloc();
1677                 if (!txn->mt_free_pgs) {
1678                         free(txn);
1679                         return ENOMEM;
1680                 }
1681                 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1682                 if (!txn->mt_u.dirty_list) {
1683                         free(txn->mt_free_pgs);
1684                         free(txn);
1685                         return ENOMEM;
1686                 }
1687                 txn->mt_txnid = parent->mt_txnid;
1688                 txn->mt_toggle = parent->mt_toggle;
1689                 txn->mt_u.dirty_list[0].mid = 0;
1690                 txn->mt_free_pgs[0] = 0;
1691                 txn->mt_next_pgno = parent->mt_next_pgno;
1692                 parent->mt_child = txn;
1693                 txn->mt_parent = parent;
1694                 txn->mt_numdbs = parent->mt_numdbs;
1695                 txn->mt_dbxs = parent->mt_dbxs;
1696                 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1697                 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1698                 mdb_cursor_shadow(parent, txn);
1699                 rc = 0;
1700         } else {
1701                 rc = mdb_txn_renew0(txn);
1702         }
1703         if (rc)
1704                 free(txn);
1705         else {
1706                 *ret = txn;
1707                 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1708                         txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1709                         (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1710         }
1711
1712         return rc;
1713 }
1714
1715 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1716  * @param[in] txn the transaction handle to reset
1717  */
1718 static void
1719 mdb_txn_reset0(MDB_txn *txn)
1720 {
1721         MDB_env *env = txn->mt_env;
1722
1723         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1724                 txn->mt_u.reader->mr_txnid = 0;
1725         } else {
1726                 MDB_oldpages *mop;
1727                 MDB_page *dp;
1728                 unsigned int i;
1729
1730                 /* close(free) all cursors */
1731                 for (i=0; i<txn->mt_numdbs; i++) {
1732                         if (txn->mt_cursors[i]) {
1733                                 MDB_cursor *mc;
1734                                 while ((mc = txn->mt_cursors[i])) {
1735                                         txn->mt_cursors[i] = mc->mc_next;
1736                                         if (mc->mc_flags & C_ALLOCD)
1737                                                 free(mc);
1738                                 }
1739                         }
1740                 }
1741
1742                 /* return all dirty pages to dpage list */
1743                 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1744                         dp = txn->mt_u.dirty_list[i].mptr;
1745                         if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1746                                 dp->mp_next = txn->mt_env->me_dpages;
1747                                 VGMEMP_FREE(txn->mt_env, dp);
1748                                 txn->mt_env->me_dpages = dp;
1749                         } else {
1750                                 /* large pages just get freed directly */
1751                                 VGMEMP_FREE(txn->mt_env, dp);
1752                                 free(dp);
1753                         }
1754                 }
1755
1756                 if (txn->mt_parent) {
1757                         txn->mt_parent->mt_child = NULL;
1758                         free(txn->mt_free_pgs);
1759                         free(txn->mt_u.dirty_list);
1760                         return;
1761                 } else {
1762                         if (mdb_midl_shrink(&txn->mt_free_pgs))
1763                                 env->me_free_pgs = txn->mt_free_pgs;
1764                 }
1765
1766                 while ((mop = txn->mt_env->me_pghead)) {
1767                         txn->mt_env->me_pghead = mop->mo_next;
1768                         free(mop);
1769                 }
1770                 txn->mt_env->me_pgfirst = 0;
1771                 txn->mt_env->me_pglast = 0;
1772
1773                 env->me_txn = NULL;
1774                 /* The writer mutex was locked in mdb_txn_begin. */
1775                 UNLOCK_MUTEX_W(env);
1776         }
1777 }
1778
1779 void
1780 mdb_txn_reset(MDB_txn *txn)
1781 {
1782         if (txn == NULL)
1783                 return;
1784
1785         DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1786                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1787                 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1788
1789         mdb_txn_reset0(txn);
1790 }
1791
1792 void
1793 mdb_txn_abort(MDB_txn *txn)
1794 {
1795         if (txn == NULL)
1796                 return;
1797
1798         DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1799                 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1800                 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1801
1802         if (txn->mt_child)
1803                 mdb_txn_abort(txn->mt_child);
1804
1805         mdb_txn_reset0(txn);
1806         free(txn);
1807 }
1808
1809 int
1810 mdb_txn_commit(MDB_txn *txn)
1811 {
1812         int              n, done;
1813         unsigned int i;
1814         ssize_t          rc;
1815         off_t            size;
1816         MDB_page        *dp;
1817         MDB_env *env;
1818         pgno_t  next, freecnt;
1819         MDB_cursor mc;
1820
1821         assert(txn != NULL);
1822         assert(txn->mt_env != NULL);
1823
1824         if (txn->mt_child) {
1825                 mdb_txn_commit(txn->mt_child);
1826                 txn->mt_child = NULL;
1827         }
1828
1829         env = txn->mt_env;
1830
1831         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1832                 if (txn->mt_numdbs > env->me_numdbs) {
1833                         /* update the DB tables */
1834                         int toggle = !env->me_db_toggle;
1835                         MDB_db *ip, *jp;
1836                         MDB_dbi i;
1837
1838                         ip = &env->me_dbs[toggle][env->me_numdbs];
1839                         jp = &txn->mt_dbs[env->me_numdbs];
1840                         LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1841                         for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1842                                 *ip++ = *jp++;
1843                         }
1844
1845                         env->me_db_toggle = toggle;
1846                         env->me_numdbs = txn->mt_numdbs;
1847                         LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1848                 }
1849                 mdb_txn_abort(txn);
1850                 return MDB_SUCCESS;
1851         }
1852
1853         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1854                 DPUTS("error flag is set, can't commit");
1855                 if (txn->mt_parent)
1856                         txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1857                 mdb_txn_abort(txn);
1858                 return EINVAL;
1859         }
1860
1861         /* Merge (and close) our cursors with parent's */
1862         mdb_cursor_merge(txn);
1863
1864         if (txn->mt_parent) {
1865                 MDB_db *ip, *jp;
1866                 MDB_dbi i;
1867                 unsigned x, y;
1868                 ID2L dst, src;
1869
1870                 /* Update parent's DB table */
1871                 ip = &txn->mt_parent->mt_dbs[2];
1872                 jp = &txn->mt_dbs[2];
1873                 for (i = 2; i < txn->mt_numdbs; i++) {
1874                         if (ip->md_root != jp->md_root)
1875                                 *ip = *jp;
1876                         ip++; jp++;
1877                 }
1878                 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1879
1880                 /* Append our free list to parent's */
1881                 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1882                         txn->mt_free_pgs);
1883                 mdb_midl_free(txn->mt_free_pgs);
1884
1885                 /* Merge our dirty list with parent's */
1886                 dst = txn->mt_parent->mt_u.dirty_list;
1887                 src = txn->mt_u.dirty_list;
1888                 x = mdb_mid2l_search(dst, src[1].mid);
1889                 for (y=1; y<=src[0].mid; y++) {
1890                         while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1891                         if (x > dst[0].mid)
1892                                 break;
1893                         free(dst[x].mptr);
1894                         dst[x].mptr = src[y].mptr;
1895                 }
1896                 x = dst[0].mid;
1897                 for (; y<=src[0].mid; y++) {
1898                         if (++x >= MDB_IDL_UM_MAX) {
1899                                 mdb_txn_abort(txn);
1900                                 return ENOMEM;
1901                         }
1902                         dst[x] = src[y];
1903                 }
1904                 dst[0].mid = x;
1905                 free(txn->mt_u.dirty_list);
1906                 txn->mt_parent->mt_child = NULL;
1907                 free(txn);
1908                 return MDB_SUCCESS;
1909         }
1910
1911         if (txn != env->me_txn) {
1912                 DPUTS("attempt to commit unknown transaction");
1913                 mdb_txn_abort(txn);
1914                 return EINVAL;
1915         }
1916
1917         if (!txn->mt_u.dirty_list[0].mid)
1918                 goto done;
1919
1920         DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1921             txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1922
1923         mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1924
1925         /* should only be one record now */
1926         if (env->me_pghead) {
1927                 /* make sure first page of freeDB is touched and on freelist */
1928                 mdb_page_search(&mc, NULL, 1);
1929         }
1930
1931         /* Delete IDLs we used from the free list */
1932         if (env->me_pgfirst) {
1933                 txnid_t cur;
1934                 MDB_val key;
1935                 int exact = 0;
1936
1937                 key.mv_size = sizeof(cur);
1938                 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
1939                         key.mv_data = &cur;
1940
1941                         mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
1942                         mdb_cursor_del(&mc, 0);
1943                 }
1944                 env->me_pgfirst = 0;
1945                 env->me_pglast = 0;
1946         }
1947
1948         /* save to free list */
1949 free2:
1950         freecnt = txn->mt_free_pgs[0];
1951         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1952                 MDB_val key, data;
1953
1954                 /* make sure last page of freeDB is touched and on freelist */
1955                 key.mv_size = MAXKEYSIZE+1;
1956                 key.mv_data = NULL;
1957                 mdb_page_search(&mc, &key, 1);
1958
1959                 mdb_midl_sort(txn->mt_free_pgs);
1960 #if MDB_DEBUG > 1
1961                 {
1962                         unsigned int i;
1963                         ID *idl = txn->mt_free_pgs;
1964                         DPRINTF("IDL write txn %zu root %zu num %zu",
1965                                 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1966                         for (i=0; i<idl[0]; i++) {
1967                                 DPRINTF("IDL %zu", idl[i+1]);
1968                         }
1969                 }
1970 #endif
1971                 /* write to last page of freeDB */
1972                 key.mv_size = sizeof(pgno_t);
1973                 key.mv_data = &txn->mt_txnid;
1974                 data.mv_data = txn->mt_free_pgs;
1975                 /* The free list can still grow during this call,
1976                  * despite the pre-emptive touches above. So check
1977                  * and make sure the entire thing got written.
1978                  */
1979                 do {
1980                         freecnt = txn->mt_free_pgs[0];
1981                         data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1982                         rc = mdb_cursor_put(&mc, &key, &data, 0);
1983                         if (rc) {
1984                                 mdb_txn_abort(txn);
1985                                 return rc;
1986                         }
1987                 } while (freecnt != txn->mt_free_pgs[0]);
1988         }
1989         /* should only be one record now */
1990 again:
1991         if (env->me_pghead) {
1992                 MDB_val key, data;
1993                 MDB_oldpages *mop;
1994                 pgno_t orig;
1995                 txnid_t id;
1996
1997                 mop = env->me_pghead;
1998                 id = mop->mo_txnid;
1999                 key.mv_size = sizeof(id);
2000                 key.mv_data = &id;
2001                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2002                 data.mv_data = mop->mo_pages;
2003                 orig = mop->mo_pages[0];
2004                 /* These steps may grow the freelist again
2005                  * due to freed overflow pages...
2006                  */
2007                 mdb_cursor_put(&mc, &key, &data, 0);
2008                 if (mop == env->me_pghead && env->me_pghead->mo_txnid == id) {
2009                         /* could have been used again here */
2010                         if (mop->mo_pages[0] != orig) {
2011                                 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2012                                 data.mv_data = mop->mo_pages;
2013                                 id = mop->mo_txnid;
2014                                 mdb_cursor_put(&mc, &key, &data, 0);
2015                         }
2016                         env->me_pghead = NULL;
2017                         free(mop);
2018                 } else {
2019                         /* was completely used up */
2020                         mdb_cursor_del(&mc, 0);
2021                         if (env->me_pghead)
2022                                 goto again;
2023                 }
2024                 env->me_pgfirst = 0;
2025                 env->me_pglast = 0;
2026         }
2027         /* Check for growth of freelist again */
2028         if (freecnt != txn->mt_free_pgs[0])
2029                 goto free2;
2030
2031         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2032                 if (mdb_midl_shrink(&txn->mt_free_pgs))
2033                         env->me_free_pgs = txn->mt_free_pgs;
2034         }
2035
2036         /* Update DB root pointers. Their pages have already been
2037          * touched so this is all in-place and cannot fail.
2038          */
2039         {
2040                 MDB_dbi i;
2041                 MDB_val data;
2042                 data.mv_size = sizeof(MDB_db);
2043
2044                 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2045                 for (i = 2; i < txn->mt_numdbs; i++) {
2046                         if (txn->mt_dbflags[i] & DB_DIRTY) {
2047                                 data.mv_data = &txn->mt_dbs[i];
2048                                 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2049                         }
2050                 }
2051         }
2052 #if MDB_DEBUG > 2
2053         mdb_audit(txn);
2054 #endif
2055
2056         /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2057          */
2058         next = 0;
2059         i = 1;
2060         do {
2061 #ifdef _WIN32
2062                 /* Windows actually supports scatter/gather I/O, but only on
2063                  * unbuffered file handles. Since we're relying on the OS page
2064                  * cache for all our data, that's self-defeating. So we just
2065                  * write pages one at a time. We use the ov structure to set
2066                  * the write offset, to at least save the overhead of a Seek
2067                  * system call.
2068                  */
2069                 OVERLAPPED ov;
2070                 memset(&ov, 0, sizeof(ov));
2071                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2072                         size_t wsize;
2073                         dp = txn->mt_u.dirty_list[i].mptr;
2074                         DPRINTF("committing page %zu", dp->mp_pgno);
2075                         size = dp->mp_pgno * env->me_psize;
2076                         ov.Offset = size & 0xffffffff;
2077                         ov.OffsetHigh = size >> 16;
2078                         ov.OffsetHigh >>= 16;
2079                         /* clear dirty flag */
2080                         dp->mp_flags &= ~P_DIRTY;
2081                         wsize = env->me_psize;
2082                         if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2083                         rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2084                         if (!rc) {
2085                                 n = ErrCode();
2086                                 DPRINTF("WriteFile: %d", n);
2087                                 mdb_txn_abort(txn);
2088                                 return n;
2089                         }
2090                 }
2091                 done = 1;
2092 #else
2093                 struct iovec     iov[MDB_COMMIT_PAGES];
2094                 n = 0;
2095                 done = 1;
2096                 size = 0;
2097                 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2098                         dp = txn->mt_u.dirty_list[i].mptr;
2099                         if (dp->mp_pgno != next) {
2100                                 if (n) {
2101                                         rc = writev(env->me_fd, iov, n);
2102                                         if (rc != size) {
2103                                                 n = ErrCode();
2104                                                 if (rc > 0)
2105                                                         DPUTS("short write, filesystem full?");
2106                                                 else
2107                                                         DPRINTF("writev: %s", strerror(n));
2108                                                 mdb_txn_abort(txn);
2109                                                 return n;
2110                                         }
2111                                         n = 0;
2112                                         size = 0;
2113                                 }
2114                                 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2115                                 next = dp->mp_pgno;
2116                         }
2117                         DPRINTF("committing page %zu", dp->mp_pgno);
2118                         iov[n].iov_len = env->me_psize;
2119                         if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2120                         iov[n].iov_base = (char *)dp;
2121                         size += iov[n].iov_len;
2122                         next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2123                         /* clear dirty flag */
2124                         dp->mp_flags &= ~P_DIRTY;
2125                         if (++n >= MDB_COMMIT_PAGES) {
2126                                 done = 0;
2127                                 i++;
2128                                 break;
2129                         }
2130                 }
2131
2132                 if (n == 0)
2133                         break;
2134
2135                 rc = writev(env->me_fd, iov, n);
2136                 if (rc != size) {
2137                         n = ErrCode();
2138                         if (rc > 0)
2139                                 DPUTS("short write, filesystem full?");
2140                         else
2141                                 DPRINTF("writev: %s", strerror(n));
2142                         mdb_txn_abort(txn);
2143                         return n;
2144                 }
2145 #endif
2146         } while (!done);
2147
2148         /* Drop the dirty pages.
2149          */
2150         for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2151                 dp = txn->mt_u.dirty_list[i].mptr;
2152                 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2153                         dp->mp_next = txn->mt_env->me_dpages;
2154                         VGMEMP_FREE(txn->mt_env, dp);
2155                         txn->mt_env->me_dpages = dp;
2156                 } else {
2157                         VGMEMP_FREE(txn->mt_env, dp);
2158                         free(dp);
2159                 }
2160                 txn->mt_u.dirty_list[i].mid = 0;
2161         }
2162         txn->mt_u.dirty_list[0].mid = 0;
2163
2164         if ((n = mdb_env_sync(env, 0)) != 0 ||
2165             (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2166                 mdb_txn_abort(txn);
2167                 return n;
2168         }
2169         env->me_wtxnid = txn->mt_txnid;
2170
2171 done:
2172         env->me_txn = NULL;
2173         /* update the DB tables */
2174         {
2175                 int toggle = !env->me_db_toggle;
2176                 MDB_db *ip, *jp;
2177                 MDB_dbi i;
2178
2179                 ip = &env->me_dbs[toggle][2];
2180                 jp = &txn->mt_dbs[2];
2181                 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
2182                 for (i = 2; i < txn->mt_numdbs; i++) {
2183                         if (ip->md_root != jp->md_root)
2184                                 *ip = *jp;
2185                         ip++; jp++;
2186                 }
2187
2188                 env->me_db_toggle = toggle;
2189                 env->me_numdbs = txn->mt_numdbs;
2190                 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
2191         }
2192
2193         UNLOCK_MUTEX_W(env);
2194         free(txn);
2195
2196         return MDB_SUCCESS;
2197 }
2198
2199 /** Read the environment parameters of a DB environment before
2200  * mapping it into memory.
2201  * @param[in] env the environment handle
2202  * @param[out] meta address of where to store the meta information
2203  * @return 0 on success, non-zero on failure.
2204  */
2205 static int
2206 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2207 {
2208         MDB_pagebuf     pbuf;
2209         MDB_page        *p;
2210         MDB_meta        *m;
2211         int              rc, err;
2212
2213         /* We don't know the page size yet, so use a minimum value.
2214          */
2215
2216 #ifdef _WIN32
2217         if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2218 #else
2219         if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2220 #endif
2221         {
2222                 return ENOENT;
2223         }
2224         else if (rc != MDB_PAGESIZE) {
2225                 err = ErrCode();
2226                 if (rc > 0)
2227                         err = EINVAL;
2228                 DPRINTF("read: %s", strerror(err));
2229                 return err;
2230         }
2231
2232         p = (MDB_page *)&pbuf;
2233
2234         if (!F_ISSET(p->mp_flags, P_META)) {
2235                 DPRINTF("page %zu not a meta page", p->mp_pgno);
2236                 return EINVAL;
2237         }
2238
2239         m = METADATA(p);
2240         if (m->mm_magic != MDB_MAGIC) {
2241                 DPUTS("meta has invalid magic");
2242                 return EINVAL;
2243         }
2244
2245         if (m->mm_version != MDB_VERSION) {
2246                 DPRINTF("database is version %u, expected version %u",
2247                     m->mm_version, MDB_VERSION);
2248                 return MDB_VERSION_MISMATCH;
2249         }
2250
2251         memcpy(meta, m, sizeof(*m));
2252         return 0;
2253 }
2254
2255 /** Write the environment parameters of a freshly created DB environment.
2256  * @param[in] env the environment handle
2257  * @param[out] meta address of where to store the meta information
2258  * @return 0 on success, non-zero on failure.
2259  */
2260 static int
2261 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2262 {
2263         MDB_page *p, *q;
2264         MDB_meta *m;
2265         int rc;
2266         unsigned int     psize;
2267
2268         DPUTS("writing new meta page");
2269
2270         GET_PAGESIZE(psize);
2271
2272         meta->mm_magic = MDB_MAGIC;
2273         meta->mm_version = MDB_VERSION;
2274         meta->mm_psize = psize;
2275         meta->mm_last_pg = 1;
2276         meta->mm_flags = env->me_flags & 0xffff;
2277         meta->mm_flags |= MDB_INTEGERKEY;
2278         meta->mm_dbs[0].md_root = P_INVALID;
2279         meta->mm_dbs[1].md_root = P_INVALID;
2280
2281         p = calloc(2, psize);
2282         p->mp_pgno = 0;
2283         p->mp_flags = P_META;
2284
2285         m = METADATA(p);
2286         memcpy(m, meta, sizeof(*meta));
2287
2288         q = (MDB_page *)((char *)p + psize);
2289
2290         q->mp_pgno = 1;
2291         q->mp_flags = P_META;
2292
2293         m = METADATA(q);
2294         memcpy(m, meta, sizeof(*meta));
2295
2296 #ifdef _WIN32
2297         {
2298                 DWORD len;
2299                 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2300                 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2301         }
2302 #else
2303         rc = write(env->me_fd, p, psize * 2);
2304         rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2305 #endif
2306         free(p);
2307         return rc;
2308 }
2309
2310 /** Update the environment info to commit a transaction.
2311  * @param[in] txn the transaction that's being committed
2312  * @return 0 on success, non-zero on failure.
2313  */
2314 static int
2315 mdb_env_write_meta(MDB_txn *txn)
2316 {
2317         MDB_env *env;
2318         MDB_meta        meta, metab;
2319         off_t off;
2320         int rc, len, toggle;
2321         char *ptr;
2322 #ifdef _WIN32
2323         OVERLAPPED ov;
2324 #endif
2325
2326         assert(txn != NULL);
2327         assert(txn->mt_env != NULL);
2328
2329         toggle = !txn->mt_toggle;
2330         DPRINTF("writing meta page %d for root page %zu",
2331                 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2332
2333         env = txn->mt_env;
2334
2335         metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2336         metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2337
2338         ptr = (char *)&meta;
2339         off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2340         len = sizeof(MDB_meta) - off;
2341
2342         ptr += off;
2343         meta.mm_dbs[0] = txn->mt_dbs[0];
2344         meta.mm_dbs[1] = txn->mt_dbs[1];
2345         meta.mm_last_pg = txn->mt_next_pgno - 1;
2346         meta.mm_txnid = txn->mt_txnid;
2347
2348         if (toggle)
2349                 off += env->me_psize;
2350         off += PAGEHDRSZ;
2351
2352         /* Write to the SYNC fd */
2353 #ifdef _WIN32
2354         {
2355                 memset(&ov, 0, sizeof(ov));
2356                 ov.Offset = off;
2357                 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2358         }
2359 #else
2360         rc = pwrite(env->me_mfd, ptr, len, off);
2361 #endif
2362         if (rc != len) {
2363                 int r2;
2364                 rc = ErrCode();
2365                 DPUTS("write failed, disk error?");
2366                 /* On a failure, the pagecache still contains the new data.
2367                  * Write some old data back, to prevent it from being used.
2368                  * Use the non-SYNC fd; we know it will fail anyway.
2369                  */
2370                 meta.mm_last_pg = metab.mm_last_pg;
2371                 meta.mm_txnid = metab.mm_txnid;
2372 #ifdef _WIN32
2373                 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2374 #else
2375                 r2 = pwrite(env->me_fd, ptr, len, off);
2376 #endif
2377                 env->me_flags |= MDB_FATAL_ERROR;
2378                 return rc;
2379         }
2380         /* Memory ordering issues are irrelevant; since the entire writer
2381          * is wrapped by wmutex, all of these changes will become visible
2382          * after the wmutex is unlocked. Since the DB is multi-version,
2383          * readers will get consistent data regardless of how fresh or
2384          * how stale their view of these values is.
2385          */
2386         LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2387         txn->mt_env->me_txns->mti_me_toggle = toggle;
2388         txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2389         LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2390
2391         return MDB_SUCCESS;
2392 }
2393
2394 /** Check both meta pages to see which one is newer.
2395  * @param[in] env the environment handle
2396  * @param[out] which address of where to store the meta toggle ID
2397  * @return 0 on success, non-zero on failure.
2398  */
2399 static int
2400 mdb_env_read_meta(MDB_env *env, int *which)
2401 {
2402         int toggle = 0;
2403
2404         assert(env != NULL);
2405
2406         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2407                 toggle = 1;
2408
2409         DPRINTF("Using meta page %d", toggle);
2410         *which = toggle;
2411
2412         return MDB_SUCCESS;
2413 }
2414
2415 int
2416 mdb_env_create(MDB_env **env)
2417 {
2418         MDB_env *e;
2419
2420         e = calloc(1, sizeof(MDB_env));
2421         if (!e)
2422                 return ENOMEM;
2423
2424         e->me_free_pgs = mdb_midl_alloc();
2425         if (!e->me_free_pgs) {
2426                 free(e);
2427                 return ENOMEM;
2428         }
2429         e->me_maxreaders = DEFAULT_READERS;
2430         e->me_maxdbs = 2;
2431         e->me_fd = INVALID_HANDLE_VALUE;
2432         e->me_lfd = INVALID_HANDLE_VALUE;
2433         e->me_mfd = INVALID_HANDLE_VALUE;
2434         VGMEMP_CREATE(e,0,0);
2435         *env = e;
2436         return MDB_SUCCESS;
2437 }
2438
2439 int
2440 mdb_env_set_mapsize(MDB_env *env, size_t size)
2441 {
2442         if (env->me_map)
2443                 return EINVAL;
2444         env->me_mapsize = size;
2445         if (env->me_psize)
2446                 env->me_maxpg = env->me_mapsize / env->me_psize;
2447         return MDB_SUCCESS;
2448 }
2449
2450 int
2451 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2452 {
2453         if (env->me_map)
2454                 return EINVAL;
2455         env->me_maxdbs = dbs;
2456         return MDB_SUCCESS;
2457 }
2458
2459 int
2460 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2461 {
2462         if (env->me_map || readers < 1)
2463                 return EINVAL;
2464         env->me_maxreaders = readers;
2465         return MDB_SUCCESS;
2466 }
2467
2468 int
2469 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2470 {
2471         if (!env || !readers)
2472                 return EINVAL;
2473         *readers = env->me_maxreaders;
2474         return MDB_SUCCESS;
2475 }
2476
2477 /** Further setup required for opening an MDB environment
2478  */
2479 static int
2480 mdb_env_open2(MDB_env *env, unsigned int flags)
2481 {
2482         int i, newenv = 0, toggle;
2483         MDB_meta meta;
2484         MDB_page *p;
2485
2486         env->me_flags = flags;
2487
2488         memset(&meta, 0, sizeof(meta));
2489
2490         if ((i = mdb_env_read_header(env, &meta)) != 0) {
2491                 if (i != ENOENT)
2492                         return i;
2493                 DPUTS("new mdbenv");
2494                 newenv = 1;
2495         }
2496
2497         if (!env->me_mapsize) {
2498                 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2499         }
2500
2501 #ifdef _WIN32
2502         {
2503                 HANDLE mh;
2504                 LONG sizelo, sizehi;
2505                 sizelo = env->me_mapsize & 0xffffffff;
2506                 sizehi = env->me_mapsize >> 16;         /* pointless on WIN32, only needed on W64 */
2507                 sizehi >>= 16;
2508                 /* Windows won't create mappings for zero length files.
2509                  * Just allocate the maxsize right now.
2510                  */
2511                 if (newenv) {
2512                         SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2513                         if (!SetEndOfFile(env->me_fd))
2514                                 return ErrCode();
2515                         SetFilePointer(env->me_fd, 0, NULL, 0);
2516                 }
2517                 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2518                         sizehi, sizelo, NULL);
2519                 if (!mh)
2520                         return ErrCode();
2521                 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2522                         meta.mm_address);
2523                 CloseHandle(mh);
2524                 if (!env->me_map)
2525                         return ErrCode();
2526         }
2527 #else
2528         i = MAP_SHARED;
2529         if (meta.mm_address && (flags & MDB_FIXEDMAP))
2530                 i |= MAP_FIXED;
2531         env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2532                 env->me_fd, 0);
2533         if (env->me_map == MAP_FAILED) {
2534                 env->me_map = NULL;
2535                 return ErrCode();
2536         }
2537 #endif
2538
2539         if (newenv) {
2540                 meta.mm_mapsize = env->me_mapsize;
2541                 if (flags & MDB_FIXEDMAP)
2542                         meta.mm_address = env->me_map;
2543                 i = mdb_env_init_meta(env, &meta);
2544                 if (i != MDB_SUCCESS) {
2545                         munmap(env->me_map, env->me_mapsize);
2546                         return i;
2547                 }
2548         }
2549         env->me_psize = meta.mm_psize;
2550
2551         env->me_maxpg = env->me_mapsize / env->me_psize;
2552
2553         p = (MDB_page *)env->me_map;
2554         env->me_metas[0] = METADATA(p);
2555         env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2556
2557         if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2558                 return i;
2559
2560         DPRINTF("opened database version %u, pagesize %u",
2561             env->me_metas[toggle]->mm_version, env->me_psize);
2562         DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2563         DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2564         DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2565         DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2566         DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2567         DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2568
2569         return MDB_SUCCESS;
2570 }
2571
2572 #ifndef _WIN32
2573 /** Release a reader thread's slot in the reader lock table.
2574  *      This function is called automatically when a thread exits.
2575  *      Windows doesn't support destructor callbacks for thread-specific storage,
2576  *      so this function is not compiled there.
2577  * @param[in] ptr This points to the slot in the reader lock table.
2578  */
2579 static void
2580 mdb_env_reader_dest(void *ptr)
2581 {
2582         MDB_reader *reader = ptr;
2583
2584         reader->mr_txnid = 0;
2585         reader->mr_pid = 0;
2586         reader->mr_tid = 0;
2587 }
2588 #endif
2589
2590 /** Downgrade the exclusive lock on the region back to shared */
2591 static void
2592 mdb_env_share_locks(MDB_env *env)
2593 {
2594         int toggle = 0;
2595
2596         if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2597                 toggle = 1;
2598         env->me_txns->mti_me_toggle = toggle;
2599         env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2600
2601 #ifdef _WIN32
2602         {
2603                 OVERLAPPED ov;
2604                 /* First acquire a shared lock. The Unlock will
2605                  * then release the existing exclusive lock.
2606                  */
2607                 memset(&ov, 0, sizeof(ov));
2608                 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2609                 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2610         }
2611 #else
2612         {
2613                 struct flock lock_info;
2614                 /* The shared lock replaces the existing lock */
2615                 memset((void *)&lock_info, 0, sizeof(lock_info));
2616                 lock_info.l_type = F_RDLCK;
2617                 lock_info.l_whence = SEEK_SET;
2618                 lock_info.l_start = 0;
2619                 lock_info.l_len = 1;
2620                 fcntl(env->me_lfd, F_SETLK, &lock_info);
2621         }
2622 #endif
2623 }
2624 #if defined(_WIN32) || defined(__APPLE__)
2625 /*
2626  * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2627  *
2628  * @(#) $Revision: 5.1 $
2629  * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2630  * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2631  *
2632  *        http://www.isthe.com/chongo/tech/comp/fnv/index.html
2633  *
2634  ***
2635  *
2636  * Please do not copyright this code.  This code is in the public domain.
2637  *
2638  * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2639  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2640  * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2641  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2642  * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2643  * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2644  * PERFORMANCE OF THIS SOFTWARE.
2645  *
2646  * By:
2647  *      chongo <Landon Curt Noll> /\oo/\
2648  *        http://www.isthe.com/chongo/
2649  *
2650  * Share and Enjoy!     :-)
2651  */
2652
2653 typedef unsigned long long      mdb_hash_t;
2654 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2655
2656 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2657  * @param[in] str string to hash
2658  * @param[in] hval      initial value for hash
2659  * @return 64 bit hash
2660  *
2661  * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2662  *       hval arg on the first call.
2663  */
2664 static mdb_hash_t
2665 mdb_hash_str(char *str, mdb_hash_t hval)
2666 {
2667         unsigned char *s = (unsigned char *)str;        /* unsigned string */
2668         /*
2669          * FNV-1a hash each octet of the string
2670          */
2671         while (*s) {
2672                 /* xor the bottom with the current octet */
2673                 hval ^= (mdb_hash_t)*s++;
2674
2675                 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2676                 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2677                         (hval << 7) + (hval << 8) + (hval << 40);
2678         }
2679         /* return our new hash value */
2680         return hval;
2681 }
2682
2683 /** Hash the string and output the hash in hex.
2684  * @param[in] str string to hash
2685  * @param[out] hexbuf an array of 17 chars to hold the hash
2686  */
2687 static void
2688 mdb_hash_hex(char *str, char *hexbuf)
2689 {
2690         int i;
2691         mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2692         for (i=0; i<8; i++) {
2693                 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2694                 h >>= 8;
2695         }
2696 }
2697 #endif
2698
2699 /** Open and/or initialize the lock region for the environment.
2700  * @param[in] env The MDB environment.
2701  * @param[in] lpath The pathname of the file used for the lock region.
2702  * @param[in] mode The Unix permissions for the file, if we create it.
2703  * @param[out] excl Set to true if we got an exclusive lock on the region.
2704  * @return 0 on success, non-zero on failure.
2705  */
2706 static int
2707 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2708 {
2709         int rc;
2710         off_t size, rsize;
2711
2712         *excl = 0;
2713
2714 #ifdef _WIN32
2715         if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2716                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2717                 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2718                 rc = ErrCode();
2719                 return rc;
2720         }
2721         /* Try to get exclusive lock. If we succeed, then
2722          * nobody is using the lock region and we should initialize it.
2723          */
2724         {
2725                 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2726                         *excl = 1;
2727                 } else {
2728                         OVERLAPPED ov;
2729                         memset(&ov, 0, sizeof(ov));
2730                         if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2731                                 rc = ErrCode();
2732                                 goto fail;
2733                         }
2734                 }
2735         }
2736         size = GetFileSize(env->me_lfd, NULL);
2737 #else
2738         if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2739                 rc = ErrCode();
2740                 return rc;
2741         }
2742         /* Try to get exclusive lock. If we succeed, then
2743          * nobody is using the lock region and we should initialize it.
2744          */
2745         {
2746                 struct flock lock_info;
2747                 memset((void *)&lock_info, 0, sizeof(lock_info));
2748                 lock_info.l_type = F_WRLCK;
2749                 lock_info.l_whence = SEEK_SET;
2750                 lock_info.l_start = 0;
2751                 lock_info.l_len = 1;
2752                 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2753                 if (rc == 0) {
2754                         *excl = 1;
2755                 } else {
2756                         lock_info.l_type = F_RDLCK;
2757                         rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2758                         if (rc) {
2759                                 rc = ErrCode();
2760                                 goto fail;
2761                         }
2762                 }
2763         }
2764         size = lseek(env->me_lfd, 0, SEEK_END);
2765 #endif
2766         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2767         if (size < rsize && *excl) {
2768 #ifdef _WIN32
2769                 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2770                 if (!SetEndOfFile(env->me_lfd)) {
2771                         rc = ErrCode();
2772                         goto fail;
2773                 }
2774 #else
2775                 if (ftruncate(env->me_lfd, rsize) != 0) {
2776                         rc = ErrCode();
2777                         goto fail;
2778                 }
2779 #endif
2780         } else {
2781                 rsize = size;
2782                 size = rsize - sizeof(MDB_txninfo);
2783                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2784         }
2785         {
2786 #ifdef _WIN32
2787                 HANDLE mh;
2788                 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2789                         0, 0, NULL);
2790                 if (!mh) {
2791                         rc = ErrCode();
2792                         goto fail;
2793                 }
2794                 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2795                 CloseHandle(mh);
2796                 if (!env->me_txns) {
2797                         rc = ErrCode();
2798                         goto fail;
2799                 }
2800 #else
2801                 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2802                         env->me_lfd, 0);
2803                 if (m == MAP_FAILED) {
2804                         env->me_txns = NULL;
2805                         rc = ErrCode();
2806                         goto fail;
2807                 }
2808                 env->me_txns = m;
2809 #endif
2810         }
2811         if (*excl) {
2812 #ifdef _WIN32
2813                 char hexbuf[17];
2814                 if (!mdb_sec_inited) {
2815                         InitializeSecurityDescriptor(&mdb_null_sd,
2816                                 SECURITY_DESCRIPTOR_REVISION);
2817                         SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2818                         mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2819                         mdb_all_sa.bInheritHandle = FALSE;
2820                         mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2821                         mdb_sec_inited = 1;
2822                 }
2823                 mdb_hash_hex(lpath, hexbuf);
2824                 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2825                 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2826                 if (!env->me_rmutex) {
2827                         rc = ErrCode();
2828                         goto fail;
2829                 }
2830                 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2831                 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2832                 if (!env->me_wmutex) {
2833                         rc = ErrCode();
2834                         goto fail;
2835                 }
2836 #else   /* _WIN32 */
2837 #ifdef __APPLE__
2838                 char hexbuf[17];
2839                 mdb_hash_hex(lpath, hexbuf);
2840                 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2841                 if (sem_unlink(env->me_txns->mti_rmname)) {
2842                         rc = ErrCode();
2843                         if (rc != ENOENT && rc != EINVAL)
2844                                 goto fail;
2845                 }
2846                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2847                 if (!env->me_rmutex) {
2848                         rc = ErrCode();
2849                         goto fail;
2850                 }
2851                 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2852                 if (sem_unlink(env->me_txns->mti_wmname)) {
2853                         rc = ErrCode();
2854                         if (rc != ENOENT && rc != EINVAL)
2855                                 goto fail;
2856                 }
2857                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2858                 if (!env->me_wmutex) {
2859                         rc = ErrCode();
2860                         goto fail;
2861                 }
2862 #else   /* __APPLE__ */
2863                 pthread_mutexattr_t mattr;
2864
2865                 pthread_mutexattr_init(&mattr);
2866                 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2867                 if (rc) {
2868                         goto fail;
2869                 }
2870                 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2871                 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2872 #endif  /* __APPLE__ */
2873 #endif  /* _WIN32 */
2874                 env->me_txns->mti_version = MDB_VERSION;
2875                 env->me_txns->mti_magic = MDB_MAGIC;
2876                 env->me_txns->mti_txnid = 0;
2877                 env->me_txns->mti_numreaders = 0;
2878                 env->me_txns->mti_me_toggle = 0;
2879
2880         } else {
2881                 if (env->me_txns->mti_magic != MDB_MAGIC) {
2882                         DPUTS("lock region has invalid magic");
2883                         rc = EINVAL;
2884                         goto fail;
2885                 }
2886                 if (env->me_txns->mti_version != MDB_VERSION) {
2887                         DPRINTF("lock region is version %u, expected version %u",
2888                                 env->me_txns->mti_version, MDB_VERSION);
2889                         rc = MDB_VERSION_MISMATCH;
2890                         goto fail;
2891                 }
2892                 rc = ErrCode();
2893                 if (rc != EACCES && rc != EAGAIN) {
2894                         goto fail;
2895                 }
2896 #ifdef _WIN32
2897                 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2898                 if (!env->me_rmutex) {
2899                         rc = ErrCode();
2900                         goto fail;
2901                 }
2902                 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2903                 if (!env->me_wmutex) {
2904                         rc = ErrCode();
2905                         goto fail;
2906                 }
2907 #endif
2908 #ifdef __APPLE__
2909                 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2910                 if (!env->me_rmutex) {
2911                         rc = ErrCode();
2912                         goto fail;
2913                 }
2914                 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2915                 if (!env->me_wmutex) {
2916                         rc = ErrCode();
2917                         goto fail;
2918                 }
2919 #endif
2920         }
2921         return MDB_SUCCESS;
2922
2923 fail:
2924         close(env->me_lfd);
2925         env->me_lfd = INVALID_HANDLE_VALUE;
2926         return rc;
2927
2928 }
2929
2930         /** The name of the lock file in the DB environment */
2931 #define LOCKNAME        "/lock.mdb"
2932         /** The name of the data file in the DB environment */
2933 #define DATANAME        "/data.mdb"
2934         /** The suffix of the lock file when no subdir is used */
2935 #define LOCKSUFF        "-lock"
2936
2937 int
2938 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2939 {
2940         int             oflags, rc, len, excl;
2941         char *lpath, *dpath;
2942
2943         len = strlen(path);
2944         if (flags & MDB_NOSUBDIR) {
2945                 rc = len + sizeof(LOCKSUFF) + len + 1;
2946         } else {
2947                 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2948         }
2949         lpath = malloc(rc);
2950         if (!lpath)
2951                 return ENOMEM;
2952         if (flags & MDB_NOSUBDIR) {
2953                 dpath = lpath + len + sizeof(LOCKSUFF);
2954                 sprintf(lpath, "%s" LOCKSUFF, path);
2955                 strcpy(dpath, path);
2956         } else {
2957                 dpath = lpath + len + sizeof(LOCKNAME);
2958                 sprintf(lpath, "%s" LOCKNAME, path);
2959                 sprintf(dpath, "%s" DATANAME, path);
2960         }
2961
2962         rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2963         if (rc)
2964                 goto leave;
2965
2966 #ifdef _WIN32
2967         if (F_ISSET(flags, MDB_RDONLY)) {
2968                 oflags = GENERIC_READ;
2969                 len = OPEN_EXISTING;
2970         } else {
2971                 oflags = GENERIC_READ|GENERIC_WRITE;
2972                 len = OPEN_ALWAYS;
2973         }
2974         mode = FILE_ATTRIBUTE_NORMAL;
2975         if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2976                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2977                 rc = ErrCode();
2978                 goto leave;
2979         }
2980 #else
2981         if (F_ISSET(flags, MDB_RDONLY))
2982                 oflags = O_RDONLY;
2983         else
2984                 oflags = O_RDWR | O_CREAT;
2985
2986         if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2987                 rc = ErrCode();
2988                 goto leave;
2989         }
2990 #endif
2991
2992         if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2993                 /* synchronous fd for meta writes */
2994 #ifdef _WIN32
2995                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2996                         mode |= FILE_FLAG_WRITE_THROUGH;
2997                 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2998                         NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2999                         rc = ErrCode();
3000                         goto leave;
3001                 }
3002 #else
3003                 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
3004                         oflags |= MDB_DSYNC;
3005                 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
3006                         rc = ErrCode();
3007                         goto leave;
3008                 }
3009 #endif
3010                 env->me_path = strdup(path);
3011                 DPRINTF("opened dbenv %p", (void *) env);
3012                 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3013                 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
3014                 if (excl)
3015                         mdb_env_share_locks(env);
3016                 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3017                 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
3018                 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
3019                 env->me_numdbs = 2;
3020         }
3021
3022 leave:
3023         if (rc) {
3024                 if (env->me_fd != INVALID_HANDLE_VALUE) {
3025                         close(env->me_fd);
3026                         env->me_fd = INVALID_HANDLE_VALUE;
3027                 }
3028                 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3029                         close(env->me_lfd);
3030                         env->me_lfd = INVALID_HANDLE_VALUE;
3031                 }
3032         }
3033         free(lpath);
3034         return rc;
3035 }
3036
3037 void
3038 mdb_env_close(MDB_env *env)
3039 {
3040         MDB_page *dp;
3041
3042         if (env == NULL)
3043                 return;
3044
3045         VGMEMP_DESTROY(env);
3046         while (env->me_dpages) {
3047                 dp = env->me_dpages;
3048                 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3049                 env->me_dpages = dp->mp_next;
3050                 free(dp);
3051         }
3052
3053         free(env->me_dbs[1]);
3054         free(env->me_dbs[0]);
3055         free(env->me_dbxs);
3056         free(env->me_path);
3057
3058         LAZY_RWLOCK_DESTROY(&env->me_dblock);
3059         pthread_key_delete(env->me_txkey);
3060
3061         if (env->me_map) {
3062                 munmap(env->me_map, env->me_mapsize);
3063         }
3064         close(env->me_mfd);
3065         close(env->me_fd);
3066         if (env->me_txns) {
3067                 pid_t pid = getpid();
3068                 unsigned int i;
3069                 for (i=0; i<env->me_txns->mti_numreaders; i++)
3070                         if (env->me_txns->mti_readers[i].mr_pid == pid)
3071                                 env->me_txns->mti_readers[i].mr_pid = 0;
3072                 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3073         }
3074         close(env->me_lfd);
3075         mdb_midl_free(env->me_free_pgs);
3076         free(env);
3077 }
3078
3079 /** Compare two items pointing at aligned size_t's */
3080 static int
3081 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3082 {
3083         return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3084                 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3085 }
3086
3087 /** Compare two items pointing at aligned int's */
3088 static int
3089 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3090 {
3091         return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3092                 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3093 }
3094
3095 /** Compare two items pointing at ints of unknown alignment.
3096  *      Nodes and keys are guaranteed to be 2-byte aligned.
3097  */
3098 static int
3099 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3100 {
3101 #if BYTE_ORDER == LITTLE_ENDIAN
3102         unsigned short *u, *c;
3103         int x;
3104
3105         u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3106         c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3107         do {
3108                 x = *--u - *--c;
3109         } while(!x && u > (unsigned short *)a->mv_data);
3110         return x;
3111 #else
3112         return memcmp(a->mv_data, b->mv_data, a->mv_size);
3113 #endif
3114 }
3115
3116 /** Compare two items lexically */
3117 static int
3118 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3119 {
3120         int diff;
3121         ssize_t len_diff;
3122         unsigned int len;
3123
3124         len = a->mv_size;
3125         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3126         if (len_diff > 0) {
3127                 len = b->mv_size;
3128                 len_diff = 1;
3129         }
3130
3131         diff = memcmp(a->mv_data, b->mv_data, len);
3132         return diff ? diff : len_diff<0 ? -1 : len_diff;
3133 }
3134
3135 /** Compare two items in reverse byte order */
3136 static int
3137 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3138 {
3139         const unsigned char     *p1, *p2, *p1_lim;
3140         ssize_t len_diff;
3141         int diff;
3142
3143         p1_lim = (const unsigned char *)a->mv_data;
3144         p1 = (const unsigned char *)a->mv_data + a->mv_size;
3145         p2 = (const unsigned char *)b->mv_data + b->mv_size;
3146
3147         len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3148         if (len_diff > 0) {
3149                 p1_lim += len_diff;
3150                 len_diff = 1;
3151         }
3152
3153         while (p1 > p1_lim) {
3154                 diff = *--p1 - *--p2;
3155                 if (diff)
3156                         return diff;
3157         }
3158         return len_diff<0 ? -1 : len_diff;
3159 }
3160
3161 /** Search for key within a page, using binary search.
3162  * Returns the smallest entry larger or equal to the key.
3163  * If exactp is non-null, stores whether the found entry was an exact match
3164  * in *exactp (1 or 0).
3165  * Updates the cursor index with the index of the found entry.
3166  * If no entry larger or equal to the key is found, returns NULL.
3167  */
3168 static MDB_node *
3169 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3170 {
3171         unsigned int     i = 0, nkeys;
3172         int              low, high;
3173         int              rc = 0;
3174         MDB_page *mp = mc->mc_pg[mc->mc_top];
3175         MDB_node        *node = NULL;
3176         MDB_val  nodekey;
3177         MDB_cmp_func *cmp;
3178         DKBUF;
3179
3180         nkeys = NUMKEYS(mp);
3181
3182 #if MDB_DEBUG
3183         {
3184         pgno_t pgno;
3185         COPY_PGNO(pgno, mp->mp_pgno);
3186         DPRINTF("searching %u keys in %s %spage %zu",
3187             nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3188             pgno);
3189         }
3190 #endif
3191
3192         assert(nkeys > 0);
3193
3194         low = IS_LEAF(mp) ? 0 : 1;
3195         high = nkeys - 1;
3196         cmp = mc->mc_dbx->md_cmp;
3197
3198         /* Branch pages have no data, so if using integer keys,
3199          * alignment is guaranteed. Use faster mdb_cmp_int.
3200          */
3201         if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3202                 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3203                         cmp = mdb_cmp_long;
3204                 else
3205                         cmp = mdb_cmp_int;
3206         }
3207
3208         if (IS_LEAF2(mp)) {
3209                 nodekey.mv_size = mc->mc_db->md_pad;
3210                 node = NODEPTR(mp, 0);  /* fake */
3211                 while (low <= high) {
3212                         i = (low + high) >> 1;
3213                         nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3214                         rc = cmp(key, &nodekey);
3215                         DPRINTF("found leaf index %u [%s], rc = %i",
3216                             i, DKEY(&nodekey), rc);
3217                         if (rc == 0)
3218                                 break;
3219                         if (rc > 0)
3220                                 low = i + 1;
3221                         else
3222                                 high = i - 1;
3223                 }
3224         } else {
3225                 while (low <= high) {
3226                         i = (low + high) >> 1;
3227
3228                         node = NODEPTR(mp, i);
3229                         nodekey.mv_size = NODEKSZ(node);
3230                         nodekey.mv_data = NODEKEY(node);
3231
3232                         rc = cmp(key, &nodekey);
3233 #if MDB_DEBUG
3234                         if (IS_LEAF(mp))
3235                                 DPRINTF("found leaf index %u [%s], rc = %i",
3236                                     i, DKEY(&nodekey), rc);
3237                         else
3238                                 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3239                                     i, DKEY(&nodekey), NODEPGNO(node), rc);
3240 #endif
3241                         if (rc == 0)
3242                                 break;
3243                         if (rc > 0)
3244                                 low = i + 1;
3245                         else
3246                                 high = i - 1;
3247                 }
3248         }
3249
3250         if (rc > 0) {   /* Found entry is less than the key. */
3251                 i++;    /* Skip to get the smallest entry larger than key. */
3252                 if (!IS_LEAF2(mp))
3253                         node = NODEPTR(mp, i);
3254         }
3255         if (exactp)
3256                 *exactp = (rc == 0);
3257         /* store the key index */
3258         mc->mc_ki[mc->mc_top] = i;
3259         if (i >= nkeys)
3260                 /* There is no entry larger or equal to the key. */
3261                 return NULL;
3262
3263         /* nodeptr is fake for LEAF2 */
3264         return node;
3265 }
3266
3267 #if 0
3268 static void
3269 mdb_cursor_adjust(MDB_cursor *mc, func)
3270 {
3271         MDB_cursor *m2;
3272
3273         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3274                 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3275                         func(mc, m2);
3276                 }
3277         }
3278 }
3279 #endif
3280
3281 /** Pop a page off the top of the cursor's stack. */
3282 static void
3283 mdb_cursor_pop(MDB_cursor *mc)
3284 {
3285         MDB_page        *top;
3286
3287         if (mc->mc_snum) {
3288                 top = mc->mc_pg[mc->mc_top];
3289                 mc->mc_snum--;
3290                 if (mc->mc_snum)
3291                         mc->mc_top--;
3292
3293                 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3294                         mc->mc_dbi, (void *) mc);
3295         }
3296 }
3297
3298 /** Push a page onto the top of the cursor's stack. */
3299 static int
3300 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3301 {
3302         DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3303                 mc->mc_dbi, (void *) mc);
3304
3305         if (mc->mc_snum >= CURSOR_STACK) {
3306                 assert(mc->mc_snum < CURSOR_STACK);
3307                 return ENOMEM;
3308         }
3309
3310         mc->mc_top = mc->mc_snum++;
3311         mc->mc_pg[mc->mc_top] = mp;
3312         mc->mc_ki[mc->mc_top] = 0;
3313
3314         return MDB_SUCCESS;
3315 }
3316
3317 /** Find the address of the page corresponding to a given page number.
3318  * @param[in] txn the transaction for this access.
3319  * @param[in] pgno the page number for the page to retrieve.
3320  * @param[out] ret address of a pointer where the page's address will be stored.
3321  * @return 0 on success, non-zero on failure.
3322  */
3323 static int
3324 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3325 {
3326         MDB_page *p = NULL;
3327
3328         if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3329                 unsigned x;
3330                 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3331                 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3332                         p = txn->mt_u.dirty_list[x].mptr;
3333                 }
3334         }
3335         if (!p) {
3336                 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3337                         p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3338         }
3339         *ret = p;
3340         if (!p) {
3341                 DPRINTF("page %zu not found", pgno);
3342                 assert(p != NULL);
3343         }
3344         return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3345 }
3346
3347 /** Search for the page a given key should be in.
3348  * Pushes parent pages on the cursor stack. This function continues a
3349  * search on a cursor that has already been initialized. (Usually by
3350  * #mdb_page_search() but also by #mdb_node_move().)
3351  * @param[in,out] mc the cursor for this operation.
3352  * @param[in] key the key to search for. If NULL, search for the lowest
3353  * page. (This is used by #mdb_cursor_first().)
3354  * @param[in] modify If true, visited pages are updated with new page numbers.
3355  * @return 0 on success, non-zero on failure.
3356  */
3357 static int
3358 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3359 {
3360         MDB_page        *mp = mc->mc_pg[mc->mc_top];
3361         DKBUF;
3362         int rc;
3363
3364
3365         while (IS_BRANCH(mp)) {
3366                 MDB_node        *node;
3367                 indx_t          i;
3368
3369                 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3370                 assert(NUMKEYS(mp) > 1);
3371                 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3372
3373                 if (key == NULL)        /* Initialize cursor to first page. */
3374                         i = 0;
3375                 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3376                                                         /* cursor to last page */
3377                         i = NUMKEYS(mp)-1;
3378                 } else {
3379                         int      exact;
3380                         node = mdb_node_search(mc, key, &exact);
3381                         if (node == NULL)
3382                                 i = NUMKEYS(mp) - 1;
3383                         else {
3384                                 i = mc->mc_ki[mc->mc_top];
3385                                 if (!exact) {
3386                                         assert(i > 0);
3387                                         i--;
3388                                 }
3389                         }
3390                 }
3391
3392                 if (key)
3393                         DPRINTF("following index %u for key [%s]",
3394                             i, DKEY(key));
3395                 assert(i < NUMKEYS(mp));
3396                 node = NODEPTR(mp, i);
3397
3398                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3399                         return rc;
3400
3401                 mc->mc_ki[mc->mc_top] = i;
3402                 if ((rc = mdb_cursor_push(mc, mp)))
3403                         return rc;
3404
3405                 if (modify) {
3406                         if ((rc = mdb_page_touch(mc)) != 0)
3407                                 return rc;
3408                         mp = mc->mc_pg[mc->mc_top];
3409                 }
3410         }
3411
3412         if (!IS_LEAF(mp)) {
3413                 DPRINTF("internal error, index points to a %02X page!?",
3414                     mp->mp_flags);
3415                 return MDB_CORRUPTED;
3416         }
3417
3418         DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3419             key ? DKEY(key) : NULL);
3420
3421         return MDB_SUCCESS;
3422 }
3423
3424 /** Search for the page a given key should be in.
3425  * Pushes parent pages on the cursor stack. This function just sets up
3426  * the search; it finds the root page for \b mc's database and sets this
3427  * as the root of the cursor's stack. Then #mdb_page_search_root() is
3428  * called to complete the search.
3429  * @param[in,out] mc the cursor for this operation.
3430  * @param[in] key the key to search for. If NULL, search for the lowest
3431  * page. (This is used by #mdb_cursor_first().)
3432  * @param[in] modify If true, visited pages are updated with new page numbers.
3433  * @return 0 on success, non-zero on failure.
3434  */
3435 static int
3436 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3437 {
3438         int              rc;
3439         pgno_t           root;
3440
3441         /* Make sure the txn is still viable, then find the root from
3442          * the txn's db table.
3443          */
3444         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3445                 DPUTS("transaction has failed, must abort");
3446                 return EINVAL;
3447         } else {
3448                 /* Make sure we're using an up-to-date root */
3449                 if (mc->mc_dbi > MAIN_DBI) {
3450                         if ((*mc->mc_dbflag & DB_STALE) ||
3451                         (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3452                                 MDB_cursor mc2;
3453                                 unsigned char dbflag = 0;
3454                                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3455                                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3456                                 if (rc)
3457                                         return rc;
3458                                 if (*mc->mc_dbflag & DB_STALE) {
3459                                         MDB_val data;
3460                                         int exact = 0;
3461                                         MDB_node *leaf = mdb_node_search(&mc2,
3462                                                 &mc->mc_dbx->md_name, &exact);
3463                                         if (!exact)
3464                                                 return MDB_NOTFOUND;
3465                                         mdb_node_read(mc->mc_txn, leaf, &data);
3466                                         memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3467                                 }
3468                                 if (modify)
3469                                         dbflag = DB_DIRTY;
3470                                 *mc->mc_dbflag = dbflag;
3471                         }
3472                 }
3473                 root = mc->mc_db->md_root;
3474
3475                 if (root == P_INVALID) {                /* Tree is empty. */
3476                         DPUTS("tree is empty");
3477                         return MDB_NOTFOUND;
3478                 }
3479         }
3480
3481         assert(root > 1);
3482         if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3483                 return rc;
3484
3485         mc->mc_snum = 1;
3486         mc->mc_top = 0;
3487
3488         DPRINTF("db %u root page %zu has flags 0x%X",
3489                 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3490
3491         if (modify) {
3492                 if ((rc = mdb_page_touch(mc)))
3493                         return rc;
3494         }
3495
3496         return mdb_page_search_root(mc, key, modify);
3497 }
3498
3499 /** Return the data associated with a given node.
3500  * @param[in] txn The transaction for this operation.
3501  * @param[in] leaf The node being read.
3502  * @param[out] data Updated to point to the node's data.
3503  * @return 0 on success, non-zero on failure.
3504  */
3505 static int
3506 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3507 {
3508         MDB_page        *omp;           /* overflow page */
3509         pgno_t           pgno;
3510         int rc;
3511
3512         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3513                 data->mv_size = NODEDSZ(leaf);
3514                 data->mv_data = NODEDATA(leaf);
3515                 return MDB_SUCCESS;
3516         }
3517
3518         /* Read overflow data.
3519          */
3520         data->mv_size = NODEDSZ(leaf);
3521         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3522         if ((rc = mdb_page_get(txn, pgno, &omp))) {
3523                 DPRINTF("read overflow page %zu failed", pgno);
3524                 return rc;
3525         }
3526         data->mv_data = METADATA(omp);
3527
3528         return MDB_SUCCESS;
3529 }
3530
3531 int
3532 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3533     MDB_val *key, MDB_val *data)
3534 {
3535         MDB_cursor      mc;
3536         MDB_xcursor     mx;
3537         int exact = 0;
3538         DKBUF;
3539
3540         assert(key);
3541         assert(data);
3542         DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3543
3544         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3545                 return EINVAL;
3546
3547         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3548                 return EINVAL;
3549         }
3550
3551         mdb_cursor_init(&mc, txn, dbi, &mx);
3552         return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3553 }
3554
3555 /** Find a sibling for a page.
3556  * Replaces the page at the top of the cursor's stack with the
3557  * specified sibling, if one exists.
3558  * @param[in] mc The cursor for this operation.
3559  * @param[in] move_right Non-zero if the right sibling is requested,
3560  * otherwise the left sibling.
3561  * @return 0 on success, non-zero on failure.
3562  */
3563 static int
3564 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3565 {
3566         int              rc;
3567         MDB_node        *indx;
3568         MDB_page        *mp;
3569
3570         if (mc->mc_snum < 2) {
3571                 return MDB_NOTFOUND;            /* root has no siblings */
3572         }
3573
3574         mdb_cursor_pop(mc);
3575         DPRINTF("parent page is page %zu, index %u",
3576                 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3577
3578         if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3579                        : (mc->mc_ki[mc->mc_top] == 0)) {
3580                 DPRINTF("no more keys left, moving to %s sibling",
3581                     move_right ? "right" : "left");
3582                 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3583                         return rc;
3584         } else {
3585                 if (move_right)
3586                         mc->mc_ki[mc->mc_top]++;
3587                 else
3588                         mc->mc_ki[mc->mc_top]--;
3589                 DPRINTF("just moving to %s index key %u",
3590                     move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3591         }
3592         assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3593
3594         indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3595         if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3596                 return rc;;
3597
3598         mdb_cursor_push(mc, mp);
3599
3600         return MDB_SUCCESS;
3601 }
3602
3603 /** Move the cursor to the next data item. */
3604 static int
3605 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3606 {
3607         MDB_page        *mp;
3608         MDB_node        *leaf;
3609         int rc;
3610
3611         if (mc->mc_flags & C_EOF) {
3612                 return MDB_NOTFOUND;
3613         }
3614
3615         assert(mc->mc_flags & C_INITIALIZED);
3616
3617         mp = mc->mc_pg[mc->mc_top];
3618
3619         if (mc->mc_db->md_flags & MDB_DUPSORT) {
3620                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3621                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3622                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3623                                 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3624                                 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3625                                         return rc;
3626                         }
3627                 } else {
3628                         mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3629                         if (op == MDB_NEXT_DUP)
3630                                 return MDB_NOTFOUND;
3631                 }
3632         }
3633
3634         DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3635
3636         if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3637                 DPUTS("=====> move to next sibling page");
3638                 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3639                         mc->mc_flags |= C_EOF;
3640                         mc->mc_flags &= ~C_INITIALIZED;
3641                         return MDB_NOTFOUND;
3642                 }
3643                 mp = mc->mc_pg[mc->mc_top];
3644                 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3645         } else
3646                 mc->mc_ki[mc->mc_top]++;
3647
3648         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3649             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3650
3651         if (IS_LEAF2(mp)) {
3652                 key->mv_size = mc->mc_db->md_pad;
3653                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3654                 return MDB_SUCCESS;
3655         }
3656
3657         assert(IS_LEAF(mp));
3658         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3659
3660         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3661                 mdb_xcursor_init1(mc, leaf);
3662         }
3663         if (data) {
3664                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3665                         return rc;
3666
3667                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3668                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3669                         if (rc != MDB_SUCCESS)
3670                                 return rc;
3671                 }
3672         }
3673
3674         MDB_SET_KEY(leaf, key);
3675         return MDB_SUCCESS;
3676 }
3677
3678 /** Move the cursor to the previous data item. */
3679 static int
3680 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3681 {
3682         MDB_page        *mp;
3683         MDB_node        *leaf;
3684         int rc;
3685
3686         assert(mc->mc_flags & C_INITIALIZED);
3687
3688         mp = mc->mc_pg[mc->mc_top];
3689
3690         if (mc->mc_db->md_flags & MDB_DUPSORT) {
3691                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3692                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3693                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3694                                 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3695                                 if (op != MDB_PREV || rc == MDB_SUCCESS)
3696                                         return rc;
3697                         } else {
3698                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3699                                 if (op == MDB_PREV_DUP)
3700                                         return MDB_NOTFOUND;
3701                         }
3702                 }
3703         }
3704
3705         DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3706
3707         if (mc->mc_ki[mc->mc_top] == 0)  {
3708                 DPUTS("=====> move to prev sibling page");
3709                 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3710                         mc->mc_flags &= ~C_INITIALIZED;
3711                         return MDB_NOTFOUND;
3712                 }
3713                 mp = mc->mc_pg[mc->mc_top];
3714                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3715                 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3716         } else
3717                 mc->mc_ki[mc->mc_top]--;
3718
3719         mc->mc_flags &= ~C_EOF;
3720
3721         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3722             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3723
3724         if (IS_LEAF2(mp)) {
3725                 key->mv_size = mc->mc_db->md_pad;
3726                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3727                 return MDB_SUCCESS;
3728         }
3729
3730         assert(IS_LEAF(mp));
3731         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3732
3733         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3734                 mdb_xcursor_init1(mc, leaf);
3735         }
3736         if (data) {
3737                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3738                         return rc;
3739
3740                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3741                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3742                         if (rc != MDB_SUCCESS)
3743                                 return rc;
3744                 }
3745         }
3746
3747         MDB_SET_KEY(leaf, key);
3748         return MDB_SUCCESS;
3749 }
3750
3751 /** Set the cursor on a specific data item. */
3752 static int
3753 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3754     MDB_cursor_op op, int *exactp)
3755 {
3756         int              rc;
3757         MDB_page        *mp;
3758         MDB_node        *leaf;
3759         DKBUF;
3760
3761         assert(mc);
3762         assert(key);
3763         assert(key->mv_size > 0);
3764
3765         /* See if we're already on the right page */
3766         if (mc->mc_flags & C_INITIALIZED) {
3767                 MDB_val nodekey;
3768
3769                 mp = mc->mc_pg[mc->mc_top];
3770                 if (!NUMKEYS(mp)) {
3771                         mc->mc_ki[mc->mc_top] = 0;
3772                         return MDB_NOTFOUND;
3773                 }
3774                 if (mp->mp_flags & P_LEAF2) {
3775                         nodekey.mv_size = mc->mc_db->md_pad;
3776                         nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3777                 } else {
3778                         leaf = NODEPTR(mp, 0);
3779                         MDB_SET_KEY(leaf, &nodekey);
3780                 }
3781                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3782                 if (rc == 0) {
3783                         /* Probably happens rarely, but first node on the page
3784                          * was the one we wanted.
3785                          */
3786                         mc->mc_ki[mc->mc_top] = 0;
3787                         leaf = NODEPTR(mp, 0);
3788                         if (exactp)
3789                                 *exactp = 1;
3790                         goto set1;
3791                 }
3792                 if (rc > 0) {
3793                         unsigned int i;
3794                         unsigned int nkeys = NUMKEYS(mp);
3795                         if (nkeys > 1) {
3796                                 if (mp->mp_flags & P_LEAF2) {
3797                                         nodekey.mv_data = LEAF2KEY(mp,
3798                                                  nkeys-1, nodekey.mv_size);
3799                                 } else {
3800                                         leaf = NODEPTR(mp, nkeys-1);
3801                                         MDB_SET_KEY(leaf, &nodekey);
3802                                 }
3803                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3804                                 if (rc == 0) {
3805                                         /* last node was the one we wanted */
3806                                         mc->mc_ki[mc->mc_top] = nkeys-1;
3807                                         leaf = NODEPTR(mp, nkeys-1);
3808                                         if (exactp)
3809                                                 *exactp = 1;
3810                                         goto set1;
3811                                 }
3812                                 if (rc < 0) {
3813                                         /* This is definitely the right page, skip search_page */
3814                                         rc = 0;
3815                                         goto set2;
3816                                 }
3817                         }
3818                         /* If any parents have right-sibs, search.
3819                          * Otherwise, there's nothing further.
3820                          */
3821                         for (i=0; i<mc->mc_top; i++)
3822                                 if (mc->mc_ki[i] <
3823                                         NUMKEYS(mc->mc_pg[i])-1)
3824                                         break;
3825                         if (i == mc->mc_top) {
3826                                 /* There are no other pages */
3827                                 mc->mc_ki[mc->mc_top] = nkeys;
3828                                 return MDB_NOTFOUND;
3829                         }
3830                 }
3831                 if (!mc->mc_top) {
3832                         /* There are no other pages */
3833                         mc->mc_ki[mc->mc_top] = 0;
3834                         return MDB_NOTFOUND;
3835                 }
3836         }
3837
3838         rc = mdb_page_search(mc, key, 0);
3839         if (rc != MDB_SUCCESS)
3840                 return rc;
3841
3842         mp = mc->mc_pg[mc->mc_top];
3843         assert(IS_LEAF(mp));
3844
3845 set2:
3846         leaf = mdb_node_search(mc, key, exactp);
3847         if (exactp != NULL && !*exactp) {
3848                 /* MDB_SET specified and not an exact match. */
3849                 return MDB_NOTFOUND;
3850         }
3851
3852         if (leaf == NULL) {
3853                 DPUTS("===> inexact leaf not found, goto sibling");
3854                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3855                         return rc;              /* no entries matched */
3856                 mp = mc->mc_pg[mc->mc_top];
3857                 assert(IS_LEAF(mp));
3858                 leaf = NODEPTR(mp, 0);
3859         }
3860
3861 set1:
3862         mc->mc_flags |= C_INITIALIZED;
3863         mc->mc_flags &= ~C_EOF;
3864
3865         if (IS_LEAF2(mp)) {
3866                 key->mv_size = mc->mc_db->md_pad;
3867                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3868                 return MDB_SUCCESS;
3869         }
3870
3871         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3872                 mdb_xcursor_init1(mc, leaf);
3873         }
3874         if (data) {
3875                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3876                         if (op == MDB_SET || op == MDB_SET_RANGE) {
3877                                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3878                         } else {
3879                                 int ex2, *ex2p;
3880                                 if (op == MDB_GET_BOTH) {
3881                                         ex2p = &ex2;
3882                                         ex2 = 0;
3883                                 } else {
3884                                         ex2p = NULL;
3885                                 }
3886                                 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3887                                 if (rc != MDB_SUCCESS)
3888                                         return rc;
3889                         }
3890                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3891                         MDB_val d2;
3892                         if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3893                                 return rc;
3894                         rc = mc->mc_dbx->md_dcmp(data, &d2);
3895                         if (rc) {
3896                                 if (op == MDB_GET_BOTH || rc > 0)
3897                                         return MDB_NOTFOUND;
3898                         }
3899
3900                 } else {
3901                         if (mc->mc_xcursor)
3902                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3903                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3904                                 return rc;
3905                 }
3906         }
3907
3908         /* The key already matches in all other cases */
3909         if (op == MDB_SET_RANGE)
3910                 MDB_SET_KEY(leaf, key);
3911         DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3912
3913         return rc;
3914 }
3915
3916 /** Move the cursor to the first item in the database. */
3917 static int
3918 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3919 {
3920         int              rc;
3921         MDB_node        *leaf;
3922
3923         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3924                 rc = mdb_page_search(mc, NULL, 0);
3925                 if (rc != MDB_SUCCESS)
3926                         return rc;
3927         }
3928         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3929
3930         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3931         mc->mc_flags |= C_INITIALIZED;
3932         mc->mc_flags &= ~C_EOF;
3933
3934         mc->mc_ki[mc->mc_top] = 0;
3935
3936         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3937                 key->mv_size = mc->mc_db->md_pad;
3938                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3939                 return MDB_SUCCESS;
3940         }
3941
3942         if (data) {
3943                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3944                         mdb_xcursor_init1(mc, leaf);
3945                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3946                         if (rc)
3947                                 return rc;
3948                 } else {
3949                         if (mc->mc_xcursor)
3950                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3951                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3952                                 return rc;
3953                 }
3954         }
3955         MDB_SET_KEY(leaf, key);
3956         return MDB_SUCCESS;
3957 }
3958
3959 /** Move the cursor to the last item in the database. */
3960 static int
3961 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3962 {
3963         int              rc;
3964         MDB_node        *leaf;
3965         MDB_val lkey;
3966
3967         lkey.mv_size = MAXKEYSIZE+1;
3968         lkey.mv_data = NULL;
3969
3970         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3971                 rc = mdb_page_search(mc, &lkey, 0);
3972                 if (rc != MDB_SUCCESS)
3973                         return rc;
3974         }
3975         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3976
3977         leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3978         mc->mc_flags |= C_INITIALIZED;
3979         mc->mc_flags &= ~C_EOF;
3980
3981         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3982
3983         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3984                 key->mv_size = mc->mc_db->md_pad;
3985                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3986                 return MDB_SUCCESS;
3987         }
3988
3989         if (data) {
3990                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3991                         mdb_xcursor_init1(mc, leaf);
3992                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3993                         if (rc)
3994                                 return rc;
3995                 } else {
3996                         if (mc->mc_xcursor)
3997                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3998                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3999                                 return rc;
4000                 }
4001         }
4002
4003         MDB_SET_KEY(leaf, key);
4004         return MDB_SUCCESS;
4005 }
4006
4007 int
4008 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4009     MDB_cursor_op op)
4010 {
4011         int              rc;
4012         int              exact = 0;
4013
4014         assert(mc);
4015
4016         switch (op) {
4017         case MDB_GET_BOTH:
4018         case MDB_GET_BOTH_RANGE:
4019                 if (data == NULL || mc->mc_xcursor == NULL) {
4020                         rc = EINVAL;
4021                         break;
4022                 }
4023                 /* FALLTHRU */
4024         case MDB_SET:
4025         case MDB_SET_RANGE:
4026                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4027                         rc = EINVAL;
4028                 } else if (op == MDB_SET_RANGE)
4029                         rc = mdb_cursor_set(mc, key, data, op, NULL);
4030                 else
4031                         rc = mdb_cursor_set(mc, key, data, op, &exact);
4032                 break;
4033         case MDB_GET_MULTIPLE:
4034                 if (data == NULL ||
4035                         !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4036                         !(mc->mc_flags & C_INITIALIZED)) {
4037                         rc = EINVAL;
4038                         break;
4039                 }
4040                 rc = MDB_SUCCESS;
4041                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4042                         (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4043                         break;
4044                 goto fetchm;
4045         case MDB_NEXT_MULTIPLE:
4046                 if (data == NULL ||
4047                         !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4048                         rc = EINVAL;
4049                         break;
4050                 }
4051                 if (!(mc->mc_flags & C_INITIALIZED))
4052                         rc = mdb_cursor_first(mc, key, data);
4053                 else
4054                         rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4055                 if (rc == MDB_SUCCESS) {
4056                         if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4057                                 MDB_cursor *mx;
4058 fetchm:
4059                                 mx = &mc->mc_xcursor->mx_cursor;
4060                                 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4061                                         mx->mc_db->md_pad;
4062                                 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4063                                 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4064                         } else {
4065                                 rc = MDB_NOTFOUND;
4066                         }
4067                 }
4068                 break;
4069         case MDB_NEXT:
4070         case MDB_NEXT_DUP:
4071         case MDB_NEXT_NODUP:
4072                 if (!(mc->mc_flags & C_INITIALIZED))
4073                         rc = mdb_cursor_first(mc, key, data);
4074                 else
4075                         rc = mdb_cursor_next(mc, key, data, op);
4076                 break;
4077         case MDB_PREV:
4078         case MDB_PREV_DUP:
4079         case MDB_PREV_NODUP:
4080                 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
4081                         rc = mdb_cursor_last(mc, key, data);
4082                 else
4083                         rc = mdb_cursor_prev(mc, key, data, op);
4084                 break;
4085         case MDB_FIRST:
4086                 rc = mdb_cursor_first(mc, key, data);
4087                 break;
4088         case MDB_FIRST_DUP:
4089                 if (data == NULL ||
4090                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4091                         !(mc->mc_flags & C_INITIALIZED) ||
4092                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4093                         rc = EINVAL;
4094                         break;
4095                 }
4096                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4097                 break;
4098         case MDB_LAST:
4099                 rc = mdb_cursor_last(mc, key, data);
4100                 break;
4101         case MDB_LAST_DUP:
4102                 if (data == NULL ||
4103                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4104                         !(mc->mc_flags & C_INITIALIZED) ||
4105                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4106                         rc = EINVAL;
4107                         break;
4108                 }
4109                 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4110                 break;
4111         default:
4112                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4113                 rc = EINVAL;
4114                 break;
4115         }
4116
4117         return rc;
4118 }
4119
4120 /** Touch all the pages in the cursor stack.
4121  *      Makes sure all the pages are writable, before attempting a write operation.
4122  * @param[in] mc The cursor to operate on.
4123  */
4124 static int
4125 mdb_cursor_touch(MDB_cursor *mc)
4126 {
4127         int rc;
4128
4129         if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4130                 MDB_cursor mc2;
4131                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4132                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
4133                 if (rc)
4134                          return rc;
4135                 *mc->mc_dbflag = DB_DIRTY;
4136         }
4137         for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4138                 rc = mdb_page_touch(mc);
4139                 if (rc)
4140                         return rc;
4141         }
4142         mc->mc_top = mc->mc_snum-1;
4143         return MDB_SUCCESS;
4144 }
4145
4146 int
4147 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4148     unsigned int flags)
4149 {
4150         MDB_node        *leaf = NULL;
4151         MDB_val xdata, *rdata, dkey;
4152         MDB_page        *fp;
4153         MDB_db dummy;
4154         int do_sub = 0;
4155         unsigned int mcount = 0;
4156         size_t nsize;
4157         int rc, rc2;
4158         MDB_pagebuf pbuf;
4159         char dbuf[MAXKEYSIZE+1];
4160         unsigned int nflags;
4161         DKBUF;
4162
4163         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4164                 return EACCES;
4165
4166         DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4167                 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4168
4169         dkey.mv_size = 0;
4170
4171         if (flags == MDB_CURRENT) {
4172                 if (!(mc->mc_flags & C_INITIALIZED))
4173                         return EINVAL;
4174                 rc = MDB_SUCCESS;
4175         } else if (mc->mc_db->md_root == P_INVALID) {
4176                 MDB_page *np;
4177                 /* new database, write a root leaf page */
4178                 DPUTS("allocating new root leaf page");
4179                 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
4180                         return ENOMEM;
4181                 }
4182                 mc->mc_snum = 0;
4183                 mdb_cursor_push(mc, np);
4184                 mc->mc_db->md_root = np->mp_pgno;
4185                 mc->mc_db->md_depth++;
4186                 *mc->mc_dbflag = DB_DIRTY;
4187                 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4188                         == MDB_DUPFIXED)
4189                         np->mp_flags |= P_LEAF2;
4190                 mc->mc_flags |= C_INITIALIZED;
4191                 rc = MDB_NOTFOUND;
4192                 goto top;
4193         } else {
4194                 int exact = 0;
4195                 MDB_val d2;
4196                 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4197                 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4198                         DPRINTF("duplicate key [%s]", DKEY(key));
4199                         *data = d2;
4200                         return MDB_KEYEXIST;
4201                 }
4202                 if (rc && rc != MDB_NOTFOUND)
4203                         return rc;
4204         }
4205
4206         /* Cursor is positioned, now make sure all pages are writable */
4207         rc2 = mdb_cursor_touch(mc);
4208         if (rc2)
4209                 return rc2;
4210
4211 top:
4212         /* The key already exists */
4213         if (rc == MDB_SUCCESS) {
4214                 /* there's only a key anyway, so this is a no-op */
4215                 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4216                         unsigned int ksize = mc->mc_db->md_pad;
4217                         if (key->mv_size != ksize)
4218                                 return EINVAL;
4219                         if (flags == MDB_CURRENT) {
4220                                 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4221                                 memcpy(ptr, key->mv_data, ksize);
4222                         }
4223                         return MDB_SUCCESS;
4224                 }
4225
4226                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4227
4228                 /* DB has dups? */
4229                 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4230                         /* Was a single item before, must convert now */
4231 more:
4232                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4233                                 /* Just overwrite the current item */
4234                                 if (flags == MDB_CURRENT)
4235                                         goto current;
4236
4237                                 dkey.mv_size = NODEDSZ(leaf);
4238                                 dkey.mv_data = NODEDATA(leaf);
4239 #if UINT_MAX < SIZE_MAX
4240                                 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4241 #ifdef MISALIGNED_OK
4242                                         mc->mc_dbx->md_dcmp = mdb_cmp_long;
4243 #else
4244                                         mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4245 #endif
4246 #endif
4247                                 /* if data matches, ignore it */
4248                                 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4249                                         return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4250
4251                                 /* create a fake page for the dup items */
4252                                 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4253                                 dkey.mv_data = dbuf;
4254                                 fp = (MDB_page *)&pbuf;
4255                                 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4256                                 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4257                                 fp->mp_lower = PAGEHDRSZ;
4258                                 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4259                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4260                                         fp->mp_flags |= P_LEAF2;
4261                                         fp->mp_pad = data->mv_size;
4262                                 } else {
4263                                         fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4264                                                 (dkey.mv_size & 1) + (data->mv_size & 1);
4265                                 }
4266                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4267                                 do_sub = 1;
4268                                 rdata = &xdata;
4269                                 xdata.mv_size = fp->mp_upper;
4270                                 xdata.mv_data = fp;
4271                                 flags |= F_DUPDATA;
4272                                 goto new_sub;
4273                         }
4274                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4275                                 /* See if we need to convert from fake page to subDB */
4276                                 MDB_page *mp;
4277                                 unsigned int offset;
4278                                 unsigned int i;
4279
4280                                 fp = NODEDATA(leaf);
4281                                 if (flags == MDB_CURRENT) {
4282                                         fp->mp_flags |= P_DIRTY;
4283                                         COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4284                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4285                                         flags |= F_DUPDATA;
4286                                         goto put_sub;
4287                                 }
4288                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4289                                         offset = fp->mp_pad;
4290                                 } else {
4291                                         offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4292                                 }
4293                                 offset += offset & 1;
4294                                 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4295                                         offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4296                                                 MDB_MINKEYS) {
4297                                         /* yes, convert it */
4298                                         dummy.md_flags = 0;
4299                                         if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4300                                                 dummy.md_pad = fp->mp_pad;
4301                                                 dummy.md_flags = MDB_DUPFIXED;
4302                                                 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4303                                                         dummy.md_flags |= MDB_INTEGERKEY;
4304                                         }
4305                                         dummy.md_depth = 1;
4306                                         dummy.md_branch_pages = 0;
4307                                         dummy.md_leaf_pages = 1;
4308                                         dummy.md_overflow_pages = 0;
4309                                         dummy.md_entries = NUMKEYS(fp);
4310                                         rdata = &xdata;
4311                                         xdata.mv_size = sizeof(MDB_db);
4312                                         xdata.mv_data = &dummy;
4313                                         mp = mdb_page_alloc(mc, 1);
4314                                         if (!mp)
4315                                                 return ENOMEM;
4316                                         offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4317                                         flags |= F_DUPDATA|F_SUBDATA;
4318                                         dummy.md_root = mp->mp_pgno;
4319                                 } else {
4320                                         /* no, just grow it */
4321                                         rdata = &xdata;
4322                                         xdata.mv_size = NODEDSZ(leaf) + offset;
4323                                         xdata.mv_data = &pbuf;
4324                                         mp = (MDB_page *)&pbuf;
4325                                         mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4326                                         flags |= F_DUPDATA;
4327                                 }
4328                                 mp->mp_flags = fp->mp_flags | P_DIRTY;
4329                                 mp->mp_pad   = fp->mp_pad;
4330                                 mp->mp_lower = fp->mp_lower;
4331                                 mp->mp_upper = fp->mp_upper + offset;
4332                                 if (IS_LEAF2(fp)) {
4333                                         memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4334                                 } else {
4335                                         nsize = NODEDSZ(leaf) - fp->mp_upper;
4336                                         memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4337                                         for (i=0; i<NUMKEYS(fp); i++)
4338                                                 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4339                                 }
4340                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4341                                 do_sub = 1;
4342                                 goto new_sub;
4343                         }
4344                         /* data is on sub-DB, just store it */
4345                         flags |= F_DUPDATA|F_SUBDATA;
4346                         goto put_sub;
4347                 }
4348 current:
4349                 /* overflow page overwrites need special handling */
4350                 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4351                         MDB_page *omp;
4352                         pgno_t pg;
4353                         int ovpages, dpages;
4354
4355                         ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4356                         dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4357                         memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4358                         mdb_page_get(mc->mc_txn, pg, &omp);
4359                         /* Is the ov page writable and large enough? */
4360                         if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
4361                                 /* yes, overwrite it. Note in this case we don't
4362                                  * bother to try shrinking the node if the new data
4363                                  * is smaller than the overflow threshold.
4364                                  */
4365                                 if (F_ISSET(flags, MDB_RESERVE))
4366                                         data->mv_data = METADATA(omp);
4367                                 else
4368                                         memcpy(METADATA(omp), data->mv_data, data->mv_size);
4369                                 goto done;
4370                         } else {
4371                                 /* no, free ovpages */
4372                                 int i;
4373                                 mc->mc_db->md_overflow_pages -= ovpages;
4374                                 for (i=0; i<ovpages; i++) {
4375                                         DPRINTF("freed ov page %zu", pg);
4376                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
4377                                         pg++;
4378                                 }
4379                         }
4380                 } else if (NODEDSZ(leaf) == data->mv_size) {
4381                         /* same size, just replace it. Note that we could
4382                          * also reuse this node if the new data is smaller,
4383                          * but instead we opt to shrink the node in that case.
4384                          */
4385                         if (F_ISSET(flags, MDB_RESERVE))
4386                                 data->mv_data = NODEDATA(leaf);
4387                         else
4388                                 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4389                         goto done;
4390                 }
4391                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4392                 mc->mc_db->md_entries--;
4393         } else {
4394                 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4395         }
4396
4397         rdata = data;
4398
4399 new_sub:
4400         nflags = flags & NODE_ADD_FLAGS;
4401         nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4402         if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4403                 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4404                         nflags &= ~MDB_APPEND;
4405                 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4406         } else {
4407                 /* There is room already in this leaf page. */
4408                 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4409                 if (rc == 0 && !do_sub) {
4410                         /* Adjust other cursors pointing to mp */
4411                         MDB_cursor *m2, *m3;
4412                         MDB_dbi dbi = mc->mc_dbi;
4413                         unsigned i = mc->mc_top;
4414                         MDB_page *mp = mc->mc_pg[i];
4415
4416                         if (mc->mc_flags & C_SUB)
4417                                 dbi--;
4418
4419                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4420                                 if (mc->mc_flags & C_SUB)
4421                                         m3 = &m2->mc_xcursor->mx_cursor;
4422                                 else
4423                                         m3 = m2;
4424                                 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4425                                 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4426                                         m3->mc_ki[i]++;
4427                                 }
4428                         }
4429                 }
4430         }
4431
4432         if (rc != MDB_SUCCESS)
4433                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4434         else {
4435                 /* Now store the actual data in the child DB. Note that we're
4436                  * storing the user data in the keys field, so there are strict
4437                  * size limits on dupdata. The actual data fields of the child
4438                  * DB are all zero size.
4439                  */
4440                 if (do_sub) {
4441                         int xflags;
4442 put_sub:
4443                         xdata.mv_size = 0;
4444                         xdata.mv_data = "";
4445                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4446                         if (flags & MDB_CURRENT) {
4447                                 xflags = MDB_CURRENT;
4448                         } else {
4449                                 mdb_xcursor_init1(mc, leaf);
4450                                 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4451                         }
4452                         /* converted, write the original data first */
4453                         if (dkey.mv_size) {
4454                                 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4455                                 if (rc)
4456                                         return rc;
4457                                 {
4458                                         /* Adjust other cursors pointing to mp */
4459                                         MDB_cursor *m2;
4460                                         unsigned i = mc->mc_top;
4461                                         MDB_page *mp = mc->mc_pg[i];
4462
4463                                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4464                                                 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4465                                                 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4466                                                         mdb_xcursor_init1(m2, leaf);
4467                                                 }
4468                                         }
4469                                 }
4470                         }
4471                         xflags |= (flags & MDB_APPEND);
4472                         rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4473                         if (flags & F_SUBDATA) {
4474                                 void *db = NODEDATA(leaf);
4475                                 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4476                         }
4477                 }
4478                 /* sub-writes might have failed so check rc again.
4479                  * Don't increment count if we just replaced an existing item.
4480                  */
4481                 if (!rc && !(flags & MDB_CURRENT))
4482                         mc->mc_db->md_entries++;
4483                 if (flags & MDB_MULTIPLE) {
4484                         mcount++;
4485                         if (mcount < data[1].mv_size) {
4486                                 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4487                                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4488                                 goto more;
4489                         }
4490                 }
4491         }
4492 done:
4493         return rc;
4494 }
4495
4496 int
4497 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4498 {
4499         MDB_node        *leaf;
4500         int rc;
4501
4502         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4503                 return EACCES;
4504
4505         if (!mc->mc_flags & C_INITIALIZED)
4506                 return EINVAL;
4507
4508         rc = mdb_cursor_touch(mc);
4509         if (rc)
4510                 return rc;
4511
4512         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4513
4514         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4515                 if (flags != MDB_NODUPDATA) {
4516                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4517                                 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4518                         }
4519                         rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4520                         /* If sub-DB still has entries, we're done */
4521                         if (mc->mc_xcursor->mx_db.md_entries) {
4522                                 if (leaf->mn_flags & F_SUBDATA) {
4523                                         /* update subDB info */
4524                                         void *db = NODEDATA(leaf);
4525                                         memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4526                                 } else {
4527                                         /* shrink fake page */
4528                                         mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4529                                 }
4530                                 mc->mc_db->md_entries--;
4531                                 return rc;
4532                         }
4533                         /* otherwise fall thru and delete the sub-DB */
4534                 }
4535
4536                 if (leaf->mn_flags & F_SUBDATA) {
4537                         /* add all the child DB's pages to the free list */
4538                         rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4539                         if (rc == MDB_SUCCESS) {
4540                                 mc->mc_db->md_entries -=
4541                                         mc->mc_xcursor->mx_db.md_entries;
4542                         }
4543                 }
4544         }
4545
4546         return mdb_cursor_del0(mc, leaf);
4547 }
4548
4549 /** Allocate and initialize new pages for a database.
4550  * @param[in] mc a cursor on the database being added to.
4551  * @param[in] flags flags defining what type of page is being allocated.
4552  * @param[in] num the number of pages to allocate. This is usually 1,
4553  * unless allocating overflow pages for a large record.
4554  * @return Address of a page, or NULL on failure.
4555  */
4556 static MDB_page *
4557 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4558 {
4559         MDB_page        *np;
4560
4561         if ((np = mdb_page_alloc(mc, num)) == NULL)
4562                 return NULL;
4563         DPRINTF("allocated new mpage %zu, page size %u",
4564             np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4565         np->mp_flags = flags | P_DIRTY;
4566         np->mp_lower = PAGEHDRSZ;
4567         np->mp_upper = mc->mc_txn->mt_env->me_psize;
4568
4569         if (IS_BRANCH(np))
4570                 mc->mc_db->md_branch_pages++;
4571         else if (IS_LEAF(np))
4572                 mc->mc_db->md_leaf_pages++;
4573         else if (IS_OVERFLOW(np)) {
4574                 mc->mc_db->md_overflow_pages += num;
4575                 np->mp_pages = num;
4576         }
4577
4578         return np;
4579 }
4580
4581 /** Calculate the size of a leaf node.
4582  * The size depends on the environment's page size; if a data item
4583  * is too large it will be put onto an overflow page and the node
4584  * size will only include the key and not the data. Sizes are always
4585  * rounded up to an even number of bytes, to guarantee 2-byte alignment
4586  * of the #MDB_node headers.
4587  * @param[in] env The environment handle.
4588  * @param[in] key The key for the node.
4589  * @param[in] data The data for the node.
4590  * @return The number of bytes needed to store the node.
4591  */
4592 static size_t
4593 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4594 {
4595         size_t           sz;
4596
4597         sz = LEAFSIZE(key, data);
4598         if (sz >= env->me_psize / MDB_MINKEYS) {
4599                 /* put on overflow page */
4600                 sz -= data->mv_size - sizeof(pgno_t);
4601         }
4602         sz += sz & 1;
4603
4604         return sz + sizeof(indx_t);
4605 }
4606
4607 /** Calculate the size of a branch node.
4608  * The size should depend on the environment's page size but since
4609  * we currently don't support spilling large keys onto overflow
4610  * pages, it's simply the size of the #MDB_node header plus the
4611  * size of the key. Sizes are always rounded up to an even number
4612  * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4613  * @param[in] env The environment handle.
4614  * @param[in] key The key for the node.
4615  * @return The number of bytes needed to store the node.
4616  */
4617 static size_t
4618 mdb_branch_size(MDB_env *env, MDB_val *key)
4619 {
4620         size_t           sz;
4621
4622         sz = INDXSIZE(key);
4623         if (sz >= env->me_psize / MDB_MINKEYS) {
4624                 /* put on overflow page */
4625                 /* not implemented */
4626                 /* sz -= key->size - sizeof(pgno_t); */
4627         }
4628
4629         return sz + sizeof(indx_t);
4630 }
4631
4632 /** Add a node to the page pointed to by the cursor.
4633  * @param[in] mc The cursor for this operation.
4634  * @param[in] indx The index on the page where the new node should be added.
4635  * @param[in] key The key for the new node.
4636  * @param[in] data The data for the new node, if any.
4637  * @param[in] pgno The page number, if adding a branch node.
4638  * @param[in] flags Flags for the node.
4639  * @return 0 on success, non-zero on failure. Possible errors are:
4640  * <ul>
4641  *      <li>ENOMEM - failed to allocate overflow pages for the node.
4642  *      <li>ENOSPC - there is insufficient room in the page. This error
4643  *      should never happen since all callers already calculate the
4644  *      page's free space before calling this function.
4645  * </ul>
4646  */
4647 static int
4648 mdb_node_add(MDB_cursor *mc, indx_t indx,
4649     MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4650 {
4651         unsigned int     i;
4652         size_t           node_size = NODESIZE;
4653         indx_t           ofs;
4654         MDB_node        *node;
4655         MDB_page        *mp = mc->mc_pg[mc->mc_top];
4656         MDB_page        *ofp = NULL;            /* overflow page */
4657         DKBUF;
4658
4659         assert(mp->mp_upper >= mp->mp_lower);
4660
4661         DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4662             IS_LEAF(mp) ? "leaf" : "branch",
4663                 IS_SUBP(mp) ? "sub-" : "",
4664             mp->mp_pgno, indx, data ? data->mv_size : 0,
4665                 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4666
4667         if (IS_LEAF2(mp)) {
4668                 /* Move higher keys up one slot. */
4669                 int ksize = mc->mc_db->md_pad, dif;
4670                 char *ptr = LEAF2KEY(mp, indx, ksize);
4671                 dif = NUMKEYS(mp) - indx;
4672                 if (dif > 0)
4673                         memmove(ptr+ksize, ptr, dif*ksize);
4674                 /* insert new key */
4675                 memcpy(ptr, key->mv_data, ksize);
4676
4677                 /* Just using these for counting */
4678                 mp->mp_lower += sizeof(indx_t);
4679                 mp->mp_upper -= ksize - sizeof(indx_t);
4680                 return MDB_SUCCESS;
4681         }
4682
4683         if (key != NULL)
4684                 node_size += key->mv_size;
4685
4686         if (IS_LEAF(mp)) {
4687                 assert(data);
4688                 if (F_ISSET(flags, F_BIGDATA)) {
4689                         /* Data already on overflow page. */
4690                         node_size += sizeof(pgno_t);
4691                 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4692                         int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4693                         /* Put data on overflow page. */
4694                         DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4695                             data->mv_size, node_size+data->mv_size);
4696                         node_size += sizeof(pgno_t);
4697                         if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4698                                 return ENOMEM;
4699                         DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4700                         flags |= F_BIGDATA;
4701                 } else {
4702                         node_size += data->mv_size;
4703                 }
4704         }
4705         node_size += node_size & 1;
4706
4707         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4708                 DPRINTF("not enough room in page %zu, got %u ptrs",
4709                     mp->mp_pgno, NUMKEYS(mp));
4710                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4711                     mp->mp_upper - mp->mp_lower);
4712                 DPRINTF("node size = %zu", node_size);
4713                 return ENOSPC;
4714         }
4715
4716         /* Move higher pointers up one slot. */
4717         for (i = NUMKEYS(mp); i > indx; i--)
4718                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4719
4720         /* Adjust free space offsets. */
4721         ofs = mp->mp_upper - node_size;
4722         assert(ofs >= mp->mp_lower + sizeof(indx_t));
4723         mp->mp_ptrs[indx] = ofs;
4724         mp->mp_upper = ofs;
4725         mp->mp_lower += sizeof(indx_t);
4726
4727         /* Write the node data. */
4728         node = NODEPTR(mp, indx);
4729         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4730         node->mn_flags = flags;
4731         if (IS_LEAF(mp))
4732                 SETDSZ(node,data->mv_size);
4733         else
4734                 SETPGNO(node,pgno);
4735
4736         if (key)
4737                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4738
4739         if (IS_LEAF(mp)) {
4740                 assert(key);
4741                 if (ofp == NULL) {
4742                         if (F_ISSET(flags, F_BIGDATA))
4743                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4744                                     sizeof(pgno_t));
4745                         else if (F_ISSET(flags, MDB_RESERVE))
4746                                 data->mv_data = node->mn_data + key->mv_size;
4747                         else
4748                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4749                                     data->mv_size);
4750                 } else {
4751                         memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4752                             sizeof(pgno_t));
4753                         if (F_ISSET(flags, MDB_RESERVE))
4754                                 data->mv_data = METADATA(ofp);
4755                         else
4756                                 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4757                 }
4758         }
4759
4760         return MDB_SUCCESS;
4761 }
4762
4763 /** Delete the specified node from a page.
4764  * @param[in] mp The page to operate on.
4765  * @param[in] indx The index of the node to delete.
4766  * @param[in] ksize The size of a node. Only used if the page is
4767  * part of a #MDB_DUPFIXED database.
4768  */
4769 static void
4770 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4771 {
4772         unsigned int     sz;
4773         indx_t           i, j, numkeys, ptr;
4774         MDB_node        *node;
4775         char            *base;
4776
4777 #if MDB_DEBUG
4778         {
4779         pgno_t pgno;
4780         COPY_PGNO(pgno, mp->mp_pgno);
4781         DPRINTF("delete node %u on %s page %zu", indx,
4782             IS_LEAF(mp) ? "leaf" : "branch", pgno);
4783         }
4784 #endif
4785         assert(indx < NUMKEYS(mp));
4786
4787         if (IS_LEAF2(mp)) {
4788                 int x = NUMKEYS(mp) - 1 - indx;
4789                 base = LEAF2KEY(mp, indx, ksize);
4790                 if (x)
4791                         memmove(base, base + ksize, x * ksize);
4792                 mp->mp_lower -= sizeof(indx_t);
4793                 mp->mp_upper += ksize - sizeof(indx_t);
4794                 return;
4795         }
4796
4797         node = NODEPTR(mp, indx);
4798         sz = NODESIZE + node->mn_ksize;
4799         if (IS_LEAF(mp)) {
4800                 if (F_ISSET(node->mn_flags, F_BIGDATA))
4801                         sz += sizeof(pgno_t);
4802                 else
4803                         sz += NODEDSZ(node);
4804         }
4805         sz += sz & 1;
4806
4807         ptr = mp->mp_ptrs[indx];
4808         numkeys = NUMKEYS(mp);
4809         for (i = j = 0; i < numkeys; i++) {
4810                 if (i != indx) {
4811                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
4812                         if (mp->mp_ptrs[i] < ptr)
4813                                 mp->mp_ptrs[j] += sz;
4814                         j++;
4815                 }
4816         }
4817
4818         base = (char *)mp + mp->mp_upper;
4819         memmove(base + sz, base, ptr - mp->mp_upper);
4820
4821         mp->mp_lower -= sizeof(indx_t);
4822         mp->mp_upper += sz;
4823 }
4824
4825 /** Compact the main page after deleting a node on a subpage.
4826  * @param[in] mp The main page to operate on.
4827  * @param[in] indx The index of the subpage on the main page.
4828  */
4829 static void
4830 mdb_node_shrink(MDB_page *mp, indx_t indx)
4831 {
4832         MDB_node *node;
4833         MDB_page *sp, *xp;
4834         char *base;
4835         int osize, nsize;
4836         int delta;
4837         indx_t           i, numkeys, ptr;
4838
4839         node = NODEPTR(mp, indx);
4840         sp = (MDB_page *)NODEDATA(node);
4841         osize = NODEDSZ(node);
4842
4843         delta = sp->mp_upper - sp->mp_lower;
4844         SETDSZ(node, osize - delta);
4845         xp = (MDB_page *)((char *)sp + delta);
4846
4847         /* shift subpage upward */
4848         if (IS_LEAF2(sp)) {
4849                 nsize = NUMKEYS(sp) * sp->mp_pad;
4850                 memmove(METADATA(xp), METADATA(sp), nsize);
4851         } else {
4852                 int i;
4853                 nsize = osize - sp->mp_upper;
4854                 numkeys = NUMKEYS(sp);
4855                 for (i=numkeys-1; i>=0; i--)
4856                         xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4857         }
4858         xp->mp_upper = sp->mp_lower;
4859         xp->mp_lower = sp->mp_lower;
4860         xp->mp_flags = sp->mp_flags;
4861         xp->mp_pad = sp->mp_pad;
4862         COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4863
4864         /* shift lower nodes upward */
4865         ptr = mp->mp_ptrs[indx];
4866         numkeys = NUMKEYS(mp);
4867         for (i = 0; i < numkeys; i++) {
4868                 if (mp->mp_ptrs[i] <= ptr)
4869                         mp->mp_ptrs[i] += delta;
4870         }
4871
4872         base = (char *)mp + mp->mp_upper;
4873         memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4874         mp->mp_upper += delta;
4875 }
4876
4877 /** Initial setup of a sorted-dups cursor.
4878  * Sorted duplicates are implemented as a sub-database for the given key.
4879  * The duplicate data items are actually keys of the sub-database.
4880  * Operations on the duplicate data items are performed using a sub-cursor
4881  * initialized when the sub-database is first accessed. This function does
4882  * the preliminary setup of the sub-cursor, filling in the fields that
4883  * depend only on the parent DB.
4884  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4885  */
4886 static void
4887 mdb_xcursor_init0(MDB_cursor *mc)
4888 {
4889         MDB_xcursor *mx = mc->mc_xcursor;
4890
4891         mx->mx_cursor.mc_xcursor = NULL;
4892         mx->mx_cursor.mc_txn = mc->mc_txn;
4893         mx->mx_cursor.mc_db = &mx->mx_db;
4894         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4895         mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4896         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4897         mx->mx_cursor.mc_snum = 0;
4898         mx->mx_cursor.mc_top = 0;
4899         mx->mx_cursor.mc_flags = C_SUB;
4900         mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4901         mx->mx_dbx.md_dcmp = NULL;
4902         mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4903 }
4904
4905 /** Final setup of a sorted-dups cursor.
4906  *      Sets up the fields that depend on the data from the main cursor.
4907  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4908  * @param[in] node The data containing the #MDB_db record for the
4909  * sorted-dup database.
4910  */
4911 static void
4912 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4913 {
4914         MDB_xcursor *mx = mc->mc_xcursor;
4915
4916         if (node->mn_flags & F_SUBDATA) {
4917                 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
4918                 mx->mx_cursor.mc_snum = 0;
4919                 mx->mx_cursor.mc_flags = C_SUB;
4920         } else {
4921                 MDB_page *fp = NODEDATA(node);
4922                 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4923                 mx->mx_db.md_flags = 0;
4924                 mx->mx_db.md_depth = 1;
4925                 mx->mx_db.md_branch_pages = 0;
4926                 mx->mx_db.md_leaf_pages = 1;
4927                 mx->mx_db.md_overflow_pages = 0;
4928                 mx->mx_db.md_entries = NUMKEYS(fp);
4929                 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4930                 mx->mx_cursor.mc_snum = 1;
4931                 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4932                 mx->mx_cursor.mc_top = 0;
4933                 mx->mx_cursor.mc_pg[0] = fp;
4934                 mx->mx_cursor.mc_ki[0] = 0;
4935                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4936                         mx->mx_db.md_flags = MDB_DUPFIXED;
4937                         mx->mx_db.md_pad = fp->mp_pad;
4938                         if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4939                                 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4940                 }
4941         }
4942         DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4943                 mx->mx_db.md_root);
4944         mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4945                 DB_DIRTY : 0;
4946         mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4947         mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4948 #if UINT_MAX < SIZE_MAX
4949         if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4950 #ifdef MISALIGNED_OK
4951                 mx->mx_dbx.md_cmp = mdb_cmp_long;
4952 #else
4953                 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4954 #endif
4955 #endif
4956 }
4957
4958 /** Initialize a cursor for a given transaction and database. */
4959 static void
4960 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4961 {
4962         mc->mc_orig = NULL;
4963         mc->mc_dbi = dbi;
4964         mc->mc_txn = txn;
4965         mc->mc_db = &txn->mt_dbs[dbi];
4966         mc->mc_dbx = &txn->mt_dbxs[dbi];
4967         mc->mc_dbflag = &txn->mt_dbflags[dbi];
4968         mc->mc_snum = 0;
4969         mc->mc_top = 0;
4970         mc->mc_flags = 0;
4971         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4972                 assert(mx != NULL);
4973                 mc->mc_xcursor = mx;
4974                 mdb_xcursor_init0(mc);
4975         } else {
4976                 mc->mc_xcursor = NULL;
4977         }
4978 }
4979
4980 int
4981 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4982 {
4983         MDB_cursor      *mc;
4984         MDB_xcursor     *mx = NULL;
4985         size_t size = sizeof(MDB_cursor);
4986
4987         if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
4988                 return EINVAL;
4989
4990         /* Allow read access to the freelist */
4991         if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
4992                 return EINVAL;
4993
4994         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4995                 size += sizeof(MDB_xcursor);
4996
4997         if ((mc = malloc(size)) != NULL) {
4998                 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4999                         mx = (MDB_xcursor *)(mc + 1);
5000                 }
5001                 mdb_cursor_init(mc, txn, dbi, mx);
5002                 if (txn->mt_cursors) {
5003                         mc->mc_next = txn->mt_cursors[dbi];
5004                         txn->mt_cursors[dbi] = mc;
5005                 }
5006                 mc->mc_flags |= C_ALLOCD;
5007         } else {
5008                 return ENOMEM;
5009         }
5010
5011         *ret = mc;
5012
5013         return MDB_SUCCESS;
5014 }
5015
5016 /* Return the count of duplicate data items for the current key */
5017 int
5018 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5019 {
5020         MDB_node        *leaf;
5021
5022         if (mc == NULL || countp == NULL)
5023                 return EINVAL;
5024
5025         if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5026                 return EINVAL;
5027
5028         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5029         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5030                 *countp = 1;
5031         } else {
5032                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5033                         return EINVAL;
5034
5035                 *countp = mc->mc_xcursor->mx_db.md_entries;
5036         }
5037         return MDB_SUCCESS;
5038 }
5039
5040 void
5041 mdb_cursor_close(MDB_cursor *mc)
5042 {
5043         if (mc != NULL) {
5044                 /* remove from txn, if tracked */
5045                 if (mc->mc_txn->mt_cursors) {
5046                         MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5047                         while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5048                         if (*prev == mc)
5049                                 *prev = mc->mc_next;
5050                 }
5051                 if (mc->mc_flags & C_ALLOCD)
5052                         free(mc);
5053         }
5054 }
5055
5056 MDB_txn *
5057 mdb_cursor_txn(MDB_cursor *mc)
5058 {
5059         if (!mc) return NULL;
5060         return mc->mc_txn;
5061 }
5062
5063 MDB_dbi
5064 mdb_cursor_dbi(MDB_cursor *mc)
5065 {
5066         if (!mc) return 0;
5067         return mc->mc_dbi;
5068 }
5069
5070 /** Replace the key for a node with a new key.
5071  * @param[in] mp The page containing the node to operate on.
5072  * @param[in] indx The index of the node to operate on.
5073  * @param[in] key The new key to use.
5074  * @return 0 on success, non-zero on failure.
5075  */
5076 static int
5077 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
5078 {
5079         MDB_node                *node;
5080         char                    *base;
5081         size_t                   len;
5082         int                      delta, delta0;
5083         indx_t                   ptr, i, numkeys;
5084         DKBUF;
5085
5086         node = NODEPTR(mp, indx);
5087         ptr = mp->mp_ptrs[indx];
5088 #if MDB_DEBUG
5089         {
5090                 MDB_val k2;
5091                 char kbuf2[(MAXKEYSIZE*2+1)];
5092                 k2.mv_data = NODEKEY(node);
5093                 k2.mv_size = node->mn_ksize;
5094                 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5095                         indx, ptr,
5096                         mdb_dkey(&k2, kbuf2),
5097                         DKEY(key),
5098                         mp->mp_pgno);
5099         }
5100 #endif
5101
5102         delta0 = delta = key->mv_size - node->mn_ksize;
5103
5104         /* Must be 2-byte aligned. If new key is
5105          * shorter by 1, the shift will be skipped.
5106          */
5107         delta += (delta & 1);
5108         if (delta) {
5109                 if (delta > 0 && SIZELEFT(mp) < delta) {
5110                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
5111                         return ENOSPC;
5112                 }
5113
5114                 numkeys = NUMKEYS(mp);
5115                 for (i = 0; i < numkeys; i++) {
5116                         if (mp->mp_ptrs[i] <= ptr)
5117                                 mp->mp_ptrs[i] -= delta;
5118                 }
5119
5120                 base = (char *)mp + mp->mp_upper;
5121                 len = ptr - mp->mp_upper + NODESIZE;
5122                 memmove(base - delta, base, len);
5123                 mp->mp_upper -= delta;
5124
5125                 node = NODEPTR(mp, indx);
5126         }
5127
5128         /* But even if no shift was needed, update ksize */
5129         if (delta0)
5130                 node->mn_ksize = key->mv_size;
5131
5132         if (key->mv_size)
5133                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5134
5135         return MDB_SUCCESS;
5136 }
5137
5138 /** Move a node from csrc to cdst.
5139  */
5140 static int
5141 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5142 {
5143         int                      rc;
5144         MDB_node                *srcnode;
5145         MDB_val          key, data;
5146         pgno_t  srcpg;
5147         unsigned short flags;
5148
5149         DKBUF;
5150
5151         /* Mark src and dst as dirty. */
5152         if ((rc = mdb_page_touch(csrc)) ||
5153             (rc = mdb_page_touch(cdst)))
5154                 return rc;
5155
5156         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5157                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);        /* fake */
5158                 key.mv_size = csrc->mc_db->md_pad;
5159                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5160                 data.mv_size = 0;
5161                 data.mv_data = NULL;
5162                 srcpg = 0;
5163                 flags = 0;
5164         } else {
5165                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5166                 assert(!((long)srcnode&1));
5167                 srcpg = NODEPGNO(srcnode);
5168                 flags = srcnode->mn_flags;
5169                 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5170                         unsigned int snum = csrc->mc_snum;
5171                         MDB_node *s2;
5172                         /* must find the lowest key below src */
5173                         mdb_page_search_root(csrc, NULL, 0);
5174                         s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5175                         key.mv_size = NODEKSZ(s2);
5176                         key.mv_data = NODEKEY(s2);
5177                         csrc->mc_snum = snum--;
5178                         csrc->mc_top = snum;
5179                 } else {
5180                         key.mv_size = NODEKSZ(srcnode);
5181                         key.mv_data = NODEKEY(srcnode);
5182                 }
5183                 data.mv_size = NODEDSZ(srcnode);
5184                 data.mv_data = NODEDATA(srcnode);
5185         }
5186         if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5187                 unsigned int snum = cdst->mc_snum;
5188                 MDB_node *s2;
5189                 MDB_val bkey;
5190                 /* must find the lowest key below dst */
5191                 mdb_page_search_root(cdst, NULL, 0);
5192                 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5193                 bkey.mv_size = NODEKSZ(s2);
5194                 bkey.mv_data = NODEKEY(s2);
5195                 cdst->mc_snum = snum--;
5196                 cdst->mc_top = snum;
5197                 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5198         }
5199
5200         DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5201             IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5202             csrc->mc_ki[csrc->mc_top],
5203                 DKEY(&key),
5204             csrc->mc_pg[csrc->mc_top]->mp_pgno,
5205             cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5206
5207         /* Add the node to the destination page.
5208          */
5209         rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5210         if (rc != MDB_SUCCESS)
5211                 return rc;
5212
5213         /* Delete the node from the source page.
5214          */
5215         mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5216
5217         {
5218                 /* Adjust other cursors pointing to mp */
5219                 MDB_cursor *m2, *m3;
5220                 MDB_dbi dbi = csrc->mc_dbi;
5221                 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5222
5223                 if (csrc->mc_flags & C_SUB)
5224                         dbi--;
5225
5226                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5227                         if (m2 == csrc) continue;
5228                         if (csrc->mc_flags & C_SUB)
5229                                 m3 = &m2->mc_xcursor->mx_cursor;
5230                         else
5231                                 m3 = m2;
5232                         if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5233                                 csrc->mc_ki[csrc->mc_top]) {
5234                                 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5235                                 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5236                         }
5237                 }
5238         }
5239
5240         /* Update the parent separators.
5241          */
5242         if (csrc->mc_ki[csrc->mc_top] == 0) {
5243                 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5244                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5245                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5246                         } else {
5247                                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5248                                 key.mv_size = NODEKSZ(srcnode);
5249                                 key.mv_data = NODEKEY(srcnode);
5250                         }
5251                         DPRINTF("update separator for source page %zu to [%s]",
5252                                 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5253                         if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5254                                 &key)) != MDB_SUCCESS)
5255                                 return rc;
5256                 }
5257                 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5258                         MDB_val  nullkey;
5259                         nullkey.mv_size = 0;
5260                         rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5261                         assert(rc == MDB_SUCCESS);
5262                 }
5263         }
5264
5265         if (cdst->mc_ki[cdst->mc_top] == 0) {
5266                 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5267                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5268                                 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5269                         } else {
5270                                 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5271                                 key.mv_size = NODEKSZ(srcnode);
5272                                 key.mv_data = NODEKEY(srcnode);
5273                         }
5274                         DPRINTF("update separator for destination page %zu to [%s]",
5275                                 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5276                         if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5277                                 &key)) != MDB_SUCCESS)
5278                                 return rc;
5279                 }
5280                 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5281                         MDB_val  nullkey;
5282                         nullkey.mv_size = 0;
5283                         rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5284                         assert(rc == MDB_SUCCESS);
5285                 }
5286         }
5287
5288         return MDB_SUCCESS;
5289 }
5290
5291 /** Merge one page into another.
5292  *  The nodes from the page pointed to by \b csrc will
5293  *      be copied to the page pointed to by \b cdst and then
5294  *      the \b csrc page will be freed.
5295  * @param[in] csrc Cursor pointing to the source page.
5296  * @param[in] cdst Cursor pointing to the destination page.
5297  */
5298 static int
5299 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5300 {
5301         int                      rc;
5302         indx_t                   i, j;
5303         MDB_node                *srcnode;
5304         MDB_val          key, data;
5305         unsigned        nkeys;
5306
5307         DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5308                 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5309
5310         assert(csrc->mc_snum > 1);      /* can't merge root page */
5311         assert(cdst->mc_snum > 1);
5312
5313         /* Mark dst as dirty. */
5314         if ((rc = mdb_page_touch(cdst)))
5315                 return rc;
5316
5317         /* Move all nodes from src to dst.
5318          */
5319         j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5320         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5321                 key.mv_size = csrc->mc_db->md_pad;
5322                 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5323                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5324                         rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5325                         if (rc != MDB_SUCCESS)
5326                                 return rc;
5327                         key.mv_data = (char *)key.mv_data + key.mv_size;
5328                 }
5329         } else {
5330                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5331                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5332                         if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5333                                 unsigned int snum = csrc->mc_snum;
5334                                 MDB_node *s2;
5335                                 /* must find the lowest key below src */
5336                                 mdb_page_search_root(csrc, NULL, 0);
5337                                 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5338                                 key.mv_size = NODEKSZ(s2);
5339                                 key.mv_data = NODEKEY(s2);
5340                                 csrc->mc_snum = snum--;
5341                                 csrc->mc_top = snum;
5342                         } else {
5343                                 key.mv_size = srcnode->mn_ksize;
5344                                 key.mv_data = NODEKEY(srcnode);
5345                         }
5346
5347                         data.mv_size = NODEDSZ(srcnode);
5348                         data.mv_data = NODEDATA(srcnode);
5349                         rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5350                         if (rc != MDB_SUCCESS)
5351                                 return rc;
5352                 }
5353         }
5354
5355         DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5356             cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]), (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10);
5357
5358         /* Unlink the src page from parent and add to free list.
5359          */
5360         mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5361         if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5362                 key.mv_size = 0;
5363                 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5364                         return rc;
5365         }
5366
5367         mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5368         if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5369                 csrc->mc_db->md_leaf_pages--;
5370         else
5371                 csrc->mc_db->md_branch_pages--;
5372         {
5373                 /* Adjust other cursors pointing to mp */
5374                 MDB_cursor *m2, *m3;
5375                 MDB_dbi dbi = csrc->mc_dbi;
5376                 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5377
5378                 if (csrc->mc_flags & C_SUB)
5379                         dbi--;
5380
5381                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5382                         if (csrc->mc_flags & C_SUB)
5383                                 m3 = &m2->mc_xcursor->mx_cursor;
5384                         else
5385                                 m3 = m2;
5386                         if (m3 == csrc) continue;
5387                         if (m3->mc_snum < csrc->mc_snum) continue;
5388                         if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5389                                 m3->mc_pg[csrc->mc_top] = mp;
5390                                 m3->mc_ki[csrc->mc_top] += nkeys;
5391                         }
5392                 }
5393         }
5394         mdb_cursor_pop(csrc);
5395
5396         return mdb_rebalance(csrc);
5397 }
5398
5399 /** Copy the contents of a cursor.
5400  * @param[in] csrc The cursor to copy from.
5401  * @param[out] cdst The cursor to copy to.
5402  */
5403 static void
5404 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5405 {
5406         unsigned int i;
5407
5408         cdst->mc_txn = csrc->mc_txn;
5409         cdst->mc_dbi = csrc->mc_dbi;
5410         cdst->mc_db  = csrc->mc_db;
5411         cdst->mc_dbx = csrc->mc_dbx;
5412         cdst->mc_snum = csrc->mc_snum;
5413         cdst->mc_top = csrc->mc_top;
5414         cdst->mc_flags = csrc->mc_flags;
5415
5416         for (i=0; i<csrc->mc_snum; i++) {
5417                 cdst->mc_pg[i] = csrc->mc_pg[i];
5418                 cdst->mc_ki[i] = csrc->mc_ki[i];
5419         }
5420 }
5421
5422 /** Rebalance the tree after a delete operation.
5423  * @param[in] mc Cursor pointing to the page where rebalancing
5424  * should begin.
5425  * @return 0 on success, non-zero on failure.
5426  */
5427 static int
5428 mdb_rebalance(MDB_cursor *mc)
5429 {
5430         MDB_node        *node;
5431         int rc;
5432         unsigned int ptop;
5433         MDB_cursor      mn;
5434
5435 #if MDB_DEBUG
5436         {
5437         pgno_t pgno;
5438         COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5439         DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5440             IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5441             pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5442         }
5443 #endif
5444
5445         if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5446 #if MDB_DEBUG
5447                 pgno_t pgno;
5448                 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5449                 DPRINTF("no need to rebalance page %zu, above fill threshold",
5450                     pgno);
5451 #endif
5452                 return MDB_SUCCESS;
5453         }
5454
5455         if (mc->mc_snum < 2) {
5456                 MDB_page *mp = mc->mc_pg[0];
5457                 if (NUMKEYS(mp) == 0) {
5458                         DPUTS("tree is completely empty");
5459                         mc->mc_db->md_root = P_INVALID;
5460                         mc->mc_db->md_depth = 0;
5461                         mc->mc_db->md_leaf_pages = 0;
5462                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5463                         mc->mc_snum = 0;
5464                         mc->mc_top = 0;
5465                         {
5466                                 /* Adjust other cursors pointing to mp */
5467                                 MDB_cursor *m2, *m3;
5468                                 MDB_dbi dbi = mc->mc_dbi;
5469
5470                                 if (mc->mc_flags & C_SUB)
5471                                         dbi--;
5472
5473                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5474                                         if (m2 == mc) continue;
5475                                         if (mc->mc_flags & C_SUB)
5476                                                 m3 = &m2->mc_xcursor->mx_cursor;
5477                                         else
5478                                                 m3 = m2;
5479                                         if (m3->mc_snum < mc->mc_snum) continue;
5480                                         if (m3->mc_pg[0] == mp) {
5481                                                 m3->mc_snum = 0;
5482                                                 m3->mc_top = 0;
5483                                         }
5484                                 }
5485                         }
5486                 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5487                         DPUTS("collapsing root page!");
5488                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5489                         mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5490                         if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5491                                 &mc->mc_pg[0])))
5492                                 return rc;
5493                         mc->mc_db->md_depth--;
5494                         mc->mc_db->md_branch_pages--;
5495                         {
5496                                 /* Adjust other cursors pointing to mp */
5497                                 MDB_cursor *m2, *m3;
5498                                 MDB_dbi dbi = mc->mc_dbi;
5499
5500                                 if (mc->mc_flags & C_SUB)
5501                                         dbi--;
5502
5503                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5504                                         if (m2 == mc) continue;
5505                                         if (mc->mc_flags & C_SUB)
5506                                                 m3 = &m2->mc_xcursor->mx_cursor;
5507                                         else
5508                                                 m3 = m2;
5509                                         if (m3->mc_snum < mc->mc_snum) continue;
5510                                         if (m3->mc_pg[0] == mp) {
5511                                                 m3->mc_pg[0] = mc->mc_pg[0];
5512                                         }
5513                                 }
5514                         }
5515                 } else
5516                         DPUTS("root page doesn't need rebalancing");
5517                 return MDB_SUCCESS;
5518         }
5519
5520         /* The parent (branch page) must have at least 2 pointers,
5521          * otherwise the tree is invalid.
5522          */
5523         ptop = mc->mc_top-1;
5524         assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5525
5526         /* Leaf page fill factor is below the threshold.
5527          * Try to move keys from left or right neighbor, or
5528          * merge with a neighbor page.
5529          */
5530
5531         /* Find neighbors.
5532          */
5533         mdb_cursor_copy(mc, &mn);
5534         mn.mc_xcursor = NULL;
5535
5536         if (mc->mc_ki[ptop] == 0) {
5537                 /* We're the leftmost leaf in our parent.
5538                  */
5539                 DPUTS("reading right neighbor");
5540                 mn.mc_ki[ptop]++;
5541                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5542                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5543                         return rc;
5544                 mn.mc_ki[mn.mc_top] = 0;
5545                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5546         } else {
5547                 /* There is at least one neighbor to the left.
5548                  */
5549                 DPUTS("reading left neighbor");
5550                 mn.mc_ki[ptop]--;
5551                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5552                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5553                         return rc;
5554                 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5555                 mc->mc_ki[mc->mc_top] = 0;
5556         }
5557
5558         DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5559             mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10);
5560
5561         /* If the neighbor page is above threshold and has at least two
5562          * keys, move one key from it.
5563          *
5564          * Otherwise we should try to merge them.
5565          */
5566         if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5567                 return mdb_node_move(&mn, mc);
5568         else { /* FIXME: if (has_enough_room()) */
5569                 mc->mc_flags &= ~C_INITIALIZED;
5570                 if (mc->mc_ki[ptop] == 0)
5571                         return mdb_page_merge(&mn, mc);
5572                 else
5573                         return mdb_page_merge(mc, &mn);
5574         }
5575 }
5576
5577 /** Complete a delete operation started by #mdb_cursor_del(). */
5578 static int
5579 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5580 {
5581         int rc;
5582
5583         /* add overflow pages to free list */
5584         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5585                 int i, ovpages;
5586                 pgno_t pg;
5587
5588                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5589                 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5590                 mc->mc_db->md_overflow_pages -= ovpages;
5591                 for (i=0; i<ovpages; i++) {
5592                         DPRINTF("freed ov page %zu", pg);
5593                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5594                         pg++;
5595                 }
5596         }
5597         mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5598         mc->mc_db->md_entries--;
5599         rc = mdb_rebalance(mc);
5600         if (rc != MDB_SUCCESS)
5601                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5602
5603         return rc;
5604 }
5605
5606 int
5607 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5608     MDB_val *key, MDB_val *data)
5609 {
5610         MDB_cursor mc;
5611         MDB_xcursor mx;
5612         MDB_cursor_op op;
5613         MDB_val rdata, *xdata;
5614         int              rc, exact;
5615         DKBUF;
5616
5617         assert(key != NULL);
5618
5619         DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5620
5621         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5622                 return EINVAL;
5623
5624         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5625                 return EACCES;
5626         }
5627
5628         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5629                 return EINVAL;
5630         }
5631
5632         mdb_cursor_init(&mc, txn, dbi, &mx);
5633
5634         exact = 0;
5635         if (data) {
5636                 op = MDB_GET_BOTH;
5637                 rdata = *data;
5638                 xdata = &rdata;
5639         } else {
5640                 op = MDB_SET;
5641                 xdata = NULL;
5642         }
5643         rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5644         if (rc == 0)
5645                 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5646         return rc;
5647 }
5648
5649 /** Split a page and insert a new node.
5650  * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5651  * The cursor will be updated to point to the actual page and index where
5652  * the node got inserted after the split.
5653  * @param[in] newkey The key for the newly inserted node.
5654  * @param[in] newdata The data for the newly inserted node.
5655  * @param[in] newpgno The page number, if the new node is a branch node.
5656  * @return 0 on success, non-zero on failure.
5657  */
5658 static int
5659 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5660         unsigned int nflags)
5661 {
5662         unsigned int flags;
5663         int              rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1;
5664         indx_t           newindx;
5665         pgno_t           pgno = 0;
5666         unsigned int     i, j, split_indx, nkeys, pmax;
5667         MDB_node        *node;
5668         MDB_val  sepkey, rkey, xdata, *rdata = &xdata;
5669         MDB_page        *copy;
5670         MDB_page        *mp, *rp, *pp;
5671         unsigned int ptop;
5672         MDB_cursor      mn;
5673         DKBUF;
5674
5675         mp = mc->mc_pg[mc->mc_top];
5676         newindx = mc->mc_ki[mc->mc_top];
5677
5678         DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5679             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5680             DKEY(newkey), mc->mc_ki[mc->mc_top]);
5681
5682         /* Create a right sibling. */
5683         if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5684                 return ENOMEM;
5685         DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5686
5687         if (mc->mc_snum < 2) {
5688                 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5689                         return ENOMEM;
5690                 /* shift current top to make room for new parent */
5691                 mc->mc_pg[1] = mc->mc_pg[0];
5692                 mc->mc_ki[1] = mc->mc_ki[0];
5693                 mc->mc_pg[0] = pp;
5694                 mc->mc_ki[0] = 0;
5695                 mc->mc_db->md_root = pp->mp_pgno;
5696                 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5697                 mc->mc_db->md_depth++;
5698                 new_root = 1;
5699
5700                 /* Add left (implicit) pointer. */
5701                 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5702                         /* undo the pre-push */
5703                         mc->mc_pg[0] = mc->mc_pg[1];
5704                         mc->mc_ki[0] = mc->mc_ki[1];
5705                         mc->mc_db->md_root = mp->mp_pgno;
5706                         mc->mc_db->md_depth--;
5707                         return rc;
5708                 }
5709                 mc->mc_snum = 2;
5710                 mc->mc_top = 1;
5711                 ptop = 0;
5712         } else {
5713                 ptop = mc->mc_top-1;
5714                 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5715         }
5716
5717         mdb_cursor_copy(mc, &mn);
5718         mn.mc_pg[mn.mc_top] = rp;
5719         mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5720
5721         if (nflags & MDB_APPEND) {
5722                 mn.mc_ki[mn.mc_top] = 0;
5723                 sepkey = *newkey;
5724                 nkeys = 0;
5725                 split_indx = 0;
5726                 goto newsep;
5727         }
5728
5729         nkeys = NUMKEYS(mp);
5730         split_indx = (nkeys + 1) / 2;
5731
5732         if (IS_LEAF2(rp)) {
5733                 char *split, *ins;
5734                 int x;
5735                 unsigned int lsize, rsize, ksize;
5736                 /* Move half of the keys to the right sibling */
5737                 copy = NULL;
5738                 x = mc->mc_ki[mc->mc_top] - split_indx;
5739                 ksize = mc->mc_db->md_pad;
5740                 split = LEAF2KEY(mp, split_indx, ksize);
5741                 rsize = (nkeys - split_indx) * ksize;
5742                 lsize = (nkeys - split_indx) * sizeof(indx_t);
5743                 mp->mp_lower -= lsize;
5744                 rp->mp_lower += lsize;
5745                 mp->mp_upper += rsize - lsize;
5746                 rp->mp_upper -= rsize - lsize;
5747                 sepkey.mv_size = ksize;
5748                 if (newindx == split_indx) {
5749                         sepkey.mv_data = newkey->mv_data;
5750                 } else {
5751                         sepkey.mv_data = split;
5752                 }
5753                 if (x<0) {
5754                         ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5755                         memcpy(rp->mp_ptrs, split, rsize);
5756                         sepkey.mv_data = rp->mp_ptrs;
5757                         memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5758                         memcpy(ins, newkey->mv_data, ksize);
5759                         mp->mp_lower += sizeof(indx_t);
5760                         mp->mp_upper -= ksize - sizeof(indx_t);
5761                 } else {
5762                         if (x)
5763                                 memcpy(rp->mp_ptrs, split, x * ksize);
5764                         ins = LEAF2KEY(rp, x, ksize);
5765                         memcpy(ins, newkey->mv_data, ksize);
5766                         memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5767                         rp->mp_lower += sizeof(indx_t);
5768                         rp->mp_upper -= ksize - sizeof(indx_t);
5769                         mc->mc_ki[mc->mc_top] = x;
5770                         mc->mc_pg[mc->mc_top] = rp;
5771                 }
5772                 goto newsep;
5773         }
5774
5775         /* For leaf pages, check the split point based on what
5776          * fits where, since otherwise mdb_node_add can fail.
5777          *
5778          * This check is only needed when the data items are
5779          * relatively large, such that being off by one will
5780          * make the difference between success or failure.
5781          * When the size of the data items is much smaller than
5782          * one-half of a page, this check is irrelevant.
5783          */
5784         if (IS_LEAF(mp)) {
5785                 unsigned int psize, nsize;
5786                 /* Maximum free space in an empty page */
5787                 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5788                 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5789                 if ((nkeys < 20) || (nsize > pmax/4)) {
5790                         if (newindx <= split_indx) {
5791                                 psize = nsize;
5792                                 newpos = 0;
5793                                 for (i=0; i<split_indx; i++) {
5794                                         node = NODEPTR(mp, i);
5795                                         psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5796                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
5797                                                 psize += sizeof(pgno_t);
5798                                         else
5799                                                 psize += NODEDSZ(node);
5800                                         psize += psize & 1;
5801                                         if (psize > pmax) {
5802                                                 if (i == split_indx - 1 && newindx == split_indx)
5803                                                         newpos = 1;
5804                                                 else
5805                                                         split_indx = i;
5806                                                 break;
5807                                         }
5808                                 }
5809                         } else {
5810                                 psize = nsize;
5811                                 for (i=nkeys-1; i>=split_indx; i--) {
5812                                         node = NODEPTR(mp, i);
5813                                         psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5814                                         if (F_ISSET(node->mn_flags, F_BIGDATA))
5815                                                 psize += sizeof(pgno_t);
5816                                         else
5817                                                 psize += NODEDSZ(node);
5818                                         psize += psize & 1;
5819                                         if (psize > pmax) {
5820                                                 split_indx = i+1;
5821                                                 break;
5822                                         }
5823                                 }
5824                         }
5825                 }
5826         }
5827
5828         /* First find the separating key between the split pages.
5829          * The case where newindx == split_indx is ambiguous; the
5830          * new item could go to the new page or stay on the original
5831          * page. If newpos == 1 it goes to the new page.
5832          */
5833         if (newindx == split_indx && newpos) {
5834                 sepkey.mv_size = newkey->mv_size;
5835                 sepkey.mv_data = newkey->mv_data;
5836         } else {
5837                 node = NODEPTR(mp, split_indx);
5838                 sepkey.mv_size = node->mn_ksize;
5839                 sepkey.mv_data = NODEKEY(node);
5840         }
5841
5842 newsep:
5843         DPRINTF("separator is [%s]", DKEY(&sepkey));
5844
5845         /* Copy separator key to the parent.
5846          */
5847         if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5848                 mn.mc_snum--;
5849                 mn.mc_top--;
5850                 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5851
5852                 /* Right page might now have changed parent.
5853                  * Check if left page also changed parent.
5854                  */
5855                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5856                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5857                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
5858                         mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5859                 }
5860         } else {
5861                 mn.mc_top--;
5862                 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5863                 mn.mc_top++;
5864         }
5865         if (rc != MDB_SUCCESS) {
5866                 return rc;
5867         }
5868         if (nflags & MDB_APPEND) {
5869                 mc->mc_pg[mc->mc_top] = rp;
5870                 mc->mc_ki[mc->mc_top] = 0;
5871                 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5872                 if (rc)
5873                         return rc;
5874                 goto done;
5875         }
5876         if (IS_LEAF2(rp)) {
5877                 goto done;
5878         }
5879
5880         /* Move half of the keys to the right sibling. */
5881
5882         /* grab a page to hold a temporary copy */
5883         copy = mdb_page_malloc(mc);
5884         if (copy == NULL)
5885                 return ENOMEM;
5886
5887         copy->mp_pgno  = mp->mp_pgno;
5888         copy->mp_flags = mp->mp_flags;
5889         copy->mp_lower = PAGEHDRSZ;
5890         copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5891         mc->mc_pg[mc->mc_top] = copy;
5892         for (i = j = 0; i <= nkeys; j++) {
5893                 if (i == split_indx) {
5894                 /* Insert in right sibling. */
5895                 /* Reset insert index for right sibling. */
5896                         if (i != newindx || (newpos ^ ins_new)) {
5897                                 j = 0;
5898                                 mc->mc_pg[mc->mc_top] = rp;
5899                         }
5900                 }
5901
5902                 if (i == newindx && !ins_new) {
5903                         /* Insert the original entry that caused the split. */
5904                         rkey.mv_data = newkey->mv_data;
5905                         rkey.mv_size = newkey->mv_size;
5906                         if (IS_LEAF(mp)) {
5907                                 rdata = newdata;
5908                         } else
5909                                 pgno = newpgno;
5910                         flags = nflags;
5911
5912                         ins_new = 1;
5913
5914                         /* Update index for the new key. */
5915                         mc->mc_ki[mc->mc_top] = j;
5916                 } else if (i == nkeys) {
5917                         break;
5918                 } else {
5919                         node = NODEPTR(mp, i);
5920                         rkey.mv_data = NODEKEY(node);
5921                         rkey.mv_size = node->mn_ksize;
5922                         if (IS_LEAF(mp)) {
5923                                 xdata.mv_data = NODEDATA(node);
5924                                 xdata.mv_size = NODEDSZ(node);
5925                                 rdata = &xdata;
5926                         } else
5927                                 pgno = NODEPGNO(node);
5928                         flags = node->mn_flags;
5929
5930                         i++;
5931                 }
5932
5933                 if (!IS_LEAF(mp) && j == 0) {
5934                         /* First branch index doesn't need key data. */
5935                         rkey.mv_size = 0;
5936                 }
5937
5938                 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5939                 if (rc) break;
5940         }
5941
5942         nkeys = NUMKEYS(copy);
5943         for (i=0; i<nkeys; i++)
5944                 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5945         mp->mp_lower = copy->mp_lower;
5946         mp->mp_upper = copy->mp_upper;
5947         memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5948                 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5949
5950         /* reset back to original page */
5951         if (newindx < split_indx || (!newpos && newindx == split_indx)) {
5952                 mc->mc_pg[mc->mc_top] = mp;
5953                 if (nflags & MDB_RESERVE) {
5954                         node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5955                         if (!(node->mn_flags & F_BIGDATA))
5956                                 newdata->mv_data = NODEDATA(node);
5957                 }
5958         }
5959
5960         /* return tmp page to freelist */
5961         copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5962         VGMEMP_FREE(mc->mc_txn->mt_env, copy);
5963         mc->mc_txn->mt_env->me_dpages = copy;
5964 done:
5965         {
5966                 /* Adjust other cursors pointing to mp */
5967                 MDB_cursor *m2, *m3;
5968                 MDB_dbi dbi = mc->mc_dbi;
5969
5970                 if (mc->mc_flags & C_SUB)
5971                         dbi--;
5972
5973                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5974                         if (m2 == mc) continue;
5975                         if (mc->mc_flags & C_SUB)
5976                                 m3 = &m2->mc_xcursor->mx_cursor;
5977                         else
5978                                 m3 = m2;
5979                         if (!(m3->mc_flags & C_INITIALIZED))
5980                                 continue;
5981                         if (new_root) {
5982                                 int k;
5983                                 /* root split */
5984                                 for (k=m3->mc_top; k>=0; k--) {
5985                                         m3->mc_ki[k+1] = m3->mc_ki[k];
5986                                         m3->mc_pg[k+1] = m3->mc_pg[k];
5987                                 }
5988                                 m3->mc_ki[0] = mc->mc_ki[0];
5989                                 m3->mc_pg[0] = mc->mc_pg[0];
5990                                 m3->mc_snum++;
5991                                 m3->mc_top++;
5992                         }
5993                         if (m3->mc_pg[mc->mc_top] == mp) {
5994                                 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5995                                         m3->mc_pg[m3->mc_top] = rp;
5996                                         m3->mc_ki[m3->mc_top] -= split_indx;
5997                                 }
5998                         }
5999                 }
6000         }
6001         return rc;
6002 }
6003
6004 int
6005 mdb_put(MDB_txn *txn, MDB_dbi dbi,
6006     MDB_val *key, MDB_val *data, unsigned int flags)
6007 {
6008         MDB_cursor mc;
6009         MDB_xcursor mx;
6010
6011         assert(key != NULL);
6012         assert(data != NULL);
6013
6014         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6015                 return EINVAL;
6016
6017         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6018                 return EACCES;
6019         }
6020
6021         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
6022                 return EINVAL;
6023         }
6024
6025         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
6026                 return EINVAL;
6027
6028         mdb_cursor_init(&mc, txn, dbi, &mx);
6029         return mdb_cursor_put(&mc, key, data, flags);
6030 }
6031
6032 /** Only a subset of the @ref mdb_env flags can be changed
6033  *      at runtime. Changing other flags requires closing the environment
6034  *      and re-opening it with the new flags.
6035  */
6036 #define CHANGEABLE      (MDB_NOSYNC)
6037 int
6038 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6039 {
6040         if ((flag & CHANGEABLE) != flag)
6041                 return EINVAL;
6042         if (onoff)
6043                 env->me_flags |= flag;
6044         else
6045                 env->me_flags &= ~flag;
6046         return MDB_SUCCESS;
6047 }
6048
6049 int
6050 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6051 {
6052         if (!env || !arg)
6053                 return EINVAL;
6054
6055         *arg = env->me_flags;
6056         return MDB_SUCCESS;
6057 }
6058
6059 int
6060 mdb_env_get_path(MDB_env *env, const char **arg)
6061 {
6062         if (!env || !arg)
6063                 return EINVAL;
6064
6065         *arg = env->me_path;
6066         return MDB_SUCCESS;
6067 }
6068
6069 /** Common code for #mdb_stat() and #mdb_env_stat().
6070  * @param[in] env the environment to operate in.
6071  * @param[in] db the #MDB_db record containing the stats to return.
6072  * @param[out] arg the address of an #MDB_stat structure to receive the stats.
6073  * @return 0, this function always succeeds.
6074  */
6075 static int
6076 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
6077 {
6078         arg->ms_psize = env->me_psize;
6079         arg->ms_depth = db->md_depth;
6080         arg->ms_branch_pages = db->md_branch_pages;
6081         arg->ms_leaf_pages = db->md_leaf_pages;
6082         arg->ms_overflow_pages = db->md_overflow_pages;
6083         arg->ms_entries = db->md_entries;
6084
6085         return MDB_SUCCESS;
6086 }
6087 int
6088 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6089 {
6090         int toggle;
6091
6092         if (env == NULL || arg == NULL)
6093                 return EINVAL;
6094
6095         mdb_env_read_meta(env, &toggle);
6096
6097         return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6098 }
6099
6100 /** Set the default comparison functions for a database.
6101  * Called immediately after a database is opened to set the defaults.
6102  * The user can then override them with #mdb_set_compare() or
6103  * #mdb_set_dupsort().
6104  * @param[in] txn A transaction handle returned by #mdb_txn_begin()
6105  * @param[in] dbi A database handle returned by #mdb_open()
6106  */
6107 static void
6108 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
6109 {
6110         if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
6111                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
6112         else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
6113                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
6114         else
6115                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
6116
6117         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6118                 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
6119                         if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
6120                                 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
6121                         else
6122                                 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
6123                 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
6124                         txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
6125                 } else {
6126                         txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
6127                 }
6128         } else {
6129                 txn->mt_dbxs[dbi].md_dcmp = NULL;
6130         }
6131 }
6132
6133 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
6134 {
6135         MDB_val key, data;
6136         MDB_dbi i;
6137         MDB_cursor mc;
6138         int rc, dbflag, exact;
6139         size_t len;
6140
6141         if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
6142                 mdb_default_cmp(txn, FREE_DBI);
6143         }
6144
6145         /* main DB? */
6146         if (!name) {
6147                 *dbi = MAIN_DBI;
6148                 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
6149                         txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
6150                 mdb_default_cmp(txn, MAIN_DBI);
6151                 return MDB_SUCCESS;
6152         }
6153
6154         if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6155                 mdb_default_cmp(txn, MAIN_DBI);
6156         }
6157
6158         /* Is the DB already open? */
6159         len = strlen(name);
6160         for (i=2; i<txn->mt_numdbs; i++) {
6161                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6162                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6163                         *dbi = i;
6164                         return MDB_SUCCESS;
6165                 }
6166         }
6167
6168         if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
6169                 return ENFILE;
6170
6171         /* Find the DB info */
6172         dbflag = 0;
6173         exact = 0;
6174         key.mv_size = len;
6175         key.mv_data = (void *)name;
6176         mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6177         rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6178         if (rc == MDB_SUCCESS) {
6179                 /* make sure this is actually a DB */
6180                 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6181                 if (!(node->mn_flags & F_SUBDATA))
6182                         return EINVAL;
6183         } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6184                 /* Create if requested */
6185                 MDB_db dummy;
6186                 data.mv_size = sizeof(MDB_db);
6187                 data.mv_data = &dummy;
6188                 memset(&dummy, 0, sizeof(dummy));
6189                 dummy.md_root = P_INVALID;
6190                 dummy.md_flags = flags & 0xffff;
6191                 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6192                 dbflag = DB_DIRTY;
6193         }
6194
6195         /* OK, got info, add to table */
6196         if (rc == MDB_SUCCESS) {
6197                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
6198                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
6199                 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
6200                 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
6201                 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
6202                 *dbi = txn->mt_numdbs;
6203                 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6204                 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
6205                 mdb_default_cmp(txn, txn->mt_numdbs);
6206                 txn->mt_numdbs++;
6207         }
6208
6209         return rc;
6210 }
6211
6212 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6213 {
6214         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6215                 return EINVAL;
6216
6217         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6218 }
6219
6220 void mdb_close(MDB_env *env, MDB_dbi dbi)
6221 {
6222         char *ptr;
6223         if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
6224                 return;
6225         ptr = env->me_dbxs[dbi].md_name.mv_data;
6226         env->me_dbxs[dbi].md_name.mv_data = NULL;
6227         env->me_dbxs[dbi].md_name.mv_size = 0;
6228         free(ptr);
6229 }
6230
6231 /** Add all the DB's pages to the free list.
6232  * @param[in] mc Cursor on the DB to free.
6233  * @param[in] subs non-Zero to check for sub-DBs in this DB.
6234  * @return 0 on success, non-zero on failure.
6235  */
6236 static int
6237 mdb_drop0(MDB_cursor *mc, int subs)
6238 {
6239         int rc;
6240
6241         rc = mdb_page_search(mc, NULL, 0);
6242         if (rc == MDB_SUCCESS) {
6243                 MDB_node *ni;
6244                 MDB_cursor mx;
6245                 unsigned int i;
6246
6247                 /* LEAF2 pages have no nodes, cannot have sub-DBs */
6248                 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
6249                         mdb_cursor_pop(mc);
6250
6251                 mdb_cursor_copy(mc, &mx);
6252                 while (mc->mc_snum > 0) {
6253                         if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
6254                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6255                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6256                                         if (ni->mn_flags & F_SUBDATA) {
6257                                                 mdb_xcursor_init1(mc, ni);
6258                                                 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6259                                                 if (rc)
6260                                                         return rc;
6261                                         }
6262                                 }
6263                         } else {
6264                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6265                                         pgno_t pg;
6266                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6267                                         pg = NODEPGNO(ni);
6268                                         /* free it */
6269                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6270                                 }
6271                         }
6272                         if (!mc->mc_top)
6273                                 break;
6274                         rc = mdb_cursor_sibling(mc, 1);
6275                         if (rc) {
6276                                 /* no more siblings, go back to beginning
6277                                  * of previous level. (stack was already popped
6278                                  * by mdb_cursor_sibling)
6279                                  */
6280                                 for (i=1; i<mc->mc_top; i++)
6281                                         mc->mc_pg[i] = mx.mc_pg[i];
6282                         }
6283                 }
6284                 /* free it */
6285                 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
6286                         mc->mc_db->md_root);
6287         }
6288         return 0;
6289 }
6290
6291 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6292 {
6293         MDB_cursor *mc;
6294         int rc;
6295
6296         if (!txn || !dbi || dbi >= txn->mt_numdbs)
6297                 return EINVAL;
6298
6299         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6300                 return EACCES;
6301
6302         rc = mdb_cursor_open(txn, dbi, &mc);
6303         if (rc)
6304                 return rc;
6305
6306         rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6307         if (rc)
6308                 goto leave;
6309
6310         /* Can't delete the main DB */
6311         if (del && dbi > MAIN_DBI) {
6312                 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6313                 if (!rc)
6314                         mdb_close(txn->mt_env, dbi);
6315         } else {
6316                 txn->mt_dbflags[dbi] |= DB_DIRTY;
6317                 txn->mt_dbs[dbi].md_depth = 0;
6318                 txn->mt_dbs[dbi].md_branch_pages = 0;
6319                 txn->mt_dbs[dbi].md_leaf_pages = 0;
6320                 txn->mt_dbs[dbi].md_overflow_pages = 0;
6321                 txn->mt_dbs[dbi].md_entries = 0;
6322                 txn->mt_dbs[dbi].md_root = P_INVALID;
6323         }
6324 leave:
6325         mdb_cursor_close(mc);
6326         return rc;
6327 }
6328
6329 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6330 {
6331         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6332                 return EINVAL;
6333
6334         txn->mt_dbxs[dbi].md_cmp = cmp;
6335         return MDB_SUCCESS;
6336 }
6337
6338 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6339 {
6340         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6341                 return EINVAL;
6342
6343         txn->mt_dbxs[dbi].md_dcmp = cmp;
6344         return MDB_SUCCESS;
6345 }
6346
6347 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6348 {
6349         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6350                 return EINVAL;
6351
6352         txn->mt_dbxs[dbi].md_rel = rel;
6353         return MDB_SUCCESS;
6354 }
6355
6356 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6357 {
6358         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6359                 return EINVAL;
6360
6361         txn->mt_dbxs[dbi].md_relctx = ctx;
6362         return MDB_SUCCESS;
6363 }
6364
6365 /** @} */