1 /** @file mdb.c
2 * @brief Lightning 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-2019 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 #ifndef _GNU_SOURCE
36 #define _GNU_SOURCE 1
37 #endif
38 #if defined(__WIN64__)
39 #define _FILE_OFFSET_BITS 64
40 #endif
41 #ifdef _WIN32
42 #include <malloc.h>
43 #include <windows.h>
44 #include <wchar.h> /* get wcscpy() */
45
46 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
47 * as int64 which is wrong. MSVC doesn't define it at all, so just
48 * don't use it.
49 */
50 #define MDB_PID_T int
51 #define MDB_THR_T DWORD
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #ifdef __GNUC__
55 # include <sys/param.h>
56 #else
57 # define LITTLE_ENDIAN 1234
58 # define BIG_ENDIAN 4321
59 # define BYTE_ORDER LITTLE_ENDIAN
60 # ifndef SSIZE_MAX
61 # define SSIZE_MAX INT_MAX
62 # endif
63 #endif
64 #else
65 #include <sys/types.h>
66 #include <sys/stat.h>
67 #define MDB_PID_T pid_t
68 #define MDB_THR_T pthread_t
69 #include <sys/param.h>
70 #include <sys/uio.h>
71 #include <sys/mman.h>
72 #ifdef HAVE_SYS_FILE_H
73 #include <sys/file.h>
74 #endif
75 #include <fcntl.h>
76 #endif
77
78 #if defined(__mips) && defined(__linux)
79 /* MIPS has cache coherency issues, requires explicit cache control */
80 #include <sys/cachectl.h>
81 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
82 #else
83 #define CACHEFLUSH(addr, bytes, cache)
84 #endif
85
86 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
87 /** fdatasync is broken on ext3/ext4fs on older kernels, see
88 * description in #mdb_env_open2 comments. You can safely
89 * define MDB_FDATASYNC_WORKS if this code will only be run
90 * on kernels 3.6 and newer.
91 */
92 #define BROKEN_FDATASYNC
93 #endif
94
95 #include <errno.h>
96 #include <limits.h>
97 #include <stddef.h>
98 #include <inttypes.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <time.h>
103
104 #ifdef _MSC_VER
105 #include <io.h>
106 typedef SSIZE_T ssize_t;
107 #else
108 #include <unistd.h>
109 #endif
110
111 #if defined(__sun) || defined(__ANDROID__)
112 /* Most platforms have posix_memalign, older may only have memalign */
113 #define HAVE_MEMALIGN 1
114 #include <malloc.h>
115 /* On Solaris, we need the POSIX sigwait function */
116 #if defined (__sun)
117 # define _POSIX_PTHREAD_SEMANTICS 1
118 #endif
119 #endif
120
121 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
122 #include <netinet/in.h>
123 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
124 #endif
125
126 #if defined(__APPLE__) || defined (BSD) || defined(__FreeBSD_kernel__)
127 # define MDB_USE_POSIX_SEM 1
128 # define MDB_FDATASYNC fsync
129 #elif defined(__ANDROID__)
130 # define MDB_FDATASYNC fsync
131 #endif
132
133 #ifndef _WIN32
134 #include <pthread.h>
135 #include <signal.h>
136 #ifdef MDB_USE_POSIX_SEM
137 # define MDB_USE_HASH 1
138 #include <semaphore.h>
139 #else
140 #define MDB_USE_POSIX_MUTEX 1
141 #endif
142 #endif
143
144 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) \
145 + defined(MDB_USE_POSIX_MUTEX) != 1
146 # error "Ambiguous shared-lock implementation"
147 #endif
148
149 #ifdef USE_VALGRIND
150 #include <valgrind/memcheck.h>
151 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
152 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
153 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
154 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
155 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
156 #else
157 #define VGMEMP_CREATE(h,r,z)
158 #define VGMEMP_ALLOC(h,a,s)
159 #define VGMEMP_FREE(h,a)
160 #define VGMEMP_DESTROY(h)
161 #define VGMEMP_DEFINED(a,s)
162 #endif
163
164 #ifndef BYTE_ORDER
165 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
166 /* Solaris just defines one or the other */
167 # define LITTLE_ENDIAN 1234
168 # define BIG_ENDIAN 4321
169 # ifdef _LITTLE_ENDIAN
170 # define BYTE_ORDER LITTLE_ENDIAN
171 # else
172 # define BYTE_ORDER BIG_ENDIAN
173 # endif
174 # else
175 # define BYTE_ORDER __BYTE_ORDER
176 # endif
177 #endif
178
179 #ifndef LITTLE_ENDIAN
180 #define LITTLE_ENDIAN __LITTLE_ENDIAN
181 #endif
182 #ifndef BIG_ENDIAN
183 #define BIG_ENDIAN __BIG_ENDIAN
184 #endif
185
186 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
187 #define MISALIGNED_OK 1
188 #endif
189
190 #include "lmdb.h"
191 #include "midl.h"
192
193 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
194 # error "Unknown or unsupported endianness (BYTE_ORDER)"
195 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
196 # error "Two's complement, reasonably sized integer types, please"
197 #endif
198
199 #ifdef __GNUC__
200 /** Put infrequently used env functions in separate section */
201 # ifdef __APPLE__
202 # define ESECT __attribute__ ((section("__TEXT,text_env")))
203 # else
204 # define ESECT __attribute__ ((section("text_env")))
205 # endif
206 #else
207 #define ESECT
208 #endif
209
210 #ifdef _WIN32
211 #define CALL_CONV WINAPI
212 #else
213 #define CALL_CONV
214 #endif
215
216 /** @defgroup internal LMDB Internals
217 * @{
218 */
219 /** @defgroup compat Compatibility Macros
220 * A bunch of macros to minimize the amount of platform-specific ifdefs
221 * needed throughout the rest of the code. When the features this library
222 * needs are similar enough to POSIX to be hidden in a one-or-two line
223 * replacement, this macro approach is used.
224 * @{
225 */
226
227 /** Features under development */
228 #ifndef MDB_DEVEL
229 #define MDB_DEVEL 0
230 #endif
231
232 /** Wrapper around __func__, which is a C99 feature */
233 #if __STDC_VERSION__ >= 199901L
234 # define mdb_func_ __func__
235 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
236 # define mdb_func_ __FUNCTION__
237 #else
238 /* If a debug message says <mdb_unknown>(), update the #if statements above */
239 # define mdb_func_ "<mdb_unknown>"
240 #endif
241
242 /* Internal error codes, not exposed outside liblmdb */
243 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
244 #ifdef _WIN32
245 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
246 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
247 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
248 #endif
249
250 #ifdef __GLIBC__
251 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
252 #endif
253 /** Some platforms define the EOWNERDEAD error code
254 * even though they don't support Robust Mutexes.
255 * Compile with -DMDB_USE_ROBUST=0, or use some other
256 * mechanism like -DMDB_USE_POSIX_SEM instead of
257 * -DMDB_USE_POSIX_MUTEX.
258 * (Posix semaphores are not robust.)
259 */
260 #ifndef MDB_USE_ROBUST
261 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
262 # if defined(MDB_USE_POSIX_MUTEX) && (defined(__ANDROID__) || \
263 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
264 # define MDB_USE_ROBUST 0
265 # else
266 # define MDB_USE_ROBUST 1
267 # endif
268 #endif /* !MDB_USE_ROBUST */
269
270 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
271 /* glibc < 2.12 only provided _np API */
272 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
273 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
274 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
275 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
276 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
277 # endif
278 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
279
280 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
281 #define MDB_ROBUST_SUPPORTED 1
282 #endif
283
284 #ifdef _WIN32
285 #define MDB_USE_HASH 1
286 #define MDB_PIDLOCK 0
287 #define THREAD_RET DWORD
288 #define pthread_t HANDLE
289 #define pthread_mutex_t HANDLE
290 #define pthread_cond_t HANDLE
291 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
292 #define pthread_key_t DWORD
293 #define pthread_self() GetCurrentThreadId()
294 #define pthread_key_create(x,y) \
295 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
296 #define pthread_key_delete(x) TlsFree(x)
297 #define pthread_getspecific(x) TlsGetValue(x)
298 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
299 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
300 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
301 #define pthread_cond_signal(x) SetEvent(*x)
302 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
303 #define THREAD_CREATE(thr,start,arg) \
304 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
305 #define THREAD_FINISH(thr) \
306 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
307 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
308 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
309 #define mdb_mutex_consistent(mutex) 0
310 #define getpid() GetCurrentProcessId()
311 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
312 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
313 #define ErrCode() GetLastError()
314 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
315 #define close(fd) (CloseHandle(fd) ? 0 : -1)
316 #define munmap(ptr,len) UnmapViewOfFile(ptr)
317 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
318 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
319 #else
320 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
321 #endif
322 #define Z "I"
323 #else
324 #define THREAD_RET void *
325 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
326 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
327 #define Z "z" /**< printf format modifier for size_t */
328
329 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
330 #define MDB_PIDLOCK 1
331
332 #ifdef MDB_USE_POSIX_SEM
333
334 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
335 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
336 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
337
338 static int
mdb_sem_wait(sem_t * sem)339 mdb_sem_wait(sem_t *sem)
340 {
341 int rc;
342 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
343 return rc;
344 }
345
346 #else /* MDB_USE_POSIX_MUTEX: */
347 /** Shared mutex/semaphore as the original is stored.
348 *
349 * Not for copies. Instead it can be assigned to an #mdb_mutexref_t.
350 * When mdb_mutexref_t is a pointer and mdb_mutex_t is not, then it
351 * is array[size 1] so it can be assigned to the pointer.
352 */
353 typedef pthread_mutex_t mdb_mutex_t[1];
354 /** Reference to an #mdb_mutex_t */
355 typedef pthread_mutex_t *mdb_mutexref_t;
356 /** Lock the reader or writer mutex.
357 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
358 */
359 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
360 /** Unlock the reader or writer mutex.
361 */
362 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
363 /** Mark mutex-protected data as repaired, after death of previous owner.
364 */
365 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
366 #endif /* MDB_USE_POSIX_SEM */
367
368 /** Get the error code for the last failed system function.
369 */
370 #define ErrCode() errno
371
372 /** An abstraction for a file handle.
373 * On POSIX systems file handles are small integers. On Windows
374 * they're opaque pointers.
375 */
376 #define HANDLE int
377
378 /** A value for an invalid file handle.
379 * Mainly used to initialize file variables and signify that they are
380 * unused.
381 */
382 #define INVALID_HANDLE_VALUE (-1)
383
384 /** Get the size of a memory page for the system.
385 * This is the basic size that the platform's memory manager uses, and is
386 * fundamental to the use of memory-mapped files.
387 */
388 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
389 #endif
390
391 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
392 #define MNAME_LEN 32
393 #else
394 #define MNAME_LEN (sizeof(pthread_mutex_t))
395 #endif
396
397 /** @} */
398
399 #ifdef MDB_ROBUST_SUPPORTED
400 /** Lock mutex, handle any error, set rc = result.
401 * Return 0 on success, nonzero (not rc) on error.
402 */
403 #define LOCK_MUTEX(rc, env, mutex) \
404 (((rc) = LOCK_MUTEX0(mutex)) && \
405 ((rc) = mdb_mutex_failed(env, mutex, rc)))
406 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
407 #else
408 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
409 #define mdb_mutex_failed(env, mutex, rc) (rc)
410 #endif
411
412 #ifndef _WIN32
413 /** A flag for opening a file and requesting synchronous data writes.
414 * This is only used when writing a meta page. It's not strictly needed;
415 * we could just do a normal write and then immediately perform a flush.
416 * But if this flag is available it saves us an extra system call.
417 *
418 * @note If O_DSYNC is undefined but exists in /usr/include,
419 * preferably set some compiler flag to get the definition.
420 */
421 #ifndef MDB_DSYNC
422 # ifdef O_DSYNC
423 # define MDB_DSYNC O_DSYNC
424 # else
425 # define MDB_DSYNC O_SYNC
426 # endif
427 #endif
428 #endif
429
430 /** Function for flushing the data of a file. Define this to fsync
431 * if fdatasync() is not supported.
432 */
433 #ifndef MDB_FDATASYNC
434 # define MDB_FDATASYNC fdatasync
435 #endif
436
437 #ifndef MDB_MSYNC
438 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
439 #endif
440
441 #ifndef MS_SYNC
442 #define MS_SYNC 1
443 #endif
444
445 #ifndef MS_ASYNC
446 #define MS_ASYNC 0
447 #endif
448
449 /** A page number in the database.
450 * Note that 64 bit page numbers are overkill, since pages themselves
451 * already represent 12-13 bits of addressable memory, and the OS will
452 * always limit applications to a maximum of 63 bits of address space.
453 *
454 * @note In the #MDB_node structure, we only store 48 bits of this value,
455 * which thus limits us to only 60 bits of addressable data.
456 */
457 typedef MDB_ID pgno_t;
458
459 /** A transaction ID.
460 * See struct MDB_txn.mt_txnid for details.
461 */
462 typedef MDB_ID txnid_t;
463
464 /** @defgroup debug Debug Macros
465 * @{
466 */
467 #ifndef MDB_DEBUG
468 /** Enable debug output. Needs variable argument macros (a C99 feature).
469 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
470 * read from and written to the database (used for free space management).
471 */
472 #define MDB_DEBUG 0
473 #endif
474
475 #if MDB_DEBUG
476 static int mdb_debug;
477 static txnid_t mdb_debug_start;
478
479 /** Print a debug message with printf formatting.
480 * Requires double parenthesis around 2 or more args.
481 */
482 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
483 # define DPRINTF0(fmt, ...) \
484 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
485 #else
486 # define DPRINTF(args) ((void) 0)
487 #endif
488 /** Print a debug string.
489 * The string is printed literally, with no format processing.
490 */
491 #define DPUTS(arg) DPRINTF(("%s", arg))
492 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
493 #define DDBI(mc) \
494 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
495 /** @} */
496
497 /** @brief The maximum size of a database page.
498 *
499 * It is 32k or 64k, since value-PAGEBASE must fit in
500 * #MDB_page.%mp_upper.
501 *
502 * LMDB will use database pages < OS pages if needed.
503 * That causes more I/O in write transactions: The OS must
504 * know (read) the whole page before writing a partial page.
505 *
506 * Note that we don't currently support Huge pages. On Linux,
507 * regular data files cannot use Huge pages, and in general
508 * Huge pages aren't actually pageable. We rely on the OS
509 * demand-pager to read our data and page it out when memory
510 * pressure from other processes is high. So until OSs have
511 * actual paging support for Huge pages, they're not viable.
512 */
513 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
514
515 /** The minimum number of keys required in a database page.
516 * Setting this to a larger value will place a smaller bound on the
517 * maximum size of a data item. Data items larger than this size will
518 * be pushed into overflow pages instead of being stored directly in
519 * the B-tree node. This value used to default to 4. With a page size
520 * of 4096 bytes that meant that any item larger than 1024 bytes would
521 * go into an overflow page. That also meant that on average 2-3KB of
522 * each overflow page was wasted space. The value cannot be lower than
523 * 2 because then there would no longer be a tree structure. With this
524 * value, items larger than 2KB will go into overflow pages, and on
525 * average only 1KB will be wasted.
526 */
527 #define MDB_MINKEYS 2
528
529 /** A stamp that identifies a file as an LMDB file.
530 * There's nothing special about this value other than that it is easily
531 * recognizable, and it will reflect any byte order mismatches.
532 */
533 #define MDB_MAGIC 0xBEEFC0DE
534
535 /** The version number for a database's datafile format. */
536 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
537 /** The version number for a database's lockfile format. */
538 #define MDB_LOCK_VERSION 1
539
540 /** @brief The max size of a key we can write, or 0 for computed max.
541 *
542 * This macro should normally be left alone or set to 0.
543 * Note that a database with big keys or dupsort data cannot be
544 * reliably modified by a liblmdb which uses a smaller max.
545 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
546 *
547 * Other values are allowed, for backwards compat. However:
548 * A value bigger than the computed max can break if you do not
549 * know what you are doing, and liblmdb <= 0.9.10 can break when
550 * modifying a DB with keys/dupsort data bigger than its max.
551 *
552 * Data items in an #MDB_DUPSORT database are also limited to
553 * this size, since they're actually keys of a sub-DB. Keys and
554 * #MDB_DUPSORT data items must fit on a node in a regular page.
555 */
556 #ifndef MDB_MAXKEYSIZE
557 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
558 #endif
559
560 /** The maximum size of a key we can write to the environment. */
561 #if MDB_MAXKEYSIZE
562 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
563 #else
564 #define ENV_MAXKEY(env) ((env)->me_maxkey)
565 #endif
566
567 /** @brief The maximum size of a data item.
568 *
569 * We only store a 32 bit value for node sizes.
570 */
571 #define MAXDATASIZE 0xffffffffUL
572
573 #if MDB_DEBUG
574 /** Key size which fits in a #DKBUF.
575 * @ingroup debug
576 */
577 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
578 /** A key buffer.
579 * @ingroup debug
580 * This is used for printing a hex dump of a key's contents.
581 */
582 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
583 /** Display a key in hex.
584 * @ingroup debug
585 * Invoke a function to display a key in hex.
586 */
587 #define DKEY(x) mdb_dkey(x, kbuf)
588 #else
589 #define DKBUF
590 #define DKEY(x) 0
591 #endif
592
593 /** An invalid page number.
594 * Mainly used to denote an empty tree.
595 */
596 #define P_INVALID (~(pgno_t)0)
597
598 /** Test if the flags \b f are set in a flag word \b w. */
599 #define F_ISSET(w, f) (((w) & (f)) == (f))
600
601 /** Round \b n up to an even number. */
602 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
603
604 /** Used for offsets within a single page.
605 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
606 * this is plenty.
607 */
608 typedef uint16_t indx_t;
609
610 /** Default size of memory map.
611 * This is certainly too small for any actual applications. Apps should always set
612 * the size explicitly using #mdb_env_set_mapsize().
613 */
614 #define DEFAULT_MAPSIZE 1048576
615
616 /** @defgroup readers Reader Lock Table
617 * Readers don't acquire any locks for their data access. Instead, they
618 * simply record their transaction ID in the reader table. The reader
619 * mutex is needed just to find an empty slot in the reader table. The
620 * slot's address is saved in thread-specific data so that subsequent read
621 * transactions started by the same thread need no further locking to proceed.
622 *
623 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
624 *
625 * No reader table is used if the database is on a read-only filesystem, or
626 * if #MDB_NOLOCK is set.
627 *
628 * Since the database uses multi-version concurrency control, readers don't
629 * actually need any locking. This table is used to keep track of which
630 * readers are using data from which old transactions, so that we'll know
631 * when a particular old transaction is no longer in use. Old transactions
632 * that have discarded any data pages can then have those pages reclaimed
633 * for use by a later write transaction.
634 *
635 * The lock table is constructed such that reader slots are aligned with the
636 * processor's cache line size. Any slot is only ever used by one thread.
637 * This alignment guarantees that there will be no contention or cache
638 * thrashing as threads update their own slot info, and also eliminates
639 * any need for locking when accessing a slot.
640 *
641 * A writer thread will scan every slot in the table to determine the oldest
642 * outstanding reader transaction. Any freed pages older than this will be
643 * reclaimed by the writer. The writer doesn't use any locks when scanning
644 * this table. This means that there's no guarantee that the writer will
645 * see the most up-to-date reader info, but that's not required for correct
646 * operation - all we need is to know the upper bound on the oldest reader,
647 * we don't care at all about the newest reader. So the only consequence of
648 * reading stale information here is that old pages might hang around a
649 * while longer before being reclaimed. That's actually good anyway, because
650 * the longer we delay reclaiming old pages, the more likely it is that a
651 * string of contiguous pages can be found after coalescing old pages from
652 * many old transactions together.
653 * @{
654 */
655 /** Number of slots in the reader table.
656 * This value was chosen somewhat arbitrarily. 126 readers plus a
657 * couple mutexes fit exactly into 8KB on my development machine.
658 * Applications should set the table size using #mdb_env_set_maxreaders().
659 */
660 #define DEFAULT_READERS 126
661
662 /** The size of a CPU cache line in bytes. We want our lock structures
663 * aligned to this size to avoid false cache line sharing in the
664 * lock table.
665 * This value works for most CPUs. For Itanium this should be 128.
666 */
667 #ifndef CACHELINE
668 #define CACHELINE 64
669 #endif
670
671 /** The information we store in a single slot of the reader table.
672 * In addition to a transaction ID, we also record the process and
673 * thread ID that owns a slot, so that we can detect stale information,
674 * e.g. threads or processes that went away without cleaning up.
675 * @note We currently don't check for stale records. We simply re-init
676 * the table when we know that we're the only process opening the
677 * lock file.
678 */
679 typedef struct MDB_rxbody {
680 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
681 * Multiple readers that start at the same time will probably have the
682 * same ID here. Again, it's not important to exclude them from
683 * anything; all we need to know is which version of the DB they
684 * started from so we can avoid overwriting any data used in that
685 * particular version.
686 */
687 volatile txnid_t mrb_txnid;
688 /** The process ID of the process owning this reader txn. */
689 volatile MDB_PID_T mrb_pid;
690 /** The thread ID of the thread owning this txn. */
691 volatile MDB_THR_T mrb_tid;
692 } MDB_rxbody;
693
694 /** The actual reader record, with cacheline padding. */
695 typedef struct MDB_reader {
696 union {
697 MDB_rxbody mrx;
698 /** shorthand for mrb_txnid */
699 #define mr_txnid mru.mrx.mrb_txnid
700 #define mr_pid mru.mrx.mrb_pid
701 #define mr_tid mru.mrx.mrb_tid
702 /** cache line alignment */
703 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
704 } mru;
705 } MDB_reader;
706
707 /** The header for the reader table.
708 * The table resides in a memory-mapped file. (This is a different file
709 * than is used for the main database.)
710 *
711 * For POSIX the actual mutexes reside in the shared memory of this
712 * mapped file. On Windows, mutexes are named objects allocated by the
713 * kernel; we store the mutex names in this mapped file so that other
714 * processes can grab them. This same approach is also used on
715 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
716 * process-shared POSIX mutexes. For these cases where a named object
717 * is used, the object name is derived from a 64 bit FNV hash of the
718 * environment pathname. As such, naming collisions are extremely
719 * unlikely. If a collision occurs, the results are unpredictable.
720 */
721 typedef struct MDB_txbody {
722 /** Stamp identifying this as an LMDB file. It must be set
723 * to #MDB_MAGIC. */
724 uint32_t mtb_magic;
725 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
726 uint32_t mtb_format;
727 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
728 char mtb_rmname[MNAME_LEN];
729 #else
730 /** Mutex protecting access to this table.
731 * This is the reader table lock used with LOCK_MUTEX().
732 */
733 mdb_mutex_t mtb_rmutex;
734 #endif
735 /** The ID of the last transaction committed to the database.
736 * This is recorded here only for convenience; the value can always
737 * be determined by reading the main database meta pages.
738 */
739 volatile txnid_t mtb_txnid;
740 /** The number of slots that have been used in the reader table.
741 * This always records the maximum count, it is not decremented
742 * when readers release their slots.
743 */
744 volatile unsigned mtb_numreaders;
745 } MDB_txbody;
746
747 /** The actual reader table definition. */
748 typedef struct MDB_txninfo {
749 union {
750 MDB_txbody mtb;
751 #define mti_magic mt1.mtb.mtb_magic
752 #define mti_format mt1.mtb.mtb_format
753 #define mti_rmutex mt1.mtb.mtb_rmutex
754 #define mti_rmname mt1.mtb.mtb_rmname
755 #define mti_txnid mt1.mtb.mtb_txnid
756 #define mti_numreaders mt1.mtb.mtb_numreaders
757 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
758 } mt1;
759 union {
760 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
761 char mt2_wmname[MNAME_LEN];
762 #define mti_wmname mt2.mt2_wmname
763 #else
764 mdb_mutex_t mt2_wmutex;
765 #define mti_wmutex mt2.mt2_wmutex
766 #endif
767 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
768 } mt2;
769 MDB_reader mti_readers[1];
770 } MDB_txninfo;
771
772 /** Lockfile format signature: version, features and field layout */
773 #define MDB_LOCK_FORMAT \
774 ((uint32_t) \
775 ((MDB_LOCK_VERSION) \
776 /* Flags which describe functionality */ \
777 + (((MDB_PIDLOCK) != 0) << 16)))
778 /** @} */
779
780 /** Common header for all page types. The page type depends on #mp_flags.
781 *
782 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
783 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
784 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
785 *
786 * #P_OVERFLOW records occupy one or more contiguous pages where only the
787 * first has a page header. They hold the real data of #F_BIGDATA nodes.
788 *
789 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
790 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
791 * (Duplicate data can also go in sub-databases, which use normal pages.)
792 *
793 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
794 *
795 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
796 * in the snapshot: Either used by a database or listed in a freeDB record.
797 */
798 typedef struct MDB_page {
799 #define mp_pgno mp_p.p_pgno
800 #define mp_next mp_p.p_next
801 union {
802 pgno_t p_pgno; /**< page number */
803 struct MDB_page *p_next; /**< for in-memory list of freed pages */
804 } mp_p;
805 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
806 /** @defgroup mdb_page Page Flags
807 * @ingroup internal
808 * Flags for the page headers.
809 * @{
810 */
811 #define P_BRANCH 0x01 /**< branch page */
812 #define P_LEAF 0x02 /**< leaf page */
813 #define P_OVERFLOW 0x04 /**< overflow page */
814 #define P_META 0x08 /**< meta page */
815 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
816 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
817 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
818 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
819 #define P_KEEP 0x8000 /**< leave this page alone during spill */
820 /** @} */
821 uint16_t mp_flags; /**< @ref mdb_page */
822 #define mp_lower mp_pb.pb.pb_lower
823 #define mp_upper mp_pb.pb.pb_upper
824 #define mp_pages mp_pb.pb_pages
825 union {
826 struct {
827 indx_t pb_lower; /**< lower bound of free space */
828 indx_t pb_upper; /**< upper bound of free space */
829 } pb;
830 uint32_t pb_pages; /**< number of overflow pages */
831 } mp_pb;
832 indx_t mp_ptrs[1]; /**< dynamic size */
833 } MDB_page;
834
835 /** Size of the page header, excluding dynamic data at the end */
836 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
837
838 /** Address of first usable data byte in a page, after the header */
839 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
840
841 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
842 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
843
844 /** Number of nodes on a page */
845 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
846
847 /** The amount of space remaining in the page */
848 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
849
850 /** The percentage of space used in the page, in tenths of a percent. */
851 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
852 ((env)->me_psize - PAGEHDRSZ))
853 /** The minimum page fill factor, in tenths of a percent.
854 * Pages emptier than this are candidates for merging.
855 */
856 #define FILL_THRESHOLD 250
857
858 /** Test if a page is a leaf page */
859 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
860 /** Test if a page is a LEAF2 page */
861 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
862 /** Test if a page is a branch page */
863 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
864 /** Test if a page is an overflow page */
865 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
866 /** Test if a page is a sub page */
867 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
868
869 /** The number of overflow pages needed to store the given size. */
870 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
871
872 /** Link in #MDB_txn.%mt_loose_pgs list.
873 * Kept outside the page header, which is needed when reusing the page.
874 */
875 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
876
877 /** Header for a single key/data pair within a page.
878 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
879 * We guarantee 2-byte alignment for 'MDB_node's.
880 *
881 * #mn_lo and #mn_hi are used for data size on leaf nodes, and for child
882 * pgno on branch nodes. On 64 bit platforms, #mn_flags is also used
883 * for pgno. (Branch nodes have no flags). Lo and hi are in host byte
884 * order in case some accesses can be optimized to 32-bit word access.
885 *
886 * Leaf node flags describe node contents. #F_BIGDATA says the node's
887 * data part is the page number of an overflow page with actual data.
888 * #F_DUPDATA and #F_SUBDATA can be combined giving duplicate data in
889 * a sub-page/sub-database, and named databases (just #F_SUBDATA).
890 */
891 typedef struct MDB_node {
892 /** part of data size or pgno
893 * @{ */
894 #if BYTE_ORDER == LITTLE_ENDIAN
895 unsigned short mn_lo, mn_hi;
896 #else
897 unsigned short mn_hi, mn_lo;
898 #endif
899 /** @} */
900 /** @defgroup mdb_node Node Flags
901 * @ingroup internal
902 * Flags for node headers.
903 * @{
904 */
905 #define F_BIGDATA 0x01 /**< data put on overflow page */
906 #define F_SUBDATA 0x02 /**< data is a sub-database */
907 #define F_DUPDATA 0x04 /**< data has duplicates */
908
909 /** valid flags for #mdb_node_add() */
910 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
911
912 /** @} */
913 unsigned short mn_flags; /**< @ref mdb_node */
914 unsigned short mn_ksize; /**< key size */
915 char mn_data[1]; /**< key and data are appended here */
916 } MDB_node;
917
918 /** Size of the node header, excluding dynamic data at the end */
919 #define NODESIZE offsetof(MDB_node, mn_data)
920
921 /** Bit position of top word in page number, for shifting mn_flags */
922 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
923
924 /** Size of a node in a branch page with a given key.
925 * This is just the node header plus the key, there is no data.
926 */
927 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
928
929 /** Size of a node in a leaf page with a given key and data.
930 * This is node header plus key plus data size.
931 */
932 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
933
934 /** Address of node \b i in page \b p */
935 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
936
937 /** Address of the key for the node */
938 #define NODEKEY(node) (void *)((node)->mn_data)
939
940 /** Address of the data for a node */
941 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
942
943 /** Get the page number pointed to by a branch node */
944 #define NODEPGNO(node) \
945 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
946 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
947 /** Set the page number in a branch node */
948 #define SETPGNO(node,pgno) do { \
949 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
950 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
951
952 /** Get the size of the data in a leaf node */
953 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
954 /** Set the size of the data for a leaf node */
955 #define SETDSZ(node,size) do { \
956 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
957 /** The size of a key in a node */
958 #define NODEKSZ(node) ((node)->mn_ksize)
959
960 /** Copy a page number from src to dst */
961 #ifdef MISALIGNED_OK
962 #define COPY_PGNO(dst,src) dst = src
963 #else
964 #if SIZE_MAX > 4294967295UL
965 #define COPY_PGNO(dst,src) do { \
966 unsigned short *s, *d; \
967 s = (unsigned short *)&(src); \
968 d = (unsigned short *)&(dst); \
969 *d++ = *s++; \
970 *d++ = *s++; \
971 *d++ = *s++; \
972 *d = *s; \
973 } while (0)
974 #else
975 #define COPY_PGNO(dst,src) do { \
976 unsigned short *s, *d; \
977 s = (unsigned short *)&(src); \
978 d = (unsigned short *)&(dst); \
979 *d++ = *s++; \
980 *d = *s; \
981 } while (0)
982 #endif
983 #endif
984 /** The address of a key in a LEAF2 page.
985 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
986 * There are no node headers, keys are stored contiguously.
987 */
988 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
989
990 /** Set the \b node's key into \b keyptr, if requested. */
991 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
992 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
993
994 /** Set the \b node's key into \b key. */
995 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
996
997 /** Information about a single database in the environment. */
998 typedef struct MDB_db {
999 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1000 uint16_t md_flags; /**< @ref mdb_dbi_open */
1001 uint16_t md_depth; /**< depth of this tree */
1002 pgno_t md_branch_pages; /**< number of internal pages */
1003 pgno_t md_leaf_pages; /**< number of leaf pages */
1004 pgno_t md_overflow_pages; /**< number of overflow pages */
1005 size_t md_entries; /**< number of data items */
1006 pgno_t md_root; /**< the root page of this tree */
1007 } MDB_db;
1008
1009 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1010 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1011 /** #mdb_dbi_open() flags */
1012 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1013 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1014
1015 /** Handle for the DB used to track free pages. */
1016 #define FREE_DBI 0
1017 /** Handle for the default DB. */
1018 #define MAIN_DBI 1
1019 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1020 #define CORE_DBS 2
1021
1022 /** Number of meta pages - also hardcoded elsewhere */
1023 #define NUM_METAS 2
1024
1025 /** Meta page content.
1026 * A meta page is the start point for accessing a database snapshot.
1027 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1028 */
1029 typedef struct MDB_meta {
1030 /** Stamp identifying this as an LMDB file. It must be set
1031 * to #MDB_MAGIC. */
1032 uint32_t mm_magic;
1033 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1034 uint32_t mm_version;
1035 void *mm_address; /**< address for fixed mapping */
1036 size_t mm_mapsize; /**< size of mmap region */
1037 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1038 /** The size of pages used in this DB */
1039 #define mm_psize mm_dbs[FREE_DBI].md_pad
1040 /** Any persistent environment flags. @ref mdb_env */
1041 #define mm_flags mm_dbs[FREE_DBI].md_flags
1042 /** Last used page in the datafile.
1043 * Actually the file may be shorter if the freeDB lists the final pages.
1044 */
1045 pgno_t mm_last_pg;
1046 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1047 } MDB_meta;
1048
1049 /** Buffer for a stack-allocated meta page.
1050 * The members define size and alignment, and silence type
1051 * aliasing warnings. They are not used directly; that could
1052 * mean incorrectly using several union members in parallel.
1053 */
1054 typedef union MDB_metabuf {
1055 MDB_page mb_page;
1056 struct {
1057 char mm_pad[PAGEHDRSZ];
1058 MDB_meta mm_meta;
1059 } mb_metabuf;
1060 } MDB_metabuf;
1061
1062 /** Auxiliary DB info.
1063 * The information here is mostly static/read-only. There is
1064 * only a single copy of this record in the environment.
1065 */
1066 typedef struct MDB_dbx {
1067 MDB_val md_name; /**< name of the database */
1068 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1069 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1070 MDB_rel_func *md_rel; /**< user relocate function */
1071 void *md_relctx; /**< user-provided context for md_rel */
1072 } MDB_dbx;
1073
1074 /** A database transaction.
1075 * Every operation requires a transaction handle.
1076 */
1077 struct MDB_txn {
1078 MDB_txn *mt_parent; /**< parent of a nested txn */
1079 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1080 MDB_txn *mt_child;
1081 pgno_t mt_next_pgno; /**< next unallocated page */
1082 /** The ID of this transaction. IDs are integers incrementing from 1.
1083 * Only committed write transactions increment the ID. If a transaction
1084 * aborts, the ID may be re-used by the next writer.
1085 */
1086 txnid_t mt_txnid;
1087 MDB_env *mt_env; /**< the DB environment */
1088 /** The list of pages that became unused during this transaction.
1089 */
1090 MDB_IDL mt_free_pgs;
1091 /** The list of loose pages that became unused and may be reused
1092 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1093 */
1094 MDB_page *mt_loose_pgs;
1095 /** Number of loose pages (#mt_loose_pgs) */
1096 int mt_loose_count;
1097 /** The sorted list of dirty pages we temporarily wrote to disk
1098 * because the dirty list was full. page numbers in here are
1099 * shifted left by 1, deleted slots have the LSB set.
1100 */
1101 MDB_IDL mt_spill_pgs;
1102 union {
1103 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1104 MDB_ID2L dirty_list;
1105 /** For read txns: This thread/txn's reader table slot, or NULL. */
1106 MDB_reader *reader;
1107 } mt_u;
1108 /** Array of records for each DB known in the environment. */
1109 MDB_dbx *mt_dbxs;
1110 /** Array of MDB_db records for each known DB */
1111 MDB_db *mt_dbs;
1112 /** Array of sequence numbers for each DB handle */
1113 unsigned int *mt_dbiseqs;
1114 /** @defgroup mt_dbflag Transaction DB Flags
1115 * @ingroup internal
1116 * @{
1117 */
1118 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1119 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1120 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1121 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1122 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1123 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1124 /** @} */
1125 /** In write txns, array of cursors for each DB */
1126 MDB_cursor **mt_cursors;
1127 /** Array of flags for each DB */
1128 unsigned char *mt_dbflags;
1129 /** Number of DB records in use, or 0 when the txn is finished.
1130 * This number only ever increments until the txn finishes; we
1131 * don't decrement it when individual DB handles are closed.
1132 */
1133 MDB_dbi mt_numdbs;
1134
1135 /** @defgroup mdb_txn Transaction Flags
1136 * @ingroup internal
1137 * @{
1138 */
1139 /** #mdb_txn_begin() flags */
1140 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1141 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1142 /* internal txn flags */
1143 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1144 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1145 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1146 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1147 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1148 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1149 /** most operations on the txn are currently illegal */
1150 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1151 /** @} */
1152 unsigned int mt_flags; /**< @ref mdb_txn */
1153 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1154 * Includes ancestor txns' dirty pages not hidden by other txns'
1155 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1156 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1157 */
1158 unsigned int mt_dirty_room;
1159 };
1160
1161 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1162 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1163 * raise this on a 64 bit machine.
1164 */
1165 #define CURSOR_STACK 32
1166
1167 struct MDB_xcursor;
1168
1169 /** Cursors are used for all DB operations.
1170 * A cursor holds a path of (page pointer, key index) from the DB
1171 * root to a position in the DB, plus other state. #MDB_DUPSORT
1172 * cursors include an xcursor to the current data item. Write txns
1173 * track their cursors and keep them up to date when data moves.
1174 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1175 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1176 */
1177 struct MDB_cursor {
1178 /** Next cursor on this DB in this txn */
1179 MDB_cursor *mc_next;
1180 /** Backup of the original cursor if this cursor is a shadow */
1181 MDB_cursor *mc_backup;
1182 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1183 struct MDB_xcursor *mc_xcursor;
1184 /** The transaction that owns this cursor */
1185 MDB_txn *mc_txn;
1186 /** The database handle this cursor operates on */
1187 MDB_dbi mc_dbi;
1188 /** The database record for this cursor */
1189 MDB_db *mc_db;
1190 /** The database auxiliary record for this cursor */
1191 MDB_dbx *mc_dbx;
1192 /** The @ref mt_dbflag for this database */
1193 unsigned char *mc_dbflag;
1194 unsigned short mc_snum; /**< number of pushed pages */
1195 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1196 /** @defgroup mdb_cursor Cursor Flags
1197 * @ingroup internal
1198 * Cursor state flags.
1199 * @{
1200 */
1201 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1202 #define C_EOF 0x02 /**< No more data */
1203 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1204 #define C_DEL 0x08 /**< last op was a cursor_del */
1205 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1206 /** @} */
1207 unsigned int mc_flags; /**< @ref mdb_cursor */
1208 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1209 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1210 };
1211
1212 /** Context for sorted-dup records.
1213 * We could have gone to a fully recursive design, with arbitrarily
1214 * deep nesting of sub-databases. But for now we only handle these
1215 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1216 */
1217 typedef struct MDB_xcursor {
1218 /** A sub-cursor for traversing the Dup DB */
1219 MDB_cursor mx_cursor;
1220 /** The database record for this Dup DB */
1221 MDB_db mx_db;
1222 /** The auxiliary DB record for this Dup DB */
1223 MDB_dbx mx_dbx;
1224 /** The @ref mt_dbflag for this Dup DB */
1225 unsigned char mx_dbflag;
1226 } MDB_xcursor;
1227
1228 /** Check if there is an inited xcursor */
1229 #define XCURSOR_INITED(mc) \
1230 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1231
1232 /** Update the xcursor's sub-page pointer, if any, in \b mc. Needed
1233 * when the node which contains the sub-page may have moved. Called
1234 * with leaf page \b mp = mc->mc_pg[\b top].
1235 */
1236 #define XCURSOR_REFRESH(mc, top, mp) do { \
1237 MDB_page *xr_pg = (mp); \
1238 MDB_node *xr_node; \
1239 if (!XCURSOR_INITED(mc) || (mc)->mc_ki[top] >= NUMKEYS(xr_pg)) break; \
1240 xr_node = NODEPTR(xr_pg, (mc)->mc_ki[top]); \
1241 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1242 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1243 } while (0)
1244
1245 /** State of FreeDB old pages, stored in the MDB_env */
1246 typedef struct MDB_pgstate {
1247 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1248 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1249 } MDB_pgstate;
1250
1251 /** The database environment. */
1252 struct MDB_env {
1253 HANDLE me_fd; /**< The main data file */
1254 HANDLE me_lfd; /**< The lock file */
1255 HANDLE me_mfd; /**< For writing and syncing the meta pages */
1256 /** Failed to update the meta page. Probably an I/O error. */
1257 #define MDB_FATAL_ERROR 0x80000000U
1258 /** Some fields are initialized. */
1259 #define MDB_ENV_ACTIVE 0x20000000U
1260 /** me_txkey is set */
1261 #define MDB_ENV_TXKEY 0x10000000U
1262 /** fdatasync is unreliable */
1263 #define MDB_FSYNCONLY 0x08000000U
1264 uint32_t me_flags; /**< @ref mdb_env */
1265 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1266 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1267 unsigned int me_maxreaders; /**< size of the reader table */
1268 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1269 volatile int me_close_readers;
1270 MDB_dbi me_numdbs; /**< number of DBs opened */
1271 MDB_dbi me_maxdbs; /**< size of the DB table */
1272 MDB_PID_T me_pid; /**< process ID of this env */
1273 char *me_path; /**< path to the DB files */
1274 char *me_map; /**< the memory map of the data file */
1275 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1276 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1277 void *me_pbuf; /**< scratch area for DUPSORT put() */
1278 MDB_txn *me_txn; /**< current write transaction */
1279 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1280 size_t me_mapsize; /**< size of the data memory map */
1281 off_t me_size; /**< current file size */
1282 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1283 MDB_dbx *me_dbxs; /**< array of static DB info */
1284 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1285 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1286 pthread_key_t me_txkey; /**< thread-key for readers */
1287 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1288 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1289 # define me_pglast me_pgstate.mf_pglast
1290 # define me_pghead me_pgstate.mf_pghead
1291 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1292 /** IDL of pages that became unused in a write txn */
1293 MDB_IDL me_free_pgs;
1294 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1295 MDB_ID2L me_dirty_list;
1296 /** Max number of freelist items that can fit in a single overflow page */
1297 int me_maxfree_1pg;
1298 /** Max size of a node on a page */
1299 unsigned int me_nodemax;
1300 #if !(MDB_MAXKEYSIZE)
1301 unsigned int me_maxkey; /**< max size of a key */
1302 #endif
1303 int me_live_reader; /**< have liveness lock in reader table */
1304 #ifdef _WIN32
1305 int me_pidquery; /**< Used in OpenProcess */
1306 #endif
1307 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1308 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1309 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1310 #else
1311 mdb_mutex_t me_rmutex;
1312 mdb_mutex_t me_wmutex;
1313 #endif
1314 void *me_userctx; /**< User-settable context */
1315 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1316 };
1317
1318 /** Nested transaction */
1319 typedef struct MDB_ntxn {
1320 MDB_txn mnt_txn; /**< the transaction */
1321 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1322 } MDB_ntxn;
1323
1324 /** max number of pages to commit in one writev() call */
1325 #define MDB_COMMIT_PAGES 64
1326 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1327 #undef MDB_COMMIT_PAGES
1328 #define MDB_COMMIT_PAGES IOV_MAX
1329 #endif
1330
1331 /** max bytes to write in one call */
1332 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1333
1334 /** Check \b txn and \b dbi arguments to a function */
1335 #define TXN_DBI_EXIST(txn, dbi, validity) \
1336 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1337
1338 /** Check for misused \b dbi handles */
1339 #define TXN_DBI_CHANGED(txn, dbi) \
1340 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1341
1342 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1343 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1344 static int mdb_page_touch(MDB_cursor *mc);
1345
1346 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1347 "reset-tmp", "fail-begin", "fail-beginchild"}
1348 enum {
1349 /* mdb_txn_end operation number, for logging */
1350 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1351 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1352 };
1353 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1354 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1355 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1356 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1357 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1358
1359 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1360 static int mdb_page_search_root(MDB_cursor *mc,
1361 MDB_val *key, int modify);
1362 #define MDB_PS_MODIFY 1
1363 #define MDB_PS_ROOTONLY 2
1364 #define MDB_PS_FIRST 4
1365 #define MDB_PS_LAST 8
1366 static int mdb_page_search(MDB_cursor *mc,
1367 MDB_val *key, int flags);
1368 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1369
1370 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1371 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1372 pgno_t newpgno, unsigned int nflags);
1373
1374 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1375 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1376 static int mdb_env_write_meta(MDB_txn *txn);
1377 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1378 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1379 #endif
1380 static void mdb_env_close0(MDB_env *env, int excl);
1381
1382 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1383 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1384 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1385 static void mdb_node_del(MDB_cursor *mc, int ksize);
1386 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1387 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1388 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1389 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1390 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1391
1392 static int mdb_rebalance(MDB_cursor *mc);
1393 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1394
1395 static void mdb_cursor_pop(MDB_cursor *mc);
1396 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1397
1398 static int mdb_cursor_del0(MDB_cursor *mc);
1399 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1400 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1401 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1402 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1403 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1404 int *exactp);
1405 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1406 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1407
1408 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1409 static void mdb_xcursor_init0(MDB_cursor *mc);
1410 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1411 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1412
1413 static int mdb_drop0(MDB_cursor *mc, int subs);
1414 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1415 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1416
1417 /** @cond */
1418 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1419 /** @endcond */
1420
1421 /** Compare two items pointing at size_t's of unknown alignment. */
1422 #ifdef MISALIGNED_OK
1423 # define mdb_cmp_clong mdb_cmp_long
1424 #else
1425 # define mdb_cmp_clong mdb_cmp_cint
1426 #endif
1427
1428 #ifdef _WIN32
1429 static SECURITY_DESCRIPTOR mdb_null_sd;
1430 static SECURITY_ATTRIBUTES mdb_all_sa;
1431 static int mdb_sec_inited;
1432
1433 struct MDB_name;
1434 static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
1435 #endif
1436
1437 /** Return the library version info. */
1438 char * ESECT
mdb_version(int * major,int * minor,int * patch)1439 mdb_version(int *major, int *minor, int *patch)
1440 {
1441 if (major) *major = MDB_VERSION_MAJOR;
1442 if (minor) *minor = MDB_VERSION_MINOR;
1443 if (patch) *patch = MDB_VERSION_PATCH;
1444 return MDB_VERSION_STRING;
1445 }
1446
1447 /** Table of descriptions for LMDB @ref errors */
1448 static char *const mdb_errstr[] = {
1449 "MDB_KEYEXIST: Key/data pair already exists",
1450 "MDB_NOTFOUND: No matching key/data pair found",
1451 "MDB_PAGE_NOTFOUND: Requested page not found",
1452 "MDB_CORRUPTED: Located page was wrong type",
1453 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1454 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1455 "MDB_INVALID: File is not an LMDB file",
1456 "MDB_MAP_FULL: Environment mapsize limit reached",
1457 "MDB_DBS_FULL: Environment maxdbs limit reached",
1458 "MDB_READERS_FULL: Environment maxreaders limit reached",
1459 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1460 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1461 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1462 "MDB_PAGE_FULL: Internal error - page has no more space",
1463 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1464 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1465 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1466 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1467 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1468 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1469 };
1470
1471 char *
mdb_strerror(int err)1472 mdb_strerror(int err)
1473 {
1474 #ifdef _WIN32
1475 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1476 * This works as long as no function between the call to mdb_strerror
1477 * and the actual use of the message uses more than 4K of stack.
1478 */
1479 #define MSGSIZE 1024
1480 #define PADSIZE 4096
1481 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1482 #endif
1483 int i;
1484 if (!err)
1485 return ("Successful return: 0");
1486
1487 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1488 i = err - MDB_KEYEXIST;
1489 return mdb_errstr[i];
1490 }
1491
1492 #ifdef _WIN32
1493 /* These are the C-runtime error codes we use. The comment indicates
1494 * their numeric value, and the Win32 error they would correspond to
1495 * if the error actually came from a Win32 API. A major mess, we should
1496 * have used LMDB-specific error codes for everything.
1497 */
1498 switch(err) {
1499 case ENOENT: /* 2, FILE_NOT_FOUND */
1500 case EIO: /* 5, ACCESS_DENIED */
1501 case ENOMEM: /* 12, INVALID_ACCESS */
1502 case EACCES: /* 13, INVALID_DATA */
1503 case EBUSY: /* 16, CURRENT_DIRECTORY */
1504 case EINVAL: /* 22, BAD_COMMAND */
1505 case ENOSPC: /* 28, OUT_OF_PAPER */
1506 return strerror(err);
1507 default:
1508 ;
1509 }
1510 buf[0] = 0;
1511 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1512 FORMAT_MESSAGE_IGNORE_INSERTS,
1513 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1514 return ptr;
1515 #else
1516 return strerror(err);
1517 #endif
1518 }
1519
1520 /** assert(3) variant in cursor context */
1521 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1522 /** assert(3) variant in transaction context */
1523 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1524 /** assert(3) variant in environment context */
1525 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1526
1527 #ifndef NDEBUG
1528 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1529 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1530
1531 static void ESECT
mdb_assert_fail(MDB_env * env,const char * expr_txt,const char * func,const char * file,int line)1532 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1533 const char *func, const char *file, int line)
1534 {
1535 char buf[400];
1536 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1537 file, line, expr_txt, func);
1538 if (env->me_assert_func)
1539 env->me_assert_func(env, buf);
1540 fprintf(stderr, "%s\n", buf);
1541 abort();
1542 }
1543 #else
1544 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1545 #endif /* NDEBUG */
1546
1547 #if MDB_DEBUG
1548 /** Return the page number of \b mp which may be sub-page, for debug output */
1549 static pgno_t
mdb_dbg_pgno(MDB_page * mp)1550 mdb_dbg_pgno(MDB_page *mp)
1551 {
1552 pgno_t ret;
1553 COPY_PGNO(ret, mp->mp_pgno);
1554 return ret;
1555 }
1556
1557 /** Display a key in hexadecimal and return the address of the result.
1558 * @param[in] key the key to display
1559 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1560 * @return The key in hexadecimal form.
1561 */
1562 char *
mdb_dkey(MDB_val * key,char * buf)1563 mdb_dkey(MDB_val *key, char *buf)
1564 {
1565 char *ptr = buf;
1566 unsigned char *c = key->mv_data;
1567 unsigned int i;
1568
1569 if (!key)
1570 return "";
1571
1572 if (key->mv_size > DKBUF_MAXKEYSIZE)
1573 return "MDB_MAXKEYSIZE";
1574 /* may want to make this a dynamic check: if the key is mostly
1575 * printable characters, print it as-is instead of converting to hex.
1576 */
1577 #if 1
1578 buf[0] = '\0';
1579 for (i=0; i<key->mv_size; i++)
1580 ptr += sprintf(ptr, "%02x", *c++);
1581 #else
1582 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1583 #endif
1584 return buf;
1585 }
1586
1587 static const char *
mdb_leafnode_type(MDB_node * n)1588 mdb_leafnode_type(MDB_node *n)
1589 {
1590 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1591 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1592 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1593 }
1594
1595 /** Display all the keys in the page. */
1596 void
mdb_page_list(MDB_page * mp)1597 mdb_page_list(MDB_page *mp)
1598 {
1599 pgno_t pgno = mdb_dbg_pgno(mp);
1600 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1601 MDB_node *node;
1602 unsigned int i, nkeys, nsize, total = 0;
1603 MDB_val key;
1604 DKBUF;
1605
1606 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1607 case P_BRANCH: type = "Branch page"; break;
1608 case P_LEAF: type = "Leaf page"; break;
1609 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1610 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1611 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1612 case P_OVERFLOW:
1613 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1614 pgno, mp->mp_pages, state);
1615 return;
1616 case P_META:
1617 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1618 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1619 return;
1620 default:
1621 fprintf(stderr, "Bad page %"Z"u flags 0x%X\n", pgno, mp->mp_flags);
1622 return;
1623 }
1624
1625 nkeys = NUMKEYS(mp);
1626 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1627
1628 for (i=0; i<nkeys; i++) {
1629 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1630 key.mv_size = nsize = mp->mp_pad;
1631 key.mv_data = LEAF2KEY(mp, i, nsize);
1632 total += nsize;
1633 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1634 continue;
1635 }
1636 node = NODEPTR(mp, i);
1637 key.mv_size = node->mn_ksize;
1638 key.mv_data = node->mn_data;
1639 nsize = NODESIZE + key.mv_size;
1640 if (IS_BRANCH(mp)) {
1641 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1642 DKEY(&key));
1643 total += nsize;
1644 } else {
1645 if (F_ISSET(node->mn_flags, F_BIGDATA))
1646 nsize += sizeof(pgno_t);
1647 else
1648 nsize += NODEDSZ(node);
1649 total += nsize;
1650 nsize += sizeof(indx_t);
1651 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1652 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1653 }
1654 total = EVEN(total);
1655 }
1656 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1657 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1658 }
1659
1660 void
mdb_cursor_chk(MDB_cursor * mc)1661 mdb_cursor_chk(MDB_cursor *mc)
1662 {
1663 unsigned int i;
1664 MDB_node *node;
1665 MDB_page *mp;
1666
1667 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1668 for (i=0; i<mc->mc_top; i++) {
1669 mp = mc->mc_pg[i];
1670 node = NODEPTR(mp, mc->mc_ki[i]);
1671 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1672 printf("oops!\n");
1673 }
1674 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1675 printf("ack!\n");
1676 if (XCURSOR_INITED(mc)) {
1677 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1678 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1679 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1680 printf("blah!\n");
1681 }
1682 }
1683 }
1684 #endif
1685
1686 #if (MDB_DEBUG) > 2
1687 /** Count all the pages in each DB and in the freelist
1688 * and make sure it matches the actual number of pages
1689 * being used.
1690 * All named DBs must be open for a correct count.
1691 */
mdb_audit(MDB_txn * txn)1692 static void mdb_audit(MDB_txn *txn)
1693 {
1694 MDB_cursor mc;
1695 MDB_val key, data;
1696 MDB_ID freecount, count;
1697 MDB_dbi i;
1698 int rc;
1699
1700 freecount = 0;
1701 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1702 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1703 freecount += *(MDB_ID *)data.mv_data;
1704 mdb_tassert(txn, rc == MDB_NOTFOUND);
1705
1706 count = 0;
1707 for (i = 0; i<txn->mt_numdbs; i++) {
1708 MDB_xcursor mx;
1709 if (!(txn->mt_dbflags[i] & DB_VALID))
1710 continue;
1711 mdb_cursor_init(&mc, txn, i, &mx);
1712 if (txn->mt_dbs[i].md_root == P_INVALID)
1713 continue;
1714 count += txn->mt_dbs[i].md_branch_pages +
1715 txn->mt_dbs[i].md_leaf_pages +
1716 txn->mt_dbs[i].md_overflow_pages;
1717 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1718 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1719 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1720 unsigned j;
1721 MDB_page *mp;
1722 mp = mc.mc_pg[mc.mc_top];
1723 for (j=0; j<NUMKEYS(mp); j++) {
1724 MDB_node *leaf = NODEPTR(mp, j);
1725 if (leaf->mn_flags & F_SUBDATA) {
1726 MDB_db db;
1727 memcpy(&db, NODEDATA(leaf), sizeof(db));
1728 count += db.md_branch_pages + db.md_leaf_pages +
1729 db.md_overflow_pages;
1730 }
1731 }
1732 }
1733 mdb_tassert(txn, rc == MDB_NOTFOUND);
1734 }
1735 }
1736 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1737 fprintf(stderr, "audit: %"Z"u freecount: %"Z"u count: %"Z"u total: %"Z"u next_pgno: %"Z"u\n",
1738 txn->mt_txnid, freecount, count+NUM_METAS,
1739 freecount+count+NUM_METAS, txn->mt_next_pgno);
1740 }
1741 }
1742 #endif
1743
1744 int
mdb_cmp(MDB_txn * txn,MDB_dbi dbi,const MDB_val * a,const MDB_val * b)1745 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1746 {
1747 return txn->mt_dbxs[dbi].md_cmp(a, b);
1748 }
1749
1750 int
mdb_dcmp(MDB_txn * txn,MDB_dbi dbi,const MDB_val * a,const MDB_val * b)1751 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1752 {
1753 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1754 #if UINT_MAX < SIZE_MAX
1755 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1756 dcmp = mdb_cmp_clong;
1757 #endif
1758 return dcmp(a, b);
1759 }
1760
1761 /** Allocate memory for a page.
1762 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1763 * Set #MDB_TXN_ERROR on failure.
1764 */
1765 static MDB_page *
mdb_page_malloc(MDB_txn * txn,unsigned num)1766 mdb_page_malloc(MDB_txn *txn, unsigned num)
1767 {
1768 MDB_env *env = txn->mt_env;
1769 MDB_page *ret = env->me_dpages;
1770 size_t psize = env->me_psize, sz = psize, off;
1771 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1772 * For a single page alloc, we init everything after the page header.
1773 * For multi-page, we init the final page; if the caller needed that
1774 * many pages they will be filling in at least up to the last page.
1775 */
1776 if (num == 1) {
1777 if (ret) {
1778 VGMEMP_ALLOC(env, ret, sz);
1779 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1780 env->me_dpages = ret->mp_next;
1781 return ret;
1782 }
1783 psize -= off = PAGEHDRSZ;
1784 } else {
1785 sz *= num;
1786 off = sz - psize;
1787 }
1788 if ((ret = malloc(sz)) != NULL) {
1789 VGMEMP_ALLOC(env, ret, sz);
1790 if (!(env->me_flags & MDB_NOMEMINIT)) {
1791 memset((char *)ret + off, 0, psize);
1792 ret->mp_pad = 0;
1793 }
1794 } else {
1795 txn->mt_flags |= MDB_TXN_ERROR;
1796 }
1797 return ret;
1798 }
1799 /** Free a single page.
1800 * Saves single pages to a list, for future reuse.
1801 * (This is not used for multi-page overflow pages.)
1802 */
1803 static void
mdb_page_free(MDB_env * env,MDB_page * mp)1804 mdb_page_free(MDB_env *env, MDB_page *mp)
1805 {
1806 mp->mp_next = env->me_dpages;
1807 VGMEMP_FREE(env, mp);
1808 env->me_dpages = mp;
1809 }
1810
1811 /** Free a dirty page */
1812 static void
mdb_dpage_free(MDB_env * env,MDB_page * dp)1813 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1814 {
1815 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1816 mdb_page_free(env, dp);
1817 } else {
1818 /* large pages just get freed directly */
1819 VGMEMP_FREE(env, dp);
1820 free(dp);
1821 }
1822 }
1823
1824 /** Return all dirty pages to dpage list */
1825 static void
mdb_dlist_free(MDB_txn * txn)1826 mdb_dlist_free(MDB_txn *txn)
1827 {
1828 MDB_env *env = txn->mt_env;
1829 MDB_ID2L dl = txn->mt_u.dirty_list;
1830 unsigned i, n = dl[0].mid;
1831
1832 for (i = 1; i <= n; i++) {
1833 mdb_dpage_free(env, dl[i].mptr);
1834 }
1835 dl[0].mid = 0;
1836 }
1837
1838 /** Loosen or free a single page.
1839 * Saves single pages to a list for future reuse
1840 * in this same txn. It has been pulled from the freeDB
1841 * and already resides on the dirty list, but has been
1842 * deleted. Use these pages first before pulling again
1843 * from the freeDB.
1844 *
1845 * If the page wasn't dirtied in this txn, just add it
1846 * to this txn's free list.
1847 */
1848 static int
mdb_page_loose(MDB_cursor * mc,MDB_page * mp)1849 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1850 {
1851 int loose = 0;
1852 pgno_t pgno = mp->mp_pgno;
1853 MDB_txn *txn = mc->mc_txn;
1854
1855 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1856 if (txn->mt_parent) {
1857 MDB_ID2 *dl = txn->mt_u.dirty_list;
1858 /* If txn has a parent, make sure the page is in our
1859 * dirty list.
1860 */
1861 if (dl[0].mid) {
1862 unsigned x = mdb_mid2l_search(dl, pgno);
1863 if (x <= dl[0].mid && dl[x].mid == pgno) {
1864 if (mp != dl[x].mptr) { /* bad cursor? */
1865 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1866 txn->mt_flags |= MDB_TXN_ERROR;
1867 return MDB_CORRUPTED;
1868 }
1869 /* ok, it's ours */
1870 loose = 1;
1871 }
1872 }
1873 } else {
1874 /* no parent txn, so it's just ours */
1875 loose = 1;
1876 }
1877 }
1878 if (loose) {
1879 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1880 mp->mp_pgno));
1881 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1882 txn->mt_loose_pgs = mp;
1883 txn->mt_loose_count++;
1884 mp->mp_flags |= P_LOOSE;
1885 } else {
1886 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1887 if (rc)
1888 return rc;
1889 }
1890
1891 return MDB_SUCCESS;
1892 }
1893
1894 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1895 * @param[in] mc A cursor handle for the current operation.
1896 * @param[in] pflags Flags of the pages to update:
1897 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1898 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1899 * @return 0 on success, non-zero on failure.
1900 */
1901 static int
mdb_pages_xkeep(MDB_cursor * mc,unsigned pflags,int all)1902 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1903 {
1904 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1905 MDB_txn *txn = mc->mc_txn;
1906 MDB_cursor *m3, *m0 = mc;
1907 MDB_xcursor *mx;
1908 MDB_page *dp, *mp;
1909 MDB_node *leaf;
1910 unsigned i, j;
1911 int rc = MDB_SUCCESS, level;
1912
1913 /* Mark pages seen by cursors */
1914 if (mc->mc_flags & C_UNTRACK)
1915 mc = NULL; /* will find mc in mt_cursors */
1916 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1917 for (; mc; mc=mc->mc_next) {
1918 if (!(mc->mc_flags & C_INITIALIZED))
1919 continue;
1920 for (m3 = mc;; m3 = &mx->mx_cursor) {
1921 mp = NULL;
1922 for (j=0; j<m3->mc_snum; j++) {
1923 mp = m3->mc_pg[j];
1924 if ((mp->mp_flags & Mask) == pflags)
1925 mp->mp_flags ^= P_KEEP;
1926 }
1927 mx = m3->mc_xcursor;
1928 /* Proceed to mx if it is at a sub-database */
1929 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1930 break;
1931 if (! (mp && (mp->mp_flags & P_LEAF)))
1932 break;
1933 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1934 if (!(leaf->mn_flags & F_SUBDATA))
1935 break;
1936 }
1937 }
1938 if (i == 0)
1939 break;
1940 }
1941
1942 if (all) {
1943 /* Mark dirty root pages */
1944 for (i=0; i<txn->mt_numdbs; i++) {
1945 if (txn->mt_dbflags[i] & DB_DIRTY) {
1946 pgno_t pgno = txn->mt_dbs[i].md_root;
1947 if (pgno == P_INVALID)
1948 continue;
1949 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
1950 break;
1951 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1952 dp->mp_flags ^= P_KEEP;
1953 }
1954 }
1955 }
1956
1957 return rc;
1958 }
1959
1960 static int mdb_page_flush(MDB_txn *txn, int keep);
1961
1962 /** Spill pages from the dirty list back to disk.
1963 * This is intended to prevent running into #MDB_TXN_FULL situations,
1964 * but note that they may still occur in a few cases:
1965 * 1) our estimate of the txn size could be too small. Currently this
1966 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1967 * 2) child txns may run out of space if their parents dirtied a
1968 * lot of pages and never spilled them. TODO: we probably should do
1969 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1970 * the parent's dirty_room is below a given threshold.
1971 *
1972 * Otherwise, if not using nested txns, it is expected that apps will
1973 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1974 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1975 * If the txn never references them again, they can be left alone.
1976 * If the txn only reads them, they can be used without any fuss.
1977 * If the txn writes them again, they can be dirtied immediately without
1978 * going thru all of the work of #mdb_page_touch(). Such references are
1979 * handled by #mdb_page_unspill().
1980 *
1981 * Also note, we never spill DB root pages, nor pages of active cursors,
1982 * because we'll need these back again soon anyway. And in nested txns,
1983 * we can't spill a page in a child txn if it was already spilled in a
1984 * parent txn. That would alter the parent txns' data even though
1985 * the child hasn't committed yet, and we'd have no way to undo it if
1986 * the child aborted.
1987 *
1988 * @param[in] m0 cursor A cursor handle identifying the transaction and
1989 * database for which we are checking space.
1990 * @param[in] key For a put operation, the key being stored.
1991 * @param[in] data For a put operation, the data being stored.
1992 * @return 0 on success, non-zero on failure.
1993 */
1994 static int
mdb_page_spill(MDB_cursor * m0,MDB_val * key,MDB_val * data)1995 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1996 {
1997 MDB_txn *txn = m0->mc_txn;
1998 MDB_page *dp;
1999 MDB_ID2L dl = txn->mt_u.dirty_list;
2000 unsigned int i, j, need;
2001 int rc;
2002
2003 if (m0->mc_flags & C_SUB)
2004 return MDB_SUCCESS;
2005
2006 /* Estimate how much space this op will take */
2007 i = m0->mc_db->md_depth;
2008 /* Named DBs also dirty the main DB */
2009 if (m0->mc_dbi >= CORE_DBS)
2010 i += txn->mt_dbs[MAIN_DBI].md_depth;
2011 /* For puts, roughly factor in the key+data size */
2012 if (key)
2013 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2014 i += i; /* double it for good measure */
2015 need = i;
2016
2017 if (txn->mt_dirty_room > i)
2018 return MDB_SUCCESS;
2019
2020 if (!txn->mt_spill_pgs) {
2021 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2022 if (!txn->mt_spill_pgs)
2023 return ENOMEM;
2024 } else {
2025 /* purge deleted slots */
2026 MDB_IDL sl = txn->mt_spill_pgs;
2027 unsigned int num = sl[0];
2028 j=0;
2029 for (i=1; i<=num; i++) {
2030 if (!(sl[i] & 1))
2031 sl[++j] = sl[i];
2032 }
2033 sl[0] = j;
2034 }
2035
2036 /* Preserve pages which may soon be dirtied again */
2037 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2038 goto done;
2039
2040 /* Less aggressive spill - we originally spilled the entire dirty list,
2041 * with a few exceptions for cursor pages and DB root pages. But this
2042 * turns out to be a lot of wasted effort because in a large txn many
2043 * of those pages will need to be used again. So now we spill only 1/8th
2044 * of the dirty pages. Testing revealed this to be a good tradeoff,
2045 * better than 1/2, 1/4, or 1/10.
2046 */
2047 if (need < MDB_IDL_UM_MAX / 8)
2048 need = MDB_IDL_UM_MAX / 8;
2049
2050 /* Save the page IDs of all the pages we're flushing */
2051 /* flush from the tail forward, this saves a lot of shifting later on. */
2052 for (i=dl[0].mid; i && need; i--) {
2053 MDB_ID pn = dl[i].mid << 1;
2054 dp = dl[i].mptr;
2055 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2056 continue;
2057 /* Can't spill twice, make sure it's not already in a parent's
2058 * spill list.
2059 */
2060 if (txn->mt_parent) {
2061 MDB_txn *tx2;
2062 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2063 if (tx2->mt_spill_pgs) {
2064 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2065 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2066 dp->mp_flags |= P_KEEP;
2067 break;
2068 }
2069 }
2070 }
2071 if (tx2)
2072 continue;
2073 }
2074 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2075 goto done;
2076 need--;
2077 }
2078 mdb_midl_sort(txn->mt_spill_pgs);
2079
2080 /* Flush the spilled part of dirty list */
2081 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2082 goto done;
2083
2084 /* Reset any dirty pages we kept that page_flush didn't see */
2085 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2086
2087 done:
2088 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2089 return rc;
2090 }
2091
2092 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2093 static txnid_t
mdb_find_oldest(MDB_txn * txn)2094 mdb_find_oldest(MDB_txn *txn)
2095 {
2096 int i;
2097 txnid_t mr, oldest = txn->mt_txnid - 1;
2098 if (txn->mt_env->me_txns) {
2099 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2100 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2101 if (r[i].mr_pid) {
2102 mr = r[i].mr_txnid;
2103 if (oldest > mr)
2104 oldest = mr;
2105 }
2106 }
2107 }
2108 return oldest;
2109 }
2110
2111 /** Add a page to the txn's dirty list */
2112 static void
mdb_page_dirty(MDB_txn * txn,MDB_page * mp)2113 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2114 {
2115 MDB_ID2 mid;
2116 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2117
2118 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2119 insert = mdb_mid2l_append;
2120 } else {
2121 insert = mdb_mid2l_insert;
2122 }
2123 mid.mid = mp->mp_pgno;
2124 mid.mptr = mp;
2125 rc = insert(txn->mt_u.dirty_list, &mid);
2126 mdb_tassert(txn, rc == 0);
2127 txn->mt_dirty_room--;
2128 }
2129
2130 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2131 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2132 *
2133 * If there are free pages available from older transactions, they
2134 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2135 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2136 * and move me_pglast to say which records were consumed. Only this
2137 * function can create me_pghead and move me_pglast/mt_next_pgno.
2138 * @param[in] mc cursor A cursor handle identifying the transaction and
2139 * database for which we are allocating.
2140 * @param[in] num the number of pages to allocate.
2141 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2142 * will always be satisfied by a single contiguous chunk of memory.
2143 * @return 0 on success, non-zero on failure.
2144 */
2145 static int
mdb_page_alloc(MDB_cursor * mc,int num,MDB_page ** mp)2146 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2147 {
2148 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2149 /* Get at most <Max_retries> more freeDB records once me_pghead
2150 * has enough pages. If not enough, use new pages from the map.
2151 * If <Paranoid> and mc is updating the freeDB, only get new
2152 * records if me_pghead is empty. Then the freelist cannot play
2153 * catch-up with itself by growing while trying to save it.
2154 */
2155 enum { Paranoid = 1, Max_retries = 500 };
2156 #else
2157 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2158 #endif
2159 int rc, retry = num * 60;
2160 MDB_txn *txn = mc->mc_txn;
2161 MDB_env *env = txn->mt_env;
2162 pgno_t pgno, *mop = env->me_pghead;
2163 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2164 MDB_page *np;
2165 txnid_t oldest = 0, last;
2166 MDB_cursor_op op;
2167 MDB_cursor m2;
2168 int found_old = 0;
2169
2170 /* If there are any loose pages, just use them */
2171 if (num == 1 && txn->mt_loose_pgs) {
2172 np = txn->mt_loose_pgs;
2173 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2174 txn->mt_loose_count--;
2175 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2176 np->mp_pgno));
2177 *mp = np;
2178 return MDB_SUCCESS;
2179 }
2180
2181 *mp = NULL;
2182
2183 /* If our dirty list is already full, we can't do anything */
2184 if (txn->mt_dirty_room == 0) {
2185 rc = MDB_TXN_FULL;
2186 goto fail;
2187 }
2188
2189 for (op = MDB_FIRST;; op = MDB_NEXT) {
2190 MDB_val key, data;
2191 MDB_node *leaf;
2192 pgno_t *idl;
2193
2194 /* Seek a big enough contiguous page range. Prefer
2195 * pages at the tail, just truncating the list.
2196 */
2197 if (mop_len > n2) {
2198 i = mop_len;
2199 do {
2200 pgno = mop[i];
2201 if (mop[i-n2] == pgno+n2)
2202 goto search_done;
2203 } while (--i > n2);
2204 if (--retry < 0)
2205 break;
2206 }
2207
2208 if (op == MDB_FIRST) { /* 1st iteration */
2209 /* Prepare to fetch more and coalesce */
2210 last = env->me_pglast;
2211 oldest = env->me_pgoldest;
2212 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2213 if (last) {
2214 op = MDB_SET_RANGE;
2215 key.mv_data = &last; /* will look up last+1 */
2216 key.mv_size = sizeof(last);
2217 }
2218 if (Paranoid && mc->mc_dbi == FREE_DBI)
2219 retry = -1;
2220 }
2221 if (Paranoid && retry < 0 && mop_len)
2222 break;
2223
2224 last++;
2225 /* Do not fetch more if the record will be too recent */
2226 if (oldest <= last) {
2227 if (!found_old) {
2228 oldest = mdb_find_oldest(txn);
2229 env->me_pgoldest = oldest;
2230 found_old = 1;
2231 }
2232 if (oldest <= last)
2233 break;
2234 }
2235 rc = mdb_cursor_get(&m2, &key, NULL, op);
2236 if (rc) {
2237 if (rc == MDB_NOTFOUND)
2238 break;
2239 goto fail;
2240 }
2241 last = *(txnid_t*)key.mv_data;
2242 if (oldest <= last) {
2243 if (!found_old) {
2244 oldest = mdb_find_oldest(txn);
2245 env->me_pgoldest = oldest;
2246 found_old = 1;
2247 }
2248 if (oldest <= last)
2249 break;
2250 }
2251 np = m2.mc_pg[m2.mc_top];
2252 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2253 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2254 goto fail;
2255
2256 idl = (MDB_ID *) data.mv_data;
2257 i = idl[0];
2258 if (!mop) {
2259 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2260 rc = ENOMEM;
2261 goto fail;
2262 }
2263 } else {
2264 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2265 goto fail;
2266 mop = env->me_pghead;
2267 }
2268 env->me_pglast = last;
2269 #if (MDB_DEBUG) > 1
2270 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2271 last, txn->mt_dbs[FREE_DBI].md_root, i));
2272 for (j = i; j; j--)
2273 DPRINTF(("IDL %"Z"u", idl[j]));
2274 #endif
2275 /* Merge in descending sorted order */
2276 mdb_midl_xmerge(mop, idl);
2277 mop_len = mop[0];
2278 }
2279
2280 /* Use new pages from the map when nothing suitable in the freeDB */
2281 i = 0;
2282 pgno = txn->mt_next_pgno;
2283 if (pgno + num >= env->me_maxpg) {
2284 DPUTS("DB size maxed out");
2285 rc = MDB_MAP_FULL;
2286 goto fail;
2287 }
2288
2289 search_done:
2290 if (env->me_flags & MDB_WRITEMAP) {
2291 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2292 } else {
2293 if (!(np = mdb_page_malloc(txn, num))) {
2294 rc = ENOMEM;
2295 goto fail;
2296 }
2297 }
2298 if (i) {
2299 mop[0] = mop_len -= num;
2300 /* Move any stragglers down */
2301 for (j = i-num; j < mop_len; )
2302 mop[++j] = mop[++i];
2303 } else {
2304 txn->mt_next_pgno = pgno + num;
2305 }
2306 np->mp_pgno = pgno;
2307 mdb_page_dirty(txn, np);
2308 *mp = np;
2309
2310 return MDB_SUCCESS;
2311
2312 fail:
2313 txn->mt_flags |= MDB_TXN_ERROR;
2314 return rc;
2315 }
2316
2317 /** Copy the used portions of a non-overflow page.
2318 * @param[in] dst page to copy into
2319 * @param[in] src page to copy from
2320 * @param[in] psize size of a page
2321 */
2322 static void
mdb_page_copy(MDB_page * dst,MDB_page * src,unsigned int psize)2323 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2324 {
2325 enum { Align = sizeof(pgno_t) };
2326 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2327
2328 /* If page isn't full, just copy the used portion. Adjust
2329 * alignment so memcpy may copy words instead of bytes.
2330 */
2331 if ((unused &= -Align) && !IS_LEAF2(src)) {
2332 upper = (upper + PAGEBASE) & -Align;
2333 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2334 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2335 psize - upper);
2336 } else {
2337 memcpy(dst, src, psize - unused);
2338 }
2339 }
2340
2341 /** Pull a page off the txn's spill list, if present.
2342 * If a page being referenced was spilled to disk in this txn, bring
2343 * it back and make it dirty/writable again.
2344 * @param[in] txn the transaction handle.
2345 * @param[in] mp the page being referenced. It must not be dirty.
2346 * @param[out] ret the writable page, if any. ret is unchanged if
2347 * mp wasn't spilled.
2348 */
2349 static int
mdb_page_unspill(MDB_txn * txn,MDB_page * mp,MDB_page ** ret)2350 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2351 {
2352 MDB_env *env = txn->mt_env;
2353 const MDB_txn *tx2;
2354 unsigned x;
2355 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2356
2357 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2358 if (!tx2->mt_spill_pgs)
2359 continue;
2360 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2361 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2362 MDB_page *np;
2363 int num;
2364 if (txn->mt_dirty_room == 0)
2365 return MDB_TXN_FULL;
2366 if (IS_OVERFLOW(mp))
2367 num = mp->mp_pages;
2368 else
2369 num = 1;
2370 if (env->me_flags & MDB_WRITEMAP) {
2371 np = mp;
2372 } else {
2373 np = mdb_page_malloc(txn, num);
2374 if (!np)
2375 return ENOMEM;
2376 if (num > 1)
2377 memcpy(np, mp, num * env->me_psize);
2378 else
2379 mdb_page_copy(np, mp, env->me_psize);
2380 }
2381 if (tx2 == txn) {
2382 /* If in current txn, this page is no longer spilled.
2383 * If it happens to be the last page, truncate the spill list.
2384 * Otherwise mark it as deleted by setting the LSB.
2385 */
2386 if (x == txn->mt_spill_pgs[0])
2387 txn->mt_spill_pgs[0]--;
2388 else
2389 txn->mt_spill_pgs[x] |= 1;
2390 } /* otherwise, if belonging to a parent txn, the
2391 * page remains spilled until child commits
2392 */
2393
2394 mdb_page_dirty(txn, np);
2395 np->mp_flags |= P_DIRTY;
2396 *ret = np;
2397 break;
2398 }
2399 }
2400 return MDB_SUCCESS;
2401 }
2402
2403 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2404 * Set #MDB_TXN_ERROR on failure.
2405 * @param[in] mc cursor pointing to the page to be touched
2406 * @return 0 on success, non-zero on failure.
2407 */
2408 static int
mdb_page_touch(MDB_cursor * mc)2409 mdb_page_touch(MDB_cursor *mc)
2410 {
2411 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2412 MDB_txn *txn = mc->mc_txn;
2413 MDB_cursor *m2, *m3;
2414 pgno_t pgno;
2415 int rc;
2416
2417 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2418 if (txn->mt_flags & MDB_TXN_SPILLS) {
2419 np = NULL;
2420 rc = mdb_page_unspill(txn, mp, &np);
2421 if (rc)
2422 goto fail;
2423 if (np)
2424 goto done;
2425 }
2426 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2427 (rc = mdb_page_alloc(mc, 1, &np)))
2428 goto fail;
2429 pgno = np->mp_pgno;
2430 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2431 mp->mp_pgno, pgno));
2432 mdb_cassert(mc, mp->mp_pgno != pgno);
2433 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2434 /* Update the parent page, if any, to point to the new page */
2435 if (mc->mc_top) {
2436 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2437 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2438 SETPGNO(node, pgno);
2439 } else {
2440 mc->mc_db->md_root = pgno;
2441 }
2442 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2443 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2444 pgno = mp->mp_pgno;
2445 /* If txn has a parent, make sure the page is in our
2446 * dirty list.
2447 */
2448 if (dl[0].mid) {
2449 unsigned x = mdb_mid2l_search(dl, pgno);
2450 if (x <= dl[0].mid && dl[x].mid == pgno) {
2451 if (mp != dl[x].mptr) { /* bad cursor? */
2452 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2453 txn->mt_flags |= MDB_TXN_ERROR;
2454 return MDB_CORRUPTED;
2455 }
2456 return 0;
2457 }
2458 }
2459 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2460 /* No - copy it */
2461 np = mdb_page_malloc(txn, 1);
2462 if (!np)
2463 return ENOMEM;
2464 mid.mid = pgno;
2465 mid.mptr = np;
2466 rc = mdb_mid2l_insert(dl, &mid);
2467 mdb_cassert(mc, rc == 0);
2468 } else {
2469 return 0;
2470 }
2471
2472 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2473 np->mp_pgno = pgno;
2474 np->mp_flags |= P_DIRTY;
2475
2476 done:
2477 /* Adjust cursors pointing to mp */
2478 mc->mc_pg[mc->mc_top] = np;
2479 m2 = txn->mt_cursors[mc->mc_dbi];
2480 if (mc->mc_flags & C_SUB) {
2481 for (; m2; m2=m2->mc_next) {
2482 m3 = &m2->mc_xcursor->mx_cursor;
2483 if (m3->mc_snum < mc->mc_snum) continue;
2484 if (m3->mc_pg[mc->mc_top] == mp)
2485 m3->mc_pg[mc->mc_top] = np;
2486 }
2487 } else {
2488 for (; m2; m2=m2->mc_next) {
2489 if (m2->mc_snum < mc->mc_snum) continue;
2490 if (m2 == mc) continue;
2491 if (m2->mc_pg[mc->mc_top] == mp) {
2492 m2->mc_pg[mc->mc_top] = np;
2493 if (IS_LEAF(np))
2494 XCURSOR_REFRESH(m2, mc->mc_top, np);
2495 }
2496 }
2497 }
2498 return 0;
2499
2500 fail:
2501 txn->mt_flags |= MDB_TXN_ERROR;
2502 return rc;
2503 }
2504
2505 int
mdb_env_sync(MDB_env * env,int force)2506 mdb_env_sync(MDB_env *env, int force)
2507 {
2508 int rc = 0;
2509 if (env->me_flags & MDB_RDONLY)
2510 return EACCES;
2511 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2512 if (env->me_flags & MDB_WRITEMAP) {
2513 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2514 ? MS_ASYNC : MS_SYNC;
2515 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2516 rc = ErrCode();
2517 #ifdef _WIN32
2518 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2519 rc = ErrCode();
2520 #endif
2521 } else {
2522 #ifdef BROKEN_FDATASYNC
2523 if (env->me_flags & MDB_FSYNCONLY) {
2524 if (fsync(env->me_fd))
2525 rc = ErrCode();
2526 } else
2527 #endif
2528 if (MDB_FDATASYNC(env->me_fd))
2529 rc = ErrCode();
2530 }
2531 }
2532 return rc;
2533 }
2534
2535 /** Back up parent txn's cursors, then grab the originals for tracking */
2536 static int
mdb_cursor_shadow(MDB_txn * src,MDB_txn * dst)2537 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2538 {
2539 MDB_cursor *mc, *bk;
2540 MDB_xcursor *mx;
2541 size_t size;
2542 int i;
2543
2544 for (i = src->mt_numdbs; --i >= 0; ) {
2545 if ((mc = src->mt_cursors[i]) != NULL) {
2546 size = sizeof(MDB_cursor);
2547 if (mc->mc_xcursor)
2548 size += sizeof(MDB_xcursor);
2549 for (; mc; mc = bk->mc_next) {
2550 bk = malloc(size);
2551 if (!bk)
2552 return ENOMEM;
2553 *bk = *mc;
2554 mc->mc_backup = bk;
2555 mc->mc_db = &dst->mt_dbs[i];
2556 /* Kill pointers into src to reduce abuse: The
2557 * user may not use mc until dst ends. But we need a valid
2558 * txn pointer here for cursor fixups to keep working.
2559 */
2560 mc->mc_txn = dst;
2561 mc->mc_dbflag = &dst->mt_dbflags[i];
2562 if ((mx = mc->mc_xcursor) != NULL) {
2563 *(MDB_xcursor *)(bk+1) = *mx;
2564 mx->mx_cursor.mc_txn = dst;
2565 }
2566 mc->mc_next = dst->mt_cursors[i];
2567 dst->mt_cursors[i] = mc;
2568 }
2569 }
2570 }
2571 return MDB_SUCCESS;
2572 }
2573
2574 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2575 * @param[in] txn the transaction handle.
2576 * @param[in] merge true to keep changes to parent cursors, false to revert.
2577 * @return 0 on success, non-zero on failure.
2578 */
2579 static void
mdb_cursors_close(MDB_txn * txn,unsigned merge)2580 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2581 {
2582 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2583 MDB_xcursor *mx;
2584 int i;
2585
2586 for (i = txn->mt_numdbs; --i >= 0; ) {
2587 for (mc = cursors[i]; mc; mc = next) {
2588 next = mc->mc_next;
2589 if ((bk = mc->mc_backup) != NULL) {
2590 if (merge) {
2591 /* Commit changes to parent txn */
2592 mc->mc_next = bk->mc_next;
2593 mc->mc_backup = bk->mc_backup;
2594 mc->mc_txn = bk->mc_txn;
2595 mc->mc_db = bk->mc_db;
2596 mc->mc_dbflag = bk->mc_dbflag;
2597 if ((mx = mc->mc_xcursor) != NULL)
2598 mx->mx_cursor.mc_txn = bk->mc_txn;
2599 } else {
2600 /* Abort nested txn */
2601 *mc = *bk;
2602 if ((mx = mc->mc_xcursor) != NULL)
2603 *mx = *(MDB_xcursor *)(bk+1);
2604 }
2605 mc = bk;
2606 }
2607 /* Only malloced cursors are permanently tracked. */
2608 free(mc);
2609 }
2610 cursors[i] = NULL;
2611 }
2612 }
2613
2614 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2615 enum Pidlock_op {
2616 Pidset, Pidcheck
2617 };
2618 #else
2619 enum Pidlock_op {
2620 Pidset = F_SETLK, Pidcheck = F_GETLK
2621 };
2622 #endif
2623
2624 /** Set or check a pid lock. Set returns 0 on success.
2625 * Check returns 0 if the process is certainly dead, nonzero if it may
2626 * be alive (the lock exists or an error happened so we do not know).
2627 *
2628 * On Windows Pidset is a no-op, we merely check for the existence
2629 * of the process with the given pid. On POSIX we use a single byte
2630 * lock on the lockfile, set at an offset equal to the pid.
2631 */
2632 static int
mdb_reader_pid(MDB_env * env,enum Pidlock_op op,MDB_PID_T pid)2633 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2634 {
2635 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2636 int ret = 0;
2637 HANDLE h;
2638 if (op == Pidcheck) {
2639 h = OpenProcess(env->me_pidquery, FALSE, pid);
2640 /* No documented "no such process" code, but other program use this: */
2641 if (!h)
2642 return ErrCode() != ERROR_INVALID_PARAMETER;
2643 /* A process exists until all handles to it close. Has it exited? */
2644 ret = WaitForSingleObject(h, 0) != 0;
2645 CloseHandle(h);
2646 }
2647 return ret;
2648 #else
2649 for (;;) {
2650 int rc;
2651 struct flock lock_info;
2652 memset(&lock_info, 0, sizeof(lock_info));
2653 lock_info.l_type = F_WRLCK;
2654 lock_info.l_whence = SEEK_SET;
2655 lock_info.l_start = pid;
2656 lock_info.l_len = 1;
2657 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2658 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2659 rc = -1;
2660 } else if ((rc = ErrCode()) == EINTR) {
2661 continue;
2662 }
2663 return rc;
2664 }
2665 #endif
2666 }
2667
2668 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2669 * @param[in] txn the transaction handle to initialize
2670 * @return 0 on success, non-zero on failure.
2671 */
2672 static int
mdb_txn_renew0(MDB_txn * txn)2673 mdb_txn_renew0(MDB_txn *txn)
2674 {
2675 MDB_env *env = txn->mt_env;
2676 MDB_txninfo *ti = env->me_txns;
2677 MDB_meta *meta;
2678 unsigned int i, nr, flags = txn->mt_flags;
2679 uint16_t x;
2680 int rc, new_notls = 0;
2681
2682 if ((flags &= MDB_TXN_RDONLY) != 0) {
2683 if (!ti) {
2684 meta = mdb_env_pick_meta(env);
2685 txn->mt_txnid = meta->mm_txnid;
2686 txn->mt_u.reader = NULL;
2687 } else {
2688 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2689 pthread_getspecific(env->me_txkey);
2690 if (r) {
2691 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2692 return MDB_BAD_RSLOT;
2693 } else {
2694 MDB_PID_T pid = env->me_pid;
2695 MDB_THR_T tid = pthread_self();
2696 mdb_mutexref_t rmutex = env->me_rmutex;
2697
2698 if (!env->me_live_reader) {
2699 rc = mdb_reader_pid(env, Pidset, pid);
2700 if (rc)
2701 return rc;
2702 env->me_live_reader = 1;
2703 }
2704
2705 if (LOCK_MUTEX(rc, env, rmutex))
2706 return rc;
2707 nr = ti->mti_numreaders;
2708 for (i=0; i<nr; i++)
2709 if (ti->mti_readers[i].mr_pid == 0)
2710 break;
2711 if (i == env->me_maxreaders) {
2712 UNLOCK_MUTEX(rmutex);
2713 return MDB_READERS_FULL;
2714 }
2715 r = &ti->mti_readers[i];
2716 /* Claim the reader slot, carefully since other code
2717 * uses the reader table un-mutexed: First reset the
2718 * slot, next publish it in mti_numreaders. After
2719 * that, it is safe for mdb_env_close() to touch it.
2720 * When it will be closed, we can finally claim it.
2721 */
2722 r->mr_pid = 0;
2723 r->mr_txnid = (txnid_t)-1;
2724 r->mr_tid = tid;
2725 if (i == nr)
2726 ti->mti_numreaders = ++nr;
2727 env->me_close_readers = nr;
2728 r->mr_pid = pid;
2729 UNLOCK_MUTEX(rmutex);
2730
2731 new_notls = (env->me_flags & MDB_NOTLS);
2732 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2733 r->mr_pid = 0;
2734 return rc;
2735 }
2736 }
2737 do /* LY: Retry on a race, ITS#7970. */
2738 r->mr_txnid = ti->mti_txnid;
2739 while(r->mr_txnid != ti->mti_txnid);
2740 txn->mt_txnid = r->mr_txnid;
2741 txn->mt_u.reader = r;
2742 meta = env->me_metas[txn->mt_txnid & 1];
2743 }
2744
2745 } else {
2746 /* Not yet touching txn == env->me_txn0, it may be active */
2747 if (ti) {
2748 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2749 return rc;
2750 txn->mt_txnid = ti->mti_txnid;
2751 meta = env->me_metas[txn->mt_txnid & 1];
2752 } else {
2753 meta = mdb_env_pick_meta(env);
2754 txn->mt_txnid = meta->mm_txnid;
2755 }
2756 txn->mt_txnid++;
2757 #if MDB_DEBUG
2758 if (txn->mt_txnid == mdb_debug_start)
2759 mdb_debug = 1;
2760 #endif
2761 txn->mt_child = NULL;
2762 txn->mt_loose_pgs = NULL;
2763 txn->mt_loose_count = 0;
2764 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2765 txn->mt_u.dirty_list = env->me_dirty_list;
2766 txn->mt_u.dirty_list[0].mid = 0;
2767 txn->mt_free_pgs = env->me_free_pgs;
2768 txn->mt_free_pgs[0] = 0;
2769 txn->mt_spill_pgs = NULL;
2770 env->me_txn = txn;
2771 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2772 }
2773
2774 /* Copy the DB info and flags */
2775 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2776
2777 /* Moved to here to avoid a data race in read TXNs */
2778 txn->mt_next_pgno = meta->mm_last_pg+1;
2779
2780 txn->mt_flags = flags;
2781
2782 /* Setup db info */
2783 txn->mt_numdbs = env->me_numdbs;
2784 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2785 x = env->me_dbflags[i];
2786 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2787 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2788 }
2789 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2790 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2791
2792 if (env->me_flags & MDB_FATAL_ERROR) {
2793 DPUTS("environment had fatal error, must shutdown!");
2794 rc = MDB_PANIC;
2795 } else if (env->me_maxpg < txn->mt_next_pgno) {
2796 rc = MDB_MAP_RESIZED;
2797 } else {
2798 return MDB_SUCCESS;
2799 }
2800 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2801 return rc;
2802 }
2803
2804 int
mdb_txn_renew(MDB_txn * txn)2805 mdb_txn_renew(MDB_txn *txn)
2806 {
2807 int rc;
2808
2809 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2810 return EINVAL;
2811
2812 rc = mdb_txn_renew0(txn);
2813 if (rc == MDB_SUCCESS) {
2814 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2815 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2816 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2817 }
2818 return rc;
2819 }
2820
2821 int
mdb_txn_begin(MDB_env * env,MDB_txn * parent,unsigned int flags,MDB_txn ** ret)2822 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2823 {
2824 MDB_txn *txn;
2825 MDB_ntxn *ntxn;
2826 int rc, size, tsize;
2827
2828 flags &= MDB_TXN_BEGIN_FLAGS;
2829 flags |= env->me_flags & MDB_WRITEMAP;
2830
2831 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2832 return EACCES;
2833
2834 if (parent) {
2835 /* Nested transactions: Max 1 child, write txns only, no writemap */
2836 flags |= parent->mt_flags;
2837 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2838 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2839 }
2840 /* Child txns save MDB_pgstate and use own copy of cursors */
2841 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2842 size += tsize = sizeof(MDB_ntxn);
2843 } else if (flags & MDB_RDONLY) {
2844 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2845 size += tsize = sizeof(MDB_txn);
2846 } else {
2847 /* Reuse preallocated write txn. However, do not touch it until
2848 * mdb_txn_renew0() succeeds, since it currently may be active.
2849 */
2850 txn = env->me_txn0;
2851 goto renew;
2852 }
2853 if ((txn = calloc(1, size)) == NULL) {
2854 DPRINTF(("calloc: %s", strerror(errno)));
2855 return ENOMEM;
2856 }
2857 txn->mt_dbxs = env->me_dbxs; /* static */
2858 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2859 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2860 txn->mt_flags = flags;
2861 txn->mt_env = env;
2862
2863 if (parent) {
2864 unsigned int i;
2865 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2866 txn->mt_dbiseqs = parent->mt_dbiseqs;
2867 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2868 if (!txn->mt_u.dirty_list ||
2869 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2870 {
2871 free(txn->mt_u.dirty_list);
2872 free(txn);
2873 return ENOMEM;
2874 }
2875 txn->mt_txnid = parent->mt_txnid;
2876 txn->mt_dirty_room = parent->mt_dirty_room;
2877 txn->mt_u.dirty_list[0].mid = 0;
2878 txn->mt_spill_pgs = NULL;
2879 txn->mt_next_pgno = parent->mt_next_pgno;
2880 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2881 parent->mt_child = txn;
2882 txn->mt_parent = parent;
2883 txn->mt_numdbs = parent->mt_numdbs;
2884 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2885 /* Copy parent's mt_dbflags, but clear DB_NEW */
2886 for (i=0; i<txn->mt_numdbs; i++)
2887 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2888 rc = 0;
2889 ntxn = (MDB_ntxn *)txn;
2890 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2891 if (env->me_pghead) {
2892 size = MDB_IDL_SIZEOF(env->me_pghead);
2893 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2894 if (env->me_pghead)
2895 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2896 else
2897 rc = ENOMEM;
2898 }
2899 if (!rc)
2900 rc = mdb_cursor_shadow(parent, txn);
2901 if (rc)
2902 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2903 } else { /* MDB_RDONLY */
2904 txn->mt_dbiseqs = env->me_dbiseqs;
2905 renew:
2906 rc = mdb_txn_renew0(txn);
2907 }
2908 if (rc) {
2909 if (txn != env->me_txn0)
2910 free(txn);
2911 } else {
2912 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2913 *ret = txn;
2914 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2915 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2916 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2917 }
2918
2919 return rc;
2920 }
2921
2922 MDB_env *
mdb_txn_env(MDB_txn * txn)2923 mdb_txn_env(MDB_txn *txn)
2924 {
2925 if(!txn) return NULL;
2926 return txn->mt_env;
2927 }
2928
2929 size_t
mdb_txn_id(MDB_txn * txn)2930 mdb_txn_id(MDB_txn *txn)
2931 {
2932 if(!txn) return 0;
2933 return txn->mt_txnid;
2934 }
2935
2936 /** Export or close DBI handles opened in this txn. */
2937 static void
mdb_dbis_update(MDB_txn * txn,int keep)2938 mdb_dbis_update(MDB_txn *txn, int keep)
2939 {
2940 int i;
2941 MDB_dbi n = txn->mt_numdbs;
2942 MDB_env *env = txn->mt_env;
2943 unsigned char *tdbflags = txn->mt_dbflags;
2944
2945 for (i = n; --i >= CORE_DBS;) {
2946 if (tdbflags[i] & DB_NEW) {
2947 if (keep) {
2948 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2949 } else {
2950 char *ptr = env->me_dbxs[i].md_name.mv_data;
2951 if (ptr) {
2952 env->me_dbxs[i].md_name.mv_data = NULL;
2953 env->me_dbxs[i].md_name.mv_size = 0;
2954 env->me_dbflags[i] = 0;
2955 env->me_dbiseqs[i]++;
2956 free(ptr);
2957 }
2958 }
2959 }
2960 }
2961 if (keep && env->me_numdbs < n)
2962 env->me_numdbs = n;
2963 }
2964
2965 /** End a transaction, except successful commit of a nested transaction.
2966 * May be called twice for readonly txns: First reset it, then abort.
2967 * @param[in] txn the transaction handle to end
2968 * @param[in] mode why and how to end the transaction
2969 */
2970 static void
mdb_txn_end(MDB_txn * txn,unsigned mode)2971 mdb_txn_end(MDB_txn *txn, unsigned mode)
2972 {
2973 MDB_env *env = txn->mt_env;
2974 #if MDB_DEBUG
2975 static const char *const names[] = MDB_END_NAMES;
2976 #endif
2977
2978 /* Export or close DBI handles opened in this txn */
2979 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2980
2981 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2982 names[mode & MDB_END_OPMASK],
2983 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2984 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2985
2986 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2987 if (txn->mt_u.reader) {
2988 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2989 if (!(env->me_flags & MDB_NOTLS)) {
2990 txn->mt_u.reader = NULL; /* txn does not own reader */
2991 } else if (mode & MDB_END_SLOT) {
2992 txn->mt_u.reader->mr_pid = 0;
2993 txn->mt_u.reader = NULL;
2994 } /* else txn owns the slot until it does MDB_END_SLOT */
2995 }
2996 txn->mt_numdbs = 0; /* prevent further DBI activity */
2997 txn->mt_flags |= MDB_TXN_FINISHED;
2998
2999 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3000 pgno_t *pghead = env->me_pghead;
3001
3002 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3003 mdb_cursors_close(txn, 0);
3004 if (!(env->me_flags & MDB_WRITEMAP)) {
3005 mdb_dlist_free(txn);
3006 }
3007
3008 txn->mt_numdbs = 0;
3009 txn->mt_flags = MDB_TXN_FINISHED;
3010
3011 if (!txn->mt_parent) {
3012 mdb_midl_shrink(&txn->mt_free_pgs);
3013 env->me_free_pgs = txn->mt_free_pgs;
3014 /* me_pgstate: */
3015 env->me_pghead = NULL;
3016 env->me_pglast = 0;
3017
3018 env->me_txn = NULL;
3019 mode = 0; /* txn == env->me_txn0, do not free() it */
3020
3021 /* The writer mutex was locked in mdb_txn_begin. */
3022 if (env->me_txns)
3023 UNLOCK_MUTEX(env->me_wmutex);
3024 } else {
3025 txn->mt_parent->mt_child = NULL;
3026 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3027 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3028 mdb_midl_free(txn->mt_free_pgs);
3029 mdb_midl_free(txn->mt_spill_pgs);
3030 free(txn->mt_u.dirty_list);
3031 }
3032
3033 mdb_midl_free(pghead);
3034 }
3035
3036 if (mode & MDB_END_FREE)
3037 free(txn);
3038 }
3039
3040 void
mdb_txn_reset(MDB_txn * txn)3041 mdb_txn_reset(MDB_txn *txn)
3042 {
3043 if (txn == NULL)
3044 return;
3045
3046 /* This call is only valid for read-only txns */
3047 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3048 return;
3049
3050 mdb_txn_end(txn, MDB_END_RESET);
3051 }
3052
3053 void
mdb_txn_abort(MDB_txn * txn)3054 mdb_txn_abort(MDB_txn *txn)
3055 {
3056 if (txn == NULL)
3057 return;
3058
3059 if (txn->mt_child)
3060 mdb_txn_abort(txn->mt_child);
3061
3062 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3063 }
3064
3065 /** Save the freelist as of this transaction to the freeDB.
3066 * This changes the freelist. Keep trying until it stabilizes.
3067 */
3068 static int
mdb_freelist_save(MDB_txn * txn)3069 mdb_freelist_save(MDB_txn *txn)
3070 {
3071 /* env->me_pghead[] can grow and shrink during this call.
3072 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3073 * Page numbers cannot disappear from txn->mt_free_pgs[].
3074 */
3075 MDB_cursor mc;
3076 MDB_env *env = txn->mt_env;
3077 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3078 txnid_t pglast = 0, head_id = 0;
3079 pgno_t freecnt = 0, *free_pgs, *mop;
3080 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3081
3082 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3083
3084 if (env->me_pghead) {
3085 /* Make sure first page of freeDB is touched and on freelist */
3086 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3087 if (rc && rc != MDB_NOTFOUND)
3088 return rc;
3089 }
3090
3091 if (!env->me_pghead && txn->mt_loose_pgs) {
3092 /* Put loose page numbers in mt_free_pgs, since
3093 * we may be unable to return them to me_pghead.
3094 */
3095 MDB_page *mp = txn->mt_loose_pgs;
3096 MDB_ID2 *dl = txn->mt_u.dirty_list;
3097 unsigned x;
3098 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3099 return rc;
3100 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
3101 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3102 /* must also remove from dirty list */
3103 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
3104 for (x=1; x<=dl[0].mid; x++)
3105 if (dl[x].mid == mp->mp_pgno)
3106 break;
3107 mdb_tassert(txn, x <= dl[0].mid);
3108 } else {
3109 x = mdb_mid2l_search(dl, mp->mp_pgno);
3110 mdb_tassert(txn, dl[x].mid == mp->mp_pgno);
3111 mdb_dpage_free(env, mp);
3112 }
3113 dl[x].mptr = NULL;
3114 }
3115 {
3116 /* squash freed slots out of the dirty list */
3117 unsigned y;
3118 for (y=1; dl[y].mptr && y <= dl[0].mid; y++);
3119 if (y <= dl[0].mid) {
3120 for(x=y, y++;;) {
3121 while (!dl[y].mptr && y <= dl[0].mid) y++;
3122 if (y > dl[0].mid) break;
3123 dl[x++] = dl[y++];
3124 }
3125 dl[0].mid = x-1;
3126 } else {
3127 /* all slots freed */
3128 dl[0].mid = 0;
3129 }
3130 }
3131 txn->mt_loose_pgs = NULL;
3132 txn->mt_loose_count = 0;
3133 }
3134
3135 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3136 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3137 ? SSIZE_MAX : maxfree_1pg;
3138
3139 for (;;) {
3140 /* Come back here after each Put() in case freelist changed */
3141 MDB_val key, data;
3142 pgno_t *pgs;
3143 ssize_t j;
3144
3145 /* If using records from freeDB which we have not yet
3146 * deleted, delete them and any we reserved for me_pghead.
3147 */
3148 while (pglast < env->me_pglast) {
3149 rc = mdb_cursor_first(&mc, &key, NULL);
3150 if (rc)
3151 return rc;
3152 pglast = head_id = *(txnid_t *)key.mv_data;
3153 total_room = head_room = 0;
3154 mdb_tassert(txn, pglast <= env->me_pglast);
3155 rc = mdb_cursor_del(&mc, 0);
3156 if (rc)
3157 return rc;
3158 }
3159
3160 /* Save the IDL of pages freed by this txn, to a single record */
3161 if (freecnt < txn->mt_free_pgs[0]) {
3162 if (!freecnt) {
3163 /* Make sure last page of freeDB is touched and on freelist */
3164 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3165 if (rc && rc != MDB_NOTFOUND)
3166 return rc;
3167 }
3168 free_pgs = txn->mt_free_pgs;
3169 /* Write to last page of freeDB */
3170 key.mv_size = sizeof(txn->mt_txnid);
3171 key.mv_data = &txn->mt_txnid;
3172 do {
3173 freecnt = free_pgs[0];
3174 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3175 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3176 if (rc)
3177 return rc;
3178 /* Retry if mt_free_pgs[] grew during the Put() */
3179 free_pgs = txn->mt_free_pgs;
3180 } while (freecnt < free_pgs[0]);
3181 mdb_midl_sort(free_pgs);
3182 memcpy(data.mv_data, free_pgs, data.mv_size);
3183 #if (MDB_DEBUG) > 1
3184 {
3185 unsigned int i = free_pgs[0];
3186 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3187 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3188 for (; i; i--)
3189 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3190 }
3191 #endif
3192 continue;
3193 }
3194
3195 mop = env->me_pghead;
3196 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3197
3198 /* Reserve records for me_pghead[]. Split it if multi-page,
3199 * to avoid searching freeDB for a page range. Use keys in
3200 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3201 */
3202 if (total_room >= mop_len) {
3203 if (total_room == mop_len || --more < 0)
3204 break;
3205 } else if (head_room >= maxfree_1pg && head_id > 1) {
3206 /* Keep current record (overflow page), add a new one */
3207 head_id--;
3208 head_room = 0;
3209 }
3210 /* (Re)write {key = head_id, IDL length = head_room} */
3211 total_room -= head_room;
3212 head_room = mop_len - total_room;
3213 if (head_room > maxfree_1pg && head_id > 1) {
3214 /* Overflow multi-page for part of me_pghead */
3215 head_room /= head_id; /* amortize page sizes */
3216 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3217 } else if (head_room < 0) {
3218 /* Rare case, not bothering to delete this record */
3219 head_room = 0;
3220 }
3221 key.mv_size = sizeof(head_id);
3222 key.mv_data = &head_id;
3223 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3224 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3225 if (rc)
3226 return rc;
3227 /* IDL is initially empty, zero out at least the length */
3228 pgs = (pgno_t *)data.mv_data;
3229 j = head_room > clean_limit ? head_room : 0;
3230 do {
3231 pgs[j] = 0;
3232 } while (--j >= 0);
3233 total_room += head_room;
3234 }
3235
3236 /* Return loose page numbers to me_pghead, though usually none are
3237 * left at this point. The pages themselves remain in dirty_list.
3238 */
3239 if (txn->mt_loose_pgs) {
3240 MDB_page *mp = txn->mt_loose_pgs;
3241 unsigned count = txn->mt_loose_count;
3242 MDB_IDL loose;
3243 /* Room for loose pages + temp IDL with same */
3244 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3245 return rc;
3246 mop = env->me_pghead;
3247 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3248 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3249 loose[ ++count ] = mp->mp_pgno;
3250 loose[0] = count;
3251 mdb_midl_sort(loose);
3252 mdb_midl_xmerge(mop, loose);
3253 txn->mt_loose_pgs = NULL;
3254 txn->mt_loose_count = 0;
3255 mop_len = mop[0];
3256 }
3257
3258 /* Fill in the reserved me_pghead records */
3259 rc = MDB_SUCCESS;
3260 if (mop_len) {
3261 MDB_val key, data;
3262
3263 mop += mop_len;
3264 rc = mdb_cursor_first(&mc, &key, &data);
3265 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3266 txnid_t id = *(txnid_t *)key.mv_data;
3267 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3268 MDB_ID save;
3269
3270 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3271 key.mv_data = &id;
3272 if (len > mop_len) {
3273 len = mop_len;
3274 data.mv_size = (len + 1) * sizeof(MDB_ID);
3275 }
3276 data.mv_data = mop -= len;
3277 save = mop[0];
3278 mop[0] = len;
3279 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3280 mop[0] = save;
3281 if (rc || !(mop_len -= len))
3282 break;
3283 }
3284 }
3285 return rc;
3286 }
3287
3288 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3289 * @param[in] txn the transaction that's being committed
3290 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3291 * @return 0 on success, non-zero on failure.
3292 */
3293 static int
mdb_page_flush(MDB_txn * txn,int keep)3294 mdb_page_flush(MDB_txn *txn, int keep)
3295 {
3296 MDB_env *env = txn->mt_env;
3297 MDB_ID2L dl = txn->mt_u.dirty_list;
3298 unsigned psize = env->me_psize, j;
3299 int i, pagecount = dl[0].mid, rc;
3300 size_t size = 0, pos = 0;
3301 pgno_t pgno = 0;
3302 MDB_page *dp = NULL;
3303 #ifdef _WIN32
3304 OVERLAPPED ov;
3305 #else
3306 struct iovec iov[MDB_COMMIT_PAGES];
3307 ssize_t wpos = 0, wsize = 0, wres;
3308 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3309 int n = 0;
3310 #endif
3311
3312 j = i = keep;
3313
3314 if (env->me_flags & MDB_WRITEMAP) {
3315 /* Clear dirty flags */
3316 while (++i <= pagecount) {
3317 dp = dl[i].mptr;
3318 /* Don't flush this page yet */
3319 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3320 dp->mp_flags &= ~P_KEEP;
3321 dl[++j] = dl[i];
3322 continue;
3323 }
3324 dp->mp_flags &= ~P_DIRTY;
3325 }
3326 goto done;
3327 }
3328
3329 /* Write the pages */
3330 for (;;) {
3331 if (++i <= pagecount) {
3332 dp = dl[i].mptr;
3333 /* Don't flush this page yet */
3334 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3335 dp->mp_flags &= ~P_KEEP;
3336 dl[i].mid = 0;
3337 continue;
3338 }
3339 pgno = dl[i].mid;
3340 /* clear dirty flag */
3341 dp->mp_flags &= ~P_DIRTY;
3342 pos = pgno * psize;
3343 size = psize;
3344 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3345 }
3346 #ifdef _WIN32
3347 else break;
3348
3349 /* Windows actually supports scatter/gather I/O, but only on
3350 * unbuffered file handles. Since we're relying on the OS page
3351 * cache for all our data, that's self-defeating. So we just
3352 * write pages one at a time. We use the ov structure to set
3353 * the write offset, to at least save the overhead of a Seek
3354 * system call.
3355 */
3356 DPRINTF(("committing page %"Z"u", pgno));
3357 memset(&ov, 0, sizeof(ov));
3358 ov.Offset = pos & 0xffffffff;
3359 ov.OffsetHigh = pos >> 16 >> 16;
3360 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3361 rc = ErrCode();
3362 DPRINTF(("WriteFile: %d", rc));
3363 return rc;
3364 }
3365 #else
3366 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3367 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3368 if (n) {
3369 retry_write:
3370 /* Write previous page(s) */
3371 #ifdef MDB_USE_PWRITEV
3372 wres = pwritev(env->me_fd, iov, n, wpos);
3373 #else
3374 if (n == 1) {
3375 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3376 } else {
3377 retry_seek:
3378 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3379 rc = ErrCode();
3380 if (rc == EINTR)
3381 goto retry_seek;
3382 DPRINTF(("lseek: %s", strerror(rc)));
3383 return rc;
3384 }
3385 wres = writev(env->me_fd, iov, n);
3386 }
3387 #endif
3388 if (wres != wsize) {
3389 if (wres < 0) {
3390 rc = ErrCode();
3391 if (rc == EINTR)
3392 goto retry_write;
3393 DPRINTF(("Write error: %s", strerror(rc)));
3394 } else {
3395 rc = EIO; /* TODO: Use which error code? */
3396 DPUTS("short write, filesystem full?");
3397 }
3398 return rc;
3399 }
3400 n = 0;
3401 }
3402 if (i > pagecount)
3403 break;
3404 wpos = pos;
3405 wsize = 0;
3406 }
3407 DPRINTF(("committing page %"Z"u", pgno));
3408 next_pos = pos + size;
3409 iov[n].iov_len = size;
3410 iov[n].iov_base = (char *)dp;
3411 wsize += size;
3412 n++;
3413 #endif /* _WIN32 */
3414 }
3415
3416 /* MIPS has cache coherency issues, this is a no-op everywhere else
3417 * Note: for any size >= on-chip cache size, entire on-chip cache is
3418 * flushed.
3419 */
3420 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3421
3422 for (i = keep; ++i <= pagecount; ) {
3423 dp = dl[i].mptr;
3424 /* This is a page we skipped above */
3425 if (!dl[i].mid) {
3426 dl[++j] = dl[i];
3427 dl[j].mid = dp->mp_pgno;
3428 continue;
3429 }
3430 mdb_dpage_free(env, dp);
3431 }
3432
3433 done:
3434 i--;
3435 txn->mt_dirty_room += i - j;
3436 dl[0].mid = j;
3437 return MDB_SUCCESS;
3438 }
3439
3440 int
mdb_txn_commit(MDB_txn * txn)3441 mdb_txn_commit(MDB_txn *txn)
3442 {
3443 int rc;
3444 unsigned int i, end_mode;
3445 MDB_env *env;
3446
3447 if (txn == NULL)
3448 return EINVAL;
3449
3450 /* mdb_txn_end() mode for a commit which writes nothing */
3451 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3452
3453 if (txn->mt_child) {
3454 rc = mdb_txn_commit(txn->mt_child);
3455 if (rc)
3456 goto fail;
3457 }
3458
3459 env = txn->mt_env;
3460
3461 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3462 goto done;
3463 }
3464
3465 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3466 DPUTS("txn has failed/finished, can't commit");
3467 if (txn->mt_parent)
3468 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3469 rc = MDB_BAD_TXN;
3470 goto fail;
3471 }
3472
3473 if (txn->mt_parent) {
3474 MDB_txn *parent = txn->mt_parent;
3475 MDB_page **lp;
3476 MDB_ID2L dst, src;
3477 MDB_IDL pspill;
3478 unsigned x, y, len, ps_len;
3479
3480 /* Append our free list to parent's */
3481 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3482 if (rc)
3483 goto fail;
3484 mdb_midl_free(txn->mt_free_pgs);
3485 /* Failures after this must either undo the changes
3486 * to the parent or set MDB_TXN_ERROR in the parent.
3487 */
3488
3489 parent->mt_next_pgno = txn->mt_next_pgno;
3490 parent->mt_flags = txn->mt_flags;
3491
3492 /* Merge our cursors into parent's and close them */
3493 mdb_cursors_close(txn, 1);
3494
3495 /* Update parent's DB table. */
3496 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3497 parent->mt_numdbs = txn->mt_numdbs;
3498 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3499 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3500 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3501 /* preserve parent's DB_NEW status */
3502 x = parent->mt_dbflags[i] & DB_NEW;
3503 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3504 }
3505
3506 dst = parent->mt_u.dirty_list;
3507 src = txn->mt_u.dirty_list;
3508 /* Remove anything in our dirty list from parent's spill list */
3509 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3510 x = y = ps_len;
3511 pspill[0] = (pgno_t)-1;
3512 /* Mark our dirty pages as deleted in parent spill list */
3513 for (i=0, len=src[0].mid; ++i <= len; ) {
3514 MDB_ID pn = src[i].mid << 1;
3515 while (pn > pspill[x])
3516 x--;
3517 if (pn == pspill[x]) {
3518 pspill[x] = 1;
3519 y = --x;
3520 }
3521 }
3522 /* Squash deleted pagenums if we deleted any */
3523 for (x=y; ++x <= ps_len; )
3524 if (!(pspill[x] & 1))
3525 pspill[++y] = pspill[x];
3526 pspill[0] = y;
3527 }
3528
3529 /* Remove anything in our spill list from parent's dirty list */
3530 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3531 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3532 MDB_ID pn = txn->mt_spill_pgs[i];
3533 if (pn & 1)
3534 continue; /* deleted spillpg */
3535 pn >>= 1;
3536 y = mdb_mid2l_search(dst, pn);
3537 if (y <= dst[0].mid && dst[y].mid == pn) {
3538 free(dst[y].mptr);
3539 while (y < dst[0].mid) {
3540 dst[y] = dst[y+1];
3541 y++;
3542 }
3543 dst[0].mid--;
3544 }
3545 }
3546 }
3547
3548 /* Find len = length of merging our dirty list with parent's */
3549 x = dst[0].mid;
3550 dst[0].mid = 0; /* simplify loops */
3551 if (parent->mt_parent) {
3552 len = x + src[0].mid;
3553 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3554 for (i = x; y && i; y--) {
3555 pgno_t yp = src[y].mid;
3556 while (yp < dst[i].mid)
3557 i--;
3558 if (yp == dst[i].mid) {
3559 i--;
3560 len--;
3561 }
3562 }
3563 } else { /* Simplify the above for single-ancestor case */
3564 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3565 }
3566 /* Merge our dirty list with parent's */
3567 y = src[0].mid;
3568 for (i = len; y; dst[i--] = src[y--]) {
3569 pgno_t yp = src[y].mid;
3570 while (yp < dst[x].mid)
3571 dst[i--] = dst[x--];
3572 if (yp == dst[x].mid)
3573 free(dst[x--].mptr);
3574 }
3575 mdb_tassert(txn, i == x);
3576 dst[0].mid = len;
3577 free(txn->mt_u.dirty_list);
3578 parent->mt_dirty_room = txn->mt_dirty_room;
3579 if (txn->mt_spill_pgs) {
3580 if (parent->mt_spill_pgs) {
3581 /* TODO: Prevent failure here, so parent does not fail */
3582 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3583 if (rc)
3584 parent->mt_flags |= MDB_TXN_ERROR;
3585 mdb_midl_free(txn->mt_spill_pgs);
3586 mdb_midl_sort(parent->mt_spill_pgs);
3587 } else {
3588 parent->mt_spill_pgs = txn->mt_spill_pgs;
3589 }
3590 }
3591
3592 /* Append our loose page list to parent's */
3593 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3594 ;
3595 *lp = txn->mt_loose_pgs;
3596 parent->mt_loose_count += txn->mt_loose_count;
3597
3598 parent->mt_child = NULL;
3599 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3600 free(txn);
3601 return rc;
3602 }
3603
3604 if (txn != env->me_txn) {
3605 DPUTS("attempt to commit unknown transaction");
3606 rc = EINVAL;
3607 goto fail;
3608 }
3609
3610 mdb_cursors_close(txn, 0);
3611
3612 if (!txn->mt_u.dirty_list[0].mid &&
3613 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3614 goto done;
3615
3616 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3617 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3618
3619 /* Update DB root pointers */
3620 if (txn->mt_numdbs > CORE_DBS) {
3621 MDB_cursor mc;
3622 MDB_dbi i;
3623 MDB_val data;
3624 data.mv_size = sizeof(MDB_db);
3625
3626 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3627 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3628 if (txn->mt_dbflags[i] & DB_DIRTY) {
3629 if (TXN_DBI_CHANGED(txn, i)) {
3630 rc = MDB_BAD_DBI;
3631 goto fail;
3632 }
3633 data.mv_data = &txn->mt_dbs[i];
3634 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3635 F_SUBDATA);
3636 if (rc)
3637 goto fail;
3638 }
3639 }
3640 }
3641
3642 rc = mdb_freelist_save(txn);
3643 if (rc)
3644 goto fail;
3645
3646 mdb_midl_free(env->me_pghead);
3647 env->me_pghead = NULL;
3648 mdb_midl_shrink(&txn->mt_free_pgs);
3649
3650 #if (MDB_DEBUG) > 2
3651 mdb_audit(txn);
3652 #endif
3653
3654 if ((rc = mdb_page_flush(txn, 0)) ||
3655 (rc = mdb_env_sync(env, 0)) ||
3656 (rc = mdb_env_write_meta(txn)))
3657 goto fail;
3658 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3659
3660 done:
3661 mdb_txn_end(txn, end_mode);
3662 return MDB_SUCCESS;
3663
3664 fail:
3665 mdb_txn_abort(txn);
3666 return rc;
3667 }
3668
3669 /** Read the environment parameters of a DB environment before
3670 * mapping it into memory.
3671 * @param[in] env the environment handle
3672 * @param[out] meta address of where to store the meta information
3673 * @return 0 on success, non-zero on failure.
3674 */
3675 static int ESECT
mdb_env_read_header(MDB_env * env,MDB_meta * meta)3676 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3677 {
3678 MDB_metabuf pbuf;
3679 MDB_page *p;
3680 MDB_meta *m;
3681 int i, rc, off;
3682 enum { Size = sizeof(pbuf) };
3683
3684 /* We don't know the page size yet, so use a minimum value.
3685 * Read both meta pages so we can use the latest one.
3686 */
3687
3688 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3689 #ifdef _WIN32
3690 DWORD len;
3691 OVERLAPPED ov;
3692 memset(&ov, 0, sizeof(ov));
3693 ov.Offset = off;
3694 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3695 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3696 rc = 0;
3697 #else
3698 rc = pread(env->me_fd, &pbuf, Size, off);
3699 #endif
3700 if (rc != Size) {
3701 if (rc == 0 && off == 0)
3702 return ENOENT;
3703 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3704 DPRINTF(("read: %s", mdb_strerror(rc)));
3705 return rc;
3706 }
3707
3708 p = (MDB_page *)&pbuf;
3709
3710 if (!F_ISSET(p->mp_flags, P_META)) {
3711 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3712 return MDB_INVALID;
3713 }
3714
3715 m = METADATA(p);
3716 if (m->mm_magic != MDB_MAGIC) {
3717 DPUTS("meta has invalid magic");
3718 return MDB_INVALID;
3719 }
3720
3721 if (m->mm_version != MDB_DATA_VERSION) {
3722 DPRINTF(("database is version %u, expected version %u",
3723 m->mm_version, MDB_DATA_VERSION));
3724 return MDB_VERSION_MISMATCH;
3725 }
3726
3727 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3728 *meta = *m;
3729 }
3730 return 0;
3731 }
3732
3733 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3734 static void ESECT
mdb_env_init_meta0(MDB_env * env,MDB_meta * meta)3735 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3736 {
3737 meta->mm_magic = MDB_MAGIC;
3738 meta->mm_version = MDB_DATA_VERSION;
3739 meta->mm_mapsize = env->me_mapsize;
3740 meta->mm_psize = env->me_psize;
3741 meta->mm_last_pg = NUM_METAS-1;
3742 meta->mm_flags = env->me_flags & 0xffff;
3743 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3744 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3745 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3746 }
3747
3748 /** Write the environment parameters of a freshly created DB environment.
3749 * @param[in] env the environment handle
3750 * @param[in] meta the #MDB_meta to write
3751 * @return 0 on success, non-zero on failure.
3752 */
3753 static int ESECT
mdb_env_init_meta(MDB_env * env,MDB_meta * meta)3754 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3755 {
3756 MDB_page *p, *q;
3757 int rc;
3758 unsigned int psize;
3759 #ifdef _WIN32
3760 DWORD len;
3761 OVERLAPPED ov;
3762 memset(&ov, 0, sizeof(ov));
3763 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3764 ov.Offset = pos; \
3765 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3766 #else
3767 int len;
3768 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3769 len = pwrite(fd, ptr, size, pos); \
3770 if (len == -1 && ErrCode() == EINTR) continue; \
3771 rc = (len >= 0); break; } while(1)
3772 #endif
3773
3774 DPUTS("writing new meta page");
3775
3776 psize = env->me_psize;
3777
3778 p = calloc(NUM_METAS, psize);
3779 if (!p)
3780 return ENOMEM;
3781
3782 p->mp_pgno = 0;
3783 p->mp_flags = P_META;
3784 *(MDB_meta *)METADATA(p) = *meta;
3785
3786 q = (MDB_page *)((char *)p + psize);
3787 q->mp_pgno = 1;
3788 q->mp_flags = P_META;
3789 *(MDB_meta *)METADATA(q) = *meta;
3790
3791 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3792 if (!rc)
3793 rc = ErrCode();
3794 else if ((unsigned) len == psize * NUM_METAS)
3795 rc = MDB_SUCCESS;
3796 else
3797 rc = ENOSPC;
3798 free(p);
3799 return rc;
3800 }
3801
3802 /** Update the environment info to commit a transaction.
3803 * @param[in] txn the transaction that's being committed
3804 * @return 0 on success, non-zero on failure.
3805 */
3806 static int
mdb_env_write_meta(MDB_txn * txn)3807 mdb_env_write_meta(MDB_txn *txn)
3808 {
3809 MDB_env *env;
3810 MDB_meta meta, metab, *mp;
3811 unsigned flags;
3812 size_t mapsize;
3813 off_t off;
3814 int rc, len, toggle;
3815 char *ptr;
3816 HANDLE mfd;
3817 #ifdef _WIN32
3818 OVERLAPPED ov;
3819 #else
3820 int r2;
3821 #endif
3822
3823 toggle = txn->mt_txnid & 1;
3824 DPRINTF(("writing meta page %d for root page %"Z"u",
3825 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3826
3827 env = txn->mt_env;
3828 flags = env->me_flags;
3829 mp = env->me_metas[toggle];
3830 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3831 /* Persist any increases of mapsize config */
3832 if (mapsize < env->me_mapsize)
3833 mapsize = env->me_mapsize;
3834
3835 if (flags & MDB_WRITEMAP) {
3836 mp->mm_mapsize = mapsize;
3837 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3838 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3839 mp->mm_last_pg = txn->mt_next_pgno - 1;
3840 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3841 !(defined(__i386__) || defined(__x86_64__))
3842 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3843 __sync_synchronize();
3844 #endif
3845 mp->mm_txnid = txn->mt_txnid;
3846 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3847 unsigned meta_size = env->me_psize;
3848 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3849 ptr = (char *)mp - PAGEHDRSZ;
3850 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3851 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3852 ptr -= r2;
3853 meta_size += r2;
3854 #endif
3855 if (MDB_MSYNC(ptr, meta_size, rc)) {
3856 rc = ErrCode();
3857 goto fail;
3858 }
3859 }
3860 goto done;
3861 }
3862 metab.mm_txnid = mp->mm_txnid;
3863 metab.mm_last_pg = mp->mm_last_pg;
3864
3865 meta.mm_mapsize = mapsize;
3866 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3867 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3868 meta.mm_last_pg = txn->mt_next_pgno - 1;
3869 meta.mm_txnid = txn->mt_txnid;
3870
3871 off = offsetof(MDB_meta, mm_mapsize);
3872 ptr = (char *)&meta + off;
3873 len = sizeof(MDB_meta) - off;
3874 off += (char *)mp - env->me_map;
3875
3876 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
3877 * (me_mfd goes to the same file as me_fd, but writing to it
3878 * also syncs to disk. Avoids a separate fdatasync() call.)
3879 */
3880 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3881 #ifdef _WIN32
3882 {
3883 memset(&ov, 0, sizeof(ov));
3884 ov.Offset = off;
3885 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3886 rc = -1;
3887 }
3888 #else
3889 retry_write:
3890 rc = pwrite(mfd, ptr, len, off);
3891 #endif
3892 if (rc != len) {
3893 rc = rc < 0 ? ErrCode() : EIO;
3894 #ifndef _WIN32
3895 if (rc == EINTR)
3896 goto retry_write;
3897 #endif
3898 DPUTS("write failed, disk error?");
3899 /* On a failure, the pagecache still contains the new data.
3900 * Write some old data back, to prevent it from being used.
3901 * Use the non-SYNC fd; we know it will fail anyway.
3902 */
3903 meta.mm_last_pg = metab.mm_last_pg;
3904 meta.mm_txnid = metab.mm_txnid;
3905 #ifdef _WIN32
3906 memset(&ov, 0, sizeof(ov));
3907 ov.Offset = off;
3908 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3909 #else
3910 r2 = pwrite(env->me_fd, ptr, len, off);
3911 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3912 #endif
3913 fail:
3914 env->me_flags |= MDB_FATAL_ERROR;
3915 return rc;
3916 }
3917 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3918 CACHEFLUSH(env->me_map + off, len, DCACHE);
3919 done:
3920 /* Memory ordering issues are irrelevant; since the entire writer
3921 * is wrapped by wmutex, all of these changes will become visible
3922 * after the wmutex is unlocked. Since the DB is multi-version,
3923 * readers will get consistent data regardless of how fresh or
3924 * how stale their view of these values is.
3925 */
3926 if (env->me_txns)
3927 env->me_txns->mti_txnid = txn->mt_txnid;
3928
3929 return MDB_SUCCESS;
3930 }
3931
3932 /** Check both meta pages to see which one is newer.
3933 * @param[in] env the environment handle
3934 * @return newest #MDB_meta.
3935 */
3936 static MDB_meta *
mdb_env_pick_meta(const MDB_env * env)3937 mdb_env_pick_meta(const MDB_env *env)
3938 {
3939 MDB_meta *const *metas = env->me_metas;
3940 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3941 }
3942
3943 int ESECT
mdb_env_create(MDB_env ** env)3944 mdb_env_create(MDB_env **env)
3945 {
3946 MDB_env *e;
3947
3948 e = calloc(1, sizeof(MDB_env));
3949 if (!e)
3950 return ENOMEM;
3951
3952 e->me_maxreaders = DEFAULT_READERS;
3953 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3954 e->me_fd = INVALID_HANDLE_VALUE;
3955 e->me_lfd = INVALID_HANDLE_VALUE;
3956 e->me_mfd = INVALID_HANDLE_VALUE;
3957 #ifdef MDB_USE_POSIX_SEM
3958 e->me_rmutex = SEM_FAILED;
3959 e->me_wmutex = SEM_FAILED;
3960 #endif
3961 e->me_pid = getpid();
3962 GET_PAGESIZE(e->me_os_psize);
3963 VGMEMP_CREATE(e,0,0);
3964 *env = e;
3965 return MDB_SUCCESS;
3966 }
3967
3968 static int ESECT
mdb_env_map(MDB_env * env,void * addr)3969 mdb_env_map(MDB_env *env, void *addr)
3970 {
3971 MDB_page *p;
3972 unsigned int flags = env->me_flags;
3973 #ifdef _WIN32
3974 int rc;
3975 HANDLE mh;
3976 LONG sizelo, sizehi;
3977 size_t msize;
3978
3979 if (flags & MDB_RDONLY) {
3980 /* Don't set explicit map size, use whatever exists */
3981 msize = 0;
3982 sizelo = 0;
3983 sizehi = 0;
3984 } else {
3985 msize = env->me_mapsize;
3986 sizelo = msize & 0xffffffff;
3987 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3988
3989 /* Windows won't create mappings for zero length files.
3990 * and won't map more than the file size.
3991 * Just set the maxsize right now.
3992 */
3993 if (!(flags & MDB_WRITEMAP) && (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3994 || !SetEndOfFile(env->me_fd)
3995 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0))
3996 return ErrCode();
3997 }
3998
3999 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
4000 PAGE_READWRITE : PAGE_READONLY,
4001 sizehi, sizelo, NULL);
4002 if (!mh)
4003 return ErrCode();
4004 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
4005 FILE_MAP_WRITE : FILE_MAP_READ,
4006 0, 0, msize, addr);
4007 rc = env->me_map ? 0 : ErrCode();
4008 CloseHandle(mh);
4009 if (rc)
4010 return rc;
4011 #else
4012 int prot = PROT_READ;
4013 if (flags & MDB_WRITEMAP) {
4014 prot |= PROT_WRITE;
4015 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4016 return ErrCode();
4017 }
4018 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4019 env->me_fd, 0);
4020 if (env->me_map == MAP_FAILED) {
4021 env->me_map = NULL;
4022 return ErrCode();
4023 }
4024
4025 if (flags & MDB_NORDAHEAD) {
4026 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4027 #ifdef MADV_RANDOM
4028 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4029 #else
4030 #ifdef POSIX_MADV_RANDOM
4031 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4032 #endif /* POSIX_MADV_RANDOM */
4033 #endif /* MADV_RANDOM */
4034 }
4035 #endif /* _WIN32 */
4036
4037 /* Can happen because the address argument to mmap() is just a
4038 * hint. mmap() can pick another, e.g. if the range is in use.
4039 * The MAP_FIXED flag would prevent that, but then mmap could
4040 * instead unmap existing pages to make room for the new map.
4041 */
4042 if (addr && env->me_map != addr)
4043 return EBUSY; /* TODO: Make a new MDB_* error code? */
4044
4045 p = (MDB_page *)env->me_map;
4046 env->me_metas[0] = METADATA(p);
4047 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4048
4049 return MDB_SUCCESS;
4050 }
4051
4052 int ESECT
mdb_env_set_mapsize(MDB_env * env,size_t size)4053 mdb_env_set_mapsize(MDB_env *env, size_t size)
4054 {
4055 /* If env is already open, caller is responsible for making
4056 * sure there are no active txns.
4057 */
4058 if (env->me_map) {
4059 int rc;
4060 MDB_meta *meta;
4061 void *old;
4062 if (env->me_txn)
4063 return EINVAL;
4064 meta = mdb_env_pick_meta(env);
4065 if (!size)
4066 size = meta->mm_mapsize;
4067 {
4068 /* Silently round up to minimum if the size is too small */
4069 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4070 if (size < minsize)
4071 size = minsize;
4072 }
4073 munmap(env->me_map, env->me_mapsize);
4074 env->me_mapsize = size;
4075 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4076 rc = mdb_env_map(env, old);
4077 if (rc)
4078 return rc;
4079 }
4080 env->me_mapsize = size;
4081 if (env->me_psize)
4082 env->me_maxpg = env->me_mapsize / env->me_psize;
4083 return MDB_SUCCESS;
4084 }
4085
4086 int ESECT
mdb_env_set_maxdbs(MDB_env * env,MDB_dbi dbs)4087 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4088 {
4089 if (env->me_map)
4090 return EINVAL;
4091 env->me_maxdbs = dbs + CORE_DBS;
4092 return MDB_SUCCESS;
4093 }
4094
4095 int ESECT
mdb_env_set_maxreaders(MDB_env * env,unsigned int readers)4096 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4097 {
4098 if (env->me_map || readers < 1)
4099 return EINVAL;
4100 env->me_maxreaders = readers;
4101 return MDB_SUCCESS;
4102 }
4103
4104 int ESECT
mdb_env_get_maxreaders(MDB_env * env,unsigned int * readers)4105 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4106 {
4107 if (!env || !readers)
4108 return EINVAL;
4109 *readers = env->me_maxreaders;
4110 return MDB_SUCCESS;
4111 }
4112
4113 static int ESECT
mdb_fsize(HANDLE fd,size_t * size)4114 mdb_fsize(HANDLE fd, size_t *size)
4115 {
4116 #ifdef _WIN32
4117 LARGE_INTEGER fsize;
4118
4119 if (!GetFileSizeEx(fd, &fsize))
4120 return ErrCode();
4121
4122 *size = fsize.QuadPart;
4123 #else
4124 struct stat st;
4125
4126 if (fstat(fd, &st))
4127 return ErrCode();
4128
4129 *size = st.st_size;
4130 #endif
4131 return MDB_SUCCESS;
4132 }
4133
4134
4135 #ifdef _WIN32
4136 typedef wchar_t mdb_nchar_t;
4137 # define MDB_NAME(str) L##str
4138 # define mdb_name_cpy wcscpy
4139 #else
4140 /** Character type for file names: char on Unix, wchar_t on Windows */
4141 typedef char mdb_nchar_t;
4142 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4143 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4144 #endif
4145
4146 /** Filename - string of #mdb_nchar_t[] */
4147 typedef struct MDB_name {
4148 int mn_len; /**< Length */
4149 int mn_alloced; /**< True if #mn_val was malloced */
4150 mdb_nchar_t *mn_val; /**< Contents */
4151 } MDB_name;
4152
4153 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4154 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4155 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4156 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4157 };
4158
4159 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4160
4161 /** Set up filename + scratch area for filename suffix, for opening files.
4162 * It should be freed with #mdb_fname_destroy().
4163 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4164 *
4165 * @param[in] path Pathname for #mdb_env_open().
4166 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4167 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4168 */
4169 static int ESECT
mdb_fname_init(const char * path,unsigned envflags,MDB_name * fname)4170 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4171 {
4172 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4173 fname->mn_alloced = 0;
4174 #ifdef _WIN32
4175 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4176 #else
4177 fname->mn_len = strlen(path);
4178 if (no_suffix)
4179 fname->mn_val = (char *) path;
4180 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4181 fname->mn_alloced = 1;
4182 strcpy(fname->mn_val, path);
4183 }
4184 else
4185 return ENOMEM;
4186 return MDB_SUCCESS;
4187 #endif
4188 }
4189
4190 /** Destroy \b fname from #mdb_fname_init() */
4191 #define mdb_fname_destroy(fname) \
4192 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4193
4194 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4195 # define MDB_CLOEXEC O_CLOEXEC
4196 #else
4197 # define MDB_CLOEXEC 0
4198 #endif
4199
4200 /** File type, access mode etc. for #mdb_fopen() */
4201 enum mdb_fopen_type {
4202 #ifdef _WIN32
4203 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4204 #else
4205 /* A comment in mdb_fopen() explains some O_* flag choices. */
4206 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4207 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4208 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4209 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4210 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4211 * distinguish otherwise-equal MDB_O_* constants from each other.
4212 */
4213 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4214 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4215 #endif
4216 };
4217
4218 /** Open an LMDB file.
4219 * @param[in] env The LMDB environment.
4220 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4221 * appended if necessary to create the filename, without changing mn_len.
4222 * @param[in] which Determines file type, access mode, etc.
4223 * @param[in] mode The Unix permissions for the file, if we create it.
4224 * @param[out] res Resulting file handle.
4225 * @return 0 on success, non-zero on failure.
4226 */
4227 static int ESECT
mdb_fopen(const MDB_env * env,MDB_name * fname,enum mdb_fopen_type which,mdb_mode_t mode,HANDLE * res)4228 mdb_fopen(const MDB_env *env, MDB_name *fname,
4229 enum mdb_fopen_type which, mdb_mode_t mode,
4230 HANDLE *res)
4231 {
4232 int rc = MDB_SUCCESS;
4233 HANDLE fd;
4234 #ifdef _WIN32
4235 DWORD acc, share, disp, attrs;
4236 #else
4237 int flags;
4238 #endif
4239
4240 if (fname->mn_alloced) /* modifiable copy */
4241 mdb_name_cpy(fname->mn_val + fname->mn_len,
4242 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4243
4244 /* The directory must already exist. Usually the file need not.
4245 * MDB_O_META requires the file because we already created it using
4246 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4247 *
4248 * With MDB_O_COPY we do not want the OS to cache the writes, since
4249 * the source data is already in the OS cache.
4250 *
4251 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4252 * to avoid the flock() issues noted under Caveats in lmdb.h.
4253 * Also set it for other filehandles which the user cannot get at
4254 * and close himself, which he may need after fork(). I.e. all but
4255 * me_fd, which programs do use via mdb_env_get_fd().
4256 */
4257
4258 #ifdef _WIN32
4259 acc = GENERIC_READ|GENERIC_WRITE;
4260 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4261 disp = OPEN_ALWAYS;
4262 attrs = FILE_ATTRIBUTE_NORMAL;
4263 switch (which) {
4264 case MDB_O_RDONLY: /* read-only datafile */
4265 acc = GENERIC_READ;
4266 disp = OPEN_EXISTING;
4267 break;
4268 case MDB_O_META: /* for writing metapages */
4269 acc = GENERIC_WRITE;
4270 disp = OPEN_EXISTING;
4271 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4272 break;
4273 case MDB_O_COPY: /* mdb_env_copy() & co */
4274 acc = GENERIC_WRITE;
4275 share = 0;
4276 disp = CREATE_NEW;
4277 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4278 break;
4279 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4280 }
4281 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4282 #else
4283 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4284 #endif
4285
4286 if (fd == INVALID_HANDLE_VALUE)
4287 rc = ErrCode();
4288 #ifndef _WIN32
4289 else {
4290 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4291 /* Set CLOEXEC if we could not pass it to open() */
4292 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4293 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4294 }
4295 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4296 /* This may require buffer alignment. There is no portable
4297 * way to ask how much, so we require OS pagesize alignment.
4298 */
4299 # ifdef F_NOCACHE /* __APPLE__ */
4300 (void) fcntl(fd, F_NOCACHE, 1);
4301 # elif defined O_DIRECT
4302 /* open(...O_DIRECT...) would break on filesystems without
4303 * O_DIRECT support (ITS#7682). Try to set it here instead.
4304 */
4305 if ((flags = fcntl(fd, F_GETFL)) != -1)
4306 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4307 # endif
4308 }
4309 }
4310 #endif /* !_WIN32 */
4311
4312 *res = fd;
4313 return rc;
4314 }
4315
4316
4317 #ifdef BROKEN_FDATASYNC
4318 #include <sys/utsname.h>
4319 #include <sys/vfs.h>
4320 #endif
4321
4322 /** Further setup required for opening an LMDB environment
4323 */
4324 static int ESECT
mdb_env_open2(MDB_env * env)4325 mdb_env_open2(MDB_env *env)
4326 {
4327 unsigned int flags = env->me_flags;
4328 int i, newenv = 0, rc;
4329 MDB_meta meta;
4330
4331 #ifdef _WIN32
4332 /* See if we should use QueryLimited */
4333 rc = GetVersion();
4334 if ((rc & 0xff) > 5)
4335 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4336 else
4337 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4338 #endif /* _WIN32 */
4339
4340 #ifdef BROKEN_FDATASYNC
4341 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4342 * https://lkml.org/lkml/2012/9/3/83
4343 * Kernels after 3.6-rc6 are known good.
4344 * https://lkml.org/lkml/2012/9/10/556
4345 * See if the DB is on ext3/ext4, then check for new enough kernel
4346 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4347 * to be patched.
4348 */
4349 {
4350 struct statfs st;
4351 fstatfs(env->me_fd, &st);
4352 while (st.f_type == 0xEF53) {
4353 struct utsname uts;
4354 int i;
4355 uname(&uts);
4356 if (uts.release[0] < '3') {
4357 if (!strncmp(uts.release, "2.6.32.", 7)) {
4358 i = atoi(uts.release+7);
4359 if (i >= 60)
4360 break; /* 2.6.32.60 and newer is OK */
4361 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4362 i = atoi(uts.release+7);
4363 if (i >= 15)
4364 break; /* 2.6.34.15 and newer is OK */
4365 }
4366 } else if (uts.release[0] == '3') {
4367 i = atoi(uts.release+2);
4368 if (i > 5)
4369 break; /* 3.6 and newer is OK */
4370 if (i == 5) {
4371 i = atoi(uts.release+4);
4372 if (i >= 4)
4373 break; /* 3.5.4 and newer is OK */
4374 } else if (i == 2) {
4375 i = atoi(uts.release+4);
4376 if (i >= 30)
4377 break; /* 3.2.30 and newer is OK */
4378 }
4379 } else { /* 4.x and newer is OK */
4380 break;
4381 }
4382 env->me_flags |= MDB_FSYNCONLY;
4383 break;
4384 }
4385 }
4386 #endif
4387
4388 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4389 if (i != ENOENT)
4390 return i;
4391 DPUTS("new mdbenv");
4392 newenv = 1;
4393 env->me_psize = env->me_os_psize;
4394 if (env->me_psize > MAX_PAGESIZE)
4395 env->me_psize = MAX_PAGESIZE;
4396 memset(&meta, 0, sizeof(meta));
4397 mdb_env_init_meta0(env, &meta);
4398 meta.mm_mapsize = DEFAULT_MAPSIZE;
4399 } else {
4400 env->me_psize = meta.mm_psize;
4401 }
4402
4403 /* Was a mapsize configured? */
4404 if (!env->me_mapsize) {
4405 env->me_mapsize = meta.mm_mapsize;
4406 }
4407 {
4408 /* Make sure mapsize >= committed data size. Even when using
4409 * mm_mapsize, which could be broken in old files (ITS#7789).
4410 */
4411 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4412 if (env->me_mapsize < minsize)
4413 env->me_mapsize = minsize;
4414 }
4415 meta.mm_mapsize = env->me_mapsize;
4416
4417 if (newenv && !(flags & MDB_FIXEDMAP)) {
4418 /* mdb_env_map() may grow the datafile. Write the metapages
4419 * first, so the file will be valid if initialization fails.
4420 * Except with FIXEDMAP, since we do not yet know mm_address.
4421 * We could fill in mm_address later, but then a different
4422 * program might end up doing that - one with a memory layout
4423 * and map address which does not suit the main program.
4424 */
4425 rc = mdb_env_init_meta(env, &meta);
4426 if (rc)
4427 return rc;
4428 newenv = 0;
4429 }
4430
4431 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4432 if (rc)
4433 return rc;
4434
4435 if (newenv) {
4436 if (flags & MDB_FIXEDMAP)
4437 meta.mm_address = env->me_map;
4438 i = mdb_env_init_meta(env, &meta);
4439 if (i != MDB_SUCCESS) {
4440 return i;
4441 }
4442 }
4443
4444 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4445 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4446 - sizeof(indx_t);
4447 #if !(MDB_MAXKEYSIZE)
4448 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4449 #endif
4450 env->me_maxpg = env->me_mapsize / env->me_psize;
4451
4452 #if MDB_DEBUG
4453 {
4454 MDB_meta *meta = mdb_env_pick_meta(env);
4455 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4456
4457 DPRINTF(("opened database version %u, pagesize %u",
4458 meta->mm_version, env->me_psize));
4459 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4460 DPRINTF(("depth: %u", db->md_depth));
4461 DPRINTF(("entries: %"Z"u", db->md_entries));
4462 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4463 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4464 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4465 DPRINTF(("root: %"Z"u", db->md_root));
4466 }
4467 #endif
4468
4469 return MDB_SUCCESS;
4470 }
4471
4472
4473 /** Release a reader thread's slot in the reader lock table.
4474 * This function is called automatically when a thread exits.
4475 * @param[in] ptr This points to the slot in the reader lock table.
4476 */
4477 static void
mdb_env_reader_dest(void * ptr)4478 mdb_env_reader_dest(void *ptr)
4479 {
4480 MDB_reader *reader = ptr;
4481
4482 #ifndef _WIN32
4483 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
4484 #endif
4485 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
4486 reader->mr_pid = 0;
4487 }
4488
4489 #ifdef _WIN32
4490 /** Junk for arranging thread-specific callbacks on Windows. This is
4491 * necessarily platform and compiler-specific. Windows supports up
4492 * to 1088 keys. Let's assume nobody opens more than 64 environments
4493 * in a single process, for now. They can override this if needed.
4494 */
4495 #ifndef MAX_TLS_KEYS
4496 #define MAX_TLS_KEYS 64
4497 #endif
4498 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4499 static int mdb_tls_nkeys;
4500
mdb_tls_callback(PVOID module,DWORD reason,PVOID ptr)4501 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4502 {
4503 int i;
4504 switch(reason) {
4505 case DLL_PROCESS_ATTACH: break;
4506 case DLL_THREAD_ATTACH: break;
4507 case DLL_THREAD_DETACH:
4508 for (i=0; i<mdb_tls_nkeys; i++) {
4509 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4510 if (r) {
4511 mdb_env_reader_dest(r);
4512 }
4513 }
4514 break;
4515 case DLL_PROCESS_DETACH: break;
4516 }
4517 }
4518 #ifdef __GNUC__
4519 #ifdef _WIN64
4520 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4521 #else
4522 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4523 #endif
4524 #else
4525 #ifdef _WIN64
4526 /* Force some symbol references.
4527 * _tls_used forces the linker to create the TLS directory if not already done
4528 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4529 */
4530 #pragma comment(linker, "/INCLUDE:_tls_used")
4531 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4532 #pragma const_seg(".CRT$XLB")
4533 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4534 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4535 #pragma const_seg()
4536 #else /* _WIN32 */
4537 #pragma comment(linker, "/INCLUDE:__tls_used")
4538 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4539 #pragma data_seg(".CRT$XLB")
4540 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4541 #pragma data_seg()
4542 #endif /* WIN 32/64 */
4543 #endif /* !__GNUC__ */
4544 #endif
4545
4546 /** Downgrade the exclusive lock on the region back to shared */
4547 static int ESECT
mdb_env_share_locks(MDB_env * env,int * excl)4548 mdb_env_share_locks(MDB_env *env, int *excl)
4549 {
4550 int rc = 0;
4551 MDB_meta *meta = mdb_env_pick_meta(env);
4552
4553 env->me_txns->mti_txnid = meta->mm_txnid;
4554
4555 #ifdef _WIN32
4556 {
4557 OVERLAPPED ov;
4558 /* First acquire a shared lock. The Unlock will
4559 * then release the existing exclusive lock.
4560 */
4561 memset(&ov, 0, sizeof(ov));
4562 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4563 rc = ErrCode();
4564 } else {
4565 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4566 *excl = 0;
4567 }
4568 }
4569 #else
4570 {
4571 struct flock lock_info;
4572 /* The shared lock replaces the existing lock */
4573 memset((void *)&lock_info, 0, sizeof(lock_info));
4574 lock_info.l_type = F_RDLCK;
4575 lock_info.l_whence = SEEK_SET;
4576 lock_info.l_start = 0;
4577 lock_info.l_len = 1;
4578 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4579 (rc = ErrCode()) == EINTR) ;
4580 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4581 }
4582 #endif
4583
4584 return rc;
4585 }
4586
4587 /** Try to get exclusive lock, otherwise shared.
4588 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4589 */
4590 static int ESECT
mdb_env_excl_lock(MDB_env * env,int * excl)4591 mdb_env_excl_lock(MDB_env *env, int *excl)
4592 {
4593 int rc = 0;
4594 #ifdef _WIN32
4595 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4596 *excl = 1;
4597 } else {
4598 OVERLAPPED ov;
4599 memset(&ov, 0, sizeof(ov));
4600 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4601 *excl = 0;
4602 } else {
4603 rc = ErrCode();
4604 }
4605 }
4606 #else
4607 struct flock lock_info;
4608 memset((void *)&lock_info, 0, sizeof(lock_info));
4609 lock_info.l_type = F_WRLCK;
4610 lock_info.l_whence = SEEK_SET;
4611 lock_info.l_start = 0;
4612 lock_info.l_len = 1;
4613 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4614 (rc = ErrCode()) == EINTR) ;
4615 if (!rc) {
4616 *excl = 1;
4617 } else
4618 # ifndef MDB_USE_POSIX_MUTEX
4619 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4620 # endif
4621 {
4622 lock_info.l_type = F_RDLCK;
4623 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4624 (rc = ErrCode()) == EINTR) ;
4625 if (rc == 0)
4626 *excl = 0;
4627 }
4628 #endif
4629 return rc;
4630 }
4631
4632 #ifdef MDB_USE_HASH
4633 /*
4634 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4635 *
4636 * @(#) $Revision: 5.1 $
4637 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4638 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4639 *
4640 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4641 *
4642 ***
4643 *
4644 * Please do not copyright this code. This code is in the public domain.
4645 *
4646 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4647 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4648 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4649 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4650 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4651 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4652 * PERFORMANCE OF THIS SOFTWARE.
4653 *
4654 * By:
4655 * chongo <Landon Curt Noll> /\oo/\
4656 * http://www.isthe.com/chongo/
4657 *
4658 * Share and Enjoy! :-)
4659 */
4660
4661 typedef unsigned long long mdb_hash_t;
4662 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4663
4664 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4665 * @param[in] val value to hash
4666 * @param[in] hval initial value for hash
4667 * @return 64 bit hash
4668 *
4669 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4670 * hval arg on the first call.
4671 */
4672 static mdb_hash_t
mdb_hash_val(MDB_val * val,mdb_hash_t hval)4673 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4674 {
4675 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4676 unsigned char *end = s + val->mv_size;
4677 /*
4678 * FNV-1a hash each octet of the string
4679 */
4680 while (s < end) {
4681 /* xor the bottom with the current octet */
4682 hval ^= (mdb_hash_t)*s++;
4683
4684 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4685 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4686 (hval << 7) + (hval << 8) + (hval << 40);
4687 }
4688 /* return our new hash value */
4689 return hval;
4690 }
4691
4692 /** Hash the string and output the encoded hash.
4693 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4694 * very short name limits. We don't care about the encoding being reversible,
4695 * we just want to preserve as many bits of the input as possible in a
4696 * small printable string.
4697 * @param[in] str string to hash
4698 * @param[out] encbuf an array of 11 chars to hold the hash
4699 */
4700 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4701
4702 static void ESECT
mdb_pack85(unsigned long l,char * out)4703 mdb_pack85(unsigned long l, char *out)
4704 {
4705 int i;
4706
4707 for (i=0; i<5; i++) {
4708 *out++ = mdb_a85[l % 85];
4709 l /= 85;
4710 }
4711 }
4712
4713 static void ESECT
mdb_hash_enc(MDB_val * val,char * encbuf)4714 mdb_hash_enc(MDB_val *val, char *encbuf)
4715 {
4716 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4717
4718 mdb_pack85(h, encbuf);
4719 mdb_pack85(h>>32, encbuf+5);
4720 encbuf[10] = '\0';
4721 }
4722 #endif
4723
4724 /** Open and/or initialize the lock region for the environment.
4725 * @param[in] env The LMDB environment.
4726 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
4727 * @param[in] mode The Unix permissions for the file, if we create it.
4728 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4729 * @return 0 on success, non-zero on failure.
4730 */
4731 static int ESECT
mdb_env_setup_locks(MDB_env * env,MDB_name * fname,int mode,int * excl)4732 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
4733 {
4734 #ifdef _WIN32
4735 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4736 #else
4737 # define MDB_ERRCODE_ROFS EROFS
4738 #endif
4739 int rc;
4740 off_t size, rsize;
4741
4742 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
4743 if (rc) {
4744 /* Omit lockfile if read-only env on read-only filesystem */
4745 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4746 return MDB_SUCCESS;
4747 }
4748 goto fail;
4749 }
4750
4751 if (!(env->me_flags & MDB_NOTLS)) {
4752 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4753 if (rc)
4754 goto fail;
4755 env->me_flags |= MDB_ENV_TXKEY;
4756 #ifdef _WIN32
4757 /* Windows TLS callbacks need help finding their TLS info. */
4758 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4759 rc = MDB_TLS_FULL;
4760 goto fail;
4761 }
4762 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4763 #endif
4764 }
4765
4766 /* Try to get exclusive lock. If we succeed, then
4767 * nobody is using the lock region and we should initialize it.
4768 */
4769 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4770
4771 #ifdef _WIN32
4772 size = GetFileSize(env->me_lfd, NULL);
4773 #else
4774 size = lseek(env->me_lfd, 0, SEEK_END);
4775 if (size == -1) goto fail_errno;
4776 #endif
4777 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4778 if (size < rsize && *excl > 0) {
4779 #ifdef _WIN32
4780 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4781 || !SetEndOfFile(env->me_lfd))
4782 goto fail_errno;
4783 #else
4784 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4785 #endif
4786 } else {
4787 rsize = size;
4788 size = rsize - sizeof(MDB_txninfo);
4789 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4790 }
4791 {
4792 #ifdef _WIN32
4793 HANDLE mh;
4794 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4795 0, 0, NULL);
4796 if (!mh) goto fail_errno;
4797 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4798 CloseHandle(mh);
4799 if (!env->me_txns) goto fail_errno;
4800 #else
4801 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4802 env->me_lfd, 0);
4803 if (m == MAP_FAILED) goto fail_errno;
4804 env->me_txns = m;
4805 #endif
4806 }
4807 if (*excl > 0) {
4808 #ifdef _WIN32
4809 BY_HANDLE_FILE_INFORMATION stbuf;
4810 struct {
4811 DWORD volume;
4812 DWORD nhigh;
4813 DWORD nlow;
4814 } idbuf;
4815 MDB_val val;
4816 char encbuf[11];
4817
4818 if (!mdb_sec_inited) {
4819 InitializeSecurityDescriptor(&mdb_null_sd,
4820 SECURITY_DESCRIPTOR_REVISION);
4821 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4822 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4823 mdb_all_sa.bInheritHandle = FALSE;
4824 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4825 mdb_sec_inited = 1;
4826 }
4827 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4828 idbuf.volume = stbuf.dwVolumeSerialNumber;
4829 idbuf.nhigh = stbuf.nFileIndexHigh;
4830 idbuf.nlow = stbuf.nFileIndexLow;
4831 val.mv_data = &idbuf;
4832 val.mv_size = sizeof(idbuf);
4833 mdb_hash_enc(&val, encbuf);
4834 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4835 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4836 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4837 if (!env->me_rmutex) goto fail_errno;
4838 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4839 if (!env->me_wmutex) goto fail_errno;
4840 #elif defined(MDB_USE_POSIX_SEM)
4841 struct stat stbuf;
4842 struct {
4843 dev_t dev;
4844 ino_t ino;
4845 } idbuf;
4846 MDB_val val;
4847 char encbuf[11];
4848
4849 #if defined(__NetBSD__)
4850 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4851 #endif
4852 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4853 idbuf.dev = stbuf.st_dev;
4854 idbuf.ino = stbuf.st_ino;
4855 val.mv_data = &idbuf;
4856 val.mv_size = sizeof(idbuf);
4857 mdb_hash_enc(&val, encbuf);
4858 #ifdef MDB_SHORT_SEMNAMES
4859 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4860 #endif
4861 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4862 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4863 /* Clean up after a previous run, if needed: Try to
4864 * remove both semaphores before doing anything else.
4865 */
4866 sem_unlink(env->me_txns->mti_rmname);
4867 sem_unlink(env->me_txns->mti_wmname);
4868 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4869 O_CREAT|O_EXCL, mode, 1);
4870 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4871 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4872 O_CREAT|O_EXCL, mode, 1);
4873 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4874 #else /* MDB_USE_POSIX_MUTEX: */
4875 pthread_mutexattr_t mattr;
4876
4877 /* Solaris needs this before initing a robust mutex. Otherwise
4878 * it may skip the init and return EBUSY "seems someone already
4879 * inited" or EINVAL "it was inited differently".
4880 */
4881 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4882 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4883
4884 if ((rc = pthread_mutexattr_init(&mattr)))
4885 goto fail;
4886
4887 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4888 #ifdef MDB_ROBUST_SUPPORTED
4889 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4890 #endif
4891 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4892 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4893 pthread_mutexattr_destroy(&mattr);
4894 if (rc)
4895 goto fail;
4896 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4897
4898 env->me_txns->mti_magic = MDB_MAGIC;
4899 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4900 env->me_txns->mti_txnid = 0;
4901 env->me_txns->mti_numreaders = 0;
4902
4903 } else {
4904 if (env->me_txns->mti_magic != MDB_MAGIC) {
4905 DPUTS("lock region has invalid magic");
4906 rc = MDB_INVALID;
4907 goto fail;
4908 }
4909 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4910 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4911 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4912 rc = MDB_VERSION_MISMATCH;
4913 goto fail;
4914 }
4915 rc = ErrCode();
4916 if (rc && rc != EACCES && rc != EAGAIN) {
4917 goto fail;
4918 }
4919 #ifdef _WIN32
4920 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4921 if (!env->me_rmutex) goto fail_errno;
4922 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4923 if (!env->me_wmutex) goto fail_errno;
4924 #elif defined(MDB_USE_POSIX_SEM)
4925 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4926 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4927 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4928 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4929 #endif
4930 }
4931 return MDB_SUCCESS;
4932
4933 fail_errno:
4934 rc = ErrCode();
4935 fail:
4936 return rc;
4937 }
4938
4939 /** Only a subset of the @ref mdb_env flags can be changed
4940 * at runtime. Changing other flags requires closing the
4941 * environment and re-opening it with the new flags.
4942 */
4943 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4944 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4945 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4946
4947 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4948 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4949 #endif
4950
4951 int ESECT
mdb_env_open(MDB_env * env,const char * path,unsigned int flags,mdb_mode_t mode)4952 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4953 {
4954 int rc, excl = -1;
4955 MDB_name fname;
4956
4957 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4958 return EINVAL;
4959
4960 flags |= env->me_flags;
4961
4962 rc = mdb_fname_init(path, flags, &fname);
4963 if (rc)
4964 return rc;
4965
4966 if (flags & MDB_RDONLY) {
4967 /* silently ignore WRITEMAP when we're only getting read access */
4968 flags &= ~MDB_WRITEMAP;
4969 } else {
4970 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4971 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4972 rc = ENOMEM;
4973 }
4974 env->me_flags = flags |= MDB_ENV_ACTIVE;
4975 if (rc)
4976 goto leave;
4977
4978 env->me_path = strdup(path);
4979 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4980 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4981 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4982 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4983 rc = ENOMEM;
4984 goto leave;
4985 }
4986 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4987
4988 /* For RDONLY, get lockfile after we know datafile exists */
4989 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4990 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
4991 if (rc)
4992 goto leave;
4993 }
4994
4995 rc = mdb_fopen(env, &fname,
4996 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
4997 mode, &env->me_fd);
4998 if (rc)
4999 goto leave;
5000
5001 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5002 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5003 if (rc)
5004 goto leave;
5005 }
5006
5007 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5008 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
5009 /* Synchronous fd for meta writes. Needed even with
5010 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5011 */
5012 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
5013 if (rc)
5014 goto leave;
5015 }
5016 DPRINTF(("opened dbenv %p", (void *) env));
5017 if (excl > 0) {
5018 rc = mdb_env_share_locks(env, &excl);
5019 if (rc)
5020 goto leave;
5021 }
5022 if (!(flags & MDB_RDONLY)) {
5023 MDB_txn *txn;
5024 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5025 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5026 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5027 (txn = calloc(1, size)))
5028 {
5029 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5030 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5031 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5032 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5033 txn->mt_env = env;
5034 txn->mt_dbxs = env->me_dbxs;
5035 txn->mt_flags = MDB_TXN_FINISHED;
5036 env->me_txn0 = txn;
5037 } else {
5038 rc = ENOMEM;
5039 }
5040 }
5041 }
5042
5043 leave:
5044 if (rc) {
5045 mdb_env_close0(env, excl);
5046 }
5047 mdb_fname_destroy(fname);
5048 return rc;
5049 }
5050
5051 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5052 static void ESECT
mdb_env_close0(MDB_env * env,int excl)5053 mdb_env_close0(MDB_env *env, int excl)
5054 {
5055 int i;
5056
5057 if (!(env->me_flags & MDB_ENV_ACTIVE))
5058 return;
5059
5060 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5061 if (env->me_dbxs) {
5062 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5063 free(env->me_dbxs[i].md_name.mv_data);
5064 free(env->me_dbxs);
5065 }
5066
5067 free(env->me_pbuf);
5068 free(env->me_dbiseqs);
5069 free(env->me_dbflags);
5070 free(env->me_path);
5071 free(env->me_dirty_list);
5072 free(env->me_txn0);
5073 mdb_midl_free(env->me_free_pgs);
5074
5075 if (env->me_flags & MDB_ENV_TXKEY) {
5076 pthread_key_delete(env->me_txkey);
5077 #ifdef _WIN32
5078 /* Delete our key from the global list */
5079 for (i=0; i<mdb_tls_nkeys; i++)
5080 if (mdb_tls_keys[i] == env->me_txkey) {
5081 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5082 mdb_tls_nkeys--;
5083 break;
5084 }
5085 #endif
5086 }
5087
5088 if (env->me_map) {
5089 munmap(env->me_map, env->me_mapsize);
5090 }
5091 if (env->me_mfd != INVALID_HANDLE_VALUE)
5092 (void) close(env->me_mfd);
5093 if (env->me_fd != INVALID_HANDLE_VALUE)
5094 (void) close(env->me_fd);
5095 if (env->me_txns) {
5096 MDB_PID_T pid = getpid();
5097 /* Clearing readers is done in this function because
5098 * me_txkey with its destructor must be disabled first.
5099 *
5100 * We skip the the reader mutex, so we touch only
5101 * data owned by this process (me_close_readers and
5102 * our readers), and clear each reader atomically.
5103 */
5104 for (i = env->me_close_readers; --i >= 0; )
5105 if (env->me_txns->mti_readers[i].mr_pid == pid)
5106 env->me_txns->mti_readers[i].mr_pid = 0;
5107 #ifdef _WIN32
5108 if (env->me_rmutex) {
5109 CloseHandle(env->me_rmutex);
5110 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5111 }
5112 /* Windows automatically destroys the mutexes when
5113 * the last handle closes.
5114 */
5115 #elif defined(MDB_USE_POSIX_SEM)
5116 if (env->me_rmutex != SEM_FAILED) {
5117 sem_close(env->me_rmutex);
5118 if (env->me_wmutex != SEM_FAILED)
5119 sem_close(env->me_wmutex);
5120 /* If we have the filelock: If we are the
5121 * only remaining user, clean up semaphores.
5122 */
5123 if (excl == 0)
5124 mdb_env_excl_lock(env, &excl);
5125 if (excl > 0) {
5126 sem_unlink(env->me_txns->mti_rmname);
5127 sem_unlink(env->me_txns->mti_wmname);
5128 }
5129 }
5130 #endif
5131 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5132 }
5133 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5134 #ifdef _WIN32
5135 if (excl >= 0) {
5136 /* Unlock the lockfile. Windows would have unlocked it
5137 * after closing anyway, but not necessarily at once.
5138 */
5139 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5140 }
5141 #endif
5142 (void) close(env->me_lfd);
5143 }
5144
5145 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5146 }
5147
5148 void ESECT
mdb_env_close(MDB_env * env)5149 mdb_env_close(MDB_env *env)
5150 {
5151 MDB_page *dp;
5152
5153 if (env == NULL)
5154 return;
5155
5156 VGMEMP_DESTROY(env);
5157 while ((dp = env->me_dpages) != NULL) {
5158 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5159 env->me_dpages = dp->mp_next;
5160 free(dp);
5161 }
5162
5163 mdb_env_close0(env, 0);
5164 free(env);
5165 }
5166
5167 /** Compare two items pointing at aligned size_t's */
5168 static int
mdb_cmp_long(const MDB_val * a,const MDB_val * b)5169 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5170 {
5171 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
5172 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
5173 }
5174
5175 /** Compare two items pointing at aligned unsigned int's.
5176 *
5177 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5178 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5179 */
5180 static int
mdb_cmp_int(const MDB_val * a,const MDB_val * b)5181 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5182 {
5183 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5184 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5185 }
5186
5187 /** Compare two items pointing at unsigned ints of unknown alignment.
5188 * Nodes and keys are guaranteed to be 2-byte aligned.
5189 */
5190 static int
mdb_cmp_cint(const MDB_val * a,const MDB_val * b)5191 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5192 {
5193 #if BYTE_ORDER == LITTLE_ENDIAN
5194 unsigned short *u, *c;
5195 int x;
5196
5197 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5198 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5199 do {
5200 x = *--u - *--c;
5201 } while(!x && u > (unsigned short *)a->mv_data);
5202 return x;
5203 #else
5204 unsigned short *u, *c, *end;
5205 int x;
5206
5207 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5208 u = (unsigned short *)a->mv_data;
5209 c = (unsigned short *)b->mv_data;
5210 do {
5211 x = *u++ - *c++;
5212 } while(!x && u < end);
5213 return x;
5214 #endif
5215 }
5216
5217 /** Compare two items lexically */
5218 static int
mdb_cmp_memn(const MDB_val * a,const MDB_val * b)5219 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5220 {
5221 int diff;
5222 ssize_t len_diff;
5223 unsigned int len;
5224
5225 len = a->mv_size;
5226 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5227 if (len_diff > 0) {
5228 len = b->mv_size;
5229 len_diff = 1;
5230 }
5231
5232 diff = memcmp(a->mv_data, b->mv_data, len);
5233 return diff ? diff : len_diff<0 ? -1 : len_diff;
5234 }
5235
5236 /** Compare two items in reverse byte order */
5237 static int
mdb_cmp_memnr(const MDB_val * a,const MDB_val * b)5238 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5239 {
5240 const unsigned char *p1, *p2, *p1_lim;
5241 ssize_t len_diff;
5242 int diff;
5243
5244 p1_lim = (const unsigned char *)a->mv_data;
5245 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5246 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5247
5248 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5249 if (len_diff > 0) {
5250 p1_lim += len_diff;
5251 len_diff = 1;
5252 }
5253
5254 while (p1 > p1_lim) {
5255 diff = *--p1 - *--p2;
5256 if (diff)
5257 return diff;
5258 }
5259 return len_diff<0 ? -1 : len_diff;
5260 }
5261
5262 /** Search for key within a page, using binary search.
5263 * Returns the smallest entry larger or equal to the key.
5264 * If exactp is non-null, stores whether the found entry was an exact match
5265 * in *exactp (1 or 0).
5266 * Updates the cursor index with the index of the found entry.
5267 * If no entry larger or equal to the key is found, returns NULL.
5268 */
5269 static MDB_node *
mdb_node_search(MDB_cursor * mc,MDB_val * key,int * exactp)5270 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5271 {
5272 unsigned int i = 0, nkeys;
5273 int low, high;
5274 int rc = 0;
5275 MDB_page *mp = mc->mc_pg[mc->mc_top];
5276 MDB_node *node = NULL;
5277 MDB_val nodekey;
5278 MDB_cmp_func *cmp;
5279 DKBUF;
5280
5281 nkeys = NUMKEYS(mp);
5282
5283 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5284 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5285 mdb_dbg_pgno(mp)));
5286
5287 low = IS_LEAF(mp) ? 0 : 1;
5288 high = nkeys - 1;
5289 cmp = mc->mc_dbx->md_cmp;
5290
5291 /* Branch pages have no data, so if using integer keys,
5292 * alignment is guaranteed. Use faster mdb_cmp_int.
5293 */
5294 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5295 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5296 cmp = mdb_cmp_long;
5297 else
5298 cmp = mdb_cmp_int;
5299 }
5300
5301 if (IS_LEAF2(mp)) {
5302 nodekey.mv_size = mc->mc_db->md_pad;
5303 node = NODEPTR(mp, 0); /* fake */
5304 while (low <= high) {
5305 i = (low + high) >> 1;
5306 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5307 rc = cmp(key, &nodekey);
5308 DPRINTF(("found leaf index %u [%s], rc = %i",
5309 i, DKEY(&nodekey), rc));
5310 if (rc == 0)
5311 break;
5312 if (rc > 0)
5313 low = i + 1;
5314 else
5315 high = i - 1;
5316 }
5317 } else {
5318 while (low <= high) {
5319 i = (low + high) >> 1;
5320
5321 node = NODEPTR(mp, i);
5322 nodekey.mv_size = NODEKSZ(node);
5323 nodekey.mv_data = NODEKEY(node);
5324
5325 rc = cmp(key, &nodekey);
5326 #if MDB_DEBUG
5327 if (IS_LEAF(mp))
5328 DPRINTF(("found leaf index %u [%s], rc = %i",
5329 i, DKEY(&nodekey), rc));
5330 else
5331 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5332 i, DKEY(&nodekey), NODEPGNO(node), rc));
5333 #endif
5334 if (rc == 0)
5335 break;
5336 if (rc > 0)
5337 low = i + 1;
5338 else
5339 high = i - 1;
5340 }
5341 }
5342
5343 if (rc > 0) { /* Found entry is less than the key. */
5344 i++; /* Skip to get the smallest entry larger than key. */
5345 if (!IS_LEAF2(mp))
5346 node = NODEPTR(mp, i);
5347 }
5348 if (exactp)
5349 *exactp = (rc == 0 && nkeys > 0);
5350 /* store the key index */
5351 mc->mc_ki[mc->mc_top] = i;
5352 if (i >= nkeys)
5353 /* There is no entry larger or equal to the key. */
5354 return NULL;
5355
5356 /* nodeptr is fake for LEAF2 */
5357 return node;
5358 }
5359
5360 #if 0
5361 static void
5362 mdb_cursor_adjust(MDB_cursor *mc, func)
5363 {
5364 MDB_cursor *m2;
5365
5366 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5367 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5368 func(mc, m2);
5369 }
5370 }
5371 }
5372 #endif
5373
5374 /** Pop a page off the top of the cursor's stack. */
5375 static void
mdb_cursor_pop(MDB_cursor * mc)5376 mdb_cursor_pop(MDB_cursor *mc)
5377 {
5378 if (mc->mc_snum) {
5379 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5380 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5381
5382 mc->mc_snum--;
5383 if (mc->mc_snum) {
5384 mc->mc_top--;
5385 } else {
5386 mc->mc_flags &= ~C_INITIALIZED;
5387 }
5388 }
5389 }
5390
5391 /** Push a page onto the top of the cursor's stack.
5392 * Set #MDB_TXN_ERROR on failure.
5393 */
5394 static int
mdb_cursor_push(MDB_cursor * mc,MDB_page * mp)5395 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5396 {
5397 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5398 DDBI(mc), (void *) mc));
5399
5400 if (mc->mc_snum >= CURSOR_STACK) {
5401 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5402 return MDB_CURSOR_FULL;
5403 }
5404
5405 mc->mc_top = mc->mc_snum++;
5406 mc->mc_pg[mc->mc_top] = mp;
5407 mc->mc_ki[mc->mc_top] = 0;
5408
5409 return MDB_SUCCESS;
5410 }
5411
5412 /** Find the address of the page corresponding to a given page number.
5413 * Set #MDB_TXN_ERROR on failure.
5414 * @param[in] mc the cursor accessing the page.
5415 * @param[in] pgno the page number for the page to retrieve.
5416 * @param[out] ret address of a pointer where the page's address will be stored.
5417 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5418 * @return 0 on success, non-zero on failure.
5419 */
5420 static int
mdb_page_get(MDB_cursor * mc,pgno_t pgno,MDB_page ** ret,int * lvl)5421 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5422 {
5423 MDB_txn *txn = mc->mc_txn;
5424 MDB_env *env = txn->mt_env;
5425 MDB_page *p = NULL;
5426 int level;
5427
5428 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5429 MDB_txn *tx2 = txn;
5430 level = 1;
5431 do {
5432 MDB_ID2L dl = tx2->mt_u.dirty_list;
5433 unsigned x;
5434 /* Spilled pages were dirtied in this txn and flushed
5435 * because the dirty list got full. Bring this page
5436 * back in from the map (but don't unspill it here,
5437 * leave that unless page_touch happens again).
5438 */
5439 if (tx2->mt_spill_pgs) {
5440 MDB_ID pn = pgno << 1;
5441 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5442 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5443 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5444 goto done;
5445 }
5446 }
5447 if (dl[0].mid) {
5448 unsigned x = mdb_mid2l_search(dl, pgno);
5449 if (x <= dl[0].mid && dl[x].mid == pgno) {
5450 p = dl[x].mptr;
5451 goto done;
5452 }
5453 }
5454 level++;
5455 } while ((tx2 = tx2->mt_parent) != NULL);
5456 }
5457
5458 if (pgno < txn->mt_next_pgno) {
5459 level = 0;
5460 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5461 } else {
5462 DPRINTF(("page %"Z"u not found", pgno));
5463 txn->mt_flags |= MDB_TXN_ERROR;
5464 return MDB_PAGE_NOTFOUND;
5465 }
5466
5467 done:
5468 *ret = p;
5469 if (lvl)
5470 *lvl = level;
5471 return MDB_SUCCESS;
5472 }
5473
5474 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5475 * The cursor is at the root page, set up the rest of it.
5476 */
5477 static int
mdb_page_search_root(MDB_cursor * mc,MDB_val * key,int flags)5478 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5479 {
5480 MDB_page *mp = mc->mc_pg[mc->mc_top];
5481 int rc;
5482 DKBUF;
5483
5484 while (IS_BRANCH(mp)) {
5485 MDB_node *node;
5486 indx_t i;
5487
5488 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5489 /* Don't assert on branch pages in the FreeDB. We can get here
5490 * while in the process of rebalancing a FreeDB branch page; we must
5491 * let that proceed. ITS#8336
5492 */
5493 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
5494 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5495
5496 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5497 i = 0;
5498 if (flags & MDB_PS_LAST) {
5499 i = NUMKEYS(mp) - 1;
5500 /* if already init'd, see if we're already in right place */
5501 if (mc->mc_flags & C_INITIALIZED) {
5502 if (mc->mc_ki[mc->mc_top] == i) {
5503 mc->mc_top = mc->mc_snum++;
5504 mp = mc->mc_pg[mc->mc_top];
5505 goto ready;
5506 }
5507 }
5508 }
5509 } else {
5510 int exact;
5511 node = mdb_node_search(mc, key, &exact);
5512 if (node == NULL)
5513 i = NUMKEYS(mp) - 1;
5514 else {
5515 i = mc->mc_ki[mc->mc_top];
5516 if (!exact) {
5517 mdb_cassert(mc, i > 0);
5518 i--;
5519 }
5520 }
5521 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5522 }
5523
5524 mdb_cassert(mc, i < NUMKEYS(mp));
5525 node = NODEPTR(mp, i);
5526
5527 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5528 return rc;
5529
5530 mc->mc_ki[mc->mc_top] = i;
5531 if ((rc = mdb_cursor_push(mc, mp)))
5532 return rc;
5533
5534 ready:
5535 if (flags & MDB_PS_MODIFY) {
5536 if ((rc = mdb_page_touch(mc)) != 0)
5537 return rc;
5538 mp = mc->mc_pg[mc->mc_top];
5539 }
5540 }
5541
5542 if (!IS_LEAF(mp)) {
5543 DPRINTF(("internal error, index points to a %02X page!?",
5544 mp->mp_flags));
5545 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5546 return MDB_CORRUPTED;
5547 }
5548
5549 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5550 key ? DKEY(key) : "null"));
5551 mc->mc_flags |= C_INITIALIZED;
5552 mc->mc_flags &= ~C_EOF;
5553
5554 return MDB_SUCCESS;
5555 }
5556
5557 /** Search for the lowest key under the current branch page.
5558 * This just bypasses a NUMKEYS check in the current page
5559 * before calling mdb_page_search_root(), because the callers
5560 * are all in situations where the current page is known to
5561 * be underfilled.
5562 */
5563 static int
mdb_page_search_lowest(MDB_cursor * mc)5564 mdb_page_search_lowest(MDB_cursor *mc)
5565 {
5566 MDB_page *mp = mc->mc_pg[mc->mc_top];
5567 MDB_node *node = NODEPTR(mp, 0);
5568 int rc;
5569
5570 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5571 return rc;
5572
5573 mc->mc_ki[mc->mc_top] = 0;
5574 if ((rc = mdb_cursor_push(mc, mp)))
5575 return rc;
5576 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5577 }
5578
5579 /** Search for the page a given key should be in.
5580 * Push it and its parent pages on the cursor stack.
5581 * @param[in,out] mc the cursor for this operation.
5582 * @param[in] key the key to search for, or NULL for first/last page.
5583 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5584 * are touched (updated with new page numbers).
5585 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5586 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5587 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5588 * @return 0 on success, non-zero on failure.
5589 */
5590 static int
mdb_page_search(MDB_cursor * mc,MDB_val * key,int flags)5591 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5592 {
5593 int rc;
5594 pgno_t root;
5595
5596 /* Make sure the txn is still viable, then find the root from
5597 * the txn's db table and set it as the root of the cursor's stack.
5598 */
5599 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5600 DPUTS("transaction may not be used now");
5601 return MDB_BAD_TXN;
5602 } else {
5603 /* Make sure we're using an up-to-date root */
5604 if (*mc->mc_dbflag & DB_STALE) {
5605 MDB_cursor mc2;
5606 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5607 return MDB_BAD_DBI;
5608 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5609 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5610 if (rc)
5611 return rc;
5612 {
5613 MDB_val data;
5614 int exact = 0;
5615 uint16_t flags;
5616 MDB_node *leaf = mdb_node_search(&mc2,
5617 &mc->mc_dbx->md_name, &exact);
5618 if (!exact)
5619 return MDB_NOTFOUND;
5620 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5621 return MDB_INCOMPATIBLE; /* not a named DB */
5622 rc = mdb_node_read(&mc2, leaf, &data);
5623 if (rc)
5624 return rc;
5625 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5626 sizeof(uint16_t));
5627 /* The txn may not know this DBI, or another process may
5628 * have dropped and recreated the DB with other flags.
5629 */
5630 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5631 return MDB_INCOMPATIBLE;
5632 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5633 }
5634 *mc->mc_dbflag &= ~DB_STALE;
5635 }
5636 root = mc->mc_db->md_root;
5637
5638 if (root == P_INVALID) { /* Tree is empty. */
5639 DPUTS("tree is empty");
5640 return MDB_NOTFOUND;
5641 }
5642 }
5643
5644 mdb_cassert(mc, root > 1);
5645 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5646 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
5647 return rc;
5648
5649 mc->mc_snum = 1;
5650 mc->mc_top = 0;
5651
5652 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5653 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5654
5655 if (flags & MDB_PS_MODIFY) {
5656 if ((rc = mdb_page_touch(mc)))
5657 return rc;
5658 }
5659
5660 if (flags & MDB_PS_ROOTONLY)
5661 return MDB_SUCCESS;
5662
5663 return mdb_page_search_root(mc, key, flags);
5664 }
5665
5666 static int
mdb_ovpage_free(MDB_cursor * mc,MDB_page * mp)5667 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5668 {
5669 MDB_txn *txn = mc->mc_txn;
5670 pgno_t pg = mp->mp_pgno;
5671 unsigned x = 0, ovpages = mp->mp_pages;
5672 MDB_env *env = txn->mt_env;
5673 MDB_IDL sl = txn->mt_spill_pgs;
5674 MDB_ID pn = pg << 1;
5675 int rc;
5676
5677 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5678 /* If the page is dirty or on the spill list we just acquired it,
5679 * so we should give it back to our current free list, if any.
5680 * Otherwise put it onto the list of pages we freed in this txn.
5681 *
5682 * Won't create me_pghead: me_pglast must be inited along with it.
5683 * Unsupported in nested txns: They would need to hide the page
5684 * range in ancestor txns' dirty and spilled lists.
5685 */
5686 if (env->me_pghead &&
5687 !txn->mt_parent &&
5688 ((mp->mp_flags & P_DIRTY) ||
5689 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5690 {
5691 unsigned i, j;
5692 pgno_t *mop;
5693 MDB_ID2 *dl, ix, iy;
5694 rc = mdb_midl_need(&env->me_pghead, ovpages);
5695 if (rc)
5696 return rc;
5697 if (!(mp->mp_flags & P_DIRTY)) {
5698 /* This page is no longer spilled */
5699 if (x == sl[0])
5700 sl[0]--;
5701 else
5702 sl[x] |= 1;
5703 goto release;
5704 }
5705 /* Remove from dirty list */
5706 dl = txn->mt_u.dirty_list;
5707 x = dl[0].mid--;
5708 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5709 if (x > 1) {
5710 x--;
5711 iy = dl[x];
5712 dl[x] = ix;
5713 } else {
5714 mdb_cassert(mc, x > 1);
5715 j = ++(dl[0].mid);
5716 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5717 txn->mt_flags |= MDB_TXN_ERROR;
5718 return MDB_CORRUPTED;
5719 }
5720 }
5721 txn->mt_dirty_room++;
5722 if (!(env->me_flags & MDB_WRITEMAP))
5723 mdb_dpage_free(env, mp);
5724 release:
5725 /* Insert in me_pghead */
5726 mop = env->me_pghead;
5727 j = mop[0] + ovpages;
5728 for (i = mop[0]; i && mop[i] < pg; i--)
5729 mop[j--] = mop[i];
5730 while (j>i)
5731 mop[j--] = pg++;
5732 mop[0] += ovpages;
5733 } else {
5734 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5735 if (rc)
5736 return rc;
5737 }
5738 mc->mc_db->md_overflow_pages -= ovpages;
5739 return 0;
5740 }
5741
5742 /** Return the data associated with a given node.
5743 * @param[in] mc The cursor for this operation.
5744 * @param[in] leaf The node being read.
5745 * @param[out] data Updated to point to the node's data.
5746 * @return 0 on success, non-zero on failure.
5747 */
5748 static int
mdb_node_read(MDB_cursor * mc,MDB_node * leaf,MDB_val * data)5749 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
5750 {
5751 MDB_page *omp; /* overflow page */
5752 pgno_t pgno;
5753 int rc;
5754
5755 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5756 data->mv_size = NODEDSZ(leaf);
5757 data->mv_data = NODEDATA(leaf);
5758 return MDB_SUCCESS;
5759 }
5760
5761 /* Read overflow data.
5762 */
5763 data->mv_size = NODEDSZ(leaf);
5764 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5765 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
5766 DPRINTF(("read overflow page %"Z"u failed", pgno));
5767 return rc;
5768 }
5769 data->mv_data = METADATA(omp);
5770
5771 return MDB_SUCCESS;
5772 }
5773
5774 int
mdb_get(MDB_txn * txn,MDB_dbi dbi,MDB_val * key,MDB_val * data)5775 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5776 MDB_val *key, MDB_val *data)
5777 {
5778 MDB_cursor mc;
5779 MDB_xcursor mx;
5780 int exact = 0;
5781 DKBUF;
5782
5783 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5784
5785 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5786 return EINVAL;
5787
5788 if (txn->mt_flags & MDB_TXN_BLOCKED)
5789 return MDB_BAD_TXN;
5790
5791 mdb_cursor_init(&mc, txn, dbi, &mx);
5792 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5793 }
5794
5795 /** Find a sibling for a page.
5796 * Replaces the page at the top of the cursor's stack with the
5797 * specified sibling, if one exists.
5798 * @param[in] mc The cursor for this operation.
5799 * @param[in] move_right Non-zero if the right sibling is requested,
5800 * otherwise the left sibling.
5801 * @return 0 on success, non-zero on failure.
5802 */
5803 static int
mdb_cursor_sibling(MDB_cursor * mc,int move_right)5804 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5805 {
5806 int rc;
5807 MDB_node *indx;
5808 MDB_page *mp;
5809
5810 if (mc->mc_snum < 2) {
5811 return MDB_NOTFOUND; /* root has no siblings */
5812 }
5813
5814 mdb_cursor_pop(mc);
5815 DPRINTF(("parent page is page %"Z"u, index %u",
5816 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5817
5818 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5819 : (mc->mc_ki[mc->mc_top] == 0)) {
5820 DPRINTF(("no more keys left, moving to %s sibling",
5821 move_right ? "right" : "left"));
5822 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5823 /* undo cursor_pop before returning */
5824 mc->mc_top++;
5825 mc->mc_snum++;
5826 return rc;
5827 }
5828 } else {
5829 if (move_right)
5830 mc->mc_ki[mc->mc_top]++;
5831 else
5832 mc->mc_ki[mc->mc_top]--;
5833 DPRINTF(("just moving to %s index key %u",
5834 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5835 }
5836 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5837
5838 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5839 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
5840 /* mc will be inconsistent if caller does mc_snum++ as above */
5841 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5842 return rc;
5843 }
5844
5845 mdb_cursor_push(mc, mp);
5846 if (!move_right)
5847 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5848
5849 return MDB_SUCCESS;
5850 }
5851
5852 /** Move the cursor to the next data item. */
5853 static int
mdb_cursor_next(MDB_cursor * mc,MDB_val * key,MDB_val * data,MDB_cursor_op op)5854 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5855 {
5856 MDB_page *mp;
5857 MDB_node *leaf;
5858 int rc;
5859
5860 if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
5861 return MDB_NOTFOUND;
5862
5863 if (!(mc->mc_flags & C_INITIALIZED))
5864 return mdb_cursor_first(mc, key, data);
5865
5866 mp = mc->mc_pg[mc->mc_top];
5867
5868 if (mc->mc_flags & C_EOF) {
5869 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
5870 return MDB_NOTFOUND;
5871 mc->mc_flags ^= C_EOF;
5872 }
5873
5874 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5875 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5876 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5877 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5878 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5879 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5880 if (rc == MDB_SUCCESS)
5881 MDB_GET_KEY(leaf, key);
5882 return rc;
5883 }
5884 }
5885 } else {
5886 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5887 if (op == MDB_NEXT_DUP)
5888 return MDB_NOTFOUND;
5889 }
5890 }
5891
5892 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5893 mdb_dbg_pgno(mp), (void *) mc));
5894 if (mc->mc_flags & C_DEL) {
5895 mc->mc_flags ^= C_DEL;
5896 goto skip;
5897 }
5898
5899 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5900 DPUTS("=====> move to next sibling page");
5901 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5902 mc->mc_flags |= C_EOF;
5903 return rc;
5904 }
5905 mp = mc->mc_pg[mc->mc_top];
5906 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5907 } else
5908 mc->mc_ki[mc->mc_top]++;
5909
5910 skip:
5911 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5912 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5913
5914 if (IS_LEAF2(mp)) {
5915 key->mv_size = mc->mc_db->md_pad;
5916 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5917 return MDB_SUCCESS;
5918 }
5919
5920 mdb_cassert(mc, IS_LEAF(mp));
5921 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5922
5923 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5924 mdb_xcursor_init1(mc, leaf);
5925 }
5926 if (data) {
5927 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5928 return rc;
5929
5930 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5931 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5932 if (rc != MDB_SUCCESS)
5933 return rc;
5934 }
5935 }
5936
5937 MDB_GET_KEY(leaf, key);
5938 return MDB_SUCCESS;
5939 }
5940
5941 /** Move the cursor to the previous data item. */
5942 static int
mdb_cursor_prev(MDB_cursor * mc,MDB_val * key,MDB_val * data,MDB_cursor_op op)5943 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5944 {
5945 MDB_page *mp;
5946 MDB_node *leaf;
5947 int rc;
5948
5949 if (!(mc->mc_flags & C_INITIALIZED)) {
5950 rc = mdb_cursor_last(mc, key, data);
5951 if (rc)
5952 return rc;
5953 mc->mc_ki[mc->mc_top]++;
5954 }
5955
5956 mp = mc->mc_pg[mc->mc_top];
5957
5958 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5959 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5960 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5961 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5962 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5963 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5964 if (rc == MDB_SUCCESS) {
5965 MDB_GET_KEY(leaf, key);
5966 mc->mc_flags &= ~C_EOF;
5967 }
5968 return rc;
5969 }
5970 }
5971 } else {
5972 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5973 if (op == MDB_PREV_DUP)
5974 return MDB_NOTFOUND;
5975 }
5976 }
5977
5978 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5979 mdb_dbg_pgno(mp), (void *) mc));
5980
5981 mc->mc_flags &= ~(C_EOF|C_DEL);
5982
5983 if (mc->mc_ki[mc->mc_top] == 0) {
5984 DPUTS("=====> move to prev sibling page");
5985 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5986 return rc;
5987 }
5988 mp = mc->mc_pg[mc->mc_top];
5989 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5990 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5991 } else
5992 mc->mc_ki[mc->mc_top]--;
5993
5994 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5995 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5996
5997 if (IS_LEAF2(mp)) {
5998 key->mv_size = mc->mc_db->md_pad;
5999 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6000 return MDB_SUCCESS;
6001 }
6002
6003 mdb_cassert(mc, IS_LEAF(mp));
6004 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6005
6006 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6007 mdb_xcursor_init1(mc, leaf);
6008 }
6009 if (data) {
6010 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6011 return rc;
6012
6013 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6014 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6015 if (rc != MDB_SUCCESS)
6016 return rc;
6017 }
6018 }
6019
6020 MDB_GET_KEY(leaf, key);
6021 return MDB_SUCCESS;
6022 }
6023
6024 /** Set the cursor on a specific data item. */
6025 static int
mdb_cursor_set(MDB_cursor * mc,MDB_val * key,MDB_val * data,MDB_cursor_op op,int * exactp)6026 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6027 MDB_cursor_op op, int *exactp)
6028 {
6029 int rc;
6030 MDB_page *mp;
6031 MDB_node *leaf = NULL;
6032 DKBUF;
6033
6034 if (key->mv_size == 0)
6035 return MDB_BAD_VALSIZE;
6036
6037 if (mc->mc_xcursor)
6038 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6039
6040 /* See if we're already on the right page */
6041 if (mc->mc_flags & C_INITIALIZED) {
6042 MDB_val nodekey;
6043
6044 mp = mc->mc_pg[mc->mc_top];
6045 if (!NUMKEYS(mp)) {
6046 mc->mc_ki[mc->mc_top] = 0;
6047 return MDB_NOTFOUND;
6048 }
6049 if (mp->mp_flags & P_LEAF2) {
6050 nodekey.mv_size = mc->mc_db->md_pad;
6051 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6052 } else {
6053 leaf = NODEPTR(mp, 0);
6054 MDB_GET_KEY2(leaf, nodekey);
6055 }
6056 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6057 if (rc == 0) {
6058 /* Probably happens rarely, but first node on the page
6059 * was the one we wanted.
6060 */
6061 mc->mc_ki[mc->mc_top] = 0;
6062 if (exactp)
6063 *exactp = 1;
6064 goto set1;
6065 }
6066 if (rc > 0) {
6067 unsigned int i;
6068 unsigned int nkeys = NUMKEYS(mp);
6069 if (nkeys > 1) {
6070 if (mp->mp_flags & P_LEAF2) {
6071 nodekey.mv_data = LEAF2KEY(mp,
6072 nkeys-1, nodekey.mv_size);
6073 } else {
6074 leaf = NODEPTR(mp, nkeys-1);
6075 MDB_GET_KEY2(leaf, nodekey);
6076 }
6077 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6078 if (rc == 0) {
6079 /* last node was the one we wanted */
6080 mc->mc_ki[mc->mc_top] = nkeys-1;
6081 if (exactp)
6082 *exactp = 1;
6083 goto set1;
6084 }
6085 if (rc < 0) {
6086 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6087 /* This is definitely the right page, skip search_page */
6088 if (mp->mp_flags & P_LEAF2) {
6089 nodekey.mv_data = LEAF2KEY(mp,
6090 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6091 } else {
6092 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6093 MDB_GET_KEY2(leaf, nodekey);
6094 }
6095 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6096 if (rc == 0) {
6097 /* current node was the one we wanted */
6098 if (exactp)
6099 *exactp = 1;
6100 goto set1;
6101 }
6102 }
6103 rc = 0;
6104 mc->mc_flags &= ~C_EOF;
6105 goto set2;
6106 }
6107 }
6108 /* If any parents have right-sibs, search.
6109 * Otherwise, there's nothing further.
6110 */
6111 for (i=0; i<mc->mc_top; i++)
6112 if (mc->mc_ki[i] <
6113 NUMKEYS(mc->mc_pg[i])-1)
6114 break;
6115 if (i == mc->mc_top) {
6116 /* There are no other pages */
6117 mc->mc_ki[mc->mc_top] = nkeys;
6118 return MDB_NOTFOUND;
6119 }
6120 }
6121 if (!mc->mc_top) {
6122 /* There are no other pages */
6123 mc->mc_ki[mc->mc_top] = 0;
6124 if (op == MDB_SET_RANGE && !exactp) {
6125 rc = 0;
6126 goto set1;
6127 } else
6128 return MDB_NOTFOUND;
6129 }
6130 } else {
6131 mc->mc_pg[0] = 0;
6132 }
6133
6134 rc = mdb_page_search(mc, key, 0);
6135 if (rc != MDB_SUCCESS)
6136 return rc;
6137
6138 mp = mc->mc_pg[mc->mc_top];
6139 mdb_cassert(mc, IS_LEAF(mp));
6140
6141 set2:
6142 leaf = mdb_node_search(mc, key, exactp);
6143 if (exactp != NULL && !*exactp) {
6144 /* MDB_SET specified and not an exact match. */
6145 return MDB_NOTFOUND;
6146 }
6147
6148 if (leaf == NULL) {
6149 DPUTS("===> inexact leaf not found, goto sibling");
6150 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6151 mc->mc_flags |= C_EOF;
6152 return rc; /* no entries matched */
6153 }
6154 mp = mc->mc_pg[mc->mc_top];
6155 mdb_cassert(mc, IS_LEAF(mp));
6156 leaf = NODEPTR(mp, 0);
6157 }
6158
6159 set1:
6160 mc->mc_flags |= C_INITIALIZED;
6161 mc->mc_flags &= ~C_EOF;
6162
6163 if (IS_LEAF2(mp)) {
6164 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6165 key->mv_size = mc->mc_db->md_pad;
6166 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6167 }
6168 return MDB_SUCCESS;
6169 }
6170
6171 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6172 mdb_xcursor_init1(mc, leaf);
6173 }
6174 if (data) {
6175 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6176 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6177 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6178 } else {
6179 int ex2, *ex2p;
6180 if (op == MDB_GET_BOTH) {
6181 ex2p = &ex2;
6182 ex2 = 0;
6183 } else {
6184 ex2p = NULL;
6185 }
6186 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6187 if (rc != MDB_SUCCESS)
6188 return rc;
6189 }
6190 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6191 MDB_val olddata;
6192 MDB_cmp_func *dcmp;
6193 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6194 return rc;
6195 dcmp = mc->mc_dbx->md_dcmp;
6196 #if UINT_MAX < SIZE_MAX
6197 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6198 dcmp = mdb_cmp_clong;
6199 #endif
6200 rc = dcmp(data, &olddata);
6201 if (rc) {
6202 if (op == MDB_GET_BOTH || rc > 0)
6203 return MDB_NOTFOUND;
6204 rc = 0;
6205 }
6206 *data = olddata;
6207
6208 } else {
6209 if (mc->mc_xcursor)
6210 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6211 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6212 return rc;
6213 }
6214 }
6215
6216 /* The key already matches in all other cases */
6217 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6218 MDB_GET_KEY(leaf, key);
6219 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6220
6221 return rc;
6222 }
6223
6224 /** Move the cursor to the first item in the database. */
6225 static int
mdb_cursor_first(MDB_cursor * mc,MDB_val * key,MDB_val * data)6226 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6227 {
6228 int rc;
6229 MDB_node *leaf;
6230
6231 if (mc->mc_xcursor)
6232 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6233
6234 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6235 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6236 if (rc != MDB_SUCCESS)
6237 return rc;
6238 }
6239 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6240
6241 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6242 mc->mc_flags |= C_INITIALIZED;
6243 mc->mc_flags &= ~C_EOF;
6244
6245 mc->mc_ki[mc->mc_top] = 0;
6246
6247 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6248 key->mv_size = mc->mc_db->md_pad;
6249 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6250 return MDB_SUCCESS;
6251 }
6252
6253 if (data) {
6254 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6255 mdb_xcursor_init1(mc, leaf);
6256 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6257 if (rc)
6258 return rc;
6259 } else {
6260 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6261 return rc;
6262 }
6263 }
6264 MDB_GET_KEY(leaf, key);
6265 return MDB_SUCCESS;
6266 }
6267
6268 /** Move the cursor to the last item in the database. */
6269 static int
mdb_cursor_last(MDB_cursor * mc,MDB_val * key,MDB_val * data)6270 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6271 {
6272 int rc;
6273 MDB_node *leaf;
6274
6275 if (mc->mc_xcursor)
6276 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6277
6278 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6279 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6280 if (rc != MDB_SUCCESS)
6281 return rc;
6282 }
6283 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6284
6285 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6286 mc->mc_flags |= C_INITIALIZED|C_EOF;
6287 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6288
6289 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6290 key->mv_size = mc->mc_db->md_pad;
6291 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6292 return MDB_SUCCESS;
6293 }
6294
6295 if (data) {
6296 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6297 mdb_xcursor_init1(mc, leaf);
6298 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6299 if (rc)
6300 return rc;
6301 } else {
6302 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6303 return rc;
6304 }
6305 }
6306
6307 MDB_GET_KEY(leaf, key);
6308 return MDB_SUCCESS;
6309 }
6310
6311 int
mdb_cursor_get(MDB_cursor * mc,MDB_val * key,MDB_val * data,MDB_cursor_op op)6312 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6313 MDB_cursor_op op)
6314 {
6315 int rc;
6316 int exact = 0;
6317 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6318
6319 if (mc == NULL)
6320 return EINVAL;
6321
6322 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6323 return MDB_BAD_TXN;
6324
6325 switch (op) {
6326 case MDB_GET_CURRENT:
6327 if (!(mc->mc_flags & C_INITIALIZED)) {
6328 rc = EINVAL;
6329 } else {
6330 MDB_page *mp = mc->mc_pg[mc->mc_top];
6331 int nkeys = NUMKEYS(mp);
6332 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6333 mc->mc_ki[mc->mc_top] = nkeys;
6334 rc = MDB_NOTFOUND;
6335 break;
6336 }
6337 rc = MDB_SUCCESS;
6338 if (IS_LEAF2(mp)) {
6339 key->mv_size = mc->mc_db->md_pad;
6340 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6341 } else {
6342 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6343 MDB_GET_KEY(leaf, key);
6344 if (data) {
6345 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6346 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6347 } else {
6348 rc = mdb_node_read(mc, leaf, data);
6349 }
6350 }
6351 }
6352 }
6353 break;
6354 case MDB_GET_BOTH:
6355 case MDB_GET_BOTH_RANGE:
6356 if (data == NULL) {
6357 rc = EINVAL;
6358 break;
6359 }
6360 if (mc->mc_xcursor == NULL) {
6361 rc = MDB_INCOMPATIBLE;
6362 break;
6363 }
6364 /* FALLTHRU */
6365 case MDB_SET:
6366 case MDB_SET_KEY:
6367 case MDB_SET_RANGE:
6368 if (key == NULL) {
6369 rc = EINVAL;
6370 } else {
6371 rc = mdb_cursor_set(mc, key, data, op,
6372 op == MDB_SET_RANGE ? NULL : &exact);
6373 }
6374 break;
6375 case MDB_GET_MULTIPLE:
6376 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6377 rc = EINVAL;
6378 break;
6379 }
6380 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6381 rc = MDB_INCOMPATIBLE;
6382 break;
6383 }
6384 rc = MDB_SUCCESS;
6385 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6386 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6387 break;
6388 goto fetchm;
6389 case MDB_NEXT_MULTIPLE:
6390 if (data == NULL) {
6391 rc = EINVAL;
6392 break;
6393 }
6394 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6395 rc = MDB_INCOMPATIBLE;
6396 break;
6397 }
6398 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6399 if (rc == MDB_SUCCESS) {
6400 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6401 MDB_cursor *mx;
6402 fetchm:
6403 mx = &mc->mc_xcursor->mx_cursor;
6404 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6405 mx->mc_db->md_pad;
6406 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6407 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6408 } else {
6409 rc = MDB_NOTFOUND;
6410 }
6411 }
6412 break;
6413 case MDB_PREV_MULTIPLE:
6414 if (data == NULL) {
6415 rc = EINVAL;
6416 break;
6417 }
6418 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6419 rc = MDB_INCOMPATIBLE;
6420 break;
6421 }
6422 if (!(mc->mc_flags & C_INITIALIZED))
6423 rc = mdb_cursor_last(mc, key, data);
6424 else
6425 rc = MDB_SUCCESS;
6426 if (rc == MDB_SUCCESS) {
6427 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
6428 if (mx->mc_flags & C_INITIALIZED) {
6429 rc = mdb_cursor_sibling(mx, 0);
6430 if (rc == MDB_SUCCESS)
6431 goto fetchm;
6432 } else {
6433 rc = MDB_NOTFOUND;
6434 }
6435 }
6436 break;
6437 case MDB_NEXT:
6438 case MDB_NEXT_DUP:
6439 case MDB_NEXT_NODUP:
6440 rc = mdb_cursor_next(mc, key, data, op);
6441 break;
6442 case MDB_PREV:
6443 case MDB_PREV_DUP:
6444 case MDB_PREV_NODUP:
6445 rc = mdb_cursor_prev(mc, key, data, op);
6446 break;
6447 case MDB_FIRST:
6448 rc = mdb_cursor_first(mc, key, data);
6449 break;
6450 case MDB_FIRST_DUP:
6451 mfunc = mdb_cursor_first;
6452 mmove:
6453 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6454 rc = EINVAL;
6455 break;
6456 }
6457 if (mc->mc_xcursor == NULL) {
6458 rc = MDB_INCOMPATIBLE;
6459 break;
6460 }
6461 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top])) {
6462 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6463 rc = MDB_NOTFOUND;
6464 break;
6465 }
6466 {
6467 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6468 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6469 MDB_GET_KEY(leaf, key);
6470 rc = mdb_node_read(mc, leaf, data);
6471 break;
6472 }
6473 }
6474 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6475 rc = EINVAL;
6476 break;
6477 }
6478 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6479 break;
6480 case MDB_LAST:
6481 rc = mdb_cursor_last(mc, key, data);
6482 break;
6483 case MDB_LAST_DUP:
6484 mfunc = mdb_cursor_last;
6485 goto mmove;
6486 default:
6487 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6488 rc = EINVAL;
6489 break;
6490 }
6491
6492 if (mc->mc_flags & C_DEL)
6493 mc->mc_flags ^= C_DEL;
6494
6495 return rc;
6496 }
6497
6498 /** Touch all the pages in the cursor stack. Set mc_top.
6499 * Makes sure all the pages are writable, before attempting a write operation.
6500 * @param[in] mc The cursor to operate on.
6501 */
6502 static int
mdb_cursor_touch(MDB_cursor * mc)6503 mdb_cursor_touch(MDB_cursor *mc)
6504 {
6505 int rc = MDB_SUCCESS;
6506
6507 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
6508 /* Touch DB record of named DB */
6509 MDB_cursor mc2;
6510 MDB_xcursor mcx;
6511 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6512 return MDB_BAD_DBI;
6513 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6514 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6515 if (rc)
6516 return rc;
6517 *mc->mc_dbflag |= DB_DIRTY;
6518 }
6519 mc->mc_top = 0;
6520 if (mc->mc_snum) {
6521 do {
6522 rc = mdb_page_touch(mc);
6523 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6524 mc->mc_top = mc->mc_snum-1;
6525 }
6526 return rc;
6527 }
6528
6529 /** Do not spill pages to disk if txn is getting full, may fail instead */
6530 #define MDB_NOSPILL 0x8000
6531
6532 int
mdb_cursor_put(MDB_cursor * mc,MDB_val * key,MDB_val * data,unsigned int flags)6533 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6534 unsigned int flags)
6535 {
6536 MDB_env *env;
6537 MDB_node *leaf = NULL;
6538 MDB_page *fp, *mp, *sub_root = NULL;
6539 uint16_t fp_flags;
6540 MDB_val xdata, *rdata, dkey, olddata;
6541 MDB_db dummy;
6542 int do_sub = 0, insert_key, insert_data;
6543 unsigned int mcount = 0, dcount = 0, nospill;
6544 size_t nsize;
6545 int rc, rc2;
6546 unsigned int nflags;
6547 DKBUF;
6548
6549 if (mc == NULL || key == NULL)
6550 return EINVAL;
6551
6552 env = mc->mc_txn->mt_env;
6553
6554 /* Check this first so counter will always be zero on any
6555 * early failures.
6556 */
6557 if (flags & MDB_MULTIPLE) {
6558 dcount = data[1].mv_size;
6559 data[1].mv_size = 0;
6560 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6561 return MDB_INCOMPATIBLE;
6562 }
6563
6564 nospill = flags & MDB_NOSPILL;
6565 flags &= ~MDB_NOSPILL;
6566
6567 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6568 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6569
6570 if (key->mv_size-1 >= ENV_MAXKEY(env))
6571 return MDB_BAD_VALSIZE;
6572
6573 #if SIZE_MAX > MAXDATASIZE
6574 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6575 return MDB_BAD_VALSIZE;
6576 #else
6577 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6578 return MDB_BAD_VALSIZE;
6579 #endif
6580
6581 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6582 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6583
6584 dkey.mv_size = 0;
6585
6586 if (flags == MDB_CURRENT) {
6587 if (!(mc->mc_flags & C_INITIALIZED))
6588 return EINVAL;
6589 rc = MDB_SUCCESS;
6590 } else if (mc->mc_db->md_root == P_INVALID) {
6591 /* new database, cursor has nothing to point to */
6592 mc->mc_snum = 0;
6593 mc->mc_top = 0;
6594 mc->mc_flags &= ~C_INITIALIZED;
6595 rc = MDB_NO_ROOT;
6596 } else {
6597 int exact = 0;
6598 MDB_val d2;
6599 if (flags & MDB_APPEND) {
6600 MDB_val k2;
6601 rc = mdb_cursor_last(mc, &k2, &d2);
6602 if (rc == 0) {
6603 rc = mc->mc_dbx->md_cmp(key, &k2);
6604 if (rc > 0) {
6605 rc = MDB_NOTFOUND;
6606 mc->mc_ki[mc->mc_top]++;
6607 } else {
6608 /* new key is <= last key */
6609 rc = MDB_KEYEXIST;
6610 }
6611 }
6612 } else {
6613 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6614 }
6615 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6616 DPRINTF(("duplicate key [%s]", DKEY(key)));
6617 *data = d2;
6618 return MDB_KEYEXIST;
6619 }
6620 if (rc && rc != MDB_NOTFOUND)
6621 return rc;
6622 }
6623
6624 if (mc->mc_flags & C_DEL)
6625 mc->mc_flags ^= C_DEL;
6626
6627 /* Cursor is positioned, check for room in the dirty list */
6628 if (!nospill) {
6629 if (flags & MDB_MULTIPLE) {
6630 rdata = &xdata;
6631 xdata.mv_size = data->mv_size * dcount;
6632 } else {
6633 rdata = data;
6634 }
6635 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6636 return rc2;
6637 }
6638
6639 if (rc == MDB_NO_ROOT) {
6640 MDB_page *np;
6641 /* new database, write a root leaf page */
6642 DPUTS("allocating new root leaf page");
6643 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6644 return rc2;
6645 }
6646 mdb_cursor_push(mc, np);
6647 mc->mc_db->md_root = np->mp_pgno;
6648 mc->mc_db->md_depth++;
6649 *mc->mc_dbflag |= DB_DIRTY;
6650 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6651 == MDB_DUPFIXED)
6652 np->mp_flags |= P_LEAF2;
6653 mc->mc_flags |= C_INITIALIZED;
6654 } else {
6655 /* make sure all cursor pages are writable */
6656 rc2 = mdb_cursor_touch(mc);
6657 if (rc2)
6658 return rc2;
6659 }
6660
6661 insert_key = insert_data = rc;
6662 if (insert_key) {
6663 /* The key does not exist */
6664 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6665 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6666 LEAFSIZE(key, data) > env->me_nodemax)
6667 {
6668 /* Too big for a node, insert in sub-DB. Set up an empty
6669 * "old sub-page" for prep_subDB to expand to a full page.
6670 */
6671 fp_flags = P_LEAF|P_DIRTY;
6672 fp = env->me_pbuf;
6673 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6674 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6675 olddata.mv_size = PAGEHDRSZ;
6676 goto prep_subDB;
6677 }
6678 } else {
6679 /* there's only a key anyway, so this is a no-op */
6680 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6681 char *ptr;
6682 unsigned int ksize = mc->mc_db->md_pad;
6683 if (key->mv_size != ksize)
6684 return MDB_BAD_VALSIZE;
6685 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6686 memcpy(ptr, key->mv_data, ksize);
6687 fix_parent:
6688 /* if overwriting slot 0 of leaf, need to
6689 * update branch key if there is a parent page
6690 */
6691 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6692 unsigned short dtop = 1;
6693 mc->mc_top--;
6694 /* slot 0 is always an empty key, find real slot */
6695 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6696 mc->mc_top--;
6697 dtop++;
6698 }
6699 if (mc->mc_ki[mc->mc_top])
6700 rc2 = mdb_update_key(mc, key);
6701 else
6702 rc2 = MDB_SUCCESS;
6703 mc->mc_top += dtop;
6704 if (rc2)
6705 return rc2;
6706 }
6707 return MDB_SUCCESS;
6708 }
6709
6710 more:
6711 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6712 olddata.mv_size = NODEDSZ(leaf);
6713 olddata.mv_data = NODEDATA(leaf);
6714
6715 /* DB has dups? */
6716 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6717 /* Prepare (sub-)page/sub-DB to accept the new item,
6718 * if needed. fp: old sub-page or a header faking
6719 * it. mp: new (sub-)page. offset: growth in page
6720 * size. xdata: node data with new page or DB.
6721 */
6722 unsigned i, offset = 0;
6723 mp = fp = xdata.mv_data = env->me_pbuf;
6724 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6725
6726 /* Was a single item before, must convert now */
6727 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6728 MDB_cmp_func *dcmp;
6729 /* Just overwrite the current item */
6730 if (flags == MDB_CURRENT)
6731 goto current;
6732 dcmp = mc->mc_dbx->md_dcmp;
6733 #if UINT_MAX < SIZE_MAX
6734 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6735 dcmp = mdb_cmp_clong;
6736 #endif
6737 /* does data match? */
6738 if (!dcmp(data, &olddata)) {
6739 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
6740 return MDB_KEYEXIST;
6741 /* overwrite it */
6742 goto current;
6743 }
6744
6745 /* Back up original data item */
6746 dkey.mv_size = olddata.mv_size;
6747 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6748
6749 /* Make sub-page header for the dup items, with dummy body */
6750 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6751 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6752 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6753 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6754 fp->mp_flags |= P_LEAF2;
6755 fp->mp_pad = data->mv_size;
6756 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6757 } else {
6758 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6759 (dkey.mv_size & 1) + (data->mv_size & 1);
6760 }
6761 fp->mp_upper = xdata.mv_size - PAGEBASE;
6762 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6763 } else if (leaf->mn_flags & F_SUBDATA) {
6764 /* Data is on sub-DB, just store it */
6765 flags |= F_DUPDATA|F_SUBDATA;
6766 goto put_sub;
6767 } else {
6768 /* Data is on sub-page */
6769 fp = olddata.mv_data;
6770 switch (flags) {
6771 default:
6772 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6773 offset = EVEN(NODESIZE + sizeof(indx_t) +
6774 data->mv_size);
6775 break;
6776 }
6777 offset = fp->mp_pad;
6778 if (SIZELEFT(fp) < offset) {
6779 offset *= 4; /* space for 4 more */
6780 break;
6781 }
6782 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6783 case MDB_CURRENT:
6784 fp->mp_flags |= P_DIRTY;
6785 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6786 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6787 flags |= F_DUPDATA;
6788 goto put_sub;
6789 }
6790 xdata.mv_size = olddata.mv_size + offset;
6791 }
6792
6793 fp_flags = fp->mp_flags;
6794 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6795 /* Too big for a sub-page, convert to sub-DB */
6796 fp_flags &= ~P_SUBP;
6797 prep_subDB:
6798 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6799 fp_flags |= P_LEAF2;
6800 dummy.md_pad = fp->mp_pad;
6801 dummy.md_flags = MDB_DUPFIXED;
6802 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6803 dummy.md_flags |= MDB_INTEGERKEY;
6804 } else {
6805 dummy.md_pad = 0;
6806 dummy.md_flags = 0;
6807 }
6808 dummy.md_depth = 1;
6809 dummy.md_branch_pages = 0;
6810 dummy.md_leaf_pages = 1;
6811 dummy.md_overflow_pages = 0;
6812 dummy.md_entries = NUMKEYS(fp);
6813 xdata.mv_size = sizeof(MDB_db);
6814 xdata.mv_data = &dummy;
6815 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6816 return rc;
6817 offset = env->me_psize - olddata.mv_size;
6818 flags |= F_DUPDATA|F_SUBDATA;
6819 dummy.md_root = mp->mp_pgno;
6820 sub_root = mp;
6821 }
6822 if (mp != fp) {
6823 mp->mp_flags = fp_flags | P_DIRTY;
6824 mp->mp_pad = fp->mp_pad;
6825 mp->mp_lower = fp->mp_lower;
6826 mp->mp_upper = fp->mp_upper + offset;
6827 if (fp_flags & P_LEAF2) {
6828 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6829 } else {
6830 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6831 olddata.mv_size - fp->mp_upper - PAGEBASE);
6832 memcpy((char *)(&mp->mp_ptrs), (char *)(&fp->mp_ptrs), NUMKEYS(fp) * sizeof(mp->mp_ptrs[0]));
6833 for (i=0; i<NUMKEYS(fp); i++)
6834 mp->mp_ptrs[i] += offset;
6835 }
6836 }
6837
6838 rdata = &xdata;
6839 flags |= F_DUPDATA;
6840 do_sub = 1;
6841 if (!insert_key)
6842 mdb_node_del(mc, 0);
6843 goto new_sub;
6844 }
6845 current:
6846 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6847 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6848 return MDB_INCOMPATIBLE;
6849 /* overflow page overwrites need special handling */
6850 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6851 MDB_page *omp;
6852 pgno_t pg;
6853 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6854
6855 memcpy(&pg, olddata.mv_data, sizeof(pg));
6856 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
6857 return rc2;
6858 ovpages = omp->mp_pages;
6859
6860 /* Is the ov page large enough? */
6861 if (ovpages >= dpages) {
6862 if (!(omp->mp_flags & P_DIRTY) &&
6863 (level || (env->me_flags & MDB_WRITEMAP)))
6864 {
6865 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6866 if (rc)
6867 return rc;
6868 level = 0; /* dirty in this txn or clean */
6869 }
6870 /* Is it dirty? */
6871 if (omp->mp_flags & P_DIRTY) {
6872 /* yes, overwrite it. Note in this case we don't
6873 * bother to try shrinking the page if the new data
6874 * is smaller than the overflow threshold.
6875 */
6876 if (level > 1) {
6877 /* It is writable only in a parent txn */
6878 size_t sz = (size_t) env->me_psize * ovpages, off;
6879 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6880 MDB_ID2 id2;
6881 if (!np)
6882 return ENOMEM;
6883 id2.mid = pg;
6884 id2.mptr = np;
6885 /* Note - this page is already counted in parent's dirty_room */
6886 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6887 mdb_cassert(mc, rc2 == 0);
6888 /* Currently we make the page look as with put() in the
6889 * parent txn, in case the user peeks at MDB_RESERVEd
6890 * or unused parts. Some users treat ovpages specially.
6891 */
6892 if (!(flags & MDB_RESERVE)) {
6893 /* Skip the part where LMDB will put *data.
6894 * Copy end of page, adjusting alignment so
6895 * compiler may copy words instead of bytes.
6896 */
6897 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6898 memcpy((size_t *)((char *)np + off),
6899 (size_t *)((char *)omp + off), sz - off);
6900 sz = PAGEHDRSZ;
6901 }
6902 memcpy(np, omp, sz); /* Copy beginning of page */
6903 omp = np;
6904 }
6905 SETDSZ(leaf, data->mv_size);
6906 if (F_ISSET(flags, MDB_RESERVE))
6907 data->mv_data = METADATA(omp);
6908 else
6909 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6910 return MDB_SUCCESS;
6911 }
6912 }
6913 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6914 return rc2;
6915 } else if (data->mv_size == olddata.mv_size) {
6916 /* same size, just replace it. Note that we could
6917 * also reuse this node if the new data is smaller,
6918 * but instead we opt to shrink the node in that case.
6919 */
6920 if (F_ISSET(flags, MDB_RESERVE))
6921 data->mv_data = olddata.mv_data;
6922 else if (!(mc->mc_flags & C_SUB))
6923 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6924 else {
6925 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6926 goto fix_parent;
6927 }
6928 return MDB_SUCCESS;
6929 }
6930 mdb_node_del(mc, 0);
6931 }
6932
6933 rdata = data;
6934
6935 new_sub:
6936 nflags = flags & NODE_ADD_FLAGS;
6937 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6938 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6939 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6940 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6941 if (!insert_key)
6942 nflags |= MDB_SPLIT_REPLACE;
6943 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6944 } else {
6945 /* There is room already in this leaf page. */
6946 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6947 if (rc == 0) {
6948 /* Adjust other cursors pointing to mp */
6949 MDB_cursor *m2, *m3;
6950 MDB_dbi dbi = mc->mc_dbi;
6951 unsigned i = mc->mc_top;
6952 MDB_page *mp = mc->mc_pg[i];
6953
6954 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6955 if (mc->mc_flags & C_SUB)
6956 m3 = &m2->mc_xcursor->mx_cursor;
6957 else
6958 m3 = m2;
6959 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
6960 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
6961 m3->mc_ki[i]++;
6962 }
6963 XCURSOR_REFRESH(m3, i, mp);
6964 }
6965 }
6966 }
6967
6968 if (rc == MDB_SUCCESS) {
6969 /* Now store the actual data in the child DB. Note that we're
6970 * storing the user data in the keys field, so there are strict
6971 * size limits on dupdata. The actual data fields of the child
6972 * DB are all zero size.
6973 */
6974 if (do_sub) {
6975 int xflags, new_dupdata;
6976 size_t ecount;
6977 put_sub:
6978 xdata.mv_size = 0;
6979 xdata.mv_data = "";
6980 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6981 if (flags & MDB_CURRENT) {
6982 xflags = MDB_CURRENT|MDB_NOSPILL;
6983 } else {
6984 mdb_xcursor_init1(mc, leaf);
6985 xflags = (flags & MDB_NODUPDATA) ?
6986 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6987 }
6988 if (sub_root)
6989 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6990 new_dupdata = (int)dkey.mv_size;
6991 /* converted, write the original data first */
6992 if (dkey.mv_size) {
6993 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6994 if (rc)
6995 goto bad_sub;
6996 /* we've done our job */
6997 dkey.mv_size = 0;
6998 }
6999 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7000 /* Adjust other cursors pointing to mp */
7001 MDB_cursor *m2;
7002 MDB_xcursor *mx = mc->mc_xcursor;
7003 unsigned i = mc->mc_top;
7004 MDB_page *mp = mc->mc_pg[i];
7005
7006 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7007 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7008 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7009 if (m2->mc_pg[i] == mp) {
7010 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7011 mdb_xcursor_init2(m2, mx, new_dupdata);
7012 } else if (!insert_key) {
7013 XCURSOR_REFRESH(m2, i, mp);
7014 }
7015 }
7016 }
7017 }
7018 ecount = mc->mc_xcursor->mx_db.md_entries;
7019 if (flags & MDB_APPENDDUP)
7020 xflags |= MDB_APPEND;
7021 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7022 if (flags & F_SUBDATA) {
7023 void *db = NODEDATA(leaf);
7024 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7025 }
7026 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7027 }
7028 /* Increment count unless we just replaced an existing item. */
7029 if (insert_data)
7030 mc->mc_db->md_entries++;
7031 if (insert_key) {
7032 /* Invalidate txn if we created an empty sub-DB */
7033 if (rc)
7034 goto bad_sub;
7035 /* If we succeeded and the key didn't exist before,
7036 * make sure the cursor is marked valid.
7037 */
7038 mc->mc_flags |= C_INITIALIZED;
7039 }
7040 if (flags & MDB_MULTIPLE) {
7041 if (!rc) {
7042 mcount++;
7043 /* let caller know how many succeeded, if any */
7044 data[1].mv_size = mcount;
7045 if (mcount < dcount) {
7046 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7047 insert_key = insert_data = 0;
7048 goto more;
7049 }
7050 }
7051 }
7052 return rc;
7053 bad_sub:
7054 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7055 rc = MDB_CORRUPTED;
7056 }
7057 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7058 return rc;
7059 }
7060
7061 int
mdb_cursor_del(MDB_cursor * mc,unsigned int flags)7062 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7063 {
7064 MDB_node *leaf;
7065 MDB_page *mp;
7066 int rc;
7067
7068 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7069 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7070
7071 if (!(mc->mc_flags & C_INITIALIZED))
7072 return EINVAL;
7073
7074 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7075 return MDB_NOTFOUND;
7076
7077 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7078 return rc;
7079
7080 rc = mdb_cursor_touch(mc);
7081 if (rc)
7082 return rc;
7083
7084 mp = mc->mc_pg[mc->mc_top];
7085 if (IS_LEAF2(mp))
7086 goto del_key;
7087 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7088
7089 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7090 if (flags & MDB_NODUPDATA) {
7091 /* mdb_cursor_del0() will subtract the final entry */
7092 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7093 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7094 } else {
7095 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7096 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7097 }
7098 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7099 if (rc)
7100 return rc;
7101 /* If sub-DB still has entries, we're done */
7102 if (mc->mc_xcursor->mx_db.md_entries) {
7103 if (leaf->mn_flags & F_SUBDATA) {
7104 /* update subDB info */
7105 void *db = NODEDATA(leaf);
7106 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7107 } else {
7108 MDB_cursor *m2;
7109 /* shrink fake page */
7110 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7111 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7112 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7113 /* fix other sub-DB cursors pointed at fake pages on this page */
7114 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7115 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7116 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7117 if (m2->mc_pg[mc->mc_top] == mp) {
7118 XCURSOR_REFRESH(m2, mc->mc_top, mp);
7119 }
7120 }
7121 }
7122 mc->mc_db->md_entries--;
7123 return rc;
7124 } else {
7125 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7126 }
7127 /* otherwise fall thru and delete the sub-DB */
7128 }
7129
7130 if (leaf->mn_flags & F_SUBDATA) {
7131 /* add all the child DB's pages to the free list */
7132 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7133 if (rc)
7134 goto fail;
7135 }
7136 }
7137 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7138 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7139 rc = MDB_INCOMPATIBLE;
7140 goto fail;
7141 }
7142
7143 /* add overflow pages to free list */
7144 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7145 MDB_page *omp;
7146 pgno_t pg;
7147
7148 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7149 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7150 (rc = mdb_ovpage_free(mc, omp)))
7151 goto fail;
7152 }
7153
7154 del_key:
7155 return mdb_cursor_del0(mc);
7156
7157 fail:
7158 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7159 return rc;
7160 }
7161
7162 /** Allocate and initialize new pages for a database.
7163 * Set #MDB_TXN_ERROR on failure.
7164 * @param[in] mc a cursor on the database being added to.
7165 * @param[in] flags flags defining what type of page is being allocated.
7166 * @param[in] num the number of pages to allocate. This is usually 1,
7167 * unless allocating overflow pages for a large record.
7168 * @param[out] mp Address of a page, or NULL on failure.
7169 * @return 0 on success, non-zero on failure.
7170 */
7171 static int
mdb_page_new(MDB_cursor * mc,uint32_t flags,int num,MDB_page ** mp)7172 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7173 {
7174 MDB_page *np;
7175 int rc;
7176
7177 if ((rc = mdb_page_alloc(mc, num, &np)))
7178 return rc;
7179 DPRINTF(("allocated new mpage %"Z"u, page size %u",
7180 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7181 np->mp_flags = flags | P_DIRTY;
7182 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7183 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7184
7185 if (IS_BRANCH(np))
7186 mc->mc_db->md_branch_pages++;
7187 else if (IS_LEAF(np))
7188 mc->mc_db->md_leaf_pages++;
7189 else if (IS_OVERFLOW(np)) {
7190 mc->mc_db->md_overflow_pages += num;
7191 np->mp_pages = num;
7192 }
7193 *mp = np;
7194
7195 return 0;
7196 }
7197
7198 /** Calculate the size of a leaf node.
7199 * The size depends on the environment's page size; if a data item
7200 * is too large it will be put onto an overflow page and the node
7201 * size will only include the key and not the data. Sizes are always
7202 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7203 * of the #MDB_node headers.
7204 * @param[in] env The environment handle.
7205 * @param[in] key The key for the node.
7206 * @param[in] data The data for the node.
7207 * @return The number of bytes needed to store the node.
7208 */
7209 static size_t
mdb_leaf_size(MDB_env * env,MDB_val * key,MDB_val * data)7210 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7211 {
7212 size_t sz;
7213
7214 sz = LEAFSIZE(key, data);
7215 if (sz > env->me_nodemax) {
7216 /* put on overflow page */
7217 sz -= data->mv_size - sizeof(pgno_t);
7218 }
7219
7220 return EVEN(sz + sizeof(indx_t));
7221 }
7222
7223 /** Calculate the size of a branch node.
7224 * The size should depend on the environment's page size but since
7225 * we currently don't support spilling large keys onto overflow
7226 * pages, it's simply the size of the #MDB_node header plus the
7227 * size of the key. Sizes are always rounded up to an even number
7228 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7229 * @param[in] env The environment handle.
7230 * @param[in] key The key for the node.
7231 * @return The number of bytes needed to store the node.
7232 */
7233 static size_t
mdb_branch_size(MDB_env * env,MDB_val * key)7234 mdb_branch_size(MDB_env *env, MDB_val *key)
7235 {
7236 size_t sz;
7237
7238 sz = INDXSIZE(key);
7239 if (sz > env->me_nodemax) {
7240 /* put on overflow page */
7241 /* not implemented */
7242 /* sz -= key->size - sizeof(pgno_t); */
7243 }
7244
7245 return sz + sizeof(indx_t);
7246 }
7247
7248 /** Add a node to the page pointed to by the cursor.
7249 * Set #MDB_TXN_ERROR on failure.
7250 * @param[in] mc The cursor for this operation.
7251 * @param[in] indx The index on the page where the new node should be added.
7252 * @param[in] key The key for the new node.
7253 * @param[in] data The data for the new node, if any.
7254 * @param[in] pgno The page number, if adding a branch node.
7255 * @param[in] flags Flags for the node.
7256 * @return 0 on success, non-zero on failure. Possible errors are:
7257 * <ul>
7258 * <li>ENOMEM - failed to allocate overflow pages for the node.
7259 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7260 * should never happen since all callers already calculate the
7261 * page's free space before calling this function.
7262 * </ul>
7263 */
7264 static int
mdb_node_add(MDB_cursor * mc,indx_t indx,MDB_val * key,MDB_val * data,pgno_t pgno,unsigned int flags)7265 mdb_node_add(MDB_cursor *mc, indx_t indx,
7266 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7267 {
7268 unsigned int i;
7269 size_t node_size = NODESIZE;
7270 ssize_t room;
7271 indx_t ofs;
7272 MDB_node *node;
7273 MDB_page *mp = mc->mc_pg[mc->mc_top];
7274 MDB_page *ofp = NULL; /* overflow page */
7275 void *ndata;
7276 DKBUF;
7277
7278 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7279
7280 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7281 IS_LEAF(mp) ? "leaf" : "branch",
7282 IS_SUBP(mp) ? "sub-" : "",
7283 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7284 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7285
7286 if (IS_LEAF2(mp)) {
7287 /* Move higher keys up one slot. */
7288 int ksize = mc->mc_db->md_pad, dif;
7289 char *ptr = LEAF2KEY(mp, indx, ksize);
7290 dif = NUMKEYS(mp) - indx;
7291 if (dif > 0)
7292 memmove(ptr+ksize, ptr, dif*ksize);
7293 /* insert new key */
7294 memcpy(ptr, key->mv_data, ksize);
7295
7296 /* Just using these for counting */
7297 mp->mp_lower += sizeof(indx_t);
7298 mp->mp_upper -= ksize - sizeof(indx_t);
7299 return MDB_SUCCESS;
7300 }
7301
7302 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7303 if (key != NULL)
7304 node_size += key->mv_size;
7305 if (IS_LEAF(mp)) {
7306 mdb_cassert(mc, key && data);
7307 if (F_ISSET(flags, F_BIGDATA)) {
7308 /* Data already on overflow page. */
7309 node_size += sizeof(pgno_t);
7310 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7311 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7312 int rc;
7313 /* Put data on overflow page. */
7314 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7315 data->mv_size, node_size+data->mv_size));
7316 node_size = EVEN(node_size + sizeof(pgno_t));
7317 if ((ssize_t)node_size > room)
7318 goto full;
7319 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7320 return rc;
7321 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7322 flags |= F_BIGDATA;
7323 goto update;
7324 } else {
7325 node_size += data->mv_size;
7326 }
7327 }
7328 node_size = EVEN(node_size);
7329 if ((ssize_t)node_size > room)
7330 goto full;
7331
7332 update:
7333 /* Move higher pointers up one slot. */
7334 for (i = NUMKEYS(mp); i > indx; i--)
7335 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7336
7337 /* Adjust free space offsets. */
7338 ofs = mp->mp_upper - node_size;
7339 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7340 mp->mp_ptrs[indx] = ofs;
7341 mp->mp_upper = ofs;
7342 mp->mp_lower += sizeof(indx_t);
7343
7344 /* Write the node data. */
7345 node = NODEPTR(mp, indx);
7346 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7347 node->mn_flags = flags;
7348 if (IS_LEAF(mp))
7349 SETDSZ(node,data->mv_size);
7350 else
7351 SETPGNO(node,pgno);
7352
7353 if (key)
7354 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7355
7356 if (IS_LEAF(mp)) {
7357 ndata = NODEDATA(node);
7358 if (ofp == NULL) {
7359 if (F_ISSET(flags, F_BIGDATA))
7360 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7361 else if (F_ISSET(flags, MDB_RESERVE))
7362 data->mv_data = ndata;
7363 else
7364 memcpy(ndata, data->mv_data, data->mv_size);
7365 } else {
7366 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7367 ndata = METADATA(ofp);
7368 if (F_ISSET(flags, MDB_RESERVE))
7369 data->mv_data = ndata;
7370 else
7371 memcpy(ndata, data->mv_data, data->mv_size);
7372 }
7373 }
7374
7375 return MDB_SUCCESS;
7376
7377 full:
7378 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7379 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7380 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7381 DPRINTF(("node size = %"Z"u", node_size));
7382 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7383 return MDB_PAGE_FULL;
7384 }
7385
7386 /** Delete the specified node from a page.
7387 * @param[in] mc Cursor pointing to the node to delete.
7388 * @param[in] ksize The size of a node. Only used if the page is
7389 * part of a #MDB_DUPFIXED database.
7390 */
7391 static void
mdb_node_del(MDB_cursor * mc,int ksize)7392 mdb_node_del(MDB_cursor *mc, int ksize)
7393 {
7394 MDB_page *mp = mc->mc_pg[mc->mc_top];
7395 indx_t indx = mc->mc_ki[mc->mc_top];
7396 unsigned int sz;
7397 indx_t i, j, numkeys, ptr;
7398 MDB_node *node;
7399 char *base;
7400
7401 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7402 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7403 numkeys = NUMKEYS(mp);
7404 mdb_cassert(mc, indx < numkeys);
7405
7406 if (IS_LEAF2(mp)) {
7407 int x = numkeys - 1 - indx;
7408 base = LEAF2KEY(mp, indx, ksize);
7409 if (x)
7410 memmove(base, base + ksize, x * ksize);
7411 mp->mp_lower -= sizeof(indx_t);
7412 mp->mp_upper += ksize - sizeof(indx_t);
7413 return;
7414 }
7415
7416 node = NODEPTR(mp, indx);
7417 sz = NODESIZE + node->mn_ksize;
7418 if (IS_LEAF(mp)) {
7419 if (F_ISSET(node->mn_flags, F_BIGDATA))
7420 sz += sizeof(pgno_t);
7421 else
7422 sz += NODEDSZ(node);
7423 }
7424 sz = EVEN(sz);
7425
7426 ptr = mp->mp_ptrs[indx];
7427 for (i = j = 0; i < numkeys; i++) {
7428 if (i != indx) {
7429 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7430 if (mp->mp_ptrs[i] < ptr)
7431 mp->mp_ptrs[j] += sz;
7432 j++;
7433 }
7434 }
7435
7436 base = (char *)mp + mp->mp_upper + PAGEBASE;
7437 memmove(base + sz, base, ptr - mp->mp_upper);
7438
7439 mp->mp_lower -= sizeof(indx_t);
7440 mp->mp_upper += sz;
7441 }
7442
7443 /** Compact the main page after deleting a node on a subpage.
7444 * @param[in] mp The main page to operate on.
7445 * @param[in] indx The index of the subpage on the main page.
7446 */
7447 static void
mdb_node_shrink(MDB_page * mp,indx_t indx)7448 mdb_node_shrink(MDB_page *mp, indx_t indx)
7449 {
7450 MDB_node *node;
7451 MDB_page *sp, *xp;
7452 char *base;
7453 indx_t delta, nsize, len, ptr;
7454 int i;
7455
7456 node = NODEPTR(mp, indx);
7457 sp = (MDB_page *)NODEDATA(node);
7458 delta = SIZELEFT(sp);
7459 nsize = NODEDSZ(node) - delta;
7460
7461 /* Prepare to shift upward, set len = length(subpage part to shift) */
7462 if (IS_LEAF2(sp)) {
7463 len = nsize;
7464 if (nsize & 1)
7465 return; /* do not make the node uneven-sized */
7466 } else {
7467 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7468 for (i = NUMKEYS(sp); --i >= 0; )
7469 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7470 len = PAGEHDRSZ;
7471 }
7472 sp->mp_upper = sp->mp_lower;
7473 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7474 SETDSZ(node, nsize);
7475
7476 /* Shift <lower nodes...initial part of subpage> upward */
7477 base = (char *)mp + mp->mp_upper + PAGEBASE;
7478 memmove(base + delta, base, (char *)sp + len - base);
7479
7480 ptr = mp->mp_ptrs[indx];
7481 for (i = NUMKEYS(mp); --i >= 0; ) {
7482 if (mp->mp_ptrs[i] <= ptr)
7483 mp->mp_ptrs[i] += delta;
7484 }
7485 mp->mp_upper += delta;
7486 }
7487
7488 /** Initial setup of a sorted-dups cursor.
7489 * Sorted duplicates are implemented as a sub-database for the given key.
7490 * The duplicate data items are actually keys of the sub-database.
7491 * Operations on the duplicate data items are performed using a sub-cursor
7492 * initialized when the sub-database is first accessed. This function does
7493 * the preliminary setup of the sub-cursor, filling in the fields that
7494 * depend only on the parent DB.
7495 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7496 */
7497 static void
mdb_xcursor_init0(MDB_cursor * mc)7498 mdb_xcursor_init0(MDB_cursor *mc)
7499 {
7500 MDB_xcursor *mx = mc->mc_xcursor;
7501
7502 mx->mx_cursor.mc_xcursor = NULL;
7503 mx->mx_cursor.mc_txn = mc->mc_txn;
7504 mx->mx_cursor.mc_db = &mx->mx_db;
7505 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7506 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7507 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7508 mx->mx_cursor.mc_snum = 0;
7509 mx->mx_cursor.mc_top = 0;
7510 mx->mx_cursor.mc_flags = C_SUB;
7511 mx->mx_dbx.md_name.mv_size = 0;
7512 mx->mx_dbx.md_name.mv_data = NULL;
7513 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7514 mx->mx_dbx.md_dcmp = NULL;
7515 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7516 }
7517
7518 /** Final setup of a sorted-dups cursor.
7519 * Sets up the fields that depend on the data from the main cursor.
7520 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7521 * @param[in] node The data containing the #MDB_db record for the
7522 * sorted-dup database.
7523 */
7524 static void
mdb_xcursor_init1(MDB_cursor * mc,MDB_node * node)7525 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7526 {
7527 MDB_xcursor *mx = mc->mc_xcursor;
7528
7529 if (node->mn_flags & F_SUBDATA) {
7530 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7531 mx->mx_cursor.mc_pg[0] = 0;
7532 mx->mx_cursor.mc_snum = 0;
7533 mx->mx_cursor.mc_top = 0;
7534 mx->mx_cursor.mc_flags = C_SUB;
7535 } else {
7536 MDB_page *fp = NODEDATA(node);
7537 mx->mx_db.md_pad = 0;
7538 mx->mx_db.md_flags = 0;
7539 mx->mx_db.md_depth = 1;
7540 mx->mx_db.md_branch_pages = 0;
7541 mx->mx_db.md_leaf_pages = 1;
7542 mx->mx_db.md_overflow_pages = 0;
7543 mx->mx_db.md_entries = NUMKEYS(fp);
7544 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7545 mx->mx_cursor.mc_snum = 1;
7546 mx->mx_cursor.mc_top = 0;
7547 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7548 mx->mx_cursor.mc_pg[0] = fp;
7549 mx->mx_cursor.mc_ki[0] = 0;
7550 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7551 mx->mx_db.md_flags = MDB_DUPFIXED;
7552 mx->mx_db.md_pad = fp->mp_pad;
7553 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7554 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7555 }
7556 }
7557 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7558 mx->mx_db.md_root));
7559 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7560 #if UINT_MAX < SIZE_MAX
7561 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7562 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7563 #endif
7564 }
7565
7566
7567 /** Fixup a sorted-dups cursor due to underlying update.
7568 * Sets up some fields that depend on the data from the main cursor.
7569 * Almost the same as init1, but skips initialization steps if the
7570 * xcursor had already been used.
7571 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7572 * @param[in] src_mx The xcursor of an up-to-date cursor.
7573 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7574 */
7575 static void
mdb_xcursor_init2(MDB_cursor * mc,MDB_xcursor * src_mx,int new_dupdata)7576 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7577 {
7578 MDB_xcursor *mx = mc->mc_xcursor;
7579
7580 if (new_dupdata) {
7581 mx->mx_cursor.mc_snum = 1;
7582 mx->mx_cursor.mc_top = 0;
7583 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7584 mx->mx_cursor.mc_ki[0] = 0;
7585 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7586 #if UINT_MAX < SIZE_MAX
7587 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7588 #endif
7589 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7590 return;
7591 }
7592 mx->mx_db = src_mx->mx_db;
7593 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7594 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7595 mx->mx_db.md_root));
7596 }
7597
7598 /** Initialize a cursor for a given transaction and database. */
7599 static void
mdb_cursor_init(MDB_cursor * mc,MDB_txn * txn,MDB_dbi dbi,MDB_xcursor * mx)7600 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7601 {
7602 mc->mc_next = NULL;
7603 mc->mc_backup = NULL;
7604 mc->mc_dbi = dbi;
7605 mc->mc_txn = txn;
7606 mc->mc_db = &txn->mt_dbs[dbi];
7607 mc->mc_dbx = &txn->mt_dbxs[dbi];
7608 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7609 mc->mc_snum = 0;
7610 mc->mc_top = 0;
7611 mc->mc_pg[0] = 0;
7612 mc->mc_ki[0] = 0;
7613 mc->mc_flags = 0;
7614 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7615 mdb_tassert(txn, mx != NULL);
7616 mc->mc_xcursor = mx;
7617 mdb_xcursor_init0(mc);
7618 } else {
7619 mc->mc_xcursor = NULL;
7620 }
7621 if (*mc->mc_dbflag & DB_STALE) {
7622 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7623 }
7624 }
7625
7626 int
mdb_cursor_open(MDB_txn * txn,MDB_dbi dbi,MDB_cursor ** ret)7627 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7628 {
7629 MDB_cursor *mc;
7630 size_t size = sizeof(MDB_cursor);
7631
7632 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7633 return EINVAL;
7634
7635 if (txn->mt_flags & MDB_TXN_BLOCKED)
7636 return MDB_BAD_TXN;
7637
7638 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7639 return EINVAL;
7640
7641 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7642 size += sizeof(MDB_xcursor);
7643
7644 if ((mc = malloc(size)) != NULL) {
7645 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7646 if (txn->mt_cursors) {
7647 mc->mc_next = txn->mt_cursors[dbi];
7648 txn->mt_cursors[dbi] = mc;
7649 mc->mc_flags |= C_UNTRACK;
7650 }
7651 } else {
7652 return ENOMEM;
7653 }
7654
7655 *ret = mc;
7656
7657 return MDB_SUCCESS;
7658 }
7659
7660 int
mdb_cursor_renew(MDB_txn * txn,MDB_cursor * mc)7661 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7662 {
7663 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7664 return EINVAL;
7665
7666 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7667 return EINVAL;
7668
7669 if (txn->mt_flags & MDB_TXN_BLOCKED)
7670 return MDB_BAD_TXN;
7671
7672 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7673 return MDB_SUCCESS;
7674 }
7675
7676 /* Return the count of duplicate data items for the current key */
7677 int
mdb_cursor_count(MDB_cursor * mc,size_t * countp)7678 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7679 {
7680 MDB_node *leaf;
7681
7682 if (mc == NULL || countp == NULL)
7683 return EINVAL;
7684
7685 if (mc->mc_xcursor == NULL)
7686 return MDB_INCOMPATIBLE;
7687
7688 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7689 return MDB_BAD_TXN;
7690
7691 if (!(mc->mc_flags & C_INITIALIZED))
7692 return EINVAL;
7693
7694 if (!mc->mc_snum)
7695 return MDB_NOTFOUND;
7696
7697 if (mc->mc_flags & C_EOF) {
7698 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7699 return MDB_NOTFOUND;
7700 mc->mc_flags ^= C_EOF;
7701 }
7702
7703 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7704 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7705 *countp = 1;
7706 } else {
7707 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7708 return EINVAL;
7709
7710 *countp = mc->mc_xcursor->mx_db.md_entries;
7711 }
7712 return MDB_SUCCESS;
7713 }
7714
7715 void
mdb_cursor_close(MDB_cursor * mc)7716 mdb_cursor_close(MDB_cursor *mc)
7717 {
7718 if (mc && !mc->mc_backup) {
7719 /* remove from txn, if tracked */
7720 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7721 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7722 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7723 if (*prev == mc)
7724 *prev = mc->mc_next;
7725 }
7726 free(mc);
7727 }
7728 }
7729
7730 MDB_txn *
mdb_cursor_txn(MDB_cursor * mc)7731 mdb_cursor_txn(MDB_cursor *mc)
7732 {
7733 if (!mc) return NULL;
7734 return mc->mc_txn;
7735 }
7736
7737 MDB_dbi
mdb_cursor_dbi(MDB_cursor * mc)7738 mdb_cursor_dbi(MDB_cursor *mc)
7739 {
7740 return mc->mc_dbi;
7741 }
7742
7743 /** Replace the key for a branch node with a new key.
7744 * Set #MDB_TXN_ERROR on failure.
7745 * @param[in] mc Cursor pointing to the node to operate on.
7746 * @param[in] key The new key to use.
7747 * @return 0 on success, non-zero on failure.
7748 */
7749 static int
mdb_update_key(MDB_cursor * mc,MDB_val * key)7750 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7751 {
7752 MDB_page *mp;
7753 MDB_node *node;
7754 char *base;
7755 size_t len;
7756 int delta, ksize, oksize;
7757 indx_t ptr, i, numkeys, indx;
7758 DKBUF;
7759
7760 indx = mc->mc_ki[mc->mc_top];
7761 mp = mc->mc_pg[mc->mc_top];
7762 node = NODEPTR(mp, indx);
7763 ptr = mp->mp_ptrs[indx];
7764 #if MDB_DEBUG
7765 {
7766 MDB_val k2;
7767 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7768 k2.mv_data = NODEKEY(node);
7769 k2.mv_size = node->mn_ksize;
7770 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7771 indx, ptr,
7772 mdb_dkey(&k2, kbuf2),
7773 DKEY(key),
7774 mp->mp_pgno));
7775 }
7776 #endif
7777
7778 /* Sizes must be 2-byte aligned. */
7779 ksize = EVEN(key->mv_size);
7780 oksize = EVEN(node->mn_ksize);
7781 delta = ksize - oksize;
7782
7783 /* Shift node contents if EVEN(key length) changed. */
7784 if (delta) {
7785 if (delta > 0 && SIZELEFT(mp) < delta) {
7786 pgno_t pgno;
7787 /* not enough space left, do a delete and split */
7788 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7789 pgno = NODEPGNO(node);
7790 mdb_node_del(mc, 0);
7791 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7792 }
7793
7794 numkeys = NUMKEYS(mp);
7795 for (i = 0; i < numkeys; i++) {
7796 if (mp->mp_ptrs[i] <= ptr)
7797 mp->mp_ptrs[i] -= delta;
7798 }
7799
7800 base = (char *)mp + mp->mp_upper + PAGEBASE;
7801 len = ptr - mp->mp_upper + NODESIZE;
7802 memmove(base - delta, base, len);
7803 mp->mp_upper -= delta;
7804
7805 node = NODEPTR(mp, indx);
7806 }
7807
7808 /* But even if no shift was needed, update ksize */
7809 if (node->mn_ksize != key->mv_size)
7810 node->mn_ksize = key->mv_size;
7811
7812 if (key->mv_size)
7813 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7814
7815 return MDB_SUCCESS;
7816 }
7817
7818 static void
7819 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7820
7821 /** Perform \b act while tracking temporary cursor \b mn */
7822 #define WITH_CURSOR_TRACKING(mn, act) do { \
7823 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
7824 if ((mn).mc_flags & C_SUB) { \
7825 dummy.mc_flags = C_INITIALIZED; \
7826 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
7827 tracked = &dummy; \
7828 } else { \
7829 tracked = &(mn); \
7830 } \
7831 tracked->mc_next = *tp; \
7832 *tp = tracked; \
7833 { act; } \
7834 *tp = tracked->mc_next; \
7835 } while (0)
7836
7837 /** Move a node from csrc to cdst.
7838 */
7839 static int
mdb_node_move(MDB_cursor * csrc,MDB_cursor * cdst,int fromleft)7840 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
7841 {
7842 MDB_node *srcnode;
7843 MDB_val key, data;
7844 pgno_t srcpg;
7845 MDB_cursor mn;
7846 int rc;
7847 unsigned short flags;
7848
7849 DKBUF;
7850
7851 /* Mark src and dst as dirty. */
7852 if ((rc = mdb_page_touch(csrc)) ||
7853 (rc = mdb_page_touch(cdst)))
7854 return rc;
7855
7856 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7857 key.mv_size = csrc->mc_db->md_pad;
7858 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7859 data.mv_size = 0;
7860 data.mv_data = NULL;
7861 srcpg = 0;
7862 flags = 0;
7863 } else {
7864 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7865 mdb_cassert(csrc, !((size_t)srcnode & 1));
7866 srcpg = NODEPGNO(srcnode);
7867 flags = srcnode->mn_flags;
7868 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7869 unsigned int snum = csrc->mc_snum;
7870 MDB_node *s2;
7871 /* must find the lowest key below src */
7872 rc = mdb_page_search_lowest(csrc);
7873 if (rc)
7874 return rc;
7875 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7876 key.mv_size = csrc->mc_db->md_pad;
7877 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7878 } else {
7879 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7880 key.mv_size = NODEKSZ(s2);
7881 key.mv_data = NODEKEY(s2);
7882 }
7883 csrc->mc_snum = snum--;
7884 csrc->mc_top = snum;
7885 } else {
7886 key.mv_size = NODEKSZ(srcnode);
7887 key.mv_data = NODEKEY(srcnode);
7888 }
7889 data.mv_size = NODEDSZ(srcnode);
7890 data.mv_data = NODEDATA(srcnode);
7891 }
7892 mn.mc_xcursor = NULL;
7893 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7894 unsigned int snum = cdst->mc_snum;
7895 MDB_node *s2;
7896 MDB_val bkey;
7897 /* must find the lowest key below dst */
7898 mdb_cursor_copy(cdst, &mn);
7899 rc = mdb_page_search_lowest(&mn);
7900 if (rc)
7901 return rc;
7902 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7903 bkey.mv_size = mn.mc_db->md_pad;
7904 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7905 } else {
7906 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7907 bkey.mv_size = NODEKSZ(s2);
7908 bkey.mv_data = NODEKEY(s2);
7909 }
7910 mn.mc_snum = snum--;
7911 mn.mc_top = snum;
7912 mn.mc_ki[snum] = 0;
7913 rc = mdb_update_key(&mn, &bkey);
7914 if (rc)
7915 return rc;
7916 }
7917
7918 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7919 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7920 csrc->mc_ki[csrc->mc_top],
7921 DKEY(&key),
7922 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7923 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7924
7925 /* Add the node to the destination page.
7926 */
7927 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7928 if (rc != MDB_SUCCESS)
7929 return rc;
7930
7931 /* Delete the node from the source page.
7932 */
7933 mdb_node_del(csrc, key.mv_size);
7934
7935 {
7936 /* Adjust other cursors pointing to mp */
7937 MDB_cursor *m2, *m3;
7938 MDB_dbi dbi = csrc->mc_dbi;
7939 MDB_page *mpd, *mps;
7940
7941 mps = csrc->mc_pg[csrc->mc_top];
7942 /* If we're adding on the left, bump others up */
7943 if (fromleft) {
7944 mpd = cdst->mc_pg[csrc->mc_top];
7945 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7946 if (csrc->mc_flags & C_SUB)
7947 m3 = &m2->mc_xcursor->mx_cursor;
7948 else
7949 m3 = m2;
7950 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7951 continue;
7952 if (m3 != cdst &&
7953 m3->mc_pg[csrc->mc_top] == mpd &&
7954 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7955 m3->mc_ki[csrc->mc_top]++;
7956 }
7957 if (m3 !=csrc &&
7958 m3->mc_pg[csrc->mc_top] == mps &&
7959 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7960 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7961 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7962 m3->mc_ki[csrc->mc_top-1]++;
7963 }
7964 if (IS_LEAF(mps))
7965 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
7966 }
7967 } else
7968 /* Adding on the right, bump others down */
7969 {
7970 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7971 if (csrc->mc_flags & C_SUB)
7972 m3 = &m2->mc_xcursor->mx_cursor;
7973 else
7974 m3 = m2;
7975 if (m3 == csrc) continue;
7976 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7977 continue;
7978 if (m3->mc_pg[csrc->mc_top] == mps) {
7979 if (!m3->mc_ki[csrc->mc_top]) {
7980 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7981 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7982 m3->mc_ki[csrc->mc_top-1]--;
7983 } else {
7984 m3->mc_ki[csrc->mc_top]--;
7985 }
7986 if (IS_LEAF(mps))
7987 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
7988 }
7989 }
7990 }
7991 }
7992
7993 /* Update the parent separators.
7994 */
7995 if (csrc->mc_ki[csrc->mc_top] == 0) {
7996 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7997 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7998 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7999 } else {
8000 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8001 key.mv_size = NODEKSZ(srcnode);
8002 key.mv_data = NODEKEY(srcnode);
8003 }
8004 DPRINTF(("update separator for source page %"Z"u to [%s]",
8005 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8006 mdb_cursor_copy(csrc, &mn);
8007 mn.mc_snum--;
8008 mn.mc_top--;
8009 /* We want mdb_rebalance to find mn when doing fixups */
8010 WITH_CURSOR_TRACKING(mn,
8011 rc = mdb_update_key(&mn, &key));
8012 if (rc)
8013 return rc;
8014 }
8015 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8016 MDB_val nullkey;
8017 indx_t ix = csrc->mc_ki[csrc->mc_top];
8018 nullkey.mv_size = 0;
8019 csrc->mc_ki[csrc->mc_top] = 0;
8020 rc = mdb_update_key(csrc, &nullkey);
8021 csrc->mc_ki[csrc->mc_top] = ix;
8022 mdb_cassert(csrc, rc == MDB_SUCCESS);
8023 }
8024 }
8025
8026 if (cdst->mc_ki[cdst->mc_top] == 0) {
8027 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8028 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8029 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8030 } else {
8031 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8032 key.mv_size = NODEKSZ(srcnode);
8033 key.mv_data = NODEKEY(srcnode);
8034 }
8035 DPRINTF(("update separator for destination page %"Z"u to [%s]",
8036 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8037 mdb_cursor_copy(cdst, &mn);
8038 mn.mc_snum--;
8039 mn.mc_top--;
8040 /* We want mdb_rebalance to find mn when doing fixups */
8041 WITH_CURSOR_TRACKING(mn,
8042 rc = mdb_update_key(&mn, &key));
8043 if (rc)
8044 return rc;
8045 }
8046 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8047 MDB_val nullkey;
8048 indx_t ix = cdst->mc_ki[cdst->mc_top];
8049 nullkey.mv_size = 0;
8050 cdst->mc_ki[cdst->mc_top] = 0;
8051 rc = mdb_update_key(cdst, &nullkey);
8052 cdst->mc_ki[cdst->mc_top] = ix;
8053 mdb_cassert(cdst, rc == MDB_SUCCESS);
8054 }
8055 }
8056
8057 return MDB_SUCCESS;
8058 }
8059
8060 /** Merge one page into another.
8061 * The nodes from the page pointed to by \b csrc will
8062 * be copied to the page pointed to by \b cdst and then
8063 * the \b csrc page will be freed.
8064 * @param[in] csrc Cursor pointing to the source page.
8065 * @param[in] cdst Cursor pointing to the destination page.
8066 * @return 0 on success, non-zero on failure.
8067 */
8068 static int
mdb_page_merge(MDB_cursor * csrc,MDB_cursor * cdst)8069 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8070 {
8071 MDB_page *psrc, *pdst;
8072 MDB_node *srcnode;
8073 MDB_val key, data;
8074 unsigned nkeys;
8075 int rc;
8076 indx_t i, j;
8077
8078 psrc = csrc->mc_pg[csrc->mc_top];
8079 pdst = cdst->mc_pg[cdst->mc_top];
8080
8081 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
8082
8083 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8084 mdb_cassert(csrc, cdst->mc_snum > 1);
8085
8086 /* Mark dst as dirty. */
8087 if ((rc = mdb_page_touch(cdst)))
8088 return rc;
8089
8090 /* get dst page again now that we've touched it. */
8091 pdst = cdst->mc_pg[cdst->mc_top];
8092
8093 /* Move all nodes from src to dst.
8094 */
8095 j = nkeys = NUMKEYS(pdst);
8096 if (IS_LEAF2(psrc)) {
8097 key.mv_size = csrc->mc_db->md_pad;
8098 key.mv_data = METADATA(psrc);
8099 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8100 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8101 if (rc != MDB_SUCCESS)
8102 return rc;
8103 key.mv_data = (char *)key.mv_data + key.mv_size;
8104 }
8105 } else {
8106 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8107 srcnode = NODEPTR(psrc, i);
8108 if (i == 0 && IS_BRANCH(psrc)) {
8109 MDB_cursor mn;
8110 MDB_node *s2;
8111 mdb_cursor_copy(csrc, &mn);
8112 mn.mc_xcursor = NULL;
8113 /* must find the lowest key below src */
8114 rc = mdb_page_search_lowest(&mn);
8115 if (rc)
8116 return rc;
8117 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8118 key.mv_size = mn.mc_db->md_pad;
8119 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8120 } else {
8121 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8122 key.mv_size = NODEKSZ(s2);
8123 key.mv_data = NODEKEY(s2);
8124 }
8125 } else {
8126 key.mv_size = srcnode->mn_ksize;
8127 key.mv_data = NODEKEY(srcnode);
8128 }
8129
8130 data.mv_size = NODEDSZ(srcnode);
8131 data.mv_data = NODEDATA(srcnode);
8132 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8133 if (rc != MDB_SUCCESS)
8134 return rc;
8135 }
8136 }
8137
8138 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
8139 pdst->mp_pgno, NUMKEYS(pdst),
8140 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8141
8142 /* Unlink the src page from parent and add to free list.
8143 */
8144 csrc->mc_top--;
8145 mdb_node_del(csrc, 0);
8146 if (csrc->mc_ki[csrc->mc_top] == 0) {
8147 key.mv_size = 0;
8148 rc = mdb_update_key(csrc, &key);
8149 if (rc) {
8150 csrc->mc_top++;
8151 return rc;
8152 }
8153 }
8154 csrc->mc_top++;
8155
8156 psrc = csrc->mc_pg[csrc->mc_top];
8157 /* If not operating on FreeDB, allow this page to be reused
8158 * in this txn. Otherwise just add to free list.
8159 */
8160 rc = mdb_page_loose(csrc, psrc);
8161 if (rc)
8162 return rc;
8163 if (IS_LEAF(psrc))
8164 csrc->mc_db->md_leaf_pages--;
8165 else
8166 csrc->mc_db->md_branch_pages--;
8167 {
8168 /* Adjust other cursors pointing to mp */
8169 MDB_cursor *m2, *m3;
8170 MDB_dbi dbi = csrc->mc_dbi;
8171 unsigned int top = csrc->mc_top;
8172
8173 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8174 if (csrc->mc_flags & C_SUB)
8175 m3 = &m2->mc_xcursor->mx_cursor;
8176 else
8177 m3 = m2;
8178 if (m3 == csrc) continue;
8179 if (m3->mc_snum < csrc->mc_snum) continue;
8180 if (m3->mc_pg[top] == psrc) {
8181 m3->mc_pg[top] = pdst;
8182 m3->mc_ki[top] += nkeys;
8183 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8184 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8185 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8186 m3->mc_ki[top-1]--;
8187 }
8188 if (IS_LEAF(psrc))
8189 XCURSOR_REFRESH(m3, top, m3->mc_pg[top]);
8190 }
8191 }
8192 {
8193 unsigned int snum = cdst->mc_snum;
8194 uint16_t depth = cdst->mc_db->md_depth;
8195 mdb_cursor_pop(cdst);
8196 rc = mdb_rebalance(cdst);
8197 /* Did the tree height change? */
8198 if (depth != cdst->mc_db->md_depth)
8199 snum += cdst->mc_db->md_depth - depth;
8200 cdst->mc_snum = snum;
8201 cdst->mc_top = snum-1;
8202 }
8203 return rc;
8204 }
8205
8206 /** Copy the contents of a cursor.
8207 * @param[in] csrc The cursor to copy from.
8208 * @param[out] cdst The cursor to copy to.
8209 */
8210 static void
mdb_cursor_copy(const MDB_cursor * csrc,MDB_cursor * cdst)8211 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8212 {
8213 unsigned int i;
8214
8215 cdst->mc_txn = csrc->mc_txn;
8216 cdst->mc_dbi = csrc->mc_dbi;
8217 cdst->mc_db = csrc->mc_db;
8218 cdst->mc_dbx = csrc->mc_dbx;
8219 cdst->mc_snum = csrc->mc_snum;
8220 cdst->mc_top = csrc->mc_top;
8221 cdst->mc_flags = csrc->mc_flags;
8222
8223 for (i=0; i<csrc->mc_snum; i++) {
8224 cdst->mc_pg[i] = csrc->mc_pg[i];
8225 cdst->mc_ki[i] = csrc->mc_ki[i];
8226 }
8227 }
8228
8229 /** Rebalance the tree after a delete operation.
8230 * @param[in] mc Cursor pointing to the page where rebalancing
8231 * should begin.
8232 * @return 0 on success, non-zero on failure.
8233 */
8234 static int
mdb_rebalance(MDB_cursor * mc)8235 mdb_rebalance(MDB_cursor *mc)
8236 {
8237 MDB_node *node;
8238 int rc, fromleft;
8239 unsigned int ptop, minkeys, thresh;
8240 MDB_cursor mn;
8241 indx_t oldki;
8242
8243 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8244 minkeys = 2;
8245 thresh = 1;
8246 } else {
8247 minkeys = 1;
8248 thresh = FILL_THRESHOLD;
8249 }
8250 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
8251 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8252 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8253 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8254
8255 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8256 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8257 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
8258 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8259 return MDB_SUCCESS;
8260 }
8261
8262 if (mc->mc_snum < 2) {
8263 MDB_page *mp = mc->mc_pg[0];
8264 if (IS_SUBP(mp)) {
8265 DPUTS("Can't rebalance a subpage, ignoring");
8266 return MDB_SUCCESS;
8267 }
8268 if (NUMKEYS(mp) == 0) {
8269 DPUTS("tree is completely empty");
8270 mc->mc_db->md_root = P_INVALID;
8271 mc->mc_db->md_depth = 0;
8272 mc->mc_db->md_leaf_pages = 0;
8273 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8274 if (rc)
8275 return rc;
8276 /* Adjust cursors pointing to mp */
8277 mc->mc_snum = 0;
8278 mc->mc_top = 0;
8279 mc->mc_flags &= ~C_INITIALIZED;
8280 {
8281 MDB_cursor *m2, *m3;
8282 MDB_dbi dbi = mc->mc_dbi;
8283
8284 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8285 if (mc->mc_flags & C_SUB)
8286 m3 = &m2->mc_xcursor->mx_cursor;
8287 else
8288 m3 = m2;
8289 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8290 continue;
8291 if (m3->mc_pg[0] == mp) {
8292 m3->mc_snum = 0;
8293 m3->mc_top = 0;
8294 m3->mc_flags &= ~C_INITIALIZED;
8295 }
8296 }
8297 }
8298 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8299 int i;
8300 DPUTS("collapsing root page!");
8301 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8302 if (rc)
8303 return rc;
8304 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8305 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8306 if (rc)
8307 return rc;
8308 mc->mc_db->md_depth--;
8309 mc->mc_db->md_branch_pages--;
8310 mc->mc_ki[0] = mc->mc_ki[1];
8311 for (i = 1; i<mc->mc_db->md_depth; i++) {
8312 mc->mc_pg[i] = mc->mc_pg[i+1];
8313 mc->mc_ki[i] = mc->mc_ki[i+1];
8314 }
8315 {
8316 /* Adjust other cursors pointing to mp */
8317 MDB_cursor *m2, *m3;
8318 MDB_dbi dbi = mc->mc_dbi;
8319
8320 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8321 if (mc->mc_flags & C_SUB)
8322 m3 = &m2->mc_xcursor->mx_cursor;
8323 else
8324 m3 = m2;
8325 if (m3 == mc) continue;
8326 if (!(m3->mc_flags & C_INITIALIZED))
8327 continue;
8328 if (m3->mc_pg[0] == mp) {
8329 for (i=0; i<mc->mc_db->md_depth; i++) {
8330 m3->mc_pg[i] = m3->mc_pg[i+1];
8331 m3->mc_ki[i] = m3->mc_ki[i+1];
8332 }
8333 m3->mc_snum--;
8334 m3->mc_top--;
8335 }
8336 }
8337 }
8338 } else
8339 DPUTS("root page doesn't need rebalancing");
8340 return MDB_SUCCESS;
8341 }
8342
8343 /* The parent (branch page) must have at least 2 pointers,
8344 * otherwise the tree is invalid.
8345 */
8346 ptop = mc->mc_top-1;
8347 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8348
8349 /* Leaf page fill factor is below the threshold.
8350 * Try to move keys from left or right neighbor, or
8351 * merge with a neighbor page.
8352 */
8353
8354 /* Find neighbors.
8355 */
8356 mdb_cursor_copy(mc, &mn);
8357 mn.mc_xcursor = NULL;
8358
8359 oldki = mc->mc_ki[mc->mc_top];
8360 if (mc->mc_ki[ptop] == 0) {
8361 /* We're the leftmost leaf in our parent.
8362 */
8363 DPUTS("reading right neighbor");
8364 mn.mc_ki[ptop]++;
8365 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8366 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8367 if (rc)
8368 return rc;
8369 mn.mc_ki[mn.mc_top] = 0;
8370 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8371 fromleft = 0;
8372 } else {
8373 /* There is at least one neighbor to the left.
8374 */
8375 DPUTS("reading left neighbor");
8376 mn.mc_ki[ptop]--;
8377 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8378 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8379 if (rc)
8380 return rc;
8381 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8382 mc->mc_ki[mc->mc_top] = 0;
8383 fromleft = 1;
8384 }
8385
8386 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8387 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8388 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8389
8390 /* If the neighbor page is above threshold and has enough keys,
8391 * move one key from it. Otherwise we should try to merge them.
8392 * (A branch page must never have less than 2 keys.)
8393 */
8394 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8395 rc = mdb_node_move(&mn, mc, fromleft);
8396 if (fromleft) {
8397 /* if we inserted on left, bump position up */
8398 oldki++;
8399 }
8400 } else {
8401 if (!fromleft) {
8402 rc = mdb_page_merge(&mn, mc);
8403 } else {
8404 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8405 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8406 /* We want mdb_rebalance to find mn when doing fixups */
8407 WITH_CURSOR_TRACKING(mn,
8408 rc = mdb_page_merge(mc, &mn));
8409 mdb_cursor_copy(&mn, mc);
8410 }
8411 mc->mc_flags &= ~C_EOF;
8412 }
8413 mc->mc_ki[mc->mc_top] = oldki;
8414 return rc;
8415 }
8416
8417 /** Complete a delete operation started by #mdb_cursor_del(). */
8418 static int
mdb_cursor_del0(MDB_cursor * mc)8419 mdb_cursor_del0(MDB_cursor *mc)
8420 {
8421 int rc;
8422 MDB_page *mp;
8423 indx_t ki;
8424 unsigned int nkeys;
8425 MDB_cursor *m2, *m3;
8426 MDB_dbi dbi = mc->mc_dbi;
8427
8428 ki = mc->mc_ki[mc->mc_top];
8429 mp = mc->mc_pg[mc->mc_top];
8430 mdb_node_del(mc, mc->mc_db->md_pad);
8431 mc->mc_db->md_entries--;
8432 {
8433 /* Adjust other cursors pointing to mp */
8434 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8435 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8436 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8437 continue;
8438 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8439 continue;
8440 if (m3->mc_pg[mc->mc_top] == mp) {
8441 if (m3->mc_ki[mc->mc_top] == ki) {
8442 m3->mc_flags |= C_DEL;
8443 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8444 /* Sub-cursor referred into dataset which is gone */
8445 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
8446 }
8447 continue;
8448 } else if (m3->mc_ki[mc->mc_top] > ki) {
8449 m3->mc_ki[mc->mc_top]--;
8450 }
8451 XCURSOR_REFRESH(m3, mc->mc_top, mp);
8452 }
8453 }
8454 }
8455 rc = mdb_rebalance(mc);
8456
8457 if (rc == MDB_SUCCESS) {
8458 /* DB is totally empty now, just bail out.
8459 * Other cursors adjustments were already done
8460 * by mdb_rebalance and aren't needed here.
8461 */
8462 if (!mc->mc_snum)
8463 return rc;
8464
8465 mp = mc->mc_pg[mc->mc_top];
8466 nkeys = NUMKEYS(mp);
8467
8468 /* Adjust other cursors pointing to mp */
8469 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8470 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8471 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8472 continue;
8473 if (m3->mc_snum < mc->mc_snum)
8474 continue;
8475 if (m3->mc_pg[mc->mc_top] == mp) {
8476 /* if m3 points past last node in page, find next sibling */
8477 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
8478 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8479 rc = mdb_cursor_sibling(m3, 1);
8480 if (rc == MDB_NOTFOUND) {
8481 m3->mc_flags |= C_EOF;
8482 rc = MDB_SUCCESS;
8483 continue;
8484 }
8485 }
8486 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8487 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
8488 /* If this node has dupdata, it may need to be reinited
8489 * because its data has moved.
8490 * If the xcursor was not initd it must be reinited.
8491 * Else if node points to a subDB, nothing is needed.
8492 * Else (xcursor was initd, not a subDB) needs mc_pg[0] reset.
8493 */
8494 if (node->mn_flags & F_DUPDATA) {
8495 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
8496 if (!(node->mn_flags & F_SUBDATA))
8497 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8498 } else {
8499 mdb_xcursor_init1(m3, node);
8500 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
8501 }
8502 }
8503 }
8504 }
8505 }
8506 }
8507 mc->mc_flags |= C_DEL;
8508 }
8509
8510 if (rc)
8511 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8512 return rc;
8513 }
8514
8515 int
mdb_del(MDB_txn * txn,MDB_dbi dbi,MDB_val * key,MDB_val * data)8516 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8517 MDB_val *key, MDB_val *data)
8518 {
8519 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8520 return EINVAL;
8521
8522 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8523 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8524
8525 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8526 /* must ignore any data */
8527 data = NULL;
8528 }
8529
8530 return mdb_del0(txn, dbi, key, data, 0);
8531 }
8532
8533 static int
mdb_del0(MDB_txn * txn,MDB_dbi dbi,MDB_val * key,MDB_val * data,unsigned flags)8534 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8535 MDB_val *key, MDB_val *data, unsigned flags)
8536 {
8537 MDB_cursor mc;
8538 MDB_xcursor mx;
8539 MDB_cursor_op op;
8540 MDB_val rdata, *xdata;
8541 int rc, exact = 0;
8542 DKBUF;
8543
8544 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8545
8546 mdb_cursor_init(&mc, txn, dbi, &mx);
8547
8548 if (data) {
8549 op = MDB_GET_BOTH;
8550 rdata = *data;
8551 xdata = &rdata;
8552 } else {
8553 op = MDB_SET;
8554 xdata = NULL;
8555 flags |= MDB_NODUPDATA;
8556 }
8557 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8558 if (rc == 0) {
8559 /* let mdb_page_split know about this cursor if needed:
8560 * delete will trigger a rebalance; if it needs to move
8561 * a node from one page to another, it will have to
8562 * update the parent's separator key(s). If the new sepkey
8563 * is larger than the current one, the parent page may
8564 * run out of space, triggering a split. We need this
8565 * cursor to be consistent until the end of the rebalance.
8566 */
8567 mc.mc_flags |= C_UNTRACK;
8568 mc.mc_next = txn->mt_cursors[dbi];
8569 txn->mt_cursors[dbi] = &mc;
8570 rc = mdb_cursor_del(&mc, flags);
8571 txn->mt_cursors[dbi] = mc.mc_next;
8572 }
8573 return rc;
8574 }
8575
8576 /** Split a page and insert a new node.
8577 * Set #MDB_TXN_ERROR on failure.
8578 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8579 * The cursor will be updated to point to the actual page and index where
8580 * the node got inserted after the split.
8581 * @param[in] newkey The key for the newly inserted node.
8582 * @param[in] newdata The data for the newly inserted node.
8583 * @param[in] newpgno The page number, if the new node is a branch node.
8584 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8585 * @return 0 on success, non-zero on failure.
8586 */
8587 static int
mdb_page_split(MDB_cursor * mc,MDB_val * newkey,MDB_val * newdata,pgno_t newpgno,unsigned int nflags)8588 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8589 unsigned int nflags)
8590 {
8591 unsigned int flags;
8592 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8593 indx_t newindx;
8594 pgno_t pgno = 0;
8595 int i, j, split_indx, nkeys, pmax;
8596 MDB_env *env = mc->mc_txn->mt_env;
8597 MDB_node *node;
8598 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8599 MDB_page *copy = NULL;
8600 MDB_page *mp, *rp, *pp;
8601 int ptop;
8602 MDB_cursor mn;
8603 DKBUF;
8604
8605 mp = mc->mc_pg[mc->mc_top];
8606 newindx = mc->mc_ki[mc->mc_top];
8607 nkeys = NUMKEYS(mp);
8608
8609 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8610 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8611 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8612
8613 /* Create a right sibling. */
8614 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8615 return rc;
8616 rp->mp_pad = mp->mp_pad;
8617 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8618
8619 /* Usually when splitting the root page, the cursor
8620 * height is 1. But when called from mdb_update_key,
8621 * the cursor height may be greater because it walks
8622 * up the stack while finding the branch slot to update.
8623 */
8624 if (mc->mc_top < 1) {
8625 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8626 goto done;
8627 /* shift current top to make room for new parent */
8628 for (i=mc->mc_snum; i>0; i--) {
8629 mc->mc_pg[i] = mc->mc_pg[i-1];
8630 mc->mc_ki[i] = mc->mc_ki[i-1];
8631 }
8632 mc->mc_pg[0] = pp;
8633 mc->mc_ki[0] = 0;
8634 mc->mc_db->md_root = pp->mp_pgno;
8635 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8636 new_root = mc->mc_db->md_depth++;
8637
8638 /* Add left (implicit) pointer. */
8639 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8640 /* undo the pre-push */
8641 mc->mc_pg[0] = mc->mc_pg[1];
8642 mc->mc_ki[0] = mc->mc_ki[1];
8643 mc->mc_db->md_root = mp->mp_pgno;
8644 mc->mc_db->md_depth--;
8645 goto done;
8646 }
8647 mc->mc_snum++;
8648 mc->mc_top++;
8649 ptop = 0;
8650 } else {
8651 ptop = mc->mc_top-1;
8652 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8653 }
8654
8655 mdb_cursor_copy(mc, &mn);
8656 mn.mc_xcursor = NULL;
8657 mn.mc_pg[mn.mc_top] = rp;
8658 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8659
8660 if (nflags & MDB_APPEND) {
8661 mn.mc_ki[mn.mc_top] = 0;
8662 sepkey = *newkey;
8663 split_indx = newindx;
8664 nkeys = 0;
8665 } else {
8666
8667 split_indx = (nkeys+1) / 2;
8668
8669 if (IS_LEAF2(rp)) {
8670 char *split, *ins;
8671 int x;
8672 unsigned int lsize, rsize, ksize;
8673 /* Move half of the keys to the right sibling */
8674 x = mc->mc_ki[mc->mc_top] - split_indx;
8675 ksize = mc->mc_db->md_pad;
8676 split = LEAF2KEY(mp, split_indx, ksize);
8677 rsize = (nkeys - split_indx) * ksize;
8678 lsize = (nkeys - split_indx) * sizeof(indx_t);
8679 mp->mp_lower -= lsize;
8680 rp->mp_lower += lsize;
8681 mp->mp_upper += rsize - lsize;
8682 rp->mp_upper -= rsize - lsize;
8683 sepkey.mv_size = ksize;
8684 if (newindx == split_indx) {
8685 sepkey.mv_data = newkey->mv_data;
8686 } else {
8687 sepkey.mv_data = split;
8688 }
8689 if (x<0) {
8690 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8691 memcpy(rp->mp_ptrs, split, rsize);
8692 sepkey.mv_data = rp->mp_ptrs;
8693 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8694 memcpy(ins, newkey->mv_data, ksize);
8695 mp->mp_lower += sizeof(indx_t);
8696 mp->mp_upper -= ksize - sizeof(indx_t);
8697 } else {
8698 if (x)
8699 memcpy(rp->mp_ptrs, split, x * ksize);
8700 ins = LEAF2KEY(rp, x, ksize);
8701 memcpy(ins, newkey->mv_data, ksize);
8702 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8703 rp->mp_lower += sizeof(indx_t);
8704 rp->mp_upper -= ksize - sizeof(indx_t);
8705 mc->mc_ki[mc->mc_top] = x;
8706 }
8707 } else {
8708 int psize, nsize, k;
8709 /* Maximum free space in an empty page */
8710 pmax = env->me_psize - PAGEHDRSZ;
8711 if (IS_LEAF(mp))
8712 nsize = mdb_leaf_size(env, newkey, newdata);
8713 else
8714 nsize = mdb_branch_size(env, newkey);
8715 nsize = EVEN(nsize);
8716
8717 /* grab a page to hold a temporary copy */
8718 copy = mdb_page_malloc(mc->mc_txn, 1);
8719 if (copy == NULL) {
8720 rc = ENOMEM;
8721 goto done;
8722 }
8723 copy->mp_pgno = mp->mp_pgno;
8724 copy->mp_flags = mp->mp_flags;
8725 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8726 copy->mp_upper = env->me_psize - PAGEBASE;
8727
8728 /* prepare to insert */
8729 for (i=0, j=0; i<nkeys; i++) {
8730 if (i == newindx) {
8731 copy->mp_ptrs[j++] = 0;
8732 }
8733 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8734 }
8735
8736 /* When items are relatively large the split point needs
8737 * to be checked, because being off-by-one will make the
8738 * difference between success or failure in mdb_node_add.
8739 *
8740 * It's also relevant if a page happens to be laid out
8741 * such that one half of its nodes are all "small" and
8742 * the other half of its nodes are "large." If the new
8743 * item is also "large" and falls on the half with
8744 * "large" nodes, it also may not fit.
8745 *
8746 * As a final tweak, if the new item goes on the last
8747 * spot on the page (and thus, onto the new page), bias
8748 * the split so the new page is emptier than the old page.
8749 * This yields better packing during sequential inserts.
8750 */
8751 if (nkeys < 32 || nsize > pmax/16 || newindx >= nkeys) {
8752 /* Find split point */
8753 psize = 0;
8754 if (newindx <= split_indx || newindx >= nkeys) {
8755 i = 0; j = 1;
8756 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8757 } else {
8758 i = nkeys; j = -1;
8759 k = split_indx-1;
8760 }
8761 for (; i!=k; i+=j) {
8762 if (i == newindx) {
8763 psize += nsize;
8764 node = NULL;
8765 } else {
8766 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8767 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8768 if (IS_LEAF(mp)) {
8769 if (F_ISSET(node->mn_flags, F_BIGDATA))
8770 psize += sizeof(pgno_t);
8771 else
8772 psize += NODEDSZ(node);
8773 }
8774 psize = EVEN(psize);
8775 }
8776 if (psize > pmax || i == k-j) {
8777 split_indx = i + (j<0);
8778 break;
8779 }
8780 }
8781 }
8782 if (split_indx == newindx) {
8783 sepkey.mv_size = newkey->mv_size;
8784 sepkey.mv_data = newkey->mv_data;
8785 } else {
8786 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8787 sepkey.mv_size = node->mn_ksize;
8788 sepkey.mv_data = NODEKEY(node);
8789 }
8790 }
8791 }
8792
8793 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8794
8795 /* Copy separator key to the parent.
8796 */
8797 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8798 int snum = mc->mc_snum;
8799 mn.mc_snum--;
8800 mn.mc_top--;
8801 did_split = 1;
8802 /* We want other splits to find mn when doing fixups */
8803 WITH_CURSOR_TRACKING(mn,
8804 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8805 if (rc)
8806 goto done;
8807
8808 /* root split? */
8809 if (mc->mc_snum > snum) {
8810 ptop++;
8811 }
8812 /* Right page might now have changed parent.
8813 * Check if left page also changed parent.
8814 */
8815 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8816 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8817 for (i=0; i<ptop; i++) {
8818 mc->mc_pg[i] = mn.mc_pg[i];
8819 mc->mc_ki[i] = mn.mc_ki[i];
8820 }
8821 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8822 if (mn.mc_ki[ptop]) {
8823 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8824 } else {
8825 /* find right page's left sibling */
8826 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8827 mdb_cursor_sibling(mc, 0);
8828 }
8829 }
8830 } else {
8831 mn.mc_top--;
8832 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8833 mn.mc_top++;
8834 }
8835 if (rc != MDB_SUCCESS) {
8836 goto done;
8837 }
8838 if (nflags & MDB_APPEND) {
8839 mc->mc_pg[mc->mc_top] = rp;
8840 mc->mc_ki[mc->mc_top] = 0;
8841 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8842 if (rc)
8843 goto done;
8844 for (i=0; i<mc->mc_top; i++)
8845 mc->mc_ki[i] = mn.mc_ki[i];
8846 } else if (!IS_LEAF2(mp)) {
8847 /* Move nodes */
8848 mc->mc_pg[mc->mc_top] = rp;
8849 i = split_indx;
8850 j = 0;
8851 do {
8852 if (i == newindx) {
8853 rkey.mv_data = newkey->mv_data;
8854 rkey.mv_size = newkey->mv_size;
8855 if (IS_LEAF(mp)) {
8856 rdata = newdata;
8857 } else
8858 pgno = newpgno;
8859 flags = nflags;
8860 /* Update index for the new key. */
8861 mc->mc_ki[mc->mc_top] = j;
8862 } else {
8863 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8864 rkey.mv_data = NODEKEY(node);
8865 rkey.mv_size = node->mn_ksize;
8866 if (IS_LEAF(mp)) {
8867 xdata.mv_data = NODEDATA(node);
8868 xdata.mv_size = NODEDSZ(node);
8869 rdata = &xdata;
8870 } else
8871 pgno = NODEPGNO(node);
8872 flags = node->mn_flags;
8873 }
8874
8875 if (!IS_LEAF(mp) && j == 0) {
8876 /* First branch index doesn't need key data. */
8877 rkey.mv_size = 0;
8878 }
8879
8880 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8881 if (rc)
8882 goto done;
8883 if (i == nkeys) {
8884 i = 0;
8885 j = 0;
8886 mc->mc_pg[mc->mc_top] = copy;
8887 } else {
8888 i++;
8889 j++;
8890 }
8891 } while (i != split_indx);
8892
8893 nkeys = NUMKEYS(copy);
8894 for (i=0; i<nkeys; i++)
8895 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8896 mp->mp_lower = copy->mp_lower;
8897 mp->mp_upper = copy->mp_upper;
8898 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8899 env->me_psize - copy->mp_upper - PAGEBASE);
8900
8901 /* reset back to original page */
8902 if (newindx < split_indx) {
8903 mc->mc_pg[mc->mc_top] = mp;
8904 } else {
8905 mc->mc_pg[mc->mc_top] = rp;
8906 mc->mc_ki[ptop]++;
8907 /* Make sure mc_ki is still valid.
8908 */
8909 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8910 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8911 for (i=0; i<=ptop; i++) {
8912 mc->mc_pg[i] = mn.mc_pg[i];
8913 mc->mc_ki[i] = mn.mc_ki[i];
8914 }
8915 }
8916 }
8917 if (nflags & MDB_RESERVE) {
8918 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8919 if (!(node->mn_flags & F_BIGDATA))
8920 newdata->mv_data = NODEDATA(node);
8921 }
8922 } else {
8923 if (newindx >= split_indx) {
8924 mc->mc_pg[mc->mc_top] = rp;
8925 mc->mc_ki[ptop]++;
8926 /* Make sure mc_ki is still valid.
8927 */
8928 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8929 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8930 for (i=0; i<=ptop; i++) {
8931 mc->mc_pg[i] = mn.mc_pg[i];
8932 mc->mc_ki[i] = mn.mc_ki[i];
8933 }
8934 }
8935 }
8936 }
8937
8938 {
8939 /* Adjust other cursors pointing to mp */
8940 MDB_cursor *m2, *m3;
8941 MDB_dbi dbi = mc->mc_dbi;
8942 nkeys = NUMKEYS(mp);
8943
8944 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8945 if (mc->mc_flags & C_SUB)
8946 m3 = &m2->mc_xcursor->mx_cursor;
8947 else
8948 m3 = m2;
8949 if (m3 == mc)
8950 continue;
8951 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8952 continue;
8953 if (new_root) {
8954 int k;
8955 /* sub cursors may be on different DB */
8956 if (m3->mc_pg[0] != mp)
8957 continue;
8958 /* root split */
8959 for (k=new_root; k>=0; k--) {
8960 m3->mc_ki[k+1] = m3->mc_ki[k];
8961 m3->mc_pg[k+1] = m3->mc_pg[k];
8962 }
8963 if (m3->mc_ki[0] >= nkeys) {
8964 m3->mc_ki[0] = 1;
8965 } else {
8966 m3->mc_ki[0] = 0;
8967 }
8968 m3->mc_pg[0] = mc->mc_pg[0];
8969 m3->mc_snum++;
8970 m3->mc_top++;
8971 }
8972 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8973 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8974 m3->mc_ki[mc->mc_top]++;
8975 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8976 m3->mc_pg[mc->mc_top] = rp;
8977 m3->mc_ki[mc->mc_top] -= nkeys;
8978 for (i=0; i<mc->mc_top; i++) {
8979 m3->mc_ki[i] = mn.mc_ki[i];
8980 m3->mc_pg[i] = mn.mc_pg[i];
8981 }
8982 }
8983 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8984 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8985 m3->mc_ki[ptop]++;
8986 }
8987 if (IS_LEAF(mp))
8988 XCURSOR_REFRESH(m3, mc->mc_top, m3->mc_pg[mc->mc_top]);
8989 }
8990 }
8991 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8992
8993 done:
8994 if (copy) /* tmp page */
8995 mdb_page_free(env, copy);
8996 if (rc)
8997 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8998 return rc;
8999 }
9000
9001 int
mdb_put(MDB_txn * txn,MDB_dbi dbi,MDB_val * key,MDB_val * data,unsigned int flags)9002 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9003 MDB_val *key, MDB_val *data, unsigned int flags)
9004 {
9005 MDB_cursor mc;
9006 MDB_xcursor mx;
9007 int rc;
9008
9009 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9010 return EINVAL;
9011
9012 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9013 return EINVAL;
9014
9015 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9016 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9017
9018 mdb_cursor_init(&mc, txn, dbi, &mx);
9019 mc.mc_next = txn->mt_cursors[dbi];
9020 txn->mt_cursors[dbi] = &mc;
9021 rc = mdb_cursor_put(&mc, key, data, flags);
9022 txn->mt_cursors[dbi] = mc.mc_next;
9023 return rc;
9024 }
9025
9026 #ifndef MDB_WBUF
9027 #define MDB_WBUF (1024*1024)
9028 #endif
9029 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9030
9031 /** State needed for a double-buffering compacting copy. */
9032 typedef struct mdb_copy {
9033 MDB_env *mc_env;
9034 MDB_txn *mc_txn;
9035 pthread_mutex_t mc_mutex;
9036 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9037 char *mc_wbuf[2];
9038 char *mc_over[2];
9039 int mc_wlen[2];
9040 int mc_olen[2];
9041 pgno_t mc_next_pgno;
9042 HANDLE mc_fd;
9043 int mc_toggle; /**< Buffer number in provider */
9044 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9045 /** Error code. Never cleared if set. Both threads can set nonzero
9046 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
9047 */
9048 volatile int mc_error;
9049 } mdb_copy;
9050
9051 /** Dedicated writer thread for compacting copy. */
9052 static THREAD_RET ESECT CALL_CONV
mdb_env_copythr(void * arg)9053 mdb_env_copythr(void *arg)
9054 {
9055 mdb_copy *my = arg;
9056 char *ptr;
9057 int toggle = 0, wsize, rc;
9058 #ifdef _WIN32
9059 DWORD len;
9060 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9061 #else
9062 int len;
9063 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9064 #ifdef SIGPIPE
9065 sigset_t set;
9066 sigemptyset(&set);
9067 sigaddset(&set, SIGPIPE);
9068 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9069 my->mc_error = rc;
9070 #endif
9071 #endif
9072
9073 pthread_mutex_lock(&my->mc_mutex);
9074 for(;;) {
9075 while (!my->mc_new)
9076 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9077 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9078 break;
9079 wsize = my->mc_wlen[toggle];
9080 ptr = my->mc_wbuf[toggle];
9081 again:
9082 rc = MDB_SUCCESS;
9083 while (wsize > 0 && !my->mc_error) {
9084 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9085 if (!rc) {
9086 rc = ErrCode();
9087 #if defined(SIGPIPE) && !defined(_WIN32)
9088 if (rc == EPIPE) {
9089 /* Collect the pending SIGPIPE, otherwise at least OS X
9090 * gives it to the process on thread-exit (ITS#8504).
9091 */
9092 int tmp;
9093 sigwait(&set, &tmp);
9094 }
9095 #endif
9096 break;
9097 } else if (len > 0) {
9098 rc = MDB_SUCCESS;
9099 ptr += len;
9100 wsize -= len;
9101 continue;
9102 } else {
9103 rc = EIO;
9104 break;
9105 }
9106 }
9107 if (rc) {
9108 my->mc_error = rc;
9109 }
9110 /* If there's an overflow page tail, write it too */
9111 if (my->mc_olen[toggle]) {
9112 wsize = my->mc_olen[toggle];
9113 ptr = my->mc_over[toggle];
9114 my->mc_olen[toggle] = 0;
9115 goto again;
9116 }
9117 my->mc_wlen[toggle] = 0;
9118 toggle ^= 1;
9119 /* Return the empty buffer to provider */
9120 my->mc_new--;
9121 pthread_cond_signal(&my->mc_cond);
9122 }
9123 pthread_mutex_unlock(&my->mc_mutex);
9124 return (THREAD_RET)0;
9125 #undef DO_WRITE
9126 }
9127
9128 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9129 *
9130 * @param[in] my control structure.
9131 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9132 */
9133 static int ESECT
mdb_env_cthr_toggle(mdb_copy * my,int adjust)9134 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9135 {
9136 pthread_mutex_lock(&my->mc_mutex);
9137 my->mc_new += adjust;
9138 pthread_cond_signal(&my->mc_cond);
9139 while (my->mc_new & 2) /* both buffers in use */
9140 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9141 pthread_mutex_unlock(&my->mc_mutex);
9142
9143 my->mc_toggle ^= (adjust & 1);
9144 /* Both threads reset mc_wlen, to be safe from threading errors */
9145 my->mc_wlen[my->mc_toggle] = 0;
9146 return my->mc_error;
9147 }
9148
9149 /** Depth-first tree traversal for compacting copy.
9150 * @param[in] my control structure.
9151 * @param[in,out] pg database root.
9152 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9153 */
9154 static int ESECT
mdb_env_cwalk(mdb_copy * my,pgno_t * pg,int flags)9155 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9156 {
9157 MDB_cursor mc = {0};
9158 MDB_node *ni;
9159 MDB_page *mo, *mp, *leaf;
9160 char *buf, *ptr;
9161 int rc, toggle;
9162 unsigned int i;
9163
9164 /* Empty DB, nothing to do */
9165 if (*pg == P_INVALID)
9166 return MDB_SUCCESS;
9167
9168 mc.mc_snum = 1;
9169 mc.mc_txn = my->mc_txn;
9170
9171 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9172 if (rc)
9173 return rc;
9174 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9175 if (rc)
9176 return rc;
9177
9178 /* Make cursor pages writable */
9179 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9180 if (buf == NULL)
9181 return ENOMEM;
9182
9183 for (i=0; i<mc.mc_top; i++) {
9184 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9185 mc.mc_pg[i] = (MDB_page *)ptr;
9186 ptr += my->mc_env->me_psize;
9187 }
9188
9189 /* This is writable space for a leaf page. Usually not needed. */
9190 leaf = (MDB_page *)ptr;
9191
9192 toggle = my->mc_toggle;
9193 while (mc.mc_snum > 0) {
9194 unsigned n;
9195 mp = mc.mc_pg[mc.mc_top];
9196 n = NUMKEYS(mp);
9197
9198 if (IS_LEAF(mp)) {
9199 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9200 for (i=0; i<n; i++) {
9201 ni = NODEPTR(mp, i);
9202 if (ni->mn_flags & F_BIGDATA) {
9203 MDB_page *omp;
9204 pgno_t pg;
9205
9206 /* Need writable leaf */
9207 if (mp != leaf) {
9208 mc.mc_pg[mc.mc_top] = leaf;
9209 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9210 mp = leaf;
9211 ni = NODEPTR(mp, i);
9212 }
9213
9214 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9215 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9216 rc = mdb_page_get(&mc, pg, &omp, NULL);
9217 if (rc)
9218 goto done;
9219 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9220 rc = mdb_env_cthr_toggle(my, 1);
9221 if (rc)
9222 goto done;
9223 toggle = my->mc_toggle;
9224 }
9225 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9226 memcpy(mo, omp, my->mc_env->me_psize);
9227 mo->mp_pgno = my->mc_next_pgno;
9228 my->mc_next_pgno += omp->mp_pages;
9229 my->mc_wlen[toggle] += my->mc_env->me_psize;
9230 if (omp->mp_pages > 1) {
9231 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9232 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9233 rc = mdb_env_cthr_toggle(my, 1);
9234 if (rc)
9235 goto done;
9236 toggle = my->mc_toggle;
9237 }
9238 } else if (ni->mn_flags & F_SUBDATA) {
9239 MDB_db db;
9240
9241 /* Need writable leaf */
9242 if (mp != leaf) {
9243 mc.mc_pg[mc.mc_top] = leaf;
9244 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9245 mp = leaf;
9246 ni = NODEPTR(mp, i);
9247 }
9248
9249 memcpy(&db, NODEDATA(ni), sizeof(db));
9250 my->mc_toggle = toggle;
9251 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9252 if (rc)
9253 goto done;
9254 toggle = my->mc_toggle;
9255 memcpy(NODEDATA(ni), &db, sizeof(db));
9256 }
9257 }
9258 }
9259 } else {
9260 mc.mc_ki[mc.mc_top]++;
9261 if (mc.mc_ki[mc.mc_top] < n) {
9262 pgno_t pg;
9263 again:
9264 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9265 pg = NODEPGNO(ni);
9266 rc = mdb_page_get(&mc, pg, &mp, NULL);
9267 if (rc)
9268 goto done;
9269 mc.mc_top++;
9270 mc.mc_snum++;
9271 mc.mc_ki[mc.mc_top] = 0;
9272 if (IS_BRANCH(mp)) {
9273 /* Whenever we advance to a sibling branch page,
9274 * we must proceed all the way down to its first leaf.
9275 */
9276 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9277 goto again;
9278 } else
9279 mc.mc_pg[mc.mc_top] = mp;
9280 continue;
9281 }
9282 }
9283 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9284 rc = mdb_env_cthr_toggle(my, 1);
9285 if (rc)
9286 goto done;
9287 toggle = my->mc_toggle;
9288 }
9289 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9290 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9291 mo->mp_pgno = my->mc_next_pgno++;
9292 my->mc_wlen[toggle] += my->mc_env->me_psize;
9293 if (mc.mc_top) {
9294 /* Update parent if there is one */
9295 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9296 SETPGNO(ni, mo->mp_pgno);
9297 mdb_cursor_pop(&mc);
9298 } else {
9299 /* Otherwise we're done */
9300 *pg = mo->mp_pgno;
9301 break;
9302 }
9303 }
9304 done:
9305 free(buf);
9306 return rc;
9307 }
9308
9309 /** Copy environment with compaction. */
9310 static int ESECT
mdb_env_copyfd1(MDB_env * env,HANDLE fd)9311 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9312 {
9313 MDB_meta *mm;
9314 MDB_page *mp;
9315 mdb_copy my = {0};
9316 MDB_txn *txn = NULL;
9317 pthread_t thr;
9318 pgno_t root, new_root;
9319 int rc = MDB_SUCCESS;
9320
9321 #ifdef _WIN32
9322 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9323 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9324 rc = ErrCode();
9325 goto done;
9326 }
9327 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9328 if (my.mc_wbuf[0] == NULL) {
9329 /* _aligned_malloc() sets errno, but we use Windows error codes */
9330 rc = ERROR_NOT_ENOUGH_MEMORY;
9331 goto done;
9332 }
9333 #else
9334 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
9335 return rc;
9336 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
9337 goto done2;
9338 #ifdef HAVE_MEMALIGN
9339 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9340 if (my.mc_wbuf[0] == NULL) {
9341 rc = errno;
9342 goto done;
9343 }
9344 #else
9345 {
9346 void *p;
9347 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
9348 goto done;
9349 my.mc_wbuf[0] = p;
9350 }
9351 #endif
9352 #endif
9353 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9354 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9355 my.mc_next_pgno = NUM_METAS;
9356 my.mc_env = env;
9357 my.mc_fd = fd;
9358 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9359 if (rc)
9360 goto done;
9361
9362 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9363 if (rc)
9364 goto finish;
9365
9366 mp = (MDB_page *)my.mc_wbuf[0];
9367 memset(mp, 0, NUM_METAS * env->me_psize);
9368 mp->mp_pgno = 0;
9369 mp->mp_flags = P_META;
9370 mm = (MDB_meta *)METADATA(mp);
9371 mdb_env_init_meta0(env, mm);
9372 mm->mm_address = env->me_metas[0]->mm_address;
9373
9374 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9375 mp->mp_pgno = 1;
9376 mp->mp_flags = P_META;
9377 *(MDB_meta *)METADATA(mp) = *mm;
9378 mm = (MDB_meta *)METADATA(mp);
9379
9380 /* Set metapage 1 with current main DB */
9381 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9382 if (root != P_INVALID) {
9383 /* Count free pages + freeDB pages. Subtract from last_pg
9384 * to find the new last_pg, which also becomes the new root.
9385 */
9386 MDB_ID freecount = 0;
9387 MDB_cursor mc;
9388 MDB_val key, data;
9389 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9390 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9391 freecount += *(MDB_ID *)data.mv_data;
9392 if (rc != MDB_NOTFOUND)
9393 goto finish;
9394 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9395 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9396 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9397
9398 new_root = txn->mt_next_pgno - 1 - freecount;
9399 mm->mm_last_pg = new_root;
9400 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9401 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9402 } else {
9403 /* When the DB is empty, handle it specially to
9404 * fix any breakage like page leaks from ITS#8174.
9405 */
9406 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9407 }
9408 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9409 mm->mm_txnid = 1; /* use metapage 1 */
9410 }
9411
9412 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9413 my.mc_txn = txn;
9414 rc = mdb_env_cwalk(&my, &root, 0);
9415 if (rc == MDB_SUCCESS && root != new_root) {
9416 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
9417 }
9418
9419 finish:
9420 if (rc)
9421 my.mc_error = rc;
9422 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
9423 rc = THREAD_FINISH(thr);
9424 mdb_txn_abort(txn);
9425
9426 done:
9427 #ifdef _WIN32
9428 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
9429 if (my.mc_cond) CloseHandle(my.mc_cond);
9430 if (my.mc_mutex) CloseHandle(my.mc_mutex);
9431 #else
9432 free(my.mc_wbuf[0]);
9433 pthread_cond_destroy(&my.mc_cond);
9434 done2:
9435 pthread_mutex_destroy(&my.mc_mutex);
9436 #endif
9437 return rc ? rc : my.mc_error;
9438 }
9439
9440 /** Copy environment as-is. */
9441 static int ESECT
mdb_env_copyfd0(MDB_env * env,HANDLE fd)9442 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9443 {
9444 MDB_txn *txn = NULL;
9445 mdb_mutexref_t wmutex = NULL;
9446 int rc;
9447 size_t wsize, w3;
9448 char *ptr;
9449 #ifdef _WIN32
9450 DWORD len, w2;
9451 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9452 #else
9453 ssize_t len;
9454 size_t w2;
9455 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9456 #endif
9457
9458 /* Do the lock/unlock of the reader mutex before starting the
9459 * write txn. Otherwise other read txns could block writers.
9460 */
9461 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9462 if (rc)
9463 return rc;
9464
9465 if (env->me_txns) {
9466 /* We must start the actual read txn after blocking writers */
9467 mdb_txn_end(txn, MDB_END_RESET_TMP);
9468
9469 /* Temporarily block writers until we snapshot the meta pages */
9470 wmutex = env->me_wmutex;
9471 if (LOCK_MUTEX(rc, env, wmutex))
9472 goto leave;
9473
9474 rc = mdb_txn_renew0(txn);
9475 if (rc) {
9476 UNLOCK_MUTEX(wmutex);
9477 goto leave;
9478 }
9479 }
9480
9481 wsize = env->me_psize * NUM_METAS;
9482 ptr = env->me_map;
9483 w2 = wsize;
9484 while (w2 > 0) {
9485 DO_WRITE(rc, fd, ptr, w2, len);
9486 if (!rc) {
9487 rc = ErrCode();
9488 break;
9489 } else if (len > 0) {
9490 rc = MDB_SUCCESS;
9491 ptr += len;
9492 w2 -= len;
9493 continue;
9494 } else {
9495 /* Non-blocking or async handles are not supported */
9496 rc = EIO;
9497 break;
9498 }
9499 }
9500 if (wmutex)
9501 UNLOCK_MUTEX(wmutex);
9502
9503 if (rc)
9504 goto leave;
9505
9506 w3 = txn->mt_next_pgno * env->me_psize;
9507 {
9508 size_t fsize = 0;
9509 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9510 goto leave;
9511 if (w3 > fsize)
9512 w3 = fsize;
9513 }
9514 wsize = w3 - wsize;
9515 while (wsize > 0) {
9516 if (wsize > MAX_WRITE)
9517 w2 = MAX_WRITE;
9518 else
9519 w2 = wsize;
9520 DO_WRITE(rc, fd, ptr, w2, len);
9521 if (!rc) {
9522 rc = ErrCode();
9523 break;
9524 } else if (len > 0) {
9525 rc = MDB_SUCCESS;
9526 ptr += len;
9527 wsize -= len;
9528 continue;
9529 } else {
9530 rc = EIO;
9531 break;
9532 }
9533 }
9534
9535 leave:
9536 mdb_txn_abort(txn);
9537 return rc;
9538 }
9539
9540 int ESECT
mdb_env_copyfd2(MDB_env * env,HANDLE fd,unsigned int flags)9541 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9542 {
9543 if (flags & MDB_CP_COMPACT)
9544 return mdb_env_copyfd1(env, fd);
9545 else
9546 return mdb_env_copyfd0(env, fd);
9547 }
9548
9549 int ESECT
mdb_env_copyfd(MDB_env * env,HANDLE fd)9550 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9551 {
9552 return mdb_env_copyfd2(env, fd, 0);
9553 }
9554
9555 int ESECT
mdb_env_copy2(MDB_env * env,const char * path,unsigned int flags)9556 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9557 {
9558 int rc;
9559 MDB_name fname;
9560 HANDLE newfd = INVALID_HANDLE_VALUE;
9561
9562 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
9563 if (rc == MDB_SUCCESS) {
9564 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
9565 mdb_fname_destroy(fname);
9566 }
9567 if (rc == MDB_SUCCESS) {
9568 rc = mdb_env_copyfd2(env, newfd, flags);
9569 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9570 rc = ErrCode();
9571 }
9572 return rc;
9573 }
9574
9575 int ESECT
mdb_env_copy(MDB_env * env,const char * path)9576 mdb_env_copy(MDB_env *env, const char *path)
9577 {
9578 return mdb_env_copy2(env, path, 0);
9579 }
9580
9581 int ESECT
mdb_env_set_flags(MDB_env * env,unsigned int flag,int onoff)9582 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9583 {
9584 if (flag & ~CHANGEABLE)
9585 return EINVAL;
9586 if (onoff)
9587 env->me_flags |= flag;
9588 else
9589 env->me_flags &= ~flag;
9590 return MDB_SUCCESS;
9591 }
9592
9593 int ESECT
mdb_env_get_flags(MDB_env * env,unsigned int * arg)9594 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9595 {
9596 if (!env || !arg)
9597 return EINVAL;
9598
9599 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9600 return MDB_SUCCESS;
9601 }
9602
9603 int ESECT
mdb_env_set_userctx(MDB_env * env,void * ctx)9604 mdb_env_set_userctx(MDB_env *env, void *ctx)
9605 {
9606 if (!env)
9607 return EINVAL;
9608 env->me_userctx = ctx;
9609 return MDB_SUCCESS;
9610 }
9611
9612 void * ESECT
mdb_env_get_userctx(MDB_env * env)9613 mdb_env_get_userctx(MDB_env *env)
9614 {
9615 return env ? env->me_userctx : NULL;
9616 }
9617
9618 int ESECT
mdb_env_set_assert(MDB_env * env,MDB_assert_func * func)9619 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9620 {
9621 if (!env)
9622 return EINVAL;
9623 #ifndef NDEBUG
9624 env->me_assert_func = func;
9625 #endif
9626 return MDB_SUCCESS;
9627 }
9628
9629 int ESECT
mdb_env_get_path(MDB_env * env,const char ** arg)9630 mdb_env_get_path(MDB_env *env, const char **arg)
9631 {
9632 if (!env || !arg)
9633 return EINVAL;
9634
9635 *arg = env->me_path;
9636 return MDB_SUCCESS;
9637 }
9638
9639 int ESECT
mdb_env_get_fd(MDB_env * env,mdb_filehandle_t * arg)9640 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9641 {
9642 if (!env || !arg)
9643 return EINVAL;
9644
9645 *arg = env->me_fd;
9646 return MDB_SUCCESS;
9647 }
9648
9649 /** Common code for #mdb_stat() and #mdb_env_stat().
9650 * @param[in] env the environment to operate in.
9651 * @param[in] db the #MDB_db record containing the stats to return.
9652 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9653 * @return 0, this function always succeeds.
9654 */
9655 static int ESECT
mdb_stat0(MDB_env * env,MDB_db * db,MDB_stat * arg)9656 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9657 {
9658 arg->ms_psize = env->me_psize;
9659 arg->ms_depth = db->md_depth;
9660 arg->ms_branch_pages = db->md_branch_pages;
9661 arg->ms_leaf_pages = db->md_leaf_pages;
9662 arg->ms_overflow_pages = db->md_overflow_pages;
9663 arg->ms_entries = db->md_entries;
9664
9665 return MDB_SUCCESS;
9666 }
9667
9668 int ESECT
mdb_env_stat(MDB_env * env,MDB_stat * arg)9669 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9670 {
9671 MDB_meta *meta;
9672
9673 if (env == NULL || arg == NULL)
9674 return EINVAL;
9675
9676 meta = mdb_env_pick_meta(env);
9677
9678 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9679 }
9680
9681 int ESECT
mdb_env_info(MDB_env * env,MDB_envinfo * arg)9682 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9683 {
9684 MDB_meta *meta;
9685
9686 if (env == NULL || arg == NULL)
9687 return EINVAL;
9688
9689 meta = mdb_env_pick_meta(env);
9690 arg->me_mapaddr = meta->mm_address;
9691 arg->me_last_pgno = meta->mm_last_pg;
9692 arg->me_last_txnid = meta->mm_txnid;
9693
9694 arg->me_mapsize = env->me_mapsize;
9695 arg->me_maxreaders = env->me_maxreaders;
9696 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9697 return MDB_SUCCESS;
9698 }
9699
9700 /** Set the default comparison functions for a database.
9701 * Called immediately after a database is opened to set the defaults.
9702 * The user can then override them with #mdb_set_compare() or
9703 * #mdb_set_dupsort().
9704 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9705 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9706 */
9707 static void
mdb_default_cmp(MDB_txn * txn,MDB_dbi dbi)9708 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9709 {
9710 uint16_t f = txn->mt_dbs[dbi].md_flags;
9711
9712 txn->mt_dbxs[dbi].md_cmp =
9713 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9714 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9715
9716 txn->mt_dbxs[dbi].md_dcmp =
9717 !(f & MDB_DUPSORT) ? 0 :
9718 ((f & MDB_INTEGERDUP)
9719 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9720 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9721 }
9722
mdb_dbi_open(MDB_txn * txn,const char * name,unsigned int flags,MDB_dbi * dbi)9723 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9724 {
9725 MDB_val key, data;
9726 MDB_dbi i;
9727 MDB_cursor mc;
9728 MDB_db dummy;
9729 int rc, dbflag, exact;
9730 unsigned int unused = 0, seq;
9731 char *namedup;
9732 size_t len;
9733
9734 if (flags & ~VALID_FLAGS)
9735 return EINVAL;
9736 if (txn->mt_flags & MDB_TXN_BLOCKED)
9737 return MDB_BAD_TXN;
9738
9739 /* main DB? */
9740 if (!name) {
9741 *dbi = MAIN_DBI;
9742 if (flags & PERSISTENT_FLAGS) {
9743 uint16_t f2 = flags & PERSISTENT_FLAGS;
9744 /* make sure flag changes get committed */
9745 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9746 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9747 txn->mt_flags |= MDB_TXN_DIRTY;
9748 }
9749 }
9750 mdb_default_cmp(txn, MAIN_DBI);
9751 return MDB_SUCCESS;
9752 }
9753
9754 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9755 mdb_default_cmp(txn, MAIN_DBI);
9756 }
9757
9758 /* Is the DB already open? */
9759 len = strlen(name);
9760 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9761 if (!txn->mt_dbxs[i].md_name.mv_size) {
9762 /* Remember this free slot */
9763 if (!unused) unused = i;
9764 continue;
9765 }
9766 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9767 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9768 *dbi = i;
9769 return MDB_SUCCESS;
9770 }
9771 }
9772
9773 /* If no free slot and max hit, fail */
9774 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9775 return MDB_DBS_FULL;
9776
9777 /* Cannot mix named databases with some mainDB flags */
9778 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9779 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9780
9781 /* Find the DB info */
9782 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9783 exact = 0;
9784 key.mv_size = len;
9785 key.mv_data = (void *)name;
9786 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9787 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9788 if (rc == MDB_SUCCESS) {
9789 /* make sure this is actually a DB */
9790 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9791 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9792 return MDB_INCOMPATIBLE;
9793 } else {
9794 if (rc != MDB_NOTFOUND || !(flags & MDB_CREATE))
9795 return rc;
9796 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9797 return EACCES;
9798 }
9799
9800 /* Done here so we cannot fail after creating a new DB */
9801 if ((namedup = strdup(name)) == NULL)
9802 return ENOMEM;
9803
9804 if (rc) {
9805 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
9806 data.mv_size = sizeof(MDB_db);
9807 data.mv_data = &dummy;
9808 memset(&dummy, 0, sizeof(dummy));
9809 dummy.md_root = P_INVALID;
9810 dummy.md_flags = flags & PERSISTENT_FLAGS;
9811 WITH_CURSOR_TRACKING(mc,
9812 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
9813 dbflag |= DB_DIRTY;
9814 }
9815
9816 if (rc) {
9817 free(namedup);
9818 } else {
9819 /* Got info, register DBI in this txn */
9820 unsigned int slot = unused ? unused : txn->mt_numdbs;
9821 txn->mt_dbxs[slot].md_name.mv_data = namedup;
9822 txn->mt_dbxs[slot].md_name.mv_size = len;
9823 txn->mt_dbxs[slot].md_rel = NULL;
9824 txn->mt_dbflags[slot] = dbflag;
9825 /* txn-> and env-> are the same in read txns, use
9826 * tmp variable to avoid undefined assignment
9827 */
9828 seq = ++txn->mt_env->me_dbiseqs[slot];
9829 txn->mt_dbiseqs[slot] = seq;
9830
9831 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9832 *dbi = slot;
9833 mdb_default_cmp(txn, slot);
9834 if (!unused) {
9835 txn->mt_numdbs++;
9836 }
9837 }
9838
9839 return rc;
9840 }
9841
9842 int ESECT
mdb_stat(MDB_txn * txn,MDB_dbi dbi,MDB_stat * arg)9843 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9844 {
9845 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9846 return EINVAL;
9847
9848 if (txn->mt_flags & MDB_TXN_BLOCKED)
9849 return MDB_BAD_TXN;
9850
9851 if (txn->mt_dbflags[dbi] & DB_STALE) {
9852 MDB_cursor mc;
9853 MDB_xcursor mx;
9854 /* Stale, must read the DB's root. cursor_init does it for us. */
9855 mdb_cursor_init(&mc, txn, dbi, &mx);
9856 }
9857 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9858 }
9859
mdb_dbi_close(MDB_env * env,MDB_dbi dbi)9860 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9861 {
9862 char *ptr;
9863 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9864 return;
9865 ptr = env->me_dbxs[dbi].md_name.mv_data;
9866 /* If there was no name, this was already closed */
9867 if (ptr) {
9868 env->me_dbxs[dbi].md_name.mv_data = NULL;
9869 env->me_dbxs[dbi].md_name.mv_size = 0;
9870 env->me_dbflags[dbi] = 0;
9871 env->me_dbiseqs[dbi]++;
9872 free(ptr);
9873 }
9874 }
9875
mdb_dbi_flags(MDB_txn * txn,MDB_dbi dbi,unsigned int * flags)9876 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9877 {
9878 /* We could return the flags for the FREE_DBI too but what's the point? */
9879 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9880 return EINVAL;
9881 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9882 return MDB_SUCCESS;
9883 }
9884
9885 /** Add all the DB's pages to the free list.
9886 * @param[in] mc Cursor on the DB to free.
9887 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9888 * @return 0 on success, non-zero on failure.
9889 */
9890 static int
mdb_drop0(MDB_cursor * mc,int subs)9891 mdb_drop0(MDB_cursor *mc, int subs)
9892 {
9893 int rc;
9894
9895 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9896 if (rc == MDB_SUCCESS) {
9897 MDB_txn *txn = mc->mc_txn;
9898 MDB_node *ni;
9899 MDB_cursor mx;
9900 unsigned int i;
9901
9902 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9903 * This also avoids any P_LEAF2 pages, which have no nodes.
9904 * Also if the DB doesn't have sub-DBs and has no overflow
9905 * pages, omit scanning leaves.
9906 */
9907 if ((mc->mc_flags & C_SUB) ||
9908 (!subs && !mc->mc_db->md_overflow_pages))
9909 mdb_cursor_pop(mc);
9910
9911 mdb_cursor_copy(mc, &mx);
9912 while (mc->mc_snum > 0) {
9913 MDB_page *mp = mc->mc_pg[mc->mc_top];
9914 unsigned n = NUMKEYS(mp);
9915 if (IS_LEAF(mp)) {
9916 for (i=0; i<n; i++) {
9917 ni = NODEPTR(mp, i);
9918 if (ni->mn_flags & F_BIGDATA) {
9919 MDB_page *omp;
9920 pgno_t pg;
9921 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9922 rc = mdb_page_get(mc, pg, &omp, NULL);
9923 if (rc != 0)
9924 goto done;
9925 mdb_cassert(mc, IS_OVERFLOW(omp));
9926 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9927 pg, omp->mp_pages);
9928 if (rc)
9929 goto done;
9930 mc->mc_db->md_overflow_pages -= omp->mp_pages;
9931 if (!mc->mc_db->md_overflow_pages && !subs)
9932 break;
9933 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9934 mdb_xcursor_init1(mc, ni);
9935 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9936 if (rc)
9937 goto done;
9938 }
9939 }
9940 if (!subs && !mc->mc_db->md_overflow_pages)
9941 goto pop;
9942 } else {
9943 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9944 goto done;
9945 for (i=0; i<n; i++) {
9946 pgno_t pg;
9947 ni = NODEPTR(mp, i);
9948 pg = NODEPGNO(ni);
9949 /* free it */
9950 mdb_midl_xappend(txn->mt_free_pgs, pg);
9951 }
9952 }
9953 if (!mc->mc_top)
9954 break;
9955 mc->mc_ki[mc->mc_top] = i;
9956 rc = mdb_cursor_sibling(mc, 1);
9957 if (rc) {
9958 if (rc != MDB_NOTFOUND)
9959 goto done;
9960 /* no more siblings, go back to beginning
9961 * of previous level.
9962 */
9963 pop:
9964 mdb_cursor_pop(mc);
9965 mc->mc_ki[0] = 0;
9966 for (i=1; i<mc->mc_snum; i++) {
9967 mc->mc_ki[i] = 0;
9968 mc->mc_pg[i] = mx.mc_pg[i];
9969 }
9970 }
9971 }
9972 /* free it */
9973 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9974 done:
9975 if (rc)
9976 txn->mt_flags |= MDB_TXN_ERROR;
9977 } else if (rc == MDB_NOTFOUND) {
9978 rc = MDB_SUCCESS;
9979 }
9980 mc->mc_flags &= ~C_INITIALIZED;
9981 return rc;
9982 }
9983
mdb_drop(MDB_txn * txn,MDB_dbi dbi,int del)9984 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9985 {
9986 MDB_cursor *mc, *m2;
9987 int rc;
9988
9989 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9990 return EINVAL;
9991
9992 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9993 return EACCES;
9994
9995 if (TXN_DBI_CHANGED(txn, dbi))
9996 return MDB_BAD_DBI;
9997
9998 rc = mdb_cursor_open(txn, dbi, &mc);
9999 if (rc)
10000 return rc;
10001
10002 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10003 /* Invalidate the dropped DB's cursors */
10004 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10005 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10006 if (rc)
10007 goto leave;
10008
10009 /* Can't delete the main DB */
10010 if (del && dbi >= CORE_DBS) {
10011 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10012 if (!rc) {
10013 txn->mt_dbflags[dbi] = DB_STALE;
10014 mdb_dbi_close(txn->mt_env, dbi);
10015 } else {
10016 txn->mt_flags |= MDB_TXN_ERROR;
10017 }
10018 } else {
10019 /* reset the DB record, mark it dirty */
10020 txn->mt_dbflags[dbi] |= DB_DIRTY;
10021 txn->mt_dbs[dbi].md_depth = 0;
10022 txn->mt_dbs[dbi].md_branch_pages = 0;
10023 txn->mt_dbs[dbi].md_leaf_pages = 0;
10024 txn->mt_dbs[dbi].md_overflow_pages = 0;
10025 txn->mt_dbs[dbi].md_entries = 0;
10026 txn->mt_dbs[dbi].md_root = P_INVALID;
10027
10028 txn->mt_flags |= MDB_TXN_DIRTY;
10029 }
10030 leave:
10031 mdb_cursor_close(mc);
10032 return rc;
10033 }
10034
mdb_set_compare(MDB_txn * txn,MDB_dbi dbi,MDB_cmp_func * cmp)10035 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10036 {
10037 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10038 return EINVAL;
10039
10040 txn->mt_dbxs[dbi].md_cmp = cmp;
10041 return MDB_SUCCESS;
10042 }
10043
mdb_set_dupsort(MDB_txn * txn,MDB_dbi dbi,MDB_cmp_func * cmp)10044 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10045 {
10046 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10047 return EINVAL;
10048
10049 txn->mt_dbxs[dbi].md_dcmp = cmp;
10050 return MDB_SUCCESS;
10051 }
10052
mdb_set_relfunc(MDB_txn * txn,MDB_dbi dbi,MDB_rel_func * rel)10053 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10054 {
10055 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10056 return EINVAL;
10057
10058 txn->mt_dbxs[dbi].md_rel = rel;
10059 return MDB_SUCCESS;
10060 }
10061
mdb_set_relctx(MDB_txn * txn,MDB_dbi dbi,void * ctx)10062 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10063 {
10064 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10065 return EINVAL;
10066
10067 txn->mt_dbxs[dbi].md_relctx = ctx;
10068 return MDB_SUCCESS;
10069 }
10070
10071 int ESECT
mdb_env_get_maxkeysize(MDB_env * env)10072 mdb_env_get_maxkeysize(MDB_env *env)
10073 {
10074 return ENV_MAXKEY(env);
10075 }
10076
10077 int ESECT
mdb_reader_list(MDB_env * env,MDB_msg_func * func,void * ctx)10078 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10079 {
10080 unsigned int i, rdrs;
10081 MDB_reader *mr;
10082 char buf[64];
10083 int rc = 0, first = 1;
10084
10085 if (!env || !func)
10086 return -1;
10087 if (!env->me_txns) {
10088 return func("(no reader locks)\n", ctx);
10089 }
10090 rdrs = env->me_txns->mti_numreaders;
10091 mr = env->me_txns->mti_readers;
10092 for (i=0; i<rdrs; i++) {
10093 if (mr[i].mr_pid) {
10094 txnid_t txnid = mr[i].mr_txnid;
10095 sprintf(buf, txnid == (txnid_t)-1 ?
10096 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
10097 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10098 if (first) {
10099 first = 0;
10100 rc = func(" pid thread txnid\n", ctx);
10101 if (rc < 0)
10102 break;
10103 }
10104 rc = func(buf, ctx);
10105 if (rc < 0)
10106 break;
10107 }
10108 }
10109 if (first) {
10110 rc = func("(no active readers)\n", ctx);
10111 }
10112 return rc;
10113 }
10114
10115 /** Insert pid into list if not already present.
10116 * return -1 if already present.
10117 */
10118 static int ESECT
mdb_pid_insert(MDB_PID_T * ids,MDB_PID_T pid)10119 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10120 {
10121 /* binary search of pid in list */
10122 unsigned base = 0;
10123 unsigned cursor = 1;
10124 int val = 0;
10125 unsigned n = ids[0];
10126
10127 while( 0 < n ) {
10128 unsigned pivot = n >> 1;
10129 cursor = base + pivot + 1;
10130 val = pid - ids[cursor];
10131
10132 if( val < 0 ) {
10133 n = pivot;
10134
10135 } else if ( val > 0 ) {
10136 base = cursor;
10137 n -= pivot + 1;
10138
10139 } else {
10140 /* found, so it's a duplicate */
10141 return -1;
10142 }
10143 }
10144
10145 if( val > 0 ) {
10146 ++cursor;
10147 }
10148 ids[0]++;
10149 for (n = ids[0]; n > cursor; n--)
10150 ids[n] = ids[n-1];
10151 ids[n] = pid;
10152 return 0;
10153 }
10154
10155 int ESECT
mdb_reader_check(MDB_env * env,int * dead)10156 mdb_reader_check(MDB_env *env, int *dead)
10157 {
10158 if (!env)
10159 return EINVAL;
10160 if (dead)
10161 *dead = 0;
10162 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10163 }
10164
10165 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10166 static int ESECT
mdb_reader_check0(MDB_env * env,int rlocked,int * dead)10167 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10168 {
10169 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10170 unsigned int i, j, rdrs;
10171 MDB_reader *mr;
10172 MDB_PID_T *pids, pid;
10173 int rc = MDB_SUCCESS, count = 0;
10174
10175 rdrs = env->me_txns->mti_numreaders;
10176 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10177 if (!pids)
10178 return ENOMEM;
10179 pids[0] = 0;
10180 mr = env->me_txns->mti_readers;
10181 for (i=0; i<rdrs; i++) {
10182 pid = mr[i].mr_pid;
10183 if (pid && pid != env->me_pid) {
10184 if (mdb_pid_insert(pids, pid) == 0) {
10185 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10186 /* Stale reader found */
10187 j = i;
10188 if (rmutex) {
10189 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10190 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10191 break;
10192 rdrs = 0; /* the above checked all readers */
10193 } else {
10194 /* Recheck, a new process may have reused pid */
10195 if (mdb_reader_pid(env, Pidcheck, pid))
10196 j = rdrs;
10197 }
10198 }
10199 for (; j<rdrs; j++)
10200 if (mr[j].mr_pid == pid) {
10201 DPRINTF(("clear stale reader pid %u txn %"Z"d",
10202 (unsigned) pid, mr[j].mr_txnid));
10203 mr[j].mr_pid = 0;
10204 count++;
10205 }
10206 if (rmutex)
10207 UNLOCK_MUTEX(rmutex);
10208 }
10209 }
10210 }
10211 }
10212 free(pids);
10213 if (dead)
10214 *dead = count;
10215 return rc;
10216 }
10217
10218 #ifdef MDB_ROBUST_SUPPORTED
10219 /** Handle #LOCK_MUTEX0() failure.
10220 * Try to repair the lock file if the mutex owner died.
10221 * @param[in] env the environment handle
10222 * @param[in] mutex LOCK_MUTEX0() mutex
10223 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10224 * @return 0 on success with the mutex locked, or an error code on failure.
10225 */
10226 static int ESECT
mdb_mutex_failed(MDB_env * env,mdb_mutexref_t mutex,int rc)10227 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10228 {
10229 int rlocked, rc2;
10230 MDB_meta *meta;
10231
10232 if (rc == MDB_OWNERDEAD) {
10233 /* We own the mutex. Clean up after dead previous owner. */
10234 rc = MDB_SUCCESS;
10235 rlocked = (mutex == env->me_rmutex);
10236 if (!rlocked) {
10237 /* Keep mti_txnid updated, otherwise next writer can
10238 * overwrite data which latest meta page refers to.
10239 */
10240 meta = mdb_env_pick_meta(env);
10241 env->me_txns->mti_txnid = meta->mm_txnid;
10242 /* env is hosed if the dead thread was ours */
10243 if (env->me_txn) {
10244 env->me_flags |= MDB_FATAL_ERROR;
10245 env->me_txn = NULL;
10246 rc = MDB_PANIC;
10247 }
10248 }
10249 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10250 (rc ? "this process' env is hosed" : "recovering")));
10251 rc2 = mdb_reader_check0(env, rlocked, NULL);
10252 if (rc2 == 0)
10253 rc2 = mdb_mutex_consistent(mutex);
10254 if (rc || (rc = rc2)) {
10255 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10256 UNLOCK_MUTEX(mutex);
10257 }
10258 } else {
10259 #ifdef _WIN32
10260 rc = ErrCode();
10261 #endif
10262 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10263 }
10264
10265 return rc;
10266 }
10267 #endif /* MDB_ROBUST_SUPPORTED */
10268
10269 #if defined(_WIN32)
10270 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
10271 static int ESECT
utf8_to_utf16(const char * src,MDB_name * dst,int xtra)10272 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
10273 {
10274 int rc, need = 0;
10275 wchar_t *result = NULL;
10276 for (;;) { /* malloc result, then fill it in */
10277 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
10278 if (!need) {
10279 rc = ErrCode();
10280 free(result);
10281 return rc;
10282 }
10283 if (!result) {
10284 result = malloc(sizeof(wchar_t) * (need + xtra));
10285 if (!result)
10286 return ENOMEM;
10287 continue;
10288 }
10289 dst->mn_alloced = 1;
10290 dst->mn_len = need - 1;
10291 dst->mn_val = result;
10292 return MDB_SUCCESS;
10293 }
10294 }
10295 #endif /* defined(_WIN32) */
10296 /** @} */
10297