vhdx: Fix "log that needs to be replayed" error message
[qemu/cris-port.git] / block / raw-win32.c
blob2d0907a8222299a9066c667e325c25842204d9b1
1 /*
2 * Block driver for RAW files (win32)
4 * Copyright (c) 2006 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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 "qapi/qmp/qstring.h"
33 #include <windows.h>
34 #include <winioctl.h>
36 #define FTYPE_FILE 0
37 #define FTYPE_CD 1
38 #define FTYPE_HARDDISK 2
40 typedef struct RawWin32AIOData {
41 BlockDriverState *bs;
42 HANDLE hfile;
43 struct iovec *aio_iov;
44 int aio_niov;
45 size_t aio_nbytes;
46 off64_t aio_offset;
47 int aio_type;
48 } RawWin32AIOData;
50 typedef struct BDRVRawState {
51 HANDLE hfile;
52 int type;
53 char drive_path[16]; /* format: "d:\" */
54 QEMUWin32AIOState *aio;
55 } BDRVRawState;
58 * Read/writes the data to/from a given linear buffer.
60 * Returns the number of bytes handles or -errno in case of an error. Short
61 * reads are only returned if the end of the file is reached.
63 static size_t handle_aiocb_rw(RawWin32AIOData *aiocb)
65 size_t offset = 0;
66 int i;
68 for (i = 0; i < aiocb->aio_niov; i++) {
69 OVERLAPPED ov;
70 DWORD ret, ret_count, len;
72 memset(&ov, 0, sizeof(ov));
73 ov.Offset = (aiocb->aio_offset + offset);
74 ov.OffsetHigh = (aiocb->aio_offset + offset) >> 32;
75 len = aiocb->aio_iov[i].iov_len;
76 if (aiocb->aio_type & QEMU_AIO_WRITE) {
77 ret = WriteFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
78 len, &ret_count, &ov);
79 } else {
80 ret = ReadFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
81 len, &ret_count, &ov);
83 if (!ret) {
84 ret_count = 0;
86 if (ret_count != len) {
87 offset += ret_count;
88 break;
90 offset += len;
93 return offset;
96 static int aio_worker(void *arg)
98 RawWin32AIOData *aiocb = arg;
99 ssize_t ret = 0;
100 size_t count;
102 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
103 case QEMU_AIO_READ:
104 count = handle_aiocb_rw(aiocb);
105 if (count < aiocb->aio_nbytes) {
106 /* A short read means that we have reached EOF. Pad the buffer
107 * with zeros for bytes after EOF. */
108 iov_memset(aiocb->aio_iov, aiocb->aio_niov, count,
109 0, aiocb->aio_nbytes - count);
111 count = aiocb->aio_nbytes;
113 if (count == aiocb->aio_nbytes) {
114 ret = 0;
115 } else {
116 ret = -EINVAL;
118 break;
119 case QEMU_AIO_WRITE:
120 count = handle_aiocb_rw(aiocb);
121 if (count == aiocb->aio_nbytes) {
122 ret = 0;
123 } else {
124 ret = -EINVAL;
126 break;
127 case QEMU_AIO_FLUSH:
128 if (!FlushFileBuffers(aiocb->hfile)) {
129 return -EIO;
131 break;
132 default:
133 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
134 ret = -EINVAL;
135 break;
138 g_free(aiocb);
139 return ret;
142 static BlockAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
143 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
144 BlockCompletionFunc *cb, void *opaque, int type)
146 RawWin32AIOData *acb = g_new(RawWin32AIOData, 1);
147 ThreadPool *pool;
149 acb->bs = bs;
150 acb->hfile = hfile;
151 acb->aio_type = type;
153 if (qiov) {
154 acb->aio_iov = qiov->iov;
155 acb->aio_niov = qiov->niov;
157 acb->aio_nbytes = nb_sectors * 512;
158 acb->aio_offset = sector_num * 512;
160 trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
161 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
162 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
165 int qemu_ftruncate64(int fd, int64_t length)
167 LARGE_INTEGER li;
168 DWORD dw;
169 LONG high;
170 HANDLE h;
171 BOOL res;
173 if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
174 return -1;
176 h = (HANDLE)_get_osfhandle(fd);
178 /* get current position, ftruncate do not change position */
179 li.HighPart = 0;
180 li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
181 if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
182 return -1;
185 high = length >> 32;
186 dw = SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN);
187 if (dw == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
188 return -1;
190 res = SetEndOfFile(h);
192 /* back to old position */
193 SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
194 return res ? 0 : -1;
197 static int set_sparse(int fd)
199 DWORD returned;
200 return (int) DeviceIoControl((HANDLE)_get_osfhandle(fd), FSCTL_SET_SPARSE,
201 NULL, 0, NULL, 0, &returned, NULL);
204 static void raw_detach_aio_context(BlockDriverState *bs)
206 BDRVRawState *s = bs->opaque;
208 if (s->aio) {
209 win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
213 static void raw_attach_aio_context(BlockDriverState *bs,
214 AioContext *new_context)
216 BDRVRawState *s = bs->opaque;
218 if (s->aio) {
219 win32_aio_attach_aio_context(s->aio, new_context);
223 static void raw_probe_alignment(BlockDriverState *bs)
225 BDRVRawState *s = bs->opaque;
226 DWORD sectorsPerCluster, freeClusters, totalClusters, count;
227 DISK_GEOMETRY_EX dg;
228 BOOL status;
230 if (s->type == FTYPE_CD) {
231 bs->request_alignment = 2048;
232 return;
234 if (s->type == FTYPE_HARDDISK) {
235 status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
236 NULL, 0, &dg, sizeof(dg), &count, NULL);
237 if (status != 0) {
238 bs->request_alignment = dg.Geometry.BytesPerSector;
239 return;
241 /* try GetDiskFreeSpace too */
244 if (s->drive_path[0]) {
245 GetDiskFreeSpace(s->drive_path, &sectorsPerCluster,
246 &dg.Geometry.BytesPerSector,
247 &freeClusters, &totalClusters);
248 bs->request_alignment = dg.Geometry.BytesPerSector;
252 static void raw_parse_flags(int flags, int *access_flags, DWORD *overlapped)
254 assert(access_flags != NULL);
255 assert(overlapped != NULL);
257 if (flags & BDRV_O_RDWR) {
258 *access_flags = GENERIC_READ | GENERIC_WRITE;
259 } else {
260 *access_flags = GENERIC_READ;
263 *overlapped = FILE_ATTRIBUTE_NORMAL;
264 if (flags & BDRV_O_NATIVE_AIO) {
265 *overlapped |= FILE_FLAG_OVERLAPPED;
267 if (flags & BDRV_O_NOCACHE) {
268 *overlapped |= FILE_FLAG_NO_BUFFERING;
272 static void raw_parse_filename(const char *filename, QDict *options,
273 Error **errp)
275 /* The filename does not have to be prefixed by the protocol name, since
276 * "file" is the default protocol; therefore, the return value of this
277 * function call can be ignored. */
278 strstart(filename, "file:", &filename);
280 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
283 static QemuOptsList raw_runtime_opts = {
284 .name = "raw",
285 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
286 .desc = {
288 .name = "filename",
289 .type = QEMU_OPT_STRING,
290 .help = "File name of the image",
292 { /* end of list */ }
296 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
297 Error **errp)
299 BDRVRawState *s = bs->opaque;
300 int access_flags;
301 DWORD overlapped;
302 QemuOpts *opts;
303 Error *local_err = NULL;
304 const char *filename;
305 int ret;
307 s->type = FTYPE_FILE;
309 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
310 qemu_opts_absorb_qdict(opts, options, &local_err);
311 if (local_err) {
312 error_propagate(errp, local_err);
313 ret = -EINVAL;
314 goto fail;
317 filename = qemu_opt_get(opts, "filename");
319 raw_parse_flags(flags, &access_flags, &overlapped);
321 if (filename[0] && filename[1] == ':') {
322 snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", filename[0]);
323 } else if (filename[0] == '\\' && filename[1] == '\\') {
324 s->drive_path[0] = 0;
325 } else {
326 /* Relative path. */
327 char buf[MAX_PATH];
328 GetCurrentDirectory(MAX_PATH, buf);
329 snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]);
332 s->hfile = CreateFile(filename, access_flags,
333 FILE_SHARE_READ, NULL,
334 OPEN_EXISTING, overlapped, NULL);
335 if (s->hfile == INVALID_HANDLE_VALUE) {
336 int err = GetLastError();
338 if (err == ERROR_ACCESS_DENIED) {
339 ret = -EACCES;
340 } else {
341 ret = -EINVAL;
343 goto fail;
346 if (flags & BDRV_O_NATIVE_AIO) {
347 s->aio = win32_aio_init();
348 if (s->aio == NULL) {
349 CloseHandle(s->hfile);
350 error_setg(errp, "Could not initialize AIO");
351 ret = -EINVAL;
352 goto fail;
355 ret = win32_aio_attach(s->aio, s->hfile);
356 if (ret < 0) {
357 win32_aio_cleanup(s->aio);
358 CloseHandle(s->hfile);
359 error_setg_errno(errp, -ret, "Could not enable AIO");
360 goto fail;
363 win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));
366 raw_probe_alignment(bs);
367 ret = 0;
368 fail:
369 qemu_opts_del(opts);
370 return ret;
373 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
374 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
375 BlockCompletionFunc *cb, void *opaque)
377 BDRVRawState *s = bs->opaque;
378 if (s->aio) {
379 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
380 nb_sectors, cb, opaque, QEMU_AIO_READ);
381 } else {
382 return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
383 cb, opaque, QEMU_AIO_READ);
387 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
388 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
389 BlockCompletionFunc *cb, void *opaque)
391 BDRVRawState *s = bs->opaque;
392 if (s->aio) {
393 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
394 nb_sectors, cb, opaque, QEMU_AIO_WRITE);
395 } else {
396 return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
397 cb, opaque, QEMU_AIO_WRITE);
401 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
402 BlockCompletionFunc *cb, void *opaque)
404 BDRVRawState *s = bs->opaque;
405 return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
408 static void raw_close(BlockDriverState *bs)
410 BDRVRawState *s = bs->opaque;
412 if (s->aio) {
413 win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
414 win32_aio_cleanup(s->aio);
415 s->aio = NULL;
418 CloseHandle(s->hfile);
419 if (bs->open_flags & BDRV_O_TEMPORARY) {
420 unlink(bs->filename);
424 static int raw_truncate(BlockDriverState *bs, int64_t offset)
426 BDRVRawState *s = bs->opaque;
427 LONG low, high;
428 DWORD dwPtrLow;
430 low = offset;
431 high = offset >> 32;
434 * An error has occurred if the return value is INVALID_SET_FILE_POINTER
435 * and GetLastError doesn't return NO_ERROR.
437 dwPtrLow = SetFilePointer(s->hfile, low, &high, FILE_BEGIN);
438 if (dwPtrLow == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
439 fprintf(stderr, "SetFilePointer error: %lu\n", GetLastError());
440 return -EIO;
442 if (SetEndOfFile(s->hfile) == 0) {
443 fprintf(stderr, "SetEndOfFile error: %lu\n", GetLastError());
444 return -EIO;
446 return 0;
449 static int64_t raw_getlength(BlockDriverState *bs)
451 BDRVRawState *s = bs->opaque;
452 LARGE_INTEGER l;
453 ULARGE_INTEGER available, total, total_free;
454 DISK_GEOMETRY_EX dg;
455 DWORD count;
456 BOOL status;
458 switch(s->type) {
459 case FTYPE_FILE:
460 l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
461 if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
462 return -EIO;
463 break;
464 case FTYPE_CD:
465 if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
466 return -EIO;
467 l.QuadPart = total.QuadPart;
468 break;
469 case FTYPE_HARDDISK:
470 status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
471 NULL, 0, &dg, sizeof(dg), &count, NULL);
472 if (status != 0) {
473 l = dg.DiskSize;
475 break;
476 default:
477 return -EIO;
479 return l.QuadPart;
482 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
484 typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
485 DWORD * high);
486 get_compressed_t get_compressed;
487 struct _stati64 st;
488 const char *filename = bs->filename;
489 /* WinNT support GetCompressedFileSize to determine allocate size */
490 get_compressed =
491 (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
492 "GetCompressedFileSizeA");
493 if (get_compressed) {
494 DWORD high, low;
495 low = get_compressed(filename, &high);
496 if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR) {
497 return (((int64_t) high) << 32) + low;
501 if (_stati64(filename, &st) < 0) {
502 return -1;
504 return st.st_size;
507 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
509 int fd;
510 int64_t total_size = 0;
512 strstart(filename, "file:", &filename);
514 /* Read out options */
515 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
516 BDRV_SECTOR_SIZE);
518 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
519 0644);
520 if (fd < 0) {
521 error_setg_errno(errp, errno, "Could not create file");
522 return -EIO;
524 set_sparse(fd);
525 ftruncate(fd, total_size);
526 qemu_close(fd);
527 return 0;
531 static QemuOptsList raw_create_opts = {
532 .name = "raw-create-opts",
533 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
534 .desc = {
536 .name = BLOCK_OPT_SIZE,
537 .type = QEMU_OPT_SIZE,
538 .help = "Virtual disk size"
540 { /* end of list */ }
544 BlockDriver bdrv_file = {
545 .format_name = "file",
546 .protocol_name = "file",
547 .instance_size = sizeof(BDRVRawState),
548 .bdrv_needs_filename = true,
549 .bdrv_parse_filename = raw_parse_filename,
550 .bdrv_file_open = raw_open,
551 .bdrv_close = raw_close,
552 .bdrv_create = raw_create,
553 .bdrv_has_zero_init = bdrv_has_zero_init_1,
555 .bdrv_aio_readv = raw_aio_readv,
556 .bdrv_aio_writev = raw_aio_writev,
557 .bdrv_aio_flush = raw_aio_flush,
559 .bdrv_truncate = raw_truncate,
560 .bdrv_getlength = raw_getlength,
561 .bdrv_get_allocated_file_size
562 = raw_get_allocated_file_size,
564 .create_opts = &raw_create_opts,
567 /***********************************************/
568 /* host device */
570 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
572 char drives[256], *pdrv = drives;
573 UINT type;
575 memset(drives, 0, sizeof(drives));
576 GetLogicalDriveStrings(sizeof(drives), drives);
577 while(pdrv[0] != '\0') {
578 type = GetDriveType(pdrv);
579 switch(type) {
580 case DRIVE_CDROM:
581 snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
582 return 0;
583 break;
585 pdrv += lstrlen(pdrv) + 1;
587 return -1;
590 static int find_device_type(BlockDriverState *bs, const char *filename)
592 BDRVRawState *s = bs->opaque;
593 UINT type;
594 const char *p;
596 if (strstart(filename, "\\\\.\\", &p) ||
597 strstart(filename, "//./", &p)) {
598 if (stristart(p, "PhysicalDrive", NULL))
599 return FTYPE_HARDDISK;
600 snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", p[0]);
601 type = GetDriveType(s->drive_path);
602 switch (type) {
603 case DRIVE_REMOVABLE:
604 case DRIVE_FIXED:
605 return FTYPE_HARDDISK;
606 case DRIVE_CDROM:
607 return FTYPE_CD;
608 default:
609 return FTYPE_FILE;
611 } else {
612 return FTYPE_FILE;
616 static int hdev_probe_device(const char *filename)
618 if (strstart(filename, "/dev/cdrom", NULL))
619 return 100;
620 if (is_windows_drive(filename))
621 return 100;
622 return 0;
625 static void hdev_parse_filename(const char *filename, QDict *options,
626 Error **errp)
628 /* The prefix is optional, just as for "file". */
629 strstart(filename, "host_device:", &filename);
631 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
634 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
635 Error **errp)
637 BDRVRawState *s = bs->opaque;
638 int access_flags, create_flags;
639 int ret = 0;
640 DWORD overlapped;
641 char device_name[64];
643 Error *local_err = NULL;
644 const char *filename;
646 QemuOpts *opts = qemu_opts_create(&raw_runtime_opts, NULL, 0,
647 &error_abort);
648 qemu_opts_absorb_qdict(opts, options, &local_err);
649 if (local_err) {
650 error_propagate(errp, local_err);
651 ret = -EINVAL;
652 goto done;
655 filename = qemu_opt_get(opts, "filename");
657 if (strstart(filename, "/dev/cdrom", NULL)) {
658 if (find_cdrom(device_name, sizeof(device_name)) < 0) {
659 error_setg(errp, "Could not open CD-ROM drive");
660 ret = -ENOENT;
661 goto done;
663 filename = device_name;
664 } else {
665 /* transform drive letters into device name */
666 if (((filename[0] >= 'a' && filename[0] <= 'z') ||
667 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
668 filename[1] == ':' && filename[2] == '\0') {
669 snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
670 filename = device_name;
673 s->type = find_device_type(bs, filename);
675 raw_parse_flags(flags, &access_flags, &overlapped);
677 create_flags = OPEN_EXISTING;
679 s->hfile = CreateFile(filename, access_flags,
680 FILE_SHARE_READ, NULL,
681 create_flags, overlapped, NULL);
682 if (s->hfile == INVALID_HANDLE_VALUE) {
683 int err = GetLastError();
685 if (err == ERROR_ACCESS_DENIED) {
686 ret = -EACCES;
687 } else {
688 ret = -EINVAL;
690 error_setg_errno(errp, -ret, "Could not open device");
691 goto done;
694 done:
695 qemu_opts_del(opts);
696 return ret;
699 static BlockDriver bdrv_host_device = {
700 .format_name = "host_device",
701 .protocol_name = "host_device",
702 .instance_size = sizeof(BDRVRawState),
703 .bdrv_needs_filename = true,
704 .bdrv_parse_filename = hdev_parse_filename,
705 .bdrv_probe_device = hdev_probe_device,
706 .bdrv_file_open = hdev_open,
707 .bdrv_close = raw_close,
709 .bdrv_aio_readv = raw_aio_readv,
710 .bdrv_aio_writev = raw_aio_writev,
711 .bdrv_aio_flush = raw_aio_flush,
713 .bdrv_detach_aio_context = raw_detach_aio_context,
714 .bdrv_attach_aio_context = raw_attach_aio_context,
716 .bdrv_getlength = raw_getlength,
717 .has_variable_length = true,
719 .bdrv_get_allocated_file_size
720 = raw_get_allocated_file_size,
723 static void bdrv_file_init(void)
725 bdrv_register(&bdrv_file);
726 bdrv_register(&bdrv_host_device);
729 block_init(bdrv_file_init);