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