os0file.c 103 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/******************************************************
The interface to the operating system file i/o primitives

(c) 1995 Innobase Oy

Created 10/21/1995 Heikki Tuuri
*******************************************************/

#include "os0file.h"
#include "os0sync.h"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
11
#include "os0thread.h"
12
#include "ut0mem.h"
13
#include "srv0srv.h"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
14
#include "srv0start.h"
15
#include "fil0fil.h"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
16
#include "buf0buf.h"
17

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
18 19 20 21 22 23 24
#if defined(UNIV_HOTBACKUP) && defined(__WIN__)
/* Add includes for the _stat() call to compile on Windows */
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#endif /* UNIV_HOTBACKUP */

25
#undef HAVE_FDATASYNC
26 27 28 29 30 31 32

#ifdef POSIX_ASYNC_IO
/* We assume in this case that the OS has standard Posix aio (at least SunOS
2.6, HP-UX 11i and AIX 4.3 have) */

#endif

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
33
/* This specifies the file permissions InnoDB uses when it creates files in
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
34 35 36 37 38 39 40 41 42
Unix; the value of os_innodb_umask is initialized in ha_innodb.cc to
my_umask */

#ifndef __WIN__
ulint	os_innodb_umask		= S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
#else
ulint	os_innodb_umask		= 0;
#endif

43
#ifdef UNIV_DO_FLUSH
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
44
/* If the following is set to TRUE, we do not call os_file_flush in every
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
45
os_file_write. We can set this TRUE when the doublewrite buffer is used. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
46
ibool	os_do_not_call_flush_at_each_write	= FALSE;
47 48 49
#else
/* We do not call os_file_flush in every os_file_write. */
#endif /* UNIV_DO_FLUSH */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
50

51 52 53 54 55 56
/* We use these mutexes to protect lseek + file i/o operation, if the
OS does not provide an atomic pread or pwrite, or similar */
#define OS_FILE_N_SEEK_MUTEXES	16
os_mutex_t	os_file_seek_mutexes[OS_FILE_N_SEEK_MUTEXES];

/* In simulated aio, merge at most this many consecutive i/os */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
57
#define OS_AIO_MERGE_N_CONSECUTIVE	64
58 59 60 61 62 63 64

/* If this flag is TRUE, then we will use the native aio of the
OS (provided we compiled Innobase with it in), otherwise we will
use simulated aio we build below with threads */

ibool	os_aio_use_native_aio	= FALSE;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
65 66
ibool	os_aio_print_debug	= FALSE;

67 68 69 70 71 72 73 74
/* The aio array slot structure */
typedef struct os_aio_slot_struct	os_aio_slot_t;

struct os_aio_slot_struct{
	ibool		is_read;	/* TRUE if a read operation */
	ulint		pos;		/* index of the slot in the aio
					array */
	ibool		reserved;	/* TRUE if this slot is reserved */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
75
	time_t		reservation_time;/* time when reserved */
76 77 78 79 80 81 82 83
	ulint		len;		/* length of the block to read or
					write */
	byte*		buf;		/* buffer used in i/o */
	ulint		type;		/* OS_FILE_READ or OS_FILE_WRITE */
	ulint		offset;		/* 32 low bits of file offset in
					bytes */
	ulint		offset_high;	/* 32 high bits of file offset */
	os_file_t	file;		/* file where to read or write */
84
	const char*	name;		/* file name or path */
85 86 87 88 89
	ibool		io_already_done;/* used only in simulated aio:
					TRUE if the physical i/o already
					made and only the slot message
					needs to be passed to the caller
					of os_aio_simulated_handle */
90
	fil_node_t*	message1;	/* message which is given by the */
91 92 93 94 95
	void*		message2;	/* the requester of an aio operation
					and which can be used to identify
					which pending aio operation was
					completed */
#ifdef WIN_ASYNC_IO
96
	os_event_t	event;		/* event object we need in the
97
					OVERLAPPED struct */
98 99 100 101 102 103 104 105 106 107 108 109 110
	OVERLAPPED	control;	/* Windows control block for the
					aio request */
#elif defined(POSIX_ASYNC_IO)
	struct aiocb	control;	/* Posix control block for aio
					request */
#endif
};

/* The aio array structure */
typedef struct os_aio_array_struct	os_aio_array_t;

struct os_aio_array_struct{
	os_mutex_t	mutex;	  /* the mutex protecting the aio array */
111
	os_event_t	not_full; /* The event which is set to the signaled
112 113
				  state when there is space in the aio
				  outside the ibuf segment */
114 115 116
	os_event_t	is_empty; /* The event which is set to the signaled
				  state when there are no pending i/os
				  in this array */
117 118 119 120 121 122 123
	ulint		n_slots;  /* Total number of slots in the aio array.
				  This must be divisible by n_threads. */
	ulint		n_segments;/* Number of segments in the aio array of
				  pending aio requests. A thread can wait
				  separately for any one of the segments. */
	ulint		n_reserved;/* Number of reserved slots in the
				  aio array outside the ibuf segment */
124
	os_aio_slot_t*	slots;	  /* Pointer to the slots in the array */
125
#ifdef __WIN__
126
	os_native_event_t* native_events;
127 128 129 130
				  /* Pointer to an array of OS native event
				  handles where we copied the handles from
				  slots, in the same order. This can be used
				  in WaitForMultipleObjects; used only in
131
				  Windows */
132
#endif
133 134 135 136 137 138 139
};

/* Array of events used in simulated aio */
os_event_t*	os_aio_segment_wait_events	= NULL;

/* The aio arrays for non-ibuf i/o and ibuf i/o, as well as sync aio. These
are NULL when the module has not yet been initialized. */
140 141 142 143 144
static os_aio_array_t*	os_aio_read_array	= NULL;
static os_aio_array_t*	os_aio_write_array	= NULL;
static os_aio_array_t*	os_aio_ibuf_array	= NULL;
static os_aio_array_t*	os_aio_log_array	= NULL;
static os_aio_array_t*	os_aio_sync_array	= NULL;
145

146
static ulint	os_aio_n_segments	= ULINT_UNDEFINED;
147

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
148 149
/* If the following is TRUE, read i/o handler threads try to
wait until a batch of new read requests have been posted */
150
static ibool	os_aio_recommend_sleep_for_read_threads	= FALSE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
151

152
ulint	os_n_file_reads		= 0;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
153
ulint	os_bytes_read_since_printout = 0;
154 155 156 157 158 159 160
ulint	os_n_file_writes	= 0;
ulint	os_n_fsyncs		= 0;
ulint	os_n_file_reads_old	= 0;
ulint	os_n_file_writes_old	= 0;
ulint	os_n_fsyncs_old		= 0;
time_t	os_last_printout;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
161 162
ibool	os_has_said_disk_full	= FALSE;

163
/* The mutex protecting the following counts of pending I/O operations */
164
static os_mutex_t os_file_count_mutex;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
165 166
ulint	os_file_n_pending_preads  = 0;
ulint	os_file_n_pending_pwrites = 0;
167 168
ulint	os_n_pending_writes = 0;
ulint	os_n_pending_reads = 0;
169

170 171 172 173 174 175
/***************************************************************************
Gets the operating system version. Currently works only on Windows. */

ulint
os_get_os_version(void)
/*===================*/
176
		  /* out: OS_WIN95, OS_WIN31, OS_WINNT, OS_WIN2000 */
177 178
{
#ifdef __WIN__
179
	OSVERSIONINFO	  os_info;
180

181
	os_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
182 183 184

	ut_a(GetVersionEx(&os_info));

185 186 187 188 189
	if (os_info.dwPlatformId == VER_PLATFORM_WIN32s) {
		return(OS_WIN31);
	} else if (os_info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
		return(OS_WIN95);
	} else if (os_info.dwPlatformId == VER_PLATFORM_WIN32_NT) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
190
		if (os_info.dwMajorVersion <= 4) {
191 192
			return(OS_WINNT);
		} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
193
			return(OS_WIN2000);
194 195 196 197 198
		}
	} else {
		ut_error;
		return(0);
	}
199
#else
200
	ut_error;
201

202
	return(0);
203 204 205
#endif
}

206 207 208 209 210 211 212
/***************************************************************************
Retrieves the last error number if an error occurs in a file io function.
The number should be retrieved before any other OS calls (because they may
overwrite the error number). If the number is not known to this program,
the OS error number + 100 is returned. */

ulint
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
213 214 215 216 217 218
os_file_get_last_error(
/*===================*/
					/* out: error number, or OS error
					number + 100 */
	ibool	report_all_errors)	/* in: TRUE if we want an error message
					printed of all errors */
219 220 221 222 223 224 225
{
	ulint	err;

#ifdef __WIN__

	err = (ulint) GetLastError();

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
226
	if (report_all_errors
227
	    || (err != ERROR_DISK_FULL && err != ERROR_FILE_EXISTS)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
228

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
229
		ut_print_timestamp(stderr);
230
		fprintf(stderr,
231 232
			"  InnoDB: Operating system error number %lu"
			" in a file operation.\n", (ulong) err);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
233

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
234
		if (err == ERROR_PATH_NOT_FOUND) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
235
			fprintf(stderr,
236 237
				"InnoDB: The error means the system"
				" cannot find the path specified.\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
238 239 240

			if (srv_is_being_started) {
				fprintf(stderr,
241 242 243 244
					"InnoDB: If you are installing InnoDB,"
					" remember that you must create\n"
					"InnoDB: directories yourself, InnoDB"
					" does not create them.\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
245
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
246
		} else if (err == ERROR_ACCESS_DENIED) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
247
			fprintf(stderr,
248 249 250 251 252
				"InnoDB: The error means mysqld does not have"
				" the access rights to\n"
				"InnoDB: the directory. It may also be"
				" you have created a subdirectory\n"
				"InnoDB: of the same name as a data file.\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
253
		} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
254
			fprintf(stderr,
255 256 257 258 259
				"InnoDB: Some operating system error numbers"
				" are described at\n"
				"InnoDB: "
				"http://dev.mysql.com/doc/refman/5.1/en/"
				"operating-system-error-codes.html\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
260
		}
261
	}
262

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
263 264
	fflush(stderr);

265 266 267 268 269 270 271 272 273 274
	if (err == ERROR_FILE_NOT_FOUND) {
		return(OS_FILE_NOT_FOUND);
	} else if (err == ERROR_DISK_FULL) {
		return(OS_FILE_DISK_FULL);
	} else if (err == ERROR_FILE_EXISTS) {
		return(OS_FILE_ALREADY_EXISTS);
	} else {
		return(100 + err);
	}
#else
275 276
	err = (ulint) errno;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
277
	if (report_all_errors
278
	    || (err != ENOSPC && err != EEXIST)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
279

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
280
		ut_print_timestamp(stderr);
281
		fprintf(stderr,
282 283
			"  InnoDB: Operating system error number %lu"
			" in a file operation.\n", (ulong) err);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
284

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
285
		if (err == ENOENT) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
286
			fprintf(stderr,
287 288
				"InnoDB: The error means the system"
				" cannot find the path specified.\n");
289

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
290 291
			if (srv_is_being_started) {
				fprintf(stderr,
292 293 294 295
					"InnoDB: If you are installing InnoDB,"
					" remember that you must create\n"
					"InnoDB: directories yourself, InnoDB"
					" does not create them.\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
296
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
297
		} else if (err == EACCES) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
298
			fprintf(stderr,
299 300 301
				"InnoDB: The error means mysqld does not have"
				" the access rights to\n"
				"InnoDB: the directory.\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
302
		} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
303
			if (strerror((int)err) != NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
304
				fprintf(stderr,
305 306 307
					"InnoDB: Error number %lu"
					" means '%s'.\n",
					err, strerror((int)err));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
308
			}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
309

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
310
			fprintf(stderr,
311 312 313 314 315
				"InnoDB: Some operating system"
				" error numbers are described at\n"
				"InnoDB: "
				"http://dev.mysql.com/doc/refman/5.1/en/"
				"operating-system-error-codes.html\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
316
		}
317
	}
318

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
319 320
	fflush(stderr);

321 322 323 324 325 326 327 328 329 330
	if (err == ENOSPC ) {
		return(OS_FILE_DISK_FULL);
#ifdef POSIX_ASYNC_IO
	} else if (err == EAGAIN) {
		return(OS_FILE_AIO_RESOURCES_RESERVED);
#endif
	} else if (err == ENOENT) {
		return(OS_FILE_NOT_FOUND);
	} else if (err == EEXIST) {
		return(OS_FILE_ALREADY_EXISTS);
331 332
	} else if (err == EXDEV || err == ENOTDIR || err == EISDIR) {
		return(OS_FILE_PATH_ERROR);
333 334 335 336 337 338 339
	} else {
		return(100 + err);
	}
#endif
}

/********************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
340
Does error handling when a file operation fails. */
341 342 343 344
static
ibool
os_file_handle_error(
/*=================*/
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
345 346
				/* out: TRUE if we should retry the
				operation */
347
	const char*	name,	/* in: name of a file or NULL */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
348
	const char*	operation)/* in: operation */
349 350 351
{
	ulint	err;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
352
	err = os_file_get_last_error(FALSE);
353

354
	if (err == OS_FILE_DISK_FULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
355 356 357 358 359 360
		/* We only print a warning about disk full once */

		if (os_has_said_disk_full) {

			return(FALSE);
		}
361

362
		if (name) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
363 364
			ut_print_timestamp(stderr);
			fprintf(stderr,
365 366
				"  InnoDB: Encountered a problem with"
				" file %s\n", name);
367
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
368 369

		ut_print_timestamp(stderr);
370
		fprintf(stderr,
371 372
			"  InnoDB: Disk is full. Try to clean the disk"
			" to free space.\n");
373

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
374 375
		os_has_said_disk_full = TRUE;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
376 377
		fflush(stderr);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
378
		return(FALSE);
379

380
	} else if (err == OS_FILE_AIO_RESOURCES_RESERVED) {
381

382
		return(TRUE);
383

384
	} else if (err == OS_FILE_ALREADY_EXISTS
385
		   || err == OS_FILE_PATH_ERROR) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
386

387
		return(FALSE);
388
	} else {
389 390 391 392
		if (name) {
			fprintf(stderr, "InnoDB: File name %s\n", name);
		}

393
		fprintf(stderr, "InnoDB: File operation call: '%s'.\n",
394
			operation);
395 396
		fprintf(stderr, "InnoDB: Cannot continue operation.\n");

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
397 398
		fflush(stderr);

399
		exit(1);
400 401
	}

402
	return(FALSE);
403 404
}

405 406
#undef USE_FILE_LOCK
#define USE_FILE_LOCK
407
#if defined(UNIV_HOTBACKUP) || defined(__WIN__) || defined(__FreeBSD__) || defined(__NETWARE__)
408 409 410 411 412 413 414
/* InnoDB Hot Backup does not lock the data files.
 * On Windows, mandatory locking is used.
 * On FreeBSD with LinuxThreads, advisory locking does not work properly.
 */
# undef USE_FILE_LOCK
#endif
#ifdef USE_FILE_LOCK
415 416 417 418 419 420 421 422
/********************************************************************
Obtain an exclusive lock on a file. */
static
int
os_file_lock(
/*=========*/
				/* out: 0 on success */
	int		fd,	/* in: file descriptor */
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
423
	const char*	name)	/* in: file name */
424 425
{
	struct flock lk;
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
426
	lk.l_type = F_WRLCK;
427 428 429 430
	lk.l_whence = SEEK_SET;
	lk.l_start = lk.l_len = 0;
	if (fcntl(fd, F_SETLK, &lk) == -1) {
		fprintf(stderr,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
431 432 433 434
			"InnoDB: Unable to lock %s, error: %d\n", name, errno);

		if (errno == EAGAIN || errno == EACCES) {
			fprintf(stderr,
435 436 437 438
				"InnoDB: Check that you do not already have"
				" another mysqld process\n"
				"InnoDB: using the same InnoDB data"
				" or log files.\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
439 440
		}

441 442
		return(-1);
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
443

marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
444
	return(0);
445
}
446
#endif /* USE_FILE_LOCK */
447

448 449 450 451 452 453 454 455
/********************************************************************
Does error handling when a file operation fails. */
static
ibool
os_file_handle_error_no_exit(
/*=========================*/
				/* out: TRUE if we should retry the
				operation */
456
	const char*	name,	/* in: name of a file or NULL */
457 458 459 460 461
	const char*	operation)/* in: operation */
{
	ulint	err;

	err = os_file_get_last_error(FALSE);
462

463 464 465 466 467 468 469
	if (err == OS_FILE_DISK_FULL) {
		/* We only print a warning about disk full once */

		if (os_has_said_disk_full) {

			return(FALSE);
		}
470

471 472 473
		if (name) {
			ut_print_timestamp(stderr);
			fprintf(stderr,
474 475
				"  InnoDB: Encountered a problem with"
				" file %s\n", name);
476 477 478
		}

		ut_print_timestamp(stderr);
479
		fprintf(stderr,
480 481
			"  InnoDB: Disk is full. Try to clean the disk"
			" to free space.\n");
482 483 484 485 486 487 488 489 490 491 492

		os_has_said_disk_full = TRUE;

		fflush(stderr);

		return(FALSE);

	} else if (err == OS_FILE_AIO_RESOURCES_RESERVED) {

		return(TRUE);

493
	} else if (err == OS_FILE_ALREADY_EXISTS
494
		   || err == OS_FILE_PATH_ERROR) {
495 496 497

		return(FALSE);
	} else {
498 499 500 501
		if (name) {
			fprintf(stderr, "InnoDB: File name %s\n", name);
		}

502
		fprintf(stderr, "InnoDB: File operation call: '%s'.\n",
503
			operation);
504 505 506
		return (FALSE);
	}

507
	return(FALSE);		/* not reached */
508 509
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
510 511 512 513 514 515 516 517 518
/********************************************************************
Creates the seek mutexes used in positioned reads and writes. */

void
os_io_init_simple(void)
/*===================*/
{
	ulint	i;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
519 520
	os_file_count_mutex = os_mutex_create(NULL);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
521 522 523 524 525
	for (i = 0; i < OS_FILE_N_SEEK_MUTEXES; i++) {
		os_file_seek_mutexes[i] = os_mutex_create(NULL);
	}
}

526
#if !defined(UNIV_HOTBACKUP) && !defined(__NETWARE__)
527
/*************************************************************************
528 529
Creates a temporary file that will be deleted on close.
This function is defined in ha_innodb.cc. */
530 531 532 533 534

int
innobase_mysql_tmpfile(void);
/*========================*/
			/* out: temporary file descriptor, or < 0 on error */
535
#endif /* !UNIV_HOTBACKUP && !__NETWARE__ */
536

537
/***************************************************************************
538 539 540 541
Creates a temporary file.  This function is like tmpfile(3), but
the temporary file is created in the MySQL temporary directory.
On Netware, this function is like tmpfile(3), because the C run-time
library of Netware does not expose the delete-on-close flag. */
542 543 544 545

FILE*
os_file_create_tmpfile(void)
/*========================*/
546
			/* out: temporary file handle, or NULL on error */
547
{
548 549 550 551 552 553
#ifdef UNIV_HOTBACKUP
	ut_error;

	return(NULL);
#else
# ifdef __NETWARE__
554
	FILE*	file	= tmpfile();
555
# else /* __NETWARE__ */
556
	FILE*	file	= NULL;
557
	int	fd	= innobase_mysql_tmpfile();
558 559 560

	if (fd >= 0) {
		file = fdopen(fd, "w+b");
561
	}
562
# endif /* __NETWARE__ */
563 564

	if (!file) {
565
		ut_print_timestamp(stderr);
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
566 567 568
		fprintf(stderr,
			"  InnoDB: Error: unable to create temporary file;"
			" errno: %d\n", errno);
569
# ifndef __NETWARE__
570 571 572
		if (fd >= 0) {
			close(fd);
		}
573
# endif /* !__NETWARE__ */
574
	}
575

576
	return(file);
577
#endif /* UNIV_HOTBACKUP */
578 579
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
580 581 582 583 584 585 586 587 588
/***************************************************************************
The os_file_opendir() function opens a directory stream corresponding to the
directory named by the dirname argument. The directory stream is positioned
at the first entry. In both Unix and Windows we automatically skip the '.'
and '..' items at the start of the directory listing. */

os_file_dir_t
os_file_opendir(
/*============*/
589 590 591 592 593 594 595 596 597
					/* out: directory stream, NULL if
					error */
	const char*	dirname,	/* in: directory name; it must not
					contain a trailing '\' or '/' */
	ibool		error_is_fatal)	/* in: TRUE if we should treat an
					error as a fatal error; if we try to
					open symlinks then we do not wish a
					fatal error if it happens not to be
					a directory */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
598 599 600
{
	os_file_dir_t		dir;
#ifdef __WIN__
601
	LPWIN32_FIND_DATA	lpFindFileData;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
602 603 604 605 606
	char			path[OS_FILE_MAX_PATH + 3];

	ut_a(strlen(dirname) < OS_FILE_MAX_PATH);

	strcpy(path, dirname);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
607
	strcpy(path + strlen(path), "\\*");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
608 609 610 611 612 613 614

	/* Note that in Windows opening the 'directory stream' also retrieves
	the first entry in the directory. Since it is '.', that is no problem,
	as we will skip over the '.' and '..' entries anyway. */

	lpFindFileData = ut_malloc(sizeof(WIN32_FIND_DATA));

615
	dir = FindFirstFile((LPCTSTR) path, lpFindFileData);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
616 617 618 619 620 621

	ut_free(lpFindFileData);

	if (dir == INVALID_HANDLE_VALUE) {

		if (error_is_fatal) {
622
			os_file_handle_error(dirname, "opendir");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
623 624 625 626 627
		}

		return(NULL);
	}

628
	return(dir);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
629 630 631 632
#else
	dir = opendir(dirname);

	if (dir == NULL && error_is_fatal) {
633
		os_file_handle_error(dirname, "opendir");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
	}

	return(dir);
#endif
}

/***************************************************************************
Closes a directory stream. */

int
os_file_closedir(
/*=============*/
				/* out: 0 if success, -1 if failure */
	os_file_dir_t	dir)	/* in: directory stream */
{
#ifdef __WIN__
	BOOL		ret;

	ret = FindClose(dir);

	if (!ret) {
655 656
		os_file_handle_error_no_exit(NULL, "closedir");

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
657 658
		return(-1);
	}
659

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
660 661 662
	return(0);
#else
	int	ret;
663

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
664 665 666
	ret = closedir(dir);

	if (ret) {
667
		os_file_handle_error_no_exit(NULL, "closedir");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
	}

	return(ret);
#endif
}

/***************************************************************************
This function returns information of the next file in the directory. We jump
over the '.' and '..' entries in the directory. */

int
os_file_readdir_next_file(
/*======================*/
				/* out: 0 if ok, -1 if error, 1 if at the end
				of the directory */
683
	const char*	dirname,/* in: directory name or path */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
684 685 686 687 688 689 690 691 692 693 694 695
	os_file_dir_t	dir,	/* in: directory stream */
	os_file_stat_t*	info)	/* in/out: buffer where the info is returned */
{
#ifdef __WIN__
	LPWIN32_FIND_DATA	lpFindFileData;
	BOOL			ret;

	lpFindFileData = ut_malloc(sizeof(WIN32_FIND_DATA));
next_file:
	ret = FindNextFile(dir, lpFindFileData);

	if (ret) {
696 697
		ut_a(strlen((char *) lpFindFileData->cFileName)
		     < OS_FILE_MAX_PATH);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
698

699
		if (strcmp((char *) lpFindFileData->cFileName, ".") == 0
700
		    || strcmp((char *) lpFindFileData->cFileName, "..") == 0) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
701

702
			goto next_file;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
703 704
		}

705
		strcpy(info->name, (char *) lpFindFileData->cFileName);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
706

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
707
		info->size = (ib_longlong)(lpFindFileData->nFileSizeLow)
708 709
			+ (((ib_longlong)(lpFindFileData->nFileSizeHigh))
			   << 32);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
710 711

		if (lpFindFileData->dwFileAttributes
712 713 714 715 716 717 718
		    & FILE_ATTRIBUTE_REPARSE_POINT) {
			/* TODO: test Windows symlinks */
			/* TODO: MySQL has apparently its own symlink
			implementation in Windows, dbname.sym can
			redirect a database directory:
			http://dev.mysql.com/doc/refman/5.1/en/
			windows-symbolic-links.html */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
719 720
			info->type = OS_FILE_TYPE_LINK;
		} else if (lpFindFileData->dwFileAttributes
721
			   & FILE_ATTRIBUTE_DIRECTORY) {
722
			info->type = OS_FILE_TYPE_DIR;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
723
		} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
724 725 726 727 728
			/* It is probably safest to assume that all other
			file types are normal. Better to check them rather
			than blindly skip them. */

			info->type = OS_FILE_TYPE_FILE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
729 730 731 732 733 734 735 736 737 738 739
		}
	}

	ut_free(lpFindFileData);

	if (ret) {
		return(0);
	} else if (GetLastError() == ERROR_NO_MORE_FILES) {

		return(1);
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
740
		os_file_handle_error_no_exit(dirname,
741
					     "readdir_next_file");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
742 743 744 745 746 747 748
		return(-1);
	}
#else
	struct dirent*	ent;
	char*		full_path;
	int		ret;
	struct stat	statinfo;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
749
#ifdef HAVE_READDIR_R
750 751 752 753 754
	char		dirent_buf[sizeof(struct dirent)
				   + _POSIX_PATH_MAX + 100];
	/* In /mysys/my_lib.c, _POSIX_PATH_MAX + 1 is used as
	the max file name len; but in most standards, the
	length is NAME_MAX; we add 100 to be even safer */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
755 756
#endif

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
757
next_file:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
758 759 760 761 762 763

#ifdef HAVE_READDIR_R
	ret = readdir_r(dir, (struct dirent*)dirent_buf, &ent);

	if (ret != 0) {
		fprintf(stderr,
764 765
			"InnoDB: cannot read directory %s, error %lu\n",
			dirname, (ulong)ret);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
766 767 768

		return(-1);
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
769 770

	if (ent == NULL) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
771
		/* End of directory */
772

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
773 774 775
		return(1);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
776 777 778 779 780 781 782 783 784
	ut_a(strlen(ent->d_name) < _POSIX_PATH_MAX + 100 - 1);
#else
	ent = readdir(dir);

	if (ent == NULL) {

		return(1);
	}
#endif
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
785 786 787 788 789 790 791 792 793 794
	ut_a(strlen(ent->d_name) < OS_FILE_MAX_PATH);

	if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {

		goto next_file;
	}

	strcpy(info->name, ent->d_name);

	full_path = ut_malloc(strlen(dirname) + strlen(ent->d_name) + 10);
795

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
796 797 798 799 800
	sprintf(full_path, "%s/%s", dirname, ent->d_name);

	ret = stat(full_path, &statinfo);

	if (ret) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
801
		os_file_handle_error_no_exit(full_path, "stat");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
802 803 804 805 806 807 808 809 810 811 812

		ut_free(full_path);

		return(-1);
	}

	info->size = (ib_longlong)statinfo.st_size;

	if (S_ISDIR(statinfo.st_mode)) {
		info->type = OS_FILE_TYPE_DIR;
	} else if (S_ISLNK(statinfo.st_mode)) {
813
		info->type = OS_FILE_TYPE_LINK;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
814
	} else if (S_ISREG(statinfo.st_mode)) {
815
		info->type = OS_FILE_TYPE_FILE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
816
	} else {
817
		info->type = OS_FILE_TYPE_UNKNOWN;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
818
	}
819

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
820 821 822 823 824 825
	ut_free(full_path);

	return(0);
#endif
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
826 827 828 829 830 831 832 833 834
/*********************************************************************
This function attempts to create a directory named pathname. The new directory
gets default permissions. On Unix the permissions are (0770 & ~umask). If the
directory exists already, nothing is done and the call succeeds, unless the
fail_if_exists arguments is true. */

ibool
os_file_create_directory(
/*=====================*/
835 836 837 838 839 840
					/* out: TRUE if call succeeds,
					FALSE on error */
	const char*	pathname,	/* in: directory name as
					null-terminated string */
	ibool		fail_if_exists)	/* in: if TRUE, pre-existing directory
					is treated as an error. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
841 842 843
{
#ifdef __WIN__
	BOOL	rcode;
844

845
	rcode = CreateDirectory((LPCTSTR) pathname, NULL);
846 847 848
	if (!(rcode != 0
	      || (GetLastError() == ERROR_ALREADY_EXISTS
		  && !fail_if_exists))) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
849
		/* failure */
850
		os_file_handle_error(pathname, "CreateDirectory");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
851 852 853

		return(FALSE);
	}
854

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
855 856 857 858 859 860 861 862
	return (TRUE);
#else
	int	rcode;

	rcode = mkdir(pathname, 0770);

	if (!(rcode == 0 || (errno == EEXIST && !fail_if_exists))) {
		/* failure */
monty@mysql.com's avatar
monty@mysql.com committed
863
		os_file_handle_error(pathname, "mkdir");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
864 865 866

		return(FALSE);
	}
867

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
868
	return (TRUE);
869
#endif
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
870 871
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
872 873 874 875 876 877
/********************************************************************
A simple function to open or create a file. */

os_file_t
os_file_create_simple(
/*==================*/
878 879 880 881 882 883 884 885 886
				/* out, own: handle to the file, not defined
				if error, error number can be retrieved with
				os_file_get_last_error */
	const char*	name,	/* in: name of the file or path as a
				null-terminated string */
	ulint		create_mode,/* in: OS_FILE_OPEN if an existing file is
				opened (if does not exist, error), or
				OS_FILE_CREATE if a new file is created
				(if exists, error), or
887
				OS_FILE_CREATE_PATH if new file
888 889 890 891 892
				(if exists, error) and subdirectories along
				its path are created (if needed)*/
	ulint		access_type,/* in: OS_FILE_READ_ONLY or
				OS_FILE_READ_WRITE */
	ibool*		success)/* out: TRUE if succeed, FALSE if error */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
893 894 895 896 897 898 899
{
#ifdef __WIN__
	os_file_t	file;
	DWORD		create_flag;
	DWORD		access;
	DWORD		attributes	= 0;
	ibool		retry;
900 901

try_again:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
902 903 904 905 906 907
	ut_a(name);

	if (create_mode == OS_FILE_OPEN) {
		create_flag = OPEN_EXISTING;
	} else if (create_mode == OS_FILE_CREATE) {
		create_flag = CREATE_NEW;
908 909 910 911 912 913 914 915
	} else if (create_mode == OS_FILE_CREATE_PATH) {
		/* create subdirs along the path if needed  */
		*success = os_file_create_subdirs_if_needed(name);
		if (!*success) {
			ut_error;
		}
		create_flag = CREATE_NEW;
		create_mode = OS_FILE_CREATE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
916 917 918 919 920 921 922 923 924 925 926 927 928 929
	} else {
		create_flag = 0;
		ut_error;
	}

	if (access_type == OS_FILE_READ_ONLY) {
		access = GENERIC_READ;
	} else if (access_type == OS_FILE_READ_WRITE) {
		access = GENERIC_READ | GENERIC_WRITE;
	} else {
		access = 0;
		ut_error;
	}

930
	file = CreateFile((LPCTSTR) name,
931 932
			  access,
			  FILE_SHARE_READ | FILE_SHARE_WRITE,
933
			  /* file can be read and written also
934 935 936 937 938
			  by other processes */
			  NULL,	/* default security attributes */
			  create_flag,
			  attributes,
			  NULL);	/* no template file */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
939 940 941 942

	if (file == INVALID_HANDLE_VALUE) {
		*success = FALSE;

943
		retry = os_file_handle_error(name,
944 945
					     create_mode == OS_FILE_OPEN ?
					     "open" : "create");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
946 947 948 949 950 951 952 953
		if (retry) {
			goto try_again;
		}
	} else {
		*success = TRUE;
	}

	return(file);
954
#else /* __WIN__ */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
955 956 957
	os_file_t	file;
	int		create_flag;
	ibool		retry;
958 959

try_again:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
960 961 962 963 964 965 966 967 968 969
	ut_a(name);

	if (create_mode == OS_FILE_OPEN) {
		if (access_type == OS_FILE_READ_ONLY) {
			create_flag = O_RDONLY;
		} else {
			create_flag = O_RDWR;
		}
	} else if (create_mode == OS_FILE_CREATE) {
		create_flag = O_RDWR | O_CREAT | O_EXCL;
970 971 972 973 974 975 976 977
	} else if (create_mode == OS_FILE_CREATE_PATH) {
		/* create subdirs along the path if needed  */
		*success = os_file_create_subdirs_if_needed(name);
		if (!*success) {
			return (-1);
		}
		create_flag = O_RDWR | O_CREAT | O_EXCL;
		create_mode = OS_FILE_CREATE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
978 979 980 981 982 983
	} else {
		create_flag = 0;
		ut_error;
	}

	if (create_mode == OS_FILE_CREATE) {
984
		file = open(name, create_flag, S_IRUSR | S_IWUSR
985
			    | S_IRGRP | S_IWGRP);
986 987 988 989
	} else {
		file = open(name, create_flag);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
990 991 992
	if (file == -1) {
		*success = FALSE;

993
		retry = os_file_handle_error(name,
994 995
					     create_mode == OS_FILE_OPEN ?
					     "open" : "create");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
996 997 998
		if (retry) {
			goto try_again;
		}
999
#ifdef USE_FILE_LOCK
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1000
	} else if (access_type == OS_FILE_READ_WRITE
1001
		   && os_file_lock(file, name)) {
1002
		*success = FALSE;
1003
		close(file);
1004 1005
		file = -1;
#endif
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1006 1007 1008 1009
	} else {
		*success = TRUE;
	}

1010
	return(file);
1011
#endif /* __WIN__ */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1012
}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1013 1014 1015 1016 1017 1018 1019

/********************************************************************
A simple function to open or create a file. */

os_file_t
os_file_create_simple_no_error_handling(
/*====================================*/
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
				/* out, own: handle to the file, not defined
				if error, error number can be retrieved with
				os_file_get_last_error */
	const char*	name,	/* in: name of the file or path as a
				null-terminated string */
	ulint		create_mode,/* in: OS_FILE_OPEN if an existing file
				is opened (if does not exist, error), or
				OS_FILE_CREATE if a new file is created
				(if exists, error) */
	ulint		access_type,/* in: OS_FILE_READ_ONLY,
				OS_FILE_READ_WRITE, or
				OS_FILE_READ_ALLOW_DELETE; the last option is
				used by a backup program reading the file */
	ibool*		success)/* out: TRUE if succeed, FALSE if error */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1034 1035 1036 1037 1038 1039
{
#ifdef __WIN__
	os_file_t	file;
	DWORD		create_flag;
	DWORD		access;
	DWORD		attributes	= 0;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1040
	DWORD		share_mode	= FILE_SHARE_READ | FILE_SHARE_WRITE;
1041

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
	ut_a(name);

	if (create_mode == OS_FILE_OPEN) {
		create_flag = OPEN_EXISTING;
	} else if (create_mode == OS_FILE_CREATE) {
		create_flag = CREATE_NEW;
	} else {
		create_flag = 0;
		ut_error;
	}

	if (access_type == OS_FILE_READ_ONLY) {
		access = GENERIC_READ;
	} else if (access_type == OS_FILE_READ_WRITE) {
		access = GENERIC_READ | GENERIC_WRITE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1057 1058 1059
	} else if (access_type == OS_FILE_READ_ALLOW_DELETE) {
		access = GENERIC_READ;
		share_mode = FILE_SHARE_DELETE | FILE_SHARE_READ
1060
			| FILE_SHARE_WRITE;	/* A backup program has to give
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1061 1062 1063
						mysqld the maximum freedom to
						do what it likes with the
						file */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1064 1065 1066 1067 1068
	} else {
		access = 0;
		ut_error;
	}

1069
	file = CreateFile((LPCTSTR) name,
1070 1071 1072 1073 1074 1075
			  access,
			  share_mode,
			  NULL,	/* default security attributes */
			  create_flag,
			  attributes,
			  NULL);	/* no template file */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1076 1077 1078 1079 1080 1081 1082 1083

	if (file == INVALID_HANDLE_VALUE) {
		*success = FALSE;
	} else {
		*success = TRUE;
	}

	return(file);
1084
#else /* __WIN__ */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1085 1086
	os_file_t	file;
	int		create_flag;
1087

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
	ut_a(name);

	if (create_mode == OS_FILE_OPEN) {
		if (access_type == OS_FILE_READ_ONLY) {
			create_flag = O_RDONLY;
		} else {
			create_flag = O_RDWR;
		}
	} else if (create_mode == OS_FILE_CREATE) {
		create_flag = O_RDWR | O_CREAT | O_EXCL;
	} else {
		create_flag = 0;
		ut_error;
	}

	if (create_mode == OS_FILE_CREATE) {
1104
		file = open(name, create_flag, S_IRUSR | S_IWUSR
1105
			    | S_IRGRP | S_IWGRP);
1106 1107 1108 1109
	} else {
		file = open(name, create_flag);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1110 1111
	if (file == -1) {
		*success = FALSE;
1112
#ifdef USE_FILE_LOCK
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1113
	} else if (access_type == OS_FILE_READ_WRITE
1114
		   && os_file_lock(file, name)) {
1115
		*success = FALSE;
1116
		close(file);
1117 1118
		file = -1;
#endif
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1119 1120 1121 1122
	} else {
		*success = TRUE;
	}

1123
	return(file);
1124
#endif /* __WIN__ */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1125 1126
}

1127 1128 1129 1130 1131 1132
/********************************************************************
Opens an existing file or creates a new. */

os_file_t
os_file_create(
/*===========*/
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
				/* out, own: handle to the file, not defined
				if error, error number can be retrieved with
				os_file_get_last_error */
	const char*	name,	/* in: name of the file or path as a
				null-terminated string */
	ulint		create_mode,/* in: OS_FILE_OPEN if an existing file
				is opened (if does not exist, error), or
				OS_FILE_CREATE if a new file is created
				(if exists, error),
				OS_FILE_OVERWRITE if a new file is created
				or an old overwritten;
				OS_FILE_OPEN_RAW, if a raw device or disk
				partition should be opened */
	ulint		purpose,/* in: OS_FILE_AIO, if asynchronous,
				non-buffered i/o is desired,
				OS_FILE_NORMAL, if any normal file;
				NOTE that it also depends on type, os_aio_..
				and srv_.. variables whether we really use
				async i/o or unbuffered i/o: look in the
				function source code for the exact rules */
	ulint		type,	/* in: OS_DATA_FILE or OS_LOG_FILE */
	ibool*		success)/* out: TRUE if succeed, FALSE if error */
1155 1156 1157
{
#ifdef __WIN__
	os_file_t	file;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1158
	DWORD		share_mode	= FILE_SHARE_READ;
1159 1160 1161
	DWORD		create_flag;
	DWORD		attributes;
	ibool		retry;
1162
try_again:
1163 1164
	ut_a(name);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1165 1166 1167
	if (create_mode == OS_FILE_OPEN_RAW) {
		create_flag = OPEN_EXISTING;
		share_mode = FILE_SHARE_WRITE;
1168
	} else if (create_mode == OS_FILE_OPEN
1169
		   || create_mode == OS_FILE_OPEN_RETRY) {
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
		create_flag = OPEN_EXISTING;
	} else if (create_mode == OS_FILE_CREATE) {
		create_flag = CREATE_NEW;
	} else if (create_mode == OS_FILE_OVERWRITE) {
		create_flag = CREATE_ALWAYS;
	} else {
		create_flag = 0;
		ut_error;
	}

	if (purpose == OS_FILE_AIO) {
1181 1182
		/* If specified, use asynchronous (overlapped) io and no
		buffering of writes in the OS */
1183 1184 1185 1186 1187
		attributes = 0;
#ifdef WIN_ASYNC_IO
		if (os_aio_use_native_aio) {
			attributes = attributes | FILE_FLAG_OVERLAPPED;
		}
1188
#endif
1189
#ifdef UNIV_NON_BUFFERED_IO
1190
		if (type == OS_LOG_FILE && srv_flush_log_at_trx_commit == 2) {
1191 1192 1193
			/* Do not use unbuffered i/o to log files because
			value 2 denotes that we do not flush the log at every
			commit, but only once per second */
1194 1195
		} else if (srv_win_file_flush_method
			   == SRV_WIN_IO_UNBUFFERED) {
1196
			attributes = attributes | FILE_FLAG_NO_BUFFERING;
1197
		}
1198 1199
#endif
	} else if (purpose == OS_FILE_NORMAL) {
1200
		attributes = 0;
1201
#ifdef UNIV_NON_BUFFERED_IO
1202
		if (type == OS_LOG_FILE && srv_flush_log_at_trx_commit == 2) {
1203 1204 1205
			/* Do not use unbuffered i/o to log files because
			value 2 denotes that we do not flush the log at every
			commit, but only once per second */
1206 1207
		} else if (srv_win_file_flush_method
			   == SRV_WIN_IO_UNBUFFERED) {
1208
			attributes = attributes | FILE_FLAG_NO_BUFFERING;
1209
		}
1210 1211 1212 1213 1214 1215
#endif
	} else {
		attributes = 0;
		ut_error;
	}

1216
	file = CreateFile((LPCTSTR) name,
1217
			  GENERIC_READ | GENERIC_WRITE, /* read and write
1218
							access */
1219
			  share_mode,	/* File can be read also by other
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1220 1221 1222 1223 1224 1225
					processes; we must give the read
					permission because of ibbackup. We do
					not give the write permission to
					others because if one would succeed to
					start 2 instances of mysqld on the
					SAME files, that could cause severe
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1226
					database corruption! When opening
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1227
					raw disk partitions, Microsoft manuals
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1228 1229
					say that we must give also the write
					permission. */
1230 1231 1232 1233
			  NULL,	/* default security attributes */
			  create_flag,
			  attributes,
			  NULL);	/* no template file */
1234 1235 1236 1237

	if (file == INVALID_HANDLE_VALUE) {
		*success = FALSE;

1238
		retry = os_file_handle_error(name,
1239 1240
					     create_mode == OS_FILE_CREATE ?
					     "create" : "open");
1241 1242
		if (retry) {
			goto try_again;
1243 1244 1245 1246 1247 1248
		}
	} else {
		*success = TRUE;
	}

	return(file);
1249
#else /* __WIN__ */
1250 1251 1252
	os_file_t	file;
	int		create_flag;
	ibool		retry;
1253 1254 1255
	const char*	mode_str	= NULL;
	const char*	type_str	= NULL;
	const char*	purpose_str	= NULL;
1256 1257

try_again:
1258 1259
	ut_a(name);

1260
	if (create_mode == OS_FILE_OPEN || create_mode == OS_FILE_OPEN_RAW
1261
	    || create_mode == OS_FILE_OPEN_RETRY) {
1262
		mode_str = "OPEN";
1263 1264
		create_flag = O_RDWR;
	} else if (create_mode == OS_FILE_CREATE) {
1265
		mode_str = "CREATE";
1266 1267
		create_flag = O_RDWR | O_CREAT | O_EXCL;
	} else if (create_mode == OS_FILE_OVERWRITE) {
1268
		mode_str = "OVERWRITE";
1269 1270 1271 1272 1273 1274
		create_flag = O_RDWR | O_CREAT | O_TRUNC;
	} else {
		create_flag = 0;
		ut_error;
	}

1275 1276 1277 1278 1279
	if (type == OS_LOG_FILE) {
		type_str = "LOG";
	} else if (type == OS_DATA_FILE) {
		type_str = "DATA";
	} else {
1280
		ut_error;
1281
	}
1282

1283 1284 1285 1286 1287
	if (purpose == OS_FILE_AIO) {
		purpose_str = "AIO";
	} else if (purpose == OS_FILE_NORMAL) {
		purpose_str = "NORMAL";
	} else {
1288
		ut_error;
1289
	}
1290

1291 1292 1293 1294
#if 0
	fprintf(stderr, "Opening file %s, mode %s, type %s, purpose %s\n",
		name, mode_str, type_str, purpose_str);
#endif
1295
#ifdef O_SYNC
1296
	/* We let O_SYNC only affect log files; note that we map O_DSYNC to
1297 1298 1299
	O_SYNC because the datasync options seemed to corrupt files in 2001
	in both Linux and Solaris */
	if (type == OS_LOG_FILE
1300
	    && srv_unix_file_flush_method == SRV_UNIX_O_DSYNC) {
1301

1302 1303 1304
# if 0
		fprintf(stderr, "Using O_SYNC for file %s\n", name);
# endif
1305

1306
		create_flag = create_flag | O_SYNC;
1307
	}
1308
#endif /* O_SYNC */
1309
#ifdef O_DIRECT
1310
	/* We let O_DIRECT only affect data files */
1311
	if (type != OS_LOG_FILE
1312 1313 1314 1315
	    && srv_unix_file_flush_method == SRV_UNIX_O_DIRECT) {
# if 0
		fprintf(stderr, "Using O_DIRECT for file %s\n", name);
# endif
1316
		create_flag = create_flag | O_DIRECT;
1317
	}
1318
#endif /* O_DIRECT */
1319
	if (create_mode == OS_FILE_CREATE) {
1320 1321 1322 1323 1324
		file = open(name, create_flag, os_innodb_umask);
	} else {
		file = open(name, create_flag);
	}

1325 1326 1327
	if (file == -1) {
		*success = FALSE;

1328
		retry = os_file_handle_error(name,
1329 1330
					     create_mode == OS_FILE_CREATE ?
					     "create" : "open");
1331 1332
		if (retry) {
			goto try_again;
1333
		}
1334
#ifdef USE_FILE_LOCK
marko@hundin.mysql.fi's avatar
marko@hundin.mysql.fi committed
1335
	} else if (create_mode != OS_FILE_OPEN_RAW
1336
		   && os_file_lock(file, name)) {
1337
		*success = FALSE;
1338 1339 1340
		if (create_mode == OS_FILE_OPEN_RETRY) {
			int i;
			ut_print_timestamp(stderr);
1341 1342 1343
			fputs("  InnoDB: Retrying to lock"
			      " the first data file\n",
			      stderr);
1344 1345 1346 1347 1348 1349 1350 1351 1352
			for (i = 0; i < 100; i++) {
				os_thread_sleep(1000000);
				if (!os_file_lock(file, name)) {
					*success = TRUE;
					return(file);
				}
			}
			ut_print_timestamp(stderr);
			fputs("  InnoDB: Unable to open the first data file\n",
1353
			      stderr);
1354 1355
		}
		close(file);
1356 1357
		file = -1;
#endif
1358 1359 1360 1361
	} else {
		*success = TRUE;
	}

1362
	return(file);
1363
#endif /* __WIN__ */
1364 1365
}

1366 1367 1368 1369 1370 1371
/***************************************************************************
Deletes a file if it exists. The file has to be closed before calling this. */

ibool
os_file_delete_if_exists(
/*=====================*/
1372 1373
				/* out: TRUE if success */
	const char*	name)	/* in: file path as a null-terminated string */
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
{
#ifdef __WIN__
	BOOL	ret;
	ulint	count	= 0;
loop:
	/* In Windows, deleting an .ibd file may fail if ibbackup is copying
	it */

	ret = DeleteFile((LPCTSTR)name);

	if (ret) {
		return(TRUE);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1388
	if (GetLastError() == ERROR_FILE_NOT_FOUND) {
1389 1390 1391 1392 1393 1394 1395 1396 1397
		/* the file does not exist, this not an error */

		return(TRUE);
	}

	count++;

	if (count > 100 && 0 == (count % 10)) {
		fprintf(stderr,
1398 1399 1400
			"InnoDB: Warning: cannot delete file %s\n"
			"InnoDB: Are you running ibbackup"
			" to back up the file?\n", name);
1401

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
		os_file_get_last_error(TRUE); /* print error information */
	}

	os_thread_sleep(1000000);	/* sleep for a second */

	if (count > 2000) {

		return(FALSE);
	}

	goto loop;
#else
	int	ret;

	ret = unlink((const char*)name);

	if (ret != 0 && errno != ENOENT) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1419
		os_file_handle_error_no_exit(name, "delete");
1420 1421 1422 1423 1424 1425 1426 1427

		return(FALSE);
	}

	return(TRUE);
#endif
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1428 1429 1430 1431 1432 1433
/***************************************************************************
Deletes a file. The file has to be closed before calling this. */

ibool
os_file_delete(
/*===========*/
1434 1435
				/* out: TRUE if success */
	const char*	name)	/* in: file path as a null-terminated string */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1436 1437
{
#ifdef __WIN__
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1438
	BOOL	ret;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1439 1440 1441 1442
	ulint	count	= 0;
loop:
	/* In Windows, deleting an .ibd file may fail if ibbackup is copying
	it */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1443 1444 1445 1446 1447 1448 1449

	ret = DeleteFile((LPCTSTR)name);

	if (ret) {
		return(TRUE);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1450
	if (GetLastError() == ERROR_FILE_NOT_FOUND) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1451 1452
		/* If the file does not exist, we classify this as a 'mild'
		error and return */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1453

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1454 1455 1456 1457 1458 1459 1460
		return(FALSE);
	}

	count++;

	if (count > 100 && 0 == (count % 10)) {
		fprintf(stderr,
1461 1462 1463
			"InnoDB: Warning: cannot delete file %s\n"
			"InnoDB: Are you running ibbackup"
			" to back up the file?\n", name);
1464

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
		os_file_get_last_error(TRUE); /* print error information */
	}

	os_thread_sleep(1000000);	/* sleep for a second */

	if (count > 2000) {

		return(FALSE);
	}

	goto loop;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1476
#else
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1477
	int	ret;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1478 1479 1480 1481

	ret = unlink((const char*)name);

	if (ret != 0) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1482
		os_file_handle_error_no_exit(name, "delete");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498

		return(FALSE);
	}

	return(TRUE);
#endif
}

/***************************************************************************
Renames a file (can also move it to another directory). It is safest that the
file is closed before calling this function. */

ibool
os_file_rename(
/*===========*/
				/* out: TRUE if success */
1499
	const char*	oldpath,/* in: old file path as a null-terminated
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1500
				string */
1501
	const char*	newpath)/* in: new file path */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1502 1503
{
#ifdef __WIN__
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1504
	BOOL	ret;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1505 1506 1507 1508 1509 1510 1511

	ret = MoveFile((LPCTSTR)oldpath, (LPCTSTR)newpath);

	if (ret) {
		return(TRUE);
	}

1512
	os_file_handle_error_no_exit(oldpath, "rename");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1513 1514 1515

	return(FALSE);
#else
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1516
	int	ret;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1517 1518 1519 1520

	ret = rename((const char*)oldpath, (const char*)newpath);

	if (ret != 0) {
1521
		os_file_handle_error_no_exit(oldpath, "rename");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1522 1523 1524 1525 1526 1527 1528 1529

		return(FALSE);
	}

	return(TRUE);
#endif
}

1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
/***************************************************************************
Closes a file handle. In case of error, error number can be retrieved with
os_file_get_last_error. */

ibool
os_file_close(
/*==========*/
				/* out: TRUE if success */
	os_file_t	file)	/* in, own: handle to a file */
{
#ifdef __WIN__
	BOOL	ret;

	ut_a(file);

	ret = CloseHandle(file);

	if (ret) {
		return(TRUE);
	}

1551
	os_file_handle_error(NULL, "close");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1552

1553 1554 1555 1556 1557 1558 1559
	return(FALSE);
#else
	int	ret;

	ret = close(file);

	if (ret == -1) {
1560
		os_file_handle_error(NULL, "close");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1561

1562 1563 1564 1565 1566 1567 1568
		return(FALSE);
	}

	return(TRUE);
#endif
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
/***************************************************************************
Closes a file handle. */

ibool
os_file_close_no_error_handling(
/*============================*/
				/* out: TRUE if success */
	os_file_t	file)	/* in, own: handle to a file */
{
#ifdef __WIN__
	BOOL	ret;

	ut_a(file);

	ret = CloseHandle(file);

	if (ret) {
		return(TRUE);
	}

	return(FALSE);
#else
	int	ret;

	ret = close(file);

	if (ret == -1) {

		return(FALSE);
	}

	return(TRUE);
#endif
}

1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
/***************************************************************************
Gets a file size. */

ibool
os_file_get_size(
/*=============*/
				/* out: TRUE if success */
	os_file_t	file,	/* in: handle to a file */
	ulint*		size,	/* out: least significant 32 bits of file
				size */
	ulint*		size_high)/* out: most significant 32 bits of size */
{
#ifdef __WIN__
	DWORD	high;
	DWORD	low;

	low = GetFileSize(file, &high);

	if ((low == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) {
		return(FALSE);
	}

	*size = low;
	*size_high = high;

	return(TRUE);
#else
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1631 1632 1633 1634
	off_t	offs;

	offs = lseek(file, 0, SEEK_END);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1635 1636 1637 1638
	if (offs == ((off_t)-1)) {

		return(FALSE);
	}
1639

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1640
	if (sizeof(off_t) > 4) {
1641
		*size = (ulint)(offs & 0xFFFFFFFFUL);
1642
		*size_high = (ulint)(offs >> 32);
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1643 1644 1645 1646
	} else {
		*size = (ulint) offs;
		*size_high = 0;
	}
1647 1648

	return(TRUE);
1649 1650 1651
#endif
}

1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
/***************************************************************************
Gets file size as a 64-bit integer ib_longlong. */

ib_longlong
os_file_get_size_as_iblonglong(
/*===========================*/
				/* out: size in bytes, -1 if error */
	os_file_t	file)	/* in: handle to a file */
{
	ulint	size;
	ulint	size_high;
	ibool	success;

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

	if (!success) {

		return(-1);
	}

	return((((ib_longlong)size_high) << 32) + (ib_longlong)size);
}

1675
/***************************************************************************
1676
Write the specified number of zeros to a newly created file. */
1677 1678 1679 1680 1681

ibool
os_file_set_size(
/*=============*/
				/* out: TRUE if success */
1682
	const char*	name,	/* in: name of the file or path as a
1683 1684 1685 1686 1687 1688
				null-terminated string */
	os_file_t	file,	/* in: handle to a file */
	ulint		size,	/* in: least significant 32 bits of file
				size */
	ulint		size_high)/* in: most significant 32 bits of size */
{
1689 1690
	ib_longlong	current_size;
	ib_longlong	desired_size;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1691
	ibool		ret;
1692 1693
	byte*		buf;
	byte*		buf2;
1694
	ulint		buf_size;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1695

1696
	ut_a(size == (size & 0xFFFFFFFF));
1697

1698 1699
	current_size = 0;
	desired_size = (ib_longlong)size + (((ib_longlong)size_high) << 32);
1700

1701
	/* Write up to 1 megabyte at a time. */
1702
	buf_size = ut_min(64, (ulint) (desired_size / UNIV_PAGE_SIZE))
1703
		* UNIV_PAGE_SIZE;
1704
	buf2 = ut_malloc(buf_size + UNIV_PAGE_SIZE);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1705 1706 1707

	/* Align the buffer for possible raw i/o */
	buf = ut_align(buf2, UNIV_PAGE_SIZE);
1708 1709

	/* Write buffer full of zeros */
1710
	memset(buf, 0, buf_size);
1711

1712
	if (desired_size >= (ib_longlong)(100 * 1024 * 1024)) {
1713

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1714 1715 1716
		fprintf(stderr, "InnoDB: Progress in MB:");
	}

1717
	while (current_size < desired_size) {
1718 1719 1720 1721 1722 1723 1724 1725
		ulint	n_bytes;

		if (desired_size - current_size < (ib_longlong) buf_size) {
			n_bytes = (ulint) (desired_size - current_size);
		} else {
			n_bytes = buf_size;
		}

1726
		ret = os_file_write(name, file, buf,
1727 1728 1729
				    (ulint)(current_size & 0xFFFFFFFF),
				    (ulint)(current_size >> 32),
				    n_bytes);
1730
		if (!ret) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1731
			ut_free(buf2);
1732 1733 1734
			goto error_handling;
		}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1735
		/* Print about progress for each 100 MB written */
1736
		if ((ib_longlong) (current_size + n_bytes) / (ib_longlong)(100 * 1024 * 1024)
1737
		    != current_size / (ib_longlong)(100 * 1024 * 1024)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1738

1739
			fprintf(stderr, " %lu00",
1740
				(ulong) ((current_size + n_bytes)
1741
					 / (ib_longlong)(100 * 1024 * 1024)));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1742
		}
1743 1744

		current_size += n_bytes;
1745 1746
	}

1747
	if (desired_size >= (ib_longlong)(100 * 1024 * 1024)) {
1748

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1749 1750 1751
		fprintf(stderr, "\n");
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1752
	ut_free(buf2);
1753 1754 1755 1756

	ret = os_file_flush(file);

	if (ret) {
1757
		return(TRUE);
1758 1759 1760
	}

error_handling:
1761
	return(FALSE);
1762 1763 1764
}

/***************************************************************************
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
Truncates a file at its current position. */

ibool
os_file_set_eof(
/*============*/
				/* out: TRUE if success */
	FILE*		file)	/* in: file to be truncated */
{
#ifdef __WIN__
	HANDLE h = (HANDLE) _get_osfhandle(fileno(file));
	return(SetEndOfFile(h));
#else /* __WIN__ */
	return(!ftruncate(fileno(file), ftell(file)));
#endif /* __WIN__ */
}

1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
/***************************************************************************
Flushes the write buffers of a given file to the disk. */

ibool
os_file_flush(
/*==========*/
				/* out: TRUE if success */
	os_file_t	file)	/* in, own: handle to a file */
{
#ifdef __WIN__
	BOOL	ret;

	ut_a(file);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1795 1796
	os_n_fsyncs++;

1797 1798 1799 1800 1801 1802
	ret = FlushFileBuffers(file);

	if (ret) {
		return(TRUE);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1803 1804 1805 1806 1807
	/* Since Windows returns ERROR_INVALID_FUNCTION if the 'file' is
	actually a raw device, we choose to ignore that error if we are using
	raw disks */

	if (srv_start_raw_disk_in_use && GetLastError()
1808
	    == ERROR_INVALID_FUNCTION) {
1809
		return(TRUE);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1810 1811
	}

1812
	os_file_handle_error(NULL, "flush");
1813

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1814 1815
	/* It is a fatal error if a file flush does not succeed, because then
	the database can get corrupt on disk */
1816
	ut_error;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1817

1818 1819 1820
	return(FALSE);
#else
	int	ret;
1821

1822 1823 1824 1825 1826 1827 1828
#if defined(HAVE_DARWIN_THREADS)
# ifndef F_FULLFSYNC
	/* The following definition is from the Mac OS X 10.3 <sys/fcntl.h> */
#  define F_FULLFSYNC 51 /* fsync + ask the drive to flush to the media */
# elif F_FULLFSYNC != 51
#  error "F_FULLFSYNC != 51: ABI incompatibility with Mac OS X 10.3"
# endif
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1829 1830 1831 1832 1833
	/* Apple has disabled fsync() for internal disk drives in OS X. That
	caused corruption for a user when he tested a power outage. Let us in
	OS X use a nonstandard flush method recommended by an Apple
	engineer. */

1834 1835
	if (!srv_have_fullfsync) {
		/* If we are not on an operating system that supports this,
1836
		then fall back to a plain fsync. */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1837 1838

		ret = fsync(file);
1839 1840 1841 1842 1843
	} else {
		ret = fcntl(file, F_FULLFSYNC, NULL);

		if (ret) {
			/* If we are not on a file system that supports this,
1844
			then fall back to a plain fsync. */
1845 1846
			ret = fsync(file);
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1847 1848
	}
#elif HAVE_FDATASYNC
1849 1850
	ret = fdatasync(file);
#else
1851
	/*	fprintf(stderr, "Flushing to file %p\n", file); */
1852
	ret = fsync(file);
1853
#endif
1854 1855
	os_n_fsyncs++;

1856 1857 1858
	if (ret == 0) {
		return(TRUE);
	}
1859

heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1860
	/* Since Linux returns EINVAL if the 'file' is actually a raw device,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1861 1862 1863
	we choose to ignore that error if we are using raw disks */

	if (srv_start_raw_disk_in_use && errno == EINVAL) {
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1864

1865
		return(TRUE);
heikki@donna.mysql.fi's avatar
heikki@donna.mysql.fi committed
1866 1867
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1868
	ut_print_timestamp(stderr);
1869

1870
	fprintf(stderr,
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1871
		"  InnoDB: Error: the OS said file flush did not succeed\n");
1872

1873
	os_file_handle_error(NULL, "flush");
1874

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1875 1876
	/* It is a fatal error if a file flush does not succeed, because then
	the database can get corrupt on disk */
1877
	ut_error;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1878

1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
	return(FALSE);
#endif
}

#ifndef __WIN__
/***********************************************************************
Does a synchronous read operation in Posix. */
static
ssize_t
os_file_pread(
/*==========*/
				/* out: number of bytes read, -1 if error */
	os_file_t	file,	/* in: handle to a file */
	void*		buf,	/* in: buffer where to read */
1893
	ulint		n,	/* in: number of bytes to read */
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1894 1895 1896 1897
	ulint		offset,	/* in: least significant 32 bits of file
				offset from where to read */
	ulint		offset_high) /* in: most significant 32 bits of
				offset */
1898
{
1899
	off_t	offs;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1900
	ssize_t	n_bytes;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1901

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1902
	ut_a((offset & 0xFFFFFFFFUL) == offset);
1903 1904

	/* If off_t is > 4 bytes in size, then we assume we can pass a
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1905 1906
	64-bit address */

1907 1908 1909 1910 1911
	if (sizeof(off_t) > 4) {
		offs = (off_t)offset + (((off_t)offset_high) << 32);

	} else {
		offs = (off_t)offset;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1912

1913 1914
		if (offset_high > 0) {
			fprintf(stderr,
1915
				"InnoDB: Error: file read at offset > 4 GB\n");
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1916
		}
1917
	}
1918

1919 1920
	os_n_file_reads++;

monty@mysql.com's avatar
monty@mysql.com committed
1921
#if defined(HAVE_PREAD) && !defined(HAVE_BROKEN_PREAD)
1922
	os_mutex_enter(os_file_count_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1923
	os_file_n_pending_preads++;
1924 1925
	os_n_pending_reads++;
	os_mutex_exit(os_file_count_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1926

1927
	n_bytes = pread(file, buf, (ssize_t)n, offs);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1928

1929
	os_mutex_enter(os_file_count_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1930
	os_file_n_pending_preads--;
1931 1932
	os_n_pending_reads--;
	os_mutex_exit(os_file_count_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1933 1934

	return(n_bytes);
1935
#else
1936
	{
1937 1938 1939
		off_t	ret_offset;
		ssize_t	ret;
		ulint	i;
1940

1941 1942 1943
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_reads++;
		os_mutex_exit(os_file_count_mutex);
1944

1945 1946
		/* Protect the seek / read operation with a mutex */
		i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
1947

1948
		os_mutex_enter(os_file_seek_mutexes[i]);
1949

1950
		ret_offset = lseek(file, offs, SEEK_SET);
1951

1952 1953 1954 1955 1956
		if (ret_offset < 0) {
			ret = -1;
		} else {
			ret = read(file, buf, (ssize_t)n);
		}
1957

1958
		os_mutex_exit(os_file_seek_mutexes[i]);
1959

1960 1961 1962
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_reads--;
		os_mutex_exit(os_file_count_mutex);
1963

1964
		return(ret);
1965
	}
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
#endif
}

/***********************************************************************
Does a synchronous write operation in Posix. */
static
ssize_t
os_file_pwrite(
/*===========*/
				/* out: number of bytes written, -1 if error */
	os_file_t	file,	/* in: handle to a file */
1977
	const void*	buf,	/* in: buffer from where to write */
1978
	ulint		n,	/* in: number of bytes to write */
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1979 1980 1981 1982
	ulint		offset,	/* in: least significant 32 bits of file
				offset where to write */
	ulint		offset_high) /* in: most significant 32 bits of
				offset */
1983
{
1984
	ssize_t	ret;
1985
	off_t	offs;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1986

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
1987
	ut_a((offset & 0xFFFFFFFFUL) == offset);
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1988

1989
	/* If off_t is > 4 bytes in size, then we assume we can pass a
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1990 1991
	64-bit address */

1992 1993 1994 1995
	if (sizeof(off_t) > 4) {
		offs = (off_t)offset + (((off_t)offset_high) << 32);
	} else {
		offs = (off_t)offset;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
1996

1997 1998
		if (offset_high > 0) {
			fprintf(stderr,
1999 2000
				"InnoDB: Error: file write"
				" at offset > 4 GB\n");
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2001
		}
2002
	}
2003

2004 2005
	os_n_file_writes++;

monty@mysql.com's avatar
monty@mysql.com committed
2006
#if defined(HAVE_PWRITE) && !defined(HAVE_BROKEN_PREAD)
2007
	os_mutex_enter(os_file_count_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2008
	os_file_n_pending_pwrites++;
2009 2010
	os_n_pending_writes++;
	os_mutex_exit(os_file_count_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2011

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2012
	ret = pwrite(file, buf, (ssize_t)n, offs);
2013

2014
	os_mutex_enter(os_file_count_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2015
	os_file_n_pending_pwrites--;
2016 2017
	os_n_pending_writes--;
	os_mutex_exit(os_file_count_mutex);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2018

2019
# ifdef UNIV_DO_FLUSH
2020
	if (srv_unix_file_flush_method != SRV_UNIX_LITTLESYNC
2021 2022
	    && srv_unix_file_flush_method != SRV_UNIX_NOSYNC
	    && !os_do_not_call_flush_at_each_write) {
2023

2024 2025 2026 2027 2028
		/* Always do fsync to reduce the probability that when
		the OS crashes, a database page is only partially
		physically written to disk. */

		ut_a(TRUE == os_file_flush(file));
2029
	}
2030
# endif /* UNIV_DO_FLUSH */
2031

2032
	return(ret);
2033
#else
2034
	{
2035 2036
		off_t	ret_offset;
		ulint	i;
2037

2038 2039 2040
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_writes++;
		os_mutex_exit(os_file_count_mutex);
2041

2042 2043
		/* Protect the seek / write operation with a mutex */
		i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
2044

2045
		os_mutex_enter(os_file_seek_mutexes[i]);
2046

2047
		ret_offset = lseek(file, offs, SEEK_SET);
2048

2049 2050
		if (ret_offset < 0) {
			ret = -1;
2051

2052 2053
			goto func_exit;
		}
2054

2055
		ret = write(file, buf, (ssize_t)n);
2056

2057
# ifdef UNIV_DO_FLUSH
2058 2059 2060
		if (srv_unix_file_flush_method != SRV_UNIX_LITTLESYNC
		    && srv_unix_file_flush_method != SRV_UNIX_NOSYNC
		    && !os_do_not_call_flush_at_each_write) {
2061

2062 2063 2064
			/* Always do fsync to reduce the probability that when
			the OS crashes, a database page is only partially
			physically written to disk. */
2065

2066 2067
			ut_a(TRUE == os_file_flush(file));
		}
2068
# endif /* UNIV_DO_FLUSH */
2069

2070
func_exit:
2071
		os_mutex_exit(os_file_seek_mutexes[i]);
2072

2073 2074 2075
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_writes--;
		os_mutex_exit(os_file_count_mutex);
2076

2077
		return(ret);
2078
	}
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
#endif
}
#endif

/***********************************************************************
Requests a synchronous positioned read operation. */

ibool
os_file_read(
/*=========*/
				/* out: TRUE if request was
				successful, FALSE if fail */
	os_file_t	file,	/* in: handle to a file */
	void*		buf,	/* in: buffer where to read */
	ulint		offset,	/* in: least significant 32 bits of file
				offset where to read */
	ulint		offset_high, /* in: most significant 32 bits of
				offset */
2097
	ulint		n)	/* in: number of bytes to read */
2098 2099 2100 2101 2102 2103 2104 2105 2106
{
#ifdef __WIN__
	BOOL		ret;
	DWORD		len;
	DWORD		ret2;
	DWORD		low;
	DWORD		high;
	ibool		retry;
	ulint		i;
2107

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2108
	ut_a((offset & 0xFFFFFFFFUL) == offset);
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2109

2110
	os_n_file_reads++;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2111
	os_bytes_read_since_printout += n;
2112

2113
try_again:
2114 2115 2116 2117
	ut_ad(file);
	ut_ad(buf);
	ut_ad(n > 0);

2118 2119
	low = (DWORD) offset;
	high = (DWORD) offset_high;
2120

2121 2122 2123 2124
	os_mutex_enter(os_file_count_mutex);
	os_n_pending_reads++;
	os_mutex_exit(os_file_count_mutex);

2125 2126
	/* Protect the seek / read operation with a mutex */
	i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
2127

2128 2129 2130 2131 2132 2133 2134 2135
	os_mutex_enter(os_file_seek_mutexes[i]);

	ret2 = SetFilePointer(file, low, &high, FILE_BEGIN);

	if (ret2 == 0xFFFFFFFF && GetLastError() != NO_ERROR) {

		os_mutex_exit(os_file_seek_mutexes[i]);

2136 2137 2138 2139
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_reads--;
		os_mutex_exit(os_file_count_mutex);

2140
		goto error_handling;
2141
	}
2142

2143
	ret = ReadFile(file, buf, (DWORD) n, &len, NULL);
2144

2145
	os_mutex_exit(os_file_seek_mutexes[i]);
2146 2147 2148 2149 2150

	os_mutex_enter(os_file_count_mutex);
	os_n_pending_reads--;
	os_mutex_exit(os_file_count_mutex);

2151 2152
	if (ret && len == n) {
		return(TRUE);
2153
	}
2154 2155 2156
#else
	ibool	retry;
	ssize_t	ret;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2157

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2158 2159
	os_bytes_read_since_printout += n;

2160
try_again:
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2161
	ret = os_file_pread(file, buf, n, offset, offset_high);
2162

2163
	if ((ulint)ret == n) {
2164 2165 2166

		return(TRUE);
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2167 2168

	fprintf(stderr,
2169 2170 2171 2172
		"InnoDB: Error: tried to read %lu bytes at offset %lu %lu.\n"
		"InnoDB: Was only able to read %ld.\n",
		(ulong)n, (ulong)offset_high,
		(ulong)offset, (long)ret);
2173
#endif
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2174
#ifdef __WIN__
2175
error_handling:
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2176
#endif
2177
	retry = os_file_handle_error(NULL, "read");
2178 2179 2180 2181

	if (retry) {
		goto try_again;
	}
2182

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2183
	fprintf(stderr,
2184 2185
		"InnoDB: Fatal error: cannot read from file."
		" OS error number %lu.\n",
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2186
#ifdef __WIN__
2187
		(ulong) GetLastError()
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2188
#else
2189
		(ulong) errno
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2190 2191 2192 2193
#endif
		);
	fflush(stderr);

2194 2195 2196 2197 2198
	ut_error;

	return(FALSE);
}

2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
/***********************************************************************
Requests a synchronous positioned read operation. This function does not do
any error handling. In case of error it returns FALSE. */

ibool
os_file_read_no_error_handling(
/*===========================*/
				/* out: TRUE if request was
				successful, FALSE if fail */
	os_file_t	file,	/* in: handle to a file */
	void*		buf,	/* in: buffer where to read */
	ulint		offset,	/* in: least significant 32 bits of file
				offset where to read */
	ulint		offset_high, /* in: most significant 32 bits of
				offset */
2214
	ulint		n)	/* in: number of bytes to read */
2215 2216 2217 2218 2219 2220 2221 2222 2223
{
#ifdef __WIN__
	BOOL		ret;
	DWORD		len;
	DWORD		ret2;
	DWORD		low;
	DWORD		high;
	ibool		retry;
	ulint		i;
2224

2225 2226 2227 2228 2229
	ut_a((offset & 0xFFFFFFFFUL) == offset);

	os_n_file_reads++;
	os_bytes_read_since_printout += n;

2230
try_again:
2231 2232 2233 2234
	ut_ad(file);
	ut_ad(buf);
	ut_ad(n > 0);

2235 2236
	low = (DWORD) offset;
	high = (DWORD) offset_high;
2237

2238 2239 2240 2241
	os_mutex_enter(os_file_count_mutex);
	os_n_pending_reads++;
	os_mutex_exit(os_file_count_mutex);

2242 2243
	/* Protect the seek / read operation with a mutex */
	i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
2244

2245 2246 2247 2248 2249 2250 2251 2252
	os_mutex_enter(os_file_seek_mutexes[i]);

	ret2 = SetFilePointer(file, low, &high, FILE_BEGIN);

	if (ret2 == 0xFFFFFFFF && GetLastError() != NO_ERROR) {

		os_mutex_exit(os_file_seek_mutexes[i]);

2253 2254 2255 2256
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_reads--;
		os_mutex_exit(os_file_count_mutex);

2257
		goto error_handling;
2258 2259
	}

2260
	ret = ReadFile(file, buf, (DWORD) n, &len, NULL);
2261 2262

	os_mutex_exit(os_file_seek_mutexes[i]);
2263 2264 2265 2266 2267

	os_mutex_enter(os_file_count_mutex);
	os_n_pending_reads--;
	os_mutex_exit(os_file_count_mutex);

2268 2269
	if (ret && len == n) {
		return(TRUE);
2270
	}
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
#else
	ibool	retry;
	ssize_t	ret;

	os_bytes_read_since_printout += n;

try_again:
	ret = os_file_pread(file, buf, n, offset, offset_high);

	if ((ulint)ret == n) {

		return(TRUE);
	}
2284
#endif
2285 2286 2287
#ifdef __WIN__
error_handling:
#endif
2288
	retry = os_file_handle_error_no_exit(NULL, "read");
2289 2290 2291 2292

	if (retry) {
		goto try_again;
	}
2293

2294 2295 2296
	return(FALSE);
}

2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
/***********************************************************************
Rewind file to its start, read at most size - 1 bytes from it to str, and
NUL-terminate str. All errors are silently ignored. This function is
mostly meant to be used with temporary files. */

void
os_file_read_string(
/*================*/
	FILE*	file,	/* in: file to read from */
	char*	str,	/* in: buffer where to read */
	ulint	size)	/* in: size of buffer */
{
	size_t	flen;

	if (size == 0) {
		return;
	}
2314

2315 2316 2317 2318 2319
	rewind(file);
	flen = fread(str, 1, size - 1, file);
	str[flen] = '\0';
}

2320 2321 2322 2323 2324 2325 2326 2327
/***********************************************************************
Requests a synchronous write operation. */

ibool
os_file_write(
/*==========*/
				/* out: TRUE if request was
				successful, FALSE if fail */
2328
	const char*	name,	/* in: name of the file or path as a
2329 2330
				null-terminated string */
	os_file_t	file,	/* in: handle to a file */
2331
	const void*	buf,	/* in: buffer from which to write */
2332 2333 2334 2335
	ulint		offset,	/* in: least significant 32 bits of file
				offset where to write */
	ulint		offset_high, /* in: most significant 32 bits of
				offset */
2336
	ulint		n)	/* in: number of bytes to write */
2337 2338 2339 2340 2341 2342 2343 2344
{
#ifdef __WIN__
	BOOL		ret;
	DWORD		len;
	DWORD		ret2;
	DWORD		low;
	DWORD		high;
	ulint		i;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2345
	ulint		n_retries	= 0;
2346
	ulint		err;
2347

2348
	ut_a((offset & 0xFFFFFFFF) == offset);
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2349

2350
	os_n_file_writes++;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2351

2352 2353 2354
	ut_ad(file);
	ut_ad(buf);
	ut_ad(n > 0);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2355
retry:
2356 2357
	low = (DWORD) offset;
	high = (DWORD) offset_high;
2358 2359 2360 2361 2362

	os_mutex_enter(os_file_count_mutex);
	os_n_pending_writes++;
	os_mutex_exit(os_file_count_mutex);

2363 2364
	/* Protect the seek / write operation with a mutex */
	i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
2365

2366 2367 2368 2369 2370 2371 2372
	os_mutex_enter(os_file_seek_mutexes[i]);

	ret2 = SetFilePointer(file, low, &high, FILE_BEGIN);

	if (ret2 == 0xFFFFFFFF && GetLastError() != NO_ERROR) {

		os_mutex_exit(os_file_seek_mutexes[i]);
2373 2374 2375 2376 2377

		os_mutex_enter(os_file_count_mutex);
		os_n_pending_writes--;
		os_mutex_exit(os_file_count_mutex);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2378 2379 2380
		ut_print_timestamp(stderr);

		fprintf(stderr,
2381 2382 2383 2384 2385 2386 2387 2388 2389
			"  InnoDB: Error: File pointer positioning to"
			" file %s failed at\n"
			"InnoDB: offset %lu %lu. Operating system"
			" error number %lu.\n"
			"InnoDB: Some operating system error numbers"
			" are described at\n"
			"InnoDB: "
			"http://dev.mysql.com/doc/refman/5.1/en/"
			"operating-system-error-codes.html\n",
2390 2391
			name, (ulong) offset_high, (ulong) offset,
			(ulong) GetLastError());
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2392 2393

		return(FALSE);
2394
	}
2395

2396
	ret = WriteFile(file, buf, (DWORD) n, &len, NULL);
2397

2398 2399 2400
	/* Always do fsync to reduce the probability that when the OS crashes,
	a database page is only partially physically written to disk. */

2401
# ifdef UNIV_DO_FLUSH
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2402
	if (!os_do_not_call_flush_at_each_write) {
2403 2404
		ut_a(TRUE == os_file_flush(file));
	}
2405
# endif /* UNIV_DO_FLUSH */
2406 2407

	os_mutex_exit(os_file_seek_mutexes[i]);
2408

2409 2410 2411 2412
	os_mutex_enter(os_file_count_mutex);
	os_n_pending_writes--;
	os_mutex_exit(os_file_count_mutex);

2413
	if (ret && len == n) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2414

2415 2416
		return(TRUE);
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2417

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2418 2419 2420
	/* If some background file system backup tool is running, then, at
	least in Windows 2000, we may get here a specific error. Let us
	retry the operation 100 times, with 1 second waits. */
2421

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2422
	if (GetLastError() == ERROR_LOCK_VIOLATION && n_retries < 100) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2423

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2424
		os_thread_sleep(1000000);
2425

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2426 2427 2428
		n_retries++;

		goto retry;
2429 2430
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2431
	if (!os_has_said_disk_full) {
2432

2433 2434
		err = (ulint)GetLastError();

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2435 2436 2437
		ut_print_timestamp(stderr);

		fprintf(stderr,
2438 2439 2440 2441 2442 2443 2444 2445 2446
			"  InnoDB: Error: Write to file %s failed"
			" at offset %lu %lu.\n"
			"InnoDB: %lu bytes should have been written,"
			" only %lu were written.\n"
			"InnoDB: Operating system error number %lu.\n"
			"InnoDB: Check that your OS and file system"
			" support files of this size.\n"
			"InnoDB: Check also that the disk is not full"
			" or a disk quota exceeded.\n",
2447 2448
			name, (ulong) offset_high, (ulong) offset,
			(ulong) n, (ulong) len, (ulong) err);
2449 2450 2451

		if (strerror((int)err) != NULL) {
			fprintf(stderr,
2452 2453
				"InnoDB: Error number %lu means '%s'.\n",
				(ulong) err, strerror((int)err));
2454 2455 2456
		}

		fprintf(stderr,
2457 2458 2459 2460 2461
			"InnoDB: Some operating system error numbers"
			" are described at\n"
			"InnoDB: "
			"http://dev.mysql.com/doc/refman/5.1/en/"
			"operating-system-error-codes.html\n");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2462 2463 2464 2465 2466

		os_has_said_disk_full = TRUE;
	}

	return(FALSE);
2467 2468
#else
	ssize_t	ret;
2469

monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
2470
	ret = os_file_pwrite(file, buf, n, offset, offset_high);
2471

2472
	if ((ulint)ret == n) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2473

2474 2475 2476
		return(TRUE);
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2477
	if (!os_has_said_disk_full) {
2478

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2479
		ut_print_timestamp(stderr);
2480

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2481
		fprintf(stderr,
2482 2483 2484 2485 2486 2487 2488 2489 2490
			"  InnoDB: Error: Write to file %s failed"
			" at offset %lu %lu.\n"
			"InnoDB: %lu bytes should have been written,"
			" only %ld were written.\n"
			"InnoDB: Operating system error number %lu.\n"
			"InnoDB: Check that your OS and file system"
			" support files of this size.\n"
			"InnoDB: Check also that the disk is not full"
			" or a disk quota exceeded.\n",
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2491
			name, offset_high, offset, n, (long int)ret,
2492
			(ulint)errno);
2493 2494
		if (strerror(errno) != NULL) {
			fprintf(stderr,
2495 2496
				"InnoDB: Error number %lu means '%s'.\n",
				(ulint)errno, strerror(errno));
2497 2498 2499
		}

		fprintf(stderr,
2500 2501 2502 2503 2504
			"InnoDB: Some operating system error numbers"
			" are described at\n"
			"InnoDB: "
			"http://dev.mysql.com/doc/refman/5.1/en/"
			"operating-system-error-codes.html\n");
2505

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2506 2507 2508
		os_has_said_disk_full = TRUE;
	}

2509
	return(FALSE);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2510
#endif
2511 2512
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2513 2514 2515 2516 2517 2518 2519
/***********************************************************************
Check the existence and type of the given file. */

ibool
os_file_status(
/*===========*/
				/* out: TRUE if call succeeded */
2520
	const char*	path,	/* in:	pathname of the file */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2521 2522 2523 2524 2525 2526
	ibool*		exists,	/* out: TRUE if file exists */
	os_file_type_t* type)	/* out: type of the file (if it exists) */
{
#ifdef __WIN__
	int		ret;
	struct _stat	statinfo;
2527

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2528 2529 2530 2531 2532 2533 2534
	ret = _stat(path, &statinfo);
	if (ret && (errno == ENOENT || errno == ENOTDIR)) {
		/* file does not exist */
		*exists = FALSE;
		return(TRUE);
	} else if (ret) {
		/* file exists, but stat call failed */
2535

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2536
		os_file_handle_error_no_exit(path, "stat");
2537

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2538 2539
		return(FALSE);
	}
2540

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2541 2542 2543
	if (_S_IFDIR & statinfo.st_mode) {
		*type = OS_FILE_TYPE_DIR;
	} else if (_S_IFREG & statinfo.st_mode) {
2544
		*type = OS_FILE_TYPE_FILE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2545
	} else {
2546
		*type = OS_FILE_TYPE_UNKNOWN;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2547 2548 2549
	}

	*exists = TRUE;
2550

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2551 2552 2553 2554
	return(TRUE);
#else
	int		ret;
	struct stat	statinfo;
2555

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2556 2557 2558 2559 2560 2561 2562
	ret = stat(path, &statinfo);
	if (ret && (errno == ENOENT || errno == ENOTDIR)) {
		/* file does not exist */
		*exists = FALSE;
		return(TRUE);
	} else if (ret) {
		/* file exists, but stat call failed */
2563

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2564
		os_file_handle_error_no_exit(path, "stat");
2565

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2566 2567
		return(FALSE);
	}
2568

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2569 2570 2571
	if (S_ISDIR(statinfo.st_mode)) {
		*type = OS_FILE_TYPE_DIR;
	} else if (S_ISLNK(statinfo.st_mode)) {
2572
		*type = OS_FILE_TYPE_LINK;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2573
	} else if (S_ISREG(statinfo.st_mode)) {
2574
		*type = OS_FILE_TYPE_FILE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2575
	} else {
2576
		*type = OS_FILE_TYPE_UNKNOWN;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2577 2578 2579
	}

	*exists = TRUE;
2580

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2581 2582 2583 2584
	return(TRUE);
#endif
}

2585 2586 2587 2588 2589
/***********************************************************************
This function returns information about the specified file */

ibool
os_file_get_status(
2590
/*===============*/
2591 2592 2593 2594 2595
					/* out: TRUE if stat
					information found */
	const char*	path,		/* in:	pathname of the file */
	os_file_stat_t* stat_info)	/* information of a file in a
					directory */
2596 2597 2598 2599
{
#ifdef __WIN__
	int		ret;
	struct _stat	statinfo;
2600

2601 2602 2603 2604 2605 2606 2607
	ret = _stat(path, &statinfo);
	if (ret && (errno == ENOENT || errno == ENOTDIR)) {
		/* file does not exist */

		return(FALSE);
	} else if (ret) {
		/* file exists, but stat call failed */
2608

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2609
		os_file_handle_error_no_exit(path, "stat");
2610

2611 2612 2613 2614 2615
		return(FALSE);
	}
	if (_S_IFDIR & statinfo.st_mode) {
		stat_info->type = OS_FILE_TYPE_DIR;
	} else if (_S_IFREG & statinfo.st_mode) {
2616
		stat_info->type = OS_FILE_TYPE_FILE;
2617
	} else {
2618
		stat_info->type = OS_FILE_TYPE_UNKNOWN;
2619 2620 2621 2622 2623
	}

	stat_info->ctime = statinfo.st_ctime;
	stat_info->atime = statinfo.st_atime;
	stat_info->mtime = statinfo.st_mtime;
2624 2625
	stat_info->size	 = statinfo.st_size;

2626 2627 2628 2629
	return(TRUE);
#else
	int		ret;
	struct stat	statinfo;
2630

2631 2632 2633 2634 2635 2636 2637 2638
	ret = stat(path, &statinfo);

	if (ret && (errno == ENOENT || errno == ENOTDIR)) {
		/* file does not exist */

		return(FALSE);
	} else if (ret) {
		/* file exists, but stat call failed */
2639

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2640
		os_file_handle_error_no_exit(path, "stat");
2641

2642 2643
		return(FALSE);
	}
2644

2645 2646 2647
	if (S_ISDIR(statinfo.st_mode)) {
		stat_info->type = OS_FILE_TYPE_DIR;
	} else if (S_ISLNK(statinfo.st_mode)) {
2648
		stat_info->type = OS_FILE_TYPE_LINK;
2649
	} else if (S_ISREG(statinfo.st_mode)) {
2650
		stat_info->type = OS_FILE_TYPE_FILE;
2651
	} else {
2652
		stat_info->type = OS_FILE_TYPE_UNKNOWN;
2653 2654 2655 2656 2657
	}

	stat_info->ctime = statinfo.st_ctime;
	stat_info->atime = statinfo.st_atime;
	stat_info->mtime = statinfo.st_mtime;
2658 2659
	stat_info->size	 = statinfo.st_size;

2660 2661 2662 2663
	return(TRUE);
#endif
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
/* path name separator character */
#ifdef __WIN__
#  define OS_FILE_PATH_SEPARATOR	'\\'
#else
#  define OS_FILE_PATH_SEPARATOR	'/'
#endif

/********************************************************************
The function os_file_dirname returns a directory component of a
null-terminated pathname string.  In the usual case, dirname returns
the string up to, but not including, the final '/', and basename
2675
is the component following the final '/'.  Trailing '/' charac­
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2676 2677 2678 2679 2680 2681 2682 2683 2684
ters are not counted as part of the pathname.

If path does not contain a slash, dirname returns the string ".".

Concatenating the string returned by dirname, a "/", and the basename
yields a complete pathname.

The return value is  a copy of the directory component of the pathname.
The copy is allocated from heap. It is the caller responsibility
2685
to free it after it is no longer needed.
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2686 2687 2688 2689

The following list of examples (taken from SUSv2) shows the strings
returned by dirname and basename for different paths:

2690 2691 2692 2693 2694 2695 2696
       path	      dirname	     basename
       "/usr/lib"     "/usr"	     "lib"
       "/usr/"	      "/"	     "usr"
       "usr"	      "."	     "usr"
       "/"	      "/"	     "/"
       "."	      "."	     "."
       ".."	      "."	     ".."
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2697 2698 2699 2700 2701 2702 2703
*/

char*
os_file_dirname(
/*============*/
				/* out, own: directory component of the
				pathname */
2704
	const char*	path)	/* in: pathname */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2705
{
2706
	/* Find the offset of the last slash */
2707 2708
	const char* last_slash = strrchr(path, OS_FILE_PATH_SEPARATOR);
	if (!last_slash) {
2709 2710
		/* No slash in the path, return "." */

2711
		return(mem_strdup("."));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2712 2713
	}

2714
	/* Ok, there is a slash */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2715

2716
	if (last_slash == path) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2717
		/* last slash is the first char of the path */
2718

2719
		return(mem_strdup("/"));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2720 2721
	}

2722 2723
	/* Non-trivial directory component */

2724
	return(mem_strdupl(path, last_slash - path));
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2725
}
2726

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2727 2728
/********************************************************************
Creates all missing subdirectories along the given path. */
2729

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2730 2731 2732 2733 2734
ibool
os_file_create_subdirs_if_needed(
/*=============================*/
				/* out: TRUE if call succeeded
				   FALSE otherwise */
2735
	const char*	path)	/* in: path name */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2736 2737
{
	char*		subdir;
2738
	ibool		success, subdir_exists;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2739 2740 2741
	os_file_type_t	type;

	subdir = os_file_dirname(path);
2742
	if (strlen(subdir) == 1
2743
	    && (*subdir == OS_FILE_PATH_SEPARATOR || *subdir == '.')) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2744
		/* subdir is root or cwd, nothing to do */
2745 2746
		mem_free(subdir);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2747 2748 2749
		return(TRUE);
	}

2750
	/* Test if subdir exists */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2751 2752 2753 2754 2755
	success = os_file_status(subdir, &subdir_exists, &type);
	if (success && !subdir_exists) {
		/* subdir does not exist, create it */
		success = os_file_create_subdirs_if_needed(subdir);
		if (!success) {
2756 2757
			mem_free(subdir);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2758 2759 2760 2761 2762
			return(FALSE);
		}
		success = os_file_create_directory(subdir, FALSE);
	}

2763 2764
	mem_free(subdir);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2765 2766 2767
	return(success);
}

2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
/********************************************************************
Returns a pointer to the nth slot in the aio array. */
static
os_aio_slot_t*
os_aio_array_get_nth_slot(
/*======================*/
					/* out: pointer to slot */
	os_aio_array_t*		array,	/* in: aio array */
	ulint			index)	/* in: index of the slot */
{
	ut_a(index < array->n_slots);

	return((array->slots) + index);
}

/****************************************************************************
Creates an aio wait array. */
static
os_aio_array_t*
os_aio_array_create(
/*================*/
				/* out, own: aio array */
	ulint	n,		/* in: maximum number of pending aio operations
				allowed; n must be divisible by n_segments */
2792
	ulint	n_segments)	/* in: number of segments in the aio array */
2793 2794 2795 2796 2797 2798
{
	os_aio_array_t*	array;
	ulint		i;
	os_aio_slot_t*	slot;
#ifdef WIN_ASYNC_IO
	OVERLAPPED*	over;
2799
#endif
2800 2801 2802 2803 2804
	ut_a(n > 0);
	ut_a(n_segments > 0);

	array = ut_malloc(sizeof(os_aio_array_t));

2805
	array->mutex		= os_mutex_create(NULL);
2806
	array->not_full		= os_event_create(NULL);
2807 2808 2809
	array->is_empty		= os_event_create(NULL);

	os_event_set(array->is_empty);
2810 2811

	array->n_slots		= n;
2812 2813 2814
	array->n_segments	= n_segments;
	array->n_reserved	= 0;
	array->slots		= ut_malloc(n * sizeof(os_aio_slot_t));
2815 2816
#ifdef __WIN__
	array->native_events	= ut_malloc(n * sizeof(os_native_event_t));
2817
#endif
2818 2819 2820 2821 2822 2823
	for (i = 0; i < n; i++) {
		slot = os_aio_array_get_nth_slot(array, i);

		slot->pos = i;
		slot->reserved = FALSE;
#ifdef WIN_ASYNC_IO
2824 2825
		slot->event = os_event_create(NULL);

2826 2827
		over = &(slot->control);

2828
		over->hEvent = slot->event->handle;
2829

2830
		*((array->native_events) + i) = over->hEvent;
2831 2832
#endif
	}
2833

2834 2835 2836 2837
	return(array);
}

/****************************************************************************
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2838 2839
Initializes the asynchronous io system. Calls also os_io_init_simple.
Creates a separate aio array for
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
non-ibuf read and write, a third aio array for the ibuf i/o, with just one
segment, two aio arrays for log reads and writes with one segment, and a
synchronous aio array of the specified size. The combined number of segments
in the three first aio arrays is the parameter n_segments given to the
function. The caller must create an i/o handler thread for each segment in
the four first arrays, but not for the sync aio array. */

void
os_aio_init(
/*========*/
	ulint	n,		/* in: maximum number of pending aio operations
				allowed; n must be divisible by n_segments */
	ulint	n_segments,	/* in: combined number of segments in the four
				first aio arrays; must be >= 4 */
	ulint	n_slots_sync)	/* in: number of slots in the sync aio array */
{
	ulint	n_read_segs;
	ulint	n_write_segs;
	ulint	n_per_seg;
	ulint	i;
#ifdef POSIX_ASYNC_IO
	sigset_t   sigset;
#endif
	ut_ad(n % n_segments == 0);
	ut_ad(n_segments >= 4);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2866 2867
	os_io_init_simple();

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2868
	for (i = 0; i < n_segments; i++) {
2869
		srv_set_io_thread_op_info(i, "not started yet");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2870 2871
	}

2872 2873 2874
	n_per_seg = n / n_segments;
	n_write_segs = (n_segments - 2) / 2;
	n_read_segs = n_segments - 2 - n_write_segs;
2875

2876
	/* fprintf(stderr, "Array n per seg %lu\n", n_per_seg); */
2877

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2878 2879
	os_aio_ibuf_array = os_aio_array_create(n_per_seg, 1);

2880
	srv_io_thread_function[0] = "insert buffer thread";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2881 2882 2883

	os_aio_log_array = os_aio_array_create(n_per_seg, 1);

2884
	srv_io_thread_function[1] = "log thread";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2885

2886
	os_aio_read_array = os_aio_array_create(n_read_segs * n_per_seg,
2887
						n_read_segs);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2888
	for (i = 2; i < 2 + n_read_segs; i++) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2889
		ut_a(i < SRV_MAX_N_IO_THREADS);
2890
		srv_io_thread_function[i] = "read thread";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2891 2892
	}

2893
	os_aio_write_array = os_aio_array_create(n_write_segs * n_per_seg,
2894
						 n_write_segs);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2895
	for (i = 2 + n_read_segs; i < n_segments; i++) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2896
		ut_a(i < SRV_MAX_N_IO_THREADS);
2897
		srv_io_thread_function[i] = "write thread";
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2898
	}
2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911

	os_aio_sync_array = os_aio_array_create(n_slots_sync, 1);

	os_aio_n_segments = n_segments;

	os_aio_validate();

	os_aio_segment_wait_events = ut_malloc(n_segments * sizeof(void*));

	for (i = 0; i < n_segments; i++) {
		os_aio_segment_wait_events[i] = os_event_create(NULL);
	}

2912 2913
	os_last_printout = time(NULL);

2914
#ifdef POSIX_ASYNC_IO
2915 2916 2917 2918
	/* Block aio signals from the current thread and its children:
	for this to work, the current thread must be the first created
	in the database, so that all its children will inherit its
	signal mask */
2919

2920 2921
	/* TODO: to work MySQL needs the SIGALARM signal; the following
	will not work yet! */
2922
	sigemptyset(&sigset);
2923 2924 2925 2926 2927
	sigaddset(&sigset, SIGRTMIN + 1 + 0);
	sigaddset(&sigset, SIGRTMIN + 1 + 1);
	sigaddset(&sigset, SIGRTMIN + 1 + 2);
	sigaddset(&sigset, SIGRTMIN + 1 + 3);

2928
	pthread_sigmask(SIG_BLOCK, &sigset, NULL); */
2929
#endif
2930
		}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945

#ifdef WIN_ASYNC_IO
/****************************************************************************
Wakes up all async i/o threads in the array in Windows async i/o at
shutdown. */
static
void
os_aio_array_wake_win_aio_at_shutdown(
/*==================================*/
	os_aio_array_t*	array)	/* in: aio array */
{
	ulint	i;

	for (i = 0; i < array->n_slots; i++) {

2946
		os_event_set((array->slots + i)->event);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961
	}
}
#endif

/****************************************************************************
Wakes up all async i/o threads so that they know to exit themselves in
shutdown. */

void
os_aio_wake_all_threads_at_shutdown(void)
/*=====================================*/
{
	ulint	i;

#ifdef WIN_ASYNC_IO
2962
	/* This code wakes up all ai/o threads in Windows native aio */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2963 2964 2965 2966 2967 2968 2969 2970
	os_aio_array_wake_win_aio_at_shutdown(os_aio_read_array);
	os_aio_array_wake_win_aio_at_shutdown(os_aio_write_array);
	os_aio_array_wake_win_aio_at_shutdown(os_aio_ibuf_array);
	os_aio_array_wake_win_aio_at_shutdown(os_aio_log_array);
#endif
	/* This loop wakes up all simulated ai/o threads */

	for (i = 0; i < os_aio_n_segments; i++) {
2971

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2972
		os_event_set(os_aio_segment_wait_events[i]);
2973
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
2974
}
2975

2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986
/****************************************************************************
Waits until there are no pending writes in os_aio_write_array. There can
be other, synchronous, pending writes. */

void
os_aio_wait_until_no_pending_writes(void)
/*=====================================*/
{
	os_event_wait(os_aio_write_array->is_empty);
}

2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
/**************************************************************************
Calculates segment number for a slot. */
static
ulint
os_aio_get_segment_no_from_slot(
/*============================*/
				/* out: segment number (which is the number
				used by, for example, i/o-handler threads) */
	os_aio_array_t*	array,	/* in: aio wait array */
	os_aio_slot_t*	slot)	/* in: slot in this array */
{
	ulint	segment;
	ulint	seg_len;

	if (array == os_aio_ibuf_array) {
		segment = 0;

	} else if (array == os_aio_log_array) {
		segment = 1;
3006

3007
	} else if (array == os_aio_read_array) {
3008 3009
		seg_len = os_aio_read_array->n_slots
			/ os_aio_read_array->n_segments;
3010 3011 3012 3013

		segment = 2 + slot->pos / seg_len;
	} else {
		ut_a(array == os_aio_write_array);
3014 3015
		seg_len = os_aio_write_array->n_slots
			/ os_aio_write_array->n_segments;
3016 3017

		segment = os_aio_read_array->n_segments + 2
3018
			+ slot->pos / seg_len;
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
	}

	return(segment);
}

/**************************************************************************
Calculates local segment number and aio array from global segment number. */
static
ulint
os_aio_get_array_and_local_segment(
/*===============================*/
					/* out: local segment number within
					the aio array */
	os_aio_array_t** array,		/* out: aio wait array */
	ulint		 global_segment)/* in: global segment number */
{
	ulint	segment;

3037
	ut_a(global_segment < os_aio_n_segments);
3038 3039 3040 3041 3042 3043 3044 3045

	if (global_segment == 0) {
		*array = os_aio_ibuf_array;
		segment = 0;

	} else if (global_segment == 1) {
		*array = os_aio_log_array;
		segment = 0;
3046

3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062
	} else if (global_segment < os_aio_read_array->n_segments + 2) {
		*array = os_aio_read_array;

		segment = global_segment - 2;
	} else {
		*array = os_aio_write_array;

		segment = global_segment - (os_aio_read_array->n_segments + 2);
	}

	return(segment);
}

/***********************************************************************
Gets an integer value designating a specified aio array. This is used
to give numbers to signals in Posix aio. */
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3063 3064

#if !defined(WIN_ASYNC_IO) && defined(POSIX_ASYNC_IO)
3065 3066 3067 3068 3069
static
ulint
os_aio_get_array_no(
/*================*/
	os_aio_array_t*	array)	/* in: aio array */
3070
{
3071
	if (array == os_aio_ibuf_array) {
3072

3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
		return(0);

	} else if (array == os_aio_log_array) {

		return(1);

	} else if (array == os_aio_read_array) {

		return(2);
	} else if (array == os_aio_write_array) {

		return(3);
	} else {
3086
		ut_error;
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099

		return(0);
	}
}

/***********************************************************************
Gets the aio array for its number. */
static
os_aio_array_t*
os_aio_get_array_from_no(
/*=====================*/
			/* out: aio array */
	ulint	n)	/* in: array number */
3100
{
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112
	if (n == 0) {
		return(os_aio_ibuf_array);
	} else if (n == 1) {

		return(os_aio_log_array);
	} else if (n == 2) {

		return(os_aio_read_array);
	} else if (n == 3) {

		return(os_aio_write_array);
	} else {
3113
		ut_error;
3114 3115 3116 3117

		return(NULL);
	}
}
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3118
#endif /* if !defined(WIN_ASYNC_IO) && defined(POSIX_ASYNC_IO) */
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129

/***********************************************************************
Requests for a slot in the aio array. If no slot is available, waits until
not_full-event becomes signaled. */
static
os_aio_slot_t*
os_aio_array_reserve_slot(
/*======================*/
				/* out: pointer to slot */
	ulint		type,	/* in: OS_FILE_READ or OS_FILE_WRITE */
	os_aio_array_t*	array,	/* in: aio array */
3130
	fil_node_t*	message1,/* in: message to be passed along with
3131 3132 3133 3134
				the aio operation */
	void*		message2,/* in: message to be passed along with
				the aio operation */
	os_file_t	file,	/* in: file handle */
3135
	const char*	name,	/* in: name of the file or path as a
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165
				null-terminated string */
	void*		buf,	/* in: buffer where to read or from which
				to write */
	ulint		offset,	/* in: least significant 32 bits of file
				offset */
	ulint		offset_high, /* in: most significant 32 bits of
				offset */
	ulint		len)	/* in: length of the block to read or write */
{
	os_aio_slot_t*	slot;
#ifdef WIN_ASYNC_IO
	OVERLAPPED*	control;

#elif defined(POSIX_ASYNC_IO)

	struct aiocb*	control;
#endif
	ulint		i;
loop:
	os_mutex_enter(array->mutex);

	if (array->n_reserved == array->n_slots) {
		os_mutex_exit(array->mutex);

		if (!os_aio_use_native_aio) {
			/* If the handler threads are suspended, wake them
			so that we get more slots */

			os_aio_simulated_wake_handler_threads();
		}
3166

3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
		os_event_wait(array->not_full);

		goto loop;
	}

	for (i = 0;; i++) {
		slot = os_aio_array_get_nth_slot(array, i);

		if (slot->reserved == FALSE) {
			break;
		}
	}

	array->n_reserved++;

3182 3183 3184 3185
	if (array->n_reserved == 1) {
		os_event_reset(array->is_empty);
	}

3186 3187 3188
	if (array->n_reserved == array->n_slots) {
		os_event_reset(array->not_full);
	}
3189

3190
	slot->reserved = TRUE;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3191
	slot->reservation_time = time(NULL);
3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
	slot->message1 = message1;
	slot->message2 = message2;
	slot->file     = file;
	slot->name     = name;
	slot->len      = len;
	slot->type     = type;
	slot->buf      = buf;
	slot->offset   = offset;
	slot->offset_high = offset_high;
	slot->io_already_done = FALSE;
3202 3203

#ifdef WIN_ASYNC_IO
3204 3205 3206
	control = &(slot->control);
	control->Offset = (DWORD)offset;
	control->OffsetHigh = (DWORD)offset_high;
3207
	os_event_reset(slot->event);
3208 3209 3210 3211 3212 3213 3214

#elif defined(POSIX_ASYNC_IO)

#if (UNIV_WORD_SIZE == 8)
	offset = offset + (offset_high << 32);
#else
	ut_a(offset_high == 0);
3215
#endif
3216 3217 3218 3219 3220 3221 3222
	control = &(slot->control);
	control->aio_fildes = file;
	control->aio_buf = buf;
	control->aio_nbytes = len;
	control->aio_offset = offset;
	control->aio_reqprio = 0;
	control->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
3223 3224 3225 3226
	control->aio_sigevent.sigev_signo
		= SIGRTMIN + 1 + os_aio_get_array_no(array);
	/* TODO: How to choose the signal numbers? */
	/*
3227
	fprintf(stderr, "AIO signal number %lu\n",
3228 3229
	(ulint) control->aio_sigevent.sigev_signo);
	*/
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
	control->aio_sigevent.sigev_value.sival_ptr = slot;
#endif
	os_mutex_exit(array->mutex);

	return(slot);
}

/***********************************************************************
Frees a slot in the aio array. */
static
void
os_aio_array_free_slot(
/*===================*/
	os_aio_array_t*	array,	/* in: aio array */
	os_aio_slot_t*	slot)	/* in: pointer to slot */
{
	ut_ad(array);
	ut_ad(slot);

	os_mutex_enter(array->mutex);

	ut_ad(slot->reserved);
3252

3253 3254 3255 3256 3257 3258 3259 3260
	slot->reserved = FALSE;

	array->n_reserved--;

	if (array->n_reserved == array->n_slots - 1) {
		os_event_set(array->not_full);
	}

3261 3262 3263 3264
	if (array->n_reserved == 0) {
		os_event_set(array->is_empty);
	}

3265
#ifdef WIN_ASYNC_IO
3266
	os_event_reset(slot->event);
3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281
#endif
	os_mutex_exit(array->mutex);
}

/**************************************************************************
Wakes up a simulated aio i/o-handler thread if it has something to do. */
static
void
os_aio_simulated_wake_handler_thread(
/*=================================*/
	ulint	global_segment)	/* in: the number of the segment in the aio
				arrays */
{
	os_aio_array_t*	array;
	os_aio_slot_t*	slot;
monty@donna.mysql.fi's avatar
Merge  
monty@donna.mysql.fi committed
3282
	ulint		segment;
3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
	ulint		n;
	ulint		i;

	ut_ad(!os_aio_use_native_aio);

	segment = os_aio_get_array_and_local_segment(&array, global_segment);

	n = array->n_slots / array->n_segments;

	/* Look through n slots after the segment * n'th slot */

	os_mutex_enter(array->mutex);

	for (i = 0; i < n; i++) {
		slot = os_aio_array_get_nth_slot(array, i + segment * n);

		if (slot->reserved) {
			/* Found an i/o request */
3301

3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325
			break;
		}
	}

	os_mutex_exit(array->mutex);

	if (i < n) {
		os_event_set(os_aio_segment_wait_events[global_segment]);
	}
}

/**************************************************************************
Wakes up simulated aio i/o-handler threads if they have something to do. */

void
os_aio_simulated_wake_handler_threads(void)
/*=======================================*/
{
	ulint	i;

	if (os_aio_use_native_aio) {
		/* We do not use simulated aio: do nothing */

		return;
3326
	}
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3327 3328

	os_aio_recommend_sleep_for_read_threads	= FALSE;
3329 3330 3331 3332 3333 3334

	for (i = 0; i < os_aio_n_segments; i++) {
		os_aio_simulated_wake_handler_thread(i);
	}
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353
/**************************************************************************
This function can be called if one wants to post a batch of reads and
prefers an i/o-handler thread to handle them all at once later. You must
call os_aio_simulated_wake_handler_threads later to ensure the threads
are not left sleeping! */

void
os_aio_simulated_put_read_threads_to_sleep(void)
/*============================================*/
{
	os_aio_array_t*	array;
	ulint		g;

	os_aio_recommend_sleep_for_read_threads	= TRUE;

	for (g = 0; g < os_aio_n_segments; g++) {
		os_aio_get_array_and_local_segment(&array, g);

		if (array == os_aio_read_array) {
3354

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3355 3356 3357 3358 3359
			os_event_reset(os_aio_segment_wait_events[g]);
		}
	}
}

3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381
/***********************************************************************
Requests an asynchronous i/o operation. */

ibool
os_aio(
/*===*/
				/* out: TRUE if request was queued
				successfully, FALSE if fail */
	ulint		type,	/* in: OS_FILE_READ or OS_FILE_WRITE */
	ulint		mode,	/* in: OS_AIO_NORMAL, ..., possibly ORed
				to OS_AIO_SIMULATED_WAKE_LATER: the
				last flag advises this function not to wake
				i/o-handler threads, but the caller will
				do the waking explicitly later, in this
				way the caller can post several requests in
				a batch; NOTE that the batch must not be
				so big that it exhausts the slots in aio
				arrays! 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! */
3382
	const char*	name,	/* in: name of the file or path as a
3383 3384 3385 3386 3387 3388 3389 3390
				null-terminated string */
	os_file_t	file,	/* in: handle to a file */
	void*		buf,	/* in: buffer where to read or from which
				to write */
	ulint		offset,	/* in: least significant 32 bits of file
				offset where to read or write */
	ulint		offset_high, /* in: most significant 32 bits of
				offset */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3391
	ulint		n,	/* in: number of bytes to read or write */
3392
	fil_node_t*	message1,/* in: messages for the aio handler (these
3393 3394 3395 3396 3397 3398 3399 3400
				can be used to identify a completed aio
				operation); if mode is OS_AIO_SYNC, these
				are ignored */
	void*		message2)
{
	os_aio_array_t*	array;
	os_aio_slot_t*	slot;
#ifdef WIN_ASYNC_IO
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3401
	ibool		retval;
3402
	BOOL		ret		= TRUE;
3403
	DWORD		len		= (DWORD) n;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3404
	struct fil_node_struct * dummy_mess1;
3405
	void*		dummy_mess2;
3406
	ulint		dummy_type;
3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420
#endif
	ulint		err		= 0;
	ibool		retry;
	ulint		wake_later;

	ut_ad(file);
	ut_ad(buf);
	ut_ad(n > 0);
	ut_ad(n % OS_FILE_LOG_BLOCK_SIZE == 0);
	ut_ad(offset % OS_FILE_LOG_BLOCK_SIZE == 0);
	ut_ad(os_aio_validate());

	wake_later = mode & OS_AIO_SIMULATED_WAKE_LATER;
	mode = mode & (~OS_AIO_SIMULATED_WAKE_LATER);
3421

3422 3423
	if (mode == OS_AIO_SYNC
#ifdef WIN_ASYNC_IO
3424
	    && !os_aio_use_native_aio
3425
#endif
3426
	    ) {
3427 3428 3429 3430 3431 3432 3433 3434
		/* This is actually an ordinary synchronous read or write:
		no need to use an i/o-handler thread. NOTE that if we use
		Windows async i/o, Windows does not allow us to use
		ordinary synchronous os_file_read etc. on the same file,
		therefore we have built a special mechanism for synchronous
		wait in the Windows case. */

		if (type == OS_FILE_READ) {
3435
			return(os_file_read(file, buf, offset,
3436
					    offset_high, n));
3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452
		}

		ut_a(type == OS_FILE_WRITE);

		return(os_file_write(name, file, buf, offset, offset_high, n));
	}

try_again:
	if (mode == OS_AIO_NORMAL) {
		if (type == OS_FILE_READ) {
			array = os_aio_read_array;
		} else {
			array = os_aio_write_array;
		}
	} else if (mode == OS_AIO_IBUF) {
		ut_ad(type == OS_FILE_READ);
3453 3454 3455 3456
		/* Reduce probability of deadlock bugs in connection with ibuf:
		do not let the ibuf i/o handler sleep */

		wake_later = FALSE;
3457 3458 3459 3460 3461 3462 3463 3464

		array = os_aio_ibuf_array;
	} else if (mode == OS_AIO_LOG) {

		array = os_aio_log_array;
	} else if (mode == OS_AIO_SYNC) {
		array = os_aio_sync_array;
	} else {
3465
		array = NULL; /* Eliminate compiler warning */
3466 3467
		ut_error;
	}
3468

3469
	slot = os_aio_array_reserve_slot(type, array, message1, message2, file,
3470
					 name, buf, offset, offset_high, n);
3471 3472 3473
	if (type == OS_FILE_READ) {
		if (os_aio_use_native_aio) {
#ifdef WIN_ASYNC_IO
3474
			os_n_file_reads++;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3475
			os_bytes_read_since_printout += len;
3476

3477
			ret = ReadFile(file, buf, (DWORD)n, &len,
3478
				       &(slot->control));
3479 3480 3481
#elif defined(POSIX_ASYNC_IO)
			slot->control.aio_lio_opcode = LIO_READ;
			err = (ulint) aio_read(&(slot->control));
3482
			fprintf(stderr, "Starting POSIX aio read %lu\n", err);
3483 3484 3485
#endif
		} else {
			if (!wake_later) {
3486 3487 3488
				os_aio_simulated_wake_handler_thread(
					os_aio_get_segment_no_from_slot(
						array, slot));
3489 3490 3491 3492 3493
			}
		}
	} else if (type == OS_FILE_WRITE) {
		if (os_aio_use_native_aio) {
#ifdef WIN_ASYNC_IO
3494
			os_n_file_writes++;
3495
			ret = WriteFile(file, buf, (DWORD)n, &len,
3496
					&(slot->control));
3497 3498 3499
#elif defined(POSIX_ASYNC_IO)
			slot->control.aio_lio_opcode = LIO_WRITE;
			err = (ulint) aio_write(&(slot->control));
3500
			fprintf(stderr, "Starting POSIX aio write %lu\n", err);
3501 3502 3503
#endif
		} else {
			if (!wake_later) {
3504 3505 3506
				os_aio_simulated_wake_handler_thread(
					os_aio_get_segment_no_from_slot(
						array, slot));
3507 3508 3509 3510 3511 3512 3513 3514 3515
			}
		}
	} else {
		ut_error;
	}

#ifdef WIN_ASYNC_IO
	if (os_aio_use_native_aio) {
		if ((ret && len == n)
3516
		    || (!ret && GetLastError() == ERROR_IO_PENDING)) {
3517
			/* aio was queued successfully! */
3518 3519 3520 3521 3522 3523 3524 3525

			if (mode == OS_AIO_SYNC) {
				/* We want a synchronous i/o operation on a
				file where we also use async i/o: in Windows
				we must use the same wait mechanism as for
				async i/o */

				retval = os_aio_windows_handle(ULINT_UNDEFINED,
3526 3527 3528 3529
							       slot->pos,
							       &dummy_mess1,
							       &dummy_mess2,
							       &dummy_type);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3530

3531 3532
				return(retval);
			}
3533 3534 3535 3536

			return(TRUE);
		}

3537
		err = 1; /* Fall through the next if */
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547
	}
#endif
	if (err == 0) {
		/* aio was queued successfully! */

		return(TRUE);
	}

	os_aio_array_free_slot(array, slot);

3548
	retry = os_file_handle_error(name,
3549 3550
				     type == OS_FILE_READ
				     ? "aio read" : "aio write");
3551 3552 3553
	if (retry) {

		goto try_again;
3554
	}
3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580

	return(FALSE);
}

#ifdef WIN_ASYNC_IO
/**************************************************************************
This function is only used in Windows asynchronous i/o.
Waits for an aio operation to complete. This function is used to wait the
for completed requests. The aio array of pending requests is divided
into segments. The thread specifies which segment or slot it wants to wait
for. NOTE: this function will also take care of freeing the aio slot,
therefore no other thread is allowed to do the freeing! */

ibool
os_aio_windows_handle(
/*==================*/
				/* out: TRUE if the aio operation succeeded */
	ulint	segment,	/* in: the number of the segment in the aio
				arrays to wait for; segment 0 is the ibuf
				i/o thread, segment 1 the log i/o thread,
				then follow the non-ibuf read threads, and as
				the last are the non-ibuf write threads; if
				this is ULINT_UNDEFINED, then it means that
				sync aio is used, and this parameter is
				ignored */
	ulint	pos,		/* this parameter is used only in sync aio:
3581
				wait for the aio slot at this position */
3582
	fil_node_t**message1,	/* out: the messages passed with the aio
3583 3584 3585 3586
				request; note that also in the case where
				the aio operation failed, these output
				parameters are valid and can be used to
				restart the operation, for example */
3587 3588
	void**	message2,
	ulint*	type)		/* out: OS_FILE_WRITE or ..._READ */
3589
{
3590
	ulint		orig_seg	= segment;
3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604
	os_aio_array_t*	array;
	os_aio_slot_t*	slot;
	ulint		n;
	ulint		i;
	ibool		ret_val;
	BOOL		ret;
	DWORD		len;

	if (segment == ULINT_UNDEFINED) {
		array = os_aio_sync_array;
		segment = 0;
	} else {
		segment = os_aio_get_array_and_local_segment(&array, segment);
	}
3605

3606 3607 3608 3609 3610 3611 3612 3613 3614
	/* NOTE! We only access constant fields in os_aio_array. Therefore
	we do not have to acquire the protecting mutex yet */

	ut_ad(os_aio_validate());
	ut_ad(segment < array->n_segments);

	n = array->n_slots / array->n_segments;

	if (array == os_aio_sync_array) {
3615
		os_event_wait(os_aio_array_get_nth_slot(array, pos)->event);
3616 3617
		i = pos;
	} else {
3618
		srv_set_io_thread_op_info(orig_seg, "wait Windows aio");
3619
		i = os_event_wait_multiple(n,
3620 3621
					   (array->native_events)
					   + segment * n);
3622 3623 3624 3625 3626 3627 3628 3629
	}

	os_mutex_enter(array->mutex);

	slot = os_aio_array_get_nth_slot(array, i + segment * n);

	ut_a(slot->reserved);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3630
	if (orig_seg != ULINT_UNDEFINED) {
3631
		srv_set_io_thread_op_info(orig_seg,
3632
					  "get windows aio return value");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3633 3634
	}

3635 3636 3637 3638 3639
	ret = GetOverlappedResult(slot->file, &(slot->control), &len, TRUE);

	*message1 = slot->message1;
	*message2 = slot->message2;

3640 3641
	*type = slot->type;

3642 3643
	if (ret && len == slot->len) {
		ret_val = TRUE;
3644

3645
# ifdef UNIV_DO_FLUSH
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3646
		if (slot->type == OS_FILE_WRITE
3647 3648
		    && !os_do_not_call_flush_at_each_write) {
			ut_a(TRUE == os_file_flush(slot->file));
3649
		}
3650
# endif /* UNIV_DO_FLUSH */
3651
	} else {
3652
		os_file_handle_error(slot->name, "Windows aio");
3653

3654
		ret_val = FALSE;
3655
	}
3656 3657 3658 3659

	os_mutex_exit(array->mutex);

	os_aio_array_free_slot(array, slot);
3660

3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
	return(ret_val);
}
#endif

#ifdef POSIX_ASYNC_IO

/**************************************************************************
This function is only used in Posix asynchronous i/o. Waits for an aio
operation to complete. */

ibool
os_aio_posix_handle(
/*================*/
				/* out: TRUE if the aio operation succeeded */
	ulint	array_no,	/* in: array number 0 - 3 */
3676
	fil_node_t**message1,	/* out: the messages passed with the aio
3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
				request; note that also in the case where
				the aio operation failed, these output
				parameters are valid and can be used to
				restart the operation, for example */
	void**	message2)
{
	os_aio_array_t*	array;
	os_aio_slot_t*	slot;
	siginfo_t	info;
	sigset_t	sigset;
3687 3688
	sigset_t	proc_sigset;
	sigset_t	thr_sigset;
3689
	int		ret;
3690 3691 3692 3693
	int		i;
	int		sig;

	sigemptyset(&sigset);
3694 3695 3696 3697
	sigaddset(&sigset, SIGRTMIN + 1 + array_no);

	pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);

3698
#if 0
3699 3700 3701 3702
	sigprocmask(0, NULL, &proc_sigset);
	pthread_sigmask(0, NULL, &thr_sigset);

	for (i = 32 ; i < 40; i++) {
3703
		fprintf(stderr, "%lu : %lu %lu\n", (ulint)i,
3704 3705
			(ulint) sigismember(&proc_sigset, i),
			(ulint) sigismember(&thr_sigset, i));
3706
	}
3707
#endif
3708 3709 3710 3711 3712

	ret = sigwaitinfo(&sigset, &info);

	if (sig != SIGRTMIN + 1 + array_no) {

3713
		ut_error;
3714

3715 3716
		return(FALSE);
	}
3717

3718
	fputs("Handling POSIX aio\n", stderr);
3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730

	array = os_aio_get_array_from_no(array_no);

	os_mutex_enter(array->mutex);

	slot = info.si_value.sival_ptr;

	ut_a(slot->reserved);

	*message1 = slot->message1;
	*message2 = slot->message2;

3731
# ifdef UNIV_DO_FLUSH
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3732
	if (slot->type == OS_FILE_WRITE
3733
	    && !os_do_not_call_flush_at_each_write) {
3734 3735
		ut_a(TRUE == os_file_flush(slot->file));
	}
3736
# endif /* UNIV_DO_FLUSH */
3737

3738 3739 3740
	os_mutex_exit(array->mutex);

	os_aio_array_free_slot(array, slot);
3741

3742 3743 3744 3745
	return(TRUE);
}
#endif

3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
/**************************************************************************
Do a 'last millisecond' check that the page end is sensible;
reported page checksum errors from Linux seem to wipe over the page end. */
static
void
os_file_check_page_trailers(
/*========================*/
	byte*	combined_buf,	/* in: combined write buffer */
	ulint	total_len)	/* in: size of combined_buf, in bytes
				(a multiple of UNIV_PAGE_SIZE) */
{
	ulint	len;

	for (len = 0; len + UNIV_PAGE_SIZE <= total_len;
3760
	     len += UNIV_PAGE_SIZE) {
3761 3762
		byte*	buf = combined_buf + len;

3763 3764 3765 3766
		if (UNIV_UNLIKELY
		    (memcmp(buf + (FIL_PAGE_LSN + 4),
			    buf + (UNIV_PAGE_SIZE
				   - FIL_PAGE_END_LSN_OLD_CHKSUM + 4), 4))) {
3767 3768
		    	ut_print_timestamp(stderr);
		    	fprintf(stderr,
3769 3770 3771 3772 3773
				"  InnoDB: ERROR: The page to be written"
				" seems corrupt!\n"
				"InnoDB: Writing a block of %lu bytes,"
				" currently at offset %lu\n",
				(ulong)total_len, (ulong)len);
3774 3775
			buf_page_print(buf);
		    	fprintf(stderr,
3776 3777
				"InnoDB: ERROR: The page to be written"
				" seems corrupt!\n");
3778 3779 3780 3781
		}
	}
}

3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
/**************************************************************************
Does simulated aio. This function should be called by an i/o-handler
thread. */

ibool
os_aio_simulated_handle(
/*====================*/
				/* out: TRUE if the aio operation succeeded */
	ulint	global_segment,	/* in: the number of the segment in the aio
				arrays to wait for; segment 0 is the ibuf
				i/o thread, segment 1 the log i/o thread,
				then follow the non-ibuf read threads, and as
				the last are the non-ibuf write threads */
3795
	fil_node_t**message1,	/* out: the messages passed with the aio
3796 3797 3798 3799
				request; note that also in the case where
				the aio operation failed, these output
				parameters are valid and can be used to
				restart the operation, for example */
3800 3801
	void**	message2,
	ulint*	type)		/* out: OS_FILE_WRITE or ..._READ */
3802 3803 3804 3805 3806 3807 3808 3809 3810 3811
{
	os_aio_array_t*	array;
	ulint		segment;
	os_aio_slot_t*	slot;
	os_aio_slot_t*	slot2;
	os_aio_slot_t*	consecutive_ios[OS_AIO_MERGE_N_CONSECUTIVE];
	ulint		n_consecutive;
	ulint		total_len;
	ulint		offs;
	ulint		lowest_offset;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3812 3813
	ulint		biggest_age;
	ulint		age;
3814
	byte*		combined_buf;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3815
	byte*		combined_buf2;
3816 3817 3818
	ibool		ret;
	ulint		n;
	ulint		i;
3819

3820
	segment = os_aio_get_array_and_local_segment(&array, global_segment);
3821

3822 3823 3824 3825
restart:
	/* NOTE! We only access constant fields in os_aio_array. Therefore
	we do not have to acquire the protecting mutex yet */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3826
	srv_set_io_thread_op_info(global_segment,
3827
				  "looking for i/o requests (a)");
3828 3829 3830 3831 3832 3833 3834
	ut_ad(os_aio_validate());
	ut_ad(segment < array->n_segments);

	n = array->n_slots / array->n_segments;

	/* Look through n slots after the segment * n'th slot */

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3835
	if (array == os_aio_read_array
3836
	    && os_aio_recommend_sleep_for_read_threads) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3837 3838 3839 3840 3841 3842

		/* Give other threads chance to add several i/os to the array
		at once. */

		goto recommended_sleep;
	}
3843

3844 3845
	os_mutex_enter(array->mutex);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3846
	srv_set_io_thread_op_info(global_segment,
3847
				  "looking for i/o requests (b)");
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3848

3849 3850
	/* Check if there is a slot for which the i/o has already been
	done */
3851

3852 3853 3854 3855 3856
	for (i = 0; i < n; i++) {
		slot = os_aio_array_get_nth_slot(array, i + segment * n);

		if (slot->reserved && slot->io_already_done) {

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3857 3858
			if (os_aio_print_debug) {
				fprintf(stderr,
3859 3860 3861
					"InnoDB: i/o for slot %lu"
					" already done, returning\n",
					(ulong) i);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3862 3863
			}

3864
			ret = TRUE;
3865

3866 3867 3868 3869 3870 3871
			goto slot_io_done;
		}
	}

	n_consecutive = 0;

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3872 3873 3874
	/* If there are at least 2 seconds old requests, then pick the oldest
	one to prevent starvation. If several requests have the same age,
	then pick the one at the lowest offset. */
3875

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3876
	biggest_age = 0;
3877
	lowest_offset = ULINT_MAX;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3878

3879 3880 3881
	for (i = 0; i < n; i++) {
		slot = os_aio_array_get_nth_slot(array, i + segment * n);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3882
		if (slot->reserved) {
3883
			age = (ulint)difftime(time(NULL),
3884
					      slot->reservation_time);
3885

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3886
			if ((age >= 2 && age > biggest_age)
3887 3888
			    || (age >= 2 && age == biggest_age
				&& slot->offset < lowest_offset)) {
3889

3890
				/* Found an i/o request */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3891
				consecutive_ios[0] = slot;
3892

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3893 3894 3895 3896 3897 3898 3899 3900 3901
				n_consecutive = 1;

				biggest_age = age;
				lowest_offset = slot->offset;
			}
		}
	}

	if (n_consecutive == 0) {
3902
		/* There were no old requests. Look for an i/o request at the
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3903 3904 3905 3906
		lowest offset in the array (we ignore the high 32 bits of the
		offset in these heuristics) */

		lowest_offset = ULINT_MAX;
3907

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3908
		for (i = 0; i < n; i++) {
3909
			slot = os_aio_array_get_nth_slot(array,
3910
							 i + segment * n);
3911

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3912
			if (slot->reserved && slot->offset < lowest_offset) {
3913

3914
				/* Found an i/o request */
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3915 3916 3917 3918 3919 3920
				consecutive_ios[0] = slot;

				n_consecutive = 1;

				lowest_offset = slot->offset;
			}
3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934
		}
	}

	if (n_consecutive == 0) {

		/* No i/o requested at the moment */

		goto wait_for_io;
	}

	slot = consecutive_ios[0];

	/* Check if there are several consecutive blocks to read or write */

3935
consecutive_loop:
3936 3937 3938 3939
	for (i = 0; i < n; i++) {
		slot2 = os_aio_array_get_nth_slot(array, i + segment * n);

		if (slot2->reserved && slot2 != slot
3940 3941 3942 3943 3944 3945
		    && slot2->offset == slot->offset + slot->len
		    /* check that sum does not wrap over */
		    && slot->offset + slot->len > slot->offset
		    && slot2->offset_high == slot->offset_high
		    && slot2->type == slot->type
		    && slot2->file == slot->file) {
3946 3947 3948 3949 3950 3951 3952 3953 3954

			/* Found a consecutive i/o request */

			consecutive_ios[n_consecutive] = slot2;
			n_consecutive++;

			slot = slot2;

			if (n_consecutive < OS_AIO_MERGE_N_CONSECUTIVE) {
3955

3956 3957 3958 3959 3960 3961 3962
				goto consecutive_loop;
			} else {
				break;
			}
		}
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3963 3964
	srv_set_io_thread_op_info(global_segment, "consecutive i/o requests");

3965 3966 3967 3968 3969 3970
	/* We have now collected n_consecutive i/o requests in the array;
	allocate a single buffer which can hold all data, and perform the
	i/o */

	total_len = 0;
	slot = consecutive_ios[0];
3971

3972 3973 3974 3975 3976 3977 3978
	for (i = 0; i < n_consecutive; i++) {
		total_len += consecutive_ios[i]->len;
	}

	if (n_consecutive == 1) {
		/* We can use the buffer of the i/o request */
		combined_buf = slot->buf;
3979
		combined_buf2 = NULL;
3980
	} else {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3981
		combined_buf2 = ut_malloc(total_len + UNIV_PAGE_SIZE);
3982

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
3983 3984 3985
		ut_a(combined_buf2);

		combined_buf = ut_align(combined_buf2, UNIV_PAGE_SIZE);
3986
	}
3987

3988 3989 3990 3991 3992 3993 3994 3995 3996
	/* We release the array mutex for the time of the i/o: NOTE that
	this assumes that there is just one i/o-handler thread serving
	a single segment of slots! */

	os_mutex_exit(array->mutex);

	if (slot->type == OS_FILE_WRITE && n_consecutive > 1) {
		/* Copy the buffers to the combined buffer */
		offs = 0;
3997

3998 3999 4000
		for (i = 0; i < n_consecutive; i++) {

			ut_memcpy(combined_buf + offs, consecutive_ios[i]->buf,
4001
				  consecutive_ios[i]->len);
4002 4003 4004
			offs += consecutive_ios[i]->len;
		}
	}
4005

4006
	srv_set_io_thread_op_info(global_segment, "doing file i/o");
4007

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4008 4009
	if (os_aio_print_debug) {
		fprintf(stderr,
4010 4011
			"InnoDB: doing i/o of type %lu at offset %lu %lu,"
			" length %lu\n",
4012 4013
			(ulong) slot->type, (ulong) slot->offset_high,
			(ulong) slot->offset, (ulong) total_len);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4014 4015
	}

4016 4017
	/* Do the i/o with ordinary, synchronous i/o functions: */
	if (slot->type == OS_FILE_WRITE) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4018
		if (array == os_aio_write_array) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4019
			if ((total_len % UNIV_PAGE_SIZE != 0)
4020
			    || (slot->offset % UNIV_PAGE_SIZE != 0)) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4021
				fprintf(stderr,
4022 4023
					"InnoDB: Error: trying a displaced"
					" write to %s %lu %lu, len %lu\n",
4024 4025 4026
					slot->name, (ulong) slot->offset_high,
					(ulong) slot->offset,
					(ulong) total_len);
4027
				ut_error;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4028
			}
4029

4030
			os_file_check_page_trailers(combined_buf, total_len);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4031
		}
4032

4033
		ret = os_file_write(slot->name, slot->file, combined_buf,
4034 4035
				    slot->offset, slot->offset_high,
				    total_len);
4036 4037 4038 4039

		if (array == os_aio_write_array) {
			os_file_check_page_trailers(combined_buf, total_len);
		}
4040 4041
	} else {
		ret = os_file_read(slot->file, combined_buf,
4042
				   slot->offset, slot->offset_high, total_len);
4043 4044 4045
	}

	ut_a(ret);
4046
	srv_set_io_thread_op_info(global_segment, "file i/o done");
4047

4048 4049 4050 4051 4052
#if 0
	fprintf(stderr,
		"aio: %lu consecutive %lu:th segment, first offs %lu blocks\n",
		n_consecutive, global_segment, slot->offset / UNIV_PAGE_SIZE);
#endif
4053 4054 4055 4056

	if (slot->type == OS_FILE_READ && n_consecutive > 1) {
		/* Copy the combined buffer to individual buffers */
		offs = 0;
4057

4058 4059
		for (i = 0; i < n_consecutive; i++) {

4060
			ut_memcpy(consecutive_ios[i]->buf, combined_buf + offs,
4061
				  consecutive_ios[i]->len);
4062 4063 4064 4065
			offs += consecutive_ios[i]->len;
		}
	}

4066
	if (combined_buf2) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4067
		ut_free(combined_buf2);
4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080
	}

	os_mutex_enter(array->mutex);

	/* Mark the i/os done in slots */

	for (i = 0; i < n_consecutive; i++) {
		consecutive_ios[i]->io_already_done = TRUE;
	}

	/* We return the messages for the first slot now, and if there were
	several slots, the messages will be returned with subsequent calls
	of this function */
4081

4082 4083 4084 4085 4086 4087 4088
slot_io_done:

	ut_a(slot->reserved);

	*message1 = slot->message1;
	*message2 = slot->message2;

4089 4090
	*type = slot->type;

4091 4092 4093
	os_mutex_exit(array->mutex);

	os_aio_array_free_slot(array, slot);
4094

4095 4096 4097
	return(ret);

wait_for_io:
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4098 4099
	srv_set_io_thread_op_info(global_segment, "resetting wait event");

4100 4101
	/* We wait here until there again can be i/os in the segment
	of this thread */
4102

4103 4104 4105 4106
	os_event_reset(os_aio_segment_wait_events[global_segment]);

	os_mutex_exit(array->mutex);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4107
recommended_sleep:
4108
	srv_set_io_thread_op_info(global_segment, "waiting for i/o request");
4109

4110 4111
	os_event_wait(os_aio_segment_wait_events[global_segment]);

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4112 4113
	if (os_aio_print_debug) {
		fprintf(stderr,
4114 4115
			"InnoDB: i/o handler thread for i/o"
			" segment %lu wakes up\n",
4116
			(ulong) global_segment);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4117
	}
4118

4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133
	goto restart;
}

/**************************************************************************
Validates the consistency of an aio array. */
static
ibool
os_aio_array_validate(
/*==================*/
				/* out: TRUE if ok */
	os_aio_array_t*	array)	/* in: aio wait array */
{
	os_aio_slot_t*	slot;
	ulint		n_reserved	= 0;
	ulint		i;
4134

4135 4136 4137 4138 4139 4140
	ut_a(array);

	os_mutex_enter(array->mutex);

	ut_a(array->n_slots > 0);
	ut_a(array->n_segments > 0);
4141

4142 4143
	for (i = 0; i < array->n_slots; i++) {
		slot = os_aio_array_get_nth_slot(array, i);
4144

4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178
		if (slot->reserved) {
			n_reserved++;
			ut_a(slot->len > 0);
		}
	}

	ut_a(array->n_reserved == n_reserved);

	os_mutex_exit(array->mutex);

	return(TRUE);
}

/**************************************************************************
Validates the consistency the aio system. */

ibool
os_aio_validate(void)
/*=================*/
				/* out: TRUE if ok */
{
	os_aio_array_validate(os_aio_read_array);
	os_aio_array_validate(os_aio_write_array);
	os_aio_array_validate(os_aio_ibuf_array);
	os_aio_array_validate(os_aio_log_array);
	os_aio_array_validate(os_aio_sync_array);

	return(TRUE);
}

/**************************************************************************
Prints info of the aio arrays. */

void
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4179 4180
os_aio_print(
/*=========*/
4181
	FILE*	file)	/* in: file where to print */
4182 4183 4184 4185
{
	os_aio_array_t*	array;
	os_aio_slot_t*	slot;
	ulint		n_reserved;
4186 4187
	time_t		current_time;
	double		time_elapsed;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4188
	double		avg_bytes_read;
4189
	ulint		i;
4190

4191
	for (i = 0; i < srv_n_file_io_threads; i++) {
4192
		fprintf(file, "I/O thread %lu state: %s (%s)", (ulong) i,
4193 4194
			srv_io_thread_op_info[i],
			srv_io_thread_function[i]);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4195

rburnett@build.mysql.com's avatar
rburnett@build.mysql.com committed
4196
#ifndef __WIN__
4197
		if (os_aio_segment_wait_events[i]->is_set) {
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4198 4199
			fprintf(file, " ev set");
		}
rburnett@build.mysql.com's avatar
rburnett@build.mysql.com committed
4200
#endif
4201

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4202
		fprintf(file, "\n");
4203 4204
	}

4205
	fputs("Pending normal aio reads:", file);
4206

4207 4208 4209
	array = os_aio_read_array;
loop:
	ut_a(array);
4210

4211 4212 4213 4214
	os_mutex_enter(array->mutex);

	ut_a(array->n_slots > 0);
	ut_a(array->n_segments > 0);
4215

4216 4217 4218 4219
	n_reserved = 0;

	for (i = 0; i < array->n_slots; i++) {
		slot = os_aio_array_get_nth_slot(array, i);
4220

4221 4222
		if (slot->reserved) {
			n_reserved++;
4223 4224 4225 4226 4227
#if 0
			fprintf(stderr, "Reserved slot, messages %p %p\n",
				(void*) slot->message1,
				(void*) slot->message2);
#endif
4228
			ut_a(slot->len > 0);
4229 4230 4231 4232 4233
		}
	}

	ut_a(array->n_reserved == n_reserved);

monty@mishka.local's avatar
monty@mishka.local committed
4234
	fprintf(file, " %lu", (ulong) n_reserved);
4235

4236 4237 4238
	os_mutex_exit(array->mutex);

	if (array == os_aio_read_array) {
4239
		fputs(", aio writes:", file);
4240

4241 4242 4243 4244 4245 4246
		array = os_aio_write_array;

		goto loop;
	}

	if (array == os_aio_write_array) {
4247
		fputs(",\n ibuf aio reads:", file);
4248 4249 4250 4251 4252 4253
		array = os_aio_ibuf_array;

		goto loop;
	}

	if (array == os_aio_ibuf_array) {
4254
		fputs(", log i/o's:", file);
4255 4256 4257 4258 4259 4260
		array = os_aio_log_array;

		goto loop;
	}

	if (array == os_aio_log_array) {
4261
		fputs(", sync i/o's:", file);
4262 4263 4264 4265
		array = os_aio_sync_array;

		goto loop;
	}
4266

4267
	putc('\n', file);
4268
	current_time = time(NULL);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4269
	time_elapsed = 0.001 + difftime(current_time, os_last_printout);
4270

4271 4272
	fprintf(file,
		"Pending flushes (fsync) log: %lu; buffer pool: %lu\n"
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4273
		"%lu OS file reads, %lu OS file writes, %lu OS fsyncs\n",
monty@mishka.local's avatar
monty@mishka.local committed
4274 4275
		(ulong) fil_n_pending_log_flushes,
		(ulong) fil_n_pending_tablespace_flushes,
4276 4277
		(ulong) os_n_file_reads, (ulong) os_n_file_writes,
		(ulong) os_n_fsyncs);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4278

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4279
	if (os_file_n_pending_preads != 0 || os_file_n_pending_pwrites != 0) {
4280
		fprintf(file,
4281 4282 4283
			"%lu pending preads, %lu pending pwrites\n",
			(ulong) os_file_n_pending_preads,
			(ulong) os_file_n_pending_pwrites);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4284 4285
	}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4286 4287 4288
	if (os_n_file_reads == os_n_file_reads_old) {
		avg_bytes_read = 0.0;
	} else {
4289 4290
		avg_bytes_read = (double) os_bytes_read_since_printout
			/ (os_n_file_reads - os_n_file_reads_old);
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4291 4292
	}

4293
	fprintf(file,
4294 4295
		"%.2f reads/s, %lu avg bytes/read,"
		" %.2f writes/s, %.2f fsyncs/s\n",
4296 4297
		(os_n_file_reads - os_n_file_reads_old)
		/ time_elapsed,
4298
		(ulong)avg_bytes_read,
4299 4300 4301 4302 4303 4304 4305 4306
		(os_n_file_writes - os_n_file_writes_old)
		/ time_elapsed,
		(os_n_fsyncs - os_n_fsyncs_old)
		/ time_elapsed);

	os_n_file_reads_old = os_n_file_reads;
	os_n_file_writes_old = os_n_file_writes;
	os_n_fsyncs_old = os_n_fsyncs;
heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4307
	os_bytes_read_since_printout = 0;
4308

4309
	os_last_printout = current_time;
4310 4311
}

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322
/**************************************************************************
Refreshes the statistics used to print per-second averages. */

void
os_aio_refresh_stats(void)
/*======================*/
{
	os_n_file_reads_old = os_n_file_reads;
	os_n_file_writes_old = os_n_file_writes;
	os_n_fsyncs_old = os_n_fsyncs;
	os_bytes_read_since_printout = 0;
4323

heikki@hundin.mysql.fi's avatar
heikki@hundin.mysql.fi committed
4324 4325 4326
	os_last_printout = time(NULL);
}

4327
#ifdef UNIV_DEBUG
4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338
/**************************************************************************
Checks that all slots in the system have been freed, that is, there are
no pending io operations. */

ibool
os_aio_all_slots_free(void)
/*=======================*/
				/* out: TRUE if all free */
{
	os_aio_array_t*	array;
	ulint		n_res	= 0;
4339

4340 4341 4342 4343
	array = os_aio_read_array;

	os_mutex_enter(array->mutex);

4344 4345
	n_res += array->n_reserved;

4346 4347 4348 4349 4350 4351
	os_mutex_exit(array->mutex);

	array = os_aio_write_array;

	os_mutex_enter(array->mutex);

4352 4353
	n_res += array->n_reserved;

4354 4355 4356 4357 4358 4359
	os_mutex_exit(array->mutex);

	array = os_aio_ibuf_array;

	os_mutex_enter(array->mutex);

4360 4361
	n_res += array->n_reserved;

4362 4363 4364 4365 4366 4367
	os_mutex_exit(array->mutex);

	array = os_aio_log_array;

	os_mutex_enter(array->mutex);

4368 4369
	n_res += array->n_reserved;

4370 4371 4372 4373 4374 4375
	os_mutex_exit(array->mutex);

	array = os_aio_sync_array;

	os_mutex_enter(array->mutex);

4376 4377
	n_res += array->n_reserved;

4378 4379 4380 4381 4382 4383 4384 4385 4386
	os_mutex_exit(array->mutex);

	if (n_res == 0) {

		return(TRUE);
	}

	return(FALSE);
}
4387
#endif /* UNIV_DEBUG */