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