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