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