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