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