mdb.c 171 KB
Newer Older
1
2
3
4
5
6
/** @file mdb.c
 *	@brief memory-mapped database library
 *
 *	A Btree-based database management library modeled loosely on the
 *	BerkeleyDB API, but much simplified.
 */
Howard Chu's avatar
Howard Chu committed
7
/*
Howard Chu's avatar
Howard Chu committed
8
 * Copyright 2011-2012 Howard Chu, Symas Corp.
Howard Chu's avatar
Howard Chu committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 *
 * This code is derived from btree.c written by Martin Hedenfalk.
 *
 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
Howard Chu's avatar
Howard Chu committed
35
36
37
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
Howard Chu's avatar
Howard Chu committed
38
39
40
#ifdef _WIN32
#include <windows.h>
#else
Howard Chu's avatar
Howard Chu committed
41
42
43
44
45
#include <sys/uio.h>
#include <sys/mman.h>
#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
Howard Chu's avatar
Howard Chu committed
46
#include <fcntl.h>
Howard Chu's avatar
Howard Chu committed
47
#endif
Howard Chu's avatar
Howard Chu committed
48
49
50

#include <assert.h>
#include <errno.h>
51
#include <limits.h>
Howard Chu's avatar
Howard Chu committed
52
#include <stddef.h>
53
#include <inttypes.h>
Howard Chu's avatar
Howard Chu committed
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
59

60
61
62
63
#if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
#include <resolv.h>	/* defines BYTE_ORDER on HPUX and Solaris */
#endif

64
65
#ifndef _WIN32
#include <pthread.h>
Howard Chu's avatar
Howard Chu committed
66
67
68
69
70
#ifdef __APPLE__
#include <semaphore.h>
#endif
#endif

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#ifdef USE_VALGRIND
#include <valgrind/memcheck.h>
#define VGMEMP_CREATE(h,r,z)    VALGRIND_CREATE_MEMPOOL(h,r,z)
#define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
#define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
#define VGMEMP_DESTROY(h)	VALGRIND_DESTROY_MEMPOOL(h)
#define VGMEMP_DEFINED(a,s)	VALGRIND_MAKE_MEM_DEFINED(a,s)
#else
#define VGMEMP_CREATE(h,r,z)
#define VGMEMP_ALLOC(h,a,s)
#define VGMEMP_FREE(h,a)
#define VGMEMP_DESTROY(h)
#define VGMEMP_DEFINED(a,s)
#endif

Howard Chu's avatar
Howard Chu committed
86
#ifndef BYTE_ORDER
Howard Chu's avatar
Howard Chu committed
87
88
89
90
91
92
93
94
95
96
97
98
# if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
/* Solaris just defines one or the other */
#  define LITTLE_ENDIAN	1234
#  define BIG_ENDIAN	4321
#  ifdef _LITTLE_ENDIAN
#   define BYTE_ORDER  LITTLE_ENDIAN
#  else
#   define BYTE_ORDER  BIG_ENDIAN
#  endif
# else
#  define BYTE_ORDER   __BYTE_ORDER
# endif
Howard Chu's avatar
Howard Chu committed
99
#endif
Howard Chu's avatar
Howard Chu committed
100

Howard Chu's avatar
Howard Chu committed
101
102
103
104
105
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN	__LITTLE_ENDIAN
#endif
#ifndef BIG_ENDIAN
#define BIG_ENDIAN	__BIG_ENDIAN
106
107
#endif

Howard Chu's avatar
Howard Chu committed
108
109
110
111
#if defined(__i386) || defined(__x86_64)
#define MISALIGNED_OK	1
#endif

112
113
114
#include "mdb.h"
#include "midl.h"

Howard Chu's avatar
Howard Chu committed
115
116
#if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
# error "Unknown or unsupported endianness (BYTE_ORDER)"
117
118
119
120
#elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
# error "Two's complement, reasonably sized integer types, please"
#endif

121
122
123
124
/** @defgroup internal	MDB Internals
 *	@{
 */
/** @defgroup compat	Windows Compatibility Macros
Howard Chu's avatar
Howard Chu committed
125
126
127
128
 *	A bunch of macros to minimize the amount of platform-specific ifdefs
 *	needed throughout the rest of the code. When the features this library
 *	needs are similar enough to POSIX to be hidden in a one-or-two line
 *	replacement, this macro approach is used.
129
130
 *	@{
 */
Howard Chu's avatar
Howard Chu committed
131
132
133
134
135
#ifdef _WIN32
#define pthread_t	DWORD
#define pthread_mutex_t	HANDLE
#define pthread_key_t	DWORD
#define pthread_self()	GetCurrentThreadId()
Hallvard Furuseth's avatar
Hallvard Furuseth committed
136
#define pthread_key_create(x,y)	(*(x) = TlsAlloc())
Howard Chu's avatar
Howard Chu committed
137
138
139
140
141
#define pthread_key_delete(x)	TlsFree(x)
#define pthread_getspecific(x)	TlsGetValue(x)
#define pthread_setspecific(x,y)	TlsSetValue(x,y)
#define pthread_mutex_unlock(x)	ReleaseMutex(x)
#define pthread_mutex_lock(x)	WaitForSingleObject(x, INFINITE)
Hallvard Furuseth's avatar
Hallvard Furuseth committed
142
143
144
145
#define LOCK_MUTEX_R(env)	pthread_mutex_lock((env)->me_rmutex)
#define UNLOCK_MUTEX_R(env)	pthread_mutex_unlock((env)->me_rmutex)
#define LOCK_MUTEX_W(env)	pthread_mutex_lock((env)->me_wmutex)
#define UNLOCK_MUTEX_W(env)	pthread_mutex_unlock((env)->me_wmutex)
Howard Chu's avatar
Howard Chu committed
146
#define getpid()	GetCurrentProcessId()
Hallvard Furuseth's avatar
Hallvard Furuseth committed
147
#define	fdatasync(fd)	(!FlushFileBuffers(fd))
Howard Chu's avatar
Howard Chu committed
148
#define	ErrCode()	GetLastError()
Hallvard Furuseth's avatar
Hallvard Furuseth committed
149
#define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
Howard Chu's avatar
Howard Chu committed
150
151
#define	close(fd)	CloseHandle(fd)
#define	munmap(ptr,len)	UnmapViewOfFile(ptr)
Howard Chu's avatar
Howard Chu committed
152
153
154
155
156
157
158
#else
#ifdef __APPLE__
#define LOCK_MUTEX_R(env)	sem_wait((env)->me_rmutex)
#define UNLOCK_MUTEX_R(env)	sem_post((env)->me_rmutex)
#define LOCK_MUTEX_W(env)	sem_wait((env)->me_wmutex)
#define UNLOCK_MUTEX_W(env)	sem_post((env)->me_wmutex)
#define fdatasync(fd)	fsync(fd)
Howard Chu's avatar
Howard Chu committed
159
#else
Howard Chu's avatar
Howard Chu committed
160
161
162
#ifdef ANDROID
#define fdatasync(fd)	fsync(fd)
#endif
Howard Chu's avatar
Howard Chu committed
163
164
	/** Lock the reader mutex.
	 */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
165
#define LOCK_MUTEX_R(env)	pthread_mutex_lock(&(env)->me_txns->mti_mutex)
Howard Chu's avatar
Howard Chu committed
166
167
	/** Unlock the reader mutex.
	 */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
168
#define UNLOCK_MUTEX_R(env)	pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
Howard Chu's avatar
Howard Chu committed
169
170
171
172
173

	/** Lock the writer mutex.
	 *	Only a single write transaction is allowed at a time. Other writers
	 *	will block waiting for this mutex.
	 */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
174
#define LOCK_MUTEX_W(env)	pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
Howard Chu's avatar
Howard Chu committed
175
176
	/** Unlock the writer mutex.
	 */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
177
#define UNLOCK_MUTEX_W(env)	pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
Howard Chu's avatar
Howard Chu committed
178
#endif	/* __APPLE__ */
Howard Chu's avatar
Howard Chu committed
179
180
181

	/** Get the error code for the last failed system function.
	 */
Howard Chu's avatar
Howard Chu committed
182
#define	ErrCode()	errno
Howard Chu's avatar
Howard Chu committed
183
184
185
186
187

	/** An abstraction for a file handle.
	 *	On POSIX systems file handles are small integers. On Windows
	 *	they're opaque pointers.
	 */
Howard Chu's avatar
Howard Chu committed
188
#define	HANDLE	int
Howard Chu's avatar
Howard Chu committed
189
190
191
192
193

	/**	A value for an invalid file handle.
	 *	Mainly used to initialize file variables and signify that they are
	 *	unused.
	 */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
194
#define INVALID_HANDLE_VALUE	(-1)
Howard Chu's avatar
Howard Chu committed
195
196
197
198
199

	/** Get the size of a memory page for the system.
	 *	This is the basic size that the platform's memory manager uses, and is
	 *	fundamental to the use of memory-mapped files.
	 */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
200
#define	GET_PAGESIZE(x)	((x) = sysconf(_SC_PAGE_SIZE))
Howard Chu's avatar
Howard Chu committed
201
#endif
Howard Chu's avatar
Howard Chu committed
202

Howard Chu's avatar
Howard Chu committed
203
204
#if defined(_WIN32) || defined(__APPLE__)
#define MNAME_LEN	32
205
206
#else
#define MNAME_LEN	(sizeof(pthread_mutex_t))
Howard Chu's avatar
Howard Chu committed
207
208
#endif

209
/** @} */
Howard Chu's avatar
Howard Chu committed
210

211
#ifndef _WIN32
Howard Chu's avatar
Howard Chu committed
212
213
214
215
216
217
/**	A flag for opening a file and requesting synchronous data writes.
 *	This is only used when writing a meta page. It's not strictly needed;
 *	we could just do a normal write and then immediately perform a flush.
 *	But if this flag is available it saves us an extra system call.
 *
 *	@note If O_DSYNC is undefined but exists in /usr/include,
Hallvard Furuseth's avatar
Hallvard Furuseth committed
218
219
220
221
222
223
 * preferably set some compiler flag to get the definition.
 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
 */
#ifndef MDB_DSYNC
# define MDB_DSYNC	O_DSYNC
#endif
224
225
226
227
228
229
230
#endif

/** Function for flushing the data of a file. Define this to fsync
 *	if fdatasync() is not supported.
 */
#ifndef MDB_FDATASYNC
# define MDB_FDATASYNC	fdatasync
231
232
#endif

Howard Chu's avatar
Howard Chu committed
233
234
235
236
237
238
239
240
	/** A page number in the database.
	 *	Note that 64 bit page numbers are overkill, since pages themselves
	 *	already represent 12-13 bits of addressable memory, and the OS will
	 *	always limit applications to a maximum of 63 bits of address space.
	 *
	 *	@note In the #MDB_node structure, we only store 48 bits of this value,
	 *	which thus limits us to only 60 bits of addressable data.
	 */
241
typedef ID	pgno_t;
Hallvard Furuseth's avatar
Hallvard Furuseth committed
242

243
244
245
	/** A transaction ID.
	 *	See struct MDB_txn.mt_txnid for details.
	 */
246
typedef ID	txnid_t;
Hallvard Furuseth's avatar
Hallvard Furuseth committed
247

Howard Chu's avatar
Howard Chu committed
248
249
250
/** @defgroup debug	Debug Macros
 *	@{
 */
Howard Chu's avatar
Howard Chu committed
251
#ifndef MDB_DEBUG
Howard Chu's avatar
Howard Chu committed
252
253
254
255
	/**	Enable debug output.
	 *	Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
	 *	read from and written to the database (used for free space management).
	 */
Howard Chu's avatar
Howard Chu committed
256
#define MDB_DEBUG 0
257
#endif
Howard Chu's avatar
Howard Chu committed
258

259
260
#if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
# define DPRINTF	(void)	/* Vararg macros may be unsupported */
Howard Chu's avatar
Howard Chu committed
261
#elif MDB_DEBUG
Howard Chu's avatar
Howard Chu committed
262
263
	/**	Print a debug message with printf formatting. */
# define DPRINTF(fmt, ...)	/**< Requires 2 or more args */ \
264
	fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
Howard Chu's avatar
Howard Chu committed
265
#else
266
# define DPRINTF(fmt, ...)	((void) 0)
Howard Chu's avatar
Howard Chu committed
267
#endif
Howard Chu's avatar
Howard Chu committed
268
269
270
	/**	Print a debug string.
	 *	The string is printed literally, with no format processing.
	 */
271
#define DPUTS(arg)	DPRINTF("%s", arg)
Howard Chu's avatar
Howard Chu committed
272
/** @} */
Howard Chu's avatar
Howard Chu committed
273

Howard Chu's avatar
Howard Chu committed
274
275
276
	/** A default memory page size.
	 *	The actual size is platform-dependent, but we use this for
	 *	boot-strapping. We probably should not be using this any more.
Hallvard Furuseth's avatar
Hallvard Furuseth committed
277
	 *	The #GET_PAGESIZE() macro is used to get the actual size.
Howard Chu's avatar
Howard Chu committed
278
279
280
281
282
283
284
285
	 *
	 *	Note that we don't currently support Huge pages. On Linux,
	 *	regular data files cannot use Huge pages, and in general
	 *	Huge pages aren't actually pageable. We rely on the OS
	 *	demand-pager to read our data and page it out when memory
	 *	pressure from other processes is high. So until OSs have
	 *	actual paging support for Huge pages, they're not viable.
	 */
Howard Chu's avatar
Howard Chu committed
286
#define MDB_PAGESIZE	 4096
Howard Chu's avatar
Howard Chu committed
287
288
289
290
291
292
293
294
295
296
297
298
299

	/** The minimum number of keys required in a database page.
	 *	Setting this to a larger value will place a smaller bound on the
	 *	maximum size of a data item. Data items larger than this size will
	 *	be pushed into overflow pages instead of being stored directly in
	 *	the B-tree node. This value used to default to 4. With a page size
	 *	of 4096 bytes that meant that any item larger than 1024 bytes would
	 *	go into an overflow page. That also meant that on average 2-3KB of
	 *	each overflow page was wasted space. The value cannot be lower than
	 *	2 because then there would no longer be a tree structure. With this
	 *	value, items larger than 2KB will go into overflow pages, and on
	 *	average only 1KB will be wasted.
	 */
Howard Chu's avatar
Howard Chu committed
300
#define MDB_MINKEYS	 2
Howard Chu's avatar
Howard Chu committed
301
302
303
304
305

	/**	A stamp that identifies a file as an MDB file.
	 *	There's nothing special about this value other than that it is easily
	 *	recognizable, and it will reflect any byte order mismatches.
	 */
Howard Chu's avatar
Howard Chu committed
306
#define MDB_MAGIC	 0xBEEFC0DE
Howard Chu's avatar
Howard Chu committed
307
308

	/**	The version number for a database's file format. */
Howard Chu's avatar
Howard Chu committed
309
#define MDB_VERSION	 1
Howard Chu's avatar
Howard Chu committed
310
311
312
313

	/**	The maximum size of a key in the database.
	 *	While data items have essentially unbounded size, we require that
	 *	keys all fit onto a regular page. This limit could be raised a bit
Howard Chu's avatar
Howard Chu committed
314
	 *	further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
Howard Chu's avatar
Howard Chu committed
315
	 */
Howard Chu's avatar
Howard Chu committed
316
#define MAXKEYSIZE	 511
Howard Chu's avatar
Howard Chu committed
317

Howard Chu's avatar
Howard Chu committed
318
#if MDB_DEBUG
Howard Chu's avatar
Howard Chu committed
319
320
321
322
323
324
325
326
327
	/**	A key buffer.
	 *	@ingroup debug
	 *	This is used for printing a hex dump of a key's contents.
	 */
#define DKBUF	char kbuf[(MAXKEYSIZE*2+1)]
	/**	Display a key in hex.
	 *	@ingroup debug
	 *	Invoke a function to display a key in hex.
	 */
Howard Chu's avatar
Howard Chu committed
328
329
#define	DKEY(x)	mdb_dkey(x, kbuf)
#else
330
#define	DKBUF	typedef int dummy_kbuf	/* so we can put ';' after */
Howard Chu's avatar
Howard Chu committed
331
#define DKEY(x)	0
Howard Chu's avatar
Howard Chu committed
332
#endif
Howard Chu's avatar
Howard Chu committed
333

Howard Chu's avatar
Howard Chu committed
334
/**	@defgroup lazylock	Lazy Locking
Hallvard Furuseth's avatar
Hallvard Furuseth committed
335
 *	Macros for locks that aren't actually needed.
Howard Chu's avatar
Howard Chu committed
336
337
338
 *	The DB view is always consistent because all writes are wrapped in
 *	the wmutex. Finer-grained locks aren't necessary.
 *	@{
Howard Chu's avatar
Howard Chu committed
339
340
 */
#ifndef	LAZY_LOCKS
Howard Chu's avatar
Howard Chu committed
341
	/**	Use lazy locking. I.e., don't lock these accesses at all. */
Howard Chu's avatar
Howard Chu committed
342
343
344
#define	LAZY_LOCKS	1
#endif
#if	LAZY_LOCKS
Howard Chu's avatar
Howard Chu committed
345
	/** Grab the reader lock */
Howard Chu's avatar
Howard Chu committed
346
#define	LAZY_MUTEX_LOCK(x)
Howard Chu's avatar
Howard Chu committed
347
	/** Release the reader lock */
Howard Chu's avatar
Howard Chu committed
348
#define	LAZY_MUTEX_UNLOCK(x)
Howard Chu's avatar
Howard Chu committed
349
	/** Release the DB table reader/writer lock */
Howard Chu's avatar
Howard Chu committed
350
#define	LAZY_RWLOCK_UNLOCK(x)
Howard Chu's avatar
Howard Chu committed
351
	/** Grab the DB table write lock */
Howard Chu's avatar
Howard Chu committed
352
#define	LAZY_RWLOCK_WRLOCK(x)
Howard Chu's avatar
Howard Chu committed
353
	/** Grab the DB table read lock */
Howard Chu's avatar
Howard Chu committed
354
#define	LAZY_RWLOCK_RDLOCK(x)
355
	/** Declare the DB table rwlock.  Should not be followed by ';'. */
Howard Chu's avatar
Howard Chu committed
356
#define	LAZY_RWLOCK_DEF(x)
Howard Chu's avatar
Howard Chu committed
357
	/** Initialize the DB table rwlock */
Howard Chu's avatar
Howard Chu committed
358
#define	LAZY_RWLOCK_INIT(x,y)
Howard Chu's avatar
Howard Chu committed
359
	/**	Destroy the DB table rwlock */
Howard Chu's avatar
Howard Chu committed
360
361
362
363
364
365
366
#define	LAZY_RWLOCK_DESTROY(x)
#else
#define	LAZY_MUTEX_LOCK(x)		pthread_mutex_lock(x)
#define	LAZY_MUTEX_UNLOCK(x)	pthread_mutex_unlock(x)
#define	LAZY_RWLOCK_UNLOCK(x)	pthread_rwlock_unlock(x)
#define	LAZY_RWLOCK_WRLOCK(x)	pthread_rwlock_wrlock(x)
#define	LAZY_RWLOCK_RDLOCK(x)	pthread_rwlock_rdlock(x)
367
#define	LAZY_RWLOCK_DEF(x)		pthread_rwlock_t	x;
Howard Chu's avatar
Howard Chu committed
368
369
370
#define	LAZY_RWLOCK_INIT(x,y)	pthread_rwlock_init(x,y)
#define	LAZY_RWLOCK_DESTROY(x)	pthread_rwlock_destroy(x)
#endif
Howard Chu's avatar
Howard Chu committed
371
/** @} */
Howard Chu's avatar
Howard Chu committed
372

Howard Chu's avatar
Howard Chu committed
373
374
375
	/** An invalid page number.
	 *	Mainly used to denote an empty tree.
	 */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
376
#define P_INVALID	 (~0UL)
Howard Chu's avatar
Howard Chu committed
377

Howard Chu's avatar
Howard Chu committed
378
	/** Test if a flag \b f is set in a flag word \b w. */
Howard Chu's avatar
Howard Chu committed
379
380
#define F_ISSET(w, f)	 (((w) & (f)) == (f))

Howard Chu's avatar
Howard Chu committed
381
382
383
384
	/**	Used for offsets within a single page.
	 *	Since memory pages are typically 4 or 8KB in size, 12-13 bits,
	 *	this is plenty.
	 */
Howard Chu's avatar
Howard Chu committed
385
386
typedef uint16_t	 indx_t;

Howard Chu's avatar
Howard Chu committed
387
388
389
390
	/**	Default size of memory map.
	 *	This is certainly too small for any actual applications. Apps should always set
	 *	the size explicitly using #mdb_env_set_mapsize().
	 */
Howard Chu's avatar
Howard Chu committed
391
392
#define DEFAULT_MAPSIZE	1048576

Howard Chu's avatar
Howard Chu committed
393
394
395
396
397
398
399
400
401
402
/**	@defgroup readers	Reader Lock Table
 *	Readers don't acquire any locks for their data access. Instead, they
 *	simply record their transaction ID in the reader table. The reader
 *	mutex is needed just to find an empty slot in the reader table. The
 *	slot's address is saved in thread-specific data so that subsequent read
 *	transactions started by the same thread need no further locking to proceed.
 *
 *	Since the database uses multi-version concurrency control, readers don't
 *	actually need any locking. This table is used to keep track of which
 *	readers are using data from which old transactions, so that we'll know
403
404
 *	when a particular old transaction is no longer in use. Old transactions
 *	that have discarded any data pages can then have those pages reclaimed
Howard Chu's avatar
Howard Chu committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
 *	for use by a later write transaction.
 *
 *	The lock table is constructed such that reader slots are aligned with the
 *	processor's cache line size. Any slot is only ever used by one thread.
 *	This alignment guarantees that there will be no contention or cache
 *	thrashing as threads update their own slot info, and also eliminates
 *	any need for locking when accessing a slot.
 *
 *	A writer thread will scan every slot in the table to determine the oldest
 *	outstanding reader transaction. Any freed pages older than this will be
 *	reclaimed by the writer. The writer doesn't use any locks when scanning
 *	this table. This means that there's no guarantee that the writer will
 *	see the most up-to-date reader info, but that's not required for correct
 *	operation - all we need is to know the upper bound on the oldest reader,
 *	we don't care at all about the newest reader. So the only consequence of
 *	reading stale information here is that old pages might hang around a
 *	while longer before being reclaimed. That's actually good anyway, because
 *	the longer we delay reclaiming old pages, the more likely it is that a
 *	string of contiguous pages can be found after coalescing old pages from
 *	many old transactions together.
 *
 *	@todo We don't actually do such coalescing yet, we grab pages from one
 *	old transaction at a time.
 *	@{
 */
	/**	Number of slots in the reader table.
	 *	This value was chosen somewhat arbitrarily. 126 readers plus a
	 *	couple mutexes fit exactly into 8KB on my development machine.
	 *	Applications should set the table size using #mdb_env_set_maxreaders().
	 */
#define DEFAULT_READERS	126

	/**	The size of a CPU cache line in bytes. We want our lock structures
	 *	aligned to this size to avoid false cache line sharing in the
	 *	lock table.
	 *	This value works for most CPUs. For Itanium this should be 128.
	 */
Howard Chu's avatar
Howard Chu committed
442
#ifndef CACHELINE
Howard Chu's avatar
Howard Chu committed
443
#define CACHELINE	64
Howard Chu's avatar
Howard Chu committed
444
445
#endif

Howard Chu's avatar
Howard Chu committed
446
447
448
449
450
451
452
453
	/**	The information we store in a single slot of the reader table.
	 *	In addition to a transaction ID, we also record the process and
	 *	thread ID that owns a slot, so that we can detect stale information,
	 *	e.g. threads or processes that went away without cleaning up.
	 *	@note We currently don't check for stale records. We simply re-init
	 *	the table when we know that we're the only process opening the
	 *	lock file.
	 */
Howard Chu's avatar
Howard Chu committed
454
typedef struct MDB_rxbody {
Howard Chu's avatar
Howard Chu committed
455
456
457
458
459
460
461
	/**	The current Transaction ID when this transaction began.
	 *	Multiple readers that start at the same time will probably have the
	 *	same ID here. Again, it's not important to exclude them from
	 *	anything; all we need to know is which version of the DB they
	 *	started from so we can avoid overwriting any data used in that
	 *	particular version.
	 */
462
	txnid_t		mrb_txnid;
Howard Chu's avatar
Howard Chu committed
463
	/** The process ID of the process owning this reader txn. */
Howard Chu's avatar
Howard Chu committed
464
	pid_t		mrb_pid;
Howard Chu's avatar
Howard Chu committed
465
	/** The thread ID of the thread owning this txn. */
Howard Chu's avatar
Howard Chu committed
466
467
468
	pthread_t	mrb_tid;
} MDB_rxbody;

Howard Chu's avatar
Howard Chu committed
469
	/** The actual reader record, with cacheline padding. */
Howard Chu's avatar
Howard Chu committed
470
typedef struct MDB_reader {
Howard Chu's avatar
Howard Chu committed
471
472
	union {
		MDB_rxbody mrx;
Howard Chu's avatar
Howard Chu committed
473
		/** shorthand for mrb_txnid */
Howard Chu's avatar
Howard Chu committed
474
475
476
#define	mr_txnid	mru.mrx.mrb_txnid
#define	mr_pid	mru.mrx.mrb_pid
#define	mr_tid	mru.mrx.mrb_tid
Howard Chu's avatar
Howard Chu committed
477
		/** cache line alignment */
Howard Chu's avatar
Howard Chu committed
478
479
		char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
	} mru;
Howard Chu's avatar
Howard Chu committed
480
481
} MDB_reader;

Howard Chu's avatar
Howard Chu committed
482
483
484
485
486
487
488
	/** The header for the reader table.
	 *	The table resides in a memory-mapped file. (This is a different file
	 *	than is used for the main database.)
	 *
	 *	For POSIX the actual mutexes reside in the shared memory of this
	 *	mapped file. On Windows, mutexes are named objects allocated by the
	 *	kernel; we store the mutex names in this mapped file so that other
Howard Chu's avatar
Howard Chu committed
489
	 *	processes can grab them. This same approach is also used on
Howard Chu's avatar
Howard Chu committed
490
	 *	MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
Howard Chu's avatar
Howard Chu committed
491
492
493
494
	 *	process-shared POSIX mutexes. For these cases where a named object
	 *	is used, the object name is derived from a 64 bit FNV hash of the
	 *	environment pathname. As such, naming collisions are extremely
	 *	unlikely. If a collision occurs, the results are unpredictable.
Howard Chu's avatar
Howard Chu committed
495
	 */
Howard Chu's avatar
Howard Chu committed
496
typedef struct MDB_txbody {
Hallvard Furuseth's avatar
Hallvard Furuseth committed
497
		/** Stamp identifying this as an MDB file. It must be set
Howard Chu's avatar
Howard Chu committed
498
		 *	to #MDB_MAGIC. */
Howard Chu's avatar
Howard Chu committed
499
	uint32_t	mtb_magic;
Howard Chu's avatar
Howard Chu committed
500
		/** Version number of this lock file. Must be set to #MDB_VERSION. */
Howard Chu's avatar
Howard Chu committed
501
	uint32_t	mtb_version;
Howard Chu's avatar
Howard Chu committed
502
503
#if defined(_WIN32) || defined(__APPLE__)
	char	mtb_rmname[MNAME_LEN];
Howard Chu's avatar
Howard Chu committed
504
#else
Howard Chu's avatar
Howard Chu committed
505
506
507
		/** Mutex protecting access to this table.
		 *	This is the reader lock that #LOCK_MUTEX_R acquires.
		 */
Howard Chu's avatar
Howard Chu committed
508
	pthread_mutex_t	mtb_mutex;
Howard Chu's avatar
Howard Chu committed
509
#endif
Howard Chu's avatar
Howard Chu committed
510
511
512
513
		/**	The ID of the last transaction committed to the database.
		 *	This is recorded here only for convenience; the value can always
		 *	be determined by reading the main database meta pages.
		 */
514
	txnid_t		mtb_txnid;
Howard Chu's avatar
Howard Chu committed
515
516
517
518
		/** The number of slots that have been used in the reader table.
		 *	This always records the maximum count, it is not decremented
		 *	when readers release their slots.
		 */
519
	unsigned	mtb_numreaders;
Howard Chu's avatar
Howard Chu committed
520
521
522
523
		/**	The ID of the most recent meta page in the database.
		 *	This is recorded here only for convenience; the value can always
		 *	be determined by reading the main database meta pages.
		 */
Howard Chu's avatar
Howard Chu committed
524
	uint32_t	mtb_me_toggle;
Howard Chu's avatar
Howard Chu committed
525
526
} MDB_txbody;

Howard Chu's avatar
Howard Chu committed
527
	/** The actual reader table definition. */
Howard Chu's avatar
Howard Chu committed
528
typedef struct MDB_txninfo {
Howard Chu's avatar
Howard Chu committed
529
530
531
532
533
	union {
		MDB_txbody mtb;
#define mti_magic	mt1.mtb.mtb_magic
#define mti_version	mt1.mtb.mtb_version
#define mti_mutex	mt1.mtb.mtb_mutex
Howard Chu's avatar
Howard Chu committed
534
#define mti_rmname	mt1.mtb.mtb_rmname
Howard Chu's avatar
Howard Chu committed
535
536
#define mti_txnid	mt1.mtb.mtb_txnid
#define mti_numreaders	mt1.mtb.mtb_numreaders
Howard Chu's avatar
Howard Chu committed
537
#define mti_me_toggle	mt1.mtb.mtb_me_toggle
Howard Chu's avatar
Howard Chu committed
538
539
540
		char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
	} mt1;
	union {
Howard Chu's avatar
Howard Chu committed
541
542
#if defined(_WIN32) || defined(__APPLE__)
		char mt2_wmname[MNAME_LEN];
Howard Chu's avatar
Howard Chu committed
543
544
#define	mti_wmname	mt2.mt2_wmname
#else
Howard Chu's avatar
Howard Chu committed
545
546
		pthread_mutex_t	mt2_wmutex;
#define mti_wmutex	mt2.mt2_wmutex
Howard Chu's avatar
Howard Chu committed
547
#endif
548
		char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
Howard Chu's avatar
Howard Chu committed
549
550
	} mt2;
	MDB_reader	mti_readers[1];
Howard Chu's avatar
Howard Chu committed
551
} MDB_txninfo;
Howard Chu's avatar
Howard Chu committed
552
/** @} */
Howard Chu's avatar
Howard Chu committed
553

Howard Chu's avatar
Howard Chu committed
554
/** Common header for all page types.
Howard Chu's avatar
Howard Chu committed
555
 * Overflow records occupy a number of contiguous pages with no
Howard Chu's avatar
Howard Chu committed
556
557
 * headers on any page after the first.
 */
Howard Chu's avatar
Howard Chu committed
558
typedef struct MDB_page {
559
560
#define	mp_pgno	mp_p.p_pgno
#define	mp_next	mp_p.p_next
Howard Chu's avatar
Howard Chu committed
561
	union {
562
563
564
		pgno_t		p_pgno;	/**< page number */
		void *		p_next;	/**< for in-memory list of freed structs */
	} mp_p;
Howard Chu's avatar
Howard Chu committed
565
	uint16_t	mp_pad;
Howard Chu's avatar
Howard Chu committed
566
567
568
569
570
/**	@defgroup mdb_page	Page Flags
 *	@ingroup internal
 *	Flags for the page headers.
 *	@{
 */
Howard Chu's avatar
Howard Chu committed
571
572
573
574
575
576
#define	P_BRANCH	 0x01		/**< branch page */
#define	P_LEAF		 0x02		/**< leaf page */
#define	P_OVERFLOW	 0x04		/**< overflow page */
#define	P_META		 0x08		/**< meta page */
#define	P_DIRTY		 0x10		/**< dirty page */
#define	P_LEAF2		 0x20		/**< for #MDB_DUPFIXED records */
Howard Chu's avatar
Howard Chu committed
577
#define	P_SUBP		 0x40		/**< for #MDB_DUPSORT sub-pages */
Howard Chu's avatar
Howard Chu committed
578
/** @} */
Howard Chu's avatar
Howard Chu committed
579
	uint16_t	mp_flags;		/**< @ref mdb_page */
580
581
582
#define mp_lower	mp_pb.pb.pb_lower
#define mp_upper	mp_pb.pb.pb_upper
#define mp_pages	mp_pb.pb_pages
Howard Chu's avatar
Howard Chu committed
583
	union {
Howard Chu's avatar
Howard Chu committed
584
		struct {
585
586
587
588
589
			indx_t		pb_lower;		/**< lower bound of free space */
			indx_t		pb_upper;		/**< upper bound of free space */
		} pb;
		uint32_t	pb_pages;	/**< number of overflow pages */
	} mp_pb;
Howard Chu's avatar
Howard Chu committed
590
	indx_t		mp_ptrs[1];		/**< dynamic size */
Howard Chu's avatar
Howard Chu committed
591
592
} MDB_page;

Howard Chu's avatar
Howard Chu committed
593
	/** Size of the page header, excluding dynamic data at the end */
594
#define PAGEHDRSZ	 ((unsigned) offsetof(MDB_page, mp_ptrs))
Howard Chu's avatar
Howard Chu committed
595

Howard Chu's avatar
Howard Chu committed
596
597
598
599
	/** Address of first usable data byte in a page, after the header */
#define METADATA(p)	 ((void *)((char *)(p) + PAGEHDRSZ))

	/** Number of nodes on a page */
Howard Chu's avatar
Howard Chu committed
600
#define NUMKEYS(p)	 (((p)->mp_lower - PAGEHDRSZ) >> 1)
Howard Chu's avatar
Howard Chu committed
601
602

	/** The amount of space remaining in the page */
Howard Chu's avatar
Howard Chu committed
603
#define SIZELEFT(p)	 (indx_t)((p)->mp_upper - (p)->mp_lower)
Howard Chu's avatar
Howard Chu committed
604
605

	/** The percentage of space used in the page, in tenths of a percent. */
Howard Chu's avatar
Howard Chu committed
606
607
#define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
				((env)->me_psize - PAGEHDRSZ))
Howard Chu's avatar
Howard Chu committed
608
609
610
611
612
613
	/** The minimum page fill factor, in tenths of a percent.
	 *	Pages emptier than this are candidates for merging.
	 */
#define FILL_THRESHOLD	 250

	/** Test if a page is a leaf page */
Howard Chu's avatar
Howard Chu committed
614
#define IS_LEAF(p)	 F_ISSET((p)->mp_flags, P_LEAF)
Howard Chu's avatar
Howard Chu committed
615
	/** Test if a page is a LEAF2 page */
Howard Chu's avatar
Howard Chu committed
616
#define IS_LEAF2(p)	 F_ISSET((p)->mp_flags, P_LEAF2)
Howard Chu's avatar
Howard Chu committed
617
	/** Test if a page is a branch page */
Howard Chu's avatar
Howard Chu committed
618
#define IS_BRANCH(p)	 F_ISSET((p)->mp_flags, P_BRANCH)
Howard Chu's avatar
Howard Chu committed
619
	/** Test if a page is an overflow page */
Howard Chu's avatar
Howard Chu committed
620
#define IS_OVERFLOW(p)	 F_ISSET((p)->mp_flags, P_OVERFLOW)
Howard Chu's avatar
Howard Chu committed
621
622
	/** Test if a page is a sub page */
#define IS_SUBP(p)	 F_ISSET((p)->mp_flags, P_SUBP)
Howard Chu's avatar
Howard Chu committed
623

Howard Chu's avatar
Howard Chu committed
624
	/** The number of overflow pages needed to store the given size. */
625
#define OVPAGES(size, psize)	((PAGEHDRSZ-1 + (size)) / (psize) + 1)
Howard Chu's avatar
Howard Chu committed
626

Howard Chu's avatar
Howard Chu committed
627
628
629
630
631
632
	/** Header for a single key/data pair within a page.
	 * We guarantee 2-byte alignment for nodes.
	 */
typedef struct MDB_node {
	/** lo and hi are used for data size on leaf nodes and for
	 * child pgno on branch nodes. On 64 bit platforms, flags
633
	 * is also used for pgno. (Branch nodes have no flags).
Howard Chu's avatar
Howard Chu committed
634
	 * They are in host byte order in case that lets some
635
	 * accesses be optimized into a 32-bit word access.
Howard Chu's avatar
Howard Chu committed
636
	 */
Howard Chu's avatar
Howard Chu committed
637
638
#define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
#define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
Howard Chu's avatar
Howard Chu committed
639
640
641
642
643
644
	unsigned short	mn_offset[2];	/**< storage for #mn_lo and #mn_hi */
/** @defgroup mdb_node Node Flags
 *	@ingroup internal
 *	Flags for node headers.
 *	@{
 */
Howard Chu's avatar
Howard Chu committed
645
646
647
#define F_BIGDATA	 0x01			/**< data put on overflow page */
#define F_SUBDATA	 0x02			/**< data is a sub-database */
#define F_DUPDATA	 0x04			/**< data has duplicates */
Howard Chu's avatar
Howard Chu committed
648
649

/** valid flags for #mdb_node_add() */
650
#define	NODE_ADD_FLAGS	(F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
Howard Chu's avatar
Howard Chu committed
651

Howard Chu's avatar
Howard Chu committed
652
653
/** @} */
	unsigned short	mn_flags;		/**< @ref mdb_node */
Howard Chu's avatar
Howard Chu committed
654
655
656
657
658
659
660
	unsigned short	mn_ksize;		/**< key size */
	char		mn_data[1];			/**< key and data are appended here */
} MDB_node;

	/** Size of the node header, excluding dynamic data at the end */
#define NODESIZE	 offsetof(MDB_node, mn_data)

661
662
663
	/** Bit position of top word in page number, for shifting mn_flags */
#define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)

Howard Chu's avatar
Howard Chu committed
664
	/** Size of a node in a branch page with a given key.
Howard Chu's avatar
Howard Chu committed
665
666
667
668
	 *	This is just the node header plus the key, there is no data.
	 */
#define INDXSIZE(k)	 (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))

Howard Chu's avatar
Howard Chu committed
669
	/** Size of a node in a leaf page with a given key and data.
Howard Chu's avatar
Howard Chu committed
670
671
672
673
	 *	This is node header plus key plus data size.
	 */
#define LEAFSIZE(k, d)	 (NODESIZE + (k)->mv_size + (d)->mv_size)

Howard Chu's avatar
Howard Chu committed
674
	/** Address of node \b i in page \b p */
Howard Chu's avatar
Howard Chu committed
675
676
677
678
679
680
681
682
683
#define NODEPTR(p, i)	 ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))

	/** Address of the key for the node */
#define NODEKEY(node)	 (void *)((node)->mn_data)

	/** Address of the data for a node */
#define NODEDATA(node)	 (void *)((char *)(node)->mn_data + (node)->mn_ksize)

	/** Get the page number pointed to by a branch node */
684
685
686
#define NODEPGNO(node) \
	((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
	 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
Howard Chu's avatar
Howard Chu committed
687
688
689
	/** Set the page number in a branch node */
#define SETPGNO(node,pgno)	do { \
	(node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
690
	if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
Howard Chu's avatar
Howard Chu committed
691
692
693
694
695
696
697
698
699

	/** Get the size of the data in a leaf node */
#define NODEDSZ(node)	 ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
	/** Set the size of the data for a leaf node */
#define SETDSZ(node,size)	do { \
	(node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
	/** The size of a key in a node */
#define NODEKSZ(node)	 ((node)->mn_ksize)

Howard Chu's avatar
Howard Chu committed
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
	/** Copy a page number from src to dst */
#ifdef MISALIGNED_OK
#define COPY_PGNO(dst,src)	dst = src
#else
#if SIZE_MAX > 4294967295UL
#define COPY_PGNO(dst,src)	do { \
	unsigned short *s, *d;	\
	s = (unsigned short *)&(src);	\
	d = (unsigned short *)&(dst);	\
	*d++ = *s++;	\
	*d++ = *s++;	\
	*d++ = *s++;	\
	*d = *s;	\
} while (0)
#else
#define COPY_PGNO(dst,src)	do { \
	unsigned short *s, *d;	\
	s = (unsigned short *)&(src);	\
	d = (unsigned short *)&(dst);	\
	*d++ = *s++;	\
	*d = *s;	\
} while (0)
#endif
#endif
Howard Chu's avatar
Howard Chu committed
724
725
726
727
728
729
730
	/** The address of a key in a LEAF2 page.
	 *	LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
	 *	There are no node headers, keys are stored contiguously.
	 */
#define LEAF2KEY(p, i, ks)	((char *)(p) + PAGEHDRSZ + ((i)*(ks)))

	/** Set the \b node's key into \b key, if requested. */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
731
732
#define MDB_SET_KEY(node, key)	{ if ((key) != NULL) { \
	(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
Howard Chu's avatar
Howard Chu committed
733
734

	/** Information about a single database in the environment. */
Howard Chu's avatar
Howard Chu committed
735
typedef struct MDB_db {
Howard Chu's avatar
Howard Chu committed
736
737
738
	uint32_t	md_pad;		/**< also ksize for LEAF2 pages */
	uint16_t	md_flags;	/**< @ref mdb_open */
	uint16_t	md_depth;	/**< depth of this tree */
739
740
741
742
	pgno_t		md_branch_pages;	/**< number of internal pages */
	pgno_t		md_leaf_pages;		/**< number of leaf pages */
	pgno_t		md_overflow_pages;	/**< number of overflow pages */
	size_t		md_entries;		/**< number of data items */
Howard Chu's avatar
Howard Chu committed
743
	pgno_t		md_root;		/**< the root page of this tree */
Howard Chu's avatar
Howard Chu committed
744
745
} MDB_db;

Howard Chu's avatar
Howard Chu committed
746
	/** Handle for the DB used to track free pages. */
Howard Chu's avatar
Howard Chu committed
747
#define	FREE_DBI	0
Howard Chu's avatar
Howard Chu committed
748
	/** Handle for the default DB. */
Howard Chu's avatar
Howard Chu committed
749
750
#define	MAIN_DBI	1

Howard Chu's avatar
Howard Chu committed
751
752
	/** Meta page content. */
typedef struct MDB_meta {
Hallvard Furuseth's avatar
Hallvard Furuseth committed
753
		/** Stamp identifying this as an MDB file. It must be set
Howard Chu's avatar
Howard Chu committed
754
		 *	to #MDB_MAGIC. */
Howard Chu's avatar
Howard Chu committed
755
	uint32_t	mm_magic;
Howard Chu's avatar
Howard Chu committed
756
		/** Version number of this lock file. Must be set to #MDB_VERSION. */
Howard Chu's avatar
Howard Chu committed
757
	uint32_t	mm_version;
Howard Chu's avatar
Howard Chu committed
758
759
760
761
	void		*mm_address;		/**< address for fixed mapping */
	size_t		mm_mapsize;			/**< size of mmap region */
	MDB_db		mm_dbs[2];			/**< first is free space, 2nd is main db */
	/** The size of pages used in this DB */
Howard Chu's avatar
Howard Chu committed
762
#define	mm_psize	mm_dbs[0].md_pad
Howard Chu's avatar
Howard Chu committed
763
	/** Any persistent environment flags. @ref mdb_env */
Howard Chu's avatar
Howard Chu committed
764
#define	mm_flags	mm_dbs[0].md_flags
Howard Chu's avatar
Howard Chu committed
765
	pgno_t		mm_last_pg;			/**< last used page in file */
766
	txnid_t		mm_txnid;			/**< txnid that committed this page */
Howard Chu's avatar
Howard Chu committed
767
768
} MDB_meta;

769
770
771
772
773
774
775
776
777
778
779
780
781
782
	/** Buffer for a stack-allocated dirty page.
	 *	The members define size and alignment, and silence type
	 *	aliasing warnings.  They are not used directly; that could
	 *	mean incorrectly using several union members in parallel.
	 */
typedef union MDB_pagebuf {
	char		mb_raw[MDB_PAGESIZE];
	MDB_page	mb_page;
	struct {
		char		mm_pad[PAGEHDRSZ];
		MDB_meta	mm_meta;
	} mb_metabuf;
} MDB_pagebuf;

Howard Chu's avatar
Howard Chu committed
783
784
785
786
787
788
789
790
791
	/** Auxiliary DB info.
	 *	The information here is mostly static/read-only. There is
	 *	only a single copy of this record in the environment.
	 */
typedef struct MDB_dbx {
	MDB_val		md_name;		/**< name of the database */
	MDB_cmp_func	*md_cmp;	/**< function for comparing keys */
	MDB_cmp_func	*md_dcmp;	/**< function for comparing data items */
	MDB_rel_func	*md_rel;	/**< user relocate function */
792
	void		*md_relctx;		/**< user-provided context for md_rel */
Howard Chu's avatar
Howard Chu committed
793
} MDB_dbx;
Howard Chu's avatar
Howard Chu committed
794

Howard Chu's avatar
Howard Chu committed
795
796
797
798
	/** A database transaction.
	 *	Every operation requires a transaction handle.
	 */
struct MDB_txn {
799
800
	MDB_txn		*mt_parent;		/**< parent of a nested txn */
	MDB_txn		*mt_child;		/**< nested txn under this txn */
Howard Chu's avatar
Howard Chu committed
801
802
803
804
805
	pgno_t		mt_next_pgno;	/**< next unallocated page */
	/** The ID of this transaction. IDs are integers incrementing from 1.
	 *	Only committed write transactions increment the ID. If a transaction
	 *	aborts, the ID may be re-used by the next writer.
	 */
806
	txnid_t		mt_txnid;
Howard Chu's avatar
Howard Chu committed
807
808
809
	MDB_env		*mt_env;		/**< the DB environment */
	/** The list of pages that became unused during this transaction.
	 */
Howard Chu's avatar
Howard Chu committed
810
	IDL			mt_free_pgs;
Howard Chu's avatar
Howard Chu committed
811
812
813
814
815
816
817
818
	union {
		ID2L	dirty_list;	/**< modified pages */
		MDB_reader	*reader;	/**< this thread's slot in the reader table */
	} mt_u;
	/** Array of records for each DB known in the environment. */
	MDB_dbx		*mt_dbxs;
	/** Array of MDB_db records for each known DB */
	MDB_db		*mt_dbs;
Howard Chu's avatar
Howard Chu committed
819
820
821
822
823
824
825
/** @defgroup mt_dbflag	Transaction DB Flags
 *	@ingroup internal
 * @{
 */
#define DB_DIRTY	0x01		/**< DB was written in this txn */
#define DB_STALE	0x02		/**< DB record is older than txnID */
/** @} */
Howard Chu's avatar
Howard Chu committed
826
827
	/** Array of cursors for each DB */
	MDB_cursor	**mt_cursors;
Howard Chu's avatar
Howard Chu committed
828
829
	/** Array of flags for each DB */
	unsigned char	*mt_dbflags;
Howard Chu's avatar
Howard Chu committed
830
831
832
	/**	Number of DB records in use. This number only ever increments;
	 *	we don't decrement it when individual DB handles are closed.
	 */
833
	MDB_dbi		mt_numdbs;
Howard Chu's avatar
Howard Chu committed
834

Howard Chu's avatar
Howard Chu committed
835
836
837
838
/** @defgroup mdb_txn	Transaction Flags
 *	@ingroup internal
 *	@{
 */
Howard Chu's avatar
Howard Chu committed
839
840
#define MDB_TXN_RDONLY		0x01		/**< read-only transaction */
#define MDB_TXN_ERROR		0x02		/**< an error has occurred */
Howard Chu's avatar
Howard Chu committed
841
842
/** @} */
	unsigned int	mt_flags;		/**< @ref mdb_txn */
Howard Chu's avatar
Howard Chu committed
843
844
845
846
847
	/** Tracks which of the two meta pages was used at the start
	 * 	of this transaction.
	 */
	unsigned int	mt_toggle;
};
Howard Chu's avatar
Howard Chu committed
848

Howard Chu's avatar
Howard Chu committed
849
/** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
850
851
852
 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
 * raise this on a 64 bit machine.
 */
Howard Chu's avatar
Howard Chu committed
853
#define CURSOR_STACK		 32
Howard Chu's avatar
Howard Chu committed
854

Howard Chu's avatar
Howard Chu committed
855
struct MDB_xcursor;
856

Howard Chu's avatar
Howard Chu committed
857
	/** Cursors are used for all DB operations */
Howard Chu's avatar
Howard Chu committed
858
struct MDB_cursor {
Howard Chu's avatar
Howard Chu committed
859
860
861
862
	/** Next cursor on this DB in this txn */
	MDB_cursor	*mc_next;
	/** Original cursor if this is a shadow */
	MDB_cursor	*mc_orig;
Howard Chu's avatar
Howard Chu committed
863
	/** Context used for databases with #MDB_DUPSORT, otherwise NULL */
Howard Chu's avatar
Howard Chu committed
864
	struct MDB_xcursor	*mc_xcursor;
Howard Chu's avatar
Howard Chu committed
865
	/** The transaction that owns this cursor */
Howard Chu's avatar
Howard Chu committed
866
	MDB_txn		*mc_txn;
Howard Chu's avatar
Howard Chu committed
867
	/** The database handle this cursor operates on */
Howard Chu's avatar
Howard Chu committed
868
	MDB_dbi		mc_dbi;
869
870
871
872
	/** The database record for this cursor */
	MDB_db		*mc_db;
	/** The database auxiliary record for this cursor */
	MDB_dbx		*mc_dbx;
Howard Chu's avatar
Howard Chu committed
873
874
	/** The @ref mt_dbflag for this database */
	unsigned char	*mc_dbflag;
Howard Chu's avatar
Howard Chu committed
875
	unsigned short 	mc_snum;	/**< number of pushed pages */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
876
	unsigned short	mc_top;		/**< index of top page, normally mc_snum-1 */
Howard Chu's avatar
Howard Chu committed
877
878
879
880
881
/** @defgroup mdb_cursor	Cursor Flags
 *	@ingroup internal
 *	Cursor state flags.
 *	@{
 */
Howard Chu's avatar
Howard Chu committed
882
883
#define C_INITIALIZED	0x01	/**< cursor has been initialized and is valid */
#define C_EOF	0x02			/**< No more data */
Howard Chu's avatar
Howard Chu committed
884
#define C_SUB	0x04			/**< Cursor is a sub-cursor */
Howard Chu's avatar
Howard Chu committed
885
886
#define C_SHADOW	0x08		/**< Cursor is a dup from a parent txn */
#define C_ALLOCD	0x10		/**< Cursor was malloc'd */
Howard Chu's avatar
Howard Chu committed
887
888
/** @} */
	unsigned int	mc_flags;	/**< @ref mdb_cursor */
Howard Chu's avatar
Howard Chu committed
889
890
	MDB_page	*mc_pg[CURSOR_STACK];	/**< stack of pushed pages */
	indx_t		mc_ki[CURSOR_STACK];	/**< stack of page indices */
Howard Chu's avatar
Howard Chu committed
891
892
};

Howard Chu's avatar
Howard Chu committed
893
894
895
896
	/** Context for sorted-dup records.
	 *	We could have gone to a fully recursive design, with arbitrarily
	 *	deep nesting of sub-databases. But for now we only handle these
	 *	levels - main DB, optional sub-DB, sorted-duplicate DB.
897
	 */
Howard Chu's avatar
Howard Chu committed
898
typedef struct MDB_xcursor {
Howard Chu's avatar
Howard Chu committed
899
	/** A sub-cursor for traversing the Dup DB */
Howard Chu's avatar
Howard Chu committed
900
	MDB_cursor mx_cursor;
901
902
903
904
	/** The database record for this Dup DB */
	MDB_db	mx_db;
	/**	The auxiliary DB record for this Dup DB */
	MDB_dbx	mx_dbx;
Howard Chu's avatar
Howard Chu committed
905
906
	/** The @ref mt_dbflag for this Dup DB */
	unsigned char mx_dbflag;
Howard Chu's avatar
Howard Chu committed
907
908
} MDB_xcursor;

Howard Chu's avatar
Howard Chu committed
909
910
911
912
913
914
915
	/** A set of pages freed by an earlier transaction. */
typedef struct MDB_oldpages {
	/** Usually we only read one record from the FREEDB at a time, but
	 *	in case we read more, this will chain them together.
	 */
	struct MDB_oldpages *mo_next;
	/**	The ID of the transaction in which these pages were freed. */
916
	txnid_t		mo_txnid;
Howard Chu's avatar
Howard Chu committed
917
918
919
920
921
	/** An #IDL of the pages */
	pgno_t		mo_pages[1];	/* dynamic */
} MDB_oldpages;

	/** The database environment. */
Howard Chu's avatar
Howard Chu committed
922
struct MDB_env {
Howard Chu's avatar
Howard Chu committed
923
924
925
	HANDLE		me_fd;		/**< The main data file */
	HANDLE		me_lfd;		/**< The lock file */
	HANDLE		me_mfd;			/**< just for writing the meta pages */
Howard Chu's avatar
Howard Chu committed
926
	/** Failed to update the meta page. Probably an I/O error. */
Howard Chu's avatar
Howard Chu committed
927
#define	MDB_FATAL_ERROR	0x80000000U
Howard Chu's avatar
Howard Chu committed
928
	uint32_t 	me_flags;		/**< @ref mdb_env */
Howard Chu's avatar
Howard Chu committed
929
930
	uint32_t	me_extrapad;	/**< unused for now */
	unsigned int	me_maxreaders;	/**< size of the reader table */
931
932
	MDB_dbi		me_numdbs;		/**< number of DBs opened */
	MDB_dbi		me_maxdbs;		/**< size of the DB table */
Howard Chu's avatar
Howard Chu committed
933
934
935
936
937
938
939
940
	char		*me_path;		/**< path to the DB files */
	char		*me_map;		/**< the memory map of the data file */
	MDB_txninfo	*me_txns;		/**< the memory map of the lock file */
	MDB_meta	*me_metas[2];	/**< pointers to the two meta pages */
	MDB_txn		*me_txn;		/**< current write transaction */
	size_t		me_mapsize;		/**< size of the data memory map */
	off_t		me_size;		/**< current file size */
	pgno_t		me_maxpg;		/**< me_mapsize / me_psize */
Hallvard Furuseth's avatar
Hallvard Furuseth committed
941
	unsigned int	me_psize;	/**< size of a page, from #GET_PAGESIZE */
Howard Chu's avatar
Howard Chu committed
942
	unsigned int	me_db_toggle;	/**< which DB table is current */
Howard Chu's avatar
Howard Chu committed
943
	txnid_t		me_wtxnid;		/**< ID of last txn we committed */
Howard Chu's avatar
Howard Chu committed
944
945
	txnid_t		me_pgfirst;		/**< ID of first old page record we used */
	txnid_t		me_pglast;		/**< ID of last old page record we used */
Howard Chu's avatar
Howard Chu committed
946
947
948
949
950
951
	MDB_dbx		*me_dbxs;		/**< array of static DB info */
	MDB_db		*me_dbs[2];		/**< two arrays of MDB_db info */
	MDB_oldpages *me_pghead;	/**< list of old page records */
	pthread_key_t	me_txkey;	/**< thread-key for readers */
	MDB_page	*me_dpages;		/**< list of malloc'd blocks for re-use */
	/** IDL of pages that became unused in a write txn */
Howard Chu's avatar
Howard Chu committed
952
	IDL			me_free_pgs;
Howard Chu's avatar
Howard Chu committed
953
	/** ID2L of pages that were written during a write txn */
Howard Chu's avatar
Howard Chu committed
954
	ID2			me_dirty_list[MDB_IDL_UM_SIZE];
Howard Chu's avatar
Howard Chu committed
955
	/** rwlock for the DB tables, if #LAZY_LOCKS is false */
956
	LAZY_RWLOCK_DEF(me_dblock)
Howard Chu's avatar
Howard Chu committed
957
958
959
960
#ifdef _WIN32
	HANDLE		me_rmutex;		/* Windows mutexes don't reside in shared mem */
	HANDLE		me_wmutex;
#endif
Howard Chu's avatar
Howard Chu committed
961
962
963
964
#ifdef __APPLE__
	sem_t		*me_rmutex;		/* Apple doesn't support shared mutexes */
	sem_t		*me_wmutex;
#endif
Howard Chu's avatar
Howard Chu committed
965
};
Howard Chu's avatar
Howard Chu committed
966
967
	/** max number of pages to commit in one writev() call */
#define MDB_COMMIT_PAGES	 64
968
969
970
971
#if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
#undef MDB_COMMIT_PAGES
#define MDB_COMMIT_PAGES	IOV_MAX
#endif
Howard Chu's avatar
Howard Chu committed
972

Howard Chu's avatar
Howard Chu committed
973
static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
Howard Chu's avatar
Howard Chu committed
974
static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
Howard Chu's avatar
Howard Chu committed
975
static int 		mdb_page_touch(MDB_cursor *mc);
Howard Chu's avatar
Howard Chu committed
976

Howard Chu's avatar
Howard Chu committed
977
static int  mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
Howard Chu's avatar
Howard Chu committed
978
static int  mdb_page_search_root(MDB_cursor *mc,
979
			    MDB_val *key, int modify);
Howard Chu's avatar
Howard Chu committed
980
static int  mdb_page_search(MDB_cursor *mc,
981
			    MDB_val *key, int modify);
Howard Chu's avatar
Howard Chu committed
982
983
static int	mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
static int	mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
Howard Chu's avatar
Howard Chu committed
984
				pgno_t newpgno, unsigned int nflags);
Howard Chu's avatar
Howard Chu committed
985

Howard Chu's avatar
Howard Chu committed
986
987
988
static int  mdb_env_read_header(MDB_env *env, MDB_meta *meta);
static int  mdb_env_read_meta(MDB_env *env, int *which);
static int  mdb_env_write_meta(MDB_txn *txn);
Howard Chu's avatar
Howard Chu committed
989

Howard Chu's avatar
Howard Chu committed
990
991
static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
static int  mdb_node_add(MDB_cursor *mc, indx_t indx,
Howard Chu's avatar
Howard Chu committed
992
			    MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
Howard Chu's avatar
Howard Chu committed
993
static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
Howard Chu's avatar
Howard Chu committed
994
static void mdb_node_shrink(MDB_page *mp, indx_t indx);
Howard Chu's avatar
Howard Chu committed
995
static int	mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
Howard Chu's avatar
Howard Chu committed
996
static int  mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
Howard Chu's avatar
Howard Chu committed
997
998
static size_t	mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
static size_t	mdb_branch_size(MDB_env *env, MDB_val *key);
Howard Chu's avatar
Howard Chu committed
999

1000
static int	mdb_rebalance(MDB_cursor *mc);
Howard Chu's avatar
Howard Chu committed
1001
static int	mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
1002

Howard Chu's avatar
Howard Chu committed
1003
1004
static void	mdb_cursor_pop(MDB_cursor *mc);
static int	mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1005

Howard Chu's avatar
Howard Chu committed
1006
static int	mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
Howard Chu's avatar
Howard Chu committed
1007
static int	mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1008
1009
1010
1011
1012
1013
static int	mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
static int	mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
static int	mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
				int *exactp);
static int	mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
static int	mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
Howard Chu's avatar
Howard Chu committed
1014

Howard Chu's avatar
Howard Chu committed
1015
static void	mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
Howard Chu's avatar
Howard Chu committed
1016
static void	mdb_xcursor_init0(MDB_cursor *mc);
1017
static void	mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
Howard Chu's avatar
Howard Chu committed
1018

Howard Chu's avatar
Howard Chu committed
1019
static int	mdb_drop0(MDB_cursor *mc, int subs);
Howard Chu's avatar
Howard Chu committed
1020
1021
static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);

Howard Chu's avatar
Howard Chu committed
1022
/** @cond */
Howard Chu's avatar
Howard Chu committed
1023
static MDB_cmp_func	mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
Howard Chu's avatar
Howard Chu committed
1024
/** @endcond */
Howard Chu's avatar
Howard Chu committed
1025

Howard Chu's avatar
Howard Chu committed
1026
1027
1028
1029
1030
1031
#ifdef _WIN32
static SECURITY_DESCRIPTOR mdb_null_sd;
static SECURITY_ATTRIBUTES mdb_all_sa;
static int mdb_sec_inited;
#endif

Howard Chu's avatar
Howard Chu committed
1032
/** Return the library version info. */
Howard Chu's avatar
Howard Chu committed
1033
char *
Howard Chu's avatar
Howard Chu committed
1034
mdb_version(int *major, int *minor, int *patch)
Howard Chu's avatar
Howard Chu committed
1035
{
Howard Chu's avatar
Howard Chu committed
1036
1037
1038
	if (major) *major = MDB_VERSION_MAJOR;
	if (minor) *minor = MDB_VERSION_MINOR;
	if (patch) *patch = MDB_VERSION_PATCH;
Howard Chu's avatar
Howard Chu committed
1039
1040
1041
	return MDB_VERSION_STRING;
}

Howard Chu's avatar
Howard Chu committed
1042
/** Table of descriptions for MDB @ref errors */
Howard Chu's avatar
Howard Chu committed
1043
static char *const mdb_errstr[] = {
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
	"MDB_KEYEXIST: Key/data pair already exists",
	"MDB_NOTFOUND: No matching key/data pair found",
	"MDB_PAGE_NOTFOUND: Requested page not found",
	"MDB_CORRUPTED: Located page was wrong type",
	"MDB_PANIC: Update of meta page failed",
	"MDB_VERSION_MISMATCH: Database environment version mismatch"
};

char *
mdb_strerror(int err)
{
	if (!err)
		return ("Successful return: 0");

	if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
Howard Chu's avatar
Howard Chu committed
1059
		return mdb_errstr[err - MDB_KEYEXIST];
1060
1061
1062
1063

	return strerror(err);
}

Howard Chu's avatar
Howard Chu committed
1064
#if MDB_DEBUG
Howard Chu's avatar
Howard Chu committed
1065
1066
1067
1068
1069
/** Display a key in hexadecimal and return the address of the result.
 * @param[in] key the key to display
 * @param[in] buf the buffer to write into. Should always be #DKBUF.
 * @return The key in hexadecimal form.
 */
1070
char *
Howard Chu's avatar
Howard Chu committed
1071
1072
1073
1074
1075
1076
1077
mdb_dkey(MDB_val *key, char *buf)
{
	char *ptr = buf;
	unsigned char *c = key->mv_data;
	unsigned int i;
	if (key->mv_size > MAXKEYSIZE)
		return "MAXKEYSIZE";
Howard Chu's avatar
Howard Chu committed
1078
1079
1080
	/* may want to make this a dynamic check: if the key is mostly
	 * printable characters, print it as-is instead of converting to hex.
	 */
1081
#if 1
1082
	buf[0] = '\0';
Howard Chu's avatar
Howard Chu committed
1083
1084
	for (i=0; i<key->mv_size; i++)
		ptr += sprintf(ptr, "%02x", *c++);
Howard Chu's avatar
Howard Chu committed
1085
1086
1087
#else
	sprintf(buf, "%.*s", key->mv_size, key->mv_data);
#endif
Howard Chu's avatar
Howard Chu committed
1088
1089
	return buf;
}
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108

/** Display all the keys in the page. */
static void
mdb_page_keys(MDB_page *mp)
{
	MDB_node *node;
	unsigned int i, nkeys;
	MDB_val key;
	DKBUF;

	nkeys = NUMKEYS(mp);
	DPRINTF("numkeys %d", nkeys);
	for (i=0; i<nkeys; i++) {
		node = NODEPTR(mp, i);
		key.mv_size = node->mn_ksize;
		key.mv_data = node->mn_data;
		DPRINTF("key %d: %s", i, DKEY(&key));
	}
}
1109
#endif
Howard Chu's avatar
Howard Chu committed
1110

1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
#if MDB_DEBUG > 2
/** Count all the pages in each DB and in the freelist
 *  and make sure it matches the actual number of pages
 *  being used.
 */
static void mdb_audit(MDB_txn *txn)
{
	MDB_cursor mc;
	MDB_val key, data;
	int rc, i;
	ID freecount, count;

	freecount = 0;
	mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
	while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
		freecount += *(ID *)data.mv_data;
	freecount += txn->mt_dbs[0].md_branch_pages + txn->mt_dbs[0].md_leaf_pages +
		txn->mt_dbs[0].md_overflow_pages;

	count = 0;
	for (i = 0; i<txn->mt_numdbs; i++) {
		count += txn->mt_dbs[i].md_branch_pages +
			txn->mt_dbs[i].md_leaf_pages +
			txn->mt_dbs[i].md_overflow_pages;
		if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
			MDB_xcursor mx;
			mdb_cursor_init(&mc, txn, i, &mx);
			mdb_page_search(&mc, NULL, 0);
			do {