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