block/qapi: Move 'aio' option to file driver
[sdk/emulator/qemu.git] / block / raw-win32.c
1 /*
2  * Block driver for RAW files (win32)
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/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu/cutils.h"
27 #include "qemu/timer.h"
28 #include "block/block_int.h"
29 #include "qemu/module.h"
30 #include "block/raw-aio.h"
31 #include "trace.h"
32 #include "block/thread-pool.h"
33 #include "qemu/iov.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qapi/util.h"
36 #include <windows.h>
37 #include <winioctl.h>
38
39 #define FTYPE_FILE 0
40 #define FTYPE_CD     1
41 #define FTYPE_HARDDISK 2
42
43 typedef struct RawWin32AIOData {
44     BlockDriverState *bs;
45     HANDLE hfile;
46     struct iovec *aio_iov;
47     int aio_niov;
48     size_t aio_nbytes;
49     off64_t aio_offset;
50     int aio_type;
51 } RawWin32AIOData;
52
53 typedef struct BDRVRawState {
54     HANDLE hfile;
55     int type;
56     char drive_path[16]; /* format: "d:\" */
57     QEMUWin32AIOState *aio;
58 } BDRVRawState;
59
60 /*
61  * Read/writes the data to/from a given linear buffer.
62  *
63  * Returns the number of bytes handles or -errno in case of an error. Short
64  * reads are only returned if the end of the file is reached.
65  */
66 static size_t handle_aiocb_rw(RawWin32AIOData *aiocb)
67 {
68     size_t offset = 0;
69     int i;
70
71     for (i = 0; i < aiocb->aio_niov; i++) {
72         OVERLAPPED ov;
73         DWORD ret, ret_count, len;
74
75         memset(&ov, 0, sizeof(ov));
76         ov.Offset = (aiocb->aio_offset + offset);
77         ov.OffsetHigh = (aiocb->aio_offset + offset) >> 32;
78         len = aiocb->aio_iov[i].iov_len;
79         if (aiocb->aio_type & QEMU_AIO_WRITE) {
80             ret = WriteFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
81                             len, &ret_count, &ov);
82         } else {
83             ret = ReadFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
84                            len, &ret_count, &ov);
85         }
86         if (!ret) {
87             ret_count = 0;
88         }
89         if (ret_count != len) {
90             offset += ret_count;
91             break;
92         }
93         offset += len;
94     }
95
96     return offset;
97 }
98
99 static int aio_worker(void *arg)
100 {
101     RawWin32AIOData *aiocb = arg;
102     ssize_t ret = 0;
103     size_t count;
104
105     switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
106     case QEMU_AIO_READ:
107         count = handle_aiocb_rw(aiocb);
108         if (count < aiocb->aio_nbytes) {
109             /* A short read means that we have reached EOF. Pad the buffer
110              * with zeros for bytes after EOF. */
111             iov_memset(aiocb->aio_iov, aiocb->aio_niov, count,
112                       0, aiocb->aio_nbytes - count);
113
114             count = aiocb->aio_nbytes;
115         }
116         if (count == aiocb->aio_nbytes) {
117             ret = 0;
118         } else {
119             ret = -EINVAL;
120         }
121         break;
122     case QEMU_AIO_WRITE:
123         count = handle_aiocb_rw(aiocb);
124         if (count == aiocb->aio_nbytes) {
125             ret = 0;
126         } else {
127             ret = -EINVAL;
128         }
129         break;
130     case QEMU_AIO_FLUSH:
131         if (!FlushFileBuffers(aiocb->hfile)) {
132             return -EIO;
133         }
134         break;
135     default:
136         fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
137         ret = -EINVAL;
138         break;
139     }
140
141     g_free(aiocb);
142     return ret;
143 }
144
145 static BlockAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
146         int64_t offset, QEMUIOVector *qiov, int count,
147         BlockCompletionFunc *cb, void *opaque, int type)
148 {
149     RawWin32AIOData *acb = g_new(RawWin32AIOData, 1);
150     ThreadPool *pool;
151
152     acb->bs = bs;
153     acb->hfile = hfile;
154     acb->aio_type = type;
155
156     if (qiov) {
157         acb->aio_iov = qiov->iov;
158         acb->aio_niov = qiov->niov;
159         assert(qiov->size == count);
160     }
161     acb->aio_nbytes = count;
162     acb->aio_offset = offset;
163
164     trace_paio_submit(acb, opaque, offset, count, type);
165     pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
166     return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
167 }
168
169 int qemu_ftruncate64(int fd, int64_t length)
170 {
171     LARGE_INTEGER li;
172     DWORD dw;
173     LONG high;
174     HANDLE h;
175     BOOL res;
176
177     if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
178         return -1;
179
180     h = (HANDLE)_get_osfhandle(fd);
181
182     /* get current position, ftruncate do not change position */
183     li.HighPart = 0;
184     li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
185     if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
186         return -1;
187     }
188
189     high = length >> 32;
190     dw = SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN);
191     if (dw == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
192         return -1;
193     }
194     res = SetEndOfFile(h);
195
196     /* back to old position */
197     SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
198     return res ? 0 : -1;
199 }
200
201 static int set_sparse(int fd)
202 {
203     DWORD returned;
204     return (int) DeviceIoControl((HANDLE)_get_osfhandle(fd), FSCTL_SET_SPARSE,
205                                  NULL, 0, NULL, 0, &returned, NULL);
206 }
207
208 static void raw_detach_aio_context(BlockDriverState *bs)
209 {
210     BDRVRawState *s = bs->opaque;
211
212     if (s->aio) {
213         win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
214     }
215 }
216
217 static void raw_attach_aio_context(BlockDriverState *bs,
218                                    AioContext *new_context)
219 {
220     BDRVRawState *s = bs->opaque;
221
222     if (s->aio) {
223         win32_aio_attach_aio_context(s->aio, new_context);
224     }
225 }
226
227 static void raw_probe_alignment(BlockDriverState *bs, Error **errp)
228 {
229     BDRVRawState *s = bs->opaque;
230     DWORD sectorsPerCluster, freeClusters, totalClusters, count;
231     DISK_GEOMETRY_EX dg;
232     BOOL status;
233
234     if (s->type == FTYPE_CD) {
235         bs->bl.request_alignment = 2048;
236         return;
237     }
238     if (s->type == FTYPE_HARDDISK) {
239         status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
240                                  NULL, 0, &dg, sizeof(dg), &count, NULL);
241         if (status != 0) {
242             bs->bl.request_alignment = dg.Geometry.BytesPerSector;
243             return;
244         }
245         /* try GetDiskFreeSpace too */
246     }
247
248     if (s->drive_path[0]) {
249         GetDiskFreeSpace(s->drive_path, &sectorsPerCluster,
250                          &dg.Geometry.BytesPerSector,
251                          &freeClusters, &totalClusters);
252         bs->bl.request_alignment = dg.Geometry.BytesPerSector;
253     }
254 }
255
256 static void raw_parse_flags(int flags, bool use_aio, int *access_flags,
257                             DWORD *overlapped)
258 {
259     assert(access_flags != NULL);
260     assert(overlapped != NULL);
261
262     if (flags & BDRV_O_RDWR) {
263         *access_flags = GENERIC_READ | GENERIC_WRITE;
264     } else {
265         *access_flags = GENERIC_READ;
266     }
267
268     *overlapped = FILE_ATTRIBUTE_NORMAL;
269     if (use_aio) {
270         *overlapped |= FILE_FLAG_OVERLAPPED;
271     }
272     if (flags & BDRV_O_NOCACHE) {
273         *overlapped |= FILE_FLAG_NO_BUFFERING;
274     }
275 }
276
277 static void raw_parse_filename(const char *filename, QDict *options,
278                                Error **errp)
279 {
280     /* The filename does not have to be prefixed by the protocol name, since
281      * "file" is the default protocol; therefore, the return value of this
282      * function call can be ignored. */
283     strstart(filename, "file:", &filename);
284
285     qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
286 }
287
288 static QemuOptsList raw_runtime_opts = {
289     .name = "raw",
290     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
291     .desc = {
292         {
293             .name = "filename",
294             .type = QEMU_OPT_STRING,
295             .help = "File name of the image",
296         },
297         {
298             .name = "aio",
299             .type = QEMU_OPT_STRING,
300             .help = "host AIO implementation (threads, native)",
301         },
302         { /* end of list */ }
303     },
304 };
305
306 static bool get_aio_option(QemuOpts *opts, int flags, Error **errp)
307 {
308     BlockdevAioOptions aio, aio_default;
309
310     aio_default = (flags & BDRV_O_NATIVE_AIO) ? BLOCKDEV_AIO_OPTIONS_NATIVE
311                                               : BLOCKDEV_AIO_OPTIONS_THREADS;
312     aio = qapi_enum_parse(BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"),
313                           BLOCKDEV_AIO_OPTIONS__MAX, aio_default, errp);
314
315     switch (aio) {
316     case BLOCKDEV_AIO_OPTIONS_NATIVE:
317         return true;
318     case BLOCKDEV_AIO_OPTIONS_THREADS:
319         return false;
320     default:
321         error_setg(errp, "Invalid AIO option");
322     }
323     return false;
324 }
325
326 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
327                     Error **errp)
328 {
329     BDRVRawState *s = bs->opaque;
330     int access_flags;
331     DWORD overlapped;
332     QemuOpts *opts;
333     Error *local_err = NULL;
334     const char *filename;
335     bool use_aio;
336     int ret;
337
338     s->type = FTYPE_FILE;
339
340     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
341     qemu_opts_absorb_qdict(opts, options, &local_err);
342     if (local_err) {
343         error_propagate(errp, local_err);
344         ret = -EINVAL;
345         goto fail;
346     }
347
348     filename = qemu_opt_get(opts, "filename");
349
350     use_aio = get_aio_option(opts, flags, &local_err);
351     if (local_err) {
352         error_propagate(errp, local_err);
353         ret = -EINVAL;
354         goto fail;
355     }
356
357     raw_parse_flags(flags, use_aio, &access_flags, &overlapped);
358
359     if (filename[0] && filename[1] == ':') {
360         snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", filename[0]);
361     } else if (filename[0] == '\\' && filename[1] == '\\') {
362         s->drive_path[0] = 0;
363     } else {
364         /* Relative path.  */
365         char buf[MAX_PATH];
366         GetCurrentDirectory(MAX_PATH, buf);
367         snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]);
368     }
369
370     s->hfile = CreateFile(filename, access_flags,
371                           FILE_SHARE_READ, NULL,
372                           OPEN_EXISTING, overlapped, NULL);
373     if (s->hfile == INVALID_HANDLE_VALUE) {
374         int err = GetLastError();
375
376         if (err == ERROR_ACCESS_DENIED) {
377             ret = -EACCES;
378         } else {
379             ret = -EINVAL;
380         }
381         goto fail;
382     }
383
384     if (use_aio) {
385         s->aio = win32_aio_init();
386         if (s->aio == NULL) {
387             CloseHandle(s->hfile);
388             error_setg(errp, "Could not initialize AIO");
389             ret = -EINVAL;
390             goto fail;
391         }
392
393         ret = win32_aio_attach(s->aio, s->hfile);
394         if (ret < 0) {
395             win32_aio_cleanup(s->aio);
396             CloseHandle(s->hfile);
397             error_setg_errno(errp, -ret, "Could not enable AIO");
398             goto fail;
399         }
400
401         win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));
402     }
403
404     ret = 0;
405 fail:
406     qemu_opts_del(opts);
407     return ret;
408 }
409
410 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
411                          int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
412                          BlockCompletionFunc *cb, void *opaque)
413 {
414     BDRVRawState *s = bs->opaque;
415     if (s->aio) {
416         return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
417                                 nb_sectors, cb, opaque, QEMU_AIO_READ);
418     } else {
419         return paio_submit(bs, s->hfile, sector_num << BDRV_SECTOR_BITS, qiov,
420                            nb_sectors << BDRV_SECTOR_BITS,
421                            cb, opaque, QEMU_AIO_READ);
422     }
423 }
424
425 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
426                           int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
427                           BlockCompletionFunc *cb, void *opaque)
428 {
429     BDRVRawState *s = bs->opaque;
430     if (s->aio) {
431         return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
432                                 nb_sectors, cb, opaque, QEMU_AIO_WRITE);
433     } else {
434         return paio_submit(bs, s->hfile, sector_num << BDRV_SECTOR_BITS, qiov,
435                            nb_sectors << BDRV_SECTOR_BITS,
436                            cb, opaque, QEMU_AIO_WRITE);
437     }
438 }
439
440 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
441                          BlockCompletionFunc *cb, void *opaque)
442 {
443     BDRVRawState *s = bs->opaque;
444     return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
445 }
446
447 static void raw_close(BlockDriverState *bs)
448 {
449     BDRVRawState *s = bs->opaque;
450
451     if (s->aio) {
452         win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
453         win32_aio_cleanup(s->aio);
454         s->aio = NULL;
455     }
456
457     CloseHandle(s->hfile);
458     if (bs->open_flags & BDRV_O_TEMPORARY) {
459         unlink(bs->filename);
460     }
461 }
462
463 static int raw_truncate(BlockDriverState *bs, int64_t offset)
464 {
465     BDRVRawState *s = bs->opaque;
466     LONG low, high;
467     DWORD dwPtrLow;
468
469     low = offset;
470     high = offset >> 32;
471
472     /*
473      * An error has occurred if the return value is INVALID_SET_FILE_POINTER
474      * and GetLastError doesn't return NO_ERROR.
475      */
476     dwPtrLow = SetFilePointer(s->hfile, low, &high, FILE_BEGIN);
477     if (dwPtrLow == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
478         fprintf(stderr, "SetFilePointer error: %lu\n", GetLastError());
479         return -EIO;
480     }
481     if (SetEndOfFile(s->hfile) == 0) {
482         fprintf(stderr, "SetEndOfFile error: %lu\n", GetLastError());
483         return -EIO;
484     }
485     return 0;
486 }
487
488 static int64_t raw_getlength(BlockDriverState *bs)
489 {
490     BDRVRawState *s = bs->opaque;
491     LARGE_INTEGER l;
492     ULARGE_INTEGER available, total, total_free;
493     DISK_GEOMETRY_EX dg;
494     DWORD count;
495     BOOL status;
496
497     switch(s->type) {
498     case FTYPE_FILE:
499         l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
500         if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
501             return -EIO;
502         break;
503     case FTYPE_CD:
504         if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
505             return -EIO;
506         l.QuadPart = total.QuadPart;
507         break;
508     case FTYPE_HARDDISK:
509         status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
510                                  NULL, 0, &dg, sizeof(dg), &count, NULL);
511         if (status != 0) {
512             l = dg.DiskSize;
513         }
514         break;
515     default:
516         return -EIO;
517     }
518     return l.QuadPart;
519 }
520
521 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
522 {
523     typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
524                                               DWORD * high);
525     get_compressed_t get_compressed;
526     struct _stati64 st;
527     const char *filename = bs->filename;
528     /* WinNT support GetCompressedFileSize to determine allocate size */
529     get_compressed =
530         (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
531                                             "GetCompressedFileSizeA");
532     if (get_compressed) {
533         DWORD high, low;
534         low = get_compressed(filename, &high);
535         if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR) {
536             return (((int64_t) high) << 32) + low;
537         }
538     }
539
540     if (_stati64(filename, &st) < 0) {
541         return -1;
542     }
543     return st.st_size;
544 }
545
546 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
547 {
548     int fd;
549     int64_t total_size = 0;
550
551     strstart(filename, "file:", &filename);
552
553     /* Read out options */
554     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
555                           BDRV_SECTOR_SIZE);
556
557     fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
558                    0644);
559     if (fd < 0) {
560         error_setg_errno(errp, errno, "Could not create file");
561         return -EIO;
562     }
563     set_sparse(fd);
564     ftruncate(fd, total_size);
565     qemu_close(fd);
566     return 0;
567 }
568
569
570 static QemuOptsList raw_create_opts = {
571     .name = "raw-create-opts",
572     .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
573     .desc = {
574         {
575             .name = BLOCK_OPT_SIZE,
576             .type = QEMU_OPT_SIZE,
577             .help = "Virtual disk size"
578         },
579         { /* end of list */ }
580     }
581 };
582
583 BlockDriver bdrv_file = {
584     .format_name        = "file",
585     .protocol_name      = "file",
586     .instance_size      = sizeof(BDRVRawState),
587     .bdrv_needs_filename = true,
588     .bdrv_parse_filename = raw_parse_filename,
589     .bdrv_file_open     = raw_open,
590     .bdrv_refresh_limits = raw_probe_alignment,
591     .bdrv_close         = raw_close,
592     .bdrv_create        = raw_create,
593     .bdrv_has_zero_init = bdrv_has_zero_init_1,
594
595     .bdrv_aio_readv     = raw_aio_readv,
596     .bdrv_aio_writev    = raw_aio_writev,
597     .bdrv_aio_flush     = raw_aio_flush,
598
599     .bdrv_truncate      = raw_truncate,
600     .bdrv_getlength     = raw_getlength,
601     .bdrv_get_allocated_file_size
602                         = raw_get_allocated_file_size,
603
604     .create_opts        = &raw_create_opts,
605 };
606
607 /***********************************************/
608 /* host device */
609
610 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
611 {
612     char drives[256], *pdrv = drives;
613     UINT type;
614
615     memset(drives, 0, sizeof(drives));
616     GetLogicalDriveStrings(sizeof(drives), drives);
617     while(pdrv[0] != '\0') {
618         type = GetDriveType(pdrv);
619         switch(type) {
620         case DRIVE_CDROM:
621             snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
622             return 0;
623             break;
624         }
625         pdrv += lstrlen(pdrv) + 1;
626     }
627     return -1;
628 }
629
630 static int find_device_type(BlockDriverState *bs, const char *filename)
631 {
632     BDRVRawState *s = bs->opaque;
633     UINT type;
634     const char *p;
635
636     if (strstart(filename, "\\\\.\\", &p) ||
637         strstart(filename, "//./", &p)) {
638         if (stristart(p, "PhysicalDrive", NULL))
639             return FTYPE_HARDDISK;
640         snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", p[0]);
641         type = GetDriveType(s->drive_path);
642         switch (type) {
643         case DRIVE_REMOVABLE:
644         case DRIVE_FIXED:
645             return FTYPE_HARDDISK;
646         case DRIVE_CDROM:
647             return FTYPE_CD;
648         default:
649             return FTYPE_FILE;
650         }
651     } else {
652         return FTYPE_FILE;
653     }
654 }
655
656 static int hdev_probe_device(const char *filename)
657 {
658     if (strstart(filename, "/dev/cdrom", NULL))
659         return 100;
660     if (is_windows_drive(filename))
661         return 100;
662     return 0;
663 }
664
665 static void hdev_parse_filename(const char *filename, QDict *options,
666                                 Error **errp)
667 {
668     /* The prefix is optional, just as for "file". */
669     strstart(filename, "host_device:", &filename);
670
671     qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
672 }
673
674 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
675                      Error **errp)
676 {
677     BDRVRawState *s = bs->opaque;
678     int access_flags, create_flags;
679     int ret = 0;
680     DWORD overlapped;
681     char device_name[64];
682
683     Error *local_err = NULL;
684     const char *filename;
685     bool use_aio;
686
687     QemuOpts *opts = qemu_opts_create(&raw_runtime_opts, NULL, 0,
688                                       &error_abort);
689     qemu_opts_absorb_qdict(opts, options, &local_err);
690     if (local_err) {
691         error_propagate(errp, local_err);
692         ret = -EINVAL;
693         goto done;
694     }
695
696     filename = qemu_opt_get(opts, "filename");
697
698     use_aio = get_aio_option(opts, flags, &local_err);
699     if (!local_err && use_aio) {
700         error_setg(&local_err, "AIO is not supported on Windows host devices");
701     }
702     if (local_err) {
703         error_propagate(errp, local_err);
704         ret = -EINVAL;
705         goto done;
706     }
707
708     if (strstart(filename, "/dev/cdrom", NULL)) {
709         if (find_cdrom(device_name, sizeof(device_name)) < 0) {
710             error_setg(errp, "Could not open CD-ROM drive");
711             ret = -ENOENT;
712             goto done;
713         }
714         filename = device_name;
715     } else {
716         /* transform drive letters into device name */
717         if (((filename[0] >= 'a' && filename[0] <= 'z') ||
718              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
719             filename[1] == ':' && filename[2] == '\0') {
720             snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
721             filename = device_name;
722         }
723     }
724     s->type = find_device_type(bs, filename);
725
726     raw_parse_flags(flags, use_aio, &access_flags, &overlapped);
727
728     create_flags = OPEN_EXISTING;
729
730     s->hfile = CreateFile(filename, access_flags,
731                           FILE_SHARE_READ, NULL,
732                           create_flags, overlapped, NULL);
733     if (s->hfile == INVALID_HANDLE_VALUE) {
734         int err = GetLastError();
735
736         if (err == ERROR_ACCESS_DENIED) {
737             ret = -EACCES;
738         } else {
739             ret = -EINVAL;
740         }
741         error_setg_errno(errp, -ret, "Could not open device");
742         goto done;
743     }
744
745 done:
746     qemu_opts_del(opts);
747     return ret;
748 }
749
750 static BlockDriver bdrv_host_device = {
751     .format_name        = "host_device",
752     .protocol_name      = "host_device",
753     .instance_size      = sizeof(BDRVRawState),
754     .bdrv_needs_filename = true,
755     .bdrv_parse_filename = hdev_parse_filename,
756     .bdrv_probe_device  = hdev_probe_device,
757     .bdrv_file_open     = hdev_open,
758     .bdrv_close         = raw_close,
759
760     .bdrv_aio_readv     = raw_aio_readv,
761     .bdrv_aio_writev    = raw_aio_writev,
762     .bdrv_aio_flush     = raw_aio_flush,
763
764     .bdrv_detach_aio_context = raw_detach_aio_context,
765     .bdrv_attach_aio_context = raw_attach_aio_context,
766
767     .bdrv_getlength      = raw_getlength,
768     .has_variable_length = true,
769
770     .bdrv_get_allocated_file_size
771                         = raw_get_allocated_file_size,
772 };
773
774 static void bdrv_file_init(void)
775 {
776     bdrv_register(&bdrv_file);
777     bdrv_register(&bdrv_host_device);
778 }
779
780 block_init(bdrv_file_init);