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