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