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