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