fil0fil.c 128 KB
Newer Older
1 2
/*****************************************************************************

3
Copyright (c) 1995, 2010, Innobase Oy. All Rights Reserved.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA

*****************************************************************************/

19 20
/**************************************************//**
@file fil/fil0fil.c
osku's avatar
osku committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
The tablespace memory cache

Created 10/25/1995 Heikki Tuuri
*******************************************************/

#include "fil0fil.h"

#include "mem0mem.h"
#include "hash0hash.h"
#include "os0file.h"
#include "mach0data.h"
#include "buf0buf.h"
#include "buf0flu.h"
#include "log0recv.h"
#include "fsp0fsp.h"
#include "srv0srv.h"
#include "srv0start.h"
#include "mtr0mtr.h"
#include "mtr0log.h"
#include "dict0dict.h"
41
#include "page0page.h"
42
#include "page0zip.h"
43 44 45 46 47 48 49 50
#ifndef UNIV_HOTBACKUP
# include "buf0lru.h"
# include "ibuf0ibuf.h"
# include "sync0sync.h"
# include "os0sync.h"
#else /* !UNIV_HOTBACKUP */
static ulint srv_data_read, srv_data_written;
#endif /* !UNIV_HOTBACKUP */
51

osku's avatar
osku committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
/*
		IMPLEMENTATION OF THE TABLESPACE MEMORY CACHE
		=============================================

The tablespace cache is responsible for providing fast read/write access to
tablespaces and logs of the database. File creation and deletion is done
in other modules which know more of the logic of the operation, however.

A tablespace consists of a chain of files. The size of the files does not
have to be divisible by the database block size, because we may just leave
the last incomplete block unused. When a new file is appended to the
tablespace, the maximum size of the file is also specified. At the moment,
we think that it is best to extend the file to its maximum size already at
the creation of the file, because then we can avoid dynamically extending
the file when more space is needed for the tablespace.

A block's position in the tablespace is specified with a 32-bit unsigned
integer. The files in the chain are thought to be catenated, and the block
corresponding to an address n is the nth block in the catenated file (where
the first block is named the 0th block, and the incomplete block fragments
at the end of files are not taken into account). A tablespace can be extended
by appending a new file at the end of the chain.

Our tablespace concept is similar to the one of Oracle.

To acquire more speed in disk transfers, a technique called disk striping is
sometimes used. This means that logical block addresses are divided in a
round-robin fashion across several disks. Windows NT supports disk striping,
so there we do not need to support it in the database. Disk striping is
implemented in hardware in RAID disks. We conclude that it is not necessary
to implement it in the database. Oracle 7 does not support disk striping,
either.

Another trick used at some database sites is replacing tablespace files by
raw disks, that is, the whole physical disk drive, or a partition of it, is
opened as a single file, and it is accessed through byte offsets calculated
from the start of the disk or the partition. This is recommended in some
books on database tuning to achieve more speed in i/o. Using raw disk
certainly prevents the OS from fragmenting disk space, but it is not clear
if it really adds speed. We measured on the Pentium 100 MHz + NT + NTFS file
system + EIDE Conner disk only a negligible difference in speed when reading
93
from a file, versus reading from a raw disk.
osku's avatar
osku committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107

To have fast access to a tablespace or a log file, we put the data structures
to a hash table. Each tablespace and log file is given an unique 32-bit
identifier.

Some operating systems do not support many open files at the same time,
though NT seems to tolerate at least 900 open files. Therefore, we put the
open files in an LRU-list. If we need to open another file, we may close the
file at the end of the LRU-list. When an i/o-operation is pending on a file,
the file cannot be closed. We take the file nodes with pending i/o-operations
out of the LRU-list and keep a count of pending operations. When an operation
completes, we decrement the count and return the file node to the LRU-list if
the count drops to zero. */

108
/** When mysqld is run, the default directory "." is the mysqld datadir,
osku's avatar
osku committed
109 110
but in the MySQL Embedded Server Library and ibbackup it is not the default
directory, and we must set the base file path explicitly */
111
UNIV_INTERN const char*	fil_path_to_mysql_datadir	= ".";
osku's avatar
osku committed
112

113
/** The number of fsyncs done to the log */
114
UNIV_INTERN ulint	fil_n_log_flushes			= 0;
osku's avatar
osku committed
115

116
/** Number of pending redo log flushes */
117
UNIV_INTERN ulint	fil_n_pending_log_flushes		= 0;
118
/** Number of pending tablespace flushes */
119
UNIV_INTERN ulint	fil_n_pending_tablespace_flushes	= 0;
osku's avatar
osku committed
120

121
/** The null file address */
122
UNIV_INTERN fil_addr_t	fil_addr_null = {FIL_NULL, 0};
osku's avatar
osku committed
123

124 125 126 127 128 129 130 131 132 133
#ifdef UNIV_PFS_MUTEX
/* Key to register fil_system_mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	fil_system_mutex_key;
#endif /* UNIV_PFS_MUTEX */

#ifdef UNIV_PFS_RWLOCK
/* Key to register file space latch with performance schema */
UNIV_INTERN mysql_pfs_key_t	fil_space_latch_key;
#endif /* UNIV_PFS_RWLOCK */

134
/** File node of a tablespace or the log data space */
osku's avatar
osku committed
135
struct fil_node_struct {
136
	fil_space_t*	space;	/*!< backpointer to the space where this node
osku's avatar
osku committed
137
				belongs */
138 139 140 141
	char*		name;	/*!< path to the file */
	ibool		open;	/*!< TRUE if file open */
	os_file_t	handle;	/*!< OS handle to the file, if file open */
	ibool		is_raw_disk;/*!< TRUE if the 'file' is actually a raw
osku's avatar
osku committed
142
				device or a raw disk partition */
143
	ulint		size;	/*!< size of the file in database pages, 0 if
osku's avatar
osku committed
144 145 146
				not known yet; the possible last incomplete
				megabyte may be ignored if space == 0 */
	ulint		n_pending;
147
				/*!< count of pending i/o's on this file;
osku's avatar
osku committed
148 149 150
				closing of the file is not allowed if
				this is > 0 */
	ulint		n_pending_flushes;
151
				/*!< count of pending flushes on this file;
osku's avatar
osku committed
152
				closing of the file is not allowed if
153
				this is > 0 */
154
	ib_int64_t	modification_counter;/*!< when we write to the file we
osku's avatar
osku committed
155
				increment this by one */
156 157 158
	ib_int64_t	flush_counter;/*!< up to what
				modification_counter value we have
				flushed the modifications to disk */
osku's avatar
osku committed
159
	UT_LIST_NODE_T(fil_node_t) chain;
160
				/*!< link field for the file chain */
osku's avatar
osku committed
161
	UT_LIST_NODE_T(fil_node_t) LRU;
162 163
				/*!< link field for the LRU list */
	ulint		magic_n;/*!< FIL_NODE_MAGIC_N */
osku's avatar
osku committed
164 165
};

166
/** Value of fil_node_struct::magic_n */
osku's avatar
osku committed
167 168
#define	FIL_NODE_MAGIC_N	89389

169
/** Tablespace or log data space: let us call them by a common name space */
osku's avatar
osku committed
170
struct fil_space_struct {
171
	char*		name;	/*!< space name = the path to the first file in
osku's avatar
osku committed
172
				it */
173
	ulint		id;	/*!< space id */
174
	ib_int64_t	tablespace_version;
175 176 177 178 179 180
				/*!< in DISCARD/IMPORT this timestamp
				is used to check if we should ignore
				an insert buffer merge request for a
				page because it actually was for the
				previous incarnation of the space */
	ibool		mark;	/*!< this is set to TRUE at database startup if
osku's avatar
osku committed
181 182 183
				the space corresponds to a table in the InnoDB
				data dictionary; so we can print a warning of
				orphaned tablespaces */
184 185 186 187
	ibool		stop_ios;/*!< TRUE if we want to rename the
				.ibd file of tablespace and want to
				stop temporarily posting of new i/o
				requests on the file */
osku's avatar
osku committed
188
	ibool		stop_ibuf_merges;
189 190
				/*!< we set this TRUE when we start
				deleting a single-table tablespace */
osku's avatar
osku committed
191
	ibool		is_being_deleted;
192
				/*!< this is set to TRUE when we start
osku's avatar
osku committed
193 194 195 196 197
				deleting a single-table tablespace and its
				file; when this flag is set no further i/o
				or flush requests can be placed on this space,
				though there may be such requests still being
				processed on this space */
198 199
	ulint		purpose;/*!< FIL_TABLESPACE, FIL_LOG, or
				FIL_ARCH_LOG */
osku's avatar
osku committed
200
	UT_LIST_BASE_NODE_T(fil_node_t) chain;
201 202
				/*!< base node for the file chain */
	ulint		size;	/*!< space size in pages; 0 if a single-table
osku's avatar
osku committed
203 204
				tablespace whose size we do not know yet;
				last incomplete megabytes in data files may be
205
				ignored if space == 0 */
206
	ulint		flags;	/*!< compressed page size and file format, or 0 */
osku's avatar
osku committed
207
	ulint		n_reserved_extents;
208
				/*!< number of reserved free extents for
osku's avatar
osku committed
209
				ongoing operations like B-tree page split */
210
	ulint		n_pending_flushes; /*!< this is positive when flushing
osku's avatar
osku committed
211
				the tablespace to disk; dropping of the
212 213 214 215 216 217 218 219 220
				tablespace is forbidden if this is positive */
	ulint		n_pending_ibuf_merges;/*!< this is positive
				when merging insert buffer entries to
				a page so that we may need to access
				the ibuf bitmap page in the
				tablespade: dropping of the tablespace
				is forbidden if this is positive */
	hash_node_t	hash;	/*!< hash chain node */
	hash_node_t	name_hash;/*!< hash chain the name_hash table */
221
#ifndef UNIV_HOTBACKUP
222
	rw_lock_t	latch;	/*!< latch protecting the file space storage
osku's avatar
osku committed
223
				allocation */
224
#endif /* !UNIV_HOTBACKUP */
225
	UT_LIST_NODE_T(fil_space_t) unflushed_spaces;
226
				/*!< list of spaces with at least one unflushed
227
				file we have written to */
228 229
	ibool		is_in_unflushed_spaces; /*!< TRUE if this space is
				currently in unflushed_spaces */
osku's avatar
osku committed
230
	UT_LIST_NODE_T(fil_space_t) space_list;
231 232
				/*!< list of all spaces */
	ulint		magic_n;/*!< FIL_SPACE_MAGIC_N */
osku's avatar
osku committed
233 234
};

235
/** Value of fil_space_struct::magic_n */
osku's avatar
osku committed
236 237
#define	FIL_SPACE_MAGIC_N	89472

238
/** The tablespace memory cache */
osku's avatar
osku committed
239
typedef	struct fil_system_struct	fil_system_t;
240 241 242 243 244

/** The tablespace memory cache; also the totality of logs (the log
data space) is stored here; below we talk about tablespaces, but also
the ib_logfiles form a 'space' and it is handled here */

osku's avatar
osku committed
245
struct fil_system_struct {
246
#ifndef UNIV_HOTBACKUP
247
	mutex_t		mutex;		/*!< The mutex protecting the cache */
248
#endif /* !UNIV_HOTBACKUP */
249
	hash_table_t*	spaces;		/*!< The hash table of spaces in the
osku's avatar
osku committed
250 251
					system; they are hashed on the space
					id */
252
	hash_table_t*	name_hash;	/*!< hash table based on the space
osku's avatar
osku committed
253 254
					name */
	UT_LIST_BASE_NODE_T(fil_node_t) LRU;
255
					/*!< base node for the LRU list of the
osku's avatar
osku committed
256 257 258 259 260 261 262 263 264
					most recently used open files with no
					pending i/o's; if we start an i/o on
					the file, we first remove it from this
					list, and return it to the start of
					the list when the i/o ends;
					log files and the system tablespace are
					not put to this list: they are opened
					after the startup, and kept open until
					shutdown */
265
	UT_LIST_BASE_NODE_T(fil_space_t) unflushed_spaces;
266
					/*!< base node for the list of those
267 268 269 270
					tablespaces whose files contain
					unflushed writes; those spaces have
					at least one file node where
					modification_counter > flush_counter */
271 272
	ulint		n_open;		/*!< number of files currently open */
	ulint		max_n_open;	/*!< n_open is not allowed to exceed
osku's avatar
osku committed
273
					this */
274
	ib_int64_t	modification_counter;/*!< when we write to a file we
osku's avatar
osku committed
275
					increment this by one */
276
	ulint		max_assigned_id;/*!< maximum space id in the existing
osku's avatar
osku committed
277 278 279 280 281
					tables, or assigned during the time
					mysqld has been up; at an InnoDB
					startup we scan the data dictionary
					and set here the maximum of the
					space id's of the tables there */
282
	ib_int64_t	tablespace_version;
283
					/*!< a counter which is incremented for
osku's avatar
osku committed
284 285 286 287 288 289 290
					every space object memory creation;
					every space mem object gets a
					'timestamp' from this; in DISCARD/
					IMPORT this is used to check if we
					should ignore an insert buffer merge
					request */
	UT_LIST_BASE_NODE_T(fil_space_t) space_list;
291
					/*!< list of all file spaces */
292 293 294 295
	ibool		space_id_reuse_warned;
					/* !< TRUE if fil_space_create()
					has issued a warning about
					potential space_id reuse */
osku's avatar
osku committed
296 297
};

298
/** The tablespace memory cache. This variable is NULL before the module is
osku's avatar
osku committed
299
initialized. */
300
static fil_system_t*	fil_system	= NULL;
osku's avatar
osku committed
301 302


303
/********************************************************************//**
osku's avatar
osku committed
304 305 306 307 308 309 310 311 312 313
NOTE: you must call fil_mutex_enter_and_prepare_for_io() first!

Prepares a file node for i/o. Opens the file if it is closed. Updates the
pending i/o's field in the node and the system appropriately. Takes the node
off the LRU list if it is in the LRU list. The caller must hold the fil_sys
mutex. */
static
void
fil_node_prepare_for_io(
/*====================*/
314 315 316
	fil_node_t*	node,	/*!< in: file node */
	fil_system_t*	system,	/*!< in: tablespace memory cache */
	fil_space_t*	space);	/*!< in: space */
317
/********************************************************************//**
osku's avatar
osku committed
318 319 320 321 322 323
Updates the data structures when an i/o operation finishes. Updates the
pending i/o's field in the node appropriately. */
static
void
fil_node_complete_io(
/*=================*/
324 325 326
	fil_node_t*	node,	/*!< in: file node */
	fil_system_t*	system,	/*!< in: tablespace memory cache */
	ulint		type);	/*!< in: OS_FILE_WRITE or OS_FILE_READ; marks
osku's avatar
osku committed
327 328
				the node as modified if
				type == OS_FILE_WRITE */
329
/*******************************************************************//**
osku's avatar
osku committed
330
Checks if a single-table tablespace for a given table name exists in the
331 332
tablespace memory cache.
@return	space id, ULINT_UNDEFINED if not found */
osku's avatar
osku committed
333 334 335 336
static
ulint
fil_get_space_id_for_table(
/*=======================*/
337
	const char*	name);	/*!< in: table name in the standard
osku's avatar
osku committed
338
				'databasename/tablename' format */
339 340 341
/*******************************************************************//**
Frees a space object from the tablespace memory cache. Closes the files in
the chain but does not delete them. There must not be any pending i/o's or
342 343
flushes on the files.
@return TRUE on success */
344 345 346 347
static
ibool
fil_space_free(
/*===========*/
348 349 350
	ulint		id,		/* in: space id */
	ibool		x_latched);	/* in: TRUE if caller has space->latch
					in X mode */
351
/********************************************************************//**
352 353
Reads data from a space to a buffer. Remember that the possible incomplete
blocks at the end of file are ignored: they are not taken into account when
354
calculating the byte offset within a space.
355 356
@return DB_SUCCESS, or DB_TABLESPACE_DELETED if we are trying to do
i/o on a tablespace which does not exist */
357 358 359 360
UNIV_INLINE
ulint
fil_read(
/*=====*/
361 362 363
	ibool	sync,		/*!< in: TRUE if synchronous aio is desired */
	ulint	space_id,	/*!< in: space id */
	ulint	zip_size,	/*!< in: compressed page size in bytes;
364
				0 for uncompressed pages */
365 366
	ulint	block_offset,	/*!< in: offset in number of blocks */
	ulint	byte_offset,	/*!< in: remainder of offset in bytes; in aio
367
				this must be divisible by the OS block size */
368
	ulint	len,		/*!< in: how many bytes to read; this must not
369 370
				cross a file boundary; in aio this must be a
				block size multiple */
371
	void*	buf,		/*!< in/out: buffer where to store data read;
372
				in aio this must be appropriately aligned */
373
	void*	message)	/*!< in: message for aio handler if non-sync
374 375 376 377 378 379
				aio used, else ignored */
{
	return(fil_io(OS_FILE_READ, sync, space_id, zip_size, block_offset,
					  byte_offset, len, buf, message));
}

380
/********************************************************************//**
381 382
Writes data to a space from a buffer. Remember that the possible incomplete
blocks at the end of file are ignored: they are not taken into account when
383
calculating the byte offset within a space.
384 385
@return DB_SUCCESS, or DB_TABLESPACE_DELETED if we are trying to do
i/o on a tablespace which does not exist */
386 387 388 389
UNIV_INLINE
ulint
fil_write(
/*======*/
390 391 392
	ibool	sync,		/*!< in: TRUE if synchronous aio is desired */
	ulint	space_id,	/*!< in: space id */
	ulint	zip_size,	/*!< in: compressed page size in bytes;
393
				0 for uncompressed pages */
394 395
	ulint	block_offset,	/*!< in: offset in number of blocks */
	ulint	byte_offset,	/*!< in: remainder of offset in bytes; in aio
396
				this must be divisible by the OS block size */
397
	ulint	len,		/*!< in: how many bytes to write; this must
398 399
				not cross a file boundary; in aio this must
				be a block size multiple */
400
	void*	buf,		/*!< in: buffer from which to write; in aio
401
				this must be appropriately aligned */
402
	void*	message)	/*!< in: message for aio handler if non-sync
403 404 405 406 407
				aio used, else ignored */
{
	return(fil_io(OS_FILE_WRITE, sync, space_id, zip_size, block_offset,
					   byte_offset, len, buf, message));
}
osku's avatar
osku committed
408

409
/*******************************************************************//**
410 411 412 413 414
Returns the table space by a given id, NULL if not found. */
UNIV_INLINE
fil_space_t*
fil_space_get_by_id(
/*================*/
415
	ulint	id)	/*!< in: space id */
416 417 418 419 420 421
{
	fil_space_t*	space;

	ut_ad(mutex_own(&fil_system->mutex));

	HASH_SEARCH(hash, fil_system->spaces, id,
422 423 424
		    fil_space_t*, space,
		    ut_ad(space->magic_n == FIL_SPACE_MAGIC_N),
		    space->id == id);
425 426 427 428

	return(space);
}

429
/*******************************************************************//**
430 431 432 433 434
Returns the table space by a given name, NULL if not found. */
UNIV_INLINE
fil_space_t*
fil_space_get_by_name(
/*==================*/
435
	const char*	name)	/*!< in: space name */
436 437 438 439 440 441 442 443 444
{
	fil_space_t*	space;
	ulint		fold;

	ut_ad(mutex_own(&fil_system->mutex));

	fold = ut_fold_string(name);

	HASH_SEARCH(name_hash, fil_system->name_hash, fold,
445 446 447
		    fil_space_t*, space,
		    ut_ad(space->magic_n == FIL_SPACE_MAGIC_N),
		    !strcmp(name, space->name));
448 449 450

	return(space);
}
osku's avatar
osku committed
451

452
#ifndef UNIV_HOTBACKUP
453
/*******************************************************************//**
454
Returns the version number of a tablespace, -1 if not found.
455 456
@return version number, -1 if the tablespace does not exist in the
memory cache */
457
UNIV_INTERN
458
ib_int64_t
osku's avatar
osku committed
459 460
fil_space_get_version(
/*==================*/
461
	ulint	id)	/*!< in: space id */
osku's avatar
osku committed
462 463
{
	fil_space_t*	space;
464
	ib_int64_t	version		= -1;
osku's avatar
osku committed
465

466
	ut_ad(fil_system);
osku's avatar
osku committed
467

468
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
469

470
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
471 472 473 474 475

	if (space) {
		version = space->tablespace_version;
	}

476
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
477 478 479 480

	return(version);
}

481
/*******************************************************************//**
482 483
Returns the latch of a file space.
@return	latch protecting storage allocation */
484
UNIV_INTERN
osku's avatar
osku committed
485 486 487
rw_lock_t*
fil_space_get_latch(
/*================*/
488 489
	ulint	id,	/*!< in: space id */
	ulint*	flags)	/*!< out: tablespace flags */
osku's avatar
osku committed
490 491 492
{
	fil_space_t*	space;

493
	ut_ad(fil_system);
osku's avatar
osku committed
494

495
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
496

497
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
498 499 500

	ut_a(space);

501 502
	if (flags) {
		*flags = space->flags;
503 504
	}

505
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
506 507 508 509

	return(&(space->latch));
}

510
/*******************************************************************//**
511 512
Returns the type of a file space.
@return	FIL_TABLESPACE or FIL_LOG */
513
UNIV_INTERN
osku's avatar
osku committed
514 515 516
ulint
fil_space_get_type(
/*===============*/
517
	ulint	id)	/*!< in: space id */
osku's avatar
osku committed
518 519 520
{
	fil_space_t*	space;

521
	ut_ad(fil_system);
osku's avatar
osku committed
522

523
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
524

525
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
526 527 528

	ut_a(space);

529
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
530 531 532

	return(space->purpose);
}
533
#endif /* !UNIV_HOTBACKUP */
osku's avatar
osku committed
534

535
/**********************************************************************//**
536
Checks if all the file nodes in a space are flushed. The caller must hold
537 538
the fil_system mutex.
@return	TRUE if all are flushed */
539 540 541 542
static
ibool
fil_space_is_flushed(
/*=================*/
543
	fil_space_t*	space)	/*!< in: space */
544 545 546
{
	fil_node_t*	node;

547
	ut_ad(mutex_own(&fil_system->mutex));
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

	node = UT_LIST_GET_FIRST(space->chain);

	while (node) {
		if (node->modification_counter > node->flush_counter) {

			return(FALSE);
		}

		node = UT_LIST_GET_NEXT(chain, node);
	}

	return(TRUE);
}

563
/*******************************************************************//**
osku's avatar
osku committed
564
Appends a new file to the chain of files of a space. File must be closed. */
565
UNIV_INTERN
osku's avatar
osku committed
566 567 568
void
fil_node_create(
/*============*/
569 570
	const char*	name,	/*!< in: file name (file must be closed) */
	ulint		size,	/*!< in: file size in database blocks, rounded
osku's avatar
osku committed
571
				downwards to an integer */
572 573
	ulint		id,	/*!< in: space id where to append */
	ibool		is_raw)	/*!< in: TRUE if a raw device or
osku's avatar
osku committed
574 575 576 577 578
				a raw disk partition */
{
	fil_node_t*	node;
	fil_space_t*	space;

579
	ut_a(fil_system);
osku's avatar
osku committed
580 581
	ut_a(name);

582
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

	node = mem_alloc(sizeof(fil_node_t));

	node->name = mem_strdup(name);
	node->open = FALSE;

	ut_a(!is_raw || srv_start_raw_disk_in_use);

	node->is_raw_disk = is_raw;
	node->size = size;
	node->magic_n = FIL_NODE_MAGIC_N;
	node->n_pending = 0;
	node->n_pending_flushes = 0;

	node->modification_counter = 0;
	node->flush_counter = 0;
599

600
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
601 602 603 604

	if (!space) {
		ut_print_timestamp(stderr);
		fprintf(stderr,
605 606
			"  InnoDB: Error: Could not find tablespace %lu for\n"
			"InnoDB: file ", (ulong) id);
osku's avatar
osku committed
607 608 609 610 611 612
		ut_print_filename(stderr, name);
		fputs(" in the tablespace memory cache.\n", stderr);
		mem_free(node->name);

		mem_free(node);

613
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
614 615 616 617 618 619 620 621 622

		return;
	}

	space->size += size;

	node->space = space;

	UT_LIST_ADD_LAST(chain, space->chain, node);
623

624 625 626 627 628
	if (id < SRV_LOG_SPACE_FIRST_ID && fil_system->max_assigned_id < id) {

		fil_system->max_assigned_id = id;
	}

629
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
630 631
}

632
/********************************************************************//**
osku's avatar
osku committed
633 634 635 636 637 638
Opens a the file of a node of a tablespace. The caller must own the fil_system
mutex. */
static
void
fil_node_open_file(
/*===============*/
639 640 641
	fil_node_t*	node,	/*!< in: file node */
	fil_system_t*	system,	/*!< in: tablespace memory cache */
	fil_space_t*	space)	/*!< in: space */
osku's avatar
osku committed
642
{
643
	ib_int64_t	size_bytes;
osku's avatar
osku committed
644 645 646
	ulint		size_low;
	ulint		size_high;
	ibool		ret;
647
	ibool		success;
osku's avatar
osku committed
648 649 650
	byte*		buf2;
	byte*		page;
	ulint		space_id;
651
	ulint		flags;
osku's avatar
osku committed
652 653 654 655 656 657 658 659 660 661 662 663 664 665

	ut_ad(mutex_own(&(system->mutex)));
	ut_a(node->n_pending == 0);
	ut_a(node->open == FALSE);

	if (node->size == 0) {
		/* It must be a single-table tablespace and we do not know the
		size of the file yet. First we open the file in the normal
		mode, no async I/O here, for simplicity. Then do some checks,
		and close the file again.
		NOTE that we could not use the simple file read function
		os_file_read() in Windows to read from a file opened for
		async I/O! */

666
		node->handle = os_file_create_simple_no_error_handling(
667 668
			innodb_file_data_key, node->name, OS_FILE_OPEN,
			OS_FILE_READ_ONLY, &success);
osku's avatar
osku committed
669 670 671 672 673 674 675
		if (!success) {
			/* The following call prints an error message */
			os_file_get_last_error(TRUE);

			ut_print_timestamp(stderr);

			fprintf(stderr,
676 677 678
				"  InnoDB: Fatal error: cannot open %s\n."
				"InnoDB: Have you deleted .ibd files"
				" under a running mysqld server?\n",
osku's avatar
osku committed
679 680 681 682 683 684
				node->name);
			ut_a(0);
		}

		os_file_get_size(node->handle, &size_low, &size_high);

685 686
		size_bytes = (((ib_int64_t)size_high) << 32)
			+ (ib_int64_t)size_low;
osku's avatar
osku committed
687
#ifdef UNIV_HOTBACKUP
688 689 690 691 692 693
		if (space->id == 0) {
			node->size = (ulint) (size_bytes / UNIV_PAGE_SIZE);
			os_file_close(node->handle);
			goto add_size;
		}
#endif /* UNIV_HOTBACKUP */
694 695 696
		ut_a(space->purpose != FIL_LOG);
		ut_a(space->id != 0);

osku's avatar
osku committed
697
		if (size_bytes < FIL_IBD_FILE_INITIAL_SIZE * UNIV_PAGE_SIZE) {
698
			fprintf(stderr,
699 700 701 702 703 704 705 706 707
				"InnoDB: Error: the size of single-table"
				" tablespace file %s\n"
				"InnoDB: is only %lu %lu,"
				" should be at least %lu!\n",
				node->name,
				(ulong) size_high,
				(ulong) size_low,
				(ulong) (FIL_IBD_FILE_INITIAL_SIZE
					 * UNIV_PAGE_SIZE));
708

osku's avatar
osku committed
709 710 711 712 713 714 715 716 717 718 719
			ut_a(0);
		}

		/* Read the first page of the tablespace */

		buf2 = ut_malloc(2 * UNIV_PAGE_SIZE);
		/* Align the memory for file i/o if we might have O_DIRECT
		set */
		page = ut_align(buf2, UNIV_PAGE_SIZE);

		success = os_file_read(node->handle, page, 0, 0,
720
				       UNIV_PAGE_SIZE);
osku's avatar
osku committed
721
		space_id = fsp_header_get_space_id(page);
722
		flags = fsp_header_get_flags(page);
osku's avatar
osku committed
723 724

		ut_free(buf2);
725

osku's avatar
osku committed
726 727 728 729
		/* Close the file now that we have read the space id from it */

		os_file_close(node->handle);

730
		if (UNIV_UNLIKELY(space_id != space->id)) {
731
			fprintf(stderr,
732 733 734 735
				"InnoDB: Error: tablespace id is %lu"
				" in the data dictionary\n"
				"InnoDB: but in file %s it is %lu!\n",
				space->id, node->name, space_id);
osku's avatar
osku committed
736

737 738 739 740 741 742 743 744 745 746 747
			ut_error;
		}

		if (UNIV_UNLIKELY(space_id == ULINT_UNDEFINED
				  || space_id == 0)) {
			fprintf(stderr,
				"InnoDB: Error: tablespace id %lu"
				" in file %s is not sensible\n",
				(ulong) space_id, node->name);

			ut_error;
osku's avatar
osku committed
748 749
		}

750
		if (UNIV_UNLIKELY(space->flags != flags)) {
751
			fprintf(stderr,
752
				"InnoDB: Error: table flags are %lx"
753
				" in the data dictionary\n"
754 755
				"InnoDB: but the flags in file %s are %lx!\n",
				space->flags, node->name, flags);
756 757 758 759

			ut_error;
		}

760 761 762 763 764
		if (size_bytes >= 1024 * 1024) {
			/* Truncate the size to whole megabytes. */
			size_bytes = ut_2pow_round(size_bytes, 1024 * 1024);
		}

765
		if (!(flags & DICT_TF_ZSSIZE_MASK)) {
osku's avatar
osku committed
766
			node->size = (ulint) (size_bytes / UNIV_PAGE_SIZE);
767
		} else {
768 769 770
			node->size = (ulint)
				(size_bytes
				 / dict_table_flags_to_zip_size(flags));
osku's avatar
osku committed
771
		}
772 773 774 775

#ifdef UNIV_HOTBACKUP
add_size:
#endif /* UNIV_HOTBACKUP */
osku's avatar
osku committed
776 777 778 779 780 781 782 783 784
		space->size += node->size;
	}

	/* printf("Opening file %s\n", node->name); */

	/* Open the file for reading and writing, in Windows normally in the
	unbuffered async I/O mode, though global variables may make
	os_file_create() to fall back to the normal file I/O mode. */

785
	if (space->purpose == FIL_LOG) {
786 787 788 789
		node->handle = os_file_create(innodb_file_log_key,
					      node->name, OS_FILE_OPEN,
					      OS_FILE_AIO, OS_LOG_FILE,
					      &ret);
osku's avatar
osku committed
790
	} else if (node->is_raw_disk) {
791 792
		node->handle = os_file_create(innodb_file_data_key,
					      node->name,
793
					      OS_FILE_OPEN_RAW,
794 795
					      OS_FILE_AIO, OS_DATA_FILE,
						     &ret);
osku's avatar
osku committed
796
	} else {
797 798 799 800
		node->handle = os_file_create(innodb_file_data_key,
					      node->name, OS_FILE_OPEN,
					      OS_FILE_AIO, OS_DATA_FILE,
					      &ret);
osku's avatar
osku committed
801
	}
802

osku's avatar
osku committed
803
	ut_a(ret);
804

osku's avatar
osku committed
805 806 807 808 809 810 811 812 813 814
	node->open = TRUE;

	system->n_open++;

	if (space->purpose == FIL_TABLESPACE && space->id != 0) {
		/* Put the node to the LRU list */
		UT_LIST_ADD_FIRST(LRU, system->LRU, node);
	}
}

815
/**********************************************************************//**
osku's avatar
osku committed
816 817 818 819 820
Closes a file. */
static
void
fil_node_close_file(
/*================*/
821 822
	fil_node_t*	node,	/*!< in: file node */
	fil_system_t*	system)	/*!< in: tablespace memory cache */
osku's avatar
osku committed
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
{
	ibool	ret;

	ut_ad(node && system);
	ut_ad(mutex_own(&(system->mutex)));
	ut_a(node->open);
	ut_a(node->n_pending == 0);
	ut_a(node->n_pending_flushes == 0);
	ut_a(node->modification_counter == node->flush_counter);

	ret = os_file_close(node->handle);
	ut_a(ret);

	/* printf("Closing file %s\n", node->name); */

	node->open = FALSE;
	ut_a(system->n_open > 0);
	system->n_open--;

	if (node->space->purpose == FIL_TABLESPACE && node->space->id != 0) {
		ut_a(UT_LIST_GET_LEN(system->LRU) > 0);

		/* The node is in the LRU list, remove it */
		UT_LIST_REMOVE(LRU, system->LRU, node);
	}
}

850
/********************************************************************//**
osku's avatar
osku committed
851
Tries to close a file in the LRU list. The caller must hold the fil_sys
852
mutex.
853 854 855 856 857
@return TRUE if success, FALSE if should retry later; since i/o's
generally complete in < 100 ms, and as InnoDB writes at most 128 pages
from the buffer pool in a batch, and then immediately flushes the
files, there is a good chance that the next time we find a suitable
node from the LRU list */
osku's avatar
osku committed
858 859 860 861
static
ibool
fil_try_to_close_file_in_LRU(
/*=========================*/
862
	ibool	print_info)	/*!< in: if TRUE, prints information why it
osku's avatar
osku committed
863 864 865 866
				cannot close a file */
{
	fil_node_t*	node;

867
	ut_ad(mutex_own(&fil_system->mutex));
868

869
	node = UT_LIST_GET_LAST(fil_system->LRU);
osku's avatar
osku committed
870 871 872

	if (print_info) {
		fprintf(stderr,
873
			"InnoDB: fil_sys open file LRU len %lu\n",
874
			(ulong) UT_LIST_GET_LEN(fil_system->LRU));
osku's avatar
osku committed
875 876 877 878
	}

	while (node != NULL) {
		if (node->modification_counter == node->flush_counter
879
		    && node->n_pending_flushes == 0) {
osku's avatar
osku committed
880

881
			fil_node_close_file(node, fil_system);
882

osku's avatar
osku committed
883 884
			return(TRUE);
		}
885

osku's avatar
osku committed
886 887 888 889
		if (print_info && node->n_pending_flushes > 0) {
			fputs("InnoDB: cannot close file ", stderr);
			ut_print_filename(stderr, node->name);
			fprintf(stderr, ", because n_pending_flushes %lu\n",
890
				(ulong) node->n_pending_flushes);
osku's avatar
osku committed
891 892 893
		}

		if (print_info
894
		    && node->modification_counter != node->flush_counter) {
osku's avatar
osku committed
895 896 897 898 899 900 901 902 903 904 905 906 907 908
			fputs("InnoDB: cannot close file ", stderr);
			ut_print_filename(stderr, node->name);
			fprintf(stderr,
				", because mod_count %ld != fl_count %ld\n",
				(long) node->modification_counter,
				(long) node->flush_counter);
		}

		node = UT_LIST_GET_PREV(LRU, node);
	}

	return(FALSE);
}

909
/*******************************************************************//**
osku's avatar
osku committed
910 911 912 913 914 915 916
Reserves the fil_system mutex and tries to make sure we can open at least one
file while holding it. This should be called before calling
fil_node_prepare_for_io(), because that function may need to open a file. */
static
void
fil_mutex_enter_and_prepare_for_io(
/*===============================*/
917
	ulint	space_id)	/*!< in: space id */
osku's avatar
osku committed
918 919 920 921 922 923 924 925
{
	fil_space_t*	space;
	ibool		success;
	ibool		print_info	= FALSE;
	ulint		count		= 0;
	ulint		count2		= 0;

retry:
926
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
927 928 929 930 931 932 933 934 935 936 937

	if (space_id == 0 || space_id >= SRV_LOG_SPACE_FIRST_ID) {
		/* We keep log files and system tablespace files always open;
		this is important in preventing deadlocks in this module, as
		a page read completion often performs another read from the
		insert buffer. The insert buffer is in tablespace 0, and we
		cannot end up waiting in this function. */

		return;
	}

938
	if (fil_system->n_open < fil_system->max_n_open) {
osku's avatar
osku committed
939 940 941 942

		return;
	}

943 944
	space = fil_space_get_by_id(space_id);

osku's avatar
osku committed
945 946 947 948 949 950 951 952 953 954 955 956
	if (space != NULL && space->stop_ios) {
		/* We are going to do a rename file and want to stop new i/o's
		for a while */

		if (count2 > 20000) {
			fputs("InnoDB: Warning: tablespace ", stderr);
			ut_print_filename(stderr, space->name);
			fprintf(stderr,
				" has i/o ops stopped for a long time %lu\n",
				(ulong) count2);
		}

957
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

		os_thread_sleep(20000);

		count2++;

		goto retry;
	}

	/* If the file is already open, no need to do anything; if the space
	does not exist, we handle the situation in the function which called
	this function */

	if (!space || UT_LIST_GET_FIRST(space->chain)->open) {

		return;
	}

	if (count > 1) {
		print_info = TRUE;
	}

	/* Too many files are open, try to close some */
close_more:
	success = fil_try_to_close_file_in_LRU(print_info);

983
	if (success && fil_system->n_open >= fil_system->max_n_open) {
osku's avatar
osku committed
984 985 986 987

		goto close_more;
	}

988
	if (fil_system->n_open < fil_system->max_n_open) {
osku's avatar
osku committed
989 990 991 992 993 994 995 996
		/* Ok */

		return;
	}

	if (count >= 2) {
		ut_print_timestamp(stderr);
		fprintf(stderr,
997 998 999 1000
			"  InnoDB: Warning: too many (%lu) files stay open"
			" while the maximum\n"
			"InnoDB: allowed value would be %lu.\n"
			"InnoDB: You may need to raise the value of"
1001
			" innodb_open_files in\n"
1002
			"InnoDB: my.cnf.\n",
1003 1004
			(ulong) fil_system->n_open,
			(ulong) fil_system->max_n_open);
osku's avatar
osku committed
1005 1006 1007 1008

		return;
	}

1009
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

#ifndef UNIV_HOTBACKUP
	/* Wake the i/o-handler threads to make sure pending i/o's are
	performed */
	os_aio_simulated_wake_handler_threads();

	os_thread_sleep(20000);
#endif
	/* Flush tablespaces so that we can close modified files in the LRU
	list */

1021
	fil_flush_file_spaces(FIL_TABLESPACE);
osku's avatar
osku committed
1022 1023 1024 1025 1026 1027

	count++;

	goto retry;
}

1028
/*******************************************************************//**
osku's avatar
osku committed
1029 1030 1031 1032 1033
Frees a file node object from a tablespace memory cache. */
static
void
fil_node_free(
/*==========*/
1034 1035 1036
	fil_node_t*	node,	/*!< in, own: file node */
	fil_system_t*	system,	/*!< in: tablespace memory cache */
	fil_space_t*	space)	/*!< in: space where the file node is chained */
osku's avatar
osku committed
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
{
	ut_ad(node && system && space);
	ut_ad(mutex_own(&(system->mutex)));
	ut_a(node->magic_n == FIL_NODE_MAGIC_N);
	ut_a(node->n_pending == 0);

	if (node->open) {
		/* We fool the assertion in fil_node_close_file() to think
		there are no unflushed modifications in the file */

		node->modification_counter = node->flush_counter;

1049
		if (space->is_in_unflushed_spaces
1050
		    && fil_space_is_flushed(space)) {
1051 1052 1053 1054

			space->is_in_unflushed_spaces = FALSE;

			UT_LIST_REMOVE(unflushed_spaces,
1055 1056
				       system->unflushed_spaces,
				       space);
1057 1058
		}

osku's avatar
osku committed
1059 1060 1061 1062
		fil_node_close_file(node, system);
	}

	space->size -= node->size;
1063

osku's avatar
osku committed
1064 1065 1066 1067 1068 1069
	UT_LIST_REMOVE(chain, space->chain, node);

	mem_free(node->name);
	mem_free(node);
}

1070
#ifdef UNIV_LOG_ARCHIVE
1071
/****************************************************************//**
osku's avatar
osku committed
1072 1073
Drops files from the start of a file space, so that its size is cut by
the amount given. */
1074
UNIV_INTERN
osku's avatar
osku committed
1075 1076 1077
void
fil_space_truncate_start(
/*=====================*/
1078 1079
	ulint	id,		/*!< in: space id */
	ulint	trunc_len)	/*!< in: truncate by this much; it is an error
osku's avatar
osku committed
1080 1081 1082 1083 1084 1085
				if this does not equal to the combined size of
				some initial files in the space */
{
	fil_node_t*	node;
	fil_space_t*	space;

1086
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
1087

1088
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
1089 1090

	ut_a(space);
1091

osku's avatar
osku committed
1092 1093 1094
	while (trunc_len > 0) {
		node = UT_LIST_GET_FIRST(space->chain);

1095
		ut_a(node->size * UNIV_PAGE_SIZE <= trunc_len);
osku's avatar
osku committed
1096 1097 1098

		trunc_len -= node->size * UNIV_PAGE_SIZE;

1099
		fil_node_free(node, fil_system, space);
1100 1101
	}

1102
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1103
}
1104
#endif /* UNIV_LOG_ARCHIVE */
osku's avatar
osku committed
1105

1106
/*******************************************************************//**
osku's avatar
osku committed
1107
Creates a space memory object and puts it to the tablespace memory cache. If
1108 1109
there is an error, prints an error message to the .err log.
@return	TRUE if success */
1110
UNIV_INTERN
osku's avatar
osku committed
1111 1112 1113
ibool
fil_space_create(
/*=============*/
1114 1115 1116
	const char*	name,	/*!< in: space name */
	ulint		id,	/*!< in: space id */
	ulint		flags,	/*!< in: compressed page size
1117
				and file format, or 0 */
1118
	ulint		purpose)/*!< in: FIL_TABLESPACE, or FIL_LOG if log */
osku's avatar
osku committed
1119
{
1120
	fil_space_t*	space;
1121 1122

	/* The tablespace flags (FSP_SPACE_FLAGS) should be 0 for
1123 1124
	ROW_FORMAT=COMPACT
	((table->flags & ~(~0 << DICT_TF_BITS)) == DICT_TF_COMPACT) and
1125
	ROW_FORMAT=REDUNDANT (table->flags == 0).  For any other
1126 1127
	format, the tablespace flags should equal
	(table->flags & ~(~0 << DICT_TF_BITS)). */
1128
	ut_a(flags != DICT_TF_COMPACT);
1129
	ut_a(!(flags & (~0UL << DICT_TF_BITS)));
1130

osku's avatar
osku committed
1131 1132 1133
try_again:
	/*printf(
	"InnoDB: Adding tablespace %lu of name %s, purpose %lu\n", id, name,
1134
	purpose);*/
osku's avatar
osku committed
1135

1136
	ut_a(fil_system);
osku's avatar
osku committed
1137 1138
	ut_a(name);

1139
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
1140

1141 1142
	space = fil_space_get_by_name(name);

1143
	if (UNIV_LIKELY_NULL(space)) {
1144
		ibool	success;
1145 1146
		ulint	namesake_id;

osku's avatar
osku committed
1147 1148
		ut_print_timestamp(stderr);
		fprintf(stderr,
1149 1150 1151
			"  InnoDB: Warning: trying to init to the"
			" tablespace memory cache\n"
			"InnoDB: a tablespace %lu of name ", (ulong) id);
osku's avatar
osku committed
1152 1153
		ut_print_filename(stderr, name);
		fprintf(stderr, ",\n"
1154 1155 1156
			"InnoDB: but a tablespace %lu of the same name\n"
			"InnoDB: already exists in the"
			" tablespace memory cache!\n",
osku's avatar
osku committed
1157 1158 1159 1160
			(ulong) space->id);

		if (id == 0 || purpose != FIL_TABLESPACE) {

1161
			mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1162 1163 1164 1165 1166

			return(FALSE);
		}

		fprintf(stderr,
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
			"InnoDB: We assume that InnoDB did a crash recovery,"
			" and you had\n"
			"InnoDB: an .ibd file for which the table"
			" did not exist in the\n"
			"InnoDB: InnoDB internal data dictionary in the"
			" ibdata files.\n"
			"InnoDB: We assume that you later removed the"
			" .ibd and .frm files,\n"
			"InnoDB: and are now trying to recreate the table."
			" We now remove the\n"
			"InnoDB: conflicting tablespace object"
			" from the memory cache and try\n"
			"InnoDB: the init again.\n");
osku's avatar
osku committed
1180 1181 1182

		namesake_id = space->id;

1183 1184
		success = fil_space_free(namesake_id, FALSE);
		ut_a(success);
osku's avatar
osku committed
1185

1186
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1187 1188 1189 1190

		goto try_again;
	}

1191
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
1192

1193
	if (UNIV_LIKELY_NULL(space)) {
osku's avatar
osku committed
1194
		fprintf(stderr,
1195 1196
			"InnoDB: Error: trying to add tablespace %lu"
			" of name ", (ulong) id);
osku's avatar
osku committed
1197 1198
		ut_print_filename(stderr, name);
		fprintf(stderr, "\n"
1199 1200 1201
			"InnoDB: to the tablespace memory cache,"
			" but tablespace\n"
			"InnoDB: %lu of name ", (ulong) space->id);
osku's avatar
osku committed
1202 1203
		ut_print_filename(stderr, space->name);
		fputs(" already exists in the tablespace\n"
1204
		      "InnoDB: memory cache!\n", stderr);
osku's avatar
osku committed
1205

1206
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1207 1208 1209 1210 1211 1212 1213 1214 1215

		return(FALSE);
	}

	space = mem_alloc(sizeof(fil_space_t));

	space->name = mem_strdup(name);
	space->id = id;

1216 1217
	fil_system->tablespace_version++;
	space->tablespace_version = fil_system->tablespace_version;
osku's avatar
osku committed
1218 1219
	space->mark = FALSE;

1220
	if (UNIV_LIKELY(purpose == FIL_TABLESPACE && !recv_recovery_on)
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
	    && UNIV_UNLIKELY(id > fil_system->max_assigned_id)) {
		if (!fil_system->space_id_reuse_warned) {
			fil_system->space_id_reuse_warned = TRUE;

			ut_print_timestamp(stderr);
			fprintf(stderr,
				"  InnoDB: Warning: allocated tablespace %lu,"
				" old maximum was %lu\n",
				(ulong) id,
				(ulong) fil_system->max_assigned_id);
		}

1233
		fil_system->max_assigned_id = id;
osku's avatar
osku committed
1234 1235 1236 1237 1238 1239 1240
	}

	space->stop_ios = FALSE;
	space->stop_ibuf_merges = FALSE;
	space->is_being_deleted = FALSE;
	space->purpose = purpose;
	space->size = 0;
1241
	space->flags = flags;
osku's avatar
osku committed
1242 1243

	space->n_reserved_extents = 0;
1244

osku's avatar
osku committed
1245 1246 1247 1248 1249 1250
	space->n_pending_flushes = 0;
	space->n_pending_ibuf_merges = 0;

	UT_LIST_INIT(space->chain);
	space->magic_n = FIL_SPACE_MAGIC_N;

1251
	rw_lock_create(fil_space_latch_key, &space->latch, SYNC_FSP);
1252

1253
	HASH_INSERT(fil_space_t, hash, fil_system->spaces, id, space);
osku's avatar
osku committed
1254

1255
	HASH_INSERT(fil_space_t, name_hash, fil_system->name_hash,
1256
		    ut_fold_string(name), space);
1257 1258
	space->is_in_unflushed_spaces = FALSE;

1259
	UT_LIST_ADD_LAST(space_list, fil_system->space_list, space);
1260

1261
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1262 1263 1264 1265

	return(TRUE);
}

1266
/*******************************************************************//**
osku's avatar
osku committed
1267 1268
Assigns a new space id for a new single-table tablespace. This works simply by
incrementing the global counter. If 4 billion id's is not enough, we may need
1269
to recycle id's.
1270 1271 1272 1273 1274 1275
@return	TRUE if assigned, FALSE if not */
UNIV_INTERN
ibool
fil_assign_new_space_id(
/*====================*/
	ulint*	space_id)	/*!< in/out: space id */
osku's avatar
osku committed
1276
{
1277 1278
	ulint	id;
	ibool	success;
osku's avatar
osku committed
1279

1280
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
1281

1282
	id = *space_id;
osku's avatar
osku committed
1283

1284 1285 1286 1287 1288
	if (id < fil_system->max_assigned_id) {
		id = fil_system->max_assigned_id;
	}

	id++;
osku's avatar
osku committed
1289 1290

	if (id > (SRV_LOG_SPACE_FIRST_ID / 2) && (id % 1000000UL == 0)) {
1291 1292
		ut_print_timestamp(stderr);
		fprintf(stderr,
1293 1294 1295 1296 1297 1298 1299 1300 1301
			"InnoDB: Warning: you are running out of new"
			" single-table tablespace id's.\n"
			"InnoDB: Current counter is %lu and it"
			" must not exceed %lu!\n"
			"InnoDB: To reset the counter to zero"
			" you have to dump all your tables and\n"
			"InnoDB: recreate the whole InnoDB installation.\n",
			(ulong) id,
			(ulong) SRV_LOG_SPACE_FIRST_ID);
osku's avatar
osku committed
1302 1303
	}

1304 1305 1306 1307 1308
	success = (id < SRV_LOG_SPACE_FIRST_ID);

	if (success) {
		*space_id = fil_system->max_assigned_id = id;
	} else {
1309 1310
		ut_print_timestamp(stderr);
		fprintf(stderr,
1311 1312 1313 1314 1315 1316 1317
			"InnoDB: You have run out of single-table"
			" tablespace id's!\n"
			"InnoDB: Current counter is %lu.\n"
			"InnoDB: To reset the counter to zero you"
			" have to dump all your tables and\n"
			"InnoDB: recreate the whole InnoDB installation.\n",
			(ulong) id);
1318
		*space_id = ULINT_UNDEFINED;
osku's avatar
osku committed
1319 1320
	}

1321
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1322

1323
	return(success);
osku's avatar
osku committed
1324 1325
}

1326
/*******************************************************************//**
osku's avatar
osku committed
1327 1328
Frees a space object from the tablespace memory cache. Closes the files in
the chain but does not delete them. There must not be any pending i/o's or
1329 1330
flushes on the files.
@return	TRUE if success */
1331
static
osku's avatar
osku committed
1332 1333 1334
ibool
fil_space_free(
/*===========*/
1335 1336
					/* out: TRUE if success */
	ulint		id,		/* in: space id */
1337 1338
	ibool		x_latched)	/* in: TRUE if caller has space->latch
					in X mode */
osku's avatar
osku committed
1339 1340 1341 1342 1343
{
	fil_space_t*	space;
	fil_space_t*	namespace;
	fil_node_t*	fil_node;

1344
	ut_ad(mutex_own(&fil_system->mutex));
osku's avatar
osku committed
1345

1346
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
1347 1348 1349 1350

	if (!space) {
		ut_print_timestamp(stderr);
		fprintf(stderr,
1351 1352 1353
			"  InnoDB: Error: trying to remove tablespace %lu"
			" from the cache but\n"
			"InnoDB: it is not there.\n", (ulong) id);
osku's avatar
osku committed
1354 1355 1356 1357

		return(FALSE);
	}

1358
	HASH_DELETE(fil_space_t, hash, fil_system->spaces, id, space);
osku's avatar
osku committed
1359

1360
	namespace = fil_space_get_by_name(space->name);
osku's avatar
osku committed
1361 1362 1363
	ut_a(namespace);
	ut_a(space == namespace);

1364
	HASH_DELETE(fil_space_t, name_hash, fil_system->name_hash,
1365
		    ut_fold_string(space->name), space);
osku's avatar
osku committed
1366

1367 1368 1369
	if (space->is_in_unflushed_spaces) {
		space->is_in_unflushed_spaces = FALSE;

1370
		UT_LIST_REMOVE(unflushed_spaces, fil_system->unflushed_spaces,
1371
			       space);
1372 1373
	}

1374
	UT_LIST_REMOVE(space_list, fil_system->space_list, space);
osku's avatar
osku committed
1375 1376 1377 1378 1379 1380 1381

	ut_a(space->magic_n == FIL_SPACE_MAGIC_N);
	ut_a(0 == space->n_pending_flushes);

	fil_node = UT_LIST_GET_FIRST(space->chain);

	while (fil_node != NULL) {
1382
		fil_node_free(fil_node, fil_system, space);
osku's avatar
osku committed
1383 1384

		fil_node = UT_LIST_GET_FIRST(space->chain);
1385 1386
	}

osku's avatar
osku committed
1387 1388
	ut_a(0 == UT_LIST_GET_LEN(space->chain));

1389 1390
	if (x_latched) {
		rw_lock_x_unlock(&space->latch);
1391
	}
osku's avatar
osku committed
1392 1393 1394 1395 1396 1397 1398 1399 1400

	rw_lock_free(&(space->latch));

	mem_free(space->name);
	mem_free(space);

	return(TRUE);
}

1401
/*******************************************************************//**
osku's avatar
osku committed
1402
Returns the size of the space in pages. The tablespace must be cached in the
1403 1404
memory cache.
@return	space size, 0 if space not found */
1405
UNIV_INTERN
osku's avatar
osku committed
1406 1407 1408
ulint
fil_space_get_size(
/*===============*/
1409
	ulint	id)	/*!< in: space id */
osku's avatar
osku committed
1410 1411 1412 1413 1414
{
	fil_node_t*	node;
	fil_space_t*	space;
	ulint		size;

1415
	ut_ad(fil_system);
osku's avatar
osku committed
1416 1417 1418

	fil_mutex_enter_and_prepare_for_io(id);

1419
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
1420 1421

	if (space == NULL) {
1422
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437

		return(0);
	}

	if (space->size == 0 && space->purpose == FIL_TABLESPACE) {
		ut_a(id != 0);

		ut_a(1 == UT_LIST_GET_LEN(space->chain));

		node = UT_LIST_GET_FIRST(space->chain);

		/* It must be a single-table tablespace and we have not opened
		the file yet; the following calls will open it and update the
		size fields */

1438 1439
		fil_node_prepare_for_io(node, fil_system, space);
		fil_node_complete_io(node, fil_system, OS_FILE_READ);
osku's avatar
osku committed
1440 1441 1442
	}

	size = space->size;
1443

1444
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1445 1446 1447 1448

	return(size);
}

1449
/*******************************************************************//**
1450
Returns the flags of the space. The tablespace must be cached
1451 1452
in the memory cache.
@return	flags, ULINT_UNDEFINED if space not found */
1453
UNIV_INTERN
1454
ulint
1455 1456
fil_space_get_flags(
/*================*/
1457
	ulint	id)	/*!< in: space id */
1458 1459 1460
{
	fil_node_t*	node;
	fil_space_t*	space;
1461
	ulint		flags;
1462

1463
	ut_ad(fil_system);
1464

1465 1466 1467 1468
	if (UNIV_UNLIKELY(!id)) {
		return(0);
	}

1469 1470
	fil_mutex_enter_and_prepare_for_io(id);

1471
	space = fil_space_get_by_id(id);
1472 1473

	if (space == NULL) {
1474
		mutex_exit(&fil_system->mutex);
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489

		return(ULINT_UNDEFINED);
	}

	if (space->size == 0 && space->purpose == FIL_TABLESPACE) {
		ut_a(id != 0);

		ut_a(1 == UT_LIST_GET_LEN(space->chain));

		node = UT_LIST_GET_FIRST(space->chain);

		/* It must be a single-table tablespace and we have not opened
		the file yet; the following calls will open it and update the
		size fields */

1490 1491
		fil_node_prepare_for_io(node, fil_system, space);
		fil_node_complete_io(node, fil_system, OS_FILE_READ);
1492 1493
	}

1494
	flags = space->flags;
1495

1496
	mutex_exit(&fil_system->mutex);
1497

1498 1499 1500
	return(flags);
}

1501
/*******************************************************************//**
1502
Returns the compressed page size of the space, or 0 if the space
1503 1504
is not compressed. The tablespace must be cached in the memory cache.
@return	compressed page size, ULINT_UNDEFINED if space not found */
1505 1506 1507 1508
UNIV_INTERN
ulint
fil_space_get_zip_size(
/*===================*/
1509
	ulint	id)	/*!< in: space id */
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
{
	ulint	flags;

	flags = fil_space_get_flags(id);

	if (flags && flags != ULINT_UNDEFINED) {

		return(dict_table_flags_to_zip_size(flags));
	}

	return(flags);
1521 1522
}

1523
/*******************************************************************//**
osku's avatar
osku committed
1524
Checks if the pair space, page_no refers to an existing page in a tablespace
1525 1526
file space. The tablespace must be cached in the memory cache.
@return	TRUE if the address is meaningful */
1527
UNIV_INTERN
osku's avatar
osku committed
1528 1529 1530
ibool
fil_check_adress_in_tablespace(
/*===========================*/
1531 1532
	ulint	id,	/*!< in: space id */
	ulint	page_no)/*!< in: page number */
osku's avatar
osku committed
1533 1534 1535 1536 1537 1538 1539
{
	if (fil_space_get_size(id) > page_no) {

		return(TRUE);
	}

	return(FALSE);
1540
}
osku's avatar
osku committed
1541

1542
/****************************************************************//**
1543 1544 1545 1546 1547
Initializes the tablespace memory cache. */
UNIV_INTERN
void
fil_init(
/*=====*/
1548 1549
	ulint	hash_size,	/*!< in: hash table size */
	ulint	max_n_open)	/*!< in: max number of open files */
osku's avatar
osku committed
1550
{
1551
	ut_a(fil_system == NULL);
osku's avatar
osku committed
1552 1553 1554 1555

	ut_a(hash_size > 0);
	ut_a(max_n_open > 0);

1556
	fil_system = mem_zalloc(sizeof(fil_system_t));
osku's avatar
osku committed
1557

1558 1559
	mutex_create(fil_system_mutex_key,
		     &fil_system->mutex, SYNC_ANY_LATCH);
osku's avatar
osku committed
1560

1561 1562
	fil_system->spaces = hash_create(hash_size);
	fil_system->name_hash = hash_create(hash_size);
osku's avatar
osku committed
1563

1564
	UT_LIST_INIT(fil_system->LRU);
osku's avatar
osku committed
1565

1566
	fil_system->max_n_open = max_n_open;
osku's avatar
osku committed
1567 1568
}

1569
/*******************************************************************//**
osku's avatar
osku committed
1570 1571 1572 1573 1574
Opens all log files and system tablespace data files. They stay open until the
database server shutdown. This should be called at a server startup after the
space objects for the log and the system tablespace have been created. The
purpose of this operation is to make sure we never run out of file descriptors
if we need to read from the insert buffer or to write to the log. */
1575
UNIV_INTERN
osku's avatar
osku committed
1576 1577 1578 1579 1580 1581 1582
void
fil_open_log_and_system_tablespace_files(void)
/*==========================================*/
{
	fil_space_t*	space;
	fil_node_t*	node;

1583
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
1584

1585
	space = UT_LIST_GET_FIRST(fil_system->space_list);
osku's avatar
osku committed
1586 1587 1588 1589 1590 1591 1592

	while (space != NULL) {
		if (space->purpose != FIL_TABLESPACE || space->id == 0) {
			node = UT_LIST_GET_FIRST(space->chain);

			while (node != NULL) {
				if (!node->open) {
1593
					fil_node_open_file(node, fil_system,
1594
							   space);
osku's avatar
osku committed
1595
				}
1596 1597
				if (fil_system->max_n_open
				    < 10 + fil_system->n_open) {
osku's avatar
osku committed
1598
					fprintf(stderr,
1599 1600
						"InnoDB: Warning: you must"
						" raise the value of"
1601
						" innodb_open_files in\n"
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
						"InnoDB: my.cnf! Remember that"
						" InnoDB keeps all log files"
						" and all system\n"
						"InnoDB: tablespace files open"
						" for the whole time mysqld is"
						" running, and\n"
						"InnoDB: needs to open also"
						" some .ibd files if the"
						" file-per-table storage\n"
						"InnoDB: model is used."
						" Current open files %lu,"
						" max allowed"
						" open files %lu.\n",
1615 1616
						(ulong) fil_system->n_open,
						(ulong) fil_system->max_n_open);
osku's avatar
osku committed
1617 1618 1619 1620 1621 1622 1623
				}
				node = UT_LIST_GET_NEXT(chain, node);
			}
		}
		space = UT_LIST_GET_NEXT(space_list, space);
	}

1624
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1625 1626
}

1627
/*******************************************************************//**
osku's avatar
osku committed
1628 1629
Closes all open files. There must not be any pending i/o's or not flushed
modifications in the files. */
1630
UNIV_INTERN
osku's avatar
osku committed
1631 1632 1633 1634 1635 1636
void
fil_close_all_files(void)
/*=====================*/
{
	fil_space_t*	space;

1637
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
1638

1639
	space = UT_LIST_GET_FIRST(fil_system->space_list);
osku's avatar
osku committed
1640 1641

	while (space != NULL) {
1642
		fil_node_t*	node;
1643 1644
		fil_space_t*	prev_space = space;

1645 1646 1647
		for (node = UT_LIST_GET_FIRST(space->chain);
		     node != NULL;
		     node = UT_LIST_GET_NEXT(chain, node)) {
osku's avatar
osku committed
1648 1649

			if (node->open) {
1650
				fil_node_close_file(node, fil_system);
osku's avatar
osku committed
1651 1652
			}
		}
1653

osku's avatar
osku committed
1654
		space = UT_LIST_GET_NEXT(space_list, space);
1655 1656

		fil_space_free(prev_space->id, FALSE);
osku's avatar
osku committed
1657 1658
	}

1659
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1660 1661
}

1662
/*******************************************************************//**
osku's avatar
osku committed
1663 1664
Sets the max tablespace id counter if the given number is bigger than the
previous value. */
1665
UNIV_INTERN
osku's avatar
osku committed
1666 1667 1668
void
fil_set_max_space_id_if_bigger(
/*===========================*/
1669
	ulint	max_id)	/*!< in: maximum known id */
osku's avatar
osku committed
1670 1671 1672
{
	if (max_id >= SRV_LOG_SPACE_FIRST_ID) {
		fprintf(stderr,
1673 1674
			"InnoDB: Fatal error: max tablespace id"
			" is too high, %lu\n", (ulong) max_id);
1675
		ut_error;
osku's avatar
osku committed
1676 1677
	}

1678
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
1679

1680
	if (fil_system->max_assigned_id < max_id) {
osku's avatar
osku committed
1681

1682
		fil_system->max_assigned_id = max_id;
osku's avatar
osku committed
1683 1684
	}

1685
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1686 1687
}

1688
/****************************************************************//**
osku's avatar
osku committed
1689
Writes the flushed lsn and the latest archived log number to the page header
1690 1691
of the first page of a data file of the system tablespace (space 0),
which is uncompressed. */
osku's avatar
osku committed
1692 1693 1694 1695
static
ulint
fil_write_lsn_and_arch_no_to_file(
/*==============================*/
1696
	ulint		sum_of_sizes,	/*!< in: combined size of previous files
1697
					in space, in database pages */
1698
	ib_uint64_t	lsn,		/*!< in: lsn to write */
1699
	ulint		arch_log_no __attribute__((unused)))
1700
					/*!< in: archived log number to write */
osku's avatar
osku committed
1701 1702 1703 1704 1705 1706 1707
{
	byte*	buf1;
	byte*	buf;

	buf1 = mem_alloc(2 * UNIV_PAGE_SIZE);
	buf = ut_align(buf1, UNIV_PAGE_SIZE);

1708
	fil_read(TRUE, 0, 0, sum_of_sizes, 0, UNIV_PAGE_SIZE, buf, NULL);
osku's avatar
osku committed
1709

1710
	mach_write_to_8(buf + FIL_PAGE_FILE_FLUSH_LSN, lsn);
osku's avatar
osku committed
1711

1712
	fil_write(TRUE, 0, 0, sum_of_sizes, 0, UNIV_PAGE_SIZE, buf, NULL);
osku's avatar
osku committed
1713

1714 1715
	mem_free(buf1);

1716
	return(DB_SUCCESS);
osku's avatar
osku committed
1717 1718
}

1719
/****************************************************************//**
osku's avatar
osku committed
1720
Writes the flushed lsn and the latest archived log number to the page
1721 1722
header of the first page of each data file in the system tablespace.
@return	DB_SUCCESS or error number */
1723
UNIV_INTERN
osku's avatar
osku committed
1724 1725 1726
ulint
fil_write_flushed_lsn_to_data_files(
/*================================*/
1727 1728
	ib_uint64_t	lsn,		/*!< in: lsn to write */
	ulint		arch_log_no)	/*!< in: latest archived log
1729
					file number */
osku's avatar
osku committed
1730 1731 1732 1733 1734 1735
{
	fil_space_t*	space;
	fil_node_t*	node;
	ulint		sum_of_sizes;
	ulint		err;

1736
	mutex_enter(&fil_system->mutex);
1737

osku's avatar
osku committed
1738
	space = UT_LIST_GET_FIRST(fil_system->space_list);
1739

osku's avatar
osku committed
1740 1741 1742 1743 1744 1745 1746 1747
	while (space) {
		/* We only write the lsn to all existing data files which have
		been open during the lifetime of the mysqld process; they are
		represented by the space objects in the tablespace memory
		cache. Note that all data files in the system tablespace 0 are
		always open. */

		if (space->purpose == FIL_TABLESPACE
1748
		    && space->id == 0) {
osku's avatar
osku committed
1749 1750 1751 1752
			sum_of_sizes = 0;

			node = UT_LIST_GET_FIRST(space->chain);
			while (node) {
1753
				mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1754

1755 1756
				err = fil_write_lsn_and_arch_no_to_file(
					sum_of_sizes, lsn, arch_log_no);
osku's avatar
osku committed
1757 1758 1759 1760 1761
				if (err != DB_SUCCESS) {

					return(err);
				}

1762
				mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
1763 1764 1765 1766 1767 1768 1769 1770

				sum_of_sizes += node->size;
				node = UT_LIST_GET_NEXT(chain, node);
			}
		}
		space = UT_LIST_GET_NEXT(space_list, space);
	}

1771
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1772 1773 1774 1775

	return(DB_SUCCESS);
}

1776
/*******************************************************************//**
osku's avatar
osku committed
1777 1778
Reads the flushed lsn and arch no fields from a data file at database
startup. */
1779
UNIV_INTERN
osku's avatar
osku committed
1780 1781 1782
void
fil_read_flushed_lsn_and_arch_log_no(
/*=================================*/
1783 1784
	os_file_t	data_file,		/*!< in: open data file */
	ibool		one_read_already,	/*!< in: TRUE if min and max
1785 1786
						parameters below already
						contain sensible data */
osku's avatar
osku committed
1787
#ifdef UNIV_LOG_ARCHIVE
1788 1789
	ulint*		min_arch_log_no,	/*!< in/out: */
	ulint*		max_arch_log_no,	/*!< in/out: */
osku's avatar
osku committed
1790
#endif /* UNIV_LOG_ARCHIVE */
1791 1792
	ib_uint64_t*	min_flushed_lsn,	/*!< in/out: */
	ib_uint64_t*	max_flushed_lsn)	/*!< in/out: */
osku's avatar
osku committed
1793
{
1794 1795
	byte*		buf;
	byte*		buf2;
1796
	ib_uint64_t	flushed_lsn;
osku's avatar
osku committed
1797 1798 1799 1800

	buf2 = ut_malloc(2 * UNIV_PAGE_SIZE);
	/* Align the memory for a possible read from a raw device */
	buf = ut_align(buf2, UNIV_PAGE_SIZE);
1801

osku's avatar
osku committed
1802 1803
	os_file_read(data_file, buf, 0, 0, UNIV_PAGE_SIZE);

1804
	flushed_lsn = mach_read_from_8(buf + FIL_PAGE_FILE_FLUSH_LSN);
osku's avatar
osku committed
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817

	ut_free(buf2);

	if (!one_read_already) {
		*min_flushed_lsn = flushed_lsn;
		*max_flushed_lsn = flushed_lsn;
#ifdef UNIV_LOG_ARCHIVE
		*min_arch_log_no = arch_log_no;
		*max_arch_log_no = arch_log_no;
#endif /* UNIV_LOG_ARCHIVE */
		return;
	}

1818
	if (*min_flushed_lsn > flushed_lsn) {
osku's avatar
osku committed
1819 1820
		*min_flushed_lsn = flushed_lsn;
	}
1821
	if (*max_flushed_lsn < flushed_lsn) {
osku's avatar
osku committed
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
		*max_flushed_lsn = flushed_lsn;
	}
#ifdef UNIV_LOG_ARCHIVE
	if (*min_arch_log_no > arch_log_no) {
		*min_arch_log_no = arch_log_no;
	}
	if (*max_arch_log_no < arch_log_no) {
		*max_arch_log_no = arch_log_no;
	}
#endif /* UNIV_LOG_ARCHIVE */
}

/*================ SINGLE-TABLE TABLESPACES ==========================*/

1836
#ifndef UNIV_HOTBACKUP
1837
/*******************************************************************//**
osku's avatar
osku committed
1838
Increments the count of pending insert buffer page merges, if space is not
1839 1840
being deleted.
@return	TRUE if being deleted, and ibuf merges should be skipped */
1841
UNIV_INTERN
osku's avatar
osku committed
1842 1843 1844
ibool
fil_inc_pending_ibuf_merges(
/*========================*/
1845
	ulint	id)	/*!< in: space id */
osku's avatar
osku committed
1846 1847
{
	fil_space_t*	space;
1848

1849
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
1850

1851
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
1852 1853 1854

	if (space == NULL) {
		fprintf(stderr,
1855 1856
			"InnoDB: Error: trying to do ibuf merge to a"
			" dropped tablespace %lu\n",
osku's avatar
osku committed
1857 1858 1859 1860
			(ulong) id);
	}

	if (space == NULL || space->stop_ibuf_merges) {
1861
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1862 1863 1864 1865 1866 1867

		return(TRUE);
	}

	space->n_pending_ibuf_merges++;

1868
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1869 1870 1871 1872

	return(FALSE);
}

1873
/*******************************************************************//**
osku's avatar
osku committed
1874
Decrements the count of pending insert buffer page merges. */
1875
UNIV_INTERN
osku's avatar
osku committed
1876 1877
void
fil_decr_pending_ibuf_merges(
1878
/*=========================*/
1879
	ulint	id)	/*!< in: space id */
osku's avatar
osku committed
1880 1881
{
	fil_space_t*	space;
1882

1883
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
1884

1885
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
1886 1887 1888

	if (space == NULL) {
		fprintf(stderr,
1889 1890
			"InnoDB: Error: decrementing ibuf merge of a"
			" dropped tablespace %lu\n",
osku's avatar
osku committed
1891 1892 1893 1894 1895 1896 1897
			(ulong) id);
	}

	if (space != NULL) {
		space->n_pending_ibuf_merges--;
	}

1898
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
1899
}
1900
#endif /* !UNIV_HOTBACKUP */
osku's avatar
osku committed
1901

1902
/********************************************************//**
osku's avatar
osku committed
1903 1904 1905 1906 1907
Creates the database directory for a table if it does not exist yet. */
static
void
fil_create_directory_for_tablename(
/*===============================*/
1908
	const char*	name)	/*!< in: name in the standard
osku's avatar
osku committed
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
				'databasename/tablename' format */
{
	const char*	namend;
	char*		path;
	ulint		len;

	len = strlen(fil_path_to_mysql_datadir);
	namend = strchr(name, '/');
	ut_a(namend);
	path = mem_alloc(len + (namend - name) + 2);

	memcpy(path, fil_path_to_mysql_datadir, len);
	path[len] = '/';
	memcpy(path + len + 1, name, namend - name);
	path[len + (namend - name) + 1] = 0;

	srv_normalize_path_for_win(path);

	ut_a(os_file_create_directory(path, FALSE));
	mem_free(path);
}

#ifndef UNIV_HOTBACKUP
1932
/********************************************************//**
osku's avatar
osku committed
1933 1934 1935 1936 1937
Writes a log record about an .ibd file create/rename/delete. */
static
void
fil_op_write_log(
/*=============*/
1938
	ulint		type,		/*!< in: MLOG_FILE_CREATE,
1939
					MLOG_FILE_CREATE2,
osku's avatar
osku committed
1940 1941
					MLOG_FILE_DELETE, or
					MLOG_FILE_RENAME */
1942 1943
	ulint		space_id,	/*!< in: space id */
	ulint		log_flags,	/*!< in: redo log flags (stored
1944
					in the page number field) */
1945
	ulint		flags,		/*!< in: compressed page size
1946 1947
					and file format
					if type==MLOG_FILE_CREATE2, or 0 */
1948
	const char*	name,		/*!< in: table name in the familiar
osku's avatar
osku committed
1949 1950
					'databasename/tablename' format, or
					the file path in the case of
1951
					MLOG_FILE_DELETE */
1952
	const char*	new_name,	/*!< in: if type is MLOG_FILE_RENAME,
osku's avatar
osku committed
1953 1954
					the new table name in the
					'databasename/tablename' format */
1955
	mtr_t*		mtr)		/*!< in: mini-transaction handle */
osku's avatar
osku committed
1956 1957 1958 1959
{
	byte*	log_ptr;
	ulint	len;

1960
	log_ptr = mlog_open(mtr, 11 + 2 + 1);
osku's avatar
osku committed
1961 1962 1963 1964 1965 1966 1967

	if (!log_ptr) {
		/* Logging in mtr is switched off during crash recovery:
		in that case mlog_open returns NULL */
		return;
	}

1968 1969
	log_ptr = mlog_write_initial_log_record_for_file_op(
		type, space_id, log_flags, log_ptr, mtr);
1970 1971 1972
	if (type == MLOG_FILE_CREATE2) {
		mach_write_to_4(log_ptr, flags);
		log_ptr += 4;
1973
	}
osku's avatar
osku committed
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
	/* Let us store the strings as null-terminated for easier readability
	and handling */

	len = strlen(name) + 1;

	mach_write_to_2(log_ptr, len);
	log_ptr += 2;
	mlog_close(mtr, log_ptr);

	mlog_catenate_string(mtr, (byte*) name, len);

	if (type == MLOG_FILE_RENAME) {
1986
		len = strlen(new_name) + 1;
osku's avatar
osku committed
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
		log_ptr = mlog_open(mtr, 2 + len);
		ut_a(log_ptr);
		mach_write_to_2(log_ptr, len);
		log_ptr += 2;
		mlog_close(mtr, log_ptr);

		mlog_catenate_string(mtr, (byte*) new_name, len);
	}
}
#endif

1998
/*******************************************************************//**
osku's avatar
osku committed
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
Parses the body of a log record written about an .ibd file operation. That is,
the log record part after the standard (type, space id, page no) header of the
log record.

If desired, also replays the delete or rename operation if the .ibd file
exists and the space id in it matches. Replays the create operation if a file
at that path does not exist yet. If the database directory for the file to be
created does not exist, then we create the directory, too.

Note that ibbackup --apply-log sets fil_path_to_mysql_datadir to point to the
2009
datadir that we should use in replaying the file operations.
2010 2011
@return end of log record, or NULL if the record was not completely
contained between ptr and end_ptr */
2012
UNIV_INTERN
osku's avatar
osku committed
2013 2014 2015
byte*
fil_op_log_parse_or_replay(
/*=======================*/
2016
	byte*	ptr,		/*!< in: buffer containing the log record body,
osku's avatar
osku committed
2017 2018
				or an initial segment of it, if the record does
				not fir completely between ptr and end_ptr */
2019 2020 2021
	byte*	end_ptr,	/*!< in: buffer end */
	ulint	type,		/*!< in: the type of this log record */
	ulint	space_id,	/*!< in: the space id of the tablespace in
2022 2023
				question, or 0 if the log record should
				only be parsed but not replayed */
2024
	ulint	log_flags)	/*!< in: redo log flags
2025
				(stored in the page number parameter) */
osku's avatar
osku committed
2026 2027 2028 2029 2030
{
	ulint		name_len;
	ulint		new_name_len;
	const char*	name;
	const char*	new_name	= NULL;
2031
	ulint		flags		= 0;
2032

2033 2034
	if (type == MLOG_FILE_CREATE2) {
		if (end_ptr < ptr + 4) {
2035 2036 2037 2038

			return(NULL);
		}

2039 2040
		flags = mach_read_from_4(ptr);
		ptr += 4;
2041
	}
osku's avatar
osku committed
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052

	if (end_ptr < ptr + 2) {

		return(NULL);
	}

	name_len = mach_read_from_2(ptr);

	ptr += 2;

	if (end_ptr < ptr + name_len) {
2053

osku's avatar
osku committed
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
		return(NULL);
	}

	name = (const char*) ptr;

	ptr += name_len;

	if (type == MLOG_FILE_RENAME) {
		if (end_ptr < ptr + 2) {

			return(NULL);
		}

		new_name_len = mach_read_from_2(ptr);
2068

osku's avatar
osku committed
2069 2070 2071
		ptr += 2;

		if (end_ptr < ptr + new_name_len) {
2072

osku's avatar
osku committed
2073 2074 2075 2076 2077 2078 2079 2080 2081
			return(NULL);
		}

		new_name = (const char*) ptr;

		ptr += new_name_len;
	}

	/* We managed to parse a full log record body */
2082
	/*
osku's avatar
osku committed
2083
	printf("Parsed log rec of type %lu space %lu\n"
2084
	"name %s\n", type, space_id, name);
osku's avatar
osku committed
2085 2086

	if (type == MLOG_FILE_RENAME) {
2087
	printf("new name %s\n", new_name);
osku's avatar
osku committed
2088
	}
2089
	*/
2090
	if (!space_id) {
osku's avatar
osku committed
2091 2092 2093 2094 2095 2096 2097

		return(ptr);
	}

	/* Let us try to perform the file operation, if sensible. Note that
	ibbackup has at this stage already read in all space id info to the
	fil0fil.c data structures.
2098

osku's avatar
osku committed
2099 2100 2101 2102
	NOTE that our algorithm is not guaranteed to work correctly if there
	were renames of tables during the backup. See ibbackup code for more
	on the problem. */

2103 2104
	switch (type) {
	case MLOG_FILE_DELETE:
osku's avatar
osku committed
2105 2106 2107
		if (fil_tablespace_exists_in_mem(space_id)) {
			ut_a(fil_delete_tablespace(space_id));
		}
2108 2109 2110 2111

		break;

	case MLOG_FILE_RENAME:
osku's avatar
osku committed
2112 2113 2114 2115 2116 2117 2118 2119 2120
		/* We do the rename based on space id, not old file name;
		this should guarantee that after the log replay each .ibd file
		has the correct name for the latest log sequence number; the
		proof is left as an exercise :) */

		if (fil_tablespace_exists_in_mem(space_id)) {
			/* Create the database directory for the new name, if
			it does not exist yet */
			fil_create_directory_for_tablename(new_name);
2121

osku's avatar
osku committed
2122 2123 2124 2125
			/* Rename the table if there is not yet a tablespace
			with the same name */

			if (fil_get_space_id_for_table(new_name)
2126
			    == ULINT_UNDEFINED) {
osku's avatar
osku committed
2127 2128
				/* We do not care of the old name, that is
				why we pass NULL as the first argument */
2129 2130 2131 2132
				if (!fil_rename_tablespace(NULL, space_id,
							   new_name)) {
					ut_error;
				}
osku's avatar
osku committed
2133 2134 2135
			}
		}

2136 2137 2138
		break;

	case MLOG_FILE_CREATE:
2139
	case MLOG_FILE_CREATE2:
osku's avatar
osku committed
2140 2141
		if (fil_tablespace_exists_in_mem(space_id)) {
			/* Do nothing */
2142 2143
		} else if (fil_get_space_id_for_table(name)
			   != ULINT_UNDEFINED) {
osku's avatar
osku committed
2144
			/* Do nothing */
2145 2146
		} else if (log_flags & MLOG_FILE_FLAG_TEMP) {
			/* Temporary table, do nothing */
osku's avatar
osku committed
2147 2148 2149 2150 2151
		} else {
			/* Create the database directory for name, if it does
			not exist yet */
			fil_create_directory_for_tablename(name);

2152
			if (fil_create_new_single_table_tablespace(
2153
				    space_id, name, FALSE, flags,
2154
				    FIL_IBD_FILE_INITIAL_SIZE) != DB_SUCCESS) {
2155 2156
				ut_error;
			}
osku's avatar
osku committed
2157
		}
2158 2159 2160 2161 2162

		break;

	default:
		ut_error;
osku's avatar
osku committed
2163 2164 2165 2166 2167
	}

	return(ptr);
}

2168
/*******************************************************************//**
osku's avatar
osku committed
2169
Deletes a single-table tablespace. The tablespace must be cached in the
2170 2171
memory cache.
@return	TRUE if success */
2172
UNIV_INTERN
osku's avatar
osku committed
2173 2174 2175
ibool
fil_delete_tablespace(
/*==================*/
2176
	ulint	id)	/*!< in: space id */
osku's avatar
osku committed
2177 2178 2179 2180 2181 2182 2183 2184 2185
{
	ibool		success;
	fil_space_t*	space;
	fil_node_t*	node;
	ulint		count		= 0;
	char*		path;

	ut_a(id != 0);
stop_ibuf_merges:
2186
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
2187

2188
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
2189 2190 2191 2192 2193

	if (space != NULL) {
		space->stop_ibuf_merges = TRUE;

		if (space->n_pending_ibuf_merges == 0) {
2194
			mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2195 2196 2197 2198 2199 2200

			count = 0;

			goto try_again;
		} else {
			if (count > 5000) {
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
				ut_print_timestamp(stderr);
				fputs("  InnoDB: Warning: trying to"
				      " delete tablespace ", stderr);
				ut_print_filename(stderr, space->name);
				fprintf(stderr, ",\n"
					"InnoDB: but there are %lu pending"
					" ibuf merges on it.\n"
					"InnoDB: Loop %lu.\n",
					(ulong) space->n_pending_ibuf_merges,
					(ulong) count);
osku's avatar
osku committed
2211 2212
			}

2213
			mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2214 2215 2216 2217 2218 2219 2220 2221

			os_thread_sleep(20000);
			count++;

			goto stop_ibuf_merges;
		}
	}

2222
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2223 2224 2225
	count = 0;

try_again:
2226
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
2227

2228
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
2229 2230 2231 2232

	if (space == NULL) {
		ut_print_timestamp(stderr);
		fprintf(stderr,
2233 2234 2235
			"  InnoDB: Error: cannot delete tablespace %lu\n"
			"InnoDB: because it is not found in the"
			" tablespace memory cache.\n",
osku's avatar
osku committed
2236 2237
			(ulong) id);

2238
		mutex_exit(&fil_system->mutex);
2239

osku's avatar
osku committed
2240
		return(FALSE);
2241
	}
osku's avatar
osku committed
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253

	ut_a(space);
	ut_a(space->n_pending_ibuf_merges == 0);

	space->is_being_deleted = TRUE;

	ut_a(UT_LIST_GET_LEN(space->chain) == 1);
	node = UT_LIST_GET_FIRST(space->chain);

	if (space->n_pending_flushes > 0 || node->n_pending > 0) {
		if (count > 1000) {
			ut_print_timestamp(stderr);
2254 2255
			fputs("  InnoDB: Warning: trying to"
			      " delete tablespace ", stderr);
osku's avatar
osku committed
2256 2257
			ut_print_filename(stderr, space->name);
			fprintf(stderr, ",\n"
2258 2259 2260 2261
				"InnoDB: but there are %lu flushes"
				" and %lu pending i/o's on it\n"
				"InnoDB: Loop %lu.\n",
				(ulong) space->n_pending_flushes,
osku's avatar
osku committed
2262 2263 2264
				(ulong) node->n_pending,
				(ulong) count);
		}
2265
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2266 2267 2268 2269 2270 2271 2272 2273 2274
		os_thread_sleep(20000);

		count++;

		goto try_again;
	}

	path = mem_strdup(space->name);

2275
	mutex_exit(&fil_system->mutex);
2276 2277 2278 2279 2280 2281 2282 2283 2284

	/* Important: We rely on the data dictionary mutex to ensure
	that a race is not possible here. It should serialize the tablespace
	drop/free. We acquire an X latch only to avoid a race condition
	when accessing the tablespace instance via:

	  fsp_get_available_space_in_free_extents().

	There our main motivation is to reduce the contention on the
2285
	dictionary mutex. */
2286 2287 2288

	rw_lock_x_lock(&space->latch);

osku's avatar
osku committed
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
#ifndef UNIV_HOTBACKUP
	/* Invalidate in the buffer pool all pages belonging to the
	tablespace. Since we have set space->is_being_deleted = TRUE, readahead
	or ibuf merge can no longer read more pages of this tablespace to the
	buffer pool. Thus we can clean the tablespace out of the buffer pool
	completely and permanently. The flag is_being_deleted also prevents
	fil_flush() from being applied to this tablespace. */

	buf_LRU_invalidate_tablespace(id);
#endif
	/* printf("Deleting tablespace %s id %lu\n", space->name, id); */

2301
	mutex_enter(&fil_system->mutex);
2302 2303 2304

	success = fil_space_free(id, TRUE);

2305
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2306 2307 2308 2309 2310 2311 2312

	if (success) {
		success = os_file_delete(path);

		if (!success) {
			success = os_file_delete_if_exists(path);
		}
2313 2314
	} else {
		rw_lock_x_unlock(&space->latch);
osku's avatar
osku committed
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
	}

	if (success) {
#ifndef UNIV_HOTBACKUP
		/* Write a log record about the deletion of the .ibd
		file, so that ibbackup can replay it in the
		--apply-log phase. We use a dummy mtr and the familiar
		log write mechanism. */
		mtr_t		mtr;

		/* When replaying the operation in ibbackup, do not try
		to write any log record */
		mtr_start(&mtr);

2329
		fil_op_write_log(MLOG_FILE_DELETE, id, 0, 0, path, NULL, &mtr);
osku's avatar
osku committed
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
		mtr_commit(&mtr);
#endif
		mem_free(path);

		return(TRUE);
	}

	mem_free(path);

	return(FALSE);
}

2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
/*******************************************************************//**
Returns TRUE if a single-table tablespace is being deleted.
@return TRUE if being deleted */
UNIV_INTERN
ibool
fil_tablespace_is_being_deleted(
/*============================*/
	ulint		id)	/*!< in: space id */
{
	fil_space_t*	space;
	ibool		is_being_deleted;

	mutex_enter(&fil_system->mutex);

	space = fil_space_get_by_id(id);

	ut_a(space != NULL);

	is_being_deleted = space->is_being_deleted;

	mutex_exit(&fil_system->mutex);

	return(is_being_deleted);
}

2367
#ifndef UNIV_HOTBACKUP
2368
/*******************************************************************//**
osku's avatar
osku committed
2369 2370 2371 2372 2373 2374
Discards a single-table tablespace. The tablespace must be cached in the
memory cache. Discarding is like deleting a tablespace, but
1) we do not drop the table from the data dictionary;
2) we remove all insert buffer entries for the tablespace immediately; in DROP
TABLE they are only removed gradually in the background;
3) when the user does IMPORT TABLESPACE, the tablespace will have the same id
2375 2376
as it originally had.
@return	TRUE if success */
2377
UNIV_INTERN
osku's avatar
osku committed
2378 2379 2380
ibool
fil_discard_tablespace(
/*===================*/
2381
	ulint	id)	/*!< in: space id */
osku's avatar
osku committed
2382 2383 2384 2385 2386 2387 2388
{
	ibool	success;

	success = fil_delete_tablespace(id);

	if (!success) {
		fprintf(stderr,
2389 2390 2391 2392
			"InnoDB: Warning: cannot delete tablespace %lu"
			" in DISCARD TABLESPACE.\n"
			"InnoDB: But let us remove the"
			" insert buffer entries for this tablespace.\n",
2393
			(ulong) id);
osku's avatar
osku committed
2394 2395 2396 2397 2398 2399
	}

	/* Remove all insert buffer entries for the tablespace */

	ibuf_delete_for_discarded_space(id);

2400
	return(success);
osku's avatar
osku committed
2401
}
2402
#endif /* !UNIV_HOTBACKUP */
osku's avatar
osku committed
2403

2404
/*******************************************************************//**
2405 2406
Renames the memory cache structures of a single-table tablespace.
@return	TRUE if success */
osku's avatar
osku committed
2407 2408 2409 2410
static
ibool
fil_rename_tablespace_in_mem(
/*=========================*/
2411 2412 2413
	fil_space_t*	space,	/*!< in: tablespace memory object */
	fil_node_t*	node,	/*!< in: file node of that tablespace */
	const char*	path)	/*!< in: new name */
osku's avatar
osku committed
2414 2415 2416
{
	fil_space_t*	space2;
	const char*	old_name	= space->name;
2417

2418 2419
	ut_ad(mutex_own(&fil_system->mutex));

2420
	space2 = fil_space_get_by_name(old_name);
osku's avatar
osku committed
2421 2422 2423 2424 2425 2426 2427 2428
	if (space != space2) {
		fputs("InnoDB: Error: cannot find ", stderr);
		ut_print_filename(stderr, old_name);
		fputs(" in tablespace memory cache\n", stderr);

		return(FALSE);
	}

2429
	space2 = fil_space_get_by_name(path);
osku's avatar
osku committed
2430 2431 2432 2433
	if (space2 != NULL) {
		fputs("InnoDB: Error: ", stderr);
		ut_print_filename(stderr, path);
		fputs(" is already in tablespace memory cache\n", stderr);
2434

osku's avatar
osku committed
2435 2436 2437
		return(FALSE);
	}

2438
	HASH_DELETE(fil_space_t, name_hash, fil_system->name_hash,
2439
		    ut_fold_string(space->name), space);
osku's avatar
osku committed
2440 2441 2442 2443 2444 2445
	mem_free(space->name);
	mem_free(node->name);

	space->name = mem_strdup(path);
	node->name = mem_strdup(path);

2446
	HASH_INSERT(fil_space_t, name_hash, fil_system->name_hash,
2447
		    ut_fold_string(path), space);
osku's avatar
osku committed
2448 2449 2450
	return(TRUE);
}

2451
/*******************************************************************//**
osku's avatar
osku committed
2452
Allocates a file name for a single-table tablespace. The string must be freed
2453 2454
by caller with mem_free().
@return	own: file name */
osku's avatar
osku committed
2455 2456 2457 2458
static
char*
fil_make_ibd_name(
/*==============*/
2459
	const char*	name,		/*!< in: table name or a dir path of a
osku's avatar
osku committed
2460
					TEMPORARY table */
2461
	ibool		is_temp)	/*!< in: TRUE if it is a dir path */
osku's avatar
osku committed
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
{
	ulint	namelen		= strlen(name);
	ulint	dirlen		= strlen(fil_path_to_mysql_datadir);
	char*	filename	= mem_alloc(namelen + dirlen + sizeof "/.ibd");

	if (is_temp) {
		memcpy(filename, name, namelen);
		memcpy(filename + namelen, ".ibd", sizeof ".ibd");
	} else {
		memcpy(filename, fil_path_to_mysql_datadir, dirlen);
		filename[dirlen] = '/';

		memcpy(filename + dirlen + 1, name, namelen);
		memcpy(filename + dirlen + namelen + 1, ".ibd", sizeof ".ibd");
	}

	srv_normalize_path_for_win(filename);

	return(filename);
}

2483
/*******************************************************************//**
osku's avatar
osku committed
2484
Renames a single-table tablespace. The tablespace must be cached in the
2485 2486
tablespace memory cache.
@return	TRUE if success */
2487
UNIV_INTERN
osku's avatar
osku committed
2488 2489 2490
ibool
fil_rename_tablespace(
/*==================*/
2491
	const char*	old_name,	/*!< in: old table name in the standard
osku's avatar
osku committed
2492 2493 2494
					databasename/tablename format of
					InnoDB, or NULL if we do the rename
					based on the space id only */
2495 2496
	ulint		id,		/*!< in: space id */
	const char*	new_name)	/*!< in: new table name in the standard
osku's avatar
osku committed
2497 2498 2499 2500 2501 2502 2503 2504
					databasename/tablename format
					of InnoDB */
{
	ibool		success;
	fil_space_t*	space;
	fil_node_t*	node;
	ulint		count		= 0;
	char*		path;
2505
	ibool		old_name_was_specified		= TRUE;
osku's avatar
osku committed
2506 2507 2508
	char*		old_path;

	ut_a(id != 0);
2509

osku's avatar
osku committed
2510 2511 2512 2513 2514 2515 2516 2517 2518
	if (old_name == NULL) {
		old_name = "(name not specified)";
		old_name_was_specified = FALSE;
	}
retry:
	count++;

	if (count > 1000) {
		ut_print_timestamp(stderr);
2519
		fputs("  InnoDB: Warning: problems renaming ", stderr);
osku's avatar
osku committed
2520 2521 2522 2523 2524 2525
		ut_print_filename(stderr, old_name);
		fputs(" to ", stderr);
		ut_print_filename(stderr, new_name);
		fprintf(stderr, ", %lu iterations\n", (ulong) count);
	}

2526
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
2527

2528
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
2529 2530 2531

	if (space == NULL) {
		fprintf(stderr,
2532 2533 2534
			"InnoDB: Error: cannot find space id %lu"
			" in the tablespace memory cache\n"
			"InnoDB: though the table ", (ulong) id);
osku's avatar
osku committed
2535 2536
		ut_print_filename(stderr, old_name);
		fputs(" in a rename operation should have that id\n", stderr);
2537
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2538 2539 2540 2541 2542 2543

		return(FALSE);
	}

	if (count > 25000) {
		space->stop_ios = FALSE;
2544
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561

		return(FALSE);
	}

	/* We temporarily close the .ibd file because we do not trust that
	operating systems can rename an open file. For the closing we have to
	wait until there are no pending i/o's or flushes on the file. */

	space->stop_ios = TRUE;

	ut_a(UT_LIST_GET_LEN(space->chain) == 1);
	node = UT_LIST_GET_FIRST(space->chain);

	if (node->n_pending > 0 || node->n_pending_flushes > 0) {
		/* There are pending i/o's or flushes, sleep for a while and
		retry */

2562
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2563 2564 2565 2566 2567 2568 2569 2570

		os_thread_sleep(20000);

		goto retry;

	} else if (node->modification_counter > node->flush_counter) {
		/* Flush the space */

2571
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581

		os_thread_sleep(20000);

		fil_flush(id);

		goto retry;

	} else if (node->open) {
		/* Close the file */

2582
		fil_node_close_file(node, fil_system);
osku's avatar
osku committed
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
	}

	/* Check that the old name in the space is right */

	if (old_name_was_specified) {
		old_path = fil_make_ibd_name(old_name, FALSE);

		ut_a(strcmp(space->name, old_path) == 0);
		ut_a(strcmp(node->name, old_path) == 0);
	} else {
		old_path = mem_strdup(space->name);
	}

	/* Rename the tablespace and the node in the memory cache */
	path = fil_make_ibd_name(new_name, FALSE);
	success = fil_rename_tablespace_in_mem(space, node, path);

	if (success) {
2601
		success = os_file_rename(innodb_file_data_key, old_path, path);
osku's avatar
osku committed
2602 2603 2604 2605 2606 2607

		if (!success) {
			/* We have to revert the changes we made
			to the tablespace memory cache */

			ut_a(fil_rename_tablespace_in_mem(space, node,
2608
							  old_path));
osku's avatar
osku committed
2609 2610 2611 2612 2613 2614 2615 2616
		}
	}

	mem_free(path);
	mem_free(old_path);

	space->stop_ios = FALSE;

2617
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
2618

2619
#ifndef UNIV_HOTBACKUP
osku's avatar
osku committed
2620 2621 2622 2623 2624
	if (success) {
		mtr_t		mtr;

		mtr_start(&mtr);

2625
		fil_op_write_log(MLOG_FILE_RENAME, id, 0, 0, old_name, new_name,
2626
				 &mtr);
osku's avatar
osku committed
2627 2628 2629 2630 2631 2632
		mtr_commit(&mtr);
	}
#endif
	return(success);
}

2633
/*******************************************************************//**
osku's avatar
osku committed
2634 2635 2636 2637
Creates a new single-table tablespace to a database directory of MySQL.
Database directories are under the 'datadir' of MySQL. The datadir is the
directory of a running mysqld program. We can refer to it by simply the
path '.'. Tables created with CREATE TEMPORARY TABLE we place in the temp
2638 2639
dir of the mysqld server.
@return	DB_SUCCESS or error code */
2640
UNIV_INTERN
osku's avatar
osku committed
2641 2642 2643
ulint
fil_create_new_single_table_tablespace(
/*===================================*/
2644
	ulint		space_id,	/*!< in: space id */
2645
	const char*	tablename,	/*!< in: the table name in the usual
osku's avatar
osku committed
2646 2647 2648
					databasename/tablename format
					of InnoDB, or a dir path to a temp
					table */
2649
	ibool		is_temp,	/*!< in: TRUE if a table created with
osku's avatar
osku committed
2650
					CREATE TEMPORARY TABLE */
2651 2652
	ulint		flags,		/*!< in: tablespace flags */
	ulint		size)		/*!< in: the initial size of the
osku's avatar
osku committed
2653 2654 2655
					tablespace file in pages,
					must be >= FIL_IBD_FILE_INITIAL_SIZE */
{
2656
	os_file_t	file;
osku's avatar
osku committed
2657 2658 2659 2660 2661 2662 2663
	ibool		ret;
	ulint		err;
	byte*		buf2;
	byte*		page;
	ibool		success;
	char*		path;

2664 2665
	ut_a(space_id > 0);
	ut_a(space_id < SRV_LOG_SPACE_FIRST_ID);
osku's avatar
osku committed
2666
	ut_a(size >= FIL_IBD_FILE_INITIAL_SIZE);
2667
	/* The tablespace flags (FSP_SPACE_FLAGS) should be 0 for
2668 2669
	ROW_FORMAT=COMPACT
	((table->flags & ~(~0 << DICT_TF_BITS)) == DICT_TF_COMPACT) and
2670
	ROW_FORMAT=REDUNDANT (table->flags == 0).  For any other
2671 2672
	format, the tablespace flags should equal
	(table->flags & ~(~0 << DICT_TF_BITS)). */
2673
	ut_a(flags != DICT_TF_COMPACT);
2674
	ut_a(!(flags & (~0UL << DICT_TF_BITS)));
osku's avatar
osku committed
2675 2676

	path = fil_make_ibd_name(tablename, is_temp);
2677

2678 2679
	file = os_file_create(innodb_file_data_key, path,
			      OS_FILE_CREATE, OS_FILE_NORMAL,
2680
			      OS_DATA_FILE, &ret);
osku's avatar
osku committed
2681 2682
	if (ret == FALSE) {
		ut_print_timestamp(stderr);
2683
		fputs("  InnoDB: Error creating file ", stderr);
osku's avatar
osku committed
2684 2685 2686 2687
		ut_print_filename(stderr, path);
		fputs(".\n", stderr);

		/* The following call will print an error message */
2688

osku's avatar
osku committed
2689
		err = os_file_get_last_error(TRUE);
2690

osku's avatar
osku committed
2691
		if (err == OS_FILE_ALREADY_EXISTS) {
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
			fputs("InnoDB: The file already exists though"
			      " the corresponding table did not\n"
			      "InnoDB: exist in the InnoDB data dictionary."
			      " Have you moved InnoDB\n"
			      "InnoDB: .ibd files around without using the"
			      " SQL commands\n"
			      "InnoDB: DISCARD TABLESPACE and"
			      " IMPORT TABLESPACE, or did\n"
			      "InnoDB: mysqld crash in the middle of"
			      " CREATE TABLE? You can\n"
			      "InnoDB: resolve the problem by"
			      " removing the file ", stderr);
osku's avatar
osku committed
2704 2705
			ut_print_filename(stderr, path);
			fputs("\n"
2706 2707
			      "InnoDB: under the 'datadir' of MySQL.\n",
			      stderr);
osku's avatar
osku committed
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723

			mem_free(path);
			return(DB_TABLESPACE_ALREADY_EXISTS);
		}

		if (err == OS_FILE_DISK_FULL) {

			mem_free(path);
			return(DB_OUT_OF_FILE_SPACE);
		}

		mem_free(path);
		return(DB_ERROR);
	}

	ret = os_file_set_size(path, file, size * UNIV_PAGE_SIZE, 0);
2724

osku's avatar
osku committed
2725
	if (!ret) {
2726
		err = DB_OUT_OF_FILE_SPACE;
2727
error_exit:
osku's avatar
osku committed
2728
		os_file_close(file);
2729
error_exit2:
osku's avatar
osku committed
2730 2731 2732
		os_file_delete(path);

		mem_free(path);
2733
		return(err);
osku's avatar
osku committed
2734 2735
	}

2736 2737
	/* printf("Creating tablespace %s id %lu\n", path, space_id); */

osku's avatar
osku committed
2738 2739 2740 2741 2742 2743 2744 2745 2746
	/* We have to write the space id to the file immediately and flush the
	file to disk. This is because in crash recovery we must be aware what
	tablespaces exist and what are their space id's, so that we can apply
	the log records to the right file. It may take quite a while until
	buffer pool flush algorithms write anything to the file and flush it to
	disk. If we would not write here anything, the file would be filled
	with zeros from the call of os_file_set_size(), until a buffer pool
	flush would write to it. */

2747 2748 2749 2750
	buf2 = ut_malloc(3 * UNIV_PAGE_SIZE);
	/* Align the memory for file i/o if we might have O_DIRECT set */
	page = ut_align(buf2, UNIV_PAGE_SIZE);

osku's avatar
osku committed
2751 2752
	memset(page, '\0', UNIV_PAGE_SIZE);

2753 2754
	fsp_header_init_fields(page, space_id, flags);
	mach_write_to_4(page + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, space_id);
osku's avatar
osku committed
2755

2756
	if (!(flags & DICT_TF_ZSSIZE_MASK)) {
2757
		buf_flush_init_for_writing(page, NULL, 0);
2758
		ret = os_file_write(path, file, page, 0, 0, UNIV_PAGE_SIZE);
2759 2760
	} else {
		page_zip_des_t	page_zip;
2761 2762 2763 2764 2765 2766
		ulint		zip_size;

		zip_size = ((PAGE_ZIP_MIN_SIZE >> 1)
			    << ((flags & DICT_TF_ZSSIZE_MASK)
				>> DICT_TF_ZSSIZE_SHIFT));

2767
		page_zip_set_size(&page_zip, zip_size);
2768
		page_zip.data = page + UNIV_PAGE_SIZE;
2769 2770 2771 2772 2773
#ifdef UNIV_DEBUG
		page_zip.m_start =
#endif /* UNIV_DEBUG */
			page_zip.m_end = page_zip.m_nonempty =
			page_zip.n_blobs = 0;
2774
		buf_flush_init_for_writing(page, &page_zip, 0);
2775
		ret = os_file_write(path, file, page_zip.data, 0, 0, zip_size);
2776
	}
osku's avatar
osku committed
2777 2778 2779 2780

	ut_free(buf2);

	if (!ret) {
2781 2782
		fputs("InnoDB: Error: could not write the first page"
		      " to tablespace ", stderr);
osku's avatar
osku committed
2783 2784
		ut_print_filename(stderr, path);
		putc('\n', stderr);
2785
		err = DB_ERROR;
osku's avatar
osku committed
2786 2787 2788 2789 2790 2791
		goto error_exit;
	}

	ret = os_file_flush(file);

	if (!ret) {
2792
		fputs("InnoDB: Error: file flush of tablespace ", stderr);
osku's avatar
osku committed
2793 2794
		ut_print_filename(stderr, path);
		fputs(" failed\n", stderr);
2795
		err = DB_ERROR;
osku's avatar
osku committed
2796 2797 2798 2799 2800
		goto error_exit;
	}

	os_file_close(file);

2801
	success = fil_space_create(path, space_id, flags, FIL_TABLESPACE);
2802

osku's avatar
osku committed
2803
	if (!success) {
2804
		err = DB_ERROR;
osku's avatar
osku committed
2805
		goto error_exit2;
2806
	}
osku's avatar
osku committed
2807

2808
	fil_node_create(path, size, space_id, FALSE);
osku's avatar
osku committed
2809

2810
#ifndef UNIV_HOTBACKUP
osku's avatar
osku committed
2811
	{
2812
		mtr_t		mtr;
osku's avatar
osku committed
2813

2814
		mtr_start(&mtr);
osku's avatar
osku committed
2815

2816 2817
		fil_op_write_log(flags
				 ? MLOG_FILE_CREATE2
2818
				 : MLOG_FILE_CREATE,
2819
				 space_id,
2820 2821
				 is_temp ? MLOG_FILE_FLAG_TEMP : 0,
				 flags,
2822
				 tablename, NULL, &mtr);
osku's avatar
osku committed
2823

2824
		mtr_commit(&mtr);
osku's avatar
osku committed
2825 2826 2827 2828 2829 2830
	}
#endif
	mem_free(path);
	return(DB_SUCCESS);
}

2831
#ifndef UNIV_HOTBACKUP
2832
/********************************************************************//**
osku's avatar
osku committed
2833 2834 2835 2836 2837 2838 2839
It is possible, though very improbable, that the lsn's in the tablespace to be
imported have risen above the current system lsn, if a lengthy purge, ibuf
merge, or rollback was performed on a backup taken with ibbackup. If that is
the case, reset page lsn's in the file. We assume that mysqld was shut down
after it performed these cleanup operations on the .ibd file, so that it at
the shutdown stamped the latest lsn to the FIL_PAGE_FILE_FLUSH_LSN in the
first page of the .ibd file, and we can determine whether we need to reset the
2840 2841
lsn's just by looking at that flush lsn.
@return	TRUE if success */
2842
UNIV_INTERN
osku's avatar
osku committed
2843 2844 2845
ibool
fil_reset_too_high_lsns(
/*====================*/
2846
	const char*	name,		/*!< in: table name in the
osku's avatar
osku committed
2847
					databasename/tablename format */
2848
	ib_uint64_t	current_lsn)	/*!< in: reset lsn's if the lsn stamped
osku's avatar
osku committed
2849 2850 2851 2852 2853 2854 2855
					to FIL_PAGE_FILE_FLUSH_LSN in the
					first page is too high */
{
	os_file_t	file;
	char*		filepath;
	byte*		page;
	byte*		buf2;
2856
	ib_uint64_t	flush_lsn;
osku's avatar
osku committed
2857
	ulint		space_id;
2858 2859
	ib_int64_t	file_size;
	ib_int64_t	offset;
2860
	ulint		zip_size;
osku's avatar
osku committed
2861
	ibool		success;
2862
	page_zip_des_t	page_zip;
osku's avatar
osku committed
2863 2864 2865

	filepath = fil_make_ibd_name(name, FALSE);

2866
	file = os_file_create_simple_no_error_handling(
2867 2868
		innodb_file_data_key, filepath, OS_FILE_OPEN,
		OS_FILE_READ_WRITE, &success);
osku's avatar
osku committed
2869 2870 2871 2872 2873 2874
	if (!success) {
		/* The following call prints an error message */
		os_file_get_last_error(TRUE);

		ut_print_timestamp(stderr);

2875 2876 2877
		fputs("  InnoDB: Error: trying to open a table,"
		      " but could not\n"
		      "InnoDB: open the tablespace file ", stderr);
osku's avatar
osku committed
2878 2879 2880 2881 2882 2883 2884 2885 2886
		ut_print_filename(stderr, filepath);
		fputs("!\n", stderr);
		mem_free(filepath);

		return(FALSE);
	}

	/* Read the first page of the tablespace */

2887
	buf2 = ut_malloc(3 * UNIV_PAGE_SIZE);
osku's avatar
osku committed
2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
	/* Align the memory for file i/o if we might have O_DIRECT set */
	page = ut_align(buf2, UNIV_PAGE_SIZE);

	success = os_file_read(file, page, 0, 0, UNIV_PAGE_SIZE);
	if (!success) {

		goto func_exit;
	}

	/* We have to read the file flush lsn from the header of the file */

2899
	flush_lsn = mach_read_from_8(page + FIL_PAGE_FILE_FLUSH_LSN);
osku's avatar
osku committed
2900

2901
	if (current_lsn >= flush_lsn) {
osku's avatar
osku committed
2902 2903 2904 2905 2906 2907 2908
		/* Ok */
		success = TRUE;

		goto func_exit;
	}

	space_id = fsp_header_get_space_id(page);
2909
	zip_size = fsp_header_get_zip_size(page);
2910

2911 2912 2913 2914 2915 2916
	page_zip_des_init(&page_zip);
	page_zip_set_size(&page_zip, zip_size);
	if (zip_size) {
		page_zip.data = page + UNIV_PAGE_SIZE;
	}

osku's avatar
osku committed
2917 2918
	ut_print_timestamp(stderr);
	fprintf(stderr,
2919 2920
		"  InnoDB: Flush lsn in the tablespace file %lu"
		" to be imported\n"
2921 2922
		"InnoDB: is %llu, which exceeds current"
		" system lsn %llu.\n"
2923
		"InnoDB: We reset the lsn's in the file ",
2924
		(ulong) space_id,
2925
		flush_lsn, current_lsn);
osku's avatar
osku committed
2926 2927 2928
	ut_print_filename(stderr, filepath);
	fputs(".\n", stderr);

2929 2930 2931
	ut_a(ut_is_2pow(zip_size));
	ut_a(zip_size <= UNIV_PAGE_SIZE);

osku's avatar
osku committed
2932 2933 2934 2935 2936
	/* Loop through all the pages in the tablespace and reset the lsn and
	the page checksum if necessary */

	file_size = os_file_get_size_as_iblonglong(file);

2937 2938
	for (offset = 0; offset < file_size;
	     offset += zip_size ? zip_size : UNIV_PAGE_SIZE) {
osku's avatar
osku committed
2939
		success = os_file_read(file, page,
2940
				       (ulint)(offset & 0xFFFFFFFFUL),
2941 2942
				       (ulint)(offset >> 32),
				       zip_size ? zip_size : UNIV_PAGE_SIZE);
osku's avatar
osku committed
2943 2944 2945 2946
		if (!success) {

			goto func_exit;
		}
2947
		if (mach_read_from_8(page + FIL_PAGE_LSN) > current_lsn) {
osku's avatar
osku committed
2948
			/* We have to reset the lsn */
2949

2950
			if (zip_size) {
2951
				memcpy(page_zip.data, page, zip_size);
2952
				buf_flush_init_for_writing(
2953 2954 2955 2956 2957
					page, &page_zip, current_lsn);
				success = os_file_write(
					filepath, file, page_zip.data,
					(ulint) offset & 0xFFFFFFFFUL,
					(ulint) (offset >> 32), zip_size);
2958 2959
			} else {
				buf_flush_init_for_writing(
2960
					page, NULL, current_lsn);
2961 2962 2963 2964 2965
				success = os_file_write(
					filepath, file, page,
					(ulint)(offset & 0xFFFFFFFFUL),
					(ulint)(offset >> 32),
					UNIV_PAGE_SIZE);
2966
			}
2967

osku's avatar
osku committed
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
			if (!success) {

				goto func_exit;
			}
		}
	}

	success = os_file_flush(file);
	if (!success) {

		goto func_exit;
	}

	/* We now update the flush_lsn stamp at the start of the file */
2982 2983
	success = os_file_read(file, page, 0, 0,
			       zip_size ? zip_size : UNIV_PAGE_SIZE);
osku's avatar
osku committed
2984 2985 2986 2987 2988
	if (!success) {

		goto func_exit;
	}

2989
	mach_write_to_8(page + FIL_PAGE_FILE_FLUSH_LSN, current_lsn);
osku's avatar
osku committed
2990

2991 2992
	success = os_file_write(filepath, file, page, 0, 0,
				zip_size ? zip_size : UNIV_PAGE_SIZE);
osku's avatar
osku committed
2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
	if (!success) {

		goto func_exit;
	}
	success = os_file_flush(file);
func_exit:
	os_file_close(file);
	ut_free(buf2);
	mem_free(filepath);

	return(success);
}

3006
/********************************************************************//**
osku's avatar
osku committed
3007 3008 3009 3010 3011 3012 3013
Tries to open a single-table tablespace and optionally checks the space id is
right in it. If does not succeed, prints an error message to the .err log. This
function is used to open a tablespace when we start up mysqld, and also in
IMPORT TABLESPACE.
NOTE that we assume this operation is used either at the database startup
or under the protection of the dictionary mutex, so that two users cannot
race here. This operation does not leave the file associated with the
3014 3015
tablespace open, but closes it after we have looked at the space id in it.
@return	TRUE if success */
3016
UNIV_INTERN
osku's avatar
osku committed
3017 3018 3019
ibool
fil_open_single_table_tablespace(
/*=============================*/
3020
	ibool		check_space_id,	/*!< in: should we check that the space
osku's avatar
osku committed
3021 3022 3023 3024 3025 3026
					id in the file is right; we assume
					that this function runs much faster
					if no check is made, since accessing
					the file inode probably is much
					faster (the OS caches them) than
					accessing the first page of the file */
3027 3028 3029
	ulint		id,		/*!< in: space id */
	ulint		flags,		/*!< in: tablespace flags */
	const char*	name)		/*!< in: table name in the
osku's avatar
osku committed
3030 3031 3032 3033 3034 3035 3036 3037
					databasename/tablename format */
{
	os_file_t	file;
	char*		filepath;
	ibool		success;
	byte*		buf2;
	byte*		page;
	ulint		space_id;
3038
	ulint		space_flags;
osku's avatar
osku committed
3039 3040 3041

	filepath = fil_make_ibd_name(name, FALSE);

3042
	/* The tablespace flags (FSP_SPACE_FLAGS) should be 0 for
3043 3044
	ROW_FORMAT=COMPACT
	((table->flags & ~(~0 << DICT_TF_BITS)) == DICT_TF_COMPACT) and
3045
	ROW_FORMAT=REDUNDANT (table->flags == 0).  For any other
3046 3047
	format, the tablespace flags should equal
	(table->flags & ~(~0 << DICT_TF_BITS)). */
3048
	ut_a(flags != DICT_TF_COMPACT);
3049
	ut_a(!(flags & (~0UL << DICT_TF_BITS)));
3050

3051
	file = os_file_create_simple_no_error_handling(
3052 3053
		innodb_file_data_key, filepath, OS_FILE_OPEN,
		OS_FILE_READ_ONLY, &success);
osku's avatar
osku committed
3054 3055 3056 3057 3058 3059
	if (!success) {
		/* The following call prints an error message */
		os_file_get_last_error(TRUE);

		ut_print_timestamp(stderr);

3060 3061 3062
		fputs("  InnoDB: Error: trying to open a table,"
		      " but could not\n"
		      "InnoDB: open the tablespace file ", stderr);
osku's avatar
osku committed
3063 3064
		ut_print_filename(stderr, filepath);
		fputs("!\n"
3065 3066 3067 3068 3069 3070 3071 3072
		      "InnoDB: Have you moved InnoDB .ibd files around"
		      " without using the\n"
		      "InnoDB: commands DISCARD TABLESPACE and"
		      " IMPORT TABLESPACE?\n"
		      "InnoDB: It is also possible that this is"
		      " a temporary table #sql...,\n"
		      "InnoDB: and MySQL removed the .ibd file for this.\n"
		      "InnoDB: Please refer to\n"
3073
		      "InnoDB: " REFMAN "innodb-troubleshooting-datadict.html\n"
3074
		      "InnoDB: for how to resolve the issue.\n", stderr);
osku's avatar
osku committed
3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094

		mem_free(filepath);

		return(FALSE);
	}

	if (!check_space_id) {
		space_id = id;

		goto skip_check;
	}

	/* Read the first page of the tablespace */

	buf2 = ut_malloc(2 * UNIV_PAGE_SIZE);
	/* Align the memory for file i/o if we might have O_DIRECT set */
	page = ut_align(buf2, UNIV_PAGE_SIZE);

	success = os_file_read(file, page, 0, 0, UNIV_PAGE_SIZE);

3095
	/* We have to read the tablespace id and flags from the file. */
osku's avatar
osku committed
3096 3097

	space_id = fsp_header_get_space_id(page);
3098
	space_flags = fsp_header_get_flags(page);
osku's avatar
osku committed
3099 3100 3101

	ut_free(buf2);

3102 3103
	if (UNIV_UNLIKELY(space_id != id
			  || space_flags != (flags & ~(~0 << DICT_TF_BITS)))) {
osku's avatar
osku committed
3104 3105
		ut_print_timestamp(stderr);

3106 3107
		fputs("  InnoDB: Error: tablespace id and flags in file ",
		      stderr);
osku's avatar
osku committed
3108
		ut_print_filename(stderr, filepath);
3109 3110
		fprintf(stderr, " are %lu and %lu, but in the InnoDB\n"
			"InnoDB: data dictionary they are %lu and %lu.\n"
3111 3112 3113 3114 3115
			"InnoDB: Have you moved InnoDB .ibd files"
			" around without using the\n"
			"InnoDB: commands DISCARD TABLESPACE and"
			" IMPORT TABLESPACE?\n"
			"InnoDB: Please refer to\n"
3116
			"InnoDB: " REFMAN "innodb-troubleshooting-datadict.html\n"
3117
			"InnoDB: for how to resolve the issue.\n",
3118 3119
			(ulong) space_id, (ulong) space_flags,
			(ulong) id, (ulong) flags);
osku's avatar
osku committed
3120

3121
		success = FALSE;
osku's avatar
osku committed
3122 3123 3124 3125 3126

		goto func_exit;
	}

skip_check:
3127
	success = fil_space_create(filepath, space_id, flags, FIL_TABLESPACE);
osku's avatar
osku committed
3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140

	if (!success) {
		goto func_exit;
	}

	/* We do not measure the size of the file, that is why we pass the 0
	below */

	fil_node_create(filepath, 0, space_id, FALSE);
func_exit:
	os_file_close(file);
	mem_free(filepath);

3141
	return(success);
osku's avatar
osku committed
3142
}
3143
#endif /* !UNIV_HOTBACKUP */
osku's avatar
osku committed
3144 3145

#ifdef UNIV_HOTBACKUP
3146
/*******************************************************************//**
osku's avatar
osku committed
3147
Allocates a file name for an old version of a single-table tablespace.
3148 3149
The string must be freed by caller with mem_free()!
@return	own: file name */
osku's avatar
osku committed
3150 3151 3152 3153
static
char*
fil_make_ibbackup_old_name(
/*=======================*/
3154
	const char*	name)		/*!< in: original file name */
osku's avatar
osku committed
3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166
{
	static const char suffix[] = "_ibbackup_old_vers_";
	ulint	len	= strlen(name);
	char*	path	= mem_alloc(len + (15 + sizeof suffix));

	memcpy(path, name, len);
	memcpy(path + len, suffix, (sizeof suffix) - 1);
	ut_sprintf_timestamp_without_extra_chars(path + len + sizeof suffix);
	return(path);
}
#endif /* UNIV_HOTBACKUP */

3167
/********************************************************************//**
osku's avatar
osku committed
3168 3169 3170 3171 3172 3173
Opens an .ibd file and adds the associated single-table tablespace to the
InnoDB fil0fil.c data structures. */
static
void
fil_load_single_table_tablespace(
/*=============================*/
3174 3175
	const char*	dbname,		/*!< in: database name */
	const char*	filename)	/*!< in: file name (not a path),
osku's avatar
osku committed
3176 3177 3178 3179 3180 3181 3182 3183
					including the .ibd extension */
{
	os_file_t	file;
	char*		filepath;
	ibool		success;
	byte*		buf2;
	byte*		page;
	ulint		space_id;
3184
	ulint		flags;
osku's avatar
osku committed
3185 3186
	ulint		size_low;
	ulint		size_high;
3187
	ib_int64_t	size;
osku's avatar
osku committed
3188 3189 3190
#ifdef UNIV_HOTBACKUP
	fil_space_t*	space;
#endif
3191
	filepath = mem_alloc(strlen(dbname) + strlen(filename)
3192
			     + strlen(fil_path_to_mysql_datadir) + 3);
osku's avatar
osku committed
3193 3194

	sprintf(filepath, "%s/%s/%s", fil_path_to_mysql_datadir, dbname,
3195
		filename);
osku's avatar
osku committed
3196 3197
	srv_normalize_path_for_win(filepath);
#ifdef __WIN__
3198
# ifndef UNIV_HOTBACKUP
osku's avatar
osku committed
3199 3200 3201 3202 3203 3204 3205
	/* If lower_case_table_names is 0 or 2, then MySQL allows database
	directory names with upper case letters. On Windows, all table and
	database names in InnoDB are internally always in lower case. Put the
	file path to lower case, so that we are consistent with InnoDB's
	internal data dictionary. */

	dict_casedn_str(filepath);
3206
# endif /* !UNIV_HOTBACKUP */
osku's avatar
osku committed
3207
#endif
3208
	file = os_file_create_simple_no_error_handling(
3209 3210
		innodb_file_data_key, filepath, OS_FILE_OPEN,
		OS_FILE_READ_ONLY, &success);
osku's avatar
osku committed
3211 3212 3213 3214
	if (!success) {
		/* The following call prints an error message */
		os_file_get_last_error(TRUE);

3215
		fprintf(stderr,
3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238
			"InnoDB: Error: could not open single-table tablespace"
			" file\n"
			"InnoDB: %s!\n"
			"InnoDB: We do not continue the crash recovery,"
			" because the table may become\n"
			"InnoDB: corrupt if we cannot apply the log records"
			" in the InnoDB log to it.\n"
			"InnoDB: To fix the problem and start mysqld:\n"
			"InnoDB: 1) If there is a permission problem"
			" in the file and mysqld cannot\n"
			"InnoDB: open the file, you should"
			" modify the permissions.\n"
			"InnoDB: 2) If the table is not needed, or you can"
			" restore it from a backup,\n"
			"InnoDB: then you can remove the .ibd file,"
			" and InnoDB will do a normal\n"
			"InnoDB: crash recovery and ignore that table.\n"
			"InnoDB: 3) If the file system or the"
			" disk is broken, and you cannot remove\n"
			"InnoDB: the .ibd file, you can set"
			" innodb_force_recovery > 0 in my.cnf\n"
			"InnoDB: and force InnoDB to continue crash"
			" recovery here.\n", filepath);
osku's avatar
osku committed
3239 3240 3241 3242 3243

		mem_free(filepath);

		if (srv_force_recovery > 0) {
			fprintf(stderr,
3244 3245 3246 3247 3248
				"InnoDB: innodb_force_recovery"
				" was set to %lu. Continuing crash recovery\n"
				"InnoDB: even though we cannot access"
				" the .ibd file of this table.\n",
				srv_force_recovery);
osku's avatar
osku committed
3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260
			return;
		}

		exit(1);
	}

	success = os_file_get_size(file, &size_low, &size_high);

	if (!success) {
		/* The following call prints an error message */
		os_file_get_last_error(TRUE);

3261
		fprintf(stderr,
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
			"InnoDB: Error: could not measure the size"
			" of single-table tablespace file\n"
			"InnoDB: %s!\n"
			"InnoDB: We do not continue crash recovery,"
			" because the table will become\n"
			"InnoDB: corrupt if we cannot apply the log records"
			" in the InnoDB log to it.\n"
			"InnoDB: To fix the problem and start mysqld:\n"
			"InnoDB: 1) If there is a permission problem"
			" in the file and mysqld cannot\n"
			"InnoDB: access the file, you should"
			" modify the permissions.\n"
			"InnoDB: 2) If the table is not needed,"
			" or you can restore it from a backup,\n"
			"InnoDB: then you can remove the .ibd file,"
			" and InnoDB will do a normal\n"
			"InnoDB: crash recovery and ignore that table.\n"
			"InnoDB: 3) If the file system or the disk is broken,"
			" and you cannot remove\n"
			"InnoDB: the .ibd file, you can set"
			" innodb_force_recovery > 0 in my.cnf\n"
			"InnoDB: and force InnoDB to continue"
			" crash recovery here.\n", filepath);
osku's avatar
osku committed
3285 3286 3287 3288 3289 3290

		os_file_close(file);
		mem_free(filepath);

		if (srv_force_recovery > 0) {
			fprintf(stderr,
3291 3292 3293 3294 3295
				"InnoDB: innodb_force_recovery"
				" was set to %lu. Continuing crash recovery\n"
				"InnoDB: even though we cannot access"
				" the .ibd file of this table.\n",
				srv_force_recovery);
osku's avatar
osku committed
3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307
			return;
		}

		exit(1);
	}

	/* TODO: What to do in other cases where we cannot access an .ibd
	file during a crash recovery? */

	/* Every .ibd file is created >= 4 pages in size. Smaller files
	cannot be ok. */

3308
	size = (((ib_int64_t)size_high) << 32) + (ib_int64_t)size_low;
osku's avatar
osku committed
3309 3310
#ifndef UNIV_HOTBACKUP
	if (size < FIL_IBD_FILE_INITIAL_SIZE * UNIV_PAGE_SIZE) {
3311
		fprintf(stderr,
3312 3313 3314 3315
			"InnoDB: Error: the size of single-table tablespace"
			" file %s\n"
			"InnoDB: is only %lu %lu, should be at least %lu!",
			filepath,
osku's avatar
osku committed
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335
			(ulong) size_high,
			(ulong) size_low, (ulong) (4 * UNIV_PAGE_SIZE));
		os_file_close(file);
		mem_free(filepath);

		return;
	}
#endif
	/* Read the first page of the tablespace if the size big enough */

	buf2 = ut_malloc(2 * UNIV_PAGE_SIZE);
	/* Align the memory for file i/o if we might have O_DIRECT set */
	page = ut_align(buf2, UNIV_PAGE_SIZE);

	if (size >= FIL_IBD_FILE_INITIAL_SIZE * UNIV_PAGE_SIZE) {
		success = os_file_read(file, page, 0, 0, UNIV_PAGE_SIZE);

		/* We have to read the tablespace id from the file */

		space_id = fsp_header_get_space_id(page);
3336
		flags = fsp_header_get_flags(page);
osku's avatar
osku committed
3337 3338
	} else {
		space_id = ULINT_UNDEFINED;
3339
		flags = 0;
osku's avatar
osku committed
3340 3341 3342 3343
	}

#ifndef UNIV_HOTBACKUP
	if (space_id == ULINT_UNDEFINED || space_id == 0) {
3344
		fprintf(stderr,
3345 3346
			"InnoDB: Error: tablespace id %lu in file %s"
			" is not sensible\n",
osku's avatar
osku committed
3347 3348 3349 3350 3351 3352 3353 3354 3355
			(ulong) space_id,
			filepath);
		goto func_exit;
	}
#else
	if (space_id == ULINT_UNDEFINED || space_id == 0) {
		char*	new_path;

		fprintf(stderr,
3356 3357
			"InnoDB: Renaming tablespace %s of id %lu,\n"
			"InnoDB: to %s_ibbackup_old_vers_<timestamp>\n"
3358
			"InnoDB: because its size %" PRId64 " is too small"
3359 3360 3361 3362 3363 3364
			" (< 4 pages 16 kB each),\n"
			"InnoDB: or the space id in the file header"
			" is not sensible.\n"
			"InnoDB: This can happen in an ibbackup run,"
			" and is not dangerous.\n",
			filepath, space_id, filepath, size);
osku's avatar
osku committed
3365 3366 3367
		os_file_close(file);

		new_path = fil_make_ibbackup_old_name(filepath);
3368
		ut_a(os_file_rename(innodb_file_data_key, filepath, new_path));
osku's avatar
osku committed
3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383

		ut_free(buf2);
		mem_free(filepath);
		mem_free(new_path);

		return;
	}

	/* A backup may contain the same space several times, if the space got
	renamed at a sensitive time. Since it is enough to have one version of
	the space, we rename the file if a space with the same space id
	already exists in the tablespace memory cache. We rather rename the
	file than delete it, because if there is a bug, we do not want to
	destroy valuable data. */

3384
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
3385

3386
	space = fil_space_get_by_id(space_id);
osku's avatar
osku committed
3387 3388 3389 3390 3391

	if (space) {
		char*	new_path;

		fprintf(stderr,
3392 3393 3394 3395 3396 3397 3398 3399
			"InnoDB: Renaming tablespace %s of id %lu,\n"
			"InnoDB: to %s_ibbackup_old_vers_<timestamp>\n"
			"InnoDB: because space %s with the same id\n"
			"InnoDB: was scanned earlier. This can happen"
			" if you have renamed tables\n"
			"InnoDB: during an ibbackup run.\n",
			filepath, space_id, filepath,
			space->name);
osku's avatar
osku committed
3400 3401 3402 3403
		os_file_close(file);

		new_path = fil_make_ibbackup_old_name(filepath);

3404
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3405

3406
		ut_a(os_file_rename(innodb_file_data_key, filepath, new_path));
osku's avatar
osku committed
3407 3408 3409 3410 3411 3412 3413

		ut_free(buf2);
		mem_free(filepath);
		mem_free(new_path);

		return;
	}
3414
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3415
#endif
3416
	success = fil_space_create(filepath, space_id, flags, FIL_TABLESPACE);
osku's avatar
osku committed
3417 3418 3419

	if (!success) {

3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430
		if (srv_force_recovery > 0) {
			fprintf(stderr,
				"InnoDB: innodb_force_recovery"
				" was set to %lu. Continuing crash recovery\n"
				"InnoDB: even though the tablespace creation"
				" of this table failed.\n",
				srv_force_recovery);
			goto func_exit;
		}

		exit(1);
osku's avatar
osku committed
3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443
	}

	/* We do not use the size information we have about the file, because
	the rounding formula for extents and pages is somewhat complex; we
	let fil_node_open() do that task. */

	fil_node_create(filepath, 0, space_id, FALSE);
func_exit:
	os_file_close(file);
	ut_free(buf2);
	mem_free(filepath);
}

3444
/***********************************************************************//**
osku's avatar
osku committed
3445 3446
A fault-tolerant function that tries to read the next file name in the
directory. We retry 100 times if os_file_readdir_next_file() returns -1. The
3447
idea is to read as much good data as we can and jump over bad data.
3448 3449
@return 0 if ok, -1 if error even after the retries, 1 if at the end
of the directory */
osku's avatar
osku committed
3450 3451 3452 3453
static
int
fil_file_readdir_next_file(
/*=======================*/
3454
	ulint*		err,	/*!< out: this is set to DB_ERROR if an error
osku's avatar
osku committed
3455
				was encountered, otherwise not changed */
3456 3457 3458
	const char*	dirname,/*!< in: directory name or path */
	os_file_dir_t	dir,	/*!< in: directory stream */
	os_file_stat_t*	info)	/*!< in/out: buffer where the info is returned */
osku's avatar
osku committed
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469
{
	ulint	i;
	int	ret;

	for (i = 0; i < 100; i++) {
		ret = os_file_readdir_next_file(dirname, dir, info);

		if (ret != -1) {

			return(ret);
		}
3470

osku's avatar
osku committed
3471
		fprintf(stderr,
3472 3473 3474 3475 3476
			"InnoDB: Error: os_file_readdir_next_file()"
			" returned -1 in\n"
			"InnoDB: directory %s\n"
			"InnoDB: Crash recovery may have failed"
			" for some .ibd files!\n", dirname);
osku's avatar
osku committed
3477 3478 3479 3480 3481 3482 3483

		*err = DB_ERROR;
	}

	return(-1);
}

3484
/********************************************************************//**
osku's avatar
osku committed
3485 3486 3487 3488 3489
At the server startup, if we need crash recovery, scans the database
directories under the MySQL datadir, looking for .ibd files. Those files are
single-table tablespaces. We need to know the space id in each of them so that
we know into which file we should look to check the contents of a page stored
in the doublewrite buffer, also to know where to apply log records where the
3490 3491
space id is != 0.
@return	DB_SUCCESS or error number */
3492
UNIV_INTERN
osku's avatar
osku committed
3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503
ulint
fil_load_single_table_tablespaces(void)
/*===================================*/
{
	int		ret;
	char*		dbpath		= NULL;
	ulint		dbpath_len	= 100;
	os_file_dir_t	dir;
	os_file_dir_t	dbdir;
	os_file_stat_t	dbinfo;
	os_file_stat_t	fileinfo;
3504
	ulint		err		= DB_SUCCESS;
osku's avatar
osku committed
3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520

	/* The datadir of MySQL is always the default directory of mysqld */

	dir = os_file_opendir(fil_path_to_mysql_datadir, TRUE);

	if (dir == NULL) {

		return(DB_ERROR);
	}

	dbpath = mem_alloc(dbpath_len);

	/* Scan all directories under the datadir. They are the database
	directories of MySQL. */

	ret = fil_file_readdir_next_file(&err, fil_path_to_mysql_datadir, dir,
3521
					 &dbinfo);
osku's avatar
osku committed
3522 3523 3524 3525 3526
	while (ret == 0) {
		ulint len;
		/* printf("Looking at %s in datadir\n", dbinfo.name); */

		if (dbinfo.type == OS_FILE_TYPE_FILE
3527
		    || dbinfo.type == OS_FILE_TYPE_UNKNOWN) {
osku's avatar
osku committed
3528

3529
			goto next_datadir_item;
osku's avatar
osku committed
3530 3531 3532 3533 3534 3535
		}

		/* We found a symlink or a directory; try opening it to see
		if a symlink is a directory */

		len = strlen(fil_path_to_mysql_datadir)
3536
			+ strlen (dbinfo.name) + 2;
osku's avatar
osku committed
3537 3538 3539 3540 3541 3542 3543 3544 3545 3546
		if (len > dbpath_len) {
			dbpath_len = len;

			if (dbpath) {
				mem_free(dbpath);
			}

			dbpath = mem_alloc(dbpath_len);
		}
		sprintf(dbpath, "%s/%s", fil_path_to_mysql_datadir,
3547
			dbinfo.name);
osku's avatar
osku committed
3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
		srv_normalize_path_for_win(dbpath);

		dbdir = os_file_opendir(dbpath, FALSE);

		if (dbdir != NULL) {
			/* printf("Opened dir %s\n", dbinfo.name); */

			/* We found a database directory; loop through it,
			looking for possible .ibd files in it */

			ret = fil_file_readdir_next_file(&err, dbpath, dbdir,
3559
							 &fileinfo);
osku's avatar
osku committed
3560 3561
			while (ret == 0) {
				/* printf(
3562
				"     Looking at file %s\n", fileinfo.name); */
osku's avatar
osku committed
3563

3564
				if (fileinfo.type == OS_FILE_TYPE_DIR) {
osku's avatar
osku committed
3565

3566
					goto next_file_item;
osku's avatar
osku committed
3567 3568 3569 3570
				}

				/* We found a symlink or a file */
				if (strlen(fileinfo.name) > 4
3571 3572 3573
				    && 0 == strcmp(fileinfo.name
						   + strlen(fileinfo.name) - 4,
						   ".ibd")) {
3574
					/* The name ends in .ibd; try opening
osku's avatar
osku committed
3575
					the file */
3576 3577
					fil_load_single_table_tablespace(
						dbinfo.name, fileinfo.name);
osku's avatar
osku committed
3578 3579 3580
				}
next_file_item:
				ret = fil_file_readdir_next_file(&err,
3581 3582
								 dbpath, dbdir,
								 &fileinfo);
osku's avatar
osku committed
3583 3584 3585
			}

			if (0 != os_file_closedir(dbdir)) {
3586 3587
				fputs("InnoDB: Warning: could not"
				      " close database directory ", stderr);
osku's avatar
osku committed
3588 3589 3590 3591 3592 3593
				ut_print_filename(stderr, dbpath);
				putc('\n', stderr);

				err = DB_ERROR;
			}
		}
3594

osku's avatar
osku committed
3595 3596
next_datadir_item:
		ret = fil_file_readdir_next_file(&err,
3597 3598
						 fil_path_to_mysql_datadir,
						 dir, &dbinfo);
osku's avatar
osku committed
3599 3600 3601 3602 3603 3604
	}

	mem_free(dbpath);

	if (0 != os_file_closedir(dir)) {
		fprintf(stderr,
3605
			"InnoDB: Error: could not close MySQL datadir\n");
osku's avatar
osku committed
3606 3607 3608 3609 3610 3611 3612

		return(DB_ERROR);
	}

	return(err);
}

3613
/*******************************************************************//**
osku's avatar
osku committed
3614
Returns TRUE if a single-table tablespace does not exist in the memory cache,
3615 3616
or is being deleted there.
@return	TRUE if does not exist or is being\ deleted */
3617
UNIV_INTERN
osku's avatar
osku committed
3618 3619 3620
ibool
fil_tablespace_deleted_or_being_deleted_in_mem(
/*===========================================*/
3621 3622
	ulint		id,	/*!< in: space id */
	ib_int64_t	version)/*!< in: tablespace_version should be this; if
osku's avatar
osku committed
3623 3624 3625 3626 3627
				you pass -1 as the value of this, then this
				parameter is ignored */
{
	fil_space_t*	space;

3628
	ut_ad(fil_system);
osku's avatar
osku committed
3629

3630
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
3631

3632
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
3633 3634

	if (space == NULL || space->is_being_deleted) {
3635
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3636 3637 3638 3639

		return(TRUE);
	}

3640
	if (version != ((ib_int64_t)-1)
3641
	    && space->tablespace_version != version) {
3642
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3643 3644 3645 3646

		return(TRUE);
	}

3647
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3648 3649 3650 3651

	return(FALSE);
}

3652
/*******************************************************************//**
3653 3654
Returns TRUE if a single-table tablespace exists in the memory cache.
@return	TRUE if exists */
3655
UNIV_INTERN
osku's avatar
osku committed
3656 3657 3658
ibool
fil_tablespace_exists_in_mem(
/*=========================*/
3659
	ulint	id)	/*!< in: space id */
osku's avatar
osku committed
3660 3661 3662
{
	fil_space_t*	space;

3663
	ut_ad(fil_system);
osku's avatar
osku committed
3664

3665
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
3666

3667
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
3668

3669
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3670

3671
	return(space != NULL);
osku's avatar
osku committed
3672 3673
}

3674
/*******************************************************************//**
osku's avatar
osku committed
3675 3676
Returns TRUE if a matching tablespace exists in the InnoDB tablespace memory
cache. Note that if we have not done a crash recovery at the database startup,
3677 3678
there may be many tablespaces which are not yet in the memory cache.
@return	TRUE if a matching tablespace exists in the memory cache */
3679
UNIV_INTERN
osku's avatar
osku committed
3680 3681 3682
ibool
fil_space_for_table_exists_in_mem(
/*==============================*/
3683 3684
	ulint		id,		/*!< in: space id */
	const char*	name,		/*!< in: table name in the standard
osku's avatar
osku committed
3685 3686
					'databasename/tablename' format or
					the dir path to a temp table */
3687
	ibool		is_temp,	/*!< in: TRUE if created with CREATE
osku's avatar
osku committed
3688
					TEMPORARY TABLE */
3689
	ibool		mark_space,	/*!< in: in crash recovery, at database
osku's avatar
osku committed
3690 3691 3692 3693 3694 3695
					startup we mark all spaces which have
					an associated table in the InnoDB
					data dictionary, so that
					we can print a warning about orphaned
					tablespaces */
	ibool		print_error_if_does_not_exist)
3696
					/*!< in: print detailed error
osku's avatar
osku committed
3697 3698 3699 3700 3701 3702 3703 3704
					information to the .err log if a
					matching tablespace is not found from
					memory */
{
	fil_space_t*	namespace;
	fil_space_t*	space;
	char*		path;

3705
	ut_ad(fil_system);
osku's avatar
osku committed
3706

3707
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
3708 3709 3710 3711 3712

	path = fil_make_ibd_name(name, is_temp);

	/* Look if there is a space with the same id */

3713
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
3714 3715 3716 3717

	/* Look if there is a space with the same name; the name is the
	directory path from the datadir to the file */

3718
	namespace = fil_space_get_by_name(path);
osku's avatar
osku committed
3719 3720
	if (space && space == namespace) {
		/* Found */
3721

osku's avatar
osku committed
3722 3723 3724 3725 3726
		if (mark_space) {
			space->mark = TRUE;
		}

		mem_free(path);
3727
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3728 3729 3730 3731 3732

		return(TRUE);
	}

	if (!print_error_if_does_not_exist) {
3733

osku's avatar
osku committed
3734
		mem_free(path);
3735
		mutex_exit(&fil_system->mutex);
3736

osku's avatar
osku committed
3737 3738 3739 3740 3741
		return(FALSE);
	}

	if (space == NULL) {
		if (namespace == NULL) {
3742
			ut_print_timestamp(stderr);
3743
			fputs("  InnoDB: Error: table ", stderr);
osku's avatar
osku committed
3744 3745
			ut_print_filename(stderr, name);
			fprintf(stderr, "\n"
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756
				"InnoDB: in InnoDB data dictionary"
				" has tablespace id %lu,\n"
				"InnoDB: but tablespace with that id"
				" or name does not exist. Have\n"
				"InnoDB: you deleted or moved .ibd files?\n"
				"InnoDB: This may also be a table created with"
				" CREATE TEMPORARY TABLE\n"
				"InnoDB: whose .ibd and .frm files"
				" MySQL automatically removed, but the\n"
				"InnoDB: table still exists in the"
				" InnoDB internal data dictionary.\n",
osku's avatar
osku committed
3757 3758
				(ulong) id);
		} else {
3759
			ut_print_timestamp(stderr);
3760
			fputs("  InnoDB: Error: table ", stderr);
osku's avatar
osku committed
3761 3762
			ut_print_filename(stderr, name);
			fprintf(stderr, "\n"
3763 3764 3765 3766 3767 3768 3769
				"InnoDB: in InnoDB data dictionary has"
				" tablespace id %lu,\n"
				"InnoDB: but a tablespace with that id"
				" does not exist. There is\n"
				"InnoDB: a tablespace of name %s and id %lu,"
				" though. Have\n"
				"InnoDB: you deleted or moved .ibd files?\n",
osku's avatar
osku committed
3770 3771 3772
				(ulong) id, namespace->name,
				(ulong) namespace->id);
		}
3773 3774
error_exit:
		fputs("InnoDB: Please refer to\n"
3775
		      "InnoDB: " REFMAN "innodb-troubleshooting-datadict.html\n"
3776
		      "InnoDB: for how to resolve the issue.\n", stderr);
osku's avatar
osku committed
3777 3778

		mem_free(path);
3779
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3780 3781 3782 3783 3784 3785

		return(FALSE);
	}

	if (0 != strcmp(space->name, path)) {
		ut_print_timestamp(stderr);
3786
		fputs("  InnoDB: Error: table ", stderr);
osku's avatar
osku committed
3787 3788
		ut_print_filename(stderr, name);
		fprintf(stderr, "\n"
3789 3790 3791 3792 3793 3794
			"InnoDB: in InnoDB data dictionary has"
			" tablespace id %lu,\n"
			"InnoDB: but the tablespace with that id"
			" has name %s.\n"
			"InnoDB: Have you deleted or moved .ibd files?\n",
			(ulong) id, space->name);
osku's avatar
osku committed
3795 3796

		if (namespace != NULL) {
3797 3798 3799
			fputs("InnoDB: There is a tablespace"
			      " with the right name\n"
			      "InnoDB: ", stderr);
osku's avatar
osku committed
3800 3801 3802 3803 3804 3805 3806 3807 3808
			ut_print_filename(stderr, namespace->name);
			fprintf(stderr, ", but its id is %lu.\n",
				(ulong) namespace->id);
		}

		goto error_exit;
	}

	mem_free(path);
3809
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3810 3811 3812 3813

	return(FALSE);
}

3814
/*******************************************************************//**
osku's avatar
osku committed
3815
Checks if a single-table tablespace for a given table name exists in the
3816 3817
tablespace memory cache.
@return	space id, ULINT_UNDEFINED if not found */
osku's avatar
osku committed
3818 3819 3820 3821
static
ulint
fil_get_space_id_for_table(
/*=======================*/
3822
	const char*	name)	/*!< in: table name in the standard
osku's avatar
osku committed
3823 3824 3825 3826 3827 3828
				'databasename/tablename' format */
{
	fil_space_t*	namespace;
	ulint		id		= ULINT_UNDEFINED;
	char*		path;

3829
	ut_ad(fil_system);
osku's avatar
osku committed
3830

3831
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
3832 3833 3834 3835 3836 3837

	path = fil_make_ibd_name(name, FALSE);

	/* Look if there is a space with the same name; the name is the
	directory path to the file */

3838 3839
	namespace = fil_space_get_by_name(path);

osku's avatar
osku committed
3840 3841
	if (namespace) {
		id = namespace->id;
3842
	}
osku's avatar
osku committed
3843 3844 3845

	mem_free(path);

3846
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3847 3848 3849 3850

	return(id);
}

3851
/**********************************************************************//**
osku's avatar
osku committed
3852 3853
Tries to extend a data file so that it would accommodate the number of pages
given. The tablespace must be cached in the memory cache. If the space is big
3854 3855
enough already, does nothing.
@return	TRUE if success */
3856
UNIV_INTERN
osku's avatar
osku committed
3857 3858 3859
ibool
fil_extend_space_to_desired_size(
/*=============================*/
3860
	ulint*	actual_size,	/*!< out: size of the space after extension;
osku's avatar
osku committed
3861 3862
				if we ran out of disk space this may be lower
				than the desired size */
3863 3864
	ulint	space_id,	/*!< in: space id */
	ulint	size_after_extend)/*!< in: desired size in pages after the
osku's avatar
osku committed
3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876
				extension; if the current space size is bigger
				than this already, the function does nothing */
{
	fil_node_t*	node;
	fil_space_t*	space;
	byte*		buf2;
	byte*		buf;
	ulint		buf_size;
	ulint		start_page_no;
	ulint		file_start_page_no;
	ulint		offset_high;
	ulint		offset_low;
3877
	ulint		page_size;
osku's avatar
osku committed
3878 3879 3880 3881
	ibool		success		= TRUE;

	fil_mutex_enter_and_prepare_for_io(space_id);

3882
	space = fil_space_get_by_id(space_id);
osku's avatar
osku committed
3883 3884 3885 3886 3887 3888 3889
	ut_a(space);

	if (space->size >= size_after_extend) {
		/* Space already big enough */

		*actual_size = space->size;

3890
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3891 3892 3893

		return(TRUE);
	}
3894

3895
	page_size = dict_table_flags_to_zip_size(space->flags);
3896 3897 3898 3899
	if (!page_size) {
		page_size = UNIV_PAGE_SIZE;
	}

osku's avatar
osku committed
3900 3901
	node = UT_LIST_GET_LAST(space->chain);

3902
	fil_node_prepare_for_io(node, fil_system, space);
osku's avatar
osku committed
3903 3904 3905 3906 3907

	start_page_no = space->size;
	file_start_page_no = space->size - node->size;

	/* Extend at most 64 pages at a time */
3908
	buf_size = ut_min(64, size_after_extend - start_page_no) * page_size;
3909 3910
	buf2 = mem_alloc(buf_size + page_size);
	buf = ut_align(buf2, page_size);
osku's avatar
osku committed
3911 3912 3913 3914

	memset(buf, 0, buf_size);

	while (start_page_no < size_after_extend) {
3915
		ulint	n_pages = ut_min(buf_size / page_size,
3916
					 size_after_extend - start_page_no);
osku's avatar
osku committed
3917 3918

		offset_high = (start_page_no - file_start_page_no)
3919
			/ (4096 * ((1024 * 1024) / page_size));
osku's avatar
osku committed
3920
		offset_low  = ((start_page_no - file_start_page_no)
3921 3922
			       % (4096 * ((1024 * 1024) / page_size)))
			* page_size;
osku's avatar
osku committed
3923 3924 3925
#ifdef UNIV_HOTBACKUP
		success = os_file_write(node->name, node->handle, buf,
					offset_low, offset_high,
3926
					page_size * n_pages);
osku's avatar
osku committed
3927 3928
#else
		success = os_aio(OS_FILE_WRITE, OS_AIO_SYNC,
3929 3930 3931 3932
				 node->name, node->handle, buf,
				 offset_low, offset_high,
				 page_size * n_pages,
				 NULL, NULL);
osku's avatar
osku committed
3933 3934 3935 3936 3937 3938 3939 3940 3941
#endif
		if (success) {
			node->size += n_pages;
			space->size += n_pages;

			os_has_said_disk_full = FALSE;
		} else {
			/* Let us measure the size of the file to determine
			how much we were able to extend it */
3942

osku's avatar
osku committed
3943
			n_pages = ((ulint)
3944 3945
				   (os_file_get_size_as_iblonglong(
					   node->handle)
3946
				    / page_size)) - node->size;
osku's avatar
osku committed
3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958

			node->size += n_pages;
			space->size += n_pages;

			break;
		}

		start_page_no += n_pages;
	}

	mem_free(buf2);

3959
	fil_node_complete_io(node, fil_system, OS_FILE_WRITE);
osku's avatar
osku committed
3960 3961 3962

	*actual_size = space->size;

3963
#ifndef UNIV_HOTBACKUP
osku's avatar
osku committed
3964
	if (space_id == 0) {
3965
		ulint pages_per_mb = (1024 * 1024) / page_size;
osku's avatar
osku committed
3966 3967 3968 3969

		/* Keep the last data file size info up to date, rounded to
		full megabytes */

3970 3971
		srv_data_file_sizes[srv_n_data_files - 1]
			= (node->size / pages_per_mb) * pages_per_mb;
osku's avatar
osku committed
3972
	}
3973
#endif /* !UNIV_HOTBACKUP */
osku's avatar
osku committed
3974 3975

	/*
3976
	printf("Extended %s to %lu, actual size %lu pages\n", space->name,
3977
	size_after_extend, *actual_size); */
3978
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
3979 3980 3981 3982 3983 3984 3985

	fil_flush(space_id);

	return(success);
}

#ifdef UNIV_HOTBACKUP
3986
/********************************************************************//**
osku's avatar
osku committed
3987 3988 3989 3990
Extends all tablespaces to the size stored in the space header. During the
ibbackup --apply-log phase we extended the spaces on-demand so that log records
could be applied, but that may have left spaces still too small compared to
the size stored in the space header. */
3991
UNIV_INTERN
osku's avatar
osku committed
3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
void
fil_extend_tablespaces_to_stored_len(void)
/*======================================*/
{
	fil_space_t*	space;
	byte*		buf;
	ulint		actual_size;
	ulint		size_in_header;
	ulint		error;
	ibool		success;

	buf = mem_alloc(UNIV_PAGE_SIZE);

4005
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4006

4007
	space = UT_LIST_GET_FIRST(fil_system->space_list);
osku's avatar
osku committed
4008 4009

	while (space) {
4010
		ut_a(space->purpose == FIL_TABLESPACE);
osku's avatar
osku committed
4011

4012
		mutex_exit(&fil_system->mutex); /* no need to protect with a
4013 4014
					      mutex, because this is a
					      single-threaded operation */
4015 4016
		error = fil_read(TRUE, space->id,
				 dict_table_flags_to_zip_size(space->flags),
4017
				 0, 0, UNIV_PAGE_SIZE, buf, NULL);
osku's avatar
osku committed
4018 4019 4020 4021
		ut_a(error == DB_SUCCESS);

		size_in_header = fsp_get_size_low(buf);

4022 4023
		success = fil_extend_space_to_desired_size(
			&actual_size, space->id, size_in_header);
osku's avatar
osku committed
4024 4025
		if (!success) {
			fprintf(stderr,
4026 4027 4028 4029 4030 4031 4032 4033
				"InnoDB: Error: could not extend the"
				" tablespace of %s\n"
				"InnoDB: to the size stored in header,"
				" %lu pages;\n"
				"InnoDB: size after extension %lu pages\n"
				"InnoDB: Check that you have free disk space"
				" and retry!\n",
				space->name, size_in_header, actual_size);
4034
			exit(1);
osku's avatar
osku committed
4035 4036
		}

4037
		mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4038 4039 4040 4041

		space = UT_LIST_GET_NEXT(space_list, space);
	}

4042
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4043 4044 4045 4046 4047 4048 4049

	mem_free(buf);
}
#endif

/*========== RESERVE FREE EXTENTS (for a B-tree split, for example) ===*/

4050
/*******************************************************************//**
4051 4052
Tries to reserve free extents in a file space.
@return	TRUE if succeed */
4053
UNIV_INTERN
osku's avatar
osku committed
4054 4055 4056
ibool
fil_space_reserve_free_extents(
/*===========================*/
4057 4058 4059
	ulint	id,		/*!< in: space id */
	ulint	n_free_now,	/*!< in: number of free extents now */
	ulint	n_to_reserve)	/*!< in: how many one wants to reserve */
osku's avatar
osku committed
4060 4061 4062 4063
{
	fil_space_t*	space;
	ibool		success;

4064
	ut_ad(fil_system);
osku's avatar
osku committed
4065

4066
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4067

4068
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
4069 4070 4071 4072 4073 4074 4075 4076 4077

	ut_a(space);

	if (space->n_reserved_extents + n_to_reserve > n_free_now) {
		success = FALSE;
	} else {
		space->n_reserved_extents += n_to_reserve;
		success = TRUE;
	}
4078

4079
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4080 4081 4082 4083

	return(success);
}

4084
/*******************************************************************//**
osku's avatar
osku committed
4085
Releases free extents in a file space. */
4086
UNIV_INTERN
osku's avatar
osku committed
4087 4088 4089
void
fil_space_release_free_extents(
/*===========================*/
4090 4091
	ulint	id,		/*!< in: space id */
	ulint	n_reserved)	/*!< in: how many one reserved */
osku's avatar
osku committed
4092 4093 4094
{
	fil_space_t*	space;

4095
	ut_ad(fil_system);
osku's avatar
osku committed
4096

4097
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4098

4099
	space = fil_space_get_by_id(id);
osku's avatar
osku committed
4100 4101 4102

	ut_a(space);
	ut_a(space->n_reserved_extents >= n_reserved);
4103

osku's avatar
osku committed
4104
	space->n_reserved_extents -= n_reserved;
4105

4106
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4107 4108
}

4109
/*******************************************************************//**
osku's avatar
osku committed
4110 4111
Gets the number of reserved extents. If the database is silent, this number
should be zero. */
4112
UNIV_INTERN
osku's avatar
osku committed
4113 4114 4115
ulint
fil_space_get_n_reserved_extents(
/*=============================*/
4116
	ulint	id)		/*!< in: space id */
osku's avatar
osku committed
4117 4118 4119 4120
{
	fil_space_t*	space;
	ulint		n;

4121
	ut_ad(fil_system);
osku's avatar
osku committed
4122

4123
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4124

4125
	space = fil_space_get_by_id(id);
4126

osku's avatar
osku committed
4127 4128 4129
	ut_a(space);

	n = space->n_reserved_extents;
4130

4131
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4132 4133 4134 4135 4136 4137

	return(n);
}

/*============================ FILE I/O ================================*/

4138
/********************************************************************//**
osku's avatar
osku committed
4139 4140 4141 4142 4143 4144 4145 4146 4147 4148
NOTE: you must call fil_mutex_enter_and_prepare_for_io() first!

Prepares a file node for i/o. Opens the file if it is closed. Updates the
pending i/o's field in the node and the system appropriately. Takes the node
off the LRU list if it is in the LRU list. The caller must hold the fil_sys
mutex. */
static
void
fil_node_prepare_for_io(
/*====================*/
4149 4150 4151
	fil_node_t*	node,	/*!< in: file node */
	fil_system_t*	system,	/*!< in: tablespace memory cache */
	fil_space_t*	space)	/*!< in: space */
osku's avatar
osku committed
4152 4153 4154
{
	ut_ad(node && system && space);
	ut_ad(mutex_own(&(system->mutex)));
4155

osku's avatar
osku committed
4156 4157 4158
	if (system->n_open > system->max_n_open + 5) {
		ut_print_timestamp(stderr);
		fprintf(stderr,
4159 4160
			"  InnoDB: Warning: open files %lu"
			" exceeds the limit %lu\n",
osku's avatar
osku committed
4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172
			(ulong) system->n_open,
			(ulong) system->max_n_open);
	}

	if (node->open == FALSE) {
		/* File is closed: open it */
		ut_a(node->n_pending == 0);

		fil_node_open_file(node, system, space);
	}

	if (node->n_pending == 0 && space->purpose == FIL_TABLESPACE
4173
	    && space->id != 0) {
osku's avatar
osku committed
4174 4175 4176 4177 4178 4179 4180 4181 4182 4183
		/* The node is in the LRU list, remove it */

		ut_a(UT_LIST_GET_LEN(system->LRU) > 0);

		UT_LIST_REMOVE(LRU, system->LRU, node);
	}

	node->n_pending++;
}

4184
/********************************************************************//**
osku's avatar
osku committed
4185 4186 4187 4188 4189 4190
Updates the data structures when an i/o operation finishes. Updates the
pending i/o's field in the node appropriately. */
static
void
fil_node_complete_io(
/*=================*/
4191 4192 4193
	fil_node_t*	node,	/*!< in: file node */
	fil_system_t*	system,	/*!< in: tablespace memory cache */
	ulint		type)	/*!< in: OS_FILE_WRITE or OS_FILE_READ; marks
osku's avatar
osku committed
4194 4195 4196 4197 4198 4199 4200 4201
				the node as modified if
				type == OS_FILE_WRITE */
{
	ut_ad(node);
	ut_ad(system);
	ut_ad(mutex_own(&(system->mutex)));

	ut_a(node->n_pending > 0);
4202

osku's avatar
osku committed
4203 4204 4205 4206 4207
	node->n_pending--;

	if (type == OS_FILE_WRITE) {
		system->modification_counter++;
		node->modification_counter = system->modification_counter;
4208 4209 4210 4211 4212

		if (!node->space->is_in_unflushed_spaces) {

			node->space->is_in_unflushed_spaces = TRUE;
			UT_LIST_ADD_FIRST(unflushed_spaces,
4213 4214
					  system->unflushed_spaces,
					  node->space);
4215
		}
osku's avatar
osku committed
4216
	}
4217

osku's avatar
osku committed
4218
	if (node->n_pending == 0 && node->space->purpose == FIL_TABLESPACE
4219
	    && node->space->id != 0) {
osku's avatar
osku committed
4220 4221 4222 4223 4224
		/* The node must be put back to the LRU list */
		UT_LIST_ADD_FIRST(LRU, system->LRU, node);
	}
}

4225
/********************************************************************//**
4226 4227 4228 4229 4230
Report information about an invalid page access. */
static
void
fil_report_invalid_page_access(
/*===========================*/
4231 4232 4233 4234 4235 4236
	ulint		block_offset,	/*!< in: block offset */
	ulint		space_id,	/*!< in: space id */
	const char*	space_name,	/*!< in: space name */
	ulint		byte_offset,	/*!< in: byte offset */
	ulint		len,		/*!< in: I/O length */
	ulint		type)		/*!< in: I/O type */
4237 4238
{
	fprintf(stderr,
4239 4240 4241 4242 4243 4244 4245 4246 4247 4248
		"InnoDB: Error: trying to access page number %lu"
		" in space %lu,\n"
		"InnoDB: space name %s,\n"
		"InnoDB: which is outside the tablespace bounds.\n"
		"InnoDB: Byte offset %lu, len %lu, i/o type %lu.\n"
		"InnoDB: If you get this error at mysqld startup,"
		" please check that\n"
		"InnoDB: your my.cnf matches the ibdata files"
		" that you have in the\n"
		"InnoDB: MySQL server.\n",
4249 4250 4251 4252
		(ulong) block_offset, (ulong) space_id, space_name,
		(ulong) byte_offset, (ulong) len, (ulong) type);
}

4253
/********************************************************************//**
4254
Reads or writes data. This operation is asynchronous (aio).
4255 4256
@return DB_SUCCESS, or DB_TABLESPACE_DELETED if we are trying to do
i/o on a tablespace which does not exist */
4257
UNIV_INTERN
osku's avatar
osku committed
4258 4259 4260
ulint
fil_io(
/*===*/
4261
	ulint	type,		/*!< in: OS_FILE_READ or OS_FILE_WRITE,
osku's avatar
osku committed
4262 4263 4264 4265 4266 4267 4268 4269
				ORed to OS_FILE_LOG, if a log i/o
				and ORed to OS_AIO_SIMULATED_WAKE_LATER
				if simulated aio and we want to post a
				batch of i/os; NOTE that a simulated batch
				may introduce hidden chances of deadlocks,
				because i/os are not actually handled until
				all have been posted: use with great
				caution! */
4270 4271 4272
	ibool	sync,		/*!< in: TRUE if synchronous aio is desired */
	ulint	space_id,	/*!< in: space id */
	ulint	zip_size,	/*!< in: compressed page size in bytes;
4273
				0 for uncompressed pages */
4274 4275
	ulint	block_offset,	/*!< in: offset in number of blocks */
	ulint	byte_offset,	/*!< in: remainder of offset in bytes; in
osku's avatar
osku committed
4276 4277
				aio this must be divisible by the OS block
				size */
4278
	ulint	len,		/*!< in: how many bytes to read or write; this
osku's avatar
osku committed
4279 4280
				must not cross a file boundary; in aio this
				must be a block size multiple */
4281
	void*	buf,		/*!< in/out: buffer where to store read data
osku's avatar
osku committed
4282 4283
				or from where to write; in aio this must be
				appropriately aligned */
4284
	void*	message)	/*!< in: message for aio handler if non-sync
osku's avatar
osku committed
4285 4286 4287 4288 4289 4290 4291 4292 4293 4294
				aio used, else ignored */
{
	ulint		mode;
	fil_space_t*	space;
	fil_node_t*	node;
	ulint		offset_high;
	ulint		offset_low;
	ibool		ret;
	ulint		is_log;
	ulint		wake_later;
4295

osku's avatar
osku committed
4296 4297 4298 4299 4300
	is_log = type & OS_FILE_LOG;
	type = type & ~OS_FILE_LOG;

	wake_later = type & OS_AIO_SIMULATED_WAKE_LATER;
	type = type & ~OS_AIO_SIMULATED_WAKE_LATER;
4301

osku's avatar
osku committed
4302
	ut_ad(byte_offset < UNIV_PAGE_SIZE);
4303 4304
	ut_ad(!zip_size || !byte_offset);
	ut_ad(ut_is_2pow(zip_size));
osku's avatar
osku committed
4305 4306
	ut_ad(buf);
	ut_ad(len > 0);
4307 4308 4309
#if (1 << UNIV_PAGE_SIZE_SHIFT) != UNIV_PAGE_SIZE
# error "(1 << UNIV_PAGE_SIZE_SHIFT) != UNIV_PAGE_SIZE"
#endif
osku's avatar
osku committed
4310
	ut_ad(fil_validate());
4311 4312
#ifndef UNIV_HOTBACKUP
# ifndef UNIV_LOG_DEBUG
osku's avatar
osku committed
4313 4314
	/* ibuf bitmap pages must be read in the sync aio mode: */
	ut_ad(recv_no_ibuf_operations || (type == OS_FILE_WRITE)
4315 4316
	      || !ibuf_bitmap_page(zip_size, block_offset)
	      || sync || is_log);
osku's avatar
osku committed
4317
	ut_ad(!ibuf_inside() || is_log || (type == OS_FILE_WRITE)
4318
	      || ibuf_page(space_id, zip_size, block_offset, NULL));
4319
# endif /* UNIV_LOG_DEBUG */
osku's avatar
osku committed
4320 4321 4322 4323
	if (sync) {
		mode = OS_AIO_SYNC;
	} else if (is_log) {
		mode = OS_AIO_LOG;
4324
	} else if (type == OS_FILE_READ
4325
		   && !recv_no_ibuf_operations
4326 4327
		   && ibuf_page(space_id, zip_size, block_offset, NULL)) {
		mode = OS_AIO_IBUF;
osku's avatar
osku committed
4328 4329 4330
	} else {
		mode = OS_AIO_NORMAL;
	}
4331 4332 4333 4334
#else /* !UNIV_HOTBACKUP */
	ut_a(sync);
	mode = OS_AIO_SYNC;
#endif /* !UNIV_HOTBACKUP */
osku's avatar
osku committed
4335

4336 4337 4338 4339 4340
	if (type == OS_FILE_READ) {
		srv_data_read+= len;
	} else if (type == OS_FILE_WRITE) {
		srv_data_written+= len;
	}
osku's avatar
osku committed
4341 4342 4343 4344 4345

	/* Reserve the fil_system mutex and make sure that we can open at
	least one file while holding it, if the file is not already open */

	fil_mutex_enter_and_prepare_for_io(space_id);
4346

4347 4348
	space = fil_space_get_by_id(space_id);

osku's avatar
osku committed
4349
	if (!space) {
4350
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4351 4352 4353

		ut_print_timestamp(stderr);
		fprintf(stderr,
4354 4355 4356 4357
			"  InnoDB: Error: trying to do i/o"
			" to a tablespace which does not exist.\n"
			"InnoDB: i/o type %lu, space id %lu,"
			" page no. %lu, i/o length %lu bytes\n",
osku's avatar
osku committed
4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368
			(ulong) type, (ulong) space_id, (ulong) block_offset,
			(ulong) len);

		return(DB_TABLESPACE_DELETED);
	}

	ut_ad((mode != OS_AIO_IBUF) || (space->purpose == FIL_TABLESPACE));

	node = UT_LIST_GET_FIRST(space->chain);

	for (;;) {
4369
		if (UNIV_UNLIKELY(node == NULL)) {
4370 4371 4372
			fil_report_invalid_page_access(
				block_offset, space_id, space->name,
				byte_offset, len, type);
4373

osku's avatar
osku committed
4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390
			ut_error;
		}

		if (space->id != 0 && node->size == 0) {
			/* We do not know the size of a single-table tablespace
			before we open the file */

			break;
		}

		if (node->size > block_offset) {
			/* Found! */
			break;
		} else {
			block_offset -= node->size;
			node = UT_LIST_GET_NEXT(chain, node);
		}
4391 4392
	}

osku's avatar
osku committed
4393
	/* Open file if closed */
4394
	fil_node_prepare_for_io(node, fil_system, space);
osku's avatar
osku committed
4395 4396 4397

	/* Check that at least the start offset is within the bounds of a
	single-table tablespace */
4398 4399
	if (UNIV_UNLIKELY(node->size <= block_offset)
	    && space->id != 0 && space->purpose == FIL_TABLESPACE) {
osku's avatar
osku committed
4400

4401 4402 4403
		fil_report_invalid_page_access(
			block_offset, space_id, space->name, byte_offset,
			len, type);
4404 4405

		ut_error;
osku's avatar
osku committed
4406 4407
	}

4408 4409
	/* Now we have made the changes in the data structures of fil_system */
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4410 4411 4412

	/* Calculate the low 32 bits and the high 32 bits of the file offset */

4413 4414 4415
	if (!zip_size) {
		offset_high = (block_offset >> (32 - UNIV_PAGE_SIZE_SHIFT));
		offset_low  = ((block_offset << UNIV_PAGE_SIZE_SHIFT)
4416
			       & 0xFFFFFFFFUL) + byte_offset;
osku's avatar
osku committed
4417

4418
		ut_a(node->size - block_offset
4419 4420
		     >= ((byte_offset + len + (UNIV_PAGE_SIZE - 1))
			 / UNIV_PAGE_SIZE));
4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432
	} else {
		ulint	zip_size_shift;
		switch (zip_size) {
		case 1024: zip_size_shift = 10; break;
		case 2048: zip_size_shift = 11; break;
		case 4096: zip_size_shift = 12; break;
		case 8192: zip_size_shift = 13; break;
		case 16384: zip_size_shift = 14; break;
		default: ut_error;
		}
		offset_high = block_offset >> (32 - zip_size_shift);
		offset_low = (block_offset << zip_size_shift & 0xFFFFFFFFUL)
4433
			+ byte_offset;
4434
		ut_a(node->size - block_offset
4435
		     >= (len + (zip_size - 1)) / zip_size);
4436
	}
osku's avatar
osku committed
4437 4438 4439 4440 4441 4442 4443 4444 4445 4446

	/* Do aio */

	ut_a(byte_offset % OS_FILE_LOG_BLOCK_SIZE == 0);
	ut_a((len % OS_FILE_LOG_BLOCK_SIZE) == 0);

#ifdef UNIV_HOTBACKUP
	/* In ibbackup do normal i/o, not aio */
	if (type == OS_FILE_READ) {
		ret = os_file_read(node->handle, buf, offset_low, offset_high,
4447
				   len);
osku's avatar
osku committed
4448 4449
	} else {
		ret = os_file_write(node->name, node->handle, buf,
4450
				    offset_low, offset_high, len);
osku's avatar
osku committed
4451 4452 4453 4454
	}
#else
	/* Queue the aio request */
	ret = os_aio(type, mode | wake_later, node->name, node->handle, buf,
4455
		     offset_low, offset_high, len, node, message);
osku's avatar
osku committed
4456 4457 4458 4459 4460 4461
#endif
	ut_a(ret);

	if (mode == OS_AIO_SYNC) {
		/* The i/o operation is already completed when we return from
		os_aio: */
4462

4463
		mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4464

4465
		fil_node_complete_io(node, fil_system, type);
osku's avatar
osku committed
4466

4467
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4468 4469 4470 4471 4472 4473 4474

		ut_ad(fil_validate());
	}

	return(DB_SUCCESS);
}

4475
#ifndef UNIV_HOTBACKUP
4476
/**********************************************************************//**
osku's avatar
osku committed
4477 4478 4479 4480
Waits for an aio operation to complete. This function is used to write the
handler for completed requests. The aio array of pending requests is divided
into segments (see os0file.c for more info). The thread specifies which
segment it wants to wait for. */
4481
UNIV_INTERN
osku's avatar
osku committed
4482 4483 4484
void
fil_aio_wait(
/*=========*/
4485
	ulint	segment)	/*!< in: the number of the segment in the aio
4486
				array to wait for */
osku's avatar
osku committed
4487
{
4488
	ibool		ret;
osku's avatar
osku committed
4489 4490 4491
	fil_node_t*	fil_node;
	void*		message;
	ulint		type;
4492

osku's avatar
osku committed
4493 4494
	ut_ad(fil_validate());

inaam's avatar
inaam committed
4495
	if (srv_use_native_aio) {
osku's avatar
osku committed
4496 4497 4498
		srv_set_io_thread_op_info(segment, "native aio handle");
#ifdef WIN_ASYNC_IO
		ret = os_aio_windows_handle(segment, 0, &fil_node,
4499
					    &message, &type);
inaam's avatar
inaam committed
4500 4501 4502
#elif defined(LINUX_NATIVE_AIO)
		ret = os_aio_linux_handle(segment, &fil_node,
					  &message, &type);
osku's avatar
osku committed
4503 4504 4505 4506 4507 4508 4509 4510
#else
		ret = 0; /* Eliminate compiler warning */
		ut_error;
#endif
	} else {
		srv_set_io_thread_op_info(segment, "simulated aio handle");

		ret = os_aio_simulated_handle(segment, &fil_node,
4511
					      &message, &type);
osku's avatar
osku committed
4512
	}
4513

osku's avatar
osku committed
4514 4515 4516 4517
	ut_a(ret);

	srv_set_io_thread_op_info(segment, "complete io for fil node");

4518
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4519 4520 4521

	fil_node_complete_io(fil_node, fil_system, type);

4522
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4523 4524 4525 4526 4527 4528 4529 4530 4531

	ut_ad(fil_validate());

	/* Do the i/o handling */
	/* IMPORTANT: since i/o handling for reads will read also the insert
	buffer in tablespace 0, you have to be very careful not to introduce
	deadlocks in the i/o system. We keep tablespace 0 data files always
	open, and use a special i/o thread to serve insert buffer requests. */

4532
	if (fil_node->space->purpose == FIL_TABLESPACE) {
osku's avatar
osku committed
4533 4534 4535 4536 4537 4538 4539
		srv_set_io_thread_op_info(segment, "complete io for buf page");
		buf_page_io_complete(message);
	} else {
		srv_set_io_thread_op_info(segment, "complete io for log");
		log_io_complete(message);
	}
}
4540
#endif /* UNIV_HOTBACKUP */
osku's avatar
osku committed
4541

4542
/**********************************************************************//**
osku's avatar
osku committed
4543 4544
Flushes to disk possible writes cached by the OS. If the space does not exist
or is being dropped, does not do anything. */
4545
UNIV_INTERN
osku's avatar
osku committed
4546 4547 4548
void
fil_flush(
/*======*/
4549
	ulint	space_id)	/*!< in: file space id (this can be a group of
osku's avatar
osku committed
4550 4551 4552 4553 4554
				log files or a tablespace of the database) */
{
	fil_space_t*	space;
	fil_node_t*	node;
	os_file_t	file;
4555
	ib_int64_t	old_mod_counter;
osku's avatar
osku committed
4556

4557
	mutex_enter(&fil_system->mutex);
4558

4559 4560
	space = fil_space_get_by_id(space_id);

osku's avatar
osku committed
4561
	if (!space || space->is_being_deleted) {
4562
		mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4563 4564 4565 4566

		return;
	}

4567
	space->n_pending_flushes++;	/*!< prevent dropping of the space while
osku's avatar
osku committed
4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590
					we are flushing */
	node = UT_LIST_GET_FIRST(space->chain);

	while (node) {
		if (node->modification_counter > node->flush_counter) {
			ut_a(node->open);

			/* We want to flush the changes at least up to
			old_mod_counter */
			old_mod_counter = node->modification_counter;

			if (space->purpose == FIL_TABLESPACE) {
				fil_n_pending_tablespace_flushes++;
			} else {
				fil_n_pending_log_flushes++;
				fil_n_log_flushes++;
			}
#ifdef __WIN__
			if (node->is_raw_disk) {

				goto skip_flush;
			}
#endif
4591
retry:
osku's avatar
osku committed
4592 4593 4594 4595 4596 4597
			if (node->n_pending_flushes > 0) {
				/* We want to avoid calling os_file_flush() on
				the file twice at the same time, because we do
				not know what bugs OS's may contain in file
				i/o; sleep for a while */

4598
				mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4599 4600 4601

				os_thread_sleep(20000);

4602
				mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615

				if (node->flush_counter >= old_mod_counter) {

					goto skip_flush;
				}

				goto retry;
			}

			ut_a(node->open);
			file = node->handle;
			node->n_pending_flushes++;

4616
			mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4617 4618

			/* fprintf(stderr, "Flushing to file %s\n",
4619
			node->name); */
osku's avatar
osku committed
4620

4621
			os_file_flush(file);
osku's avatar
osku committed
4622

4623
			mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4624 4625 4626 4627 4628

			node->n_pending_flushes--;
skip_flush:
			if (node->flush_counter < old_mod_counter) {
				node->flush_counter = old_mod_counter;
4629 4630

				if (space->is_in_unflushed_spaces
4631
				    && fil_space_is_flushed(space)) {
4632 4633 4634

					space->is_in_unflushed_spaces = FALSE;

4635 4636
					UT_LIST_REMOVE(
						unflushed_spaces,
4637
						fil_system->unflushed_spaces,
4638
						space);
4639
				}
osku's avatar
osku committed
4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
			}

			if (space->purpose == FIL_TABLESPACE) {
				fil_n_pending_tablespace_flushes--;
			} else {
				fil_n_pending_log_flushes--;
			}
		}

		node = UT_LIST_GET_NEXT(chain, node);
4650
	}
osku's avatar
osku committed
4651 4652 4653

	space->n_pending_flushes--;

4654
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4655 4656
}

4657
/**********************************************************************//**
osku's avatar
osku committed
4658 4659
Flushes to disk the writes in file spaces of the given type possibly cached by
the OS. */
4660
UNIV_INTERN
osku's avatar
osku committed
4661 4662 4663
void
fil_flush_file_spaces(
/*==================*/
4664
	ulint	purpose)	/*!< in: FIL_TABLESPACE, FIL_LOG */
osku's avatar
osku committed
4665 4666
{
	fil_space_t*	space;
4667 4668 4669
	ulint*		space_ids;
	ulint		n_space_ids;
	ulint		i;
osku's avatar
osku committed
4670

4671
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4672

4673
	n_space_ids = UT_LIST_GET_LEN(fil_system->unflushed_spaces);
4674
	if (n_space_ids == 0) {
osku's avatar
osku committed
4675

4676
		mutex_exit(&fil_system->mutex);
4677 4678
		return;
	}
osku's avatar
osku committed
4679

4680
	/* Assemble a list of space ids to flush.  Previously, we
4681
	traversed fil_system->unflushed_spaces and called UT_LIST_GET_NEXT()
4682 4683 4684
	on a space that was just removed from the list by fil_flush().
	Thus, the space could be dropped and the memory overwritten. */
	space_ids = mem_alloc(n_space_ids * sizeof *space_ids);
osku's avatar
osku committed
4685

4686
	n_space_ids = 0;
osku's avatar
osku committed
4687

4688
	for (space = UT_LIST_GET_FIRST(fil_system->unflushed_spaces);
4689 4690
	     space;
	     space = UT_LIST_GET_NEXT(unflushed_spaces, space)) {
osku's avatar
osku committed
4691

4692 4693 4694
		if (space->purpose == purpose && !space->is_being_deleted) {

			space_ids[n_space_ids++] = space->id;
osku's avatar
osku committed
4695 4696
		}
	}
4697

4698
	mutex_exit(&fil_system->mutex);
4699 4700 4701 4702 4703 4704 4705 4706 4707

	/* Flush the spaces.  It will not hurt to call fil_flush() on
	a non-existing space id. */
	for (i = 0; i < n_space_ids; i++) {

		fil_flush(space_ids[i]);
	}

	mem_free(space_ids);
osku's avatar
osku committed
4708 4709
}

4710
/******************************************************************//**
4711 4712
Checks the consistency of the tablespace cache.
@return	TRUE if ok */
4713
UNIV_INTERN
osku's avatar
osku committed
4714 4715 4716
ibool
fil_validate(void)
/*==============*/
4717
{
osku's avatar
osku committed
4718 4719 4720 4721
	fil_space_t*	space;
	fil_node_t*	fil_node;
	ulint		n_open		= 0;
	ulint		i;
4722

4723
	mutex_enter(&fil_system->mutex);
osku's avatar
osku committed
4724 4725 4726

	/* Look for spaces in the hash table */

4727
	for (i = 0; i < hash_get_n_cells(fil_system->spaces); i++) {
osku's avatar
osku committed
4728

4729
		space = HASH_GET_FIRST(fil_system->spaces, i);
4730

osku's avatar
osku committed
4731
		while (space != NULL) {
4732 4733 4734
			UT_LIST_VALIDATE(chain, fil_node_t, space->chain,
					 ut_a(ut_list_node_313->open
					      || !ut_list_node_313->n_pending));
osku's avatar
osku committed
4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751

			fil_node = UT_LIST_GET_FIRST(space->chain);

			while (fil_node != NULL) {
				if (fil_node->n_pending > 0) {
					ut_a(fil_node->open);
				}

				if (fil_node->open) {
					n_open++;
				}
				fil_node = UT_LIST_GET_NEXT(chain, fil_node);
			}
			space = HASH_GET_NEXT(hash, space);
		}
	}

4752
	ut_a(fil_system->n_open == n_open);
osku's avatar
osku committed
4753

4754
	UT_LIST_VALIDATE(LRU, fil_node_t, fil_system->LRU, (void) 0);
osku's avatar
osku committed
4755

4756
	fil_node = UT_LIST_GET_FIRST(fil_system->LRU);
osku's avatar
osku committed
4757 4758 4759 4760 4761 4762 4763 4764 4765

	while (fil_node != NULL) {
		ut_a(fil_node->n_pending == 0);
		ut_a(fil_node->open);
		ut_a(fil_node->space->purpose == FIL_TABLESPACE);
		ut_a(fil_node->space->id != 0);

		fil_node = UT_LIST_GET_NEXT(LRU, fil_node);
	}
4766

4767
	mutex_exit(&fil_system->mutex);
osku's avatar
osku committed
4768 4769 4770 4771

	return(TRUE);
}

4772
/********************************************************************//**
4773 4774
Returns TRUE if file address is undefined.
@return	TRUE if undefined */
4775
UNIV_INTERN
osku's avatar
osku committed
4776 4777 4778
ibool
fil_addr_is_null(
/*=============*/
4779
	fil_addr_t	addr)	/*!< in: address */
osku's avatar
osku committed
4780
{
4781
	return(addr.page == FIL_NULL);
osku's avatar
osku committed
4782 4783
}

4784
/********************************************************************//**
4785 4786
Get the predecessor of a file page.
@return	FIL_PAGE_PREV */
4787
UNIV_INTERN
osku's avatar
osku committed
4788
ulint
4789 4790
fil_page_get_prev(
/*==============*/
4791
	const byte*	page)	/*!< in: file page */
osku's avatar
osku committed
4792 4793 4794 4795
{
	return(mach_read_from_4(page + FIL_PAGE_PREV));
}

4796
/********************************************************************//**
4797 4798
Get the successor of a file page.
@return	FIL_PAGE_NEXT */
4799
UNIV_INTERN
osku's avatar
osku committed
4800
ulint
4801 4802
fil_page_get_next(
/*==============*/
4803
	const byte*	page)	/*!< in: file page */
osku's avatar
osku committed
4804 4805 4806 4807
{
	return(mach_read_from_4(page + FIL_PAGE_NEXT));
}

4808
/*********************************************************************//**
osku's avatar
osku committed
4809
Sets the file page type. */
4810
UNIV_INTERN
osku's avatar
osku committed
4811 4812 4813
void
fil_page_set_type(
/*==============*/
4814 4815
	byte*	page,	/*!< in/out: file page */
	ulint	type)	/*!< in: type */
osku's avatar
osku committed
4816 4817 4818 4819
{
	ut_ad(page);

	mach_write_to_2(page + FIL_PAGE_TYPE, type);
4820
}
osku's avatar
osku committed
4821

4822
/*********************************************************************//**
4823
Gets the file page type.
4824 4825
@return type; NOTE that if the type has not been written to page, the
return value not defined */
4826
UNIV_INTERN
osku's avatar
osku committed
4827 4828 4829
ulint
fil_page_get_type(
/*==============*/
4830
	const byte*	page)	/*!< in: file page */
osku's avatar
osku committed
4831 4832 4833 4834 4835
{
	ut_ad(page);

	return(mach_read_from_2(page + FIL_PAGE_TYPE));
}
4836

4837
/****************************************************************//**
4838 4839 4840 4841 4842 4843
Initializes the tablespace memory cache. */
UNIV_INTERN
void
fil_close(void)
/*===========*/
{
4844
#ifndef UNIV_HOTBACKUP
4845 4846
	/* The mutex should already have been freed. */
	ut_ad(fil_system->mutex.magic_n == 0);
4847
#endif /* !UNIV_HOTBACKUP */
4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860

	hash_table_free(fil_system->spaces);

	hash_table_free(fil_system->name_hash);

	ut_a(UT_LIST_GET_LEN(fil_system->LRU) == 0);
	ut_a(UT_LIST_GET_LEN(fil_system->unflushed_spaces) == 0);
	ut_a(UT_LIST_GET_LEN(fil_system->space_list) == 0);

	mem_free(fil_system);

	fil_system = NULL;
}