os0file.c 110 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"
unknown's avatar
unknown committed
11
#include "os0thread.h"
12
#include "ut0mem.h"
13
#include "srv0srv.h"
unknown's avatar
unknown committed
14
#include "srv0start.h"
15
#include "fil0fil.h"
unknown's avatar
unknown committed
16
#include "buf0buf.h"
17

unknown's avatar
unknown 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 26 27 28 29 30
#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

unknown's avatar
unknown committed
31
/* This specifies the file permissions InnoDB uses when it creates files in
unknown's avatar
unknown committed
32 33 34 35 36 37 38 39 40
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

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

49 50 51 52 53 54
/* 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 */
unknown's avatar
unknown committed
55
#define OS_AIO_MERGE_N_CONSECUTIVE	64
56 57 58 59 60 61 62

/* 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;

unknown's avatar
unknown committed
63 64
ibool	os_aio_print_debug	= FALSE;

Mikael Ronstrom's avatar
Mikael Ronstrom committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
/* State for the state of an IO request in simulated AIO.
   Protocol for simulated aio:
     client requests IO: find slot with reserved = FALSE. Add entry with
                         status = OS_AIO_NOT_ISSUED.
     IO thread wakes: find adjacent slots with reserved = TRUE and status =
                      OS_AIO_NOT_ISSUED. Change status for slots to
                      OS_AIO_ISSUED.
     IO operation completes: set status for slots to OS_AIO_DONE. set status
                             for the first slot to OS_AIO_CLAIMED and return
                             result for that slot.
   When there are multiple read and write threads, they all compete to execute
   the requests in the array (os_aio_array_t). This avoids the need to load
   balance requests at the time the request is made at the cost of waking all
   threads when a request is available.
*/
typedef enum {
	OS_AIO_NOT_ISSUED, /* Available to be processed by an IO thread. */
	OS_AIO_ISSUED,     /* Being processed by an IO thread. */
	OS_AIO_DONE,       /* Request processed. */
	OS_AIO_CLAIMED     /* Result being returned to client. */
} os_aio_status;

87 88 89 90 91 92 93 94
/* 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 */
Mikael Ronstrom's avatar
Mikael Ronstrom committed
95 96
	os_aio_status   status;		/* Status for current request. Valid when reserved
					is TRUE. Used only in simulated aio. */
unknown's avatar
unknown committed
97
	time_t		reservation_time;/* time when reserved */
98 99 100 101 102 103 104 105
	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 */
106
	const char*	name;		/* file name or path */
unknown's avatar
unknown committed
107
	fil_node_t*	message1;	/* message which is given by the */
108 109 110 111 112
	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
113
	os_event_t	event;		/* event object we need in the
114
					OVERLAPPED struct */
115 116 117 118 119 120 121 122 123 124 125 126 127
	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 */
128
	os_event_t	not_full; /* The event which is set to the signaled
129 130
				  state when there is space in the aio
				  outside the ibuf segment */
131 132 133
	os_event_t	is_empty; /* The event which is set to the signaled
				  state when there are no pending i/os
				  in this array */
134 135 136 137
	ulint		n_slots;  /* Total number of slots in the aio array.
				  This must be divisible by n_threads. */
	ulint		n_reserved;/* Number of reserved slots in the
				  aio array outside the ibuf segment */
138
	os_aio_slot_t*	slots;	  /* Pointer to the slots in the array */
139
#ifdef __WIN__
140
	os_native_event_t* native_events;
141 142 143 144
				  /* 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
145
				  Windows */
146
#endif
147 148 149 150 151
};

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

Mikael Ronstrom's avatar
Mikael Ronstrom committed
152 153 154 155 156 157 158 159 160 161 162
/* Number of threads for reading and writing. */
ulint os_aio_read_threads = 0;
ulint os_aio_write_threads = 0;

/* Number for the first global segment for reading. */
const ulint os_aio_first_read_segment = 2;

/* Number for the first global segment for writing. Set to
2 + os_aio_read_write_threads. */
ulint os_aio_first_write_segment = 0;

163 164
/* 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. */
unknown's avatar
unknown committed
165 166 167 168 169
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;
170

Mikael Ronstrom's avatar
Mikael Ronstrom committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
/* Per thread buffer used for merged IO requests. Used by
os_aio_simulated_handle so that a buffer doesn't have to be allocated
for each request. */
static char* os_aio_thread_buffer[SRV_MAX_N_IO_THREADS];
static ulint os_aio_thread_buffer_size[SRV_MAX_N_IO_THREADS];

/* Count pages read and written per thread */
static ulint os_aio_thread_io_reads[SRV_MAX_N_IO_THREADS];
static ulint os_aio_thread_io_writes[SRV_MAX_N_IO_THREADS];

/* Number of IO operations done. One request can be for N pages. */
static ulint os_aio_thread_io_requests[SRV_MAX_N_IO_THREADS];

/* usecs spent blocked on an IO request */
static double os_aio_thread_io_wait[SRV_MAX_N_IO_THREADS];
/* max usecs spent blocked on an IO request */
static double os_aio_thread_max_io_wait[SRV_MAX_N_IO_THREADS];

/* Number of IO global segments. An IO handler thread is created for each
global segment, except for the segment associated with os_aio_sync_array.
Several segments can be associated with os_aio_{read,write}_array. One
segment is created for each of the other arrays. This is also the number
of valid entries in srv_io_thread_reads, srv_io_thread_writes,
srv_io_thread_op_info, srv_io_thread_function and os_aio_segment_wait_events. */
unknown's avatar
unknown committed
195
static ulint	os_aio_n_segments	= ULINT_UNDEFINED;
196

Mikael Ronstrom's avatar
Mikael Ronstrom committed
197 198 199 200 201 202 203
/* Set to TRUE to temporarily block reads from being scheduled while a batch
of read requests is added to allow them to be merged by the IO handler thread
if they are adjacent. Declared volatile because we don't want this to be
read from a register in a loop when another thread may change the value in
memory.
*/
static volatile ibool	os_aio_recommend_sleep_for_read_threads	= FALSE;
unknown's avatar
unknown committed
204

205
ulint	os_n_file_reads		= 0;
unknown's avatar
unknown committed
206
ulint	os_bytes_read_since_printout = 0;
207 208 209 210 211 212 213
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;

unknown's avatar
unknown committed
214 215
ibool	os_has_said_disk_full	= FALSE;

216
/* The mutex protecting the following counts of pending I/O operations */
unknown's avatar
unknown committed
217
static os_mutex_t os_file_count_mutex;
unknown's avatar
unknown committed
218 219
ulint	os_file_n_pending_preads  = 0;
ulint	os_file_n_pending_pwrites = 0;
220 221
ulint	os_n_pending_writes = 0;
ulint	os_n_pending_reads = 0;
222

Mikael Ronstrom's avatar
Mikael Ronstrom committed
223
static double time_usecs() {
224 225
  ulint sec, ms;
  if (ut_usectime(&sec, &ms))
Mikael Ronstrom's avatar
Mikael Ronstrom committed
226 227
    return 0;
  else
228
    return sec * 1000000.0 + ms;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
229 230
}

231 232 233 234 235 236
/***************************************************************************
Gets the operating system version. Currently works only on Windows. */

ulint
os_get_os_version(void)
/*===================*/
237
		  /* out: OS_WIN95, OS_WIN31, OS_WINNT, OS_WIN2000 */
238 239
{
#ifdef __WIN__
240
	OSVERSIONINFO	  os_info;
241

242
	os_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
243 244 245

	ut_a(GetVersionEx(&os_info));

246 247 248 249 250
	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) {
unknown's avatar
unknown committed
251
		if (os_info.dwMajorVersion <= 4) {
252 253
			return(OS_WINNT);
		} else {
unknown's avatar
unknown committed
254
			return(OS_WIN2000);
255 256 257 258 259
		}
	} else {
		ut_error;
		return(0);
	}
260
#else
261
	ut_error;
262

263
	return(0);
264 265 266
#endif
}

267 268 269 270 271 272 273
/***************************************************************************
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
unknown's avatar
unknown committed
274 275 276 277 278 279
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 */
280 281 282 283 284 285 286
{
	ulint	err;

#ifdef __WIN__

	err = (ulint) GetLastError();

unknown's avatar
unknown committed
287
	if (report_all_errors
unknown's avatar
unknown committed
288
	    || (err != ERROR_DISK_FULL && err != ERROR_FILE_EXISTS)) {
unknown's avatar
unknown committed
289

unknown's avatar
unknown committed
290
		ut_print_timestamp(stderr);
291
		fprintf(stderr,
unknown's avatar
unknown committed
292 293
			"  InnoDB: Operating system error number %lu"
			" in a file operation.\n", (ulong) err);
unknown's avatar
unknown committed
294

unknown's avatar
unknown committed
295
		if (err == ERROR_PATH_NOT_FOUND) {
unknown's avatar
unknown committed
296
			fprintf(stderr,
unknown's avatar
unknown committed
297 298
				"InnoDB: The error means the system"
				" cannot find the path specified.\n");
unknown's avatar
unknown committed
299 300 301

			if (srv_is_being_started) {
				fprintf(stderr,
unknown's avatar
unknown committed
302 303 304 305
					"InnoDB: If you are installing InnoDB,"
					" remember that you must create\n"
					"InnoDB: directories yourself, InnoDB"
					" does not create them.\n");
unknown's avatar
unknown committed
306
			}
unknown's avatar
unknown committed
307
		} else if (err == ERROR_ACCESS_DENIED) {
unknown's avatar
unknown committed
308
			fprintf(stderr,
unknown's avatar
unknown committed
309 310 311 312 313
				"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");
314 315 316 317 318 319 320 321 322
		} else if (err == ERROR_SHARING_VIOLATION
			   || err == ERROR_LOCK_VIOLATION) {
			fprintf(stderr,
				"InnoDB: The error means that another program"
				" is using InnoDB's files.\n"
				"InnoDB: This might be a backup or antivirus"
				" software or another instance\n"
				"InnoDB: of MySQL."
				" Please close it to get rid of this error.\n");
unknown's avatar
unknown committed
323
		} else {
unknown's avatar
unknown committed
324
			fprintf(stderr,
unknown's avatar
unknown committed
325 326 327 328 329
				"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");
unknown's avatar
unknown committed
330
		}
331
	}
332

unknown's avatar
unknown committed
333 334
	fflush(stderr);

335 336 337 338 339 340
	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);
341 342 343
	} else if (err == ERROR_SHARING_VIOLATION
		   || err == ERROR_LOCK_VIOLATION) {
		return(OS_FILE_SHARING_VIOLATION);
344 345 346 347
	} else {
		return(100 + err);
	}
#else
348 349
	err = (ulint) errno;

unknown's avatar
unknown committed
350
	if (report_all_errors
unknown's avatar
unknown committed
351
	    || (err != ENOSPC && err != EEXIST)) {
unknown's avatar
unknown committed
352

unknown's avatar
unknown committed
353
		ut_print_timestamp(stderr);
354
		fprintf(stderr,
unknown's avatar
unknown committed
355 356
			"  InnoDB: Operating system error number %lu"
			" in a file operation.\n", (ulong) err);
unknown's avatar
unknown committed
357

unknown's avatar
unknown committed
358
		if (err == ENOENT) {
unknown's avatar
unknown committed
359
			fprintf(stderr,
unknown's avatar
unknown committed
360 361
				"InnoDB: The error means the system"
				" cannot find the path specified.\n");
362

unknown's avatar
unknown committed
363 364
			if (srv_is_being_started) {
				fprintf(stderr,
unknown's avatar
unknown committed
365 366 367 368
					"InnoDB: If you are installing InnoDB,"
					" remember that you must create\n"
					"InnoDB: directories yourself, InnoDB"
					" does not create them.\n");
unknown's avatar
unknown committed
369
			}
unknown's avatar
unknown committed
370
		} else if (err == EACCES) {
unknown's avatar
unknown committed
371
			fprintf(stderr,
unknown's avatar
unknown committed
372 373 374
				"InnoDB: The error means mysqld does not have"
				" the access rights to\n"
				"InnoDB: the directory.\n");
unknown's avatar
unknown committed
375
		} else {
unknown's avatar
unknown committed
376
			if (strerror((int)err) != NULL) {
unknown's avatar
unknown committed
377
				fprintf(stderr,
unknown's avatar
unknown committed
378 379 380
					"InnoDB: Error number %lu"
					" means '%s'.\n",
					err, strerror((int)err));
unknown's avatar
unknown committed
381
			}
unknown's avatar
unknown committed
382

unknown's avatar
unknown committed
383
			fprintf(stderr,
unknown's avatar
unknown committed
384 385 386 387 388
				"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");
unknown's avatar
unknown committed
389
		}
390
	}
391

unknown's avatar
unknown committed
392 393
	fflush(stderr);

unknown's avatar
unknown committed
394
	if (err == ENOSPC) {
395 396 397 398 399 400 401 402 403
		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);
404 405
	} else if (err == EXDEV || err == ENOTDIR || err == EISDIR) {
		return(OS_FILE_PATH_ERROR);
406 407 408 409 410 411 412
	} else {
		return(100 + err);
	}
#endif
}

/********************************************************************
unknown's avatar
unknown committed
413 414 415 416
Does error handling when a file operation fails.
Conditionally exits (calling exit(3)) based on should_exit value and the
error type */

417 418
static
ibool
unknown's avatar
unknown committed
419 420 421 422 423 424 425 426
os_file_handle_error_cond_exit(
/*===========================*/
					/* out: TRUE if we should retry the
					operation */
	const char*	name,		/* in: name of a file or NULL */
	const char*	operation,	/* in: operation */
	ibool		should_exit)	/* in: call exit(3) if unknown error
					and this parameter is TRUE */
427 428 429
{
	ulint	err;

unknown's avatar
unknown committed
430
	err = os_file_get_last_error(FALSE);
431

432
	if (err == OS_FILE_DISK_FULL) {
unknown's avatar
unknown committed
433 434 435 436 437 438
		/* We only print a warning about disk full once */

		if (os_has_said_disk_full) {

			return(FALSE);
		}
439

440
		if (name) {
unknown's avatar
unknown committed
441 442
			ut_print_timestamp(stderr);
			fprintf(stderr,
unknown's avatar
unknown committed
443 444
				"  InnoDB: Encountered a problem with"
				" file %s\n", name);
445
		}
unknown's avatar
unknown committed
446 447

		ut_print_timestamp(stderr);
448
		fprintf(stderr,
unknown's avatar
unknown committed
449 450
			"  InnoDB: Disk is full. Try to clean the disk"
			" to free space.\n");
451

unknown's avatar
unknown committed
452 453
		os_has_said_disk_full = TRUE;

unknown's avatar
unknown committed
454 455
		fflush(stderr);

unknown's avatar
unknown committed
456
		return(FALSE);
457
	} else if (err == OS_FILE_AIO_RESOURCES_RESERVED) {
unknown's avatar
unknown committed
458

459
		return(TRUE);
460
	} else if (err == OS_FILE_ALREADY_EXISTS
unknown's avatar
unknown committed
461
		   || err == OS_FILE_PATH_ERROR) {
unknown's avatar
unknown committed
462

463
		return(FALSE);
464 465 466 467
	} else if (err == OS_FILE_SHARING_VIOLATION) {

		os_thread_sleep(10000000);  /* 10 sec */
		return(TRUE);
468
	} else {
469 470 471 472
		if (name) {
			fprintf(stderr, "InnoDB: File name %s\n", name);
		}

473
		fprintf(stderr, "InnoDB: File operation call: '%s'.\n",
474
			operation);
475

unknown's avatar
unknown committed
476 477 478 479
		if (should_exit) {
			fprintf(stderr, "InnoDB: Cannot continue operation.\n");

			fflush(stderr);
unknown's avatar
unknown committed
480

unknown's avatar
unknown committed
481 482
			exit(1);
		}
483 484
	}

485
	return(FALSE);
486 487
}

unknown's avatar
unknown committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
/********************************************************************
Does error handling when a file operation fails. */
static
ibool
os_file_handle_error(
/*=================*/
				/* out: TRUE if we should retry the
				operation */
	const char*	name,	/* in: name of a file or NULL */
	const char*	operation)/* in: operation */
{
	/* exit in case of unknown error */
	return(os_file_handle_error_cond_exit(name, operation, TRUE));
}

/********************************************************************
Does error handling when a file operation fails. */
static
ibool
os_file_handle_error_no_exit(
/*=========================*/
				/* out: TRUE if we should retry the
				operation */
	const char*	name,	/* in: name of a file or NULL */
	const char*	operation)/* in: operation */
{
	/* don't exit in case of unknown error */
	return(os_file_handle_error_cond_exit(name, operation, FALSE));
}

518 519
#undef USE_FILE_LOCK
#define USE_FILE_LOCK
unknown's avatar
unknown committed
520
#if defined(UNIV_HOTBACKUP) || defined(__WIN__) || defined(__NETWARE__)
521 522 523 524 525 526
/* InnoDB Hot Backup does not lock the data files.
 * On Windows, mandatory locking is used.
 */
# undef USE_FILE_LOCK
#endif
#ifdef USE_FILE_LOCK
527 528 529 530 531 532 533 534
/********************************************************************
Obtain an exclusive lock on a file. */
static
int
os_file_lock(
/*=========*/
				/* out: 0 on success */
	int		fd,	/* in: file descriptor */
unknown's avatar
unknown committed
535
	const char*	name)	/* in: file name */
536 537
{
	struct flock lk;
unknown's avatar
unknown committed
538
	lk.l_type = F_WRLCK;
539 540 541 542
	lk.l_whence = SEEK_SET;
	lk.l_start = lk.l_len = 0;
	if (fcntl(fd, F_SETLK, &lk) == -1) {
		fprintf(stderr,
unknown's avatar
unknown committed
543 544 545 546
			"InnoDB: Unable to lock %s, error: %d\n", name, errno);

		if (errno == EAGAIN || errno == EACCES) {
			fprintf(stderr,
unknown's avatar
unknown committed
547 548 549 550
				"InnoDB: Check that you do not already have"
				" another mysqld process\n"
				"InnoDB: using the same InnoDB data"
				" or log files.\n");
unknown's avatar
unknown committed
551 552
		}

553 554
		return(-1);
	}
unknown's avatar
unknown committed
555

unknown's avatar
unknown committed
556
	return(0);
557
}
558
#endif /* USE_FILE_LOCK */
559

unknown's avatar
unknown committed
560 561 562 563 564 565 566 567 568
/********************************************************************
Creates the seek mutexes used in positioned reads and writes. */

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

unknown's avatar
unknown committed
569 570
	os_file_count_mutex = os_mutex_create(NULL);

unknown's avatar
unknown committed
571 572 573 574 575
	for (i = 0; i < OS_FILE_N_SEEK_MUTEXES; i++) {
		os_file_seek_mutexes[i] = os_mutex_create(NULL);
	}
}

576
#if !defined(UNIV_HOTBACKUP) && !defined(__NETWARE__)
577
/*************************************************************************
578 579
Creates a temporary file that will be deleted on close.
This function is defined in ha_innodb.cc. */
580 581 582 583 584

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

587
/***************************************************************************
588 589 590 591
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. */
592 593 594 595

FILE*
os_file_create_tmpfile(void)
/*========================*/
596
			/* out: temporary file handle, or NULL on error */
597
{
598 599 600 601 602 603
#ifdef UNIV_HOTBACKUP
	ut_error;

	return(NULL);
#else
# ifdef __NETWARE__
604
	FILE*	file	= tmpfile();
605
# else /* __NETWARE__ */
606
	FILE*	file	= NULL;
607
	int	fd	= innobase_mysql_tmpfile();
608 609 610

	if (fd >= 0) {
		file = fdopen(fd, "w+b");
611
	}
612
# endif /* __NETWARE__ */
613 614

	if (!file) {
615
		ut_print_timestamp(stderr);
unknown's avatar
unknown committed
616 617 618
		fprintf(stderr,
			"  InnoDB: Error: unable to create temporary file;"
			" errno: %d\n", errno);
619
# ifndef __NETWARE__
620 621 622
		if (fd >= 0) {
			close(fd);
		}
623
# endif /* !__NETWARE__ */
624
	}
625

626
	return(file);
627
#endif /* UNIV_HOTBACKUP */
628 629
}

unknown's avatar
unknown committed
630 631 632 633 634 635 636 637 638
/***************************************************************************
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(
/*============*/
639 640 641 642 643 644 645 646 647
					/* 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 */
unknown's avatar
unknown committed
648 649 650
{
	os_file_dir_t		dir;
#ifdef __WIN__
651
	LPWIN32_FIND_DATA	lpFindFileData;
unknown's avatar
unknown committed
652 653 654 655 656
	char			path[OS_FILE_MAX_PATH + 3];

	ut_a(strlen(dirname) < OS_FILE_MAX_PATH);

	strcpy(path, dirname);
unknown's avatar
unknown committed
657
	strcpy(path + strlen(path), "\\*");
unknown's avatar
unknown committed
658 659 660 661 662 663 664

	/* 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));

unknown's avatar
unknown committed
665
	dir = FindFirstFile((LPCTSTR) path, lpFindFileData);
unknown's avatar
unknown committed
666 667 668 669 670 671

	ut_free(lpFindFileData);

	if (dir == INVALID_HANDLE_VALUE) {

		if (error_is_fatal) {
672
			os_file_handle_error(dirname, "opendir");
unknown's avatar
unknown committed
673 674 675 676 677
		}

		return(NULL);
	}

678
	return(dir);
unknown's avatar
unknown committed
679 680 681 682
#else
	dir = opendir(dirname);

	if (dir == NULL && error_is_fatal) {
683
		os_file_handle_error(dirname, "opendir");
unknown's avatar
unknown committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
	}

	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) {
705 706
		os_file_handle_error_no_exit(NULL, "closedir");

unknown's avatar
unknown committed
707 708
		return(-1);
	}
709

unknown's avatar
unknown committed
710 711 712
	return(0);
#else
	int	ret;
713

unknown's avatar
unknown committed
714 715 716
	ret = closedir(dir);

	if (ret) {
717
		os_file_handle_error_no_exit(NULL, "closedir");
unknown's avatar
unknown committed
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
	}

	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 */
733
	const char*	dirname,/* in: directory name or path */
unknown's avatar
unknown committed
734 735 736 737 738 739 740 741 742 743 744 745
	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) {
unknown's avatar
unknown committed
746 747
		ut_a(strlen((char *) lpFindFileData->cFileName)
		     < OS_FILE_MAX_PATH);
unknown's avatar
unknown committed
748

unknown's avatar
unknown committed
749
		if (strcmp((char *) lpFindFileData->cFileName, ".") == 0
unknown's avatar
unknown committed
750
		    || strcmp((char *) lpFindFileData->cFileName, "..") == 0) {
unknown's avatar
unknown committed
751

752
			goto next_file;
unknown's avatar
unknown committed
753 754
		}

unknown's avatar
unknown committed
755
		strcpy(info->name, (char *) lpFindFileData->cFileName);
unknown's avatar
unknown committed
756

unknown's avatar
unknown committed
757
		info->size = (ib_longlong)(lpFindFileData->nFileSizeLow)
unknown's avatar
unknown committed
758 759
			+ (((ib_longlong)(lpFindFileData->nFileSizeHigh))
			   << 32);
unknown's avatar
unknown committed
760 761

		if (lpFindFileData->dwFileAttributes
unknown's avatar
unknown committed
762 763 764 765 766 767 768
		    & 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 */
unknown's avatar
unknown committed
769 770
			info->type = OS_FILE_TYPE_LINK;
		} else if (lpFindFileData->dwFileAttributes
unknown's avatar
unknown committed
771
			   & FILE_ATTRIBUTE_DIRECTORY) {
772
			info->type = OS_FILE_TYPE_DIR;
unknown's avatar
unknown committed
773
		} else {
unknown's avatar
unknown committed
774 775 776 777 778
			/* 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;
unknown's avatar
unknown committed
779 780 781 782 783 784 785 786 787 788 789
		}
	}

	ut_free(lpFindFileData);

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

		return(1);
	} else {
unknown's avatar
unknown committed
790
		os_file_handle_error_no_exit(dirname,
unknown's avatar
unknown committed
791
					     "readdir_next_file");
unknown's avatar
unknown committed
792 793 794 795 796 797 798
		return(-1);
	}
#else
	struct dirent*	ent;
	char*		full_path;
	int		ret;
	struct stat	statinfo;
unknown's avatar
unknown committed
799
#ifdef HAVE_READDIR_R
unknown's avatar
unknown committed
800 801 802 803 804
	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 */
unknown's avatar
unknown committed
805 806
#endif

unknown's avatar
unknown committed
807
next_file:
unknown's avatar
unknown committed
808 809 810 811 812 813

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

	if (ret != 0) {
		fprintf(stderr,
unknown's avatar
unknown committed
814 815
			"InnoDB: cannot read directory %s, error %lu\n",
			dirname, (ulong)ret);
unknown's avatar
unknown committed
816 817 818

		return(-1);
	}
unknown's avatar
unknown committed
819 820

	if (ent == NULL) {
unknown's avatar
unknown committed
821
		/* End of directory */
822

unknown's avatar
unknown committed
823 824 825
		return(1);
	}

unknown's avatar
unknown committed
826 827 828 829 830 831 832 833 834
	ut_a(strlen(ent->d_name) < _POSIX_PATH_MAX + 100 - 1);
#else
	ent = readdir(dir);

	if (ent == NULL) {

		return(1);
	}
#endif
unknown's avatar
unknown committed
835 836 837 838 839 840 841 842 843 844
	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);
845

unknown's avatar
unknown committed
846 847 848 849 850
	sprintf(full_path, "%s/%s", dirname, ent->d_name);

	ret = stat(full_path, &statinfo);

	if (ret) {
unknown's avatar
unknown committed
851
		os_file_handle_error_no_exit(full_path, "stat");
unknown's avatar
unknown committed
852 853 854 855 856 857 858 859 860 861 862

		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)) {
863
		info->type = OS_FILE_TYPE_LINK;
unknown's avatar
unknown committed
864
	} else if (S_ISREG(statinfo.st_mode)) {
865
		info->type = OS_FILE_TYPE_FILE;
unknown's avatar
unknown committed
866
	} else {
867
		info->type = OS_FILE_TYPE_UNKNOWN;
unknown's avatar
unknown committed
868
	}
869

unknown's avatar
unknown committed
870 871 872 873 874 875
	ut_free(full_path);

	return(0);
#endif
}

unknown's avatar
unknown committed
876 877 878 879 880 881 882 883 884
/*********************************************************************
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(
/*=====================*/
885 886 887 888 889 890
					/* 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. */
unknown's avatar
unknown committed
891 892 893
{
#ifdef __WIN__
	BOOL	rcode;
894

unknown's avatar
unknown committed
895
	rcode = CreateDirectory((LPCTSTR) pathname, NULL);
unknown's avatar
unknown committed
896 897 898
	if (!(rcode != 0
	      || (GetLastError() == ERROR_ALREADY_EXISTS
		  && !fail_if_exists))) {
unknown's avatar
unknown committed
899
		/* failure */
900
		os_file_handle_error(pathname, "CreateDirectory");
unknown's avatar
unknown committed
901 902 903

		return(FALSE);
	}
904

unknown's avatar
unknown committed
905 906 907 908 909 910 911 912
	return (TRUE);
#else
	int	rcode;

	rcode = mkdir(pathname, 0770);

	if (!(rcode == 0 || (errno == EEXIST && !fail_if_exists))) {
		/* failure */
unknown's avatar
unknown committed
913
		os_file_handle_error(pathname, "mkdir");
unknown's avatar
unknown committed
914 915 916

		return(FALSE);
	}
917

unknown's avatar
unknown committed
918
	return (TRUE);
919
#endif
unknown's avatar
unknown committed
920 921
}

unknown's avatar
unknown committed
922 923 924 925 926 927
/********************************************************************
A simple function to open or create a file. */

os_file_t
os_file_create_simple(
/*==================*/
928 929 930 931 932 933 934 935 936
				/* 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
937
				OS_FILE_CREATE_PATH if new file
938 939 940 941 942
				(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 */
unknown's avatar
unknown committed
943 944 945 946 947 948 949
{
#ifdef __WIN__
	os_file_t	file;
	DWORD		create_flag;
	DWORD		access;
	DWORD		attributes	= 0;
	ibool		retry;
950 951

try_again:
unknown's avatar
unknown committed
952 953 954 955 956 957
	ut_a(name);

	if (create_mode == OS_FILE_OPEN) {
		create_flag = OPEN_EXISTING;
	} else if (create_mode == OS_FILE_CREATE) {
		create_flag = CREATE_NEW;
958 959 960 961 962 963 964 965
	} 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;
unknown's avatar
unknown committed
966 967 968 969 970 971 972 973 974 975 976 977 978 979
	} 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;
	}

unknown's avatar
unknown committed
980
	file = CreateFile((LPCTSTR) name,
unknown's avatar
unknown committed
981 982
			  access,
			  FILE_SHARE_READ | FILE_SHARE_WRITE,
unknown's avatar
unknown committed
983
			  /* file can be read and written also
unknown's avatar
unknown committed
984 985 986 987 988
			  by other processes */
			  NULL,	/* default security attributes */
			  create_flag,
			  attributes,
			  NULL);	/* no template file */
unknown's avatar
unknown committed
989 990 991 992

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

993
		retry = os_file_handle_error(name,
unknown's avatar
unknown committed
994 995
					     create_mode == OS_FILE_OPEN ?
					     "open" : "create");
unknown's avatar
unknown committed
996 997 998 999 1000 1001 1002 1003
		if (retry) {
			goto try_again;
		}
	} else {
		*success = TRUE;
	}

	return(file);
1004
#else /* __WIN__ */
unknown's avatar
unknown committed
1005 1006 1007
	os_file_t	file;
	int		create_flag;
	ibool		retry;
1008 1009

try_again:
unknown's avatar
unknown committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
	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;
1020 1021 1022 1023 1024 1025 1026 1027
	} 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;
unknown's avatar
unknown committed
1028 1029 1030 1031 1032 1033
	} else {
		create_flag = 0;
		ut_error;
	}

	if (create_mode == OS_FILE_CREATE) {
1034
		file = open(name, create_flag, S_IRUSR | S_IWUSR
unknown's avatar
unknown committed
1035
			    | S_IRGRP | S_IWGRP);
1036 1037 1038 1039
	} else {
		file = open(name, create_flag);
	}

unknown's avatar
unknown committed
1040 1041 1042
	if (file == -1) {
		*success = FALSE;

1043
		retry = os_file_handle_error(name,
unknown's avatar
unknown committed
1044 1045
					     create_mode == OS_FILE_OPEN ?
					     "open" : "create");
unknown's avatar
unknown committed
1046 1047 1048
		if (retry) {
			goto try_again;
		}
1049
#ifdef USE_FILE_LOCK
unknown's avatar
unknown committed
1050
	} else if (access_type == OS_FILE_READ_WRITE
unknown's avatar
unknown committed
1051
		   && os_file_lock(file, name)) {
1052
		*success = FALSE;
1053
		close(file);
1054 1055
		file = -1;
#endif
unknown's avatar
unknown committed
1056 1057 1058 1059
	} else {
		*success = TRUE;
	}

1060
	return(file);
1061
#endif /* __WIN__ */
unknown's avatar
unknown committed
1062
}
unknown's avatar
unknown committed
1063 1064 1065 1066 1067 1068 1069

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

os_file_t
os_file_create_simple_no_error_handling(
/*====================================*/
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
				/* 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 */
unknown's avatar
unknown committed
1084 1085 1086 1087 1088 1089
{
#ifdef __WIN__
	os_file_t	file;
	DWORD		create_flag;
	DWORD		access;
	DWORD		attributes	= 0;
unknown's avatar
unknown committed
1090
	DWORD		share_mode	= FILE_SHARE_READ | FILE_SHARE_WRITE;
1091

unknown's avatar
unknown committed
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
	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;
unknown's avatar
unknown committed
1107 1108 1109
	} else if (access_type == OS_FILE_READ_ALLOW_DELETE) {
		access = GENERIC_READ;
		share_mode = FILE_SHARE_DELETE | FILE_SHARE_READ
unknown's avatar
unknown committed
1110
			| FILE_SHARE_WRITE;	/* A backup program has to give
unknown's avatar
unknown committed
1111 1112 1113
						mysqld the maximum freedom to
						do what it likes with the
						file */
unknown's avatar
unknown committed
1114 1115 1116 1117 1118
	} else {
		access = 0;
		ut_error;
	}

unknown's avatar
unknown committed
1119
	file = CreateFile((LPCTSTR) name,
unknown's avatar
unknown committed
1120 1121 1122 1123 1124 1125
			  access,
			  share_mode,
			  NULL,	/* default security attributes */
			  create_flag,
			  attributes,
			  NULL);	/* no template file */
unknown's avatar
unknown committed
1126 1127 1128 1129 1130 1131 1132 1133

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

	return(file);
1134
#else /* __WIN__ */
unknown's avatar
unknown committed
1135 1136
	os_file_t	file;
	int		create_flag;
1137

unknown's avatar
unknown committed
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
	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) {
1154
		file = open(name, create_flag, S_IRUSR | S_IWUSR
unknown's avatar
unknown committed
1155
			    | S_IRGRP | S_IWGRP);
1156 1157 1158 1159
	} else {
		file = open(name, create_flag);
	}

unknown's avatar
unknown committed
1160 1161
	if (file == -1) {
		*success = FALSE;
1162
#ifdef USE_FILE_LOCK
unknown's avatar
unknown committed
1163
	} else if (access_type == OS_FILE_READ_WRITE
unknown's avatar
unknown committed
1164
		   && os_file_lock(file, name)) {
1165
		*success = FALSE;
1166
		close(file);
1167 1168
		file = -1;
#endif
unknown's avatar
unknown committed
1169 1170 1171 1172
	} else {
		*success = TRUE;
	}

1173
	return(file);
1174
#endif /* __WIN__ */
unknown's avatar
unknown committed
1175 1176
}

unknown's avatar
unknown committed
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
/********************************************************************
Tries to disable OS caching on an opened file descriptor. */

void
os_file_set_nocache(
/*================*/
	int		fd,		/* in: file descriptor to alter */
	const char*	file_name,	/* in: used in the diagnostic message */
	const char*	operation_name)	/* in: used in the diagnostic message,
					we call os_file_set_nocache()
					immediately after opening or creating
					a file, so this is either "open" or
					"create" */
{
	/* some versions of Solaris may not have DIRECTIO_ON */
#if defined(UNIV_SOLARIS) && defined(DIRECTIO_ON)
	if (directio(fd, DIRECTIO_ON) == -1) {
		int	errno_save;
		errno_save = (int)errno;
		ut_print_timestamp(stderr);
		fprintf(stderr,
			"  InnoDB: Failed to set DIRECTIO_ON "
			"on file %s: %s: %s, continuing anyway\n",
			file_name, operation_name, strerror(errno_save));
	}
#elif defined(O_DIRECT)
	if (fcntl(fd, F_SETFL, O_DIRECT) == -1) {
		int	errno_save;
		errno_save = (int)errno;
		ut_print_timestamp(stderr);
		fprintf(stderr,
			"  InnoDB: Failed to set O_DIRECT "
			"on file %s: %s: %s, continuing anyway\n",
			file_name, operation_name, strerror(errno_save));
		if (errno_save == EINVAL) {
			ut_print_timestamp(stderr);
			fprintf(stderr,
				"  InnoDB: O_DIRECT is known to result in "
				"'Invalid argument' on Linux on tmpfs, "
				"see MySQL Bug#26662\n");
		}
	}
#endif
}

1222 1223 1224 1225 1226 1227
/********************************************************************
Opens an existing file or creates a new. */

os_file_t
os_file_create(
/*===========*/
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
				/* 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 */
1250 1251 1252
{
#ifdef __WIN__
	os_file_t	file;
unknown's avatar
unknown committed
1253
	DWORD		share_mode	= FILE_SHARE_READ;
1254 1255 1256
	DWORD		create_flag;
	DWORD		attributes;
	ibool		retry;
1257
try_again:
1258 1259
	ut_a(name);

unknown's avatar
unknown committed
1260 1261 1262
	if (create_mode == OS_FILE_OPEN_RAW) {
		create_flag = OPEN_EXISTING;
		share_mode = FILE_SHARE_WRITE;
1263
	} else if (create_mode == OS_FILE_OPEN
unknown's avatar
unknown committed
1264
		   || create_mode == OS_FILE_OPEN_RETRY) {
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
		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) {
1276 1277
		/* If specified, use asynchronous (overlapped) io and no
		buffering of writes in the OS */
1278 1279 1280 1281 1282
		attributes = 0;
#ifdef WIN_ASYNC_IO
		if (os_aio_use_native_aio) {
			attributes = attributes | FILE_FLAG_OVERLAPPED;
		}
1283
#endif
1284
#ifdef UNIV_NON_BUFFERED_IO
1285
		if (type == OS_LOG_FILE && srv_flush_log_at_trx_commit == 2) {
1286 1287 1288
			/* 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 */
unknown's avatar
unknown committed
1289 1290
		} else if (srv_win_file_flush_method
			   == SRV_WIN_IO_UNBUFFERED) {
1291
			attributes = attributes | FILE_FLAG_NO_BUFFERING;
unknown's avatar
unknown committed
1292
		}
1293 1294
#endif
	} else if (purpose == OS_FILE_NORMAL) {
1295
		attributes = 0;
1296
#ifdef UNIV_NON_BUFFERED_IO
unknown's avatar
unknown committed
1297
		if (type == OS_LOG_FILE && srv_flush_log_at_trx_commit == 2) {
1298 1299 1300
			/* 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 */
unknown's avatar
unknown committed
1301 1302
		} else if (srv_win_file_flush_method
			   == SRV_WIN_IO_UNBUFFERED) {
1303
			attributes = attributes | FILE_FLAG_NO_BUFFERING;
unknown's avatar
unknown committed
1304
		}
1305 1306 1307 1308 1309 1310
#endif
	} else {
		attributes = 0;
		ut_error;
	}

unknown's avatar
unknown committed
1311
	file = CreateFile((LPCTSTR) name,
unknown's avatar
unknown committed
1312
			  GENERIC_READ | GENERIC_WRITE, /* read and write
1313
							access */
unknown's avatar
unknown committed
1314
			  share_mode,	/* File can be read also by other
unknown's avatar
unknown committed
1315 1316 1317 1318 1319 1320
					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
unknown's avatar
unknown committed
1321
					database corruption! When opening
unknown's avatar
unknown committed
1322
					raw disk partitions, Microsoft manuals
unknown's avatar
unknown committed
1323 1324
					say that we must give also the write
					permission. */
unknown's avatar
unknown committed
1325 1326 1327 1328
			  NULL,	/* default security attributes */
			  create_flag,
			  attributes,
			  NULL);	/* no template file */
1329 1330 1331 1332

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

1333
		retry = os_file_handle_error(name,
unknown's avatar
unknown committed
1334 1335
					     create_mode == OS_FILE_CREATE ?
					     "create" : "open");
1336 1337
		if (retry) {
			goto try_again;
1338 1339 1340 1341 1342 1343
		}
	} else {
		*success = TRUE;
	}

	return(file);
1344
#else /* __WIN__ */
1345 1346 1347
	os_file_t	file;
	int		create_flag;
	ibool		retry;
1348 1349 1350
	const char*	mode_str	= NULL;
	const char*	type_str	= NULL;
	const char*	purpose_str	= NULL;
1351 1352

try_again:
1353 1354
	ut_a(name);

1355
	if (create_mode == OS_FILE_OPEN || create_mode == OS_FILE_OPEN_RAW
unknown's avatar
unknown committed
1356
	    || create_mode == OS_FILE_OPEN_RETRY) {
1357
		mode_str = "OPEN";
1358 1359
		create_flag = O_RDWR;
	} else if (create_mode == OS_FILE_CREATE) {
1360
		mode_str = "CREATE";
1361 1362
		create_flag = O_RDWR | O_CREAT | O_EXCL;
	} else if (create_mode == OS_FILE_OVERWRITE) {
1363
		mode_str = "OVERWRITE";
1364 1365 1366 1367 1368 1369
		create_flag = O_RDWR | O_CREAT | O_TRUNC;
	} else {
		create_flag = 0;
		ut_error;
	}

1370 1371 1372 1373 1374
	if (type == OS_LOG_FILE) {
		type_str = "LOG";
	} else if (type == OS_DATA_FILE) {
		type_str = "DATA";
	} else {
1375
		ut_error;
1376
	}
1377

1378 1379 1380 1381 1382
	if (purpose == OS_FILE_AIO) {
		purpose_str = "AIO";
	} else if (purpose == OS_FILE_NORMAL) {
		purpose_str = "NORMAL";
	} else {
1383
		ut_error;
1384
	}
1385

unknown's avatar
unknown committed
1386 1387 1388 1389
#if 0
	fprintf(stderr, "Opening file %s, mode %s, type %s, purpose %s\n",
		name, mode_str, type_str, purpose_str);
#endif
1390
#ifdef O_SYNC
1391
	/* We let O_SYNC only affect log files; note that we map O_DSYNC to
1392 1393 1394
	O_SYNC because the datasync options seemed to corrupt files in 2001
	in both Linux and Solaris */
	if (type == OS_LOG_FILE
unknown's avatar
unknown committed
1395
	    && srv_unix_file_flush_method == SRV_UNIX_O_DSYNC) {
1396

unknown's avatar
unknown committed
1397 1398 1399
# if 0
		fprintf(stderr, "Using O_SYNC for file %s\n", name);
# endif
1400

1401
		create_flag = create_flag | O_SYNC;
1402
	}
unknown's avatar
unknown committed
1403
#endif /* O_SYNC */
unknown's avatar
unknown committed
1404 1405

	file = open(name, create_flag, os_innodb_umask);
1406

1407 1408 1409
	if (file == -1) {
		*success = FALSE;

1410
		retry = os_file_handle_error(name,
unknown's avatar
unknown committed
1411 1412
					     create_mode == OS_FILE_CREATE ?
					     "create" : "open");
1413 1414
		if (retry) {
			goto try_again;
unknown's avatar
unknown committed
1415 1416
		} else {
			return(file /* -1 */);
1417
		}
unknown's avatar
unknown committed
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
	}
	/* else */

	*success = TRUE;

	/* We disable OS caching (O_DIRECT) only on data files */
	if (type != OS_LOG_FILE
	    && srv_unix_file_flush_method == SRV_UNIX_O_DIRECT) {
		
		os_file_set_nocache(file, name, mode_str);
	}

1430
#ifdef USE_FILE_LOCK
unknown's avatar
unknown committed
1431 1432
	if (create_mode != OS_FILE_OPEN_RAW && os_file_lock(file, name)) {

1433 1434 1435
		if (create_mode == OS_FILE_OPEN_RETRY) {
			int i;
			ut_print_timestamp(stderr);
unknown's avatar
unknown committed
1436 1437 1438
			fputs("  InnoDB: Retrying to lock"
			      " the first data file\n",
			      stderr);
1439 1440 1441 1442 1443 1444 1445 1446 1447
			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",
unknown's avatar
unknown committed
1448
			      stderr);
1449
		}
unknown's avatar
unknown committed
1450 1451

		*success = FALSE;
1452
		close(file);
1453
		file = -1;
1454
	}
unknown's avatar
unknown committed
1455
#endif /* USE_FILE_LOCK */
1456

1457
	return(file);
1458
#endif /* __WIN__ */
1459 1460
}

unknown's avatar
unknown committed
1461 1462 1463 1464 1465 1466
/***************************************************************************
Deletes a file if it exists. The file has to be closed before calling this. */

ibool
os_file_delete_if_exists(
/*=====================*/
1467 1468
				/* out: TRUE if success */
	const char*	name)	/* in: file path as a null-terminated string */
unknown's avatar
unknown committed
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
{
#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);
	}

unknown's avatar
unknown committed
1483
	if (GetLastError() == ERROR_FILE_NOT_FOUND) {
unknown's avatar
unknown committed
1484 1485 1486 1487 1488 1489 1490 1491 1492
		/* the file does not exist, this not an error */

		return(TRUE);
	}

	count++;

	if (count > 100 && 0 == (count % 10)) {
		fprintf(stderr,
unknown's avatar
unknown committed
1493 1494 1495
			"InnoDB: Warning: cannot delete file %s\n"
			"InnoDB: Are you running ibbackup"
			" to back up the file?\n", name);
1496

unknown's avatar
unknown committed
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
		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) {
unknown's avatar
unknown committed
1514
		os_file_handle_error_no_exit(name, "delete");
unknown's avatar
unknown committed
1515 1516 1517 1518 1519 1520 1521 1522

		return(FALSE);
	}

	return(TRUE);
#endif
}

unknown's avatar
unknown committed
1523 1524 1525 1526 1527 1528
/***************************************************************************
Deletes a file. The file has to be closed before calling this. */

ibool
os_file_delete(
/*===========*/
1529 1530
				/* out: TRUE if success */
	const char*	name)	/* in: file path as a null-terminated string */
unknown's avatar
unknown committed
1531 1532
{
#ifdef __WIN__
unknown's avatar
unknown committed
1533
	BOOL	ret;
unknown's avatar
unknown committed
1534 1535 1536 1537
	ulint	count	= 0;
loop:
	/* In Windows, deleting an .ibd file may fail if ibbackup is copying
	it */
unknown's avatar
unknown committed
1538 1539 1540 1541 1542 1543 1544

	ret = DeleteFile((LPCTSTR)name);

	if (ret) {
		return(TRUE);
	}

unknown's avatar
unknown committed
1545
	if (GetLastError() == ERROR_FILE_NOT_FOUND) {
unknown's avatar
unknown committed
1546 1547
		/* If the file does not exist, we classify this as a 'mild'
		error and return */
unknown's avatar
unknown committed
1548

unknown's avatar
unknown committed
1549 1550 1551 1552 1553 1554 1555
		return(FALSE);
	}

	count++;

	if (count > 100 && 0 == (count % 10)) {
		fprintf(stderr,
unknown's avatar
unknown committed
1556 1557 1558
			"InnoDB: Warning: cannot delete file %s\n"
			"InnoDB: Are you running ibbackup"
			" to back up the file?\n", name);
1559

unknown's avatar
unknown committed
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
		os_file_get_last_error(TRUE); /* print error information */
	}

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

	if (count > 2000) {

		return(FALSE);
	}

	goto loop;
unknown's avatar
unknown committed
1571
#else
unknown's avatar
unknown committed
1572
	int	ret;
unknown's avatar
unknown committed
1573 1574 1575 1576

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

	if (ret != 0) {
unknown's avatar
unknown committed
1577
		os_file_handle_error_no_exit(name, "delete");
unknown's avatar
unknown committed
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593

		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 */
1594
	const char*	oldpath,/* in: old file path as a null-terminated
unknown's avatar
unknown committed
1595
				string */
1596
	const char*	newpath)/* in: new file path */
unknown's avatar
unknown committed
1597 1598
{
#ifdef __WIN__
unknown's avatar
unknown committed
1599
	BOOL	ret;
unknown's avatar
unknown committed
1600 1601 1602 1603 1604 1605 1606

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

	if (ret) {
		return(TRUE);
	}

unknown's avatar
unknown committed
1607
	os_file_handle_error_no_exit(oldpath, "rename");
unknown's avatar
unknown committed
1608 1609 1610

	return(FALSE);
#else
unknown's avatar
unknown committed
1611
	int	ret;
unknown's avatar
unknown committed
1612 1613 1614 1615

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

	if (ret != 0) {
unknown's avatar
unknown committed
1616
		os_file_handle_error_no_exit(oldpath, "rename");
unknown's avatar
unknown committed
1617 1618 1619 1620 1621 1622 1623 1624

		return(FALSE);
	}

	return(TRUE);
#endif
}

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
/***************************************************************************
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);
	}

1646
	os_file_handle_error(NULL, "close");
unknown's avatar
unknown committed
1647

1648 1649 1650 1651 1652 1653 1654
	return(FALSE);
#else
	int	ret;

	ret = close(file);

	if (ret == -1) {
1655
		os_file_handle_error(NULL, "close");
unknown's avatar
unknown committed
1656

1657 1658 1659 1660 1661 1662 1663
		return(FALSE);
	}

	return(TRUE);
#endif
}

unknown's avatar
unknown committed
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
/***************************************************************************
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
}

1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
/***************************************************************************
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
unknown's avatar
Merge  
unknown committed
1726 1727 1728 1729
	off_t	offs;

	offs = lseek(file, 0, SEEK_END);

unknown's avatar
unknown committed
1730 1731 1732 1733
	if (offs == ((off_t)-1)) {

		return(FALSE);
	}
1734

unknown's avatar
Merge  
unknown committed
1735
	if (sizeof(off_t) > 4) {
1736
		*size = (ulint)(offs & 0xFFFFFFFFUL);
1737
		*size_high = (ulint)(offs >> 32);
unknown's avatar
Merge  
unknown committed
1738 1739 1740 1741
	} else {
		*size = (ulint) offs;
		*size_high = 0;
	}
1742 1743

	return(TRUE);
1744 1745 1746
#endif
}

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
/***************************************************************************
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);
}

1770
/***************************************************************************
1771
Write the specified number of zeros to a newly created file. */
1772 1773 1774 1775 1776

ibool
os_file_set_size(
/*=============*/
				/* out: TRUE if success */
1777
	const char*	name,	/* in: name of the file or path as a
1778 1779 1780 1781 1782 1783
				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 */
{
1784 1785
	ib_longlong	current_size;
	ib_longlong	desired_size;
unknown's avatar
Merge  
unknown committed
1786
	ibool		ret;
1787 1788
	byte*		buf;
	byte*		buf2;
1789
	ulint		buf_size;
unknown's avatar
Merge  
unknown committed
1790

1791
	ut_a(size == (size & 0xFFFFFFFF));
1792

1793 1794
	current_size = 0;
	desired_size = (ib_longlong)size + (((ib_longlong)size_high) << 32);
1795

1796
	/* Write up to 1 megabyte at a time. */
unknown's avatar
unknown committed
1797
	buf_size = ut_min(64, (ulint) (desired_size / UNIV_PAGE_SIZE))
unknown's avatar
unknown committed
1798
		* UNIV_PAGE_SIZE;
1799
	buf2 = ut_malloc(buf_size + UNIV_PAGE_SIZE);
unknown's avatar
unknown committed
1800 1801 1802

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

	/* Write buffer full of zeros */
1805
	memset(buf, 0, buf_size);
1806

1807
	if (desired_size >= (ib_longlong)(100 * 1024 * 1024)) {
1808

unknown's avatar
unknown committed
1809 1810 1811
		fprintf(stderr, "InnoDB: Progress in MB:");
	}

1812
	while (current_size < desired_size) {
unknown's avatar
unknown committed
1813 1814 1815 1816 1817 1818 1819 1820
		ulint	n_bytes;

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

1821
		ret = os_file_write(name, file, buf,
unknown's avatar
unknown committed
1822 1823 1824
				    (ulint)(current_size & 0xFFFFFFFF),
				    (ulint)(current_size >> 32),
				    n_bytes);
1825
		if (!ret) {
unknown's avatar
unknown committed
1826
			ut_free(buf2);
1827 1828 1829
			goto error_handling;
		}

unknown's avatar
unknown committed
1830
		/* Print about progress for each 100 MB written */
unknown's avatar
unknown committed
1831
		if ((ib_longlong) (current_size + n_bytes) / (ib_longlong)(100 * 1024 * 1024)
unknown's avatar
unknown committed
1832
		    != current_size / (ib_longlong)(100 * 1024 * 1024)) {
unknown's avatar
unknown committed
1833

1834
			fprintf(stderr, " %lu00",
1835
				(ulong) ((current_size + n_bytes)
unknown's avatar
unknown committed
1836
					 / (ib_longlong)(100 * 1024 * 1024)));
unknown's avatar
unknown committed
1837
		}
1838 1839

		current_size += n_bytes;
1840 1841
	}

1842
	if (desired_size >= (ib_longlong)(100 * 1024 * 1024)) {
1843

unknown's avatar
unknown committed
1844 1845 1846
		fprintf(stderr, "\n");
	}

unknown's avatar
unknown committed
1847
	ut_free(buf2);
1848 1849 1850 1851

	ret = os_file_flush(file);

	if (ret) {
1852
		return(TRUE);
1853 1854 1855
	}

error_handling:
1856
	return(FALSE);
1857 1858 1859
}

/***************************************************************************
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
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__ */
}

unknown's avatar
unknown committed
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
#ifndef __WIN__
/***************************************************************************
Wrapper to fsync(2) that retries the call on some errors.
Returns the value 0 if successful; otherwise the value -1 is returned and
the global variable errno is set to indicate the error. */

static
int
os_file_fsync(
/*==========*/
				/* out: 0 if success, -1 otherwise */
	os_file_t	file)	/* in: handle to a file */
{
	int	ret;
	int	failures;
	ibool	retry;

	failures = 0;

	do {
		ret = fsync(file);

		os_n_fsyncs++;

		if (ret == -1 && errno == ENOLCK) {

			if (failures % 100 == 0) {

				ut_print_timestamp(stderr);
				fprintf(stderr,
					"  InnoDB: fsync(): "
					"No locks available; retrying\n");
			}

			os_thread_sleep(200000 /* 0.2 sec */);

			failures++;

			retry = TRUE;
		} else {

			retry = FALSE;
		}
	} while (retry);

	return(ret);
}
#endif /* !__WIN__ */

1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
/***************************************************************************
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);

unknown's avatar
unknown committed
1939 1940
	os_n_fsyncs++;

1941 1942 1943 1944 1945 1946
	ret = FlushFileBuffers(file);

	if (ret) {
		return(TRUE);
	}

unknown's avatar
unknown committed
1947 1948 1949 1950 1951
	/* 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()
unknown's avatar
unknown committed
1952
	    == ERROR_INVALID_FUNCTION) {
1953
		return(TRUE);
unknown's avatar
unknown committed
1954 1955
	}

1956
	os_file_handle_error(NULL, "flush");
1957

unknown's avatar
unknown committed
1958 1959
	/* It is a fatal error if a file flush does not succeed, because then
	the database can get corrupt on disk */
1960
	ut_error;
unknown's avatar
unknown committed
1961

1962 1963 1964
	return(FALSE);
#else
	int	ret;
1965

1966 1967 1968 1969 1970 1971 1972
#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
unknown's avatar
unknown committed
1973 1974 1975 1976 1977
	/* 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. */

1978 1979
	if (!srv_have_fullfsync) {
		/* If we are not on an operating system that supports this,
1980
		then fall back to a plain fsync. */
unknown's avatar
unknown committed
1981

unknown's avatar
unknown committed
1982
		ret = os_file_fsync(file);
1983 1984 1985 1986 1987
	} else {
		ret = fcntl(file, F_FULLFSYNC, NULL);

		if (ret) {
			/* If we are not on a file system that supports this,
1988
			then fall back to a plain fsync. */
unknown's avatar
unknown committed
1989
			ret = os_file_fsync(file);
1990
		}
unknown's avatar
unknown committed
1991
	}
1992
#else
unknown's avatar
unknown committed
1993
	ret = os_file_fsync(file);
1994
#endif
1995

1996 1997 1998
	if (ret == 0) {
		return(TRUE);
	}
1999

unknown's avatar
unknown committed
2000
	/* Since Linux returns EINVAL if the 'file' is actually a raw device,
unknown's avatar
unknown committed
2001 2002 2003
	we choose to ignore that error if we are using raw disks */

	if (srv_start_raw_disk_in_use && errno == EINVAL) {
unknown's avatar
unknown committed
2004

2005
		return(TRUE);
unknown's avatar
unknown committed
2006 2007
	}

unknown's avatar
unknown committed
2008
	ut_print_timestamp(stderr);
2009

2010
	fprintf(stderr,
unknown's avatar
unknown committed
2011
		"  InnoDB: Error: the OS said file flush did not succeed\n");
2012

2013
	os_file_handle_error(NULL, "flush");
2014

unknown's avatar
unknown committed
2015 2016
	/* It is a fatal error if a file flush does not succeed, because then
	the database can get corrupt on disk */
2017
	ut_error;
unknown's avatar
unknown committed
2018

2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
	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 */
2033
	ulint		n,	/* in: number of bytes to read */
unknown's avatar
Merge  
unknown committed
2034 2035 2036 2037
	ulint		offset,	/* in: least significant 32 bits of file
				offset from where to read */
	ulint		offset_high) /* in: most significant 32 bits of
				offset */
2038
{
2039
	off_t	offs;
unknown's avatar
unknown committed
2040
	ssize_t	n_bytes;
unknown's avatar
Merge  
unknown committed
2041

unknown's avatar
unknown committed
2042
	ut_a((offset & 0xFFFFFFFFUL) == offset);
2043 2044

	/* If off_t is > 4 bytes in size, then we assume we can pass a
unknown's avatar
Merge  
unknown committed
2045 2046
	64-bit address */

2047 2048 2049 2050 2051
	if (sizeof(off_t) > 4) {
		offs = (off_t)offset + (((off_t)offset_high) << 32);

	} else {
		offs = (off_t)offset;
unknown's avatar
Merge  
unknown committed
2052

2053 2054
		if (offset_high > 0) {
			fprintf(stderr,
unknown's avatar
unknown committed
2055
				"InnoDB: Error: file read at offset > 4 GB\n");
unknown's avatar
Merge  
unknown committed
2056
		}
2057
	}
2058

2059 2060
	os_n_file_reads++;

unknown's avatar
unknown committed
2061
#if defined(HAVE_PREAD) && !defined(HAVE_BROKEN_PREAD)
2062
	os_mutex_enter(os_file_count_mutex);
unknown's avatar
unknown committed
2063
	os_file_n_pending_preads++;
2064 2065
	os_n_pending_reads++;
	os_mutex_exit(os_file_count_mutex);
unknown's avatar
unknown committed
2066

2067
	n_bytes = pread(file, buf, (ssize_t)n, offs);
unknown's avatar
unknown committed
2068

2069
	os_mutex_enter(os_file_count_mutex);
unknown's avatar
unknown committed
2070
	os_file_n_pending_preads--;
2071 2072
	os_n_pending_reads--;
	os_mutex_exit(os_file_count_mutex);
unknown's avatar
unknown committed
2073 2074

	return(n_bytes);
2075
#else
unknown's avatar
unknown committed
2076
	{
unknown's avatar
unknown committed
2077 2078 2079
		off_t	ret_offset;
		ssize_t	ret;
		ulint	i;
2080

unknown's avatar
unknown committed
2081 2082 2083
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_reads++;
		os_mutex_exit(os_file_count_mutex);
2084

unknown's avatar
unknown committed
2085 2086
		/* Protect the seek / read operation with a mutex */
		i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
2087

unknown's avatar
unknown committed
2088
		os_mutex_enter(os_file_seek_mutexes[i]);
2089

unknown's avatar
unknown committed
2090
		ret_offset = lseek(file, offs, SEEK_SET);
2091

unknown's avatar
unknown committed
2092 2093 2094 2095 2096
		if (ret_offset < 0) {
			ret = -1;
		} else {
			ret = read(file, buf, (ssize_t)n);
		}
2097

unknown's avatar
unknown committed
2098
		os_mutex_exit(os_file_seek_mutexes[i]);
2099

unknown's avatar
unknown committed
2100 2101 2102
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_reads--;
		os_mutex_exit(os_file_count_mutex);
2103

unknown's avatar
unknown committed
2104
		return(ret);
unknown's avatar
unknown committed
2105
	}
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
#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 */
2117
	const void*	buf,	/* in: buffer from where to write */
2118
	ulint		n,	/* in: number of bytes to write */
unknown's avatar
Merge  
unknown committed
2119 2120 2121 2122
	ulint		offset,	/* in: least significant 32 bits of file
				offset where to write */
	ulint		offset_high) /* in: most significant 32 bits of
				offset */
2123
{
2124
	ssize_t	ret;
2125
	off_t	offs;
unknown's avatar
Merge  
unknown committed
2126

unknown's avatar
unknown committed
2127
	ut_a((offset & 0xFFFFFFFFUL) == offset);
unknown's avatar
Merge  
unknown committed
2128

2129
	/* If off_t is > 4 bytes in size, then we assume we can pass a
unknown's avatar
Merge  
unknown committed
2130 2131
	64-bit address */

2132 2133 2134 2135
	if (sizeof(off_t) > 4) {
		offs = (off_t)offset + (((off_t)offset_high) << 32);
	} else {
		offs = (off_t)offset;
unknown's avatar
Merge  
unknown committed
2136

2137 2138
		if (offset_high > 0) {
			fprintf(stderr,
unknown's avatar
unknown committed
2139 2140
				"InnoDB: Error: file write"
				" at offset > 4 GB\n");
unknown's avatar
Merge  
unknown committed
2141
		}
2142
	}
2143

2144 2145
	os_n_file_writes++;

unknown's avatar
unknown committed
2146
#if defined(HAVE_PWRITE) && !defined(HAVE_BROKEN_PREAD)
2147
	os_mutex_enter(os_file_count_mutex);
unknown's avatar
unknown committed
2148
	os_file_n_pending_pwrites++;
2149 2150
	os_n_pending_writes++;
	os_mutex_exit(os_file_count_mutex);
unknown's avatar
unknown committed
2151

unknown's avatar
unknown committed
2152
	ret = pwrite(file, buf, (ssize_t)n, offs);
2153

2154
	os_mutex_enter(os_file_count_mutex);
unknown's avatar
unknown committed
2155
	os_file_n_pending_pwrites--;
2156 2157
	os_n_pending_writes--;
	os_mutex_exit(os_file_count_mutex);
unknown's avatar
unknown committed
2158

2159
# ifdef UNIV_DO_FLUSH
2160
	if (srv_unix_file_flush_method != SRV_UNIX_LITTLESYNC
unknown's avatar
unknown committed
2161 2162
	    && srv_unix_file_flush_method != SRV_UNIX_NOSYNC
	    && !os_do_not_call_flush_at_each_write) {
2163

2164 2165 2166 2167 2168
		/* 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));
2169
	}
2170
# endif /* UNIV_DO_FLUSH */
2171

2172
	return(ret);
2173
#else
unknown's avatar
unknown committed
2174
	{
unknown's avatar
unknown committed
2175 2176
		off_t	ret_offset;
		ulint	i;
2177

unknown's avatar
unknown committed
2178 2179 2180
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_writes++;
		os_mutex_exit(os_file_count_mutex);
2181

unknown's avatar
unknown committed
2182 2183
		/* Protect the seek / write operation with a mutex */
		i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
2184

unknown's avatar
unknown committed
2185
		os_mutex_enter(os_file_seek_mutexes[i]);
2186

unknown's avatar
unknown committed
2187
		ret_offset = lseek(file, offs, SEEK_SET);
2188

unknown's avatar
unknown committed
2189 2190
		if (ret_offset < 0) {
			ret = -1;
2191

unknown's avatar
unknown committed
2192 2193
			goto func_exit;
		}
2194

unknown's avatar
unknown committed
2195
		ret = write(file, buf, (ssize_t)n);
2196

2197
# ifdef UNIV_DO_FLUSH
unknown's avatar
unknown committed
2198 2199 2200
		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) {
2201

unknown's avatar
unknown committed
2202 2203 2204
			/* Always do fsync to reduce the probability that when
			the OS crashes, a database page is only partially
			physically written to disk. */
2205

unknown's avatar
unknown committed
2206 2207
			ut_a(TRUE == os_file_flush(file));
		}
2208
# endif /* UNIV_DO_FLUSH */
2209

2210
func_exit:
unknown's avatar
unknown committed
2211
		os_mutex_exit(os_file_seek_mutexes[i]);
2212

unknown's avatar
unknown committed
2213 2214 2215
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_writes--;
		os_mutex_exit(os_file_count_mutex);
2216

unknown's avatar
unknown committed
2217
		return(ret);
unknown's avatar
unknown committed
2218
	}
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
#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 */
2237
	ulint		n)	/* in: number of bytes to read */
2238 2239 2240 2241 2242 2243 2244 2245 2246
{
#ifdef __WIN__
	BOOL		ret;
	DWORD		len;
	DWORD		ret2;
	DWORD		low;
	DWORD		high;
	ibool		retry;
	ulint		i;
2247

unknown's avatar
unknown committed
2248
	ut_a((offset & 0xFFFFFFFFUL) == offset);
unknown's avatar
Merge  
unknown committed
2249

2250
	os_n_file_reads++;
unknown's avatar
unknown committed
2251
	os_bytes_read_since_printout += n;
2252

2253
try_again:
2254 2255 2256 2257
	ut_ad(file);
	ut_ad(buf);
	ut_ad(n > 0);

2258 2259
	low = (DWORD) offset;
	high = (DWORD) offset_high;
2260

2261 2262 2263 2264
	os_mutex_enter(os_file_count_mutex);
	os_n_pending_reads++;
	os_mutex_exit(os_file_count_mutex);

2265 2266
	/* Protect the seek / read operation with a mutex */
	i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
2267

2268 2269 2270 2271 2272 2273 2274 2275
	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]);

2276 2277 2278 2279
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_reads--;
		os_mutex_exit(os_file_count_mutex);

2280
		goto error_handling;
2281
	}
2282

2283
	ret = ReadFile(file, buf, (DWORD) n, &len, NULL);
2284

2285
	os_mutex_exit(os_file_seek_mutexes[i]);
2286 2287 2288 2289 2290

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

2291 2292
	if (ret && len == n) {
		return(TRUE);
2293
	}
2294 2295 2296
#else
	ibool	retry;
	ssize_t	ret;
unknown's avatar
Merge  
unknown committed
2297

unknown's avatar
unknown committed
2298 2299
	os_bytes_read_since_printout += n;

2300
try_again:
unknown's avatar
Merge  
unknown committed
2301
	ret = os_file_pread(file, buf, n, offset, offset_high);
2302

2303
	if ((ulint)ret == n) {
2304 2305 2306

		return(TRUE);
	}
unknown's avatar
unknown committed
2307 2308

	fprintf(stderr,
unknown's avatar
unknown committed
2309 2310 2311 2312
		"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);
2313
#endif
unknown's avatar
unknown committed
2314
#ifdef __WIN__
2315
error_handling:
unknown's avatar
unknown committed
2316
#endif
2317
	retry = os_file_handle_error(NULL, "read");
2318 2319 2320 2321

	if (retry) {
		goto try_again;
	}
2322

unknown's avatar
unknown committed
2323
	fprintf(stderr,
unknown's avatar
unknown committed
2324 2325
		"InnoDB: Fatal error: cannot read from file."
		" OS error number %lu.\n",
unknown's avatar
unknown committed
2326
#ifdef __WIN__
2327
		(ulong) GetLastError()
unknown's avatar
unknown committed
2328
#else
2329
		(ulong) errno
unknown's avatar
unknown committed
2330 2331 2332 2333
#endif
		);
	fflush(stderr);

2334 2335 2336 2337 2338
	ut_error;

	return(FALSE);
}

unknown's avatar
unknown committed
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
/***********************************************************************
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 */
2354
	ulint		n)	/* in: number of bytes to read */
unknown's avatar
unknown committed
2355 2356 2357 2358 2359 2360 2361 2362 2363
{
#ifdef __WIN__
	BOOL		ret;
	DWORD		len;
	DWORD		ret2;
	DWORD		low;
	DWORD		high;
	ibool		retry;
	ulint		i;
2364

unknown's avatar
unknown committed
2365 2366 2367 2368 2369
	ut_a((offset & 0xFFFFFFFFUL) == offset);

	os_n_file_reads++;
	os_bytes_read_since_printout += n;

2370
try_again:
unknown's avatar
unknown committed
2371 2372 2373 2374
	ut_ad(file);
	ut_ad(buf);
	ut_ad(n > 0);

2375 2376
	low = (DWORD) offset;
	high = (DWORD) offset_high;
unknown's avatar
unknown committed
2377

2378 2379 2380 2381
	os_mutex_enter(os_file_count_mutex);
	os_n_pending_reads++;
	os_mutex_exit(os_file_count_mutex);

unknown's avatar
unknown committed
2382 2383
	/* Protect the seek / read operation with a mutex */
	i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
2384

unknown's avatar
unknown committed
2385 2386 2387 2388 2389 2390 2391 2392
	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]);

2393 2394 2395 2396
		os_mutex_enter(os_file_count_mutex);
		os_n_pending_reads--;
		os_mutex_exit(os_file_count_mutex);

unknown's avatar
unknown committed
2397
		goto error_handling;
2398 2399
	}

2400
	ret = ReadFile(file, buf, (DWORD) n, &len, NULL);
unknown's avatar
unknown committed
2401 2402

	os_mutex_exit(os_file_seek_mutexes[i]);
2403 2404 2405 2406 2407

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

unknown's avatar
unknown committed
2408 2409
	if (ret && len == n) {
		return(TRUE);
2410
	}
unknown's avatar
unknown committed
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
#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);
	}
2424
#endif
unknown's avatar
unknown committed
2425 2426 2427
#ifdef __WIN__
error_handling:
#endif
2428
	retry = os_file_handle_error_no_exit(NULL, "read");
unknown's avatar
unknown committed
2429 2430 2431 2432

	if (retry) {
		goto try_again;
	}
2433

unknown's avatar
unknown committed
2434 2435 2436
	return(FALSE);
}

2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
/***********************************************************************
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;
	}
2454

2455 2456 2457 2458 2459
	rewind(file);
	flen = fread(str, 1, size - 1, file);
	str[flen] = '\0';
}

2460 2461 2462 2463 2464 2465 2466 2467
/***********************************************************************
Requests a synchronous write operation. */

ibool
os_file_write(
/*==========*/
				/* out: TRUE if request was
				successful, FALSE if fail */
2468
	const char*	name,	/* in: name of the file or path as a
2469 2470
				null-terminated string */
	os_file_t	file,	/* in: handle to a file */
2471
	const void*	buf,	/* in: buffer from which to write */
2472 2473 2474 2475
	ulint		offset,	/* in: least significant 32 bits of file
				offset where to write */
	ulint		offset_high, /* in: most significant 32 bits of
				offset */
2476
	ulint		n)	/* in: number of bytes to write */
2477 2478 2479 2480 2481 2482 2483 2484
{
#ifdef __WIN__
	BOOL		ret;
	DWORD		len;
	DWORD		ret2;
	DWORD		low;
	DWORD		high;
	ulint		i;
unknown's avatar
unknown committed
2485
	ulint		n_retries	= 0;
2486
	ulint		err;
2487

2488
	ut_a((offset & 0xFFFFFFFF) == offset);
unknown's avatar
Merge  
unknown committed
2489

2490
	os_n_file_writes++;
unknown's avatar
unknown committed
2491

2492 2493 2494
	ut_ad(file);
	ut_ad(buf);
	ut_ad(n > 0);
unknown's avatar
unknown committed
2495
retry:
2496 2497
	low = (DWORD) offset;
	high = (DWORD) offset_high;
2498 2499 2500 2501 2502

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

2503 2504
	/* Protect the seek / write operation with a mutex */
	i = ((ulint) file) % OS_FILE_N_SEEK_MUTEXES;
2505

2506 2507 2508 2509 2510 2511 2512
	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]);
2513 2514 2515 2516 2517

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

unknown's avatar
unknown committed
2518 2519 2520
		ut_print_timestamp(stderr);

		fprintf(stderr,
unknown's avatar
unknown committed
2521 2522 2523 2524 2525 2526 2527 2528 2529
			"  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",
2530 2531
			name, (ulong) offset_high, (ulong) offset,
			(ulong) GetLastError());
unknown's avatar
unknown committed
2532 2533

		return(FALSE);
2534
	}
2535

2536
	ret = WriteFile(file, buf, (DWORD) n, &len, NULL);
2537

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

2541
# ifdef UNIV_DO_FLUSH
unknown's avatar
unknown committed
2542
	if (!os_do_not_call_flush_at_each_write) {
2543 2544
		ut_a(TRUE == os_file_flush(file));
	}
2545
# endif /* UNIV_DO_FLUSH */
2546 2547

	os_mutex_exit(os_file_seek_mutexes[i]);
2548

2549 2550 2551 2552
	os_mutex_enter(os_file_count_mutex);
	os_n_pending_writes--;
	os_mutex_exit(os_file_count_mutex);

2553
	if (ret && len == n) {
unknown's avatar
unknown committed
2554

2555 2556
		return(TRUE);
	}
unknown's avatar
unknown committed
2557

unknown's avatar
unknown committed
2558 2559 2560
	/* 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. */
2561

unknown's avatar
unknown committed
2562
	if (GetLastError() == ERROR_LOCK_VIOLATION && n_retries < 100) {
unknown's avatar
unknown committed
2563

unknown's avatar
unknown committed
2564
		os_thread_sleep(1000000);
2565

unknown's avatar
unknown committed
2566 2567 2568
		n_retries++;

		goto retry;
2569 2570
	}

unknown's avatar
unknown committed
2571
	if (!os_has_said_disk_full) {
2572

2573 2574
		err = (ulint)GetLastError();

unknown's avatar
unknown committed
2575 2576 2577
		ut_print_timestamp(stderr);

		fprintf(stderr,
unknown's avatar
unknown committed
2578 2579 2580 2581 2582 2583 2584 2585 2586
			"  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",
2587 2588
			name, (ulong) offset_high, (ulong) offset,
			(ulong) n, (ulong) len, (ulong) err);
2589 2590 2591

		if (strerror((int)err) != NULL) {
			fprintf(stderr,
unknown's avatar
unknown committed
2592 2593
				"InnoDB: Error number %lu means '%s'.\n",
				(ulong) err, strerror((int)err));
2594 2595 2596
		}

		fprintf(stderr,
unknown's avatar
unknown committed
2597 2598 2599 2600 2601
			"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");
unknown's avatar
unknown committed
2602 2603 2604 2605 2606

		os_has_said_disk_full = TRUE;
	}

	return(FALSE);
2607 2608
#else
	ssize_t	ret;
2609

unknown's avatar
Merge  
unknown committed
2610
	ret = os_file_pwrite(file, buf, n, offset, offset_high);
2611

2612
	if ((ulint)ret == n) {
unknown's avatar
unknown committed
2613

2614 2615 2616
		return(TRUE);
	}

unknown's avatar
unknown committed
2617
	if (!os_has_said_disk_full) {
2618

unknown's avatar
unknown committed
2619
		ut_print_timestamp(stderr);
2620

unknown's avatar
unknown committed
2621
		fprintf(stderr,
unknown's avatar
unknown committed
2622 2623 2624 2625 2626 2627 2628 2629 2630
			"  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",
unknown's avatar
unknown committed
2631
			name, offset_high, offset, n, (long int)ret,
unknown's avatar
unknown committed
2632
			(ulint)errno);
2633 2634
		if (strerror(errno) != NULL) {
			fprintf(stderr,
unknown's avatar
unknown committed
2635 2636
				"InnoDB: Error number %lu means '%s'.\n",
				(ulint)errno, strerror(errno));
2637 2638 2639
		}

		fprintf(stderr,
unknown's avatar
unknown committed
2640 2641 2642 2643 2644
			"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");
2645

unknown's avatar
unknown committed
2646 2647 2648
		os_has_said_disk_full = TRUE;
	}

2649
	return(FALSE);
unknown's avatar
unknown committed
2650
#endif
2651 2652
}

unknown's avatar
unknown committed
2653 2654 2655 2656 2657 2658 2659
/***********************************************************************
Check the existence and type of the given file. */

ibool
os_file_status(
/*===========*/
				/* out: TRUE if call succeeded */
2660
	const char*	path,	/* in:	pathname of the file */
unknown's avatar
unknown committed
2661 2662 2663 2664 2665 2666
	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;
2667

unknown's avatar
unknown committed
2668 2669 2670 2671 2672 2673 2674
	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 */
2675

unknown's avatar
unknown committed
2676
		os_file_handle_error_no_exit(path, "stat");
2677

unknown's avatar
unknown committed
2678 2679
		return(FALSE);
	}
2680

unknown's avatar
unknown committed
2681 2682 2683
	if (_S_IFDIR & statinfo.st_mode) {
		*type = OS_FILE_TYPE_DIR;
	} else if (_S_IFREG & statinfo.st_mode) {
2684
		*type = OS_FILE_TYPE_FILE;
unknown's avatar
unknown committed
2685
	} else {
2686
		*type = OS_FILE_TYPE_UNKNOWN;
unknown's avatar
unknown committed
2687 2688 2689
	}

	*exists = TRUE;
2690

unknown's avatar
unknown committed
2691 2692 2693 2694
	return(TRUE);
#else
	int		ret;
	struct stat	statinfo;
2695

unknown's avatar
unknown committed
2696 2697 2698 2699 2700 2701 2702
	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 */
2703

unknown's avatar
unknown committed
2704
		os_file_handle_error_no_exit(path, "stat");
2705

unknown's avatar
unknown committed
2706 2707
		return(FALSE);
	}
2708

unknown's avatar
unknown committed
2709 2710 2711
	if (S_ISDIR(statinfo.st_mode)) {
		*type = OS_FILE_TYPE_DIR;
	} else if (S_ISLNK(statinfo.st_mode)) {
2712
		*type = OS_FILE_TYPE_LINK;
unknown's avatar
unknown committed
2713
	} else if (S_ISREG(statinfo.st_mode)) {
2714
		*type = OS_FILE_TYPE_FILE;
unknown's avatar
unknown committed
2715
	} else {
2716
		*type = OS_FILE_TYPE_UNKNOWN;
unknown's avatar
unknown committed
2717 2718 2719
	}

	*exists = TRUE;
2720

unknown's avatar
unknown committed
2721 2722 2723 2724
	return(TRUE);
#endif
}

2725 2726 2727 2728 2729
/***********************************************************************
This function returns information about the specified file */

ibool
os_file_get_status(
2730
/*===============*/
unknown's avatar
unknown committed
2731 2732 2733 2734 2735
					/* 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 */
2736 2737 2738 2739
{
#ifdef __WIN__
	int		ret;
	struct _stat	statinfo;
2740

2741 2742 2743 2744 2745 2746 2747
	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 */
2748

unknown's avatar
unknown committed
2749
		os_file_handle_error_no_exit(path, "stat");
2750

2751 2752 2753 2754 2755
		return(FALSE);
	}
	if (_S_IFDIR & statinfo.st_mode) {
		stat_info->type = OS_FILE_TYPE_DIR;
	} else if (_S_IFREG & statinfo.st_mode) {
2756
		stat_info->type = OS_FILE_TYPE_FILE;
2757
	} else {
2758
		stat_info->type = OS_FILE_TYPE_UNKNOWN;
2759 2760 2761 2762 2763
	}

	stat_info->ctime = statinfo.st_ctime;
	stat_info->atime = statinfo.st_atime;
	stat_info->mtime = statinfo.st_mtime;
2764 2765
	stat_info->size	 = statinfo.st_size;

2766 2767 2768 2769
	return(TRUE);
#else
	int		ret;
	struct stat	statinfo;
2770

2771 2772 2773 2774 2775 2776 2777 2778
	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 */
2779

unknown's avatar
unknown committed
2780
		os_file_handle_error_no_exit(path, "stat");
2781

2782 2783
		return(FALSE);
	}
2784

2785 2786 2787
	if (S_ISDIR(statinfo.st_mode)) {
		stat_info->type = OS_FILE_TYPE_DIR;
	} else if (S_ISLNK(statinfo.st_mode)) {
2788
		stat_info->type = OS_FILE_TYPE_LINK;
2789
	} else if (S_ISREG(statinfo.st_mode)) {
2790
		stat_info->type = OS_FILE_TYPE_FILE;
2791
	} else {
2792
		stat_info->type = OS_FILE_TYPE_UNKNOWN;
2793 2794 2795 2796 2797
	}

	stat_info->ctime = statinfo.st_ctime;
	stat_info->atime = statinfo.st_atime;
	stat_info->mtime = statinfo.st_mtime;
2798 2799
	stat_info->size	 = statinfo.st_size;

2800 2801 2802 2803
	return(TRUE);
#endif
}

unknown's avatar
unknown committed
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
/* 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
unknown's avatar
unknown committed
2815
is the component following the final '/'.  Trailing '/' charac­
unknown's avatar
unknown committed
2816 2817 2818 2819 2820 2821 2822 2823 2824
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
2825
to free it after it is no longer needed.
unknown's avatar
unknown committed
2826 2827 2828 2829

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

2830 2831 2832 2833 2834 2835 2836
       path	      dirname	     basename
       "/usr/lib"     "/usr"	     "lib"
       "/usr/"	      "/"	     "usr"
       "usr"	      "."	     "usr"
       "/"	      "/"	     "/"
       "."	      "."	     "."
       ".."	      "."	     ".."
unknown's avatar
unknown committed
2837 2838 2839 2840 2841 2842 2843
*/

char*
os_file_dirname(
/*============*/
				/* out, own: directory component of the
				pathname */
2844
	const char*	path)	/* in: pathname */
unknown's avatar
unknown committed
2845
{
unknown's avatar
unknown committed
2846
	/* Find the offset of the last slash */
2847 2848
	const char* last_slash = strrchr(path, OS_FILE_PATH_SEPARATOR);
	if (!last_slash) {
unknown's avatar
unknown committed
2849 2850
		/* No slash in the path, return "." */

2851
		return(mem_strdup("."));
unknown's avatar
unknown committed
2852 2853
	}

unknown's avatar
unknown committed
2854
	/* Ok, there is a slash */
unknown's avatar
unknown committed
2855

2856
	if (last_slash == path) {
unknown's avatar
unknown committed
2857
		/* last slash is the first char of the path */
unknown's avatar
unknown committed
2858

2859
		return(mem_strdup("/"));
unknown's avatar
unknown committed
2860 2861
	}

unknown's avatar
unknown committed
2862 2863
	/* Non-trivial directory component */

2864
	return(mem_strdupl(path, last_slash - path));
unknown's avatar
unknown committed
2865
}
2866

unknown's avatar
unknown committed
2867 2868
/********************************************************************
Creates all missing subdirectories along the given path. */
2869

unknown's avatar
unknown committed
2870 2871 2872 2873 2874
ibool
os_file_create_subdirs_if_needed(
/*=============================*/
				/* out: TRUE if call succeeded
				   FALSE otherwise */
2875
	const char*	path)	/* in: path name */
unknown's avatar
unknown committed
2876 2877
{
	char*		subdir;
2878
	ibool		success, subdir_exists;
unknown's avatar
unknown committed
2879 2880 2881
	os_file_type_t	type;

	subdir = os_file_dirname(path);
2882
	if (strlen(subdir) == 1
unknown's avatar
unknown committed
2883
	    && (*subdir == OS_FILE_PATH_SEPARATOR || *subdir == '.')) {
unknown's avatar
unknown committed
2884
		/* subdir is root or cwd, nothing to do */
unknown's avatar
unknown committed
2885 2886
		mem_free(subdir);

unknown's avatar
unknown committed
2887 2888 2889
		return(TRUE);
	}

unknown's avatar
unknown committed
2890
	/* Test if subdir exists */
unknown's avatar
unknown committed
2891 2892 2893 2894 2895
	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) {
unknown's avatar
unknown committed
2896 2897
			mem_free(subdir);

unknown's avatar
unknown committed
2898 2899 2900 2901 2902
			return(FALSE);
		}
		success = os_file_create_directory(subdir, FALSE);
	}

unknown's avatar
unknown committed
2903 2904
	mem_free(subdir);

unknown's avatar
unknown committed
2905 2906 2907
	return(success);
}

2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929
/********************************************************************
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 */
Mikael Ronstrom's avatar
Mikael Ronstrom committed
2930 2931
	ulint	n)	/* in: maximum number of pending aio operations
				allowed */
2932 2933 2934 2935 2936 2937
{
	os_aio_array_t*	array;
	ulint		i;
	os_aio_slot_t*	slot;
#ifdef WIN_ASYNC_IO
	OVERLAPPED*	over;
2938
#endif
2939 2940 2941 2942
	ut_a(n > 0);

	array = ut_malloc(sizeof(os_aio_array_t));

2943
	array->mutex		= os_mutex_create(NULL);
2944
	array->not_full		= os_event_create(NULL);
2945 2946 2947
	array->is_empty		= os_event_create(NULL);

	os_event_set(array->is_empty);
2948 2949

	array->n_slots		= n;
2950 2951
	array->n_reserved	= 0;
	array->slots		= ut_malloc(n * sizeof(os_aio_slot_t));
2952 2953
#ifdef __WIN__
	array->native_events	= ut_malloc(n * sizeof(os_native_event_t));
2954
#endif
2955 2956 2957 2958 2959 2960
	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
2961 2962
		slot->event = os_event_create(NULL);

2963 2964
		over = &(slot->control);

2965
		over->hEvent = slot->event->handle;
2966

2967
		*((array->native_events) + i) = over->hEvent;
2968 2969
#endif
	}
2970

2971 2972 2973 2974
	return(array);
}

/****************************************************************************
unknown's avatar
unknown committed
2975
Initializes the asynchronous io system. Calls also os_io_init_simple.
Mikael Ronstrom's avatar
Mikael Ronstrom committed
2976 2977 2978 2979 2980
Creates an aio array for each of non-ibuf read, non-ibuf write, ibuf IO,
log IO, and synchronous IO. The caller must create i/o handler thread for all
but the synchronous aio array. Multiple threads can access the same array for
the non-ibuf read (prefetch) and write (flush dirty buffer pages) arrays.
Return the number of AIO handler threads. */
2981

Mikael Ronstrom's avatar
Mikael Ronstrom committed
2982
ulint
2983 2984
os_aio_init(
/*========*/
Mikael Ronstrom's avatar
Mikael Ronstrom committed
2985 2986 2987 2988
	ulint	ios_per_array,	/* in: maximum number of pending aio operations
                                 allowed per array */
	ulint	n_read_threads, /* in: number of read threads */
	ulint	n_write_threads, /* in: number of write threads */
2989 2990 2991
	ulint	n_slots_sync)	/* in: number of slots in the sync aio array */
{
	ulint	i;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
2992
	ulint   n_segments = 2 + n_read_threads + n_write_threads;
2993 2994 2995
#ifdef POSIX_ASYNC_IO
	sigset_t   sigset;
#endif
Mikael Ronstrom's avatar
Mikael Ronstrom committed
2996 2997 2998 2999
	ut_a(ios_per_array >= OS_AIO_N_PENDING_IOS_PER_THREAD);
	ut_a(n_read_threads >= 1 && n_read_threads <= 64);
	ut_a(n_write_threads >= 1 && n_write_threads <= 64);
	ut_a(n_segments < SRV_MAX_N_IO_THREADS);
3000

unknown's avatar
unknown committed
3001 3002
	os_io_init_simple();

unknown's avatar
unknown committed
3003
	for (i = 0; i < n_segments; i++) {
3004
		srv_set_io_thread_op_info(i, "not started yet");
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3005 3006 3007 3008 3009 3010 3011
		os_aio_thread_io_reads[i] = 0;
		os_aio_thread_io_writes[i] = 0;
		os_aio_thread_io_requests[i] = 0;
		os_aio_thread_buffer[i] = 0;
		os_aio_thread_buffer_size[i] = 0;
		os_aio_thread_io_wait[i] = 0;
		os_aio_thread_max_io_wait[i] = 0;
unknown's avatar
unknown committed
3012 3013
	}

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3014 3015 3016 3017 3018 3019 3020
 	os_aio_read_threads = n_read_threads;
 	os_aio_write_threads = n_write_threads;
 	os_aio_first_write_segment = os_aio_first_read_segment + os_aio_read_threads;
 
 	fprintf(stderr,
 		"InnoDB: ios_per_array %lu read threads %lu write threads %lu\n",
 		ios_per_array, os_aio_read_threads, os_aio_write_threads);
3021

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3022
	os_aio_ibuf_array = os_aio_array_create(ios_per_array);
unknown's avatar
unknown committed
3023

3024
	srv_io_thread_function[0] = "insert buffer thread";
unknown's avatar
unknown committed
3025

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3026
	os_aio_log_array = os_aio_array_create(ios_per_array);
unknown's avatar
unknown committed
3027

3028
	srv_io_thread_function[1] = "log thread";
unknown's avatar
unknown committed
3029

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3030 3031
	os_aio_read_array = os_aio_array_create(ios_per_array);
	for (i = os_aio_first_read_segment; i < os_aio_first_write_segment; i++) {
unknown's avatar
unknown committed
3032
		ut_a(i < SRV_MAX_N_IO_THREADS);
3033
		srv_io_thread_function[i] = "read thread";
unknown's avatar
unknown committed
3034 3035
	}

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3036 3037
	os_aio_write_array = os_aio_array_create(ios_per_array);
	for (i = os_aio_first_write_segment; i < n_segments; i++) {
unknown's avatar
unknown committed
3038
		ut_a(i < SRV_MAX_N_IO_THREADS);
3039
		srv_io_thread_function[i] = "write thread";
unknown's avatar
unknown committed
3040
	}
3041

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3042
	os_aio_sync_array = os_aio_array_create(n_slots_sync);
3043

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3044
	os_aio_n_segments = 2 + os_aio_read_threads + os_aio_write_threads;
3045 3046 3047 3048 3049 3050 3051 3052 3053

	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);
	}

3054 3055
	os_last_printout = time(NULL);

3056
#ifdef POSIX_ASYNC_IO
3057 3058 3059 3060
	/* 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 */
3061

3062 3063
	/* TODO: to work MySQL needs the SIGALARM signal; the following
	will not work yet! */
3064
	sigemptyset(&sigset);
3065 3066 3067 3068 3069
	sigaddset(&sigset, SIGRTMIN + 1 + 0);
	sigaddset(&sigset, SIGRTMIN + 1 + 1);
	sigaddset(&sigset, SIGRTMIN + 1 + 2);
	sigaddset(&sigset, SIGRTMIN + 1 + 3);

3070
	pthread_sigmask(SIG_BLOCK, &sigset, NULL); */
3071
#endif
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3072 3073
	return os_aio_n_segments;
}
unknown's avatar
unknown committed
3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088

#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++) {

3089
		os_event_set((array->slots + i)->event);
unknown's avatar
unknown committed
3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
	}
}
#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
3105
	/* This code wakes up all ai/o threads in Windows native aio */
unknown's avatar
unknown committed
3106 3107 3108 3109 3110 3111 3112 3113
	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++) {
3114

unknown's avatar
unknown committed
3115
		os_event_set(os_aio_segment_wait_events[i]);
3116
	}
unknown's avatar
unknown committed
3117
}
3118

3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129
/****************************************************************************
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);
}

3130
/**************************************************************************
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3131
Calculates aio array from global segment number. */
3132
static
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3133 3134
os_aio_array_t*
os_aio_get_array(
3135
/*===============================*/
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3136
	/* out: aio wait array */
3137 3138
	ulint		 global_segment)/* in: global segment number */
{
3139
	ut_a(global_segment < os_aio_n_segments);
3140 3141

	if (global_segment == 0) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3142 3143
		return os_aio_ibuf_array;
  
3144
	} else if (global_segment == 1) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3145
		return os_aio_log_array;
3146

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3147 3148
	} else if (global_segment < os_aio_first_write_segment) {
		return os_aio_read_array;
3149 3150

	} else {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3151 3152
		return os_aio_write_array;
  	}
3153 3154 3155 3156 3157
}

/***********************************************************************
Gets an integer value designating a specified aio array. This is used
to give numbers to signals in Posix aio. */
unknown's avatar
unknown committed
3158 3159

#if !defined(WIN_ASYNC_IO) && defined(POSIX_ASYNC_IO)
3160 3161 3162 3163 3164
static
ulint
os_aio_get_array_no(
/*================*/
	os_aio_array_t*	array)	/* in: aio array */
3165
{
3166
	if (array == os_aio_ibuf_array) {
3167

3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180
		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 {
3181
		ut_error;
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194

		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 */
3195
{
3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
	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 {
3208
		ut_error;
3209 3210 3211 3212

		return(NULL);
	}
}
unknown's avatar
unknown committed
3213
#endif /* if !defined(WIN_ASYNC_IO) && defined(POSIX_ASYNC_IO) */
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224

/***********************************************************************
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 */
unknown's avatar
unknown committed
3225
	fil_node_t*	message1,/* in: message to be passed along with
3226 3227 3228 3229
				the aio operation */
	void*		message2,/* in: message to be passed along with
				the aio operation */
	os_file_t	file,	/* in: file handle */
3230
	const char*	name,	/* in: name of the file or path as a
3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260
				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();
		}
3261

3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
		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;
		}
	}
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3274
	ut_a(i < array->n_slots);
3275 3276
	array->n_reserved++;

3277 3278 3279 3280
	if (array->n_reserved == 1) {
		os_event_reset(array->is_empty);
	}

3281 3282 3283
	if (array->n_reserved == array->n_slots) {
		os_event_reset(array->not_full);
	}
3284

3285
	slot->reserved = TRUE;
unknown's avatar
unknown committed
3286
	slot->reservation_time = time(NULL);
3287 3288 3289 3290 3291 3292 3293 3294 3295
	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;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3296
	slot->status = OS_AIO_NOT_ISSUED;
3297 3298

#ifdef WIN_ASYNC_IO
3299 3300 3301
	control = &(slot->control);
	control->Offset = (DWORD)offset;
	control->OffsetHigh = (DWORD)offset_high;
3302
	os_event_reset(slot->event);
3303 3304 3305 3306 3307 3308 3309

#elif defined(POSIX_ASYNC_IO)

#if (UNIV_WORD_SIZE == 8)
	offset = offset + (offset_high << 32);
#else
	ut_a(offset_high == 0);
3310
#endif
3311 3312 3313 3314 3315 3316 3317
	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;
unknown's avatar
unknown committed
3318 3319 3320 3321
	control->aio_sigevent.sigev_signo
		= SIGRTMIN + 1 + os_aio_get_array_no(array);
	/* TODO: How to choose the signal numbers? */
	/*
3322
	fprintf(stderr, "AIO signal number %lu\n",
unknown's avatar
unknown committed
3323 3324
	(ulint) control->aio_sigevent.sigev_signo);
	*/
3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346
	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);
3347

3348
	slot->reserved = FALSE;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3349
 	slot->status = OS_AIO_NOT_ISSUED;
3350 3351 3352 3353 3354 3355 3356

	array->n_reserved--;

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

3357 3358 3359 3360
	if (array->n_reserved == 0) {
		os_event_set(array->is_empty);
	}

3361
#ifdef WIN_ASYNC_IO
3362
	os_event_reset(slot->event);
3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
#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(
/*=================================*/
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3373
		os_aio_array_t* array)	/* in: aio array for which wakeup is done */
3374 3375 3376 3377 3378 3379
{
	os_aio_slot_t*	slot;
	ulint		n;
	ulint		i;

	ut_ad(!os_aio_use_native_aio);
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3380
 	n = array->n_slots;
3381

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3382
	/* Look through n slots */
3383 3384 3385 3386

	os_mutex_enter(array->mutex);

	for (i = 0; i < n; i++) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400
		slot = os_aio_array_get_nth_slot(array, i);
 
		if (slot->reserved &&
		    (slot->status == OS_AIO_NOT_ISSUED ||
		     slot->status == OS_AIO_DONE)) {
			/* Found an i/o request
			   OS_AIO_NOT_ISSUED means the read or write request has
			   * yet to be done. OS_AIO_DONE means the request has been
			   * done but it was part of a set of requests merged into
			   * one read or write call and was not the first block in
			   * the request, so the handling of the IO completion for
			   * that block has not been done. */
  			break;
  		}
3401 3402 3403 3404 3405
	}

	os_mutex_exit(array->mutex);

	if (i < n) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424
		if (array == os_aio_ibuf_array) {
			os_event_set(os_aio_segment_wait_events[0]);

		} else if (array == os_aio_log_array) {
			os_event_set(os_aio_segment_wait_events[1]);

		} else if (array == os_aio_read_array) {
			ulint	x;
			for (x = os_aio_first_read_segment; x < os_aio_first_write_segment; x++)
				os_event_set(os_aio_segment_wait_events[x]);

		} else if (array == os_aio_write_array) {
			ulint	x;
			for (x = os_aio_first_write_segment; x < os_aio_n_segments; x++)
				os_event_set(os_aio_segment_wait_events[x]);

		} else {
			ut_a(0);
		}
3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438
	}
}

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

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

		return;
3439
	}
unknown's avatar
unknown committed
3440 3441

	os_aio_recommend_sleep_for_read_threads	= FALSE;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3442 3443 3444 3445 3446
  
	os_aio_simulated_wake_handler_thread(os_aio_ibuf_array);
	os_aio_simulated_wake_handler_thread(os_aio_log_array);
	os_aio_simulated_wake_handler_thread(os_aio_read_array);
	os_aio_simulated_wake_handler_thread(os_aio_write_array);
3447 3448
}

unknown's avatar
unknown committed
3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460
/**************************************************************************
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)
/*============================================*/
{
	ulint		g;

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3461
	/* TODO(mcallaghan): provide similar function for write? */
unknown's avatar
unknown committed
3462
	os_aio_recommend_sleep_for_read_threads	= TRUE;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3463 3464 3465
  
	for (g = os_aio_first_read_segment; g < os_aio_first_write_segment; g++) {
		os_event_reset(os_aio_segment_wait_events[g]);
unknown's avatar
unknown committed
3466 3467 3468
	}
}

3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490
/***********************************************************************
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! */
3491
	const char*	name,	/* in: name of the file or path as a
3492 3493 3494 3495 3496 3497 3498 3499
				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 */
unknown's avatar
unknown committed
3500
	ulint		n,	/* in: number of bytes to read or write */
unknown's avatar
unknown committed
3501
	fil_node_t*	message1,/* in: messages for the aio handler (these
3502 3503 3504 3505 3506 3507 3508 3509
				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
unknown's avatar
unknown committed
3510
	ibool		retval;
3511
	BOOL		ret		= TRUE;
3512
	DWORD		len		= (DWORD) n;
unknown's avatar
unknown committed
3513
	struct fil_node_struct * dummy_mess1;
3514
	void*		dummy_mess2;
3515
	ulint		dummy_type;
3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529
#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);
3530

3531 3532
	if (mode == OS_AIO_SYNC
#ifdef WIN_ASYNC_IO
unknown's avatar
unknown committed
3533
	    && !os_aio_use_native_aio
3534
#endif
unknown's avatar
unknown committed
3535
	    ) {
3536 3537 3538 3539 3540 3541 3542 3543
		/* 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) {
3544
			return(os_file_read(file, buf, offset,
unknown's avatar
unknown committed
3545
					    offset_high, n));
3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561
		}

		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);
3562 3563 3564 3565
		/* Reduce probability of deadlock bugs in connection with ibuf:
		do not let the ibuf i/o handler sleep */

		wake_later = FALSE;
3566 3567 3568 3569 3570 3571 3572 3573

		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 {
3574
		array = NULL; /* Eliminate compiler warning */
3575 3576
		ut_error;
	}
3577

3578
	slot = os_aio_array_reserve_slot(type, array, message1, message2, file,
unknown's avatar
unknown committed
3579
					 name, buf, offset, offset_high, n);
3580 3581 3582
	if (type == OS_FILE_READ) {
		if (os_aio_use_native_aio) {
#ifdef WIN_ASYNC_IO
3583
			os_n_file_reads++;
unknown's avatar
unknown committed
3584
			os_bytes_read_since_printout += len;
3585

3586
			ret = ReadFile(file, buf, (DWORD)n, &len,
unknown's avatar
unknown committed
3587
				       &(slot->control));
3588 3589 3590
#elif defined(POSIX_ASYNC_IO)
			slot->control.aio_lio_opcode = LIO_READ;
			err = (ulint) aio_read(&(slot->control));
3591
			fprintf(stderr, "Starting POSIX aio read %lu\n", err);
3592 3593 3594
#endif
		} else {
			if (!wake_later) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3595
				os_aio_simulated_wake_handler_thread(array);
3596 3597 3598 3599 3600
			}
		}
	} else if (type == OS_FILE_WRITE) {
		if (os_aio_use_native_aio) {
#ifdef WIN_ASYNC_IO
3601
			os_n_file_writes++;
3602
			ret = WriteFile(file, buf, (DWORD)n, &len,
unknown's avatar
unknown committed
3603
					&(slot->control));
3604 3605 3606
#elif defined(POSIX_ASYNC_IO)
			slot->control.aio_lio_opcode = LIO_WRITE;
			err = (ulint) aio_write(&(slot->control));
3607
			fprintf(stderr, "Starting POSIX aio write %lu\n", err);
3608 3609 3610
#endif
		} else {
			if (!wake_later) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3611
				os_aio_simulated_wake_handler_thread(array);
3612 3613 3614 3615 3616 3617 3618 3619 3620
			}
		}
	} else {
		ut_error;
	}

#ifdef WIN_ASYNC_IO
	if (os_aio_use_native_aio) {
		if ((ret && len == n)
unknown's avatar
unknown committed
3621
		    || (!ret && GetLastError() == ERROR_IO_PENDING)) {
3622
			/* aio was queued successfully! */
3623 3624 3625 3626 3627 3628 3629 3630

			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,
unknown's avatar
unknown committed
3631 3632 3633 3634
							       slot->pos,
							       &dummy_mess1,
							       &dummy_mess2,
							       &dummy_type);
unknown's avatar
unknown committed
3635

3636 3637
				return(retval);
			}
3638 3639 3640 3641

			return(TRUE);
		}

3642
		err = 1; /* Fall through the next if */
3643 3644 3645 3646 3647 3648 3649 3650 3651 3652
	}
#endif
	if (err == 0) {
		/* aio was queued successfully! */

		return(TRUE);
	}

	os_aio_array_free_slot(array, slot);

3653
	retry = os_file_handle_error(name,
unknown's avatar
unknown committed
3654 3655
				     type == OS_FILE_READ
				     ? "aio read" : "aio write");
3656 3657 3658
	if (retry) {

		goto try_again;
3659
	}
3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676

	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 */
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3677
	ulint	global_segment,	/* in: the number of the segment in the aio
3678 3679 3680 3681 3682 3683 3684 3685
				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:
3686
				wait for the aio slot at this position */
unknown's avatar
unknown committed
3687
	fil_node_t**message1,	/* out: the messages passed with the aio
3688 3689 3690 3691
				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 */
3692 3693
	void**	message2,
	ulint*	type)		/* out: OS_FILE_WRITE or ..._READ */
3694 3695 3696 3697 3698 3699 3700 3701 3702
{
	os_aio_array_t*	array;
	os_aio_slot_t*	slot;
	ulint		n;
	ulint		i;
	ibool		ret_val;
	BOOL		ret;
	DWORD		len;

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3703
	if (global_segment == ULINT_UNDEFINED) {
3704 3705
		array = os_aio_sync_array;
	} else {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3706
		array = os_aio_get_array(global_segment);
3707
	}
3708

3709 3710 3711 3712 3713
	/* 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());

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3714
	n = array->n_slots;
3715 3716

	if (array == os_aio_sync_array) {
3717
		os_event_wait(os_aio_array_get_nth_slot(array, pos)->event);
3718 3719
		i = pos;
	} else {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3720 3721
		srv_set_io_thread_op_info(global_segment, "wait Windows aio");
		i = os_event_wait_multiple(n, (array->native_events));
3722 3723 3724 3725
	}

	os_mutex_enter(array->mutex);

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3726
	slot = os_aio_array_get_nth_slot(array, i);
3727 3728 3729

	ut_a(slot->reserved);

3730
	if (global_segment != ULINT_UNDEFINED) {
3731
		srv_set_io_thread_op_info(global_segment,
unknown's avatar
unknown committed
3732
					  "get windows aio return value");
unknown's avatar
unknown committed
3733 3734
	}

3735 3736 3737 3738 3739
	ret = GetOverlappedResult(slot->file, &(slot->control), &len, TRUE);

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

3740 3741
	*type = slot->type;

3742 3743
	if (ret && len == slot->len) {
		ret_val = TRUE;
3744

3745
# ifdef UNIV_DO_FLUSH
unknown's avatar
unknown committed
3746
		if (slot->type == OS_FILE_WRITE
unknown's avatar
unknown committed
3747 3748
		    && !os_do_not_call_flush_at_each_write) {
			ut_a(TRUE == os_file_flush(slot->file));
3749
		}
3750
# endif /* UNIV_DO_FLUSH */
3751
	} else {
3752
		os_file_handle_error(slot->name, "Windows aio");
3753

3754
		ret_val = FALSE;
3755
	}
3756 3757 3758 3759

	os_mutex_exit(array->mutex);

	os_aio_array_free_slot(array, slot);
3760

3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775
	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 */
unknown's avatar
unknown committed
3776
	fil_node_t**message1,	/* out: the messages passed with the aio
3777 3778 3779 3780 3781 3782 3783 3784 3785 3786
				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;
3787 3788
	sigset_t	proc_sigset;
	sigset_t	thr_sigset;
3789
	int		ret;
3790 3791 3792 3793
	int		i;
	int		sig;

	sigemptyset(&sigset);
3794 3795 3796 3797
	sigaddset(&sigset, SIGRTMIN + 1 + array_no);

	pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);

unknown's avatar
unknown committed
3798
#if 0
3799 3800 3801 3802
	sigprocmask(0, NULL, &proc_sigset);
	pthread_sigmask(0, NULL, &thr_sigset);

	for (i = 32 ; i < 40; i++) {
3803
		fprintf(stderr, "%lu : %lu %lu\n", (ulint)i,
unknown's avatar
unknown committed
3804 3805
			(ulint) sigismember(&proc_sigset, i),
			(ulint) sigismember(&thr_sigset, i));
3806
	}
unknown's avatar
unknown committed
3807
#endif
3808 3809 3810 3811 3812

	ret = sigwaitinfo(&sigset, &info);

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

3813
		ut_error;
3814

3815 3816
		return(FALSE);
	}
3817

3818
	fputs("Handling POSIX aio\n", stderr);
3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830

	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;

3831
# ifdef UNIV_DO_FLUSH
unknown's avatar
unknown committed
3832
	if (slot->type == OS_FILE_WRITE
unknown's avatar
unknown committed
3833
	    && !os_do_not_call_flush_at_each_write) {
3834 3835
		ut_a(TRUE == os_file_flush(slot->file));
	}
3836
# endif /* UNIV_DO_FLUSH */
3837

3838 3839 3840
	os_mutex_exit(array->mutex);

	os_aio_array_free_slot(array, slot);
3841

3842 3843 3844 3845
	return(TRUE);
}
#endif

unknown's avatar
unknown committed
3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859
/**************************************************************************
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;
unknown's avatar
unknown committed
3860
	     len += UNIV_PAGE_SIZE) {
unknown's avatar
unknown committed
3861 3862
		byte*	buf = combined_buf + len;

unknown's avatar
unknown committed
3863 3864 3865 3866
		if (UNIV_UNLIKELY
		    (memcmp(buf + (FIL_PAGE_LSN + 4),
			    buf + (UNIV_PAGE_SIZE
				   - FIL_PAGE_END_LSN_OLD_CHKSUM + 4), 4))) {
unknown's avatar
unknown committed
3867 3868
		    	ut_print_timestamp(stderr);
		    	fprintf(stderr,
unknown's avatar
unknown committed
3869 3870 3871 3872 3873
				"  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);
unknown's avatar
unknown committed
3874 3875
			buf_page_print(buf);
		    	fprintf(stderr,
unknown's avatar
unknown committed
3876 3877
				"InnoDB: ERROR: The page to be written"
				" seems corrupt!\n");
unknown's avatar
unknown committed
3878 3879 3880 3881
		}
	}
}

3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
/**************************************************************************
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 */
unknown's avatar
unknown committed
3895
	fil_node_t**message1,	/* out: the messages passed with the aio
3896 3897 3898 3899
				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 */
3900 3901
	void**	message2,
	ulint*	type)		/* out: OS_FILE_WRITE or ..._READ */
3902 3903 3904 3905 3906
{
	os_aio_array_t*	array;
	os_aio_slot_t*	slot;
	os_aio_slot_t*	slot2;
	os_aio_slot_t*	consecutive_ios[OS_AIO_MERGE_N_CONSECUTIVE];
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3907 3908
	os_aio_slot_t*  lowest_request;
	os_aio_slot_t*	oldest_request;
3909 3910 3911 3912
	ulint		n_consecutive;
	ulint		total_len;
	ulint		offs;
	ulint		lowest_offset;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3913
	ulint		oldest_offset;
unknown's avatar
unknown committed
3914 3915
	ulint		biggest_age;
	ulint		age;
3916
	byte*		combined_buf;
unknown's avatar
unknown committed
3917
	byte*		combined_buf2;
3918 3919 3920
	ibool		ret;
	ulint		n;
	ulint		i;
3921

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3922 3923 3924
 	double          start_usecs, stop_usecs, elapsed_usecs;
 	time_t          now;
 	array = os_aio_get_array(global_segment);	
3925

3926 3927 3928 3929
restart:
	/* NOTE! We only access constant fields in os_aio_array. Therefore
	we do not have to acquire the protecting mutex yet */

unknown's avatar
unknown committed
3930
	srv_set_io_thread_op_info(global_segment,
unknown's avatar
unknown committed
3931
				  "looking for i/o requests (a)");
3932 3933
	ut_ad(os_aio_validate());

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3934
	n = array->n_slots;
3935

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3936
	/* Look through n slots */
3937

unknown's avatar
unknown committed
3938
	if (array == os_aio_read_array
unknown's avatar
unknown committed
3939
	    && os_aio_recommend_sleep_for_read_threads) {
unknown's avatar
unknown committed
3940 3941 3942 3943 3944 3945

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

		goto recommended_sleep;
	}
3946

3947 3948
	os_mutex_enter(array->mutex);

unknown's avatar
unknown committed
3949
	srv_set_io_thread_op_info(global_segment,
unknown's avatar
unknown committed
3950
				  "looking for i/o requests (b)");
unknown's avatar
unknown committed
3951

3952 3953
	/* Check if there is a slot for which the i/o has already been
	done */
3954

3955
	for (i = 0; i < n; i++) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3956
		slot = os_aio_array_get_nth_slot(array, i);
3957

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3958
		if (slot->reserved && slot->status == OS_AIO_DONE) {
3959

unknown's avatar
unknown committed
3960 3961
			if (os_aio_print_debug) {
				fprintf(stderr,
unknown's avatar
unknown committed
3962 3963 3964
					"InnoDB: i/o for slot %lu"
					" already done, returning\n",
					(ulong) i);
unknown's avatar
unknown committed
3965 3966
			}

3967
			ret = TRUE;
3968

3969 3970 3971 3972
			goto slot_io_done;
		}
	}

unknown's avatar
unknown committed
3973
	biggest_age = 0;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3974 3975 3976
	now = time(NULL);
        oldest_request = lowest_request = NULL;
        oldest_offset = lowest_offset = ULINT_MAX;
unknown's avatar
unknown committed
3977

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3978
        /* Find the oldest request and the request with the smallest offset */
3979
	for (i = 0; i < n; i++) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3980
		slot = os_aio_array_get_nth_slot(array, i);
3981

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3982 3983
		if (slot->reserved && slot->status == OS_AIO_NOT_ISSUED) {
			age = (ulint)difftime(now, slot->reservation_time);
3984

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3985 3986 3987
			/* 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. */
unknown's avatar
unknown committed
3988
			if ((age >= 2 && age > biggest_age)
unknown's avatar
unknown committed
3989
			    || (age >= 2 && age == biggest_age
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3990
			        && slot->offset < oldest_offset)) {
unknown's avatar
unknown committed
3991

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3992
			        /* Found an i/o request */
unknown's avatar
unknown committed
3993
				biggest_age = age;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
3994 3995
				oldest_request = slot;
				oldest_offset = slot->offset;
unknown's avatar
unknown committed
3996 3997
			}

Mikael Ronstrom's avatar
Mikael Ronstrom committed
3998 3999 4000 4001 4002
			/* Look for an i/o request at the lowest offset in the array
			 * (we ignore the high 32 bits of the offset) */
			if (slot->offset < lowest_offset) {
			        /* Found an i/o request */
				lowest_request = slot;
4003

4004

unknown's avatar
unknown committed
4005 4006 4007

				lowest_offset = slot->offset;
			}
4008 4009 4010
		}
	}

Mikael Ronstrom's avatar
Mikael Ronstrom committed
4011
	if (!lowest_request && !oldest_request) {
4012 4013 4014 4015 4016 4017

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

		goto wait_for_io;
	}

Mikael Ronstrom's avatar
Mikael Ronstrom committed
4018 4019 4020 4021 4022 4023 4024 4025
        if (oldest_request) {
		slot = oldest_request;
        } else {
		slot = lowest_request;
        }
        consecutive_ios[0] = slot;
	n_consecutive = 1;
  
4026 4027
	/* Check if there are several consecutive blocks to read or write */

4028
consecutive_loop:
4029
	for (i = 0; i < n; i++) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4030
		slot2 = os_aio_array_get_nth_slot(array, i);
4031 4032

		if (slot2->reserved && slot2 != slot
unknown's avatar
unknown committed
4033 4034 4035 4036 4037
		    && 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
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4038 4039
		    && slot2->file == slot->file
		    && slot2->status == OS_AIO_NOT_ISSUED) { 
4040 4041 4042 4043 4044 4045 4046 4047

			/* Found a consecutive i/o request */

			consecutive_ios[n_consecutive] = slot2;
			n_consecutive++;

			slot = slot2;

Mikael Ronstrom's avatar
Mikael Ronstrom committed
4048 4049
			if (n_consecutive < OS_AIO_MERGE_N_CONSECUTIVE &&
 			    n_consecutive < srv_max_merged_io) {
4050

4051 4052 4053 4054 4055 4056 4057
				goto consecutive_loop;
			} else {
				break;
			}
		}
	}

unknown's avatar
unknown committed
4058 4059
	srv_set_io_thread_op_info(global_segment, "consecutive i/o requests");

4060 4061 4062 4063 4064 4065
	/* 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];
4066

4067 4068
	for (i = 0; i < n_consecutive; i++) {
		total_len += consecutive_ios[i]->len;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4069 4070
		ut_a(consecutive_ios[i]->status == OS_AIO_NOT_ISSUED);
		consecutive_ios[i]->status = OS_AIO_ISSUED;
4071 4072 4073 4074 4075
	}

	if (n_consecutive == 1) {
		/* We can use the buffer of the i/o request */
		combined_buf = slot->buf;
4076
		combined_buf2 = NULL;
4077
	} else {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4078 4079 4080 4081 4082 4083 4084 4085 4086 4087
		if ((total_len + UNIV_PAGE_SIZE) > os_aio_thread_buffer_size[global_segment]) {

			if (os_aio_thread_buffer[global_segment])
				ut_free(os_aio_thread_buffer[global_segment]);

			os_aio_thread_buffer[global_segment] = ut_malloc(total_len + UNIV_PAGE_SIZE);
 
			os_aio_thread_buffer_size[global_segment] = total_len + UNIV_PAGE_SIZE;
		}
		combined_buf2 = os_aio_thread_buffer[global_segment];
4088

unknown's avatar
unknown committed
4089 4090 4091
		ut_a(combined_buf2);

		combined_buf = ut_align(combined_buf2, UNIV_PAGE_SIZE);
4092
	}
4093

4094 4095 4096 4097
	/* 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! */

Mikael Ronstrom's avatar
Mikael Ronstrom committed
4098 4099 4100
	ut_a(slot->reserved);
	ut_a(slot->status == OS_AIO_ISSUED);

4101 4102 4103 4104 4105
	os_mutex_exit(array->mutex);

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

4107 4108 4109
		for (i = 0; i < n_consecutive; i++) {

			ut_memcpy(combined_buf + offs, consecutive_ios[i]->buf,
unknown's avatar
unknown committed
4110
				  consecutive_ios[i]->len);
4111 4112 4113
			offs += consecutive_ios[i]->len;
		}
	}
4114

4115
	srv_set_io_thread_op_info(global_segment, "doing file i/o");
4116

unknown's avatar
unknown committed
4117 4118
	if (os_aio_print_debug) {
		fprintf(stderr,
unknown's avatar
unknown committed
4119 4120
			"InnoDB: doing i/o of type %lu at offset %lu %lu,"
			" length %lu\n",
4121 4122
			(ulong) slot->type, (ulong) slot->offset_high,
			(ulong) slot->offset, (ulong) total_len);
unknown's avatar
unknown committed
4123 4124
	}

4125 4126
	/* Do the i/o with ordinary, synchronous i/o functions: */
	if (slot->type == OS_FILE_WRITE) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4127
		os_aio_thread_io_writes[global_segment] += n_consecutive;
unknown's avatar
unknown committed
4128
		if (array == os_aio_write_array) {
unknown's avatar
unknown committed
4129
			if ((total_len % UNIV_PAGE_SIZE != 0)
unknown's avatar
unknown committed
4130
			    || (slot->offset % UNIV_PAGE_SIZE != 0)) {
unknown's avatar
unknown committed
4131
				fprintf(stderr,
unknown's avatar
unknown committed
4132 4133
					"InnoDB: Error: trying a displaced"
					" write to %s %lu %lu, len %lu\n",
4134 4135 4136
					slot->name, (ulong) slot->offset_high,
					(ulong) slot->offset,
					(ulong) total_len);
4137
				ut_error;
unknown's avatar
unknown committed
4138
			}
4139

unknown's avatar
unknown committed
4140
			os_file_check_page_trailers(combined_buf, total_len);
unknown's avatar
unknown committed
4141
		}
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4142
 		start_usecs = time_usecs();
4143
		ret = os_file_write(slot->name, slot->file, combined_buf,
unknown's avatar
unknown committed
4144 4145
				    slot->offset, slot->offset_high,
				    total_len);
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4146 4147 4148
 		stop_usecs = time_usecs();
                elapsed_usecs = stop_usecs - start_usecs;
                if (elapsed_usecs < 0) elapsed_usecs = 0;
unknown's avatar
unknown committed
4149 4150 4151 4152

		if (array == os_aio_write_array) {
			os_file_check_page_trailers(combined_buf, total_len);
		}
4153
	} else {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4154 4155
		start_usecs = time_usecs();
 		os_aio_thread_io_reads[global_segment] += n_consecutive;
4156
		ret = os_file_read(slot->file, combined_buf,
unknown's avatar
unknown committed
4157
				   slot->offset, slot->offset_high, total_len);
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4158 4159 4160
		stop_usecs = time_usecs();
                elapsed_usecs = stop_usecs - start_usecs;
                if (elapsed_usecs < 0) elapsed_usecs = 0;
4161
	}
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4162 4163 4164 4165
 	if (elapsed_usecs > os_aio_thread_max_io_wait[global_segment])
 		os_aio_thread_max_io_wait[global_segment] = elapsed_usecs;
 	os_aio_thread_io_wait[global_segment] += elapsed_usecs;
 	os_aio_thread_io_requests[global_segment]++;
4166 4167

	ut_a(ret);
4168
	srv_set_io_thread_op_info(global_segment, "file i/o done");
4169

unknown's avatar
unknown committed
4170 4171 4172 4173 4174
#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
4175 4176 4177 4178

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

4180 4181
		for (i = 0; i < n_consecutive; i++) {

4182
			ut_memcpy(consecutive_ios[i]->buf, combined_buf + offs,
unknown's avatar
unknown committed
4183
				  consecutive_ios[i]->len);
4184 4185 4186 4187 4188 4189 4190 4191 4192
			offs += consecutive_ios[i]->len;
		}
	}

	os_mutex_enter(array->mutex);

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

	for (i = 0; i < n_consecutive; i++) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4193 4194
		ut_a(consecutive_ios[i]->status == OS_AIO_ISSUED);
		consecutive_ios[i]->status = OS_AIO_DONE;
4195 4196 4197 4198 4199
	}

	/* 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 */
4200

4201 4202 4203
slot_io_done:

	ut_a(slot->reserved);
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4204 4205
	ut_a(slot->status == OS_AIO_DONE);
	slot->status = OS_AIO_CLAIMED;
4206 4207 4208 4209

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

4210 4211
	*type = slot->type;

4212 4213 4214
	os_mutex_exit(array->mutex);

	os_aio_array_free_slot(array, slot);
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4215
 	srv_set_io_thread_op_info(global_segment, "exited handler");
4216

4217 4218 4219
	return(ret);

wait_for_io:
unknown's avatar
unknown committed
4220 4221
	srv_set_io_thread_op_info(global_segment, "resetting wait event");

4222 4223
	/* We wait here until there again can be i/os in the segment
	of this thread */
4224

4225 4226 4227 4228
	os_event_reset(os_aio_segment_wait_events[global_segment]);

	os_mutex_exit(array->mutex);

unknown's avatar
unknown committed
4229
recommended_sleep:
4230
	srv_set_io_thread_op_info(global_segment, "waiting for i/o request");
4231

4232 4233
	os_event_wait(os_aio_segment_wait_events[global_segment]);

unknown's avatar
unknown committed
4234 4235
	if (os_aio_print_debug) {
		fprintf(stderr,
unknown's avatar
unknown committed
4236 4237
			"InnoDB: i/o handler thread for i/o"
			" segment %lu wakes up\n",
4238
			(ulong) global_segment);
unknown's avatar
unknown committed
4239
	}
4240

4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255
	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;
4256

4257 4258 4259 4260 4261
	ut_a(array);

	os_mutex_enter(array->mutex);

	ut_a(array->n_slots > 0);
4262

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

4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299
		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
unknown's avatar
unknown committed
4300 4301
os_aio_print(
/*=========*/
4302
	FILE*	file)	/* in: file where to print */
4303 4304 4305 4306
{
	os_aio_array_t*	array;
	os_aio_slot_t*	slot;
	ulint		n_reserved;
4307 4308
	time_t		current_time;
	double		time_elapsed;
unknown's avatar
unknown committed
4309
	double		avg_bytes_read;
4310
	ulint		i;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323
 	ulint		num_issued, num_done, num_claimed;
  
	for (i = 0; i < os_aio_n_segments; i++) {
		fprintf(file,
			"I/O thread %lu state: %s (%s) reads %lu writes %lu "
			"requests %lu io secs %lf io msecs/request %lf max_io_wait %lf",
			i, srv_io_thread_op_info[i], srv_io_thread_function[i],
			os_aio_thread_io_reads[i], os_aio_thread_io_writes[i],
			os_aio_thread_io_requests[i],
			os_aio_thread_io_wait[i] / 1000000.0,
			os_aio_thread_io_requests[i] ?
			os_aio_thread_io_wait[i] / os_aio_thread_io_requests[i] / 1000.0 : 0.0,
			os_aio_thread_max_io_wait[i] / 1000.0);
unknown's avatar
unknown committed
4324

unknown's avatar
unknown committed
4325
#ifndef __WIN__
4326
		if (os_aio_segment_wait_events[i]->is_set) {
unknown's avatar
unknown committed
4327 4328
			fprintf(file, " ev set");
		}
unknown's avatar
unknown committed
4329
#endif
4330

unknown's avatar
unknown committed
4331
		fprintf(file, "\n");
4332 4333
	}

4334
	fputs("Pending normal aio reads:", file);
4335

4336 4337 4338
	array = os_aio_read_array;
loop:
	ut_a(array);
4339

4340 4341 4342 4343
	os_mutex_enter(array->mutex);

	ut_a(array->n_slots > 0);
	n_reserved = 0;
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4344
	num_done = num_issued = num_claimed = 0;
4345 4346 4347

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

4349
		if (slot->reserved) {
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4350 4351 4352 4353 4354 4355 4356 4357
 			if (slot->status == OS_AIO_ISSUED)
 				num_issued++;
 			else if (slot->status == OS_AIO_DONE)
 				num_done++;
 			else {
 				ut_ad(slot->status == OS_AIO_CLAIMED);
 				num_claimed++;
 			}
4358
			n_reserved++;
unknown's avatar
unknown committed
4359 4360 4361 4362 4363
#if 0
			fprintf(stderr, "Reserved slot, messages %p %p\n",
				(void*) slot->message1,
				(void*) slot->message2);
#endif
4364
			ut_a(slot->len > 0);
4365 4366 4367 4368 4369
		}
	}

	ut_a(array->n_reserved == n_reserved);

unknown's avatar
unknown committed
4370
	fprintf(file, " %lu", (ulong) n_reserved);
4371

4372 4373 4374
	os_mutex_exit(array->mutex);

	if (array == os_aio_read_array) {
4375
		fputs(", aio writes:", file);
4376

4377 4378 4379 4380 4381 4382
		array = os_aio_write_array;

		goto loop;
	}

	if (array == os_aio_write_array) {
4383
		fputs(",\n ibuf aio reads:", file);
4384 4385 4386 4387 4388 4389
		array = os_aio_ibuf_array;

		goto loop;
	}

	if (array == os_aio_ibuf_array) {
4390
		fputs(", log i/o's:", file);
4391 4392 4393 4394 4395 4396
		array = os_aio_log_array;

		goto loop;
	}

	if (array == os_aio_log_array) {
4397
		fputs(", sync i/o's:", file);
4398 4399 4400 4401
		array = os_aio_sync_array;

		goto loop;
	}
4402

Mikael Ronstrom's avatar
Mikael Ronstrom committed
4403 4404 4405
 	putc('\n', file);
 	fprintf(file,
 		"Summary of background IO slot status: %lu issued, "
4406
 		"%lu done, %lu claimed, sleep set %u\n",
Mikael Ronstrom's avatar
Mikael Ronstrom committed
4407 4408 4409
 		num_issued, num_done, num_claimed,
 		os_aio_recommend_sleep_for_read_threads);

4410
	putc('\n', file);
4411
	current_time = time(NULL);
unknown's avatar
unknown committed
4412
	time_elapsed = 0.001 + difftime(current_time, os_last_printout);
4413

4414 4415
	fprintf(file,
		"Pending flushes (fsync) log: %lu; buffer pool: %lu\n"
unknown's avatar
unknown committed
4416
		"%lu OS file reads, %lu OS file writes, %lu OS fsyncs\n",
unknown's avatar
unknown committed
4417 4418
		(ulong) fil_n_pending_log_flushes,
		(ulong) fil_n_pending_tablespace_flushes,
4419 4420
		(ulong) os_n_file_reads, (ulong) os_n_file_writes,
		(ulong) os_n_fsyncs);
unknown's avatar
unknown committed
4421

unknown's avatar
unknown committed
4422
	if (os_file_n_pending_preads != 0 || os_file_n_pending_pwrites != 0) {
4423
		fprintf(file,
4424 4425 4426
			"%lu pending preads, %lu pending pwrites\n",
			(ulong) os_file_n_pending_preads,
			(ulong) os_file_n_pending_pwrites);
unknown's avatar
unknown committed
4427 4428
	}

unknown's avatar
unknown committed
4429 4430 4431
	if (os_n_file_reads == os_n_file_reads_old) {
		avg_bytes_read = 0.0;
	} else {
unknown's avatar
unknown committed
4432 4433
		avg_bytes_read = (double) os_bytes_read_since_printout
			/ (os_n_file_reads - os_n_file_reads_old);
unknown's avatar
unknown committed
4434 4435
	}

4436
	fprintf(file,
unknown's avatar
unknown committed
4437 4438
		"%.2f reads/s, %lu avg bytes/read,"
		" %.2f writes/s, %.2f fsyncs/s\n",
4439 4440
		(os_n_file_reads - os_n_file_reads_old)
		/ time_elapsed,
4441
		(ulong)avg_bytes_read,
4442 4443 4444 4445 4446 4447 4448 4449
		(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;
unknown's avatar
unknown committed
4450
	os_bytes_read_since_printout = 0;
4451

4452
	os_last_printout = current_time;
4453 4454
}

unknown's avatar
unknown committed
4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465
/**************************************************************************
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;
4466

unknown's avatar
unknown committed
4467 4468 4469
	os_last_printout = time(NULL);
}

unknown's avatar
unknown committed
4470
#ifdef UNIV_DEBUG
4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481
/**************************************************************************
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;
4482

4483 4484 4485 4486
	array = os_aio_read_array;

	os_mutex_enter(array->mutex);

4487 4488
	n_res += array->n_reserved;

4489 4490 4491 4492 4493 4494
	os_mutex_exit(array->mutex);

	array = os_aio_write_array;

	os_mutex_enter(array->mutex);

4495 4496
	n_res += array->n_reserved;

4497 4498 4499 4500 4501 4502
	os_mutex_exit(array->mutex);

	array = os_aio_ibuf_array;

	os_mutex_enter(array->mutex);

4503 4504
	n_res += array->n_reserved;

4505 4506 4507 4508 4509 4510
	os_mutex_exit(array->mutex);

	array = os_aio_log_array;

	os_mutex_enter(array->mutex);

4511 4512
	n_res += array->n_reserved;

4513 4514 4515 4516 4517 4518
	os_mutex_exit(array->mutex);

	array = os_aio_sync_array;

	os_mutex_enter(array->mutex);

4519 4520
	n_res += array->n_reserved;

4521 4522 4523 4524 4525 4526 4527 4528 4529
	os_mutex_exit(array->mutex);

	if (n_res == 0) {

		return(TRUE);
	}

	return(FALSE);
}
unknown's avatar
unknown committed
4530
#endif /* UNIV_DEBUG */