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