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