]> git.proxmox.com Git - qemu.git/blob - block-raw-posix.c
Fix the build for --disable-aio
[qemu.git] / block-raw-posix.c
1 /*
2 * Block driver for RAW files (posix)
3 *
4 * Copyright (c) 2006 Fabrice Bellard
5 *
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 */
24 #include "qemu-common.h"
25 #include "qemu-timer.h"
26 #include "qemu-char.h"
27 #include "block_int.h"
28 #include <assert.h>
29 #ifdef CONFIG_AIO
30 #include "posix-aio-compat.h"
31 #endif
32
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__
46 #define _POSIX_PTHREAD_SEMANTICS 1
47 #include <signal.h>
48 #include <sys/dkio.h>
49 #endif
50 #ifdef __linux__
51 #include <sys/ioctl.h>
52 #include <linux/cdrom.h>
53 #include <linux/fd.h>
54 #endif
55 #ifdef __FreeBSD__
56 #include <signal.h>
57 #include <sys/disk.h>
58 #include <sys/cdio.h>
59 #endif
60
61 #ifdef __OpenBSD__
62 #include <sys/ioctl.h>
63 #include <sys/disklabel.h>
64 #include <sys/dkio.h>
65 #endif
66
67 #ifdef __DragonFly__
68 #include <sys/ioctl.h>
69 #include <sys/diskslice.h>
70 #endif
71
72 //#define DEBUG_FLOPPY
73
74 //#define DEBUG_BLOCK
75 #if defined(DEBUG_BLOCK)
76 #define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (qemu_log_enabled()) \
77 { qemu_log(formatCstr, ##args); qemu_log_flush(); } } while (0)
78 #else
79 #define DEBUG_BLOCK_PRINT(formatCstr, args...)
80 #endif
81
82 /* OS X does not have O_DSYNC */
83 #ifndef O_DSYNC
84 #define O_DSYNC O_SYNC
85 #endif
86
87 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
88 #ifndef O_DIRECT
89 #define O_DIRECT O_DSYNC
90 #endif
91
92 #define FTYPE_FILE 0
93 #define FTYPE_CD 1
94 #define FTYPE_FD 2
95
96 #define ALIGNED_BUFFER_SIZE (32 * 512)
97
98 /* if the FD is not accessed during that time (in ms), we try to
99 reopen it to see if the disk has been changed */
100 #define FD_OPEN_TIMEOUT 1000
101
102 typedef struct BDRVRawState {
103 int fd;
104 int type;
105 unsigned int lseek_err_cnt;
106 #if defined(__linux__)
107 /* linux floppy specific */
108 int fd_open_flags;
109 int64_t fd_open_time;
110 int64_t fd_error_time;
111 int fd_got_error;
112 int fd_media_changed;
113 #endif
114 #if defined(__FreeBSD__)
115 int cd_open_flags;
116 #endif
117 uint8_t* aligned_buf;
118 } BDRVRawState;
119
120 static int posix_aio_init(void);
121
122 static int fd_open(BlockDriverState *bs);
123
124 #if defined(__FreeBSD__)
125 static int cd_open(BlockDriverState *bs);
126 #endif
127
128 static int raw_is_inserted(BlockDriverState *bs);
129
130 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
131 {
132 BDRVRawState *s = bs->opaque;
133 int fd, open_flags, ret;
134
135 posix_aio_init();
136
137 s->lseek_err_cnt = 0;
138
139 open_flags = O_BINARY;
140 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
141 open_flags |= O_RDWR;
142 } else {
143 open_flags |= O_RDONLY;
144 bs->read_only = 1;
145 }
146 if (flags & BDRV_O_CREAT)
147 open_flags |= O_CREAT | O_TRUNC;
148
149 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
150 * and O_DIRECT for no caching. */
151 if ((flags & BDRV_O_NOCACHE))
152 open_flags |= O_DIRECT;
153 else if (!(flags & BDRV_O_CACHE_WB))
154 open_flags |= O_DSYNC;
155
156 s->type = FTYPE_FILE;
157
158 fd = open(filename, open_flags, 0644);
159 if (fd < 0) {
160 ret = -errno;
161 if (ret == -EROFS)
162 ret = -EACCES;
163 return ret;
164 }
165 s->fd = fd;
166 s->aligned_buf = NULL;
167 if ((flags & BDRV_O_NOCACHE)) {
168 s->aligned_buf = qemu_memalign(512, ALIGNED_BUFFER_SIZE);
169 if (s->aligned_buf == NULL) {
170 ret = -errno;
171 close(fd);
172 return ret;
173 }
174 }
175 return 0;
176 }
177
178 /* XXX: use host sector size if necessary with:
179 #ifdef DIOCGSECTORSIZE
180 {
181 unsigned int sectorsize = 512;
182 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
183 sectorsize > bufsize)
184 bufsize = sectorsize;
185 }
186 #endif
187 #ifdef CONFIG_COCOA
188 u_int32_t blockSize = 512;
189 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
190 bufsize = blockSize;
191 }
192 #endif
193 */
194
195 /*
196 * offset and count are in bytes, but must be multiples of 512 for files
197 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
198 *
199 * This function may be called without alignment if the caller ensures
200 * that O_DIRECT is not in effect.
201 */
202 static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
203 uint8_t *buf, int count)
204 {
205 BDRVRawState *s = bs->opaque;
206 int ret;
207
208 ret = fd_open(bs);
209 if (ret < 0)
210 return ret;
211
212 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
213 ++(s->lseek_err_cnt);
214 if(s->lseek_err_cnt <= 10) {
215 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
216 "] lseek failed : %d = %s\n",
217 s->fd, bs->filename, offset, buf, count,
218 bs->total_sectors, errno, strerror(errno));
219 }
220 return -1;
221 }
222 s->lseek_err_cnt=0;
223
224 ret = read(s->fd, buf, count);
225 if (ret == count)
226 goto label__raw_read__success;
227
228 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
229 "] read failed %d : %d = %s\n",
230 s->fd, bs->filename, offset, buf, count,
231 bs->total_sectors, ret, errno, strerror(errno));
232
233 /* Try harder for CDrom. */
234 if (bs->type == BDRV_TYPE_CDROM) {
235 lseek(s->fd, offset, SEEK_SET);
236 ret = read(s->fd, buf, count);
237 if (ret == count)
238 goto label__raw_read__success;
239 lseek(s->fd, offset, SEEK_SET);
240 ret = read(s->fd, buf, count);
241 if (ret == count)
242 goto label__raw_read__success;
243
244 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
245 "] retry read failed %d : %d = %s\n",
246 s->fd, bs->filename, offset, buf, count,
247 bs->total_sectors, ret, errno, strerror(errno));
248 }
249
250 label__raw_read__success:
251
252 return ret;
253 }
254
255 /*
256 * offset and count are in bytes, but must be multiples of 512 for files
257 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
258 *
259 * This function may be called without alignment if the caller ensures
260 * that O_DIRECT is not in effect.
261 */
262 static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
263 const uint8_t *buf, int count)
264 {
265 BDRVRawState *s = bs->opaque;
266 int ret;
267
268 ret = fd_open(bs);
269 if (ret < 0)
270 return -errno;
271
272 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
273 ++(s->lseek_err_cnt);
274 if(s->lseek_err_cnt) {
275 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
276 PRId64 "] lseek failed : %d = %s\n",
277 s->fd, bs->filename, offset, buf, count,
278 bs->total_sectors, errno, strerror(errno));
279 }
280 return -EIO;
281 }
282 s->lseek_err_cnt = 0;
283
284 ret = write(s->fd, buf, count);
285 if (ret == count)
286 goto label__raw_write__success;
287
288 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
289 "] write failed %d : %d = %s\n",
290 s->fd, bs->filename, offset, buf, count,
291 bs->total_sectors, ret, errno, strerror(errno));
292
293 label__raw_write__success:
294
295 return (ret < 0) ? -errno : ret;
296 }
297
298
299 /*
300 * offset and count are in bytes and possibly not aligned. For files opened
301 * with O_DIRECT, necessary alignments are ensured before calling
302 * raw_pread_aligned to do the actual read.
303 */
304 static int raw_pread(BlockDriverState *bs, int64_t offset,
305 uint8_t *buf, int count)
306 {
307 BDRVRawState *s = bs->opaque;
308 int size, ret, shift, sum;
309
310 sum = 0;
311
312 if (s->aligned_buf != NULL) {
313
314 if (offset & 0x1ff) {
315 /* align offset on a 512 bytes boundary */
316
317 shift = offset & 0x1ff;
318 size = (shift + count + 0x1ff) & ~0x1ff;
319 if (size > ALIGNED_BUFFER_SIZE)
320 size = ALIGNED_BUFFER_SIZE;
321 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, size);
322 if (ret < 0)
323 return ret;
324
325 size = 512 - shift;
326 if (size > count)
327 size = count;
328 memcpy(buf, s->aligned_buf + shift, size);
329
330 buf += size;
331 offset += size;
332 count -= size;
333 sum += size;
334
335 if (count == 0)
336 return sum;
337 }
338 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
339
340 /* read on aligned buffer */
341
342 while (count) {
343
344 size = (count + 0x1ff) & ~0x1ff;
345 if (size > ALIGNED_BUFFER_SIZE)
346 size = ALIGNED_BUFFER_SIZE;
347
348 ret = raw_pread_aligned(bs, offset, s->aligned_buf, size);
349 if (ret < 0)
350 return ret;
351
352 size = ret;
353 if (size > count)
354 size = count;
355
356 memcpy(buf, s->aligned_buf, size);
357
358 buf += size;
359 offset += size;
360 count -= size;
361 sum += size;
362 }
363
364 return sum;
365 }
366 }
367
368 return raw_pread_aligned(bs, offset, buf, count) + sum;
369 }
370
371 static int raw_read(BlockDriverState *bs, int64_t sector_num,
372 uint8_t *buf, int nb_sectors)
373 {
374 int ret;
375
376 ret = raw_pread(bs, sector_num * 512, buf, nb_sectors * 512);
377 if (ret == (nb_sectors * 512))
378 ret = 0;
379 return ret;
380 }
381
382 /*
383 * offset and count are in bytes and possibly not aligned. For files opened
384 * with O_DIRECT, necessary alignments are ensured before calling
385 * raw_pwrite_aligned to do the actual write.
386 */
387 static int raw_pwrite(BlockDriverState *bs, int64_t offset,
388 const uint8_t *buf, int count)
389 {
390 BDRVRawState *s = bs->opaque;
391 int size, ret, shift, sum;
392
393 sum = 0;
394
395 if (s->aligned_buf != NULL) {
396
397 if (offset & 0x1ff) {
398 /* align offset on a 512 bytes boundary */
399 shift = offset & 0x1ff;
400 ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);
401 if (ret < 0)
402 return ret;
403
404 size = 512 - shift;
405 if (size > count)
406 size = count;
407 memcpy(s->aligned_buf + shift, buf, size);
408
409 ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);
410 if (ret < 0)
411 return ret;
412
413 buf += size;
414 offset += size;
415 count -= size;
416 sum += size;
417
418 if (count == 0)
419 return sum;
420 }
421 if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {
422
423 while ((size = (count & ~0x1ff)) != 0) {
424
425 if (size > ALIGNED_BUFFER_SIZE)
426 size = ALIGNED_BUFFER_SIZE;
427
428 memcpy(s->aligned_buf, buf, size);
429
430 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);
431 if (ret < 0)
432 return ret;
433
434 buf += ret;
435 offset += ret;
436 count -= ret;
437 sum += ret;
438 }
439 /* here, count < 512 because (count & ~0x1ff) == 0 */
440 if (count) {
441 ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);
442 if (ret < 0)
443 return ret;
444 memcpy(s->aligned_buf, buf, count);
445
446 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);
447 if (ret < 0)
448 return ret;
449 if (count < ret)
450 ret = count;
451
452 sum += ret;
453 }
454 return sum;
455 }
456 }
457 return raw_pwrite_aligned(bs, offset, buf, count) + sum;
458 }
459
460 static int raw_write(BlockDriverState *bs, int64_t sector_num,
461 const uint8_t *buf, int nb_sectors)
462 {
463 int ret;
464 ret = raw_pwrite(bs, sector_num * 512, buf, nb_sectors * 512);
465 if (ret == (nb_sectors * 512))
466 ret = 0;
467 return ret;
468 }
469
470 #ifdef CONFIG_AIO
471 /***********************************************************/
472 /* Unix AIO using POSIX AIO */
473
474 typedef struct RawAIOCB {
475 BlockDriverAIOCB common;
476 struct qemu_paiocb aiocb;
477 struct RawAIOCB *next;
478 int ret;
479 } RawAIOCB;
480
481 typedef struct PosixAioState
482 {
483 int rfd, wfd;
484 RawAIOCB *first_aio;
485 } PosixAioState;
486
487 static void posix_aio_read(void *opaque)
488 {
489 PosixAioState *s = opaque;
490 RawAIOCB *acb, **pacb;
491 int ret;
492 ssize_t len;
493
494 /* read all bytes from signal pipe */
495 for (;;) {
496 char bytes[16];
497
498 len = read(s->rfd, bytes, sizeof(bytes));
499 if (len == -1 && errno == EINTR)
500 continue; /* try again */
501 if (len == sizeof(bytes))
502 continue; /* more to read */
503 break;
504 }
505
506 for(;;) {
507 pacb = &s->first_aio;
508 for(;;) {
509 acb = *pacb;
510 if (!acb)
511 goto the_end;
512 ret = qemu_paio_error(&acb->aiocb);
513 if (ret == ECANCELED) {
514 /* remove the request */
515 *pacb = acb->next;
516 qemu_aio_release(acb);
517 } else if (ret != EINPROGRESS) {
518 /* end of aio */
519 if (ret == 0) {
520 ret = qemu_paio_return(&acb->aiocb);
521 if (ret == acb->aiocb.aio_nbytes)
522 ret = 0;
523 else
524 ret = -EINVAL;
525 } else {
526 ret = -ret;
527 }
528 /* remove the request */
529 *pacb = acb->next;
530 /* call the callback */
531 acb->common.cb(acb->common.opaque, ret);
532 qemu_aio_release(acb);
533 break;
534 } else {
535 pacb = &acb->next;
536 }
537 }
538 }
539 the_end: ;
540 }
541
542 static int posix_aio_flush(void *opaque)
543 {
544 PosixAioState *s = opaque;
545 return !!s->first_aio;
546 }
547
548 static PosixAioState *posix_aio_state;
549
550 static void aio_signal_handler(int signum)
551 {
552 if (posix_aio_state) {
553 char byte = 0;
554
555 write(posix_aio_state->wfd, &byte, sizeof(byte));
556 }
557
558 qemu_service_io();
559 }
560
561 static int posix_aio_init(void)
562 {
563 struct sigaction act;
564 PosixAioState *s;
565 int fds[2];
566 struct qemu_paioinit ai;
567
568 if (posix_aio_state)
569 return 0;
570
571 s = qemu_malloc(sizeof(PosixAioState));
572
573 sigfillset(&act.sa_mask);
574 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
575 act.sa_handler = aio_signal_handler;
576 sigaction(SIGUSR2, &act, NULL);
577
578 s->first_aio = NULL;
579 if (pipe(fds) == -1) {
580 fprintf(stderr, "failed to create pipe\n");
581 return -errno;
582 }
583
584 s->rfd = fds[0];
585 s->wfd = fds[1];
586
587 fcntl(s->rfd, F_SETFL, O_NONBLOCK);
588 fcntl(s->wfd, F_SETFL, O_NONBLOCK);
589
590 qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);
591
592 memset(&ai, 0, sizeof(ai));
593 ai.aio_threads = 64;
594 ai.aio_num = 64;
595 qemu_paio_init(&ai);
596
597 posix_aio_state = s;
598
599 return 0;
600 }
601
602 static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
603 int64_t sector_num, uint8_t *buf, int nb_sectors,
604 BlockDriverCompletionFunc *cb, void *opaque)
605 {
606 BDRVRawState *s = bs->opaque;
607 RawAIOCB *acb;
608
609 if (fd_open(bs) < 0)
610 return NULL;
611
612 acb = qemu_aio_get(bs, cb, opaque);
613 if (!acb)
614 return NULL;
615 acb->aiocb.aio_fildes = s->fd;
616 acb->aiocb.ev_signo = SIGUSR2;
617 acb->aiocb.aio_buf = buf;
618 if (nb_sectors < 0)
619 acb->aiocb.aio_nbytes = -nb_sectors;
620 else
621 acb->aiocb.aio_nbytes = nb_sectors * 512;
622 acb->aiocb.aio_offset = sector_num * 512;
623 acb->next = posix_aio_state->first_aio;
624 posix_aio_state->first_aio = acb;
625 return acb;
626 }
627
628 static void raw_aio_em_cb(void* opaque)
629 {
630 RawAIOCB *acb = opaque;
631 acb->common.cb(acb->common.opaque, acb->ret);
632 qemu_aio_release(acb);
633 }
634
635 static void raw_aio_remove(RawAIOCB *acb)
636 {
637 RawAIOCB **pacb;
638
639 /* remove the callback from the queue */
640 pacb = &posix_aio_state->first_aio;
641 for(;;) {
642 if (*pacb == NULL) {
643 fprintf(stderr, "raw_aio_remove: aio request not found!\n");
644 break;
645 } else if (*pacb == acb) {
646 *pacb = acb->next;
647 qemu_aio_release(acb);
648 break;
649 }
650 pacb = &(*pacb)->next;
651 }
652 }
653
654 static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
655 int64_t sector_num, uint8_t *buf, int nb_sectors,
656 BlockDriverCompletionFunc *cb, void *opaque)
657 {
658 RawAIOCB *acb;
659
660 /*
661 * If O_DIRECT is used and the buffer is not aligned fall back
662 * to synchronous IO.
663 */
664 BDRVRawState *s = bs->opaque;
665
666 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
667 QEMUBH *bh;
668 acb = qemu_aio_get(bs, cb, opaque);
669 acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
670 bh = qemu_bh_new(raw_aio_em_cb, acb);
671 qemu_bh_schedule(bh);
672 return &acb->common;
673 }
674
675 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
676 if (!acb)
677 return NULL;
678 if (qemu_paio_read(&acb->aiocb) < 0) {
679 raw_aio_remove(acb);
680 return NULL;
681 }
682 return &acb->common;
683 }
684
685 static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
686 int64_t sector_num, const uint8_t *buf, int nb_sectors,
687 BlockDriverCompletionFunc *cb, void *opaque)
688 {
689 RawAIOCB *acb;
690
691 /*
692 * If O_DIRECT is used and the buffer is not aligned fall back
693 * to synchronous IO.
694 */
695 BDRVRawState *s = bs->opaque;
696
697 if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {
698 QEMUBH *bh;
699 acb = qemu_aio_get(bs, cb, opaque);
700 acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
701 bh = qemu_bh_new(raw_aio_em_cb, acb);
702 qemu_bh_schedule(bh);
703 return &acb->common;
704 }
705
706 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
707 if (!acb)
708 return NULL;
709 if (qemu_paio_write(&acb->aiocb) < 0) {
710 raw_aio_remove(acb);
711 return NULL;
712 }
713 return &acb->common;
714 }
715
716 static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
717 {
718 int ret;
719 RawAIOCB *acb = (RawAIOCB *)blockacb;
720
721 ret = qemu_paio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
722 if (ret == QEMU_PAIO_NOTCANCELED) {
723 /* fail safe: if the aio could not be canceled, we wait for
724 it */
725 while (qemu_paio_error(&acb->aiocb) == EINPROGRESS);
726 }
727
728 raw_aio_remove(acb);
729 }
730 #else /* CONFIG_AIO */
731 static int posix_aio_init(void)
732 {
733 return 0;
734 }
735 #endif /* CONFIG_AIO */
736
737
738 static void raw_close(BlockDriverState *bs)
739 {
740 BDRVRawState *s = bs->opaque;
741 if (s->fd >= 0) {
742 close(s->fd);
743 s->fd = -1;
744 if (s->aligned_buf != NULL)
745 qemu_free(s->aligned_buf);
746 }
747 }
748
749 static int raw_truncate(BlockDriverState *bs, int64_t offset)
750 {
751 BDRVRawState *s = bs->opaque;
752 if (s->type != FTYPE_FILE)
753 return -ENOTSUP;
754 if (ftruncate(s->fd, offset) < 0)
755 return -errno;
756 return 0;
757 }
758
759 #ifdef __OpenBSD__
760 static int64_t raw_getlength(BlockDriverState *bs)
761 {
762 BDRVRawState *s = bs->opaque;
763 int fd = s->fd;
764 struct stat st;
765
766 if (fstat(fd, &st))
767 return -1;
768 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
769 struct disklabel dl;
770
771 if (ioctl(fd, DIOCGDINFO, &dl))
772 return -1;
773 return (uint64_t)dl.d_secsize *
774 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
775 } else
776 return st.st_size;
777 }
778 #else /* !__OpenBSD__ */
779 static int64_t raw_getlength(BlockDriverState *bs)
780 {
781 BDRVRawState *s = bs->opaque;
782 int fd = s->fd;
783 int64_t size;
784 #ifdef HOST_BSD
785 struct stat sb;
786 #ifdef __FreeBSD__
787 int reopened = 0;
788 #endif
789 #endif
790 #ifdef __sun__
791 struct dk_minfo minfo;
792 int rv;
793 #endif
794 int ret;
795
796 ret = fd_open(bs);
797 if (ret < 0)
798 return ret;
799
800 #ifdef HOST_BSD
801 #ifdef __FreeBSD__
802 again:
803 #endif
804 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
805 #ifdef DIOCGMEDIASIZE
806 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
807 #elif defined(DIOCGPART)
808 {
809 struct partinfo pi;
810 if (ioctl(fd, DIOCGPART, &pi) == 0)
811 size = pi.media_size;
812 else
813 size = 0;
814 }
815 if (size == 0)
816 #endif
817 #ifdef CONFIG_COCOA
818 size = LONG_LONG_MAX;
819 #else
820 size = lseek(fd, 0LL, SEEK_END);
821 #endif
822 #ifdef __FreeBSD__
823 switch(s->type) {
824 case FTYPE_CD:
825 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
826 if (size == 2048LL * (unsigned)-1)
827 size = 0;
828 /* XXX no disc? maybe we need to reopen... */
829 if (size <= 0 && !reopened && cd_open(bs) >= 0) {
830 reopened = 1;
831 goto again;
832 }
833 }
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 }
851 return size;
852 }
853 #endif
854
855 static 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
863 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
864 0644);
865 if (fd < 0)
866 return -EIO;
867 ftruncate(fd, total_size * 512);
868 close(fd);
869 return 0;
870 }
871
872 static void raw_flush(BlockDriverState *bs)
873 {
874 BDRVRawState *s = bs->opaque;
875 fsync(s->fd);
876 }
877
878 BlockDriver 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,
888
889 #ifdef CONFIG_AIO
890 .bdrv_aio_read = raw_aio_read,
891 .bdrv_aio_write = raw_aio_write,
892 .bdrv_aio_cancel = raw_aio_cancel,
893 .aiocb_size = sizeof(RawAIOCB),
894 #endif
895
896 .bdrv_read = raw_read,
897 .bdrv_write = raw_write,
898 .bdrv_truncate = raw_truncate,
899 .bdrv_getlength = raw_getlength,
900 };
901
902 /***********************************************/
903 /* host device */
904
905 #ifdef CONFIG_COCOA
906 static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
907 static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
908
909 kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
910 {
911 kern_return_t kernResult;
912 mach_port_t masterPort;
913 CFMutableDictionaryRef classesToMatch;
914
915 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
916 if ( KERN_SUCCESS != kernResult ) {
917 printf( "IOMasterPort returned %d\n", kernResult );
918 }
919
920 classesToMatch = IOServiceMatching( kIOCDMediaClass );
921 if ( classesToMatch == NULL ) {
922 printf( "IOServiceMatching returned a NULL dictionary.\n" );
923 } else {
924 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
925 }
926 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
927 if ( KERN_SUCCESS != kernResult )
928 {
929 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
930 }
931
932 return kernResult;
933 }
934
935 kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
936 {
937 io_object_t nextMedia;
938 kern_return_t kernResult = KERN_FAILURE;
939 *bsdPath = '\0';
940 nextMedia = IOIteratorNext( mediaIterator );
941 if ( nextMedia )
942 {
943 CFTypeRef bsdPathAsCFString;
944 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
945 if ( bsdPathAsCFString ) {
946 size_t devPathLength;
947 strcpy( bsdPath, _PATH_DEV );
948 strcat( bsdPath, "r" );
949 devPathLength = strlen( bsdPath );
950 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
951 kernResult = KERN_SUCCESS;
952 }
953 CFRelease( bsdPathAsCFString );
954 }
955 IOObjectRelease( nextMedia );
956 }
957
958 return kernResult;
959 }
960
961 #endif
962
963 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
964 {
965 BDRVRawState *s = bs->opaque;
966 int fd, open_flags, ret;
967
968 posix_aio_init();
969
970 #ifdef CONFIG_COCOA
971 if (strstart(filename, "/dev/cdrom", NULL)) {
972 kern_return_t kernResult;
973 io_iterator_t mediaIterator;
974 char bsdPath[ MAXPATHLEN ];
975 int fd;
976
977 kernResult = FindEjectableCDMedia( &mediaIterator );
978 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
979
980 if ( bsdPath[ 0 ] != '\0' ) {
981 strcat(bsdPath,"s0");
982 /* some CDs don't have a partition 0 */
983 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
984 if (fd < 0) {
985 bsdPath[strlen(bsdPath)-1] = '1';
986 } else {
987 close(fd);
988 }
989 filename = bsdPath;
990 }
991
992 if ( mediaIterator )
993 IOObjectRelease( mediaIterator );
994 }
995 #endif
996 open_flags = O_BINARY;
997 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
998 open_flags |= O_RDWR;
999 } else {
1000 open_flags |= O_RDONLY;
1001 bs->read_only = 1;
1002 }
1003 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
1004 * and O_DIRECT for no caching. */
1005 if ((flags & BDRV_O_NOCACHE))
1006 open_flags |= O_DIRECT;
1007 else if (!(flags & BDRV_O_CACHE_WB))
1008 open_flags |= O_DSYNC;
1009
1010 s->type = FTYPE_FILE;
1011 #if defined(__linux__)
1012 if (strstart(filename, "/dev/cd", NULL)) {
1013 /* open will not fail even if no CD is inserted */
1014 open_flags |= O_NONBLOCK;
1015 s->type = FTYPE_CD;
1016 } else if (strstart(filename, "/dev/fd", NULL)) {
1017 s->type = FTYPE_FD;
1018 s->fd_open_flags = open_flags;
1019 /* open will not fail even if no floppy is inserted */
1020 open_flags |= O_NONBLOCK;
1021 #ifdef CONFIG_AIO
1022 } else if (strstart(filename, "/dev/sg", NULL)) {
1023 bs->sg = 1;
1024 #endif
1025 }
1026 #endif
1027 #if defined(__FreeBSD__)
1028 if (strstart(filename, "/dev/cd", NULL) ||
1029 strstart(filename, "/dev/acd", NULL)) {
1030 s->type = FTYPE_CD;
1031 s->cd_open_flags = open_flags;
1032 }
1033 #endif
1034 s->fd = -1;
1035 fd = open(filename, open_flags, 0644);
1036 if (fd < 0) {
1037 ret = -errno;
1038 if (ret == -EROFS)
1039 ret = -EACCES;
1040 return ret;
1041 }
1042 s->fd = fd;
1043 #if defined(__FreeBSD__)
1044 /* make sure the door isnt locked at this time */
1045 if (s->type == FTYPE_CD)
1046 ioctl (s->fd, CDIOCALLOW);
1047 #endif
1048 #if defined(__linux__)
1049 /* close fd so that we can reopen it as needed */
1050 if (s->type == FTYPE_FD) {
1051 close(s->fd);
1052 s->fd = -1;
1053 s->fd_media_changed = 1;
1054 }
1055 #endif
1056 return 0;
1057 }
1058
1059 #if defined(__linux__)
1060 /* Note: we do not have a reliable method to detect if the floppy is
1061 present. The current method is to try to open the floppy at every
1062 I/O and to keep it opened during a few hundreds of ms. */
1063 static int fd_open(BlockDriverState *bs)
1064 {
1065 BDRVRawState *s = bs->opaque;
1066 int last_media_present;
1067
1068 if (s->type != FTYPE_FD)
1069 return 0;
1070 last_media_present = (s->fd >= 0);
1071 if (s->fd >= 0 &&
1072 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
1073 close(s->fd);
1074 s->fd = -1;
1075 #ifdef DEBUG_FLOPPY
1076 printf("Floppy closed\n");
1077 #endif
1078 }
1079 if (s->fd < 0) {
1080 if (s->fd_got_error &&
1081 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
1082 #ifdef DEBUG_FLOPPY
1083 printf("No floppy (open delayed)\n");
1084 #endif
1085 return -EIO;
1086 }
1087 s->fd = open(bs->filename, s->fd_open_flags);
1088 if (s->fd < 0) {
1089 s->fd_error_time = qemu_get_clock(rt_clock);
1090 s->fd_got_error = 1;
1091 if (last_media_present)
1092 s->fd_media_changed = 1;
1093 #ifdef DEBUG_FLOPPY
1094 printf("No floppy\n");
1095 #endif
1096 return -EIO;
1097 }
1098 #ifdef DEBUG_FLOPPY
1099 printf("Floppy opened\n");
1100 #endif
1101 }
1102 if (!last_media_present)
1103 s->fd_media_changed = 1;
1104 s->fd_open_time = qemu_get_clock(rt_clock);
1105 s->fd_got_error = 0;
1106 return 0;
1107 }
1108
1109 static int raw_is_inserted(BlockDriverState *bs)
1110 {
1111 BDRVRawState *s = bs->opaque;
1112 int ret;
1113
1114 switch(s->type) {
1115 case FTYPE_CD:
1116 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
1117 if (ret == CDS_DISC_OK)
1118 return 1;
1119 else
1120 return 0;
1121 break;
1122 case FTYPE_FD:
1123 ret = fd_open(bs);
1124 return (ret >= 0);
1125 default:
1126 return 1;
1127 }
1128 }
1129
1130 /* currently only used by fdc.c, but a CD version would be good too */
1131 static int raw_media_changed(BlockDriverState *bs)
1132 {
1133 BDRVRawState *s = bs->opaque;
1134
1135 switch(s->type) {
1136 case FTYPE_FD:
1137 {
1138 int ret;
1139 /* XXX: we do not have a true media changed indication. It
1140 does not work if the floppy is changed without trying
1141 to read it */
1142 fd_open(bs);
1143 ret = s->fd_media_changed;
1144 s->fd_media_changed = 0;
1145 #ifdef DEBUG_FLOPPY
1146 printf("Floppy changed=%d\n", ret);
1147 #endif
1148 return ret;
1149 }
1150 default:
1151 return -ENOTSUP;
1152 }
1153 }
1154
1155 static int raw_eject(BlockDriverState *bs, int eject_flag)
1156 {
1157 BDRVRawState *s = bs->opaque;
1158
1159 switch(s->type) {
1160 case FTYPE_CD:
1161 if (eject_flag) {
1162 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
1163 perror("CDROMEJECT");
1164 } else {
1165 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
1166 perror("CDROMEJECT");
1167 }
1168 break;
1169 case FTYPE_FD:
1170 {
1171 int fd;
1172 if (s->fd >= 0) {
1173 close(s->fd);
1174 s->fd = -1;
1175 }
1176 fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);
1177 if (fd >= 0) {
1178 if (ioctl(fd, FDEJECT, 0) < 0)
1179 perror("FDEJECT");
1180 close(fd);
1181 }
1182 }
1183 break;
1184 default:
1185 return -ENOTSUP;
1186 }
1187 return 0;
1188 }
1189
1190 static int raw_set_locked(BlockDriverState *bs, int locked)
1191 {
1192 BDRVRawState *s = bs->opaque;
1193
1194 switch(s->type) {
1195 case FTYPE_CD:
1196 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
1197 /* Note: an error can happen if the distribution automatically
1198 mounts the CD-ROM */
1199 // perror("CDROM_LOCKDOOR");
1200 }
1201 break;
1202 default:
1203 return -ENOTSUP;
1204 }
1205 return 0;
1206 }
1207
1208 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1209 {
1210 BDRVRawState *s = bs->opaque;
1211
1212 return ioctl(s->fd, req, buf);
1213 }
1214
1215 #ifdef CONFIG_AIO
1216 static BlockDriverAIOCB *raw_aio_ioctl(BlockDriverState *bs,
1217 unsigned long int req, void *buf,
1218 BlockDriverCompletionFunc *cb, void *opaque)
1219 {
1220 RawAIOCB *acb;
1221
1222 acb = raw_aio_setup(bs, 0, buf, 0, cb, opaque);
1223 if (!acb)
1224 return NULL;
1225
1226 acb->aiocb.aio_ioctl_cmd = req;
1227 if (qemu_paio_ioctl(&acb->aiocb) < 0) {
1228 raw_aio_remove(acb);
1229 return NULL;
1230 }
1231
1232 return &acb->common;
1233 }
1234 #endif
1235
1236 #elif defined(__FreeBSD__)
1237
1238 static int fd_open(BlockDriverState *bs)
1239 {
1240 BDRVRawState *s = bs->opaque;
1241
1242 /* this is just to ensure s->fd is sane (its called by io ops) */
1243 if (s->fd >= 0)
1244 return 0;
1245 return -EIO;
1246 }
1247
1248 static int cd_open(BlockDriverState *bs)
1249 {
1250 #if defined(__FreeBSD__)
1251 BDRVRawState *s = bs->opaque;
1252 int fd;
1253
1254 switch(s->type) {
1255 case FTYPE_CD:
1256 /* XXX force reread of possibly changed/newly loaded disc,
1257 * FreeBSD seems to not notice sometimes... */
1258 if (s->fd >= 0)
1259 close (s->fd);
1260 fd = open(bs->filename, s->cd_open_flags, 0644);
1261 if (fd < 0) {
1262 s->fd = -1;
1263 return -EIO;
1264 }
1265 s->fd = fd;
1266 /* make sure the door isnt locked at this time */
1267 ioctl (s->fd, CDIOCALLOW);
1268 }
1269 #endif
1270 return 0;
1271 }
1272
1273 static int raw_is_inserted(BlockDriverState *bs)
1274 {
1275 BDRVRawState *s = bs->opaque;
1276
1277 switch(s->type) {
1278 case FTYPE_CD:
1279 return (raw_getlength(bs) > 0);
1280 case FTYPE_FD:
1281 /* XXX handle this */
1282 /* FALLTHRU */
1283 default:
1284 return 1;
1285 }
1286 }
1287
1288 static int raw_media_changed(BlockDriverState *bs)
1289 {
1290 return -ENOTSUP;
1291 }
1292
1293 static int raw_eject(BlockDriverState *bs, int eject_flag)
1294 {
1295 BDRVRawState *s = bs->opaque;
1296
1297 switch(s->type) {
1298 case FTYPE_CD:
1299 if (s->fd < 0)
1300 return -ENOTSUP;
1301 (void) ioctl (s->fd, CDIOCALLOW);
1302 if (eject_flag) {
1303 if (ioctl (s->fd, CDIOCEJECT) < 0)
1304 perror("CDIOCEJECT");
1305 } else {
1306 if (ioctl (s->fd, CDIOCCLOSE) < 0)
1307 perror("CDIOCCLOSE");
1308 }
1309 if (cd_open(bs) < 0)
1310 return -ENOTSUP;
1311 break;
1312 case FTYPE_FD:
1313 /* XXX handle this */
1314 /* FALLTHRU */
1315 default:
1316 return -ENOTSUP;
1317 }
1318 return 0;
1319 }
1320
1321 static int raw_set_locked(BlockDriverState *bs, int locked)
1322 {
1323 BDRVRawState *s = bs->opaque;
1324
1325 switch(s->type) {
1326 case FTYPE_CD:
1327 if (s->fd < 0)
1328 return -ENOTSUP;
1329 if (ioctl (s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
1330 /* Note: an error can happen if the distribution automatically
1331 mounts the CD-ROM */
1332 // perror("CDROM_LOCKDOOR");
1333 }
1334 break;
1335 default:
1336 return -ENOTSUP;
1337 }
1338 return 0;
1339 }
1340
1341 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1342 {
1343 return -ENOTSUP;
1344 }
1345 #else /* !linux && !FreeBSD */
1346
1347 static int fd_open(BlockDriverState *bs)
1348 {
1349 return 0;
1350 }
1351
1352 static int raw_is_inserted(BlockDriverState *bs)
1353 {
1354 return 1;
1355 }
1356
1357 static int raw_media_changed(BlockDriverState *bs)
1358 {
1359 return -ENOTSUP;
1360 }
1361
1362 static int raw_eject(BlockDriverState *bs, int eject_flag)
1363 {
1364 return -ENOTSUP;
1365 }
1366
1367 static int raw_set_locked(BlockDriverState *bs, int locked)
1368 {
1369 return -ENOTSUP;
1370 }
1371
1372 static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1373 {
1374 return -ENOTSUP;
1375 }
1376
1377 static BlockDriverAIOCB *raw_aio_ioctl(BlockDriverState *bs,
1378 unsigned long int req, void *buf,
1379 BlockDriverCompletionFunc *cb, void *opaque)
1380 {
1381 return NULL;
1382 }
1383 #endif /* !linux && !FreeBSD */
1384
1385 #if defined(__linux__) || defined(__FreeBSD__)
1386 static int hdev_create(const char *filename, int64_t total_size,
1387 const char *backing_file, int flags)
1388 {
1389 int fd;
1390 int ret = 0;
1391 struct stat stat_buf;
1392
1393 if (flags || backing_file)
1394 return -ENOTSUP;
1395
1396 fd = open(filename, O_WRONLY | O_BINARY);
1397 if (fd < 0)
1398 return -EIO;
1399
1400 if (fstat(fd, &stat_buf) < 0)
1401 ret = -EIO;
1402 else if (!S_ISBLK(stat_buf.st_mode))
1403 ret = -EIO;
1404 else if (lseek(fd, 0, SEEK_END) < total_size * 512)
1405 ret = -ENOSPC;
1406
1407 close(fd);
1408 return ret;
1409 }
1410
1411 #else /* !(linux || freebsd) */
1412
1413 static int hdev_create(const char *filename, int64_t total_size,
1414 const char *backing_file, int flags)
1415 {
1416 return -ENOTSUP;
1417 }
1418 #endif
1419
1420 BlockDriver bdrv_host_device = {
1421 .format_name = "host_device",
1422 .instance_size = sizeof(BDRVRawState),
1423 .bdrv_open = hdev_open,
1424 .bdrv_close = raw_close,
1425 .bdrv_create = hdev_create,
1426 .bdrv_flush = raw_flush,
1427
1428 #ifdef CONFIG_AIO
1429 .bdrv_aio_read = raw_aio_read,
1430 .bdrv_aio_write = raw_aio_write,
1431 .bdrv_aio_cancel = raw_aio_cancel,
1432 .aiocb_size = sizeof(RawAIOCB),
1433 #endif
1434
1435 .bdrv_read = raw_read,
1436 .bdrv_write = raw_write,
1437 .bdrv_getlength = raw_getlength,
1438
1439 /* removable device support */
1440 .bdrv_is_inserted = raw_is_inserted,
1441 .bdrv_media_changed = raw_media_changed,
1442 .bdrv_eject = raw_eject,
1443 .bdrv_set_locked = raw_set_locked,
1444 /* generic scsi device */
1445 .bdrv_ioctl = raw_ioctl,
1446 #ifdef CONFIG_AIO
1447 .bdrv_aio_ioctl = raw_aio_ioctl,
1448 #endif
1449 };