]> git.proxmox.com Git - qemu.git/blame - block-raw-posix.c
CRIS: More TCG conversion.
[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
PB
25#ifndef QEMU_IMG
26#include "qemu-timer.h"
ae5fc450 27#include "exec-all.h"
faf07963 28#endif
83f64091
FB
29#include "block_int.h"
30#include <assert.h>
83f64091
FB
31#include <aio.h>
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
TS
55#ifdef __FreeBSD__
56#include <sys/disk.h>
57#endif
83f64091 58
19cb3738 59//#define DEBUG_FLOPPY
83f64091 60
faf07963
PB
61//#define DEBUG_BLOCK
62#if defined(DEBUG_BLOCK) && !defined(QEMU_IMG)
a50a6282 63#define DEBUG_BLOCK_PRINT(formatCstr, args...) do { if (loglevel != 0) \
2e03286b 64 { fprintf(logfile, formatCstr, ##args); fflush(logfile); } } while (0)
8c05dbf9
TS
65#else
66#define DEBUG_BLOCK_PRINT(formatCstr, args...)
67#endif
68
19cb3738
FB
69#define FTYPE_FILE 0
70#define FTYPE_CD 1
71#define FTYPE_FD 2
83f64091 72
19cb3738
FB
73/* if the FD is not accessed during that time (in ms), we try to
74 reopen it to see if the disk has been changed */
75#define FD_OPEN_TIMEOUT 1000
83f64091 76
19cb3738
FB
77typedef struct BDRVRawState {
78 int fd;
79 int type;
adcbebaa 80 int open_flags;
8c05dbf9 81 unsigned int lseek_err_cnt;
19cb3738
FB
82#if defined(__linux__)
83 /* linux floppy specific */
19cb3738
FB
84 int64_t fd_open_time;
85 int64_t fd_error_time;
86 int fd_got_error;
87 int fd_media_changed;
83f64091 88#endif
19cb3738
FB
89} BDRVRawState;
90
91static int fd_open(BlockDriverState *bs);
83f64091
FB
92
93static int raw_open(BlockDriverState *bs, const char *filename, int flags)
94{
95 BDRVRawState *s = bs->opaque;
19cb3738 96 int fd, open_flags, ret;
83f64091 97
8c05dbf9
TS
98 s->lseek_err_cnt = 0;
99
83f64091
FB
100 open_flags = O_BINARY;
101 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
102 open_flags |= O_RDWR;
103 } else {
104 open_flags |= O_RDONLY;
105 bs->read_only = 1;
106 }
107 if (flags & BDRV_O_CREAT)
108 open_flags |= O_CREAT | O_TRUNC;
33f00271
AZ
109#ifdef O_DIRECT
110 if (flags & BDRV_O_DIRECT)
111 open_flags |= O_DIRECT;
112#endif
83f64091 113
adcbebaa 114 s->open_flags = open_flags;
19cb3738
FB
115 s->type = FTYPE_FILE;
116
83f64091 117 fd = open(filename, open_flags, 0644);
19cb3738
FB
118 if (fd < 0) {
119 ret = -errno;
120 if (ret == -EROFS)
121 ret = -EACCES;
122 return ret;
123 }
83f64091
FB
124 s->fd = fd;
125 return 0;
126}
127
128/* XXX: use host sector size if necessary with:
129#ifdef DIOCGSECTORSIZE
130 {
131 unsigned int sectorsize = 512;
132 if (!ioctl(fd, DIOCGSECTORSIZE, &sectorsize) &&
133 sectorsize > bufsize)
134 bufsize = sectorsize;
135 }
136#endif
137#ifdef CONFIG_COCOA
138 u_int32_t blockSize = 512;
139 if ( !ioctl( fd, DKIOCGETBLOCKSIZE, &blockSize ) && blockSize > bufsize) {
140 bufsize = blockSize;
141 }
142#endif
143*/
144
adcbebaa
BS
145/*
146 * offset and count are in bytes, but must be multiples of 512 for files
147 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
148 *
149 * This function may be called without alignment if the caller ensures
150 * that O_DIRECT is not in effect.
151 */
152static int raw_pread_aligned(BlockDriverState *bs, int64_t offset,
83f64091
FB
153 uint8_t *buf, int count)
154{
155 BDRVRawState *s = bs->opaque;
156 int ret;
3b46e624 157
19cb3738
FB
158 ret = fd_open(bs);
159 if (ret < 0)
160 return ret;
161
985a03b0 162 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
8c05dbf9
TS
163 ++(s->lseek_err_cnt);
164 if(s->lseek_err_cnt <= 10) {
92868412
JM
165 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
166 "] lseek failed : %d = %s\n",
8c05dbf9
TS
167 s->fd, bs->filename, offset, buf, count,
168 bs->total_sectors, errno, strerror(errno));
169 }
170 return -1;
171 }
172 s->lseek_err_cnt=0;
173
83f64091 174 ret = read(s->fd, buf, count);
8c05dbf9
TS
175 if (ret == count)
176 goto label__raw_read__success;
177
92868412
JM
178 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
179 "] read failed %d : %d = %s\n",
8c05dbf9
TS
180 s->fd, bs->filename, offset, buf, count,
181 bs->total_sectors, ret, errno, strerror(errno));
182
183 /* Try harder for CDrom. */
184 if (bs->type == BDRV_TYPE_CDROM) {
185 lseek(s->fd, offset, SEEK_SET);
186 ret = read(s->fd, buf, count);
187 if (ret == count)
188 goto label__raw_read__success;
189 lseek(s->fd, offset, SEEK_SET);
190 ret = read(s->fd, buf, count);
191 if (ret == count)
192 goto label__raw_read__success;
193
92868412
JM
194 DEBUG_BLOCK_PRINT("raw_pread(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
195 "] retry read failed %d : %d = %s\n",
8c05dbf9
TS
196 s->fd, bs->filename, offset, buf, count,
197 bs->total_sectors, ret, errno, strerror(errno));
198 }
199
8c05dbf9
TS
200label__raw_read__success:
201
83f64091
FB
202 return ret;
203}
204
adcbebaa
BS
205/*
206 * offset and count are in bytes, but must be multiples of 512 for files
207 * opened with O_DIRECT. buf must be aligned to 512 bytes then.
208 *
209 * This function may be called without alignment if the caller ensures
210 * that O_DIRECT is not in effect.
211 */
212static int raw_pwrite_aligned(BlockDriverState *bs, int64_t offset,
83f64091
FB
213 const uint8_t *buf, int count)
214{
215 BDRVRawState *s = bs->opaque;
216 int ret;
3b46e624 217
19cb3738
FB
218 ret = fd_open(bs);
219 if (ret < 0)
220 return ret;
221
985a03b0 222 if (offset >= 0 && lseek(s->fd, offset, SEEK_SET) == (off_t)-1) {
8c05dbf9
TS
223 ++(s->lseek_err_cnt);
224 if(s->lseek_err_cnt) {
92868412
JM
225 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%"
226 PRId64 "] lseek failed : %d = %s\n",
8c05dbf9
TS
227 s->fd, bs->filename, offset, buf, count,
228 bs->total_sectors, errno, strerror(errno));
229 }
230 return -1;
231 }
232 s->lseek_err_cnt = 0;
233
83f64091 234 ret = write(s->fd, buf, count);
8c05dbf9
TS
235 if (ret == count)
236 goto label__raw_write__success;
237
92868412
JM
238 DEBUG_BLOCK_PRINT("raw_pwrite(%d:%s, %" PRId64 ", %p, %d) [%" PRId64
239 "] write failed %d : %d = %s\n",
8c05dbf9
TS
240 s->fd, bs->filename, offset, buf, count,
241 bs->total_sectors, ret, errno, strerror(errno));
242
8c05dbf9
TS
243label__raw_write__success:
244
83f64091
FB
245 return ret;
246}
247
adcbebaa
BS
248
249#ifdef O_DIRECT
250/*
251 * offset and count are in bytes and possibly not aligned. For files opened
252 * with O_DIRECT, necessary alignments are ensured before calling
253 * raw_pread_aligned to do the actual read.
254 */
255static int raw_pread(BlockDriverState *bs, int64_t offset,
256 uint8_t *buf, int count)
257{
258 BDRVRawState *s = bs->opaque;
259
260 if (unlikely((s->open_flags & O_DIRECT) &&
261 (offset % 512 || count % 512 || (uintptr_t) buf % 512))) {
262
263 int ret;
264
265 // Temporarily disable O_DIRECT for unaligned access
266 fcntl(s->fd, F_SETFL, s->open_flags & ~O_DIRECT);
267 ret = raw_pread_aligned(bs, offset, buf, count);
268 fcntl(s->fd, F_SETFL, s->open_flags);
269
270 return ret;
271
272 } else {
273 return raw_pread_aligned(bs, offset, buf, count);
274 }
275}
276
277/*
278 * offset and count are in bytes and possibly not aligned. For files opened
279 * with O_DIRECT, necessary alignments are ensured before calling
280 * raw_pwrite_aligned to do the actual write.
281 */
282static int raw_pwrite(BlockDriverState *bs, int64_t offset,
283 const uint8_t *buf, int count)
284{
285 BDRVRawState *s = bs->opaque;
286
287 if (unlikely((s->open_flags & O_DIRECT) &&
288 (offset % 512 || count % 512 || (uintptr_t) buf % 512))) {
289
290 int ret;
291
292 // Temporarily disable O_DIRECT for unaligned access
293 fcntl(s->fd, F_SETFL, s->open_flags & ~O_DIRECT);
294 ret = raw_pwrite_aligned(bs, offset, buf, count);
295 fcntl(s->fd, F_SETFL, s->open_flags);
296
297 return ret;
298 } else {
299 return raw_pwrite_aligned(bs, offset, buf, count);
300 }
301}
302
303#else
304#define raw_pread raw_pread_aligned
305#define raw_pwrite raw_pwrite_aligned
306#endif
307
308
83f64091 309/***********************************************************/
19cb3738 310/* Unix AIO using POSIX AIO */
83f64091
FB
311
312typedef struct RawAIOCB {
ce1a14dc 313 BlockDriverAIOCB common;
83f64091 314 struct aiocb aiocb;
ce1a14dc 315 struct RawAIOCB *next;
83f64091
FB
316} RawAIOCB;
317
318static int aio_sig_num = SIGUSR2;
ce1a14dc 319static RawAIOCB *first_aio; /* AIO issued */
979b67ad 320static int aio_initialized = 0;
83f64091 321
83f64091
FB
322static void aio_signal_handler(int signum)
323{
faf07963 324#ifndef QEMU_IMG
83f64091
FB
325 CPUState *env = cpu_single_env;
326 if (env) {
327 /* stop the currently executing cpu because a timer occured */
328 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
329#ifdef USE_KQEMU
330 if (env->kqemu_enabled) {
331 kqemu_cpu_interrupt(env);
332 }
333#endif
334 }
979b67ad 335#endif
83f64091
FB
336}
337
338void qemu_aio_init(void)
339{
340 struct sigaction act;
979b67ad
FB
341
342 aio_initialized = 1;
3b46e624 343
83f64091
FB
344 sigfillset(&act.sa_mask);
345 act.sa_flags = 0; /* do not restart syscalls to interrupt select() */
346 act.sa_handler = aio_signal_handler;
347 sigaction(aio_sig_num, &act, NULL);
348
19cb3738 349#if defined(__GLIBC__) && defined(__linux__)
83f64091 350 {
19cb3738
FB
351 /* XXX: aio thread exit seems to hang on RedHat 9 and this init
352 seems to fix the problem. */
83f64091
FB
353 struct aioinit ai;
354 memset(&ai, 0, sizeof(ai));
01534fe9
FB
355 ai.aio_threads = 1;
356 ai.aio_num = 1;
83f64091
FB
357 ai.aio_idle_time = 365 * 100000;
358 aio_init(&ai);
359 }
19cb3738 360#endif
83f64091 361}
83f64091
FB
362
363void qemu_aio_poll(void)
364{
ce1a14dc 365 RawAIOCB *acb, **pacb;
83f64091
FB
366 int ret;
367
368 for(;;) {
369 pacb = &first_aio;
370 for(;;) {
371 acb = *pacb;
372 if (!acb)
373 goto the_end;
ce1a14dc 374 ret = aio_error(&acb->aiocb);
83f64091
FB
375 if (ret == ECANCELED) {
376 /* remove the request */
ce1a14dc
PB
377 *pacb = acb->next;
378 qemu_aio_release(acb);
83f64091
FB
379 } else if (ret != EINPROGRESS) {
380 /* end of aio */
381 if (ret == 0) {
ce1a14dc
PB
382 ret = aio_return(&acb->aiocb);
383 if (ret == acb->aiocb.aio_nbytes)
83f64091
FB
384 ret = 0;
385 else
19cb3738 386 ret = -EINVAL;
83f64091
FB
387 } else {
388 ret = -ret;
389 }
390 /* remove the request */
ce1a14dc 391 *pacb = acb->next;
83f64091 392 /* call the callback */
ce1a14dc
PB
393 acb->common.cb(acb->common.opaque, ret);
394 qemu_aio_release(acb);
83f64091
FB
395 break;
396 } else {
ce1a14dc 397 pacb = &acb->next;
83f64091
FB
398 }
399 }
400 }
401 the_end: ;
402}
403
6192bc37
PB
404/* Wait for all IO requests to complete. */
405void qemu_aio_flush(void)
406{
407 qemu_aio_wait_start();
408 qemu_aio_poll();
409 while (first_aio) {
410 qemu_aio_wait();
411 }
412 qemu_aio_wait_end();
413}
414
83f64091
FB
415/* wait until at least one AIO was handled */
416static sigset_t wait_oset;
417
418void qemu_aio_wait_start(void)
419{
420 sigset_t set;
979b67ad
FB
421
422 if (!aio_initialized)
423 qemu_aio_init();
83f64091
FB
424 sigemptyset(&set);
425 sigaddset(&set, aio_sig_num);
426 sigprocmask(SIG_BLOCK, &set, &wait_oset);
427}
428
429void qemu_aio_wait(void)
430{
431 sigset_t set;
432 int nb_sigs;
6eb5733a 433
faf07963 434#ifndef QEMU_IMG
6eb5733a
FB
435 if (qemu_bh_poll())
436 return;
437#endif
83f64091
FB
438 sigemptyset(&set);
439 sigaddset(&set, aio_sig_num);
440 sigwait(&set, &nb_sigs);
441 qemu_aio_poll();
442}
443
444void qemu_aio_wait_end(void)
445{
446 sigprocmask(SIG_SETMASK, &wait_oset, NULL);
447}
448
ce1a14dc
PB
449static RawAIOCB *raw_aio_setup(BlockDriverState *bs,
450 int64_t sector_num, uint8_t *buf, int nb_sectors,
451 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 452{
ce1a14dc
PB
453 BDRVRawState *s = bs->opaque;
454 RawAIOCB *acb;
455
19cb3738
FB
456 if (fd_open(bs) < 0)
457 return NULL;
458
ce1a14dc
PB
459 acb = qemu_aio_get(bs, cb, opaque);
460 if (!acb)
461 return NULL;
462 acb->aiocb.aio_fildes = s->fd;
463 acb->aiocb.aio_sigevent.sigev_signo = aio_sig_num;
464 acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;
465 acb->aiocb.aio_buf = buf;
985a03b0
TS
466 if (nb_sectors < 0)
467 acb->aiocb.aio_nbytes = -nb_sectors;
468 else
469 acb->aiocb.aio_nbytes = nb_sectors * 512;
ce1a14dc
PB
470 acb->aiocb.aio_offset = sector_num * 512;
471 acb->next = first_aio;
472 first_aio = acb;
473 return acb;
83f64091
FB
474}
475
ce1a14dc
PB
476static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,
477 int64_t sector_num, uint8_t *buf, int nb_sectors,
478 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 479{
ce1a14dc 480 RawAIOCB *acb;
adcbebaa
BS
481 BDRVRawState *s = bs->opaque;
482
483 /*
484 * If O_DIRECT is used and the buffer is not aligned fall back
485 * to synchronous IO.
486 */
487 if (unlikely((s->open_flags & O_DIRECT) && ((uintptr_t) buf % 512))) {
488 int ret;
489
490 acb = qemu_aio_get(bs, cb, opaque);
491 ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);
492 acb->common.cb(acb->common.opaque, ret);
493 qemu_aio_release(acb);
494 return &acb->common;
495 }
83f64091 496
ce1a14dc
PB
497 acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);
498 if (!acb)
499 return NULL;
adcbebaa 500
ce1a14dc
PB
501 if (aio_read(&acb->aiocb) < 0) {
502 qemu_aio_release(acb);
503 return NULL;
5fafdf24 504 }
ce1a14dc 505 return &acb->common;
83f64091
FB
506}
507
ce1a14dc
PB
508static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,
509 int64_t sector_num, const uint8_t *buf, int nb_sectors,
510 BlockDriverCompletionFunc *cb, void *opaque)
83f64091 511{
ce1a14dc 512 RawAIOCB *acb;
adcbebaa
BS
513 BDRVRawState *s = bs->opaque;
514
515 /*
516 * If O_DIRECT is used and the buffer is not aligned fall back
517 * to synchronous IO.
518 */
519 if (unlikely((s->open_flags & O_DIRECT) && ((uintptr_t) buf % 512))) {
520 int ret;
521
522 acb = qemu_aio_get(bs, cb, opaque);
523 ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);
524 acb->common.cb(acb->common.opaque, ret);
525 qemu_aio_release(acb);
526 return &acb->common;
527 }
83f64091 528
ce1a14dc
PB
529 acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);
530 if (!acb)
531 return NULL;
532 if (aio_write(&acb->aiocb) < 0) {
533 qemu_aio_release(acb);
534 return NULL;
5fafdf24 535 }
ce1a14dc 536 return &acb->common;
83f64091
FB
537}
538
ce1a14dc 539static void raw_aio_cancel(BlockDriverAIOCB *blockacb)
83f64091 540{
83f64091 541 int ret;
ce1a14dc
PB
542 RawAIOCB *acb = (RawAIOCB *)blockacb;
543 RawAIOCB **pacb;
83f64091 544
ce1a14dc 545 ret = aio_cancel(acb->aiocb.aio_fildes, &acb->aiocb);
83f64091
FB
546 if (ret == AIO_NOTCANCELED) {
547 /* fail safe: if the aio could not be canceled, we wait for
548 it */
ce1a14dc 549 while (aio_error(&acb->aiocb) == EINPROGRESS);
83f64091
FB
550 }
551
552 /* remove the callback from the queue */
553 pacb = &first_aio;
554 for(;;) {
555 if (*pacb == NULL) {
556 break;
557 } else if (*pacb == acb) {
ce1a14dc
PB
558 *pacb = acb->next;
559 qemu_aio_release(acb);
83f64091
FB
560 break;
561 }
ce1a14dc 562 pacb = &acb->next;
83f64091
FB
563 }
564}
565
83f64091
FB
566static void raw_close(BlockDriverState *bs)
567{
568 BDRVRawState *s = bs->opaque;
19cb3738
FB
569 if (s->fd >= 0) {
570 close(s->fd);
571 s->fd = -1;
572 }
83f64091
FB
573}
574
575static int raw_truncate(BlockDriverState *bs, int64_t offset)
576{
577 BDRVRawState *s = bs->opaque;
19cb3738
FB
578 if (s->type != FTYPE_FILE)
579 return -ENOTSUP;
83f64091
FB
580 if (ftruncate(s->fd, offset) < 0)
581 return -errno;
582 return 0;
583}
584
585static int64_t raw_getlength(BlockDriverState *bs)
586{
587 BDRVRawState *s = bs->opaque;
588 int fd = s->fd;
589 int64_t size;
590#ifdef _BSD
591 struct stat sb;
592#endif
593#ifdef __sun__
594 struct dk_minfo minfo;
595 int rv;
596#endif
19cb3738
FB
597 int ret;
598
599 ret = fd_open(bs);
600 if (ret < 0)
601 return ret;
83f64091
FB
602
603#ifdef _BSD
604 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
605#ifdef DIOCGMEDIASIZE
606 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
607#endif
608#ifdef CONFIG_COCOA
609 size = LONG_LONG_MAX;
610#else
611 size = lseek(fd, 0LL, SEEK_END);
612#endif
613 } else
614#endif
615#ifdef __sun__
616 /*
617 * use the DKIOCGMEDIAINFO ioctl to read the size.
618 */
619 rv = ioctl ( fd, DKIOCGMEDIAINFO, &minfo );
620 if ( rv != -1 ) {
621 size = minfo.dki_lbsize * minfo.dki_capacity;
622 } else /* there are reports that lseek on some devices
623 fails, but irc discussion said that contingency
624 on contingency was overkill */
625#endif
626 {
627 size = lseek(fd, 0, SEEK_END);
628 }
83f64091
FB
629 return size;
630}
631
632static int raw_create(const char *filename, int64_t total_size,
633 const char *backing_file, int flags)
634{
635 int fd;
636
637 if (flags || backing_file)
638 return -ENOTSUP;
639
5fafdf24 640 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
83f64091
FB
641 0644);
642 if (fd < 0)
643 return -EIO;
644 ftruncate(fd, total_size * 512);
645 close(fd);
646 return 0;
647}
648
649static void raw_flush(BlockDriverState *bs)
650{
651 BDRVRawState *s = bs->opaque;
652 fsync(s->fd);
653}
654
655BlockDriver bdrv_raw = {
656 "raw",
657 sizeof(BDRVRawState),
658 NULL, /* no probe for protocols */
659 raw_open,
660 NULL,
661 NULL,
662 raw_close,
663 raw_create,
664 raw_flush,
3b46e624 665
83f64091
FB
666 .bdrv_aio_read = raw_aio_read,
667 .bdrv_aio_write = raw_aio_write,
668 .bdrv_aio_cancel = raw_aio_cancel,
ce1a14dc 669 .aiocb_size = sizeof(RawAIOCB),
83f64091
FB
670 .protocol_name = "file",
671 .bdrv_pread = raw_pread,
672 .bdrv_pwrite = raw_pwrite,
673 .bdrv_truncate = raw_truncate,
674 .bdrv_getlength = raw_getlength,
675};
676
19cb3738
FB
677/***********************************************/
678/* host device */
679
680#ifdef CONFIG_COCOA
681static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
682static kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize );
683
684kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
685{
5fafdf24 686 kern_return_t kernResult;
19cb3738
FB
687 mach_port_t masterPort;
688 CFMutableDictionaryRef classesToMatch;
689
690 kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
691 if ( KERN_SUCCESS != kernResult ) {
692 printf( "IOMasterPort returned %d\n", kernResult );
693 }
3b46e624 694
5fafdf24 695 classesToMatch = IOServiceMatching( kIOCDMediaClass );
19cb3738
FB
696 if ( classesToMatch == NULL ) {
697 printf( "IOServiceMatching returned a NULL dictionary.\n" );
698 } else {
699 CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
700 }
701 kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
702 if ( KERN_SUCCESS != kernResult )
703 {
704 printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
705 }
3b46e624 706
19cb3738
FB
707 return kernResult;
708}
709
710kern_return_t GetBSDPath( io_iterator_t mediaIterator, char *bsdPath, CFIndex maxPathSize )
711{
712 io_object_t nextMedia;
713 kern_return_t kernResult = KERN_FAILURE;
714 *bsdPath = '\0';
715 nextMedia = IOIteratorNext( mediaIterator );
716 if ( nextMedia )
717 {
718 CFTypeRef bsdPathAsCFString;
719 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
720 if ( bsdPathAsCFString ) {
721 size_t devPathLength;
722 strcpy( bsdPath, _PATH_DEV );
723 strcat( bsdPath, "r" );
724 devPathLength = strlen( bsdPath );
725 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
726 kernResult = KERN_SUCCESS;
727 }
728 CFRelease( bsdPathAsCFString );
729 }
730 IOObjectRelease( nextMedia );
731 }
3b46e624 732
19cb3738
FB
733 return kernResult;
734}
735
736#endif
737
738static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
739{
740 BDRVRawState *s = bs->opaque;
741 int fd, open_flags, ret;
742
743#ifdef CONFIG_COCOA
744 if (strstart(filename, "/dev/cdrom", NULL)) {
745 kern_return_t kernResult;
746 io_iterator_t mediaIterator;
747 char bsdPath[ MAXPATHLEN ];
748 int fd;
5fafdf24 749
19cb3738
FB
750 kernResult = FindEjectableCDMedia( &mediaIterator );
751 kernResult = GetBSDPath( mediaIterator, bsdPath, sizeof( bsdPath ) );
3b46e624 752
19cb3738
FB
753 if ( bsdPath[ 0 ] != '\0' ) {
754 strcat(bsdPath,"s0");
755 /* some CDs don't have a partition 0 */
756 fd = open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
757 if (fd < 0) {
758 bsdPath[strlen(bsdPath)-1] = '1';
759 } else {
760 close(fd);
761 }
762 filename = bsdPath;
763 }
3b46e624 764
19cb3738
FB
765 if ( mediaIterator )
766 IOObjectRelease( mediaIterator );
767 }
768#endif
769 open_flags = O_BINARY;
770 if ((flags & BDRV_O_ACCESS) == O_RDWR) {
771 open_flags |= O_RDWR;
772 } else {
773 open_flags |= O_RDONLY;
774 bs->read_only = 1;
775 }
33f00271
AZ
776#ifdef O_DIRECT
777 if (flags & BDRV_O_DIRECT)
778 open_flags |= O_DIRECT;
779#endif
19cb3738
FB
780
781 s->type = FTYPE_FILE;
782#if defined(__linux__)
783 if (strstart(filename, "/dev/cd", NULL)) {
784 /* open will not fail even if no CD is inserted */
785 open_flags |= O_NONBLOCK;
786 s->type = FTYPE_CD;
787 } else if (strstart(filename, "/dev/fd", NULL)) {
788 s->type = FTYPE_FD;
adcbebaa 789 s->open_flags = open_flags;
19cb3738
FB
790 /* open will not fail even if no floppy is inserted */
791 open_flags |= O_NONBLOCK;
985a03b0
TS
792 } else if (strstart(filename, "/dev/sg", NULL)) {
793 bs->sg = 1;
19cb3738
FB
794 }
795#endif
796 fd = open(filename, open_flags, 0644);
797 if (fd < 0) {
798 ret = -errno;
799 if (ret == -EROFS)
800 ret = -EACCES;
801 return ret;
802 }
803 s->fd = fd;
804#if defined(__linux__)
805 /* close fd so that we can reopen it as needed */
806 if (s->type == FTYPE_FD) {
807 close(s->fd);
808 s->fd = -1;
809 s->fd_media_changed = 1;
810 }
811#endif
812 return 0;
813}
814
faf07963 815#if defined(__linux__) && !defined(QEMU_IMG)
19cb3738
FB
816
817/* Note: we do not have a reliable method to detect if the floppy is
818 present. The current method is to try to open the floppy at every
819 I/O and to keep it opened during a few hundreds of ms. */
820static int fd_open(BlockDriverState *bs)
821{
822 BDRVRawState *s = bs->opaque;
823 int last_media_present;
824
825 if (s->type != FTYPE_FD)
826 return 0;
827 last_media_present = (s->fd >= 0);
5fafdf24 828 if (s->fd >= 0 &&
19cb3738
FB
829 (qemu_get_clock(rt_clock) - s->fd_open_time) >= FD_OPEN_TIMEOUT) {
830 close(s->fd);
831 s->fd = -1;
832#ifdef DEBUG_FLOPPY
833 printf("Floppy closed\n");
834#endif
835 }
836 if (s->fd < 0) {
5fafdf24 837 if (s->fd_got_error &&
19cb3738
FB
838 (qemu_get_clock(rt_clock) - s->fd_error_time) < FD_OPEN_TIMEOUT) {
839#ifdef DEBUG_FLOPPY
840 printf("No floppy (open delayed)\n");
841#endif
842 return -EIO;
843 }
adcbebaa 844 s->fd = open(bs->filename, s->open_flags);
19cb3738
FB
845 if (s->fd < 0) {
846 s->fd_error_time = qemu_get_clock(rt_clock);
847 s->fd_got_error = 1;
848 if (last_media_present)
849 s->fd_media_changed = 1;
850#ifdef DEBUG_FLOPPY
851 printf("No floppy\n");
852#endif
853 return -EIO;
854 }
855#ifdef DEBUG_FLOPPY
856 printf("Floppy opened\n");
857#endif
858 }
859 if (!last_media_present)
860 s->fd_media_changed = 1;
861 s->fd_open_time = qemu_get_clock(rt_clock);
862 s->fd_got_error = 0;
863 return 0;
864}
865#else
866static int fd_open(BlockDriverState *bs)
867{
868 return 0;
869}
870#endif
871
872#if defined(__linux__)
873
874static int raw_is_inserted(BlockDriverState *bs)
875{
876 BDRVRawState *s = bs->opaque;
877 int ret;
878
879 switch(s->type) {
880 case FTYPE_CD:
881 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
882 if (ret == CDS_DISC_OK)
883 return 1;
884 else
885 return 0;
886 break;
887 case FTYPE_FD:
888 ret = fd_open(bs);
889 return (ret >= 0);
890 default:
891 return 1;
892 }
893}
894
895/* currently only used by fdc.c, but a CD version would be good too */
896static int raw_media_changed(BlockDriverState *bs)
897{
898 BDRVRawState *s = bs->opaque;
899
900 switch(s->type) {
901 case FTYPE_FD:
902 {
903 int ret;
904 /* XXX: we do not have a true media changed indication. It
905 does not work if the floppy is changed without trying
906 to read it */
907 fd_open(bs);
908 ret = s->fd_media_changed;
909 s->fd_media_changed = 0;
910#ifdef DEBUG_FLOPPY
911 printf("Floppy changed=%d\n", ret);
912#endif
913 return ret;
914 }
915 default:
916 return -ENOTSUP;
917 }
918}
919
920static int raw_eject(BlockDriverState *bs, int eject_flag)
921{
922 BDRVRawState *s = bs->opaque;
923
924 switch(s->type) {
925 case FTYPE_CD:
926 if (eject_flag) {
927 if (ioctl (s->fd, CDROMEJECT, NULL) < 0)
928 perror("CDROMEJECT");
929 } else {
930 if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)
931 perror("CDROMEJECT");
932 }
933 break;
934 case FTYPE_FD:
935 {
936 int fd;
937 if (s->fd >= 0) {
938 close(s->fd);
939 s->fd = -1;
940 }
adcbebaa 941 fd = open(bs->filename, s->open_flags | O_NONBLOCK);
19cb3738
FB
942 if (fd >= 0) {
943 if (ioctl(fd, FDEJECT, 0) < 0)
944 perror("FDEJECT");
945 close(fd);
946 }
947 }
948 break;
949 default:
950 return -ENOTSUP;
951 }
952 return 0;
953}
954
955static int raw_set_locked(BlockDriverState *bs, int locked)
956{
957 BDRVRawState *s = bs->opaque;
958
959 switch(s->type) {
960 case FTYPE_CD:
961 if (ioctl (s->fd, CDROM_LOCKDOOR, locked) < 0) {
962 /* Note: an error can happen if the distribution automatically
963 mounts the CD-ROM */
964 // perror("CDROM_LOCKDOOR");
965 }
966 break;
967 default:
968 return -ENOTSUP;
969 }
970 return 0;
971}
972
985a03b0
TS
973static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
974{
975 BDRVRawState *s = bs->opaque;
976
977 return ioctl(s->fd, req, buf);
978}
19cb3738
FB
979#else
980
981static int raw_is_inserted(BlockDriverState *bs)
982{
983 return 1;
984}
985
986static int raw_media_changed(BlockDriverState *bs)
987{
988 return -ENOTSUP;
989}
990
991static int raw_eject(BlockDriverState *bs, int eject_flag)
992{
993 return -ENOTSUP;
994}
995
996static int raw_set_locked(BlockDriverState *bs, int locked)
997{
998 return -ENOTSUP;
999}
1000
985a03b0
TS
1001static int raw_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1002{
1003 return -ENOTSUP;
1004}
19cb3738
FB
1005#endif /* !linux */
1006
1007BlockDriver bdrv_host_device = {
1008 "host_device",
1009 sizeof(BDRVRawState),
1010 NULL, /* no probe for protocols */
1011 hdev_open,
1012 NULL,
1013 NULL,
1014 raw_close,
1015 NULL,
1016 raw_flush,
3b46e624 1017
19cb3738
FB
1018 .bdrv_aio_read = raw_aio_read,
1019 .bdrv_aio_write = raw_aio_write,
1020 .bdrv_aio_cancel = raw_aio_cancel,
1021 .aiocb_size = sizeof(RawAIOCB),
1022 .bdrv_pread = raw_pread,
1023 .bdrv_pwrite = raw_pwrite,
1024 .bdrv_getlength = raw_getlength,
1025
1026 /* removable device support */
1027 .bdrv_is_inserted = raw_is_inserted,
1028 .bdrv_media_changed = raw_media_changed,
1029 .bdrv_eject = raw_eject,
1030 .bdrv_set_locked = raw_set_locked,
985a03b0
TS
1031 /* generic scsi device */
1032 .bdrv_ioctl = raw_ioctl,
19cb3738 1033};