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