]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
bec30d3e06062bbb0083c3b2227bfcb6f4795932
[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 #if MDB_DEBUG
2963         {
2964         pgno_t pgno;
2965         COPY_PGNO(pgno, mp->mp_pgno);
2966         DPRINTF("searching %u keys in %s %spage %zu",
2967             nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2968             pgno);
2969         }
2970 #endif
2971
2972         assert(nkeys > 0);
2973
2974         low = IS_LEAF(mp) ? 0 : 1;
2975         high = nkeys - 1;
2976         cmp = mc->mc_dbx->md_cmp;
2977
2978         /* Branch pages have no data, so if using integer keys,
2979          * alignment is guaranteed. Use faster mdb_cmp_int.
2980          */
2981         if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2982                 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2983                         cmp = mdb_cmp_long;
2984                 else
2985                         cmp = mdb_cmp_int;
2986         }
2987
2988         if (IS_LEAF2(mp)) {
2989                 nodekey.mv_size = mc->mc_db->md_pad;
2990                 node = NODEPTR(mp, 0);  /* fake */
2991                 while (low <= high) {
2992                         i = (low + high) >> 1;
2993                         nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2994                         rc = cmp(key, &nodekey);
2995                         DPRINTF("found leaf index %u [%s], rc = %i",
2996                             i, DKEY(&nodekey), rc);
2997                         if (rc == 0)
2998                                 break;
2999                         if (rc > 0)
3000                                 low = i + 1;
3001                         else
3002                                 high = i - 1;
3003                 }
3004         } else {
3005                 while (low <= high) {
3006                         i = (low + high) >> 1;
3007
3008                         node = NODEPTR(mp, i);
3009                         nodekey.mv_size = NODEKSZ(node);
3010                         nodekey.mv_data = NODEKEY(node);
3011
3012                         rc = cmp(key, &nodekey);
3013 #if MDB_DEBUG
3014                         if (IS_LEAF(mp))
3015                                 DPRINTF("found leaf index %u [%s], rc = %i",
3016                                     i, DKEY(&nodekey), rc);
3017                         else
3018                                 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3019                                     i, DKEY(&nodekey), NODEPGNO(node), rc);
3020 #endif
3021                         if (rc == 0)
3022                                 break;
3023                         if (rc > 0)
3024                                 low = i + 1;
3025                         else
3026                                 high = i - 1;
3027                 }
3028         }
3029
3030         if (rc > 0) {   /* Found entry is less than the key. */
3031                 i++;    /* Skip to get the smallest entry larger than key. */
3032                 if (!IS_LEAF2(mp))
3033                         node = NODEPTR(mp, i);
3034         }
3035         if (exactp)
3036                 *exactp = (rc == 0);
3037         /* store the key index */
3038         mc->mc_ki[mc->mc_top] = i;
3039         if (i >= nkeys)
3040                 /* There is no entry larger or equal to the key. */
3041                 return NULL;
3042
3043         /* nodeptr is fake for LEAF2 */
3044         return node;
3045 }
3046
3047 #if 0
3048 static void
3049 mdb_cursor_adjust(MDB_cursor *mc, func)
3050 {
3051         MDB_cursor *m2;
3052
3053         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3054                 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3055                         func(mc, m2);
3056                 }
3057         }
3058 }
3059 #endif
3060
3061 /** Pop a page off the top of the cursor's stack. */
3062 static void
3063 mdb_cursor_pop(MDB_cursor *mc)
3064 {
3065         MDB_page        *top;
3066
3067         if (mc->mc_snum) {
3068                 top = mc->mc_pg[mc->mc_top];
3069                 mc->mc_snum--;
3070                 if (mc->mc_snum)
3071                         mc->mc_top--;
3072
3073                 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3074                         mc->mc_dbi, (void *) mc);
3075         }
3076 }
3077
3078 /** Push a page onto the top of the cursor's stack. */
3079 static int
3080 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3081 {
3082         DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3083                 mc->mc_dbi, (void *) mc);
3084
3085         if (mc->mc_snum >= CURSOR_STACK) {
3086                 assert(mc->mc_snum < CURSOR_STACK);
3087                 return ENOMEM;
3088         }
3089
3090         mc->mc_top = mc->mc_snum++;
3091         mc->mc_pg[mc->mc_top] = mp;
3092         mc->mc_ki[mc->mc_top] = 0;
3093
3094         return MDB_SUCCESS;
3095 }
3096
3097 /** Find the address of the page corresponding to a given page number.
3098  * @param[in] txn the transaction for this access.
3099  * @param[in] pgno the page number for the page to retrieve.
3100  * @param[out] ret address of a pointer where the page's address will be stored.
3101  * @return 0 on success, non-zero on failure.
3102  */
3103 static int
3104 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3105 {
3106         MDB_page *p = NULL;
3107
3108         if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3109                 unsigned x;
3110                 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3111                 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3112                         p = txn->mt_u.dirty_list[x].mptr;
3113                 }
3114         }
3115         if (!p) {
3116                 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3117                         p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3118         }
3119         *ret = p;
3120         if (!p) {
3121                 DPRINTF("page %zu not found", pgno);
3122                 assert(p != NULL);
3123         }
3124         return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3125 }
3126
3127 /** Search for the page a given key should be in.
3128  * Pushes parent pages on the cursor stack. This function continues a
3129  * search on a cursor that has already been initialized. (Usually by
3130  * #mdb_page_search() but also by #mdb_node_move().)
3131  * @param[in,out] mc the cursor for this operation.
3132  * @param[in] key the key to search for. If NULL, search for the lowest
3133  * page. (This is used by #mdb_cursor_first().)
3134  * @param[in] modify If true, visited pages are updated with new page numbers.
3135  * @return 0 on success, non-zero on failure.
3136  */
3137 static int
3138 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3139 {
3140         MDB_page        *mp = mc->mc_pg[mc->mc_top];
3141         DKBUF;
3142         int rc;
3143
3144
3145         while (IS_BRANCH(mp)) {
3146                 MDB_node        *node;
3147                 indx_t          i;
3148
3149                 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3150                 assert(NUMKEYS(mp) > 1);
3151                 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3152
3153                 if (key == NULL)        /* Initialize cursor to first page. */
3154                         i = 0;
3155                 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3156                                                         /* cursor to last page */
3157                         i = NUMKEYS(mp)-1;
3158                 } else {
3159                         int      exact;
3160                         node = mdb_node_search(mc, key, &exact);
3161                         if (node == NULL)
3162                                 i = NUMKEYS(mp) - 1;
3163                         else {
3164                                 i = mc->mc_ki[mc->mc_top];
3165                                 if (!exact) {
3166                                         assert(i > 0);
3167                                         i--;
3168                                 }
3169                         }
3170                 }
3171
3172                 if (key)
3173                         DPRINTF("following index %u for key [%s]",
3174                             i, DKEY(key));
3175                 assert(i < NUMKEYS(mp));
3176                 node = NODEPTR(mp, i);
3177
3178                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3179                         return rc;
3180
3181                 mc->mc_ki[mc->mc_top] = i;
3182                 if ((rc = mdb_cursor_push(mc, mp)))
3183                         return rc;
3184
3185                 if (modify) {
3186                         if ((rc = mdb_page_touch(mc)) != 0)
3187                                 return rc;
3188                         mp = mc->mc_pg[mc->mc_top];
3189                 }
3190         }
3191
3192         if (!IS_LEAF(mp)) {
3193                 DPRINTF("internal error, index points to a %02X page!?",
3194                     mp->mp_flags);
3195                 return MDB_CORRUPTED;
3196         }
3197
3198         DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3199             key ? DKEY(key) : NULL);
3200
3201         return MDB_SUCCESS;
3202 }
3203
3204 /** Search for the page a given key should be in.
3205  * Pushes parent pages on the cursor stack. This function just sets up
3206  * the search; it finds the root page for \b mc's database and sets this
3207  * as the root of the cursor's stack. Then #mdb_page_search_root() is
3208  * called to complete the search.
3209  * @param[in,out] mc the cursor for this operation.
3210  * @param[in] key the key to search for. If NULL, search for the lowest
3211  * page. (This is used by #mdb_cursor_first().)
3212  * @param[in] modify If true, visited pages are updated with new page numbers.
3213  * @return 0 on success, non-zero on failure.
3214  */
3215 static int
3216 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3217 {
3218         int              rc;
3219         pgno_t           root;
3220
3221         /* Make sure the txn is still viable, then find the root from
3222          * the txn's db table.
3223          */
3224         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3225                 DPUTS("transaction has failed, must abort");
3226                 return EINVAL;
3227         } else {
3228                 /* Make sure we're using an up-to-date root */
3229                 if (mc->mc_dbi > MAIN_DBI) {
3230                         if ((*mc->mc_dbflag & DB_STALE) ||
3231                         (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3232                                 MDB_cursor mc2;
3233                                 unsigned char dbflag = 0;
3234                                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3235                                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3236                                 if (rc)
3237                                         return rc;
3238                                 if (*mc->mc_dbflag & DB_STALE) {
3239                                         MDB_val data;
3240                                         int exact = 0;
3241                                         MDB_node *leaf = mdb_node_search(&mc2,
3242                                                 &mc->mc_dbx->md_name, &exact);
3243                                         if (!exact)
3244                                                 return MDB_NOTFOUND;
3245                                         mdb_node_read(mc->mc_txn, leaf, &data);
3246                                         memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3247                                 }
3248                                 if (modify)
3249                                         dbflag = DB_DIRTY;
3250                                 *mc->mc_dbflag = dbflag;
3251                         }
3252                 }
3253                 root = mc->mc_db->md_root;
3254
3255                 if (root == P_INVALID) {                /* Tree is empty. */
3256                         DPUTS("tree is empty");
3257                         return MDB_NOTFOUND;
3258                 }
3259         }
3260
3261         assert(root > 1);
3262         if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3263                 return rc;
3264
3265         mc->mc_snum = 1;
3266         mc->mc_top = 0;
3267
3268         DPRINTF("db %u root page %zu has flags 0x%X",
3269                 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3270
3271         if (modify) {
3272                 if ((rc = mdb_page_touch(mc)))
3273                         return rc;
3274         }
3275
3276         return mdb_page_search_root(mc, key, modify);
3277 }
3278
3279 /** Return the data associated with a given node.
3280  * @param[in] txn The transaction for this operation.
3281  * @param[in] leaf The node being read.
3282  * @param[out] data Updated to point to the node's data.
3283  * @return 0 on success, non-zero on failure.
3284  */
3285 static int
3286 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3287 {
3288         MDB_page        *omp;           /* overflow page */
3289         pgno_t           pgno;
3290         int rc;
3291
3292         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3293                 data->mv_size = NODEDSZ(leaf);
3294                 data->mv_data = NODEDATA(leaf);
3295                 return MDB_SUCCESS;
3296         }
3297
3298         /* Read overflow data.
3299          */
3300         data->mv_size = NODEDSZ(leaf);
3301         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3302         if ((rc = mdb_page_get(txn, pgno, &omp))) {
3303                 DPRINTF("read overflow page %zu failed", pgno);
3304                 return rc;
3305         }
3306         data->mv_data = METADATA(omp);
3307
3308         return MDB_SUCCESS;
3309 }
3310
3311 int
3312 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3313     MDB_val *key, MDB_val *data)
3314 {
3315         MDB_cursor      mc;
3316         MDB_xcursor     mx;
3317         int exact = 0;
3318         DKBUF;
3319
3320         assert(key);
3321         assert(data);
3322         DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3323
3324         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3325                 return EINVAL;
3326
3327         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3328                 return EINVAL;
3329         }
3330
3331         mdb_cursor_init(&mc, txn, dbi, &mx);
3332         return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3333 }
3334
3335 /** Find a sibling for a page.
3336  * Replaces the page at the top of the cursor's stack with the
3337  * specified sibling, if one exists.
3338  * @param[in] mc The cursor for this operation.
3339  * @param[in] move_right Non-zero if the right sibling is requested,
3340  * otherwise the left sibling.
3341  * @return 0 on success, non-zero on failure.
3342  */
3343 static int
3344 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3345 {
3346         int              rc;
3347         MDB_node        *indx;
3348         MDB_page        *mp;
3349
3350         if (mc->mc_snum < 2) {
3351                 return MDB_NOTFOUND;            /* root has no siblings */
3352         }
3353
3354         mdb_cursor_pop(mc);
3355         DPRINTF("parent page is page %zu, index %u",
3356                 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3357
3358         if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3359                        : (mc->mc_ki[mc->mc_top] == 0)) {
3360                 DPRINTF("no more keys left, moving to %s sibling",
3361                     move_right ? "right" : "left");
3362                 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3363                         return rc;
3364         } else {
3365                 if (move_right)
3366                         mc->mc_ki[mc->mc_top]++;
3367                 else
3368                         mc->mc_ki[mc->mc_top]--;
3369                 DPRINTF("just moving to %s index key %u",
3370                     move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3371         }
3372         assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3373
3374         indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3375         if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3376                 return rc;;
3377
3378         mdb_cursor_push(mc, mp);
3379
3380         return MDB_SUCCESS;
3381 }
3382
3383 /** Move the cursor to the next data item. */
3384 static int
3385 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3386 {
3387         MDB_page        *mp;
3388         MDB_node        *leaf;
3389         int rc;
3390
3391         if (mc->mc_flags & C_EOF) {
3392                 return MDB_NOTFOUND;
3393         }
3394
3395         assert(mc->mc_flags & C_INITIALIZED);
3396
3397         mp = mc->mc_pg[mc->mc_top];
3398
3399         if (mc->mc_db->md_flags & MDB_DUPSORT) {
3400                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3401                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3402                         if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3403                                 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3404                                 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3405                                         return rc;
3406                         }
3407                 } else {
3408                         mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3409                         if (op == MDB_NEXT_DUP)
3410                                 return MDB_NOTFOUND;
3411                 }
3412         }
3413
3414         DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3415
3416         if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3417                 DPUTS("=====> move to next sibling page");
3418                 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3419                         mc->mc_flags |= C_EOF;
3420                         mc->mc_flags &= ~C_INITIALIZED;
3421                         return MDB_NOTFOUND;
3422                 }
3423                 mp = mc->mc_pg[mc->mc_top];
3424                 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3425         } else
3426                 mc->mc_ki[mc->mc_top]++;
3427
3428         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3429             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3430
3431         if (IS_LEAF2(mp)) {
3432                 key->mv_size = mc->mc_db->md_pad;
3433                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3434                 return MDB_SUCCESS;
3435         }
3436
3437         assert(IS_LEAF(mp));
3438         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3439
3440         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3441                 mdb_xcursor_init1(mc, leaf);
3442         }
3443         if (data) {
3444                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3445                         return rc;
3446
3447                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3448                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3449                         if (rc != MDB_SUCCESS)
3450                                 return rc;
3451                 }
3452         }
3453
3454         MDB_SET_KEY(leaf, key);
3455         return MDB_SUCCESS;
3456 }
3457
3458 /** Move the cursor to the previous data item. */
3459 static int
3460 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3461 {
3462         MDB_page        *mp;
3463         MDB_node        *leaf;
3464         int rc;
3465
3466         assert(mc->mc_flags & C_INITIALIZED);
3467
3468         mp = mc->mc_pg[mc->mc_top];
3469
3470         if (mc->mc_db->md_flags & MDB_DUPSORT) {
3471                 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3472                 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3473                         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3474                                 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3475                                 if (op != MDB_PREV || rc == MDB_SUCCESS)
3476                                         return rc;
3477                         } else {
3478                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3479                                 if (op == MDB_PREV_DUP)
3480                                         return MDB_NOTFOUND;
3481                         }
3482                 }
3483         }
3484
3485         DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3486
3487         if (mc->mc_ki[mc->mc_top] == 0)  {
3488                 DPUTS("=====> move to prev sibling page");
3489                 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3490                         mc->mc_flags &= ~C_INITIALIZED;
3491                         return MDB_NOTFOUND;
3492                 }
3493                 mp = mc->mc_pg[mc->mc_top];
3494                 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3495                 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3496         } else
3497                 mc->mc_ki[mc->mc_top]--;
3498
3499         mc->mc_flags &= ~C_EOF;
3500
3501         DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3502             mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3503
3504         if (IS_LEAF2(mp)) {
3505                 key->mv_size = mc->mc_db->md_pad;
3506                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3507                 return MDB_SUCCESS;
3508         }
3509
3510         assert(IS_LEAF(mp));
3511         leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3512
3513         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3514                 mdb_xcursor_init1(mc, leaf);
3515         }
3516         if (data) {
3517                 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3518                         return rc;
3519
3520                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3521                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3522                         if (rc != MDB_SUCCESS)
3523                                 return rc;
3524                 }
3525         }
3526
3527         MDB_SET_KEY(leaf, key);
3528         return MDB_SUCCESS;
3529 }
3530
3531 /** Set the cursor on a specific data item. */
3532 static int
3533 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3534     MDB_cursor_op op, int *exactp)
3535 {
3536         int              rc;
3537         MDB_page        *mp;
3538         MDB_node        *leaf;
3539         DKBUF;
3540
3541         assert(mc);
3542         assert(key);
3543         assert(key->mv_size > 0);
3544
3545         /* See if we're already on the right page */
3546         if (mc->mc_flags & C_INITIALIZED) {
3547                 MDB_val nodekey;
3548
3549                 mp = mc->mc_pg[mc->mc_top];
3550                 if (!NUMKEYS(mp)) {
3551                         mc->mc_ki[mc->mc_top] = 0;
3552                         return MDB_NOTFOUND;
3553                 }
3554                 if (mp->mp_flags & P_LEAF2) {
3555                         nodekey.mv_size = mc->mc_db->md_pad;
3556                         nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3557                 } else {
3558                         leaf = NODEPTR(mp, 0);
3559                         MDB_SET_KEY(leaf, &nodekey);
3560                 }
3561                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3562                 if (rc == 0) {
3563                         /* Probably happens rarely, but first node on the page
3564                          * was the one we wanted.
3565                          */
3566                         mc->mc_ki[mc->mc_top] = 0;
3567                         leaf = NODEPTR(mp, 0);
3568                         if (exactp)
3569                                 *exactp = 1;
3570                         goto set1;
3571                 }
3572                 if (rc > 0) {
3573                         unsigned int i;
3574                         unsigned int nkeys = NUMKEYS(mp);
3575                         if (nkeys > 1) {
3576                                 if (mp->mp_flags & P_LEAF2) {
3577                                         nodekey.mv_data = LEAF2KEY(mp,
3578                                                  nkeys-1, nodekey.mv_size);
3579                                 } else {
3580                                         leaf = NODEPTR(mp, nkeys-1);
3581                                         MDB_SET_KEY(leaf, &nodekey);
3582                                 }
3583                                 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3584                                 if (rc == 0) {
3585                                         /* last node was the one we wanted */
3586                                         mc->mc_ki[mc->mc_top] = nkeys-1;
3587                                         leaf = NODEPTR(mp, nkeys-1);
3588                                         if (exactp)
3589                                                 *exactp = 1;
3590                                         goto set1;
3591                                 }
3592                                 if (rc < 0) {
3593                                         /* This is definitely the right page, skip search_page */
3594                                         rc = 0;
3595                                         goto set2;
3596                                 }
3597                         }
3598                         /* If any parents have right-sibs, search.
3599                          * Otherwise, there's nothing further.
3600                          */
3601                         for (i=0; i<mc->mc_top; i++)
3602                                 if (mc->mc_ki[i] <
3603                                         NUMKEYS(mc->mc_pg[i])-1)
3604                                         break;
3605                         if (i == mc->mc_top) {
3606                                 /* There are no other pages */
3607                                 mc->mc_ki[mc->mc_top] = nkeys;
3608                                 return MDB_NOTFOUND;
3609                         }
3610                 }
3611                 if (!mc->mc_top) {
3612                         /* There are no other pages */
3613                         mc->mc_ki[mc->mc_top] = 0;
3614                         return MDB_NOTFOUND;
3615                 }
3616         }
3617
3618         rc = mdb_page_search(mc, key, 0);
3619         if (rc != MDB_SUCCESS)
3620                 return rc;
3621
3622         mp = mc->mc_pg[mc->mc_top];
3623         assert(IS_LEAF(mp));
3624
3625 set2:
3626         leaf = mdb_node_search(mc, key, exactp);
3627         if (exactp != NULL && !*exactp) {
3628                 /* MDB_SET specified and not an exact match. */
3629                 return MDB_NOTFOUND;
3630         }
3631
3632         if (leaf == NULL) {
3633                 DPUTS("===> inexact leaf not found, goto sibling");
3634                 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3635                         return rc;              /* no entries matched */
3636                 mp = mc->mc_pg[mc->mc_top];
3637                 assert(IS_LEAF(mp));
3638                 leaf = NODEPTR(mp, 0);
3639         }
3640
3641 set1:
3642         mc->mc_flags |= C_INITIALIZED;
3643         mc->mc_flags &= ~C_EOF;
3644
3645         if (IS_LEAF2(mp)) {
3646                 key->mv_size = mc->mc_db->md_pad;
3647                 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3648                 return MDB_SUCCESS;
3649         }
3650
3651         if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3652                 mdb_xcursor_init1(mc, leaf);
3653         }
3654         if (data) {
3655                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3656                         if (op == MDB_SET || op == MDB_SET_RANGE) {
3657                                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3658                         } else {
3659                                 int ex2, *ex2p;
3660                                 if (op == MDB_GET_BOTH) {
3661                                         ex2p = &ex2;
3662                                         ex2 = 0;
3663                                 } else {
3664                                         ex2p = NULL;
3665                                 }
3666                                 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3667                                 if (rc != MDB_SUCCESS)
3668                                         return rc;
3669                         }
3670                 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3671                         MDB_val d2;
3672                         if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3673                                 return rc;
3674                         rc = mc->mc_dbx->md_dcmp(data, &d2);
3675                         if (rc) {
3676                                 if (op == MDB_GET_BOTH || rc > 0)
3677                                         return MDB_NOTFOUND;
3678                         }
3679
3680                 } else {
3681                         if (mc->mc_xcursor)
3682                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3683                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3684                                 return rc;
3685                 }
3686         }
3687
3688         /* The key already matches in all other cases */
3689         if (op == MDB_SET_RANGE)
3690                 MDB_SET_KEY(leaf, key);
3691         DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3692
3693         return rc;
3694 }
3695
3696 /** Move the cursor to the first item in the database. */
3697 static int
3698 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3699 {
3700         int              rc;
3701         MDB_node        *leaf;
3702
3703         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3704                 rc = mdb_page_search(mc, NULL, 0);
3705                 if (rc != MDB_SUCCESS)
3706                         return rc;
3707         }
3708         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3709
3710         leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3711         mc->mc_flags |= C_INITIALIZED;
3712         mc->mc_flags &= ~C_EOF;
3713
3714         mc->mc_ki[mc->mc_top] = 0;
3715
3716         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3717                 key->mv_size = mc->mc_db->md_pad;
3718                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3719                 return MDB_SUCCESS;
3720         }
3721
3722         if (data) {
3723                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3724                         mdb_xcursor_init1(mc, leaf);
3725                         rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3726                         if (rc)
3727                                 return rc;
3728                 } else {
3729                         if (mc->mc_xcursor)
3730                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3731                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3732                                 return rc;
3733                 }
3734         }
3735         MDB_SET_KEY(leaf, key);
3736         return MDB_SUCCESS;
3737 }
3738
3739 /** Move the cursor to the last item in the database. */
3740 static int
3741 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3742 {
3743         int              rc;
3744         MDB_node        *leaf;
3745         MDB_val lkey;
3746
3747         lkey.mv_size = MAXKEYSIZE+1;
3748         lkey.mv_data = NULL;
3749
3750         if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3751                 rc = mdb_page_search(mc, &lkey, 0);
3752                 if (rc != MDB_SUCCESS)
3753                         return rc;
3754         }
3755         assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3756
3757         leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3758         mc->mc_flags |= C_INITIALIZED;
3759         mc->mc_flags &= ~C_EOF;
3760
3761         mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3762
3763         if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3764                 key->mv_size = mc->mc_db->md_pad;
3765                 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3766                 return MDB_SUCCESS;
3767         }
3768
3769         if (data) {
3770                 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3771                         mdb_xcursor_init1(mc, leaf);
3772                         rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3773                         if (rc)
3774                                 return rc;
3775                 } else {
3776                         if (mc->mc_xcursor)
3777                                 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3778                         if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3779                                 return rc;
3780                 }
3781         }
3782
3783         MDB_SET_KEY(leaf, key);
3784         return MDB_SUCCESS;
3785 }
3786
3787 int
3788 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3789     MDB_cursor_op op)
3790 {
3791         int              rc;
3792         int              exact = 0;
3793
3794         assert(mc);
3795
3796         switch (op) {
3797         case MDB_GET_BOTH:
3798         case MDB_GET_BOTH_RANGE:
3799                 if (data == NULL || mc->mc_xcursor == NULL) {
3800                         rc = EINVAL;
3801                         break;
3802                 }
3803                 /* FALLTHRU */
3804         case MDB_SET:
3805         case MDB_SET_RANGE:
3806                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3807                         rc = EINVAL;
3808                 } else if (op == MDB_SET_RANGE)
3809                         rc = mdb_cursor_set(mc, key, data, op, NULL);
3810                 else
3811                         rc = mdb_cursor_set(mc, key, data, op, &exact);
3812                 break;
3813         case MDB_GET_MULTIPLE:
3814                 if (data == NULL ||
3815                         !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3816                         !(mc->mc_flags & C_INITIALIZED)) {
3817                         rc = EINVAL;
3818                         break;
3819                 }
3820                 rc = MDB_SUCCESS;
3821                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3822                         (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3823                         break;
3824                 goto fetchm;
3825         case MDB_NEXT_MULTIPLE:
3826                 if (data == NULL ||
3827                         !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3828                         rc = EINVAL;
3829                         break;
3830                 }
3831                 if (!(mc->mc_flags & C_INITIALIZED))
3832                         rc = mdb_cursor_first(mc, key, data);
3833                 else
3834                         rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3835                 if (rc == MDB_SUCCESS) {
3836                         if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3837                                 MDB_cursor *mx;
3838 fetchm:
3839                                 mx = &mc->mc_xcursor->mx_cursor;
3840                                 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3841                                         mx->mc_db->md_pad;
3842                                 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3843                                 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3844                         } else {
3845                                 rc = MDB_NOTFOUND;
3846                         }
3847                 }
3848                 break;
3849         case MDB_NEXT:
3850         case MDB_NEXT_DUP:
3851         case MDB_NEXT_NODUP:
3852                 if (!(mc->mc_flags & C_INITIALIZED))
3853                         rc = mdb_cursor_first(mc, key, data);
3854                 else
3855                         rc = mdb_cursor_next(mc, key, data, op);
3856                 break;
3857         case MDB_PREV:
3858         case MDB_PREV_DUP:
3859         case MDB_PREV_NODUP:
3860                 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3861                         rc = mdb_cursor_last(mc, key, data);
3862                 else
3863                         rc = mdb_cursor_prev(mc, key, data, op);
3864                 break;
3865         case MDB_FIRST:
3866                 rc = mdb_cursor_first(mc, key, data);
3867                 break;
3868         case MDB_FIRST_DUP:
3869                 if (data == NULL ||
3870                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3871                         !(mc->mc_flags & C_INITIALIZED) ||
3872                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3873                         rc = EINVAL;
3874                         break;
3875                 }
3876                 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3877                 break;
3878         case MDB_LAST:
3879                 rc = mdb_cursor_last(mc, key, data);
3880                 break;
3881         case MDB_LAST_DUP:
3882                 if (data == NULL ||
3883                         !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3884                         !(mc->mc_flags & C_INITIALIZED) ||
3885                         !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3886                         rc = EINVAL;
3887                         break;
3888                 }
3889                 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3890                 break;
3891         default:
3892                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3893                 rc = EINVAL;
3894                 break;
3895         }
3896
3897         return rc;
3898 }
3899
3900 /** Touch all the pages in the cursor stack.
3901  *      Makes sure all the pages are writable, before attempting a write operation.
3902  * @param[in] mc The cursor to operate on.
3903  */
3904 static int
3905 mdb_cursor_touch(MDB_cursor *mc)
3906 {
3907         int rc;
3908
3909         if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3910                 MDB_cursor mc2;
3911                 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3912                 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3913                 if (rc)
3914                          return rc;
3915                 *mc->mc_dbflag = DB_DIRTY;
3916         }
3917         for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3918                 rc = mdb_page_touch(mc);
3919                 if (rc)
3920                         return rc;
3921         }
3922         mc->mc_top = mc->mc_snum-1;
3923         return MDB_SUCCESS;
3924 }
3925
3926 int
3927 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3928     unsigned int flags)
3929 {
3930         MDB_node        *leaf = NULL;
3931         MDB_val xdata, *rdata, dkey;
3932         MDB_page        *fp;
3933         MDB_db dummy;
3934         int do_sub = 0;
3935         unsigned int mcount = 0;
3936         size_t nsize;
3937         int rc, rc2;
3938         char pbuf[MDB_PAGESIZE];
3939         char dbuf[MAXKEYSIZE+1];
3940         unsigned int nflags;
3941         DKBUF;
3942
3943         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3944                 return EACCES;
3945
3946         DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3947                 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3948
3949         dkey.mv_size = 0;
3950
3951         if (flags == MDB_CURRENT) {
3952                 if (!(mc->mc_flags & C_INITIALIZED))
3953                         return EINVAL;
3954                 rc = MDB_SUCCESS;
3955         } else if (mc->mc_db->md_root == P_INVALID) {
3956                 MDB_page *np;
3957                 /* new database, write a root leaf page */
3958                 DPUTS("allocating new root leaf page");
3959                 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3960                         return ENOMEM;
3961                 }
3962                 mc->mc_snum = 0;
3963                 mdb_cursor_push(mc, np);
3964                 mc->mc_db->md_root = np->mp_pgno;
3965                 mc->mc_db->md_depth++;
3966                 *mc->mc_dbflag = DB_DIRTY;
3967                 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3968                         == MDB_DUPFIXED)
3969                         np->mp_flags |= P_LEAF2;
3970                 mc->mc_flags |= C_INITIALIZED;
3971                 rc = MDB_NOTFOUND;
3972                 goto top;
3973         } else {
3974                 int exact = 0;
3975                 MDB_val d2;
3976                 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3977                 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
3978                         DPRINTF("duplicate key [%s]", DKEY(key));
3979                         *data = d2;
3980                         return MDB_KEYEXIST;
3981                 }
3982                 if (rc && rc != MDB_NOTFOUND)
3983                         return rc;
3984         }
3985
3986         /* Cursor is positioned, now make sure all pages are writable */
3987         rc2 = mdb_cursor_touch(mc);
3988         if (rc2)
3989                 return rc2;
3990
3991 top:
3992         /* The key already exists */
3993         if (rc == MDB_SUCCESS) {
3994                 /* there's only a key anyway, so this is a no-op */
3995                 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3996                         unsigned int ksize = mc->mc_db->md_pad;
3997                         if (key->mv_size != ksize)
3998                                 return EINVAL;
3999                         if (flags == MDB_CURRENT) {
4000                                 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4001                                 memcpy(ptr, key->mv_data, ksize);
4002                         }
4003                         return MDB_SUCCESS;
4004                 }
4005
4006                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4007
4008                 /* DB has dups? */
4009                 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4010                         /* Was a single item before, must convert now */
4011 more:
4012                         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4013                                 /* Just overwrite the current item */
4014                                 if (flags == MDB_CURRENT)
4015                                         goto current;
4016
4017                                 dkey.mv_size = NODEDSZ(leaf);
4018                                 dkey.mv_data = NODEDATA(leaf);
4019 #if UINT_MAX < SIZE_MAX
4020                                 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4021 #ifdef MISALIGNED_OK
4022                                         mc->mc_dbx->md_dcmp = mdb_cmp_long;
4023 #else
4024                                         mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4025 #endif
4026 #endif
4027                                 /* if data matches, ignore it */
4028                                 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4029                                         return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4030
4031                                 /* create a fake page for the dup items */
4032                                 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4033                                 dkey.mv_data = dbuf;
4034                                 fp = (MDB_page *)pbuf;
4035                                 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4036                                 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4037                                 fp->mp_lower = PAGEHDRSZ;
4038                                 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4039                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4040                                         fp->mp_flags |= P_LEAF2;
4041                                         fp->mp_pad = data->mv_size;
4042                                 } else {
4043                                         fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4044                                                 (dkey.mv_size & 1) + (data->mv_size & 1);
4045                                 }
4046                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4047                                 do_sub = 1;
4048                                 rdata = &xdata;
4049                                 xdata.mv_size = fp->mp_upper;
4050                                 xdata.mv_data = pbuf;
4051                                 flags |= F_DUPDATA;
4052                                 goto new_sub;
4053                         }
4054                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4055                                 /* See if we need to convert from fake page to subDB */
4056                                 MDB_page *mp;
4057                                 unsigned int offset;
4058                                 unsigned int i;
4059
4060                                 fp = NODEDATA(leaf);
4061                                 if (flags == MDB_CURRENT) {
4062                                         fp->mp_flags |= P_DIRTY;
4063                                         COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4064                                         mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4065                                         flags |= F_DUPDATA;
4066                                         goto put_sub;
4067                                 }
4068                                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4069                                         offset = fp->mp_pad;
4070                                 } else {
4071                                         offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4072                                 }
4073                                 offset += offset & 1;
4074                                 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4075                                         offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4076                                                 MDB_MINKEYS) {
4077                                         /* yes, convert it */
4078                                         dummy.md_flags = 0;
4079                                         if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4080                                                 dummy.md_pad = fp->mp_pad;
4081                                                 dummy.md_flags = MDB_DUPFIXED;
4082                                                 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4083                                                         dummy.md_flags |= MDB_INTEGERKEY;
4084                                         }
4085                                         dummy.md_depth = 1;
4086                                         dummy.md_branch_pages = 0;
4087                                         dummy.md_leaf_pages = 1;
4088                                         dummy.md_overflow_pages = 0;
4089                                         dummy.md_entries = NUMKEYS(fp);
4090                                         rdata = &xdata;
4091                                         xdata.mv_size = sizeof(MDB_db);
4092                                         xdata.mv_data = &dummy;
4093                                         mp = mdb_page_alloc(mc, 1);
4094                                         if (!mp)
4095                                                 return ENOMEM;
4096                                         offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4097                                         flags |= F_DUPDATA|F_SUBDATA;
4098                                         dummy.md_root = mp->mp_pgno;
4099                                 } else {
4100                                         /* no, just grow it */
4101                                         rdata = &xdata;
4102                                         xdata.mv_size = NODEDSZ(leaf) + offset;
4103                                         xdata.mv_data = pbuf;
4104                                         mp = (MDB_page *)pbuf;
4105                                         mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4106                                         flags |= F_DUPDATA;
4107                                 }
4108                                 mp->mp_flags = fp->mp_flags | P_DIRTY;
4109                                 mp->mp_pad   = fp->mp_pad;
4110                                 mp->mp_lower = fp->mp_lower;
4111                                 mp->mp_upper = fp->mp_upper + offset;
4112                                 if (IS_LEAF2(fp)) {
4113                                         memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4114                                 } else {
4115                                         nsize = NODEDSZ(leaf) - fp->mp_upper;
4116                                         memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4117                                         for (i=0; i<NUMKEYS(fp); i++)
4118                                                 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4119                                 }
4120                                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4121                                 do_sub = 1;
4122                                 goto new_sub;
4123                         }
4124                         /* data is on sub-DB, just store it */
4125                         flags |= F_DUPDATA|F_SUBDATA;
4126                         goto put_sub;
4127                 }
4128 current:
4129                 /* same size, just replace it */
4130                 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4131                         NODEDSZ(leaf) == data->mv_size) {
4132                         if (F_ISSET(flags, MDB_RESERVE))
4133                                 data->mv_data = NODEDATA(leaf);
4134                         else
4135                                 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4136                         goto done;
4137                 }
4138                 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4139         } else {
4140                 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4141         }
4142
4143         rdata = data;
4144
4145 new_sub:
4146         nflags = flags & NODE_ADD_FLAGS;
4147         nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4148         if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4149                 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4150                         nflags &= ~MDB_APPEND;
4151                 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4152         } else {
4153                 /* There is room already in this leaf page. */
4154                 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4155                 if (rc == 0 && !do_sub) {
4156                         /* Adjust other cursors pointing to mp */
4157                         MDB_cursor *m2, *m3;
4158                         MDB_dbi dbi = mc->mc_dbi;
4159                         unsigned i = mc->mc_top;
4160                         MDB_page *mp = mc->mc_pg[i];
4161
4162                         if (mc->mc_flags & C_SUB)
4163                                 dbi--;
4164
4165                         for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4166                                 if (mc->mc_flags & C_SUB)
4167                                         m3 = &m2->mc_xcursor->mx_cursor;
4168                                 else
4169                                         m3 = m2;
4170                                 if (m3 == mc) continue;
4171                                 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4172                                         m3->mc_ki[i]++;
4173                                 }
4174                         }
4175                 }
4176         }
4177
4178         if (rc != MDB_SUCCESS)
4179                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4180         else {
4181                 /* Now store the actual data in the child DB. Note that we're
4182                  * storing the user data in the keys field, so there are strict
4183                  * size limits on dupdata. The actual data fields of the child
4184                  * DB are all zero size.
4185                  */
4186                 if (do_sub) {
4187                         MDB_db *db;
4188                         int xflags;
4189 put_sub:
4190                         xdata.mv_size = 0;
4191                         xdata.mv_data = "";
4192                         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4193                         if (flags & MDB_CURRENT) {
4194                                 xflags = MDB_CURRENT;
4195                         } else {
4196                                 mdb_xcursor_init1(mc, leaf);
4197                                 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4198                         }
4199                         /* converted, write the original data first */
4200                         if (dkey.mv_size) {
4201                                 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4202                                 if (rc)
4203                                         return rc;
4204                                 {
4205                                         /* Adjust other cursors pointing to mp */
4206                                         MDB_cursor *m2;
4207                                         unsigned i = mc->mc_top;
4208                                         MDB_page *mp = mc->mc_pg[i];
4209
4210                                         for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4211                                                 if (m2 == mc) continue;
4212                                                 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4213                                                         mdb_xcursor_init1(m2, leaf);
4214                                                 }
4215                                         }
4216                                 }
4217                         }
4218                         xflags |= (flags & MDB_APPEND);
4219                         rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4220                         if (flags & F_SUBDATA) {
4221                                 db = NODEDATA(leaf);
4222                                 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4223                         }
4224                 }
4225                 /* sub-writes might have failed so check rc again.
4226                  * Don't increment count if we just replaced an existing item.
4227                  */
4228                 if (!rc && !(flags & MDB_CURRENT))
4229                         mc->mc_db->md_entries++;
4230                 if (flags & MDB_MULTIPLE) {
4231                         mcount++;
4232                         if (mcount < data[1].mv_size) {
4233                                 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4234                                 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4235                                 goto more;
4236                         }
4237                 }
4238         }
4239 done:
4240         return rc;
4241 }
4242
4243 int
4244 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4245 {
4246         MDB_node        *leaf;
4247         int rc;
4248
4249         if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4250                 return EACCES;
4251
4252         if (!mc->mc_flags & C_INITIALIZED)
4253                 return EINVAL;
4254
4255         rc = mdb_cursor_touch(mc);
4256         if (rc)
4257                 return rc;
4258
4259         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4260
4261         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4262                 if (flags != MDB_NODUPDATA) {
4263                         if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4264                                 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4265                         }
4266                         rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4267                         /* If sub-DB still has entries, we're done */
4268                         if (mc->mc_xcursor->mx_db.md_entries) {
4269                                 if (leaf->mn_flags & F_SUBDATA) {
4270                                         /* update subDB info */
4271                                         MDB_db *db = NODEDATA(leaf);
4272                                         memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4273                                 } else {
4274                                         /* shrink fake page */
4275                                         mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4276                                 }
4277                                 mc->mc_db->md_entries--;
4278                                 return rc;
4279                         }
4280                         /* otherwise fall thru and delete the sub-DB */
4281                 }
4282
4283                 if (leaf->mn_flags & F_SUBDATA) {
4284                         /* add all the child DB's pages to the free list */
4285                         rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4286                         if (rc == MDB_SUCCESS) {
4287                                 mc->mc_db->md_entries -=
4288                                         mc->mc_xcursor->mx_db.md_entries;
4289                         }
4290                 }
4291         }
4292
4293         return mdb_cursor_del0(mc, leaf);
4294 }
4295
4296 /** Allocate and initialize new pages for a database.
4297  * @param[in] mc a cursor on the database being added to.
4298  * @param[in] flags flags defining what type of page is being allocated.
4299  * @param[in] num the number of pages to allocate. This is usually 1,
4300  * unless allocating overflow pages for a large record.
4301  * @return Address of a page, or NULL on failure.
4302  */
4303 static MDB_page *
4304 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4305 {
4306         MDB_page        *np;
4307
4308         if ((np = mdb_page_alloc(mc, num)) == NULL)
4309                 return NULL;
4310         DPRINTF("allocated new mpage %zu, page size %u",
4311             np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4312         np->mp_flags = flags | P_DIRTY;
4313         np->mp_lower = PAGEHDRSZ;
4314         np->mp_upper = mc->mc_txn->mt_env->me_psize;
4315
4316         if (IS_BRANCH(np))
4317                 mc->mc_db->md_branch_pages++;
4318         else if (IS_LEAF(np))
4319                 mc->mc_db->md_leaf_pages++;
4320         else if (IS_OVERFLOW(np)) {
4321                 mc->mc_db->md_overflow_pages += num;
4322                 np->mp_pages = num;
4323         }
4324
4325         return np;
4326 }
4327
4328 /** Calculate the size of a leaf node.
4329  * The size depends on the environment's page size; if a data item
4330  * is too large it will be put onto an overflow page and the node
4331  * size will only include the key and not the data. Sizes are always
4332  * rounded up to an even number of bytes, to guarantee 2-byte alignment
4333  * of the #MDB_node headers.
4334  * @param[in] env The environment handle.
4335  * @param[in] key The key for the node.
4336  * @param[in] data The data for the node.
4337  * @return The number of bytes needed to store the node.
4338  */
4339 static size_t
4340 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4341 {
4342         size_t           sz;
4343
4344         sz = LEAFSIZE(key, data);
4345         if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
4346                 /* put on overflow page */
4347                 sz -= data->mv_size - sizeof(pgno_t);
4348         }
4349         sz += sz & 1;
4350
4351         return sz + sizeof(indx_t);
4352 }
4353
4354 /** Calculate the size of a branch node.
4355  * The size should depend on the environment's page size but since
4356  * we currently don't support spilling large keys onto overflow
4357  * pages, it's simply the size of the #MDB_node header plus the
4358  * size of the key. Sizes are always rounded up to an even number
4359  * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4360  * @param[in] env The environment handle.
4361  * @param[in] key The key for the node.
4362  * @return The number of bytes needed to store the node.
4363  */
4364 static size_t
4365 mdb_branch_size(MDB_env *env, MDB_val *key)
4366 {
4367         size_t           sz;
4368
4369         sz = INDXSIZE(key);
4370         if (sz >= env->me_psize / MDB_MINKEYS) {
4371                 /* put on overflow page */
4372                 /* not implemented */
4373                 /* sz -= key->size - sizeof(pgno_t); */
4374         }
4375
4376         return sz + sizeof(indx_t);
4377 }
4378
4379 /** Add a node to the page pointed to by the cursor.
4380  * @param[in] mc The cursor for this operation.
4381  * @param[in] indx The index on the page where the new node should be added.
4382  * @param[in] key The key for the new node.
4383  * @param[in] data The data for the new node, if any.
4384  * @param[in] pgno The page number, if adding a branch node.
4385  * @param[in] flags Flags for the node.
4386  * @return 0 on success, non-zero on failure. Possible errors are:
4387  * <ul>
4388  *      <li>ENOMEM - failed to allocate overflow pages for the node.
4389  *      <li>ENOSPC - there is insufficient room in the page. This error
4390  *      should never happen since all callers already calculate the
4391  *      page's free space before calling this function.
4392  * </ul>
4393  */
4394 static int
4395 mdb_node_add(MDB_cursor *mc, indx_t indx,
4396     MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4397 {
4398         unsigned int     i;
4399         size_t           node_size = NODESIZE;
4400         indx_t           ofs;
4401         MDB_node        *node;
4402         MDB_page        *mp = mc->mc_pg[mc->mc_top];
4403         MDB_page        *ofp = NULL;            /* overflow page */
4404         DKBUF;
4405
4406         assert(mp->mp_upper >= mp->mp_lower);
4407
4408         DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4409             IS_LEAF(mp) ? "leaf" : "branch",
4410                 IS_SUBP(mp) ? "sub-" : "",
4411             mp->mp_pgno, indx, data ? data->mv_size : 0,
4412                 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4413
4414         if (IS_LEAF2(mp)) {
4415                 /* Move higher keys up one slot. */
4416                 int ksize = mc->mc_db->md_pad, dif;
4417                 char *ptr = LEAF2KEY(mp, indx, ksize);
4418                 dif = NUMKEYS(mp) - indx;
4419                 if (dif > 0)
4420                         memmove(ptr+ksize, ptr, dif*ksize);
4421                 /* insert new key */
4422                 memcpy(ptr, key->mv_data, ksize);
4423
4424                 /* Just using these for counting */
4425                 mp->mp_lower += sizeof(indx_t);
4426                 mp->mp_upper -= ksize - sizeof(indx_t);
4427                 return MDB_SUCCESS;
4428         }
4429
4430         if (key != NULL)
4431                 node_size += key->mv_size;
4432
4433         if (IS_LEAF(mp)) {
4434                 assert(data);
4435                 if (F_ISSET(flags, F_BIGDATA)) {
4436                         /* Data already on overflow page. */
4437                         node_size += sizeof(pgno_t);
4438                 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4439                         int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4440                         /* Put data on overflow page. */
4441                         DPRINTF("data size is %zu, put on overflow page",
4442                             data->mv_size);
4443                         node_size += sizeof(pgno_t);
4444                         if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4445                                 return ENOMEM;
4446                         DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4447                         flags |= F_BIGDATA;
4448                 } else {
4449                         node_size += data->mv_size;
4450                 }
4451         }
4452         node_size += node_size & 1;
4453
4454         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4455                 DPRINTF("not enough room in page %zu, got %u ptrs",
4456                     mp->mp_pgno, NUMKEYS(mp));
4457                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4458                     mp->mp_upper - mp->mp_lower);
4459                 DPRINTF("node size = %zu", node_size);
4460                 return ENOSPC;
4461         }
4462
4463         /* Move higher pointers up one slot. */
4464         for (i = NUMKEYS(mp); i > indx; i--)
4465                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4466
4467         /* Adjust free space offsets. */
4468         ofs = mp->mp_upper - node_size;
4469         assert(ofs >= mp->mp_lower + sizeof(indx_t));
4470         mp->mp_ptrs[indx] = ofs;
4471         mp->mp_upper = ofs;
4472         mp->mp_lower += sizeof(indx_t);
4473
4474         /* Write the node data. */
4475         node = NODEPTR(mp, indx);
4476         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4477         node->mn_flags = flags;
4478         if (IS_LEAF(mp))
4479                 SETDSZ(node,data->mv_size);
4480         else
4481                 SETPGNO(node,pgno);
4482
4483         if (key)
4484                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4485
4486         if (IS_LEAF(mp)) {
4487                 assert(key);
4488                 if (ofp == NULL) {
4489                         if (F_ISSET(flags, F_BIGDATA))
4490                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4491                                     sizeof(pgno_t));
4492                         else if (F_ISSET(flags, MDB_RESERVE))
4493                                 data->mv_data = node->mn_data + key->mv_size;
4494                         else
4495                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
4496                                     data->mv_size);
4497                 } else {
4498                         memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4499                             sizeof(pgno_t));
4500                         if (F_ISSET(flags, MDB_RESERVE))
4501                                 data->mv_data = METADATA(ofp);
4502                         else
4503                                 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4504                 }
4505         }
4506
4507         return MDB_SUCCESS;
4508 }
4509
4510 /** Delete the specified node from a page.
4511  * @param[in] mp The page to operate on.
4512  * @param[in] indx The index of the node to delete.
4513  * @param[in] ksize The size of a node. Only used if the page is
4514  * part of a #MDB_DUPFIXED database.
4515  */
4516 static void
4517 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4518 {
4519         unsigned int     sz;
4520         indx_t           i, j, numkeys, ptr;
4521         MDB_node        *node;
4522         char            *base;
4523
4524 #if MDB_DEBUG
4525         {
4526         pgno_t pgno;
4527         COPY_PGNO(pgno, mp->mp_pgno);
4528         DPRINTF("delete node %u on %s page %zu", indx,
4529             IS_LEAF(mp) ? "leaf" : "branch", pgno);
4530         }
4531 #endif
4532         assert(indx < NUMKEYS(mp));
4533
4534         if (IS_LEAF2(mp)) {
4535                 int x = NUMKEYS(mp) - 1 - indx;
4536                 base = LEAF2KEY(mp, indx, ksize);
4537                 if (x)
4538                         memmove(base, base + ksize, x * ksize);
4539                 mp->mp_lower -= sizeof(indx_t);
4540                 mp->mp_upper += ksize - sizeof(indx_t);
4541                 return;
4542         }
4543
4544         node = NODEPTR(mp, indx);
4545         sz = NODESIZE + node->mn_ksize;
4546         if (IS_LEAF(mp)) {
4547                 if (F_ISSET(node->mn_flags, F_BIGDATA))
4548                         sz += sizeof(pgno_t);
4549                 else
4550                         sz += NODEDSZ(node);
4551         }
4552         sz += sz & 1;
4553
4554         ptr = mp->mp_ptrs[indx];
4555         numkeys = NUMKEYS(mp);
4556         for (i = j = 0; i < numkeys; i++) {
4557                 if (i != indx) {
4558                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
4559                         if (mp->mp_ptrs[i] < ptr)
4560                                 mp->mp_ptrs[j] += sz;
4561                         j++;
4562                 }
4563         }
4564
4565         base = (char *)mp + mp->mp_upper;
4566         memmove(base + sz, base, ptr - mp->mp_upper);
4567
4568         mp->mp_lower -= sizeof(indx_t);
4569         mp->mp_upper += sz;
4570 }
4571
4572 /** Compact the main page after deleting a node on a subpage.
4573  * @param[in] mp The main page to operate on.
4574  * @param[in] indx The index of the subpage on the main page.
4575  */
4576 static void
4577 mdb_node_shrink(MDB_page *mp, indx_t indx)
4578 {
4579         MDB_node *node;
4580         MDB_page *sp, *xp;
4581         char *base;
4582         int osize, nsize;
4583         int delta;
4584         indx_t           i, numkeys, ptr;
4585
4586         node = NODEPTR(mp, indx);
4587         sp = (MDB_page *)NODEDATA(node);
4588         osize = NODEDSZ(node);
4589
4590         delta = sp->mp_upper - sp->mp_lower;
4591         SETDSZ(node, osize - delta);
4592         xp = (MDB_page *)((char *)sp + delta);
4593
4594         /* shift subpage upward */
4595         if (IS_LEAF2(sp)) {
4596                 nsize = NUMKEYS(sp) * sp->mp_pad;
4597                 memmove(METADATA(xp), METADATA(sp), nsize);
4598         } else {
4599                 int i;
4600                 nsize = osize - sp->mp_upper;
4601                 numkeys = NUMKEYS(sp);
4602                 for (i=numkeys-1; i>=0; i--)
4603                         xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4604         }
4605         xp->mp_upper = sp->mp_lower;
4606         xp->mp_lower = sp->mp_lower;
4607         xp->mp_flags = sp->mp_flags;
4608         xp->mp_pad = sp->mp_pad;
4609         COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4610
4611         /* shift lower nodes upward */
4612         ptr = mp->mp_ptrs[indx];
4613         numkeys = NUMKEYS(mp);
4614         for (i = 0; i < numkeys; i++) {
4615                 if (mp->mp_ptrs[i] <= ptr)
4616                         mp->mp_ptrs[i] += delta;
4617         }
4618
4619         base = (char *)mp + mp->mp_upper;
4620         memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4621         mp->mp_upper += delta;
4622 }
4623
4624 /** Initial setup of a sorted-dups cursor.
4625  * Sorted duplicates are implemented as a sub-database for the given key.
4626  * The duplicate data items are actually keys of the sub-database.
4627  * Operations on the duplicate data items are performed using a sub-cursor
4628  * initialized when the sub-database is first accessed. This function does
4629  * the preliminary setup of the sub-cursor, filling in the fields that
4630  * depend only on the parent DB.
4631  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4632  */
4633 static void
4634 mdb_xcursor_init0(MDB_cursor *mc)
4635 {
4636         MDB_xcursor *mx = mc->mc_xcursor;
4637
4638         mx->mx_cursor.mc_xcursor = NULL;
4639         mx->mx_cursor.mc_txn = mc->mc_txn;
4640         mx->mx_cursor.mc_db = &mx->mx_db;
4641         mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4642         mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4643         mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4644         mx->mx_cursor.mc_snum = 0;
4645         mx->mx_cursor.mc_flags = C_SUB;
4646         mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4647         mx->mx_dbx.md_dcmp = NULL;
4648         mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4649 }
4650
4651 /** Final setup of a sorted-dups cursor.
4652  *      Sets up the fields that depend on the data from the main cursor.
4653  * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4654  * @param[in] node The data containing the #MDB_db record for the
4655  * sorted-dup database.
4656  */
4657 static void
4658 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4659 {
4660         MDB_xcursor *mx = mc->mc_xcursor;
4661
4662         if (node->mn_flags & F_SUBDATA) {
4663                 MDB_db *db = NODEDATA(node);
4664                 mx->mx_db = *db;
4665                 mx->mx_cursor.mc_snum = 0;
4666                 mx->mx_cursor.mc_flags = C_SUB;
4667         } else {
4668                 MDB_page *fp = NODEDATA(node);
4669                 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4670                 mx->mx_db.md_flags = 0;
4671                 mx->mx_db.md_depth = 1;
4672                 mx->mx_db.md_branch_pages = 0;
4673                 mx->mx_db.md_leaf_pages = 1;
4674                 mx->mx_db.md_overflow_pages = 0;
4675                 mx->mx_db.md_entries = NUMKEYS(fp);
4676                 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4677                 mx->mx_cursor.mc_snum = 1;
4678                 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4679                 mx->mx_cursor.mc_top = 0;
4680                 mx->mx_cursor.mc_pg[0] = fp;
4681                 mx->mx_cursor.mc_ki[0] = 0;
4682                 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4683                         mx->mx_db.md_flags = MDB_DUPFIXED;
4684                         mx->mx_db.md_pad = fp->mp_pad;
4685                         if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4686                                 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4687                 }
4688         }
4689         DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4690                 mx->mx_db.md_root);
4691         mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4692                 DB_DIRTY : 0;
4693         mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4694         mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4695 #if UINT_MAX < SIZE_MAX
4696         if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4697 #ifdef MISALIGNED_OK
4698                 mx->mx_dbx.md_cmp = mdb_cmp_long;
4699 #else
4700                 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4701 #endif
4702 #endif
4703 }
4704
4705 /** Initialize a cursor for a given transaction and database. */
4706 static void
4707 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4708 {
4709         mc->mc_orig = NULL;
4710         mc->mc_dbi = dbi;
4711         mc->mc_txn = txn;
4712         mc->mc_db = &txn->mt_dbs[dbi];
4713         mc->mc_dbx = &txn->mt_dbxs[dbi];
4714         mc->mc_dbflag = &txn->mt_dbflags[dbi];
4715         mc->mc_snum = 0;
4716         mc->mc_flags = 0;
4717         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4718                 assert(mx != NULL);
4719                 mc->mc_xcursor = mx;
4720                 mdb_xcursor_init0(mc);
4721         } else {
4722                 mc->mc_xcursor = NULL;
4723         }
4724 }
4725
4726 int
4727 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4728 {
4729         MDB_cursor      *mc;
4730         MDB_xcursor     *mx = NULL;
4731         size_t size = sizeof(MDB_cursor);
4732
4733         if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4734                 return EINVAL;
4735
4736         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4737                 size += sizeof(MDB_xcursor);
4738
4739         if ((mc = malloc(size)) != NULL) {
4740                 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4741                         mx = (MDB_xcursor *)(mc + 1);
4742                 }
4743                 mdb_cursor_init(mc, txn, dbi, mx);
4744                 if (txn->mt_cursors) {
4745                         mc->mc_next = txn->mt_cursors[dbi];
4746                         txn->mt_cursors[dbi] = mc;
4747                 }
4748                 mc->mc_flags |= C_ALLOCD;
4749         } else {
4750                 return ENOMEM;
4751         }
4752
4753         *ret = mc;
4754
4755         return MDB_SUCCESS;
4756 }
4757
4758 /* Return the count of duplicate data items for the current key */
4759 int
4760 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4761 {
4762         MDB_node        *leaf;
4763
4764         if (mc == NULL || countp == NULL)
4765                 return EINVAL;
4766
4767         if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4768                 return EINVAL;
4769
4770         leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4771         if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4772                 *countp = 1;
4773         } else {
4774                 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4775                         return EINVAL;
4776
4777                 *countp = mc->mc_xcursor->mx_db.md_entries;
4778         }
4779         return MDB_SUCCESS;
4780 }
4781
4782 void
4783 mdb_cursor_close(MDB_cursor *mc)
4784 {
4785         if (mc != NULL) {
4786                 /* remove from txn, if tracked */
4787                 if (mc->mc_txn->mt_cursors) {
4788                         MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4789                         while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4790                         if (*prev == mc)
4791                                 *prev = mc->mc_next;
4792                 }
4793                 if (mc->mc_flags & C_ALLOCD)
4794                         free(mc);
4795         }
4796 }
4797
4798 MDB_txn *
4799 mdb_cursor_txn(MDB_cursor *mc)
4800 {
4801         if (!mc) return NULL;
4802         return mc->mc_txn;
4803 }
4804
4805 MDB_dbi
4806 mdb_cursor_dbi(MDB_cursor *mc)
4807 {
4808         if (!mc) return 0;
4809         return mc->mc_dbi;
4810 }
4811
4812 /** Replace the key for a node with a new key.
4813  * @param[in] mp The page containing the node to operate on.
4814  * @param[in] indx The index of the node to operate on.
4815  * @param[in] key The new key to use.
4816  * @return 0 on success, non-zero on failure.
4817  */
4818 static int
4819 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4820 {
4821         indx_t                   ptr, i, numkeys;
4822         int                      delta;
4823         size_t                   len;
4824         MDB_node                *node;
4825         char                    *base;
4826         DKBUF;
4827
4828         node = NODEPTR(mp, indx);
4829         ptr = mp->mp_ptrs[indx];
4830         DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4831             indx, ptr,
4832             (int)node->mn_ksize, (char *)NODEKEY(node),
4833                 DKEY(key),
4834             mp->mp_pgno);
4835
4836         delta = key->mv_size - node->mn_ksize;
4837         if (delta) {
4838                 if (delta > 0 && SIZELEFT(mp) < delta) {
4839                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
4840                         return ENOSPC;
4841                 }
4842
4843                 numkeys = NUMKEYS(mp);
4844                 for (i = 0; i < numkeys; i++) {
4845                         if (mp->mp_ptrs[i] <= ptr)
4846                                 mp->mp_ptrs[i] -= delta;
4847                 }
4848
4849                 base = (char *)mp + mp->mp_upper;
4850                 len = ptr - mp->mp_upper + NODESIZE;
4851                 memmove(base - delta, base, len);
4852                 mp->mp_upper -= delta;
4853
4854                 node = NODEPTR(mp, indx);
4855                 node->mn_ksize = key->mv_size;
4856         }
4857
4858         memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4859
4860         return MDB_SUCCESS;
4861 }
4862
4863 /** Move a node from csrc to cdst.
4864  */
4865 static int
4866 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4867 {
4868         int                      rc;
4869         MDB_node                *srcnode;
4870         MDB_val          key, data;
4871         DKBUF;
4872
4873         /* Mark src and dst as dirty. */
4874         if ((rc = mdb_page_touch(csrc)) ||
4875             (rc = mdb_page_touch(cdst)))
4876                 return rc;
4877
4878         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4879                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);        /* fake */
4880                 key.mv_size = csrc->mc_db->md_pad;
4881                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4882                 data.mv_size = 0;
4883                 data.mv_data = NULL;
4884         } else {
4885                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4886                 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4887                         unsigned int snum = csrc->mc_snum;
4888                         MDB_node *s2;
4889                         /* must find the lowest key below src */
4890                         mdb_page_search_root(csrc, NULL, 0);
4891                         s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4892                         key.mv_size = NODEKSZ(s2);
4893                         key.mv_data = NODEKEY(s2);
4894                         csrc->mc_snum = snum--;
4895                         csrc->mc_top = snum;
4896                 } else {
4897                         key.mv_size = NODEKSZ(srcnode);
4898                         key.mv_data = NODEKEY(srcnode);
4899                 }
4900                 data.mv_size = NODEDSZ(srcnode);
4901                 data.mv_data = NODEDATA(srcnode);
4902         }
4903         DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4904             IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4905             csrc->mc_ki[csrc->mc_top],
4906                 DKEY(&key),
4907             csrc->mc_pg[csrc->mc_top]->mp_pgno,
4908             cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4909
4910         /* Add the node to the destination page.
4911          */
4912         rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4913             srcnode->mn_flags);
4914         if (rc != MDB_SUCCESS)
4915                 return rc;
4916
4917         /* Delete the node from the source page.
4918          */
4919         mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4920
4921         {
4922                 /* Adjust other cursors pointing to mp */
4923                 MDB_cursor *m2, *m3;
4924                 MDB_dbi dbi = csrc->mc_dbi;
4925                 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4926
4927                 if (csrc->mc_flags & C_SUB)
4928                         dbi--;
4929
4930                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4931                         if (m2 == csrc) continue;
4932                         if (csrc->mc_flags & C_SUB)
4933                                 m3 = &m2->mc_xcursor->mx_cursor;
4934                         else
4935                                 m3 = m2;
4936                         if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4937                                 csrc->mc_ki[csrc->mc_top]) {
4938                                 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4939                                 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4940                         }
4941                 }
4942         }
4943
4944         /* Update the parent separators.
4945          */
4946         if (csrc->mc_ki[csrc->mc_top] == 0) {
4947                 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4948                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4949                                 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4950                         } else {
4951                                 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4952                                 key.mv_size = NODEKSZ(srcnode);
4953                                 key.mv_data = NODEKEY(srcnode);
4954                         }
4955                         DPRINTF("update separator for source page %zu to [%s]",
4956                                 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4957                         if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4958                                 &key)) != MDB_SUCCESS)
4959                                 return rc;
4960                 }
4961                 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4962                         MDB_val  nullkey;
4963                         nullkey.mv_size = 0;
4964                         rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
4965                         assert(rc == MDB_SUCCESS);
4966                 }
4967         }
4968
4969         if (cdst->mc_ki[cdst->mc_top] == 0) {
4970                 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4971                         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4972                                 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4973                         } else {
4974                                 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4975                                 key.mv_size = NODEKSZ(srcnode);
4976                                 key.mv_data = NODEKEY(srcnode);
4977                         }
4978                         DPRINTF("update separator for destination page %zu to [%s]",
4979                                 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4980                         if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4981                                 &key)) != MDB_SUCCESS)
4982                                 return rc;
4983                 }
4984                 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4985                         MDB_val  nullkey;
4986                         nullkey.mv_size = 0;
4987                         rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
4988                         assert(rc == MDB_SUCCESS);
4989                 }
4990         }
4991
4992         return MDB_SUCCESS;
4993 }
4994
4995 /** Merge one page into another.
4996  *  The nodes from the page pointed to by \b csrc will
4997  *      be copied to the page pointed to by \b cdst and then
4998  *      the \b csrc page will be freed.
4999  * @param[in] csrc Cursor pointing to the source page.
5000  * @param[in] cdst Cursor pointing to the destination page.
5001  */
5002 static int
5003 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5004 {
5005         int                      rc;
5006         indx_t                   i, j;
5007         MDB_node                *srcnode;
5008         MDB_val          key, data;
5009         unsigned        nkeys;
5010
5011         DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5012                 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5013
5014         assert(csrc->mc_snum > 1);      /* can't merge root page */
5015         assert(cdst->mc_snum > 1);
5016
5017         /* Mark dst as dirty. */
5018         if ((rc = mdb_page_touch(cdst)))
5019                 return rc;
5020
5021         /* Move all nodes from src to dst.
5022          */
5023         j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5024         if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5025                 key.mv_size = csrc->mc_db->md_pad;
5026                 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5027                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5028                         rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5029                         if (rc != MDB_SUCCESS)
5030                                 return rc;
5031                         key.mv_data = (char *)key.mv_data + key.mv_size;
5032                 }
5033         } else {
5034                 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5035                         srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5036
5037                         key.mv_size = srcnode->mn_ksize;
5038                         key.mv_data = NODEKEY(srcnode);
5039                         data.mv_size = NODEDSZ(srcnode);
5040                         data.mv_data = NODEDATA(srcnode);
5041                         rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5042                         if (rc != MDB_SUCCESS)
5043                                 return rc;
5044                 }
5045         }
5046
5047         DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5048             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);
5049
5050         /* Unlink the src page from parent and add to free list.
5051          */
5052         mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5053         if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5054                 key.mv_size = 0;
5055                 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5056                         return rc;
5057         }
5058
5059         mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5060         if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5061                 csrc->mc_db->md_leaf_pages--;
5062         else
5063                 csrc->mc_db->md_branch_pages--;
5064         {
5065                 /* Adjust other cursors pointing to mp */
5066                 MDB_cursor *m2, *m3;
5067                 MDB_dbi dbi = csrc->mc_dbi;
5068                 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5069
5070                 if (csrc->mc_flags & C_SUB)
5071                         dbi--;
5072
5073                 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5074                         if (m2 == csrc) continue;
5075                         if (csrc->mc_flags & C_SUB)
5076                                 m3 = &m2->mc_xcursor->mx_cursor;
5077                         else
5078                                 m3 = m2;
5079                         if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5080                                 m3->mc_pg[csrc->mc_top] = mp;
5081                                 m3->mc_ki[csrc->mc_top] += nkeys;
5082                         }
5083                 }
5084         }
5085         mdb_cursor_pop(csrc);
5086
5087         return mdb_rebalance(csrc);
5088 }
5089
5090 /** Copy the contents of a cursor.
5091  * @param[in] csrc The cursor to copy from.
5092  * @param[out] cdst The cursor to copy to.
5093  */
5094 static void
5095 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5096 {
5097         unsigned int i;
5098
5099         cdst->mc_txn = csrc->mc_txn;
5100         cdst->mc_dbi = csrc->mc_dbi;
5101         cdst->mc_db  = csrc->mc_db;
5102         cdst->mc_dbx = csrc->mc_dbx;
5103         cdst->mc_snum = csrc->mc_snum;
5104         cdst->mc_top = csrc->mc_top;
5105         cdst->mc_flags = csrc->mc_flags;
5106
5107         for (i=0; i<csrc->mc_snum; i++) {
5108                 cdst->mc_pg[i] = csrc->mc_pg[i];
5109                 cdst->mc_ki[i] = csrc->mc_ki[i];
5110         }
5111 }
5112
5113 /** Rebalance the tree after a delete operation.
5114  * @param[in] mc Cursor pointing to the page where rebalancing
5115  * should begin.
5116  * @return 0 on success, non-zero on failure.
5117  */
5118 static int
5119 mdb_rebalance(MDB_cursor *mc)
5120 {
5121         MDB_node        *node;
5122         int rc;
5123         unsigned int ptop;
5124         MDB_cursor      mn;
5125
5126 #if MDB_DEBUG
5127         {
5128         pgno_t pgno;
5129         COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5130         DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5131             IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5132             pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5133         }
5134 #endif
5135
5136         if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5137 #if MDB_DEBUG
5138                 pgno_t pgno;
5139                 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5140                 DPRINTF("no need to rebalance page %zu, above fill threshold",
5141                     pgno);
5142 #endif
5143                 return MDB_SUCCESS;
5144         }
5145
5146         if (mc->mc_snum < 2) {
5147                 MDB_page *mp = mc->mc_pg[0];
5148                 if (NUMKEYS(mp) == 0) {
5149                         DPUTS("tree is completely empty");
5150                         mc->mc_db->md_root = P_INVALID;
5151                         mc->mc_db->md_depth = 0;
5152                         mc->mc_db->md_leaf_pages = 0;
5153                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5154                         mc->mc_snum = 0;
5155                         mc->mc_top = 0;
5156                         {
5157                                 /* Adjust other cursors pointing to mp */
5158                                 MDB_cursor *m2, *m3;
5159                                 MDB_dbi dbi = mc->mc_dbi;
5160
5161                                 if (mc->mc_flags & C_SUB)
5162                                         dbi--;
5163
5164                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5165                                         if (m2 == mc) continue;
5166                                         if (mc->mc_flags & C_SUB)
5167                                                 m3 = &m2->mc_xcursor->mx_cursor;
5168                                         else
5169                                                 m3 = m2;
5170                                         if (m3->mc_pg[0] == mp) {
5171                                                 m3->mc_snum = 0;
5172                                                 m3->mc_top = 0;
5173                                         }
5174                                 }
5175                         }
5176                 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5177                         DPUTS("collapsing root page!");
5178                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5179                         mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5180                         if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5181                                 &mc->mc_pg[0])))
5182                                 return rc;
5183                         mc->mc_db->md_depth--;
5184                         mc->mc_db->md_branch_pages--;
5185                         {
5186                                 /* Adjust other cursors pointing to mp */
5187                                 MDB_cursor *m2, *m3;
5188                                 MDB_dbi dbi = mc->mc_dbi;
5189
5190                                 if (mc->mc_flags & C_SUB)
5191                                         dbi--;
5192
5193                                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5194                                         if (m2 == mc) continue;
5195                                         if (mc->mc_flags & C_SUB)
5196                                                 m3 = &m2->mc_xcursor->mx_cursor;
5197                                         else
5198                                                 m3 = m2;
5199                                         if (m3->mc_pg[0] == mp) {
5200                                                 m3->mc_pg[0] = mc->mc_pg[0];
5201                                         }
5202                                 }
5203                         }
5204                 } else
5205                         DPUTS("root page doesn't need rebalancing");
5206                 return MDB_SUCCESS;
5207         }
5208
5209         /* The parent (branch page) must have at least 2 pointers,
5210          * otherwise the tree is invalid.
5211          */
5212         ptop = mc->mc_top-1;
5213         assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5214
5215         /* Leaf page fill factor is below the threshold.
5216          * Try to move keys from left or right neighbor, or
5217          * merge with a neighbor page.
5218          */
5219
5220         /* Find neighbors.
5221          */
5222         mdb_cursor_copy(mc, &mn);
5223         mn.mc_xcursor = NULL;
5224
5225         if (mc->mc_ki[ptop] == 0) {
5226                 /* We're the leftmost leaf in our parent.
5227                  */
5228                 DPUTS("reading right neighbor");
5229                 mn.mc_ki[ptop]++;
5230                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5231                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5232                         return rc;
5233                 mn.mc_ki[mn.mc_top] = 0;
5234                 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5235         } else {
5236                 /* There is at least one neighbor to the left.
5237                  */
5238                 DPUTS("reading left neighbor");
5239                 mn.mc_ki[ptop]--;
5240                 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5241                 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5242                         return rc;
5243                 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5244                 mc->mc_ki[mc->mc_top] = 0;
5245         }
5246
5247         DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5248             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);
5249
5250         /* If the neighbor page is above threshold and has at least two
5251          * keys, move one key from it.
5252          *
5253          * Otherwise we should try to merge them.
5254          */
5255         if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5256                 return mdb_node_move(&mn, mc);
5257         else { /* FIXME: if (has_enough_room()) */
5258                 mc->mc_flags &= ~C_INITIALIZED;
5259                 if (mc->mc_ki[ptop] == 0)
5260                         return mdb_page_merge(&mn, mc);
5261                 else
5262                         return mdb_page_merge(mc, &mn);
5263         }
5264 }
5265
5266 /** Complete a delete operation started by #mdb_cursor_del(). */
5267 static int
5268 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5269 {
5270         int rc;
5271
5272         /* add overflow pages to free list */
5273         if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5274                 int i, ovpages;
5275                 pgno_t pg;
5276
5277                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5278                 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5279                 for (i=0; i<ovpages; i++) {
5280                         DPRINTF("freed ov page %zu", pg);
5281                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5282                         pg++;
5283                 }
5284         }
5285         mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5286         mc->mc_db->md_entries--;
5287         rc = mdb_rebalance(mc);
5288         if (rc != MDB_SUCCESS)
5289                 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5290
5291         return rc;
5292 }
5293
5294 int
5295 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5296     MDB_val *key, MDB_val *data)
5297 {
5298         MDB_cursor mc;
5299         MDB_xcursor mx;
5300         MDB_cursor_op op;
5301         MDB_val rdata, *xdata;
5302         int              rc, exact;
5303         DKBUF;
5304
5305         assert(key != NULL);
5306
5307         DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5308
5309         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5310                 return EINVAL;
5311
5312         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5313                 return EACCES;
5314         }
5315
5316         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5317                 return EINVAL;
5318         }
5319
5320         mdb_cursor_init(&mc, txn, dbi, &mx);
5321
5322         exact = 0;
5323         if (data) {
5324                 op = MDB_GET_BOTH;
5325                 rdata = *data;
5326                 xdata = &rdata;
5327         } else {
5328                 op = MDB_SET;
5329                 xdata = NULL;
5330         }
5331         rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5332         if (rc == 0)
5333                 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5334         return rc;
5335 }
5336
5337 /** Split a page and insert a new node.
5338  * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5339  * The cursor will be updated to point to the actual page and index where
5340  * the node got inserted after the split.
5341  * @param[in] newkey The key for the newly inserted node.
5342  * @param[in] newdata The data for the newly inserted node.
5343  * @param[in] newpgno The page number, if the new node is a branch node.
5344  * @return 0 on success, non-zero on failure.
5345  */
5346 static int
5347 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5348         unsigned int nflags)
5349 {
5350         unsigned int flags;
5351         int              rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5352         indx_t           newindx;
5353         pgno_t           pgno = 0;
5354         unsigned int     i, j, split_indx, nkeys, pmax;
5355         MDB_node        *node;
5356         MDB_val  sepkey, rkey, xdata, *rdata = &xdata;
5357         MDB_page        *copy;
5358         MDB_page        *mp, *rp, *pp;
5359         unsigned int ptop;
5360         MDB_cursor      mn;
5361         DKBUF;
5362
5363         mp = mc->mc_pg[mc->mc_top];
5364         newindx = mc->mc_ki[mc->mc_top];
5365
5366         DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5367             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5368             DKEY(newkey), mc->mc_ki[mc->mc_top]);
5369
5370         if (mc->mc_snum < 2) {
5371                 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5372                         return ENOMEM;
5373                 /* shift current top to make room for new parent */
5374                 mc->mc_pg[1] = mc->mc_pg[0];
5375                 mc->mc_ki[1] = mc->mc_ki[0];
5376                 mc->mc_pg[0] = pp;
5377                 mc->mc_ki[0] = 0;
5378                 mc->mc_db->md_root = pp->mp_pgno;
5379                 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5380                 mc->mc_db->md_depth++;
5381                 new_root = 1;
5382
5383                 /* Add left (implicit) pointer. */
5384                 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5385                         /* undo the pre-push */
5386                         mc->mc_pg[0] = mc->mc_pg[1];
5387                         mc->mc_ki[0] = mc->mc_ki[1];
5388                         mc->mc_db->md_root = mp->mp_pgno;
5389                         mc->mc_db->md_depth--;
5390                         return rc;
5391                 }
5392                 mc->mc_snum = 2;
5393                 mc->mc_top = 1;
5394                 ptop = 0;
5395         } else {
5396                 ptop = mc->mc_top-1;
5397                 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5398         }
5399
5400         /* Create a right sibling. */
5401         if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5402                 return ENOMEM;
5403         DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5404
5405         mdb_cursor_copy(mc, &mn);
5406         mn.mc_pg[mn.mc_top] = rp;
5407         mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5408
5409         if (nflags & MDB_APPEND) {
5410                 mn.mc_ki[mn.mc_top] = 0;
5411                 sepkey = *newkey;
5412                 nkeys = 0;
5413                 split_indx = 0;
5414                 goto newsep;
5415         }
5416
5417         nkeys = NUMKEYS(mp);
5418         split_indx = nkeys / 2 + 1;
5419
5420         if (IS_LEAF2(rp)) {
5421                 char *split, *ins;
5422                 int x;
5423                 unsigned int lsize, rsize, ksize;
5424                 /* Move half of the keys to the right sibling */
5425                 copy = NULL;
5426                 x = mc->mc_ki[mc->mc_top] - split_indx;
5427                 ksize = mc->mc_db->md_pad;
5428                 split = LEAF2KEY(mp, split_indx, ksize);
5429                 rsize = (nkeys - split_indx) * ksize;
5430                 lsize = (nkeys - split_indx) * sizeof(indx_t);
5431                 mp->mp_lower -= lsize;
5432                 rp->mp_lower += lsize;
5433                 mp->mp_upper += rsize - lsize;
5434                 rp->mp_upper -= rsize - lsize;
5435                 sepkey.mv_size = ksize;
5436                 if (newindx == split_indx) {
5437                         sepkey.mv_data = newkey->mv_data;
5438                 } else {
5439                         sepkey.mv_data = split;
5440                 }
5441                 if (x<0) {
5442                         ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5443                         memcpy(rp->mp_ptrs, split, rsize);
5444                         sepkey.mv_data = rp->mp_ptrs;
5445                         memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5446                         memcpy(ins, newkey->mv_data, ksize);
5447                         mp->mp_lower += sizeof(indx_t);
5448                         mp->mp_upper -= ksize - sizeof(indx_t);
5449                 } else {
5450                         if (x)
5451                                 memcpy(rp->mp_ptrs, split, x * ksize);
5452                         ins = LEAF2KEY(rp, x, ksize);
5453                         memcpy(ins, newkey->mv_data, ksize);
5454                         memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5455                         rp->mp_lower += sizeof(indx_t);
5456                         rp->mp_upper -= ksize - sizeof(indx_t);
5457                         mc->mc_ki[mc->mc_top] = x;
5458                         mc->mc_pg[mc->mc_top] = rp;
5459                 }
5460                 goto newsep;
5461         }
5462
5463         /* For leaf pages, check the split point based on what
5464          * fits where, since otherwise add_node can fail.
5465          */
5466         if (IS_LEAF(mp)) {
5467                 unsigned int psize, nsize;
5468                 /* Maximum free space in an empty page */
5469                 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5470                 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5471                 if (newindx < split_indx) {
5472                         psize = nsize;
5473                         for (i=0; i<split_indx; i++) {
5474                                 node = NODEPTR(mp, i);
5475                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5476                                 if (F_ISSET(node->mn_flags, F_BIGDATA))
5477                                         psize += sizeof(pgno_t);
5478                                 else
5479                                         psize += NODEDSZ(node);
5480                                 psize += psize & 1;
5481                                 if (psize > pmax) {
5482                                         split_indx = i;
5483                                         break;
5484                                 }
5485                         }
5486                 } else {
5487                         psize = nsize;
5488                         for (i=nkeys-1; i>=split_indx; i--) {
5489                                 node = NODEPTR(mp, i);
5490                                 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5491                                 if (F_ISSET(node->mn_flags, F_BIGDATA))
5492                                         psize += sizeof(pgno_t);
5493                                 else
5494                                         psize += NODEDSZ(node);
5495                                 psize += psize & 1;
5496                                 if (psize > pmax) {
5497                                         split_indx = i+1;
5498                                         break;
5499                                 }
5500                         }
5501                 }
5502         }
5503
5504         /* First find the separating key between the split pages.
5505          */
5506         if (newindx == split_indx) {
5507                 sepkey.mv_size = newkey->mv_size;
5508                 sepkey.mv_data = newkey->mv_data;
5509         } else {
5510                 node = NODEPTR(mp, split_indx);
5511                 sepkey.mv_size = node->mn_ksize;
5512                 sepkey.mv_data = NODEKEY(node);
5513         }
5514
5515 newsep:
5516         DPRINTF("separator is [%s]", DKEY(&sepkey));
5517
5518         /* Copy separator key to the parent.
5519          */
5520         if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5521                 mn.mc_snum--;
5522                 mn.mc_top--;
5523                 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5524
5525                 /* Right page might now have changed parent.
5526                  * Check if left page also changed parent.
5527                  */
5528                 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5529                     mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5530                         mc->mc_pg[ptop] = mn.mc_pg[ptop];
5531                         mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5532                 }
5533         } else {
5534                 mn.mc_top--;
5535                 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5536                 mn.mc_top++;
5537         }
5538         if (rc != MDB_SUCCESS) {
5539                 return rc;
5540         }
5541         if (nflags & MDB_APPEND) {
5542                 mc->mc_pg[mc->mc_top] = rp;
5543                 mc->mc_ki[mc->mc_top] = 0;
5544                 return mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5545         }
5546         if (IS_LEAF2(rp)) {
5547                 goto done;
5548         }
5549
5550         /* Move half of the keys to the right sibling. */
5551
5552         /* grab a page to hold a temporary copy */
5553         copy = mdb_page_malloc(mc);
5554         if (copy == NULL)
5555                 return ENOMEM;
5556
5557         copy->mp_pgno  = mp->mp_pgno;
5558         copy->mp_flags = mp->mp_flags;
5559         copy->mp_lower = PAGEHDRSZ;
5560         copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5561         mc->mc_pg[mc->mc_top] = copy;
5562         for (i = j = 0; i <= nkeys; j++) {
5563                 if (i == split_indx) {
5564                 /* Insert in right sibling. */
5565                 /* Reset insert index for right sibling. */
5566                         j = (i == newindx && ins_new);
5567                         mc->mc_pg[mc->mc_top] = rp;
5568                 }
5569
5570                 if (i == newindx && !ins_new) {
5571                         /* Insert the original entry that caused the split. */
5572                         rkey.mv_data = newkey->mv_data;
5573                         rkey.mv_size = newkey->mv_size;
5574                         if (IS_LEAF(mp)) {
5575                                 rdata = newdata;
5576                         } else
5577                                 pgno = newpgno;
5578                         flags = nflags;
5579
5580                         ins_new = 1;
5581
5582                         /* Update page and index for the new key. */
5583                         mc->mc_ki[mc->mc_top] = j;
5584                 } else if (i == nkeys) {
5585                         break;
5586                 } else {
5587                         node = NODEPTR(mp, i);
5588                         rkey.mv_data = NODEKEY(node);
5589                         rkey.mv_size = node->mn_ksize;
5590                         if (IS_LEAF(mp)) {
5591                                 xdata.mv_data = NODEDATA(node);
5592                                 xdata.mv_size = NODEDSZ(node);
5593                                 rdata = &xdata;
5594                         } else
5595                                 pgno = NODEPGNO(node);
5596                         flags = node->mn_flags;
5597
5598                         i++;
5599                 }
5600
5601                 if (!IS_LEAF(mp) && j == 0) {
5602                         /* First branch index doesn't need key data. */
5603                         rkey.mv_size = 0;
5604                 }
5605
5606                 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5607         }
5608
5609         nkeys = NUMKEYS(copy);
5610         for (i=0; i<nkeys; i++)
5611                 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5612         mp->mp_lower = copy->mp_lower;
5613         mp->mp_upper = copy->mp_upper;
5614         memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5615                 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5616
5617         /* reset back to original page */
5618         if (newindx < split_indx) {
5619                 mc->mc_pg[mc->mc_top] = mp;
5620                 if (nflags & MDB_RESERVE) {
5621                         node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5622                         if (!(node->mn_flags & F_BIGDATA))
5623                                 newdata->mv_data = NODEDATA(node);
5624                 }
5625         }
5626
5627         /* return tmp page to freelist */
5628         copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5629         mc->mc_txn->mt_env->me_dpages = copy;
5630 done:
5631         {
5632                 /* Adjust other cursors pointing to mp */
5633                 MDB_cursor *m2, *m3;
5634                 MDB_dbi dbi = mc->mc_dbi;
5635
5636                 if (mc->mc_flags & C_SUB)
5637                         dbi--;
5638
5639                 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5640                         if (m2 == mc) continue;
5641                         if (mc->mc_flags & C_SUB)
5642                                 m3 = &m2->mc_xcursor->mx_cursor;
5643                         else
5644                                 m3 = m2;
5645                         if (!(m3->mc_flags & C_INITIALIZED))
5646                                 continue;
5647                         if (new_root) {
5648                                 /* root split */
5649                                 for (i=m3->mc_top; i>0; i--) {
5650                                         m3->mc_ki[i+1] = m3->mc_ki[i];
5651                                         m3->mc_pg[i+1] = m3->mc_pg[i];
5652                                 }
5653                                 m3->mc_ki[0] = mc->mc_ki[0];
5654                                 m3->mc_pg[0] = mc->mc_pg[0];
5655                                 m3->mc_snum++;
5656                                 m3->mc_top++;
5657                         }
5658                         if (m3->mc_pg[mc->mc_top] == mp) {
5659                                 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5660                                         m3->mc_pg[m3->mc_top] = rp;
5661                                         m3->mc_ki[m3->mc_top] -= split_indx;
5662                                 }
5663                         }
5664                 }
5665         }
5666         return rc;
5667 }
5668
5669 int
5670 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5671     MDB_val *key, MDB_val *data, unsigned int flags)
5672 {
5673         MDB_cursor mc;
5674         MDB_xcursor mx;
5675
5676         assert(key != NULL);
5677         assert(data != NULL);
5678
5679         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5680                 return EINVAL;
5681
5682         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5683                 return EACCES;
5684         }
5685
5686         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5687                 return EINVAL;
5688         }
5689
5690         if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5691                 return EINVAL;
5692
5693         mdb_cursor_init(&mc, txn, dbi, &mx);
5694         return mdb_cursor_put(&mc, key, data, flags);
5695 }
5696
5697 /** Only a subset of the @ref mdb_env flags can be changed
5698  *      at runtime. Changing other flags requires closing the environment
5699  *      and re-opening it with the new flags.
5700  */
5701 #define CHANGEABLE      (MDB_NOSYNC)
5702 int
5703 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5704 {
5705         if ((flag & CHANGEABLE) != flag)
5706                 return EINVAL;
5707         if (onoff)
5708                 env->me_flags |= flag;
5709         else
5710                 env->me_flags &= ~flag;
5711         return MDB_SUCCESS;
5712 }
5713
5714 int
5715 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5716 {
5717         if (!env || !arg)
5718                 return EINVAL;
5719
5720         *arg = env->me_flags;
5721         return MDB_SUCCESS;
5722 }
5723
5724 int
5725 mdb_env_get_path(MDB_env *env, const char **arg)
5726 {
5727         if (!env || !arg)
5728                 return EINVAL;
5729
5730         *arg = env->me_path;
5731         return MDB_SUCCESS;
5732 }
5733
5734 /** Common code for #mdb_stat() and #mdb_env_stat().
5735  * @param[in] env the environment to operate in.
5736  * @param[in] db the #MDB_db record containing the stats to return.
5737  * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5738  * @return 0, this function always succeeds.
5739  */
5740 static int
5741 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5742 {
5743         arg->ms_psize = env->me_psize;
5744         arg->ms_depth = db->md_depth;
5745         arg->ms_branch_pages = db->md_branch_pages;
5746         arg->ms_leaf_pages = db->md_leaf_pages;
5747         arg->ms_overflow_pages = db->md_overflow_pages;
5748         arg->ms_entries = db->md_entries;
5749
5750         return MDB_SUCCESS;
5751 }
5752 int
5753 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5754 {
5755         int toggle;
5756
5757         if (env == NULL || arg == NULL)
5758                 return EINVAL;
5759
5760         mdb_env_read_meta(env, &toggle);
5761
5762         return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5763 }
5764
5765 /** Set the default comparison functions for a database.
5766  * Called immediately after a database is opened to set the defaults.
5767  * The user can then override them with #mdb_set_compare() or
5768  * #mdb_set_dupsort().
5769  * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5770  * @param[in] dbi A database handle returned by #mdb_open()
5771  */
5772 static void
5773 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5774 {
5775         if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5776                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5777         else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5778                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5779         else
5780                 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5781
5782         if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5783                 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5784                         if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5785                                 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5786                         else
5787                                 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5788                 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5789                         txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5790                 } else {
5791                         txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5792                 }
5793         } else {
5794                 txn->mt_dbxs[dbi].md_dcmp = NULL;
5795         }
5796 }
5797
5798 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5799 {
5800         MDB_val key, data;
5801         MDB_dbi i;
5802         MDB_cursor mc;
5803         int rc, dbflag, exact;
5804         size_t len;
5805
5806         if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5807                 mdb_default_cmp(txn, FREE_DBI);
5808         }
5809
5810         /* main DB? */
5811         if (!name) {
5812                 *dbi = MAIN_DBI;
5813                 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5814                         txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5815                 mdb_default_cmp(txn, MAIN_DBI);
5816                 return MDB_SUCCESS;
5817         }
5818
5819         if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5820                 mdb_default_cmp(txn, MAIN_DBI);
5821         }
5822
5823         /* Is the DB already open? */
5824         len = strlen(name);
5825         for (i=2; i<txn->mt_numdbs; i++) {
5826                 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5827                         !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5828                         *dbi = i;
5829                         return MDB_SUCCESS;
5830                 }
5831         }
5832
5833         if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5834                 return ENFILE;
5835
5836         /* Find the DB info */
5837         dbflag = 0;
5838         exact = 0;
5839         key.mv_size = len;
5840         key.mv_data = (void *)name;
5841         mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5842         rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
5843         if (rc == MDB_SUCCESS) {
5844                 /* make sure this is actually a DB */
5845                 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
5846                 if (!(node->mn_flags & F_SUBDATA))
5847                         return EINVAL;
5848         } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5849                 /* Create if requested */
5850                 MDB_db dummy;
5851                 data.mv_size = sizeof(MDB_db);
5852                 data.mv_data = &dummy;
5853                 memset(&dummy, 0, sizeof(dummy));
5854                 dummy.md_root = P_INVALID;
5855                 dummy.md_flags = flags & 0xffff;
5856                 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5857                 dbflag = DB_DIRTY;
5858         }
5859
5860         /* OK, got info, add to table */
5861         if (rc == MDB_SUCCESS) {
5862                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5863                 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5864                 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5865                 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5866                 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5867                 *dbi = txn->mt_numdbs;
5868                 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5869                 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5870                 mdb_default_cmp(txn, txn->mt_numdbs);
5871                 txn->mt_numdbs++;
5872         }
5873
5874         return rc;
5875 }
5876
5877 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5878 {
5879         if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5880                 return EINVAL;
5881
5882         return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5883 }
5884
5885 void mdb_close(MDB_env *env, MDB_dbi dbi)
5886 {
5887         char *ptr;
5888         if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5889                 return;
5890         ptr = env->me_dbxs[dbi].md_name.mv_data;
5891         env->me_dbxs[dbi].md_name.mv_data = NULL;
5892         env->me_dbxs[dbi].md_name.mv_size = 0;
5893         free(ptr);
5894 }
5895
5896 /** Add all the DB's pages to the free list.
5897  * @param[in] mc Cursor on the DB to free.
5898  * @param[in] subs non-Zero to check for sub-DBs in this DB.
5899  * @return 0 on success, non-zero on failure.
5900  */
5901 static int
5902 mdb_drop0(MDB_cursor *mc, int subs)
5903 {
5904         int rc;
5905
5906         rc = mdb_page_search(mc, NULL, 0);
5907         if (rc == MDB_SUCCESS) {
5908                 MDB_node *ni;
5909                 MDB_cursor mx;
5910                 unsigned int i;
5911
5912                 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5913                 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5914                         mdb_cursor_pop(mc);
5915
5916                 mdb_cursor_copy(mc, &mx);
5917                 while (mc->mc_snum > 0) {
5918                         if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5919                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5920                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5921                                         if (ni->mn_flags & F_SUBDATA) {
5922                                                 mdb_xcursor_init1(mc, ni);
5923                                                 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5924                                                 if (rc)
5925                                                         return rc;
5926                                         }
5927                                 }
5928                         } else {
5929                                 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5930                                         pgno_t pg;
5931                                         ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5932                                         pg = NODEPGNO(ni);
5933                                         /* free it */
5934                                         mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5935                                 }
5936                         }
5937                         if (!mc->mc_top)
5938                                 break;
5939                         rc = mdb_cursor_sibling(mc, 1);
5940                         if (rc) {
5941                                 /* no more siblings, go back to beginning
5942                                  * of previous level. (stack was already popped
5943                                  * by mdb_cursor_sibling)
5944                                  */
5945                                 for (i=1; i<mc->mc_top; i++)
5946                                         mc->mc_pg[i] = mx.mc_pg[i];
5947                         }
5948                 }
5949                 /* free it */
5950                 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5951                         mc->mc_db->md_root);
5952         }
5953         return 0;
5954 }
5955
5956 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5957 {
5958         MDB_cursor *mc;
5959         int rc;
5960
5961         if (!txn || !dbi || dbi >= txn->mt_numdbs)
5962                 return EINVAL;
5963
5964         rc = mdb_cursor_open(txn, dbi, &mc);
5965         if (rc)
5966                 return rc;
5967
5968         rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
5969         if (rc)
5970                 goto leave;
5971
5972         /* Can't delete the main DB */
5973         if (del && dbi > MAIN_DBI) {
5974                 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5975                 if (!rc)
5976                         mdb_close(txn->mt_env, dbi);
5977         } else {
5978                 txn->mt_dbflags[dbi] |= DB_DIRTY;
5979                 txn->mt_dbs[dbi].md_depth = 0;
5980                 txn->mt_dbs[dbi].md_branch_pages = 0;
5981                 txn->mt_dbs[dbi].md_leaf_pages = 0;
5982                 txn->mt_dbs[dbi].md_overflow_pages = 0;
5983                 txn->mt_dbs[dbi].md_entries = 0;
5984                 txn->mt_dbs[dbi].md_root = P_INVALID;
5985         }
5986 leave:
5987         mdb_cursor_close(mc);
5988         return rc;
5989 }
5990
5991 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5992 {
5993         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5994                 return EINVAL;
5995
5996         txn->mt_dbxs[dbi].md_cmp = cmp;
5997         return MDB_SUCCESS;
5998 }
5999
6000 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6001 {
6002         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6003                 return EINVAL;
6004
6005         txn->mt_dbxs[dbi].md_dcmp = cmp;
6006         return MDB_SUCCESS;
6007 }
6008
6009 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6010 {
6011         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6012                 return EINVAL;
6013
6014         txn->mt_dbxs[dbi].md_rel = rel;
6015         return MDB_SUCCESS;
6016 }
6017
6018 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6019 {
6020         if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6021                 return EINVAL;
6022
6023         txn->mt_dbxs[dbi].md_relctx = ctx;
6024         return MDB_SUCCESS;
6025 }
6026
6027 /** @} */