hds: fix a file creation error on windows host.
[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-common.h"
25 #include "qemu/timer.h"
26 #include "block/block_int.h"
27 #include "qemu/module.h"
28 #include "raw-aio.h"
29 #include "trace.h"
30 #include "block/thread-pool.h"
31 #include "qemu/iov.h"
32 #include <windows.h>
33 #include <winioctl.h>
34 #ifdef CONFIG_MARU
35 #include <errno.h>
36 #endif
37
38 #define FTYPE_FILE 0
39 #define FTYPE_CD     1
40 #define FTYPE_HARDDISK 2
41
42 static QEMUWin32AIOState *aio;
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 && aiocb->bs->growable) {
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             count = 0;
127         } else {
128             count = -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_slice_free(RawWin32AIOData, aiocb);
143     return ret;
144 }
145
146 static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
147         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
148         BlockDriverCompletionFunc *cb, void *opaque, int type)
149 {
150     RawWin32AIOData *acb = g_slice_new(RawWin32AIOData);
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     }
161     acb->aio_nbytes = nb_sectors * 512;
162     acb->aio_offset = sector_num * 512;
163
164     trace_paio_submit(acb, opaque, sector_num, nb_sectors, 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_probe_alignment(BlockDriverState *bs)
209 {
210     BDRVRawState *s = bs->opaque;
211     DWORD sectorsPerCluster, freeClusters, totalClusters, count;
212     DISK_GEOMETRY_EX dg;
213     BOOL status;
214
215     if (s->type == FTYPE_CD) {
216         bs->request_alignment = 2048;
217         return;
218     }
219     if (s->type == FTYPE_HARDDISK) {
220         status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
221                                  NULL, 0, &dg, sizeof(dg), &count, NULL);
222         if (status != 0) {
223             bs->request_alignment = dg.Geometry.BytesPerSector;
224             return;
225         }
226         /* try GetDiskFreeSpace too */
227     }
228
229     if (s->drive_path[0]) {
230         GetDiskFreeSpace(s->drive_path, &sectorsPerCluster,
231                          &dg.Geometry.BytesPerSector,
232                          &freeClusters, &totalClusters);
233         bs->request_alignment = dg.Geometry.BytesPerSector;
234     }
235 }
236
237 #ifndef CONFIG_MARU
238 static void raw_parse_flags(int flags, int *access_flags, DWORD *overlapped)
239 {
240     assert(access_flags != NULL);
241     assert(overlapped != NULL);
242
243     if (flags & BDRV_O_RDWR) {
244         *access_flags = GENERIC_READ | GENERIC_WRITE;
245     } else {
246         *access_flags = GENERIC_READ;
247     }
248
249     *overlapped = FILE_ATTRIBUTE_NORMAL;
250     if (flags & BDRV_O_NATIVE_AIO) {
251         *overlapped |= FILE_FLAG_OVERLAPPED;
252     }
253     if (flags & BDRV_O_NOCACHE) {
254         *overlapped |= FILE_FLAG_NO_BUFFERING;
255     }
256 }
257 #endif
258
259 static void raw_parse_filename(const char *filename, QDict *options,
260                                Error **errp)
261 {
262     /* The filename does not have to be prefixed by the protocol name, since
263      * "file" is the default protocol; therefore, the return value of this
264      * function call can be ignored. */
265     strstart(filename, "file:", &filename);
266
267     qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
268 }
269
270 static QemuOptsList raw_runtime_opts = {
271     .name = "raw",
272     .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
273     .desc = {
274         {
275             .name = "filename",
276             .type = QEMU_OPT_STRING,
277             .help = "File name of the image",
278         },
279         { /* end of list */ }
280     },
281 };
282
283 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
284                     Error **errp)
285 {
286     BDRVRawState *s = bs->opaque;
287     QemuOpts *opts;
288     Error *local_err = NULL;
289     const char *filename;
290     int ret;
291 #ifndef CONFIG_MARU
292     DWORD overlapped;
293     int access_flags;
294 #else
295     int open_flags;
296 #endif
297
298     s->type = FTYPE_FILE;
299
300     opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
301     qemu_opts_absorb_qdict(opts, options, &local_err);
302     if (local_err) {
303         error_propagate(errp, local_err);
304         ret = -EINVAL;
305         goto fail;
306     }
307
308     filename = qemu_opt_get(opts, "filename");
309
310 #ifndef CONFIG_MARU
311     raw_parse_flags(flags, &access_flags, &overlapped);
312
313     if ((flags & BDRV_O_NATIVE_AIO) && aio == NULL) {
314         aio = win32_aio_init();
315         if (aio == NULL) {
316             error_setg(errp, "Could not initialize AIO");
317             ret = -EINVAL;
318             goto fail;
319         }
320     }
321
322     if (filename[0] && filename[1] == ':') {
323         snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", filename[0]);
324     } else if (filename[0] == '\\' && filename[1] == '\\') {
325         s->drive_path[0] = 0;
326     } else {
327         /* Relative path.  */
328         char buf[MAX_PATH];
329         GetCurrentDirectory(MAX_PATH, buf);
330         snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]);
331     }
332
333     s->hfile = CreateFile(filename, access_flags,
334                           FILE_SHARE_READ, NULL,
335                           OPEN_EXISTING, overlapped, NULL);
336         if (s->hfile == INVALID_HANDLE_VALUE) {
337         int err = GetLastError();
338
339         if (err == ERROR_ACCESS_DENIED) {
340             ret = -EACCES;
341         } else {
342             ret = -EINVAL;
343         }
344         goto fail;
345     }
346 #else
347     open_flags = O_BINARY & ~O_ACCMODE;
348     if (flags & BDRV_O_RDWR) {
349         open_flags |= O_RDWR;
350     } else {
351         open_flags |= O_RDONLY;
352     }
353
354     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
355      * and O_DIRECT for no caching. */
356     /*
357        if ((flags & BDRV_O_NOCACHE)) {
358        open_flags |= O_DIRECT;
359        }
360        if (!(flags & BDRV_O_CACHE_WB)) {
361        open_flags |= O_DSYNC;
362        }
363      */
364
365     if ((flags & BDRV_O_NATIVE_AIO) && aio == NULL) {
366         aio = win32_aio_init();
367         if (aio == NULL) {
368             ret = -EINVAL;
369             goto fail;
370         }
371     }
372
373     ret = qemu_open(filename, open_flags, 0644);
374     if (ret < 0) {
375         error_report("raw_open failed(%d) \n", ret);
376         return -errno;
377     }
378     s->hfile = (HANDLE)_get_osfhandle(ret);
379 #endif
380
381     if (flags & BDRV_O_NATIVE_AIO) {
382         ret = win32_aio_attach(aio, s->hfile);
383         if (ret < 0) {
384             CloseHandle(s->hfile);
385             error_setg_errno(errp, -ret, "Could not enable AIO");
386             goto fail;
387         }
388         s->aio = aio;
389     }
390
391     raw_probe_alignment(bs);
392     ret = 0;
393 fail:
394     qemu_opts_del(opts);
395     return ret;
396 }
397
398 static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
399                          int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
400                          BlockDriverCompletionFunc *cb, void *opaque)
401 {
402     BDRVRawState *s = bs->opaque;
403     if (s->aio) {
404         return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
405                                 nb_sectors, cb, opaque, QEMU_AIO_READ); 
406     } else {
407         return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
408                            cb, opaque, QEMU_AIO_READ);
409     }
410 }
411
412 static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
413                           int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
414                           BlockDriverCompletionFunc *cb, void *opaque)
415 {
416     BDRVRawState *s = bs->opaque;
417     if (s->aio) {
418         return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
419                                 nb_sectors, cb, opaque, QEMU_AIO_WRITE); 
420     } else {
421         return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
422                            cb, opaque, QEMU_AIO_WRITE);
423     }
424 }
425
426 static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
427                          BlockDriverCompletionFunc *cb, void *opaque)
428 {
429     BDRVRawState *s = bs->opaque;
430     return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
431 }
432
433 static void raw_close(BlockDriverState *bs)
434 {
435     BDRVRawState *s = bs->opaque;
436     CloseHandle(s->hfile);
437 }
438
439 static int raw_truncate(BlockDriverState *bs, int64_t offset)
440 {
441     BDRVRawState *s = bs->opaque;
442     LONG low, high;
443     DWORD dwPtrLow;
444
445     low = offset;
446     high = offset >> 32;
447
448     /*
449      * An error has occurred if the return value is INVALID_SET_FILE_POINTER
450      * and GetLastError doesn't return NO_ERROR.
451      */
452     dwPtrLow = SetFilePointer(s->hfile, low, &high, FILE_BEGIN);
453     if (dwPtrLow == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
454         fprintf(stderr, "SetFilePointer error: %lu\n", GetLastError());
455         return -EIO;
456     }
457     if (SetEndOfFile(s->hfile) == 0) {
458         fprintf(stderr, "SetEndOfFile error: %lu\n", GetLastError());
459         return -EIO;
460     }
461     return 0;
462 }
463
464 static int64_t raw_getlength(BlockDriverState *bs)
465 {
466     BDRVRawState *s = bs->opaque;
467     LARGE_INTEGER l;
468     ULARGE_INTEGER available, total, total_free;
469     DISK_GEOMETRY_EX dg;
470     DWORD count;
471     BOOL status;
472
473     switch(s->type) {
474     case FTYPE_FILE:
475         l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
476         if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
477             return -EIO;
478         break;
479     case FTYPE_CD:
480         if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
481             return -EIO;
482         l.QuadPart = total.QuadPart;
483         break;
484     case FTYPE_HARDDISK:
485         status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
486                                  NULL, 0, &dg, sizeof(dg), &count, NULL);
487         if (status != 0) {
488             l = dg.DiskSize;
489         }
490         break;
491     default:
492         return -EIO;
493     }
494     return l.QuadPart;
495 }
496
497 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
498 {
499     typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
500                                               DWORD * high);
501     get_compressed_t get_compressed;
502     struct _stati64 st;
503     const char *filename = bs->filename;
504     /* WinNT support GetCompressedFileSize to determine allocate size */
505     get_compressed =
506         (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
507                                             "GetCompressedFileSizeA");
508     if (get_compressed) {
509         DWORD high, low;
510         low = get_compressed(filename, &high);
511         if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR) {
512             return (((int64_t) high) << 32) + low;
513         }
514     }
515
516     if (_stati64(filename, &st) < 0) {
517         return -1;
518     }
519     return st.st_size;
520 }
521
522 static int raw_create(const char *filename, QEMUOptionParameter *options,
523                       Error **errp)
524 {
525     int fd;
526     int64_t total_size = 0;
527
528     strstart(filename, "file:", &filename);
529
530     /* Read out options */
531     while (options && options->name) {
532         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
533             total_size = options->value.n / 512;
534         }
535         options++;
536     }
537
538     fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
539                    0644);
540     if (fd < 0) {
541         error_setg_errno(errp, errno, "Could not create file");
542         return -EIO;
543     }
544     set_sparse(fd);
545     ftruncate(fd, total_size * 512);
546     qemu_close(fd);
547     return 0;
548 }
549
550 static QEMUOptionParameter raw_create_options[] = {
551     {
552         .name = BLOCK_OPT_SIZE,
553         .type = OPT_SIZE,
554         .help = "Virtual disk size"
555     },
556     { NULL }
557 };
558
559 static BlockDriver bdrv_file = {
560     .format_name        = "file",
561     .protocol_name      = "file",
562     .instance_size      = sizeof(BDRVRawState),
563     .bdrv_needs_filename = true,
564     .bdrv_parse_filename = raw_parse_filename,
565     .bdrv_file_open     = raw_open,
566     .bdrv_close         = raw_close,
567     .bdrv_create        = raw_create,
568     .bdrv_has_zero_init = bdrv_has_zero_init_1,
569
570     .bdrv_aio_readv     = raw_aio_readv,
571     .bdrv_aio_writev    = raw_aio_writev,
572     .bdrv_aio_flush     = raw_aio_flush,
573
574     .bdrv_truncate      = raw_truncate,
575     .bdrv_getlength     = raw_getlength,
576     .bdrv_get_allocated_file_size
577                         = raw_get_allocated_file_size,
578
579     .create_options = raw_create_options,
580 };
581
582 /***********************************************/
583 /* host device */
584
585 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
586 {
587     char drives[256], *pdrv = drives;
588     UINT type;
589
590     memset(drives, 0, sizeof(drives));
591     GetLogicalDriveStrings(sizeof(drives), drives);
592     while(pdrv[0] != '\0') {
593         type = GetDriveType(pdrv);
594         switch(type) {
595         case DRIVE_CDROM:
596             snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
597             return 0;
598             break;
599         }
600         pdrv += lstrlen(pdrv) + 1;
601     }
602     return -1;
603 }
604
605 static int find_device_type(BlockDriverState *bs, const char *filename)
606 {
607     BDRVRawState *s = bs->opaque;
608     UINT type;
609     const char *p;
610
611     if (strstart(filename, "\\\\.\\", &p) ||
612         strstart(filename, "//./", &p)) {
613         if (stristart(p, "PhysicalDrive", NULL))
614             return FTYPE_HARDDISK;
615         snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", p[0]);
616         type = GetDriveType(s->drive_path);
617         switch (type) {
618         case DRIVE_REMOVABLE:
619         case DRIVE_FIXED:
620             return FTYPE_HARDDISK;
621         case DRIVE_CDROM:
622             return FTYPE_CD;
623         default:
624             return FTYPE_FILE;
625         }
626     } else {
627         return FTYPE_FILE;
628     }
629 }
630
631 static int hdev_probe_device(const char *filename)
632 {
633     if (strstart(filename, "/dev/cdrom", NULL))
634         return 100;
635     if (is_windows_drive(filename))
636         return 100;
637     return 0;
638 }
639
640 static void hdev_parse_filename(const char *filename, QDict *options,
641                                 Error **errp)
642 {
643     /* The prefix is optional, just as for "file". */
644     strstart(filename, "host_device:", &filename);
645
646     qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
647 }
648
649 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
650                      Error **errp)
651 {
652     BDRVRawState *s = bs->opaque;
653 #ifndef CONFIG_MARU
654     int access_flags, create_flags;
655     int ret = 0;
656     DWORD overlapped;
657 #else
658     int open_flags;
659 #endif
660     int ret = 0;
661     char device_name[64];
662
663     Error *local_err = NULL;
664     const char *filename;
665
666     QemuOpts *opts = qemu_opts_create(&raw_runtime_opts, NULL, 0,
667                                       &error_abort);
668     qemu_opts_absorb_qdict(opts, options, &local_err);
669     if (local_err) {
670         error_propagate(errp, local_err);
671         ret = -EINVAL;
672         goto done;
673     }
674
675     filename = qemu_opt_get(opts, "filename");
676
677     if (strstart(filename, "/dev/cdrom", NULL)) {
678         if (find_cdrom(device_name, sizeof(device_name)) < 0) {
679             error_setg(errp, "Could not open CD-ROM drive");
680             ret = -ENOENT;
681             goto done;
682         }
683         filename = device_name;
684     } else {
685         /* transform drive letters into device name */
686         if (((filename[0] >= 'a' && filename[0] <= 'z') ||
687              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
688             filename[1] == ':' && filename[2] == '\0') {
689             snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
690             filename = device_name;
691         }
692     }
693     s->type = find_device_type(bs, filename);
694
695 #ifndef CONFIG_MARU
696     raw_parse_flags(flags, &access_flags, &overlapped);
697
698     create_flags = OPEN_EXISTING;
699
700     s->hfile = CreateFile(filename, access_flags,
701                           FILE_SHARE_READ, NULL,
702                           create_flags, overlapped, NULL);
703         if (s->hfile == INVALID_HANDLE_VALUE) {
704         int err = GetLastError();
705
706         if (err == ERROR_ACCESS_DENIED) {
707             ret = -EACCES;
708         } else {
709             ret = -EINVAL;
710         }
711         error_setg_errno(errp, -ret, "Could not open device");
712         goto done;
713     }
714 #else
715         /*
716     s->hfile = CreateFile(g_win32_locale_filename_from_utf8(filename),
717                           access_flags,
718                           FILE_SHARE_READ, NULL,
719                           create_flags, overlapped, NULL);
720         */
721     open_flags = (O_BINARY & ~O_ACCMODE);
722     if (flags & BDRV_O_RDWR) {
723         open_flags |= O_RDWR;
724     } else {
725         open_flags |= O_RDONLY;
726     }
727
728     /* Use O_DSYNC for write-through caching, no flags for write-back caching,
729      * and O_DIRECT for no caching. */
730     /*
731        if ((flags & BDRV_O_NOCACHE)) {
732        open_flags |= O_DIRECT;
733        }
734        if (!(flags & BDRV_O_CACHE_WB)) {
735        open_flags |= O_DSYNC;
736        }
737      */
738
739     ret = qemu_open(filename, open_flags, 0644);
740     if (ret < 0) {
741         error_report("raw_open failed(%d) \n", ret);
742         return -errno;
743     }
744     s->hfile = (HANDLE)_get_osfhandle(ret);
745 #endif
746     return 0;
747
748 done:
749     qemu_opts_del(opts);
750     return ret;
751 }
752
753 static BlockDriver bdrv_host_device = {
754     .format_name        = "host_device",
755     .protocol_name      = "host_device",
756     .instance_size      = sizeof(BDRVRawState),
757     .bdrv_needs_filename = true,
758     .bdrv_parse_filename = hdev_parse_filename,
759     .bdrv_probe_device  = hdev_probe_device,
760     .bdrv_file_open     = hdev_open,
761     .bdrv_close         = raw_close,
762
763     .bdrv_aio_readv     = raw_aio_readv,
764     .bdrv_aio_writev    = raw_aio_writev,
765     .bdrv_aio_flush     = raw_aio_flush,
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);