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