]> git.proxmox.com Git - mirror_qemu.git/blame - block-raw-posix.c
Define O_DSYNC as O_SYNC if necessary.
[mirror_qemu.git] / block-raw-posix.c
CommitLineData
83f64091 1/*
223d4670 2 * Block driver for RAW files (posix)
5fafdf24 3 *
83f64091 4 * Copyright (c) 2006 Fabrice Bellard
5fafdf24 5 *
83f64091
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
faf07963 24#include "qemu-common.h"
87ecb68b 25#include "qemu-timer.h"
baf35cb9 26#include "qemu-char.h"
83f64091
FB
27#include "block_int.h"
28#include <assert.h>
414f0dab 29#ifdef CONFIG_AIO
83f64091 30#include <aio.h>
414f0dab 31#endif
83f64091 32
83f64091
FB
33#ifdef CONFIG_COCOA
34#include <paths.h>
35#include <sys/param.h>
36#include <IOKit/IOKitLib.h>
37#include <IOKit/IOBSD.h>
38#include <IOKit/storage/IOMediaBSDClient.h>
39#include <IOKit/storage/IOMedia.h>
40#include <IOKit/storage/IOCDMedia.h>
41//#include <IOKit/storage/IOCDTypes.h>
42#include <CoreFoundation/CoreFoundation.h>
43#endif
44
45#ifdef __sun__
2e9671da
TS
46#define _POSIX_PTHREAD_SEMANTICS 1
47#include <signal.h>
83f64091
FB
48#include <sys/dkio.h>
49#endif
19cb3738
FB
50#ifdef __linux__
51#include <sys/ioctl.h>
52#include <linux/cdrom.h>
53#include <linux/fd.h>
54#endif
1cb6c3fd 55#ifdef __FreeBSD__
543952ca 56#include <signal.h>
1cb6c3fd
TS
57#include <sys/disk.h>
58#endif
83f64091 59
128ab2ff
BS
60#ifdef __OpenBSD__
61#include <sys/ioctl.h>
62#include <sys/disklabel.h>
63#include <sys/dkio.h>
64#endif
65
19cb3738 66//#define DEBUG_FLOPPY
83f64091 67
faf07963 68//#define DEBUG_BLOCK
03ff3ca3 69#if defined(DEBUG_BLOCK)
a50a6282 70#define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (loglevel != 0) \
2e03286b 71 { fprintf(logfile, formatCstr, ##args); fflush(logfile); } } while (0)
8c05dbf9
TS
72#else
73#define DEBUG_BLOCK_PRINT(formatCstr, args...)
74#endif
75
f6465578
AL
76/* OS X does not have O_DSYNC */
77#ifndef O_DSYNC
78#define O_SYNC
79#endif
80
9f7965c7
AL
81/* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
82#ifndef O_DIRECT
83#define O_DIRECT O_DSYNC
84#endif
85
19cb3738
FB
86#define FTYPE_FILE 0
87#define FTYPE_CD 1
88#define FTYPE_FD 2
83f64091 89
bed5cc52
FB
90#define ALIGNED_BUFFER_SIZE (32 * 512)
91
19cb3738
FB
92/* if the FD is not accessed during that time (in ms), we try to
93 reopen it to see if the disk has been changed */
94#define FD_OPEN_TIMEOUT 1000
83f64091 95
53538725
AL
96/* posix-aio doesn't allow multiple outstanding requests to a single file
97 * descriptor. we implement a pool of dup()'d file descriptors to work
98 * around this */
99#define RAW_FD_POOL_SIZE 64
100
19cb3738
FB
101typedef struct BDRVRawState {
102 int fd;
103 int type;
8c05dbf9 104 unsigned int lseek_err_cnt;
53538725 105 int fd_pool[RAW_FD_POOL_SIZE];
19cb3738
FB
106#if defined(__linux__)
107 /* linux floppy specific */
6dd2db52 108 int fd_open_flags;
19cb3738
FB
109 int64_t fd_open_time;
110 int64_t fd_error_time;
111 int fd_got_error;
112 int fd_media_changed;
83f64091 113#endif
bed5cc52 114 uint8_t* aligned_buf;
19cb3738
FB
115} BDRVRawState;
116
a76bab49
AL
117static int posix_aio_init(void);
118
19cb3738 119static int fd_open(BlockDriverState *bs);
83f64091
FB
120
121static int raw_open(BlockDriverState *bs, const char *filename, int flags)
122{
123 BDRVRawState *s = bs->opaque;
19cb3738 124 int fd, open_flags, ret;
53538725 125 int i;
83f64091 126
a76bab49
AL
127 posix_aio_init();
128
8c05dbf9
TS
129 s->lseek_err_cnt = 0;
130
83f64091
FB
131 open_flags = O_BINARY;
132 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
133 open_flags |= O_RDWR;
134 } else {
135 open_flags |= O_RDONLY;
136 bs->read_only = 1;
137 }
138 if (flags & BDRV_O_CREAT)
139 open_flags |= O_CREAT | O_TRUNC;
9f7965c7
AL
140
141 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
142 * and O_DIRECT for no caching. */
143 if ((flags & BDRV_O_NOCACHE))
33f00271 144 open_flags |= O_DIRECT;
9f7965c7
AL
145 else if (!(flags & BDRV_O_CACHE_WB))
146 open_flags |= O_DSYNC;
83f64091 147
19cb3738
FB
148 s->type = FTYPE_FILE;
149
83f64091 150 fd = open(filename, open_flags, 0644);
19cb3738
FB
151 if (fd < 0) {
152 ret = -errno;
153 if (ret == -EROFS)
154 ret = -EACCES;
155 return ret;
156 }
83f64091 157 s->fd = fd;
53538725
AL
158 for (i = 0; i < RAW_FD_POOL_SIZE; i++)
159 s->fd_pool[i] = -1;
bed5cc52 160 s->aligned_buf = NULL;
9f7965c7 161 if ((flags & BDRV_O_NOCACHE)) {
bed5cc52
FB
162 s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
163 if (s->aligned_buf == NULL) {
164 ret = -errno;
165 close(fd);
166 return ret;
167 }
168 }
83f64091
FB
169 return 0;
170}
171
172/* XXX: use host sector size if necessary with:
173#ifdef DIOCGSECTORSIZE
174 {
175 unsigned int sectorsize = 512;
176 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
177 sectorsize > bufsize)
178 bufsize = sectorsize;
179 }
180#endif
181#ifdef CONFIG_COCOA
182 u_int32_t blockSize = 512;
183 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
184 bufsize = blockSize;
185 }
186#endif
187*/
188
bed5cc52
FB
189/*
190 * offset and count are in bytes, but must be multiples of 512 for files
191 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
192 *
193 * This function may be called without alignment if the caller ensures
194 * that O_DIRECT is not in effect.
195 */
196static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
83f64091
FB
197 uint8_t *buf, int count)
198{
199 BDRVRawState *s = bs->opaque;
200 int ret;
3b46e624 201
19cb3738
FB
202 ret = fd_open(bs);
203 if (ret < 0)
204 return ret;
205
985a03b0 206 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
8c05dbf9
TS
207 ++(s->lseek_err_cnt);
208 if(s->lseek_err_cnt <= 10) {
92868412
JM
209 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
210 "] lseek failed : %d = %s\n",
8c05dbf9
TS
211 s->fd, bs->filename, offset, buf, count,
212 bs->total_sectors, errno, strerror(errno));
213 }
214 return -1;
215 }
216 s->lseek_err_cnt=0;
217
83f64091 218 ret = read(s->fd, buf, count);
8c05dbf9
TS
219 if (ret == count)
220 goto label__raw_read__success;
221
92868412
JM
222 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
223 "] read failed %d : %d = %s\n",
8c05dbf9
TS
224 s->fd, bs->filename, offset, buf, count,
225 bs->total_sectors, ret, errno, strerror(errno));
226
227 /* Try harder for CDrom. */
228 if (bs->type == BDRV_TYPE_CDROM) {
229 lseek(s->fd, offset, SEEK_SET);
230 ret = read(s->fd, buf, count);
231 if (ret == count)
232 goto label__raw_read__success;
233 lseek(s->fd, offset, SEEK_SET);
234 ret = read(s->fd, buf, count);
235 if (ret == count)
236 goto label__raw_read__success;
237
92868412
JM
238 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
239 "] retry read failed %d : %d = %s\n",
8c05dbf9
TS
240 s->fd, bs->filename, offset, buf, count,
241 bs->total_sectors, ret, errno, strerror(errno));
242 }
243
8c05dbf9
TS
244label__raw_read__success:
245
83f64091
FB
246 return ret;
247}
248
bed5cc52
FB
249/*
250 * offset and count are in bytes, but must be multiples of 512 for files
251 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
252 *
253 * This function may be called without alignment if the caller ensures
254 * that O_DIRECT is not in effect.
255 */
256static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
83f64091
FB
257 const uint8_t *buf, int count)
258{
259 BDRVRawState *s = bs->opaque;
260 int ret;
3b46e624 261
19cb3738
FB
262 ret = fd_open(bs);
263 if (ret < 0)
264 return ret;
265
985a03b0 266 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
8c05dbf9
TS
267 ++(s->lseek_err_cnt);
268 if(s->lseek_err_cnt) {
92868412
JM
269 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
270 PRId64 "] lseek failed : %d = %s\n",
8c05dbf9
TS
271 s->fd, bs->filename, offset, buf, count,
272 bs->total_sectors, errno, strerror(errno));
273 }
274 return -1;
275 }
276 s->lseek_err_cnt = 0;
277
83f64091 278 ret = write(s->fd, buf, count);
8c05dbf9
TS
279 if (ret == count)
280 goto label__raw_write__success;
281
92868412
JM
282 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
283 "] write failed %d : %d = %s\n",
8c05dbf9
TS
284 s->fd, bs->filename, offset, buf, count,
285 bs->total_sectors, ret, errno, strerror(errno));
286
8c05dbf9
TS
287label__raw_write__success:
288
83f64091
FB
289 return ret;
290}
291
bed5cc52 292
bed5cc52
FB
293/*
294 * offset and count are in bytes and possibly not aligned. For files opened
295 * with O_DIRECT, necessary alignments are ensured before calling
296 * raw_pread_aligned to do the actual read.
297 */
298static int raw_pread(BlockDriverState *bs, int64_t offset,
299 uint8_t *buf, int count)
300{
301 BDRVRawState *s = bs->opaque;
302 int size, ret, shift, sum;
303
304 sum = 0;
305
306 if (s->aligned_buf != NULL) {
307
308 if (offset & 0x1ff) {
309 /* align offset on a 512 bytes boundary */
310
311 shift = offset & 0x1ff;
312 size = (shift + count + 0x1ff) & ~0x1ff;
313 if (size > ALIGNED_BUFFER_SIZE)
314 size = ALIGNED_BUFFER_SIZE;
315 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
316 if (ret < 0)
317 return ret;
318
319 size = 512 - shift;
320 if (size > count)
321 size = count;
322 memcpy(buf, s->aligned_buf + shift, size);
323
324 buf += size;
325 offset += size;
326 count -= size;
327 sum += size;
328
329 if (count == 0)
330 return sum;
331 }
332 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
333
334 /* read on aligned buffer */
335
336 while (count) {
337
338 size = (count + 0x1ff) & ~0x1ff;
339 if (size > ALIGNED_BUFFER_SIZE)
340 size = ALIGNED_BUFFER_SIZE;
341
342 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
343 if (ret < 0)
344 return ret;
345
346 size = ret;
347 if (size > count)
348 size = count;
349
350 memcpy(buf, s->aligned_buf, size);
351
352 buf += size;
353 offset += size;
354 count -= size;
355 sum += size;
356 }
357
358 return sum;
359 }
360 }
361
362 return raw_pread_aligned(bs, offset, buf, count) + sum;
363}
364
365/*
366 * offset and count are in bytes and possibly not aligned. For files opened
367 * with O_DIRECT, necessary alignments are ensured before calling
368 * raw_pwrite_aligned to do the actual write.
369 */
370static int raw_pwrite(BlockDriverState *bs, int64_t offset,
371 const uint8_t *buf, int count)
372{
373 BDRVRawState *s = bs->opaque;
374 int size, ret, shift, sum;
375
376 sum = 0;
377
378 if (s->aligned_buf != NULL) {
379
380 if (offset & 0x1ff) {
381 /* align offset on a 512 bytes boundary */
382 shift = offset & 0x1ff;
383 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
384 if (ret < 0)
385 return ret;
386
387 size = 512 - shift;
388 if (size > count)
389 size = count;
390 memcpy(s->aligned_buf + shift, buf, size);
391
392 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
393 if (ret < 0)
394 return ret;
395
396 buf += size;
397 offset += size;
398 count -= size;
399 sum += size;
400
401 if (count == 0)
402 return sum;
403 }
404 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
405
406 while ((size = (count & ~0x1ff)) != 0) {
407
408 if (size > ALIGNED_BUFFER_SIZE)
409 size = ALIGNED_BUFFER_SIZE;
410
411 memcpy(s->aligned_buf, buf, size);
412
413 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
414 if (ret < 0)
415 return ret;
416
417 buf += ret;
418 offset += ret;
419 count -= ret;
420 sum += ret;
421 }
422 /* here, count < 512 because (count & ~0x1ff) == 0 */
423 if (count) {
424 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
425 if (ret < 0)
426 return ret;
427 memcpy(s->aligned_buf, buf, count);
428
429 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
430 if (ret < 0)
431 return ret;
432 if (count < ret)
433 ret = count;
434
435 sum += ret;
436 }
437 return sum;
438 }
439 }
440 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
441}
442
414f0dab 443#ifdef CONFIG_AIO
83f64091 444/***********************************************************/
19cb3738 445/* Unix AIO using POSIX AIO */
83f64091
FB
446
447typedef struct RawAIOCB {
ce1a14dc 448 BlockDriverAIOCB common;
53538725 449 int fd;
83f64091 450 struct aiocb aiocb;
ce1a14dc 451 struct RawAIOCB *next;
bed5cc52 452 int ret;
83f64091
FB
453} RawAIOCB;
454
a76bab49
AL
455typedef struct PosixAioState
456{
9e472e10 457 int rfd, wfd;
a76bab49
AL
458 RawAIOCB *first_aio;
459} PosixAioState;
83f64091 460
53538725
AL
461static int raw_fd_pool_get(BDRVRawState *s)
462{
463 int i;
464
465 for (i = 0; i < RAW_FD_POOL_SIZE; i++) {
466 /* already in use */
467 if (s->fd_pool[i] != -1)
468 continue;
469
470 /* try to dup file descriptor */
471 s->fd_pool[i] = dup(s->fd);
472 if (s->fd_pool[i] != -1)
473 return s->fd_pool[i];
474 }
475
476 /* we couldn't dup the file descriptor so just use the main one */
477 return s->fd;
478}
479
480static void raw_fd_pool_put(RawAIOCB *acb)
481{
482 BDRVRawState *s = acb->common.bs->opaque;
483 int i;
484
485 for (i = 0; i < RAW_FD_POOL_SIZE; i++) {
486 if (s->fd_pool[i] == acb->fd) {
487 close(s->fd_pool[i]);
488 s->fd_pool[i] = -1;
489 }
490 }
491}
492
a76bab49 493static void posix_aio_read(void *opaque)
83f64091 494{
a76bab49 495 PosixAioState *s = opaque;
ce1a14dc 496 RawAIOCB *acb, **pacb;
83f64091 497 int ret;
9e472e10
AL
498 ssize_t len;
499
500 do {
501 char byte;
502
503 len = read(s->rfd, &byte, 1);
2c41a5f9
AL
504 if (len == -1 && errno == EINTR)
505 continue;
9e472e10
AL
506 if (len == -1 && errno == EAGAIN)
507 break;
508 } while (len == -1);
83f64091
FB
509
510 for(;;) {
a76bab49 511 pacb = &s->first_aio;
83f64091
FB
512 for(;;) {
513 acb = *pacb;
514 if (!acb)
515 goto the_end;
ce1a14dc 516 ret = aio_error(&acb->aiocb);
83f64091
FB
517 if (ret == ECANCELED) {
518 /* remove the request */
ce1a14dc 519 *pacb = acb->next;
53538725 520 raw_fd_pool_put(acb);
ce1a14dc 521 qemu_aio_release(acb);
83f64091
FB
522 } else if (ret != EINPROGRESS) {
523 /* end of aio */
524 if (ret == 0) {
ce1a14dc
PB
525 ret = aio_return(&acb->aiocb);
526 if (ret == acb->aiocb.aio_nbytes)
83f64091
FB
527 ret = 0;
528 else
19cb3738 529 ret = -EINVAL;
83f64091
FB
530 } else {
531 ret = -ret;
532 }
533 /* remove the request */
ce1a14dc 534 *pacb = acb->next;
83f64091 535 /* call the callback */
ce1a14dc 536 acb->common.cb(acb->common.opaque, ret);
53538725 537 raw_fd_pool_put(acb);
ce1a14dc 538 qemu_aio_release(acb);
83f64091
FB
539 break;
540 } else {
ce1a14dc 541 pacb = &acb->next;
83f64091
FB
542 }
543 }
544 }
545 the_end: ;
546}
547
a76bab49 548static int posix_aio_flush(void *opaque)
baf35cb9 549{
a76bab49
AL
550 PosixAioState *s = opaque;
551 return !!s->first_aio;
552}
553
554static PosixAioState *posix_aio_state;
baf35cb9 555
9e472e10
AL
556static void aio_signal_handler(int signum)
557{
558 if (posix_aio_state) {
559 char byte = 0;
560
561 write(posix_aio_state->wfd, &byte, sizeof(byte));
562 }
563
564 qemu_service_io();
565}
566
a76bab49
AL
567static int posix_aio_init(void)
568{
9e472e10 569 struct sigaction act;
a76bab49 570 PosixAioState *s;
9e472e10 571 int fds[2];
a76bab49
AL
572
573 if (posix_aio_state)
574 return 0;
ad02ad6f 575
a76bab49
AL
576 s = qemu_malloc(sizeof(PosixAioState));
577 if (s == NULL)
578 return -ENOMEM;
baf35cb9 579
9e472e10
AL
580 sigfillset(&act.sa_mask);
581 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
582 act.sa_handler = aio_signal_handler;
583 sigaction(SIGUSR2, &act, NULL);
584
a76bab49 585 s->first_aio = NULL;
9e472e10
AL
586 if (pipe(fds) == -1) {
587 fprintf(stderr, "failed to create pipe\n");
27463101
AL
588 return -errno;
589 }
2c41a5f9 590
9e472e10
AL
591 s->rfd = fds[0];
592 s->wfd = fds[1];
593
594 fcntl(s->wfd, F_SETFL, O_NONBLOCK);
2c41a5f9 595
9e472e10 596 qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);
baf35cb9 597
acce87f9
AL
598#if defined(__linux__)
599 {
600 struct aioinit ai;
601
602 memset(&ai, 0, sizeof(ai));
603#if defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2, 4)
604 ai.aio_threads = 64;
605 ai.aio_num = 64;
997306fc 606#else
acce87f9
AL
607 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
608 seems to fix the problem. */
609 ai.aio_threads = 1;
610 ai.aio_num = 1;
611 ai.aio_idle_time = 365 * 100000;
612#endif
613 aio_init(&ai);
614 }
baf35cb9 615#endif
a76bab49 616 posix_aio_state = s;
6eb5733a 617
a76bab49 618 return 0;
83f64091
FB
619}
620
ce1a14dc
PB
621static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
622 int64_t sector_num, uint8_t *buf, int nb_sectors,
623 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 624{
ce1a14dc
PB
625 BDRVRawState *s = bs->opaque;
626 RawAIOCB *acb;
627
19cb3738
FB
628 if (fd_open(bs) < 0)
629 return NULL;
630
ce1a14dc
PB
631 acb = qemu_aio_get(bs, cb, opaque);
632 if (!acb)
633 return NULL;
53538725
AL
634 acb->fd = raw_fd_pool_get(s);
635 acb->aiocb.aio_fildes = acb->fd;
a76bab49 636 acb->aiocb.aio_sigevent.sigev_signo = SIGUSR2;
ce1a14dc
PB
637 acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
638 acb->aiocb.aio_buf = buf;
985a03b0
TS
639 if (nb_sectors < 0)
640 acb->aiocb.aio_nbytes = -nb_sectors;
641 else
642 acb->aiocb.aio_nbytes = nb_sectors * 512;
ce1a14dc 643 acb->aiocb.aio_offset = sector_num * 512;
a76bab49
AL
644 acb->next = posix_aio_state->first_aio;
645 posix_aio_state->first_aio = acb;
ce1a14dc 646 return acb;
83f64091
FB
647}
648
bed5cc52
FB
649static void raw_aio_em_cb(void* opaque)
650{
651 RawAIOCB *acb = opaque;
652 acb->common.cb(acb->common.opaque, acb->ret);
653 qemu_aio_release(acb);
654}
bed5cc52 655
ce1a14dc
PB
656static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
657 int64_t sector_num, uint8_t *buf, int nb_sectors,
658 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 659{
ce1a14dc 660 RawAIOCB *acb;
83f64091 661
bed5cc52
FB
662 /*
663 * If O_DIRECT is used and the buffer is not aligned fall back
664 * to synchronous IO.
665 */
bed5cc52
FB
666 BDRVRawState *s = bs->opaque;
667
668 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
669 QEMUBH *bh;
670 acb = qemu_aio_get(bs, cb, opaque);
671 acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
672 bh = qemu_bh_new(raw_aio_em_cb, acb);
673 qemu_bh_schedule(bh);
674 return &acb->common;
675 }
bed5cc52 676
ce1a14dc
PB
677 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
678 if (!acb)
679 return NULL;
680 if (aio_read(&acb->aiocb) < 0) {
681 qemu_aio_release(acb);
682 return NULL;
5fafdf24 683 }
ce1a14dc 684 return &acb->common;
83f64091
FB
685}
686
ce1a14dc
PB
687static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
688 int64_t sector_num, const uint8_t *buf, int nb_sectors,
689 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 690{
ce1a14dc 691 RawAIOCB *acb;
83f64091 692
bed5cc52
FB
693 /*
694 * If O_DIRECT is used and the buffer is not aligned fall back
695 * to synchronous IO.
696 */
bed5cc52
FB
697 BDRVRawState *s = bs->opaque;
698
699 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
700 QEMUBH *bh;
701 acb = qemu_aio_get(bs, cb, opaque);
702 acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
703 bh = qemu_bh_new(raw_aio_em_cb, acb);
704 qemu_bh_schedule(bh);
705 return &acb->common;
706 }
bed5cc52 707
ce1a14dc
PB
708 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
709 if (!acb)
710 return NULL;
711 if (aio_write(&acb->aiocb) < 0) {
712 qemu_aio_release(acb);
713 return NULL;
5fafdf24 714 }
ce1a14dc 715 return &acb->common;
83f64091
FB
716}
717
ce1a14dc 718static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
83f64091 719{
83f64091 720 int ret;
ce1a14dc
PB
721 RawAIOCB *acb = (RawAIOCB *)blockacb;
722 RawAIOCB **pacb;
83f64091 723
ce1a14dc 724 ret = aio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
83f64091
FB
725 if (ret == AIO_NOTCANCELED) {
726 /* fail safe: if the aio could not be canceled, we wait for
727 it */
ce1a14dc 728 while (aio_error(&acb->aiocb) == EINPROGRESS);
83f64091
FB
729 }
730
731 /* remove the callback from the queue */
a76bab49 732 pacb = &posix_aio_state->first_aio;
83f64091
FB
733 for(;;) {
734 if (*pacb == NULL) {
735 break;
736 } else if (*pacb == acb) {
ce1a14dc 737 *pacb = acb->next;
53538725 738 raw_fd_pool_put(acb);
ce1a14dc 739 qemu_aio_release(acb);
83f64091
FB
740 break;
741 }
ce1a14dc 742 pacb = &acb->next;
83f64091
FB
743 }
744}
745
a76bab49
AL
746#else /* CONFIG_AIO */
747static int posix_aio_init(void)
414f0dab 748{
674a24ac 749 return 0;
414f0dab 750}
414f0dab
BS
751#endif /* CONFIG_AIO */
752
53538725
AL
753static void raw_close_fd_pool(BDRVRawState *s)
754{
755 int i;
756
757 for (i = 0; i < RAW_FD_POOL_SIZE; i++) {
758 if (s->fd_pool[i] != -1) {
759 close(s->fd_pool[i]);
760 s->fd_pool[i] = -1;
761 }
762 }
763}
764
83f64091
FB
765static void raw_close(BlockDriverState *bs)
766{
767 BDRVRawState *s = bs->opaque;
19cb3738
FB
768 if (s->fd >= 0) {
769 close(s->fd);
770 s->fd = -1;
bed5cc52
FB
771 if (s->aligned_buf != NULL)
772 qemu_free(s->aligned_buf);
19cb3738 773 }
53538725 774 raw_close_fd_pool(s);
83f64091
FB
775}
776
777static int raw_truncate(BlockDriverState *bs, int64_t offset)
778{
779 BDRVRawState *s = bs->opaque;
19cb3738
FB
780 if (s->type != FTYPE_FILE)
781 return -ENOTSUP;
83f64091
FB
782 if (ftruncate(s->fd, offset) < 0)
783 return -errno;
784 return 0;
785}
786
128ab2ff
BS
787#ifdef __OpenBSD__
788static int64_t raw_getlength(BlockDriverState *bs)
789{
790 BDRVRawState *s = bs->opaque;
791 int fd = s->fd;
792 struct stat st;
793
794 if (fstat(fd, &st))
795 return -1;
796 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
797 struct disklabel dl;
798
799 if (ioctl(fd, DIOCGDINFO, &dl))
800 return -1;
801 return (uint64_t)dl.d_secsize *
802 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
803 } else
804 return st.st_size;
805}
806#else /* !__OpenBSD__ */
83f64091
FB
807static int64_t raw_getlength(BlockDriverState *bs)
808{
809 BDRVRawState *s = bs->opaque;
810 int fd = s->fd;
811 int64_t size;
812#ifdef _BSD
813 struct stat sb;
814#endif
815#ifdef __sun__
816 struct dk_minfo minfo;
817 int rv;
818#endif
19cb3738
FB
819 int ret;
820
821 ret = fd_open(bs);
822 if (ret < 0)
823 return ret;
83f64091
FB
824
825#ifdef _BSD
826 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
827#ifdef DIOCGMEDIASIZE
828 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
829#endif
830#ifdef CONFIG_COCOA
831 size = LONG_LONG_MAX;
832#else
833 size = lseek(fd, 0LL, SEEK_END);
834#endif
835 } else
836#endif
837#ifdef __sun__
838 /*
839 * use the DKIOCGMEDIAINFO ioctl to read the size.
840 */
841 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
842 if ( rv != -1 ) {
843 size = minfo.dki_lbsize * minfo.dki_capacity;
844 } else /* there are reports that lseek on some devices
845 fails, but irc discussion said that contingency
846 on contingency was overkill */
847#endif
848 {
849 size = lseek(fd, 0, SEEK_END);
850 }
83f64091
FB
851 return size;
852}
128ab2ff 853#endif
83f64091
FB
854
855static int raw_create(const char *filename, int64_t total_size,
856 const char *backing_file, int flags)
857{
858 int fd;
859
860 if (flags || backing_file)
861 return -ENOTSUP;
862
5fafdf24 863 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
83f64091
FB
864 0644);
865 if (fd < 0)
866 return -EIO;
867 ftruncate(fd, total_size * 512);
868 close(fd);
869 return 0;
870}
871
872static void raw_flush(BlockDriverState *bs)
873{
874 BDRVRawState *s = bs->opaque;
875 fsync(s->fd);
876}
877
878BlockDriver bdrv_raw = {
879 "raw",
880 sizeof(BDRVRawState),
881 NULL, /* no probe for protocols */
882 raw_open,
883 NULL,
884 NULL,
885 raw_close,
886 raw_create,
887 raw_flush,
3b46e624 888
414f0dab 889#ifdef CONFIG_AIO
83f64091
FB
890 .bdrv_aio_read = raw_aio_read,
891 .bdrv_aio_write = raw_aio_write,
892 .bdrv_aio_cancel = raw_aio_cancel,
ce1a14dc 893 .aiocb_size = sizeof(RawAIOCB),
414f0dab 894#endif
83f64091
FB
895 .bdrv_pread = raw_pread,
896 .bdrv_pwrite = raw_pwrite,
897 .bdrv_truncate = raw_truncate,
898 .bdrv_getlength = raw_getlength,
899};
900
19cb3738
FB
901/***********************************************/
902/* host device */
903
904#ifdef CONFIG_COCOA
905static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
906static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
907
908kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
909{
5fafdf24 910 kern_return_t kernResult;
19cb3738
FB
911 mach_port_t masterPort;
912 CFMutableDictionaryRef classesToMatch;
913
914 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
915 if ( KERN_SUCCESS != kernResult ) {
916 printf( "IOMasterPort returned %d\n", kernResult );
917 }
3b46e624 918
5fafdf24 919 classesToMatch = IOServiceMatching( kIOCDMediaClass );
19cb3738
FB
920 if ( classesToMatch == NULL ) {
921 printf( "IOServiceMatching returned a NULL dictionary.\n" );
922 } else {
923 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
924 }
925 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
926 if ( KERN_SUCCESS != kernResult )
927 {
928 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
929 }
3b46e624 930
19cb3738
FB
931 return kernResult;
932}
933
934kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
935{
936 io_object_t nextMedia;
937 kern_return_t kernResult = KERN_FAILURE;
938 *bsdPath = '\0';
939 nextMedia = IOIteratorNext( mediaIterator );
940 if ( nextMedia )
941 {
942 CFTypeRef bsdPathAsCFString;
943 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
944 if ( bsdPathAsCFString ) {
945 size_t devPathLength;
946 strcpy( bsdPath, _PATH_DEV );
947 strcat( bsdPath, "r" );
948 devPathLength = strlen( bsdPath );
949 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
950 kernResult = KERN_SUCCESS;
951 }
952 CFRelease( bsdPathAsCFString );
953 }
954 IOObjectRelease( nextMedia );
955 }
3b46e624 956
19cb3738
FB
957 return kernResult;
958}
959
960#endif
961
962static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
963{
964 BDRVRawState *s = bs->opaque;
53538725 965 int fd, open_flags, ret, i;
19cb3738 966
a76bab49
AL
967 posix_aio_init();
968
19cb3738
FB
969#ifdef CONFIG_COCOA
970 if (strstart(filename, "/dev/cdrom", NULL)) {
971 kern_return_t kernResult;
972 io_iterator_t mediaIterator;
973 char bsdPath[ MAXPATHLEN ];
974 int fd;
5fafdf24 975
19cb3738
FB
976 kernResult = FindEjectableCDMedia( &mediaIterator );
977 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
3b46e624 978
19cb3738
FB
979 if ( bsdPath[ 0 ] != '\0' ) {
980 strcat(bsdPath,"s0");
981 /* some CDs don't have a partition 0 */
982 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
983 if (fd < 0) {
984 bsdPath[strlen(bsdPath)-1] = '1';
985 } else {
986 close(fd);
987 }
988 filename = bsdPath;
989 }
3b46e624 990
19cb3738
FB
991 if ( mediaIterator )
992 IOObjectRelease( mediaIterator );
993 }
994#endif
995 open_flags = O_BINARY;
996 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
997 open_flags |= O_RDWR;
998 } else {
999 open_flags |= O_RDONLY;
1000 bs->read_only = 1;
1001 }
9f7965c7
AL
1002 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
1003 * and O_DIRECT for no caching. */
1004 if ((flags & BDRV_O_NOCACHE))
33f00271 1005 open_flags |= O_DIRECT;
9f7965c7
AL
1006 else if (!(flags & BDRV_O_CACHE_WB))
1007 open_flags |= O_DSYNC;
19cb3738
FB
1008
1009 s->type = FTYPE_FILE;
1010#if defined(__linux__)
1011 if (strstart(filename, "/dev/cd", NULL)) {
1012 /* open will not fail even if no CD is inserted */
1013 open_flags |= O_NONBLOCK;
1014 s->type = FTYPE_CD;
1015 } else if (strstart(filename, "/dev/fd", NULL)) {
1016 s->type = FTYPE_FD;
6dd2db52 1017 s->fd_open_flags = open_flags;
19cb3738
FB
1018 /* open will not fail even if no floppy is inserted */
1019 open_flags |= O_NONBLOCK;
985a03b0
TS
1020 } else if (strstart(filename, "/dev/sg", NULL)) {
1021 bs->sg = 1;
19cb3738
FB
1022 }
1023#endif
1024 fd = open(filename, open_flags, 0644);
1025 if (fd < 0) {
1026 ret = -errno;
1027 if (ret == -EROFS)
1028 ret = -EACCES;
1029 return ret;
1030 }
1031 s->fd = fd;
53538725
AL
1032 for (i = 0; i < RAW_FD_POOL_SIZE; i++)
1033 s->fd_pool[i] = -1;
19cb3738
FB
1034#if defined(__linux__)
1035 /* close fd so that we can reopen it as needed */
1036 if (s->type == FTYPE_FD) {
1037 close(s->fd);
1038 s->fd = -1;
1039 s->fd_media_changed = 1;
1040 }
1041#endif
1042 return 0;
1043}
1044
03ff3ca3 1045#if defined(__linux__)
19cb3738
FB
1046/* Note: we do not have a reliable method to detect if the floppy is
1047 present. The current method is to try to open the floppy at every
1048 I/O and to keep it opened during a few hundreds of ms. */
1049static int fd_open(BlockDriverState *bs)
1050{
1051 BDRVRawState *s = bs->opaque;
1052 int last_media_present;
1053
1054 if (s->type != FTYPE_FD)
1055 return 0;
1056 last_media_present = (s->fd >= 0);
5fafdf24 1057 if (s->fd >= 0 &&
19cb3738
FB
1058 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1059 close(s->fd);
1060 s->fd = -1;
53538725 1061 raw_close_fd_pool(s);
19cb3738
FB
1062#ifdef DEBUG_FLOPPY
1063 printf("Floppy closed\n");
1064#endif
1065 }
1066 if (s->fd < 0) {
5fafdf24 1067 if (s->fd_got_error &&
19cb3738
FB
1068 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1069#ifdef DEBUG_FLOPPY
1070 printf("No floppy (open delayed)\n");
1071#endif
1072 return -EIO;
1073 }
6dd2db52 1074 s->fd = open(bs->filename, s->fd_open_flags);
19cb3738
FB
1075 if (s->fd < 0) {
1076 s->fd_error_time = qemu_get_clock(rt_clock);
1077 s->fd_got_error = 1;
1078 if (last_media_present)
1079 s->fd_media_changed = 1;
1080#ifdef DEBUG_FLOPPY
1081 printf("No floppy\n");
1082#endif
1083 return -EIO;
1084 }
1085#ifdef DEBUG_FLOPPY
1086 printf("Floppy opened\n");
1087#endif
1088 }
1089 if (!last_media_present)
1090 s->fd_media_changed = 1;
1091 s->fd_open_time = qemu_get_clock(rt_clock);
1092 s->fd_got_error = 0;
1093 return 0;
1094}
19cb3738
FB
1095
1096static int raw_is_inserted(BlockDriverState *bs)
1097{
1098 BDRVRawState *s = bs->opaque;
1099 int ret;
1100
1101 switch(s->type) {
1102 case FTYPE_CD:
1103 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1104 if (ret == CDS_DISC_OK)
1105 return 1;
1106 else
1107 return 0;
1108 break;
1109 case FTYPE_FD:
1110 ret = fd_open(bs);
1111 return (ret >= 0);
1112 default:
1113 return 1;
1114 }
1115}
1116
1117/* currently only used by fdc.c, but a CD version would be good too */
1118static int raw_media_changed(BlockDriverState *bs)
1119{
1120 BDRVRawState *s = bs->opaque;
1121
1122 switch(s->type) {
1123 case FTYPE_FD:
1124 {
1125 int ret;
1126 /* XXX: we do not have a true media changed indication. It
1127 does not work if the floppy is changed without trying
1128 to read it */
1129 fd_open(bs);
1130 ret = s->fd_media_changed;
1131 s->fd_media_changed = 0;
1132#ifdef DEBUG_FLOPPY
1133 printf("Floppy changed=%d\n", ret);
1134#endif
1135 return ret;
1136 }
1137 default:
1138 return -ENOTSUP;
1139 }
1140}
1141
1142static int raw_eject(BlockDriverState *bs, int eject_flag)
1143{
1144 BDRVRawState *s = bs->opaque;
1145
1146 switch(s->type) {
1147 case FTYPE_CD:
1148 if (eject_flag) {
1149 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1150 perror("CDROMEJECT");
1151 } else {
1152 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1153 perror("CDROMEJECT");
1154 }
1155 break;
1156 case FTYPE_FD:
1157 {
1158 int fd;
1159 if (s->fd >= 0) {
1160 close(s->fd);
1161 s->fd = -1;
53538725 1162 raw_close_fd_pool(s);
19cb3738 1163 }
6dd2db52 1164 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
19cb3738
FB
1165 if (fd >= 0) {
1166 if (ioctl(fd, FDEJECT, 0) < 0)
1167 perror("FDEJECT");
1168 close(fd);
1169 }
1170 }
1171 break;
1172 default:
1173 return -ENOTSUP;
1174 }
1175 return 0;
1176}
1177
1178static int raw_set_locked(BlockDriverState *bs, int locked)
1179{
1180 BDRVRawState *s = bs->opaque;
1181
1182 switch(s->type) {
1183 case FTYPE_CD:
1184 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1185 /* Note: an error can happen if the distribution automatically
1186 mounts the CD-ROM */
1187 // perror("CDROM_LOCKDOOR");
1188 }
1189 break;
1190 default:
1191 return -ENOTSUP;
1192 }
1193 return 0;
1194}
1195
985a03b0
TS
1196static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1197{
1198 BDRVRawState *s = bs->opaque;
1199
1200 return ioctl(s->fd, req, buf);
1201}
19cb3738
FB
1202#else
1203
08af02e2
AL
1204static int fd_open(BlockDriverState *bs)
1205{
1206 return 0;
1207}
1208
19cb3738
FB
1209static int raw_is_inserted(BlockDriverState *bs)
1210{
1211 return 1;
1212}
1213
1214static int raw_media_changed(BlockDriverState *bs)
1215{
1216 return -ENOTSUP;
1217}
1218
1219static int raw_eject(BlockDriverState *bs, int eject_flag)
1220{
1221 return -ENOTSUP;
1222}
1223
1224static int raw_set_locked(BlockDriverState *bs, int locked)
1225{
1226 return -ENOTSUP;
1227}
1228
985a03b0
TS
1229static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1230{
1231 return -ENOTSUP;
1232}
19cb3738
FB
1233#endif /* !linux */
1234
1235BlockDriver bdrv_host_device = {
1236 "host_device",
1237 sizeof(BDRVRawState),
1238 NULL, /* no probe for protocols */
1239 hdev_open,
1240 NULL,
1241 NULL,
1242 raw_close,
1243 NULL,
1244 raw_flush,
3b46e624 1245
414f0dab 1246#ifdef CONFIG_AIO
19cb3738
FB
1247 .bdrv_aio_read = raw_aio_read,
1248 .bdrv_aio_write = raw_aio_write,
1249 .bdrv_aio_cancel = raw_aio_cancel,
1250 .aiocb_size = sizeof(RawAIOCB),
414f0dab 1251#endif
19cb3738
FB
1252 .bdrv_pread = raw_pread,
1253 .bdrv_pwrite = raw_pwrite,
1254 .bdrv_getlength = raw_getlength,
1255
1256 /* removable device support */
1257 .bdrv_is_inserted = raw_is_inserted,
1258 .bdrv_media_changed = raw_media_changed,
1259 .bdrv_eject = raw_eject,
1260 .bdrv_set_locked = raw_set_locked,
985a03b0
TS
1261 /* generic scsi device */
1262 .bdrv_ioctl = raw_ioctl,
19cb3738 1263};