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