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