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