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