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