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
24 #include "qemu-common.h"
25 #include "qemu/timer.h"
26 #include "block/block_int.h"
27 #include "qemu/module.h"
30 #include "block/thread-pool.h"
40 #define FTYPE_HARDDISK 2
42 typedef struct RawWin32AIOData {
45 struct iovec *aio_iov;
52 typedef struct BDRVRawState {
55 char drive_path[16]; /* format: "d:\" */
56 QEMUWin32AIOState *aio;
60 * Read/writes the data to/from a given linear buffer.
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.
65 static size_t handle_aiocb_rw(RawWin32AIOData *aiocb)
70 for (i = 0; i < aiocb->aio_niov; i++) {
72 DWORD ret, ret_count, len;
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);
82 ret = ReadFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
83 len, &ret_count, &ov);
88 if (ret_count != len) {
98 static int aio_worker(void *arg)
100 RawWin32AIOData *aiocb = arg;
104 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
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);
113 count = aiocb->aio_nbytes;
115 if (count == aiocb->aio_nbytes) {
122 count = handle_aiocb_rw(aiocb);
123 if (count == aiocb->aio_nbytes) {
130 if (!FlushFileBuffers(aiocb->hfile)) {
135 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
140 g_slice_free(RawWin32AIOData, aiocb);
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)
148 RawWin32AIOData *acb = g_slice_new(RawWin32AIOData);
153 acb->aio_type = type;
156 acb->aio_iov = qiov->iov;
157 acb->aio_niov = qiov->niov;
159 acb->aio_nbytes = nb_sectors * 512;
160 acb->aio_offset = sector_num * 512;
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);
167 int qemu_ftruncate64(int fd, int64_t length)
175 if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
178 h = (HANDLE)_get_osfhandle(fd);
180 /* get current position, ftruncate do not change position */
182 li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
183 if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
188 dw = SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN);
189 if (dw == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
192 res = SetEndOfFile(h);
194 /* back to old position */
195 SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
199 static int set_sparse(int fd)
202 return (int) DeviceIoControl((HANDLE)_get_osfhandle(fd), FSCTL_SET_SPARSE,
203 NULL, 0, NULL, 0, &returned, NULL);
206 static void raw_detach_aio_context(BlockDriverState *bs)
208 BDRVRawState *s = bs->opaque;
211 win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
215 static void raw_attach_aio_context(BlockDriverState *bs,
216 AioContext *new_context)
218 BDRVRawState *s = bs->opaque;
221 win32_aio_attach_aio_context(s->aio, new_context);
225 static void raw_probe_alignment(BlockDriverState *bs)
227 BDRVRawState *s = bs->opaque;
228 DWORD sectorsPerCluster, freeClusters, totalClusters, count;
232 if (s->type == FTYPE_CD) {
233 bs->request_alignment = 2048;
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);
240 bs->request_alignment = dg.Geometry.BytesPerSector;
243 /* try GetDiskFreeSpace too */
246 if (s->drive_path[0]) {
247 GetDiskFreeSpace(s->drive_path, §orsPerCluster,
248 &dg.Geometry.BytesPerSector,
249 &freeClusters, &totalClusters);
250 bs->request_alignment = dg.Geometry.BytesPerSector;
255 static void raw_parse_flags(int flags, int *access_flags, DWORD *overlapped)
257 assert(access_flags != NULL);
258 assert(overlapped != NULL);
260 if (flags & BDRV_O_RDWR) {
261 *access_flags = GENERIC_READ | GENERIC_WRITE;
263 *access_flags = GENERIC_READ;
266 *overlapped = FILE_ATTRIBUTE_NORMAL;
267 if (flags & BDRV_O_NATIVE_AIO) {
268 *overlapped |= FILE_FLAG_OVERLAPPED;
270 if (flags & BDRV_O_NOCACHE) {
271 *overlapped |= FILE_FLAG_NO_BUFFERING;
276 static void raw_parse_filename(const char *filename, QDict *options,
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);
284 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
287 static QemuOptsList raw_runtime_opts = {
289 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
293 .type = QEMU_OPT_STRING,
294 .help = "File name of the image",
296 { /* end of list */ }
300 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
303 BDRVRawState *s = bs->opaque;
305 Error *local_err = NULL;
306 const char *filename;
315 s->type = FTYPE_FILE;
317 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
318 qemu_opts_absorb_qdict(opts, options, &local_err);
320 error_propagate(errp, local_err);
325 filename = qemu_opt_get(opts, "filename");
328 raw_parse_flags(flags, &access_flags, &overlapped);
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;
337 GetCurrentDirectory(MAX_PATH, buf);
338 snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]);
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();
347 if (err == ERROR_ACCESS_DENIED) {
355 open_flags = O_BINARY & ~O_ACCMODE;
356 if (flags & BDRV_O_RDWR) {
357 open_flags |= O_RDWR;
359 open_flags |= O_RDONLY;
362 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
363 * and O_DIRECT for no caching. */
365 if ((flags & BDRV_O_NOCACHE)) {
366 open_flags |= O_DIRECT;
368 if (!(flags & BDRV_O_CACHE_WB)) {
369 open_flags |= O_DSYNC;
373 if ((flags & BDRV_O_NATIVE_AIO) && aio == NULL) {
374 aio = win32_aio_init();
381 ret = qemu_open(filename, open_flags, 0644);
383 error_report("raw_open failed(%d) \n", ret);
386 s->hfile = (HANDLE)_get_osfhandle(ret);
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");
398 ret = win32_aio_attach(s->aio, s->hfile);
400 win32_aio_cleanup(s->aio);
401 CloseHandle(s->hfile);
402 error_setg_errno(errp, -ret, "Could not enable AIO");
406 win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));
409 raw_probe_alignment(bs);
416 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
417 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
418 BlockCompletionFunc *cb, void *opaque)
420 BDRVRawState *s = bs->opaque;
422 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
423 nb_sectors, cb, opaque, QEMU_AIO_READ);
425 return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
426 cb, opaque, QEMU_AIO_READ);
430 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
431 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
432 BlockCompletionFunc *cb, void *opaque)
434 BDRVRawState *s = bs->opaque;
436 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
437 nb_sectors, cb, opaque, QEMU_AIO_WRITE);
439 return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
440 cb, opaque, QEMU_AIO_WRITE);
444 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
445 BlockCompletionFunc *cb, void *opaque)
447 BDRVRawState *s = bs->opaque;
448 return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
451 static void raw_close(BlockDriverState *bs)
453 BDRVRawState *s = bs->opaque;
456 win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
457 win32_aio_cleanup(s->aio);
461 CloseHandle(s->hfile);
462 if (bs->open_flags & BDRV_O_TEMPORARY) {
463 unlink(bs->filename);
467 static int raw_truncate(BlockDriverState *bs, int64_t offset)
469 BDRVRawState *s = bs->opaque;
477 * An error has occurred if the return value is INVALID_SET_FILE_POINTER
478 * and GetLastError doesn't return NO_ERROR.
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());
485 if (SetEndOfFile(s->hfile) == 0) {
486 fprintf(stderr, "SetEndOfFile error: %lu\n", GetLastError());
492 static int64_t raw_getlength(BlockDriverState *bs)
494 BDRVRawState *s = bs->opaque;
496 ULARGE_INTEGER available, total, total_free;
503 l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
504 if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
508 if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
510 l.QuadPart = total.QuadPart;
513 status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
514 NULL, 0, &dg, sizeof(dg), &count, NULL);
525 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
527 typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
529 get_compressed_t get_compressed;
531 const char *filename = bs->filename;
532 /* WinNT support GetCompressedFileSize to determine allocate size */
534 (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
535 "GetCompressedFileSizeA");
536 if (get_compressed) {
538 low = get_compressed(filename, &high);
539 if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR) {
540 return (((int64_t) high) << 32) + low;
544 if (_stati64(filename, &st) < 0) {
550 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
553 int64_t total_size = 0;
555 strstart(filename, "file:", &filename);
557 /* Read out options */
558 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
561 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
564 error_setg_errno(errp, errno, "Could not create file");
568 ftruncate(fd, total_size);
574 static QemuOptsList raw_create_opts = {
575 .name = "raw-create-opts",
576 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
579 .name = BLOCK_OPT_SIZE,
580 .type = QEMU_OPT_SIZE,
581 .help = "Virtual disk size"
583 { /* end of list */ }
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,
598 .bdrv_aio_readv = raw_aio_readv,
599 .bdrv_aio_writev = raw_aio_writev,
600 .bdrv_aio_flush = raw_aio_flush,
602 .bdrv_truncate = raw_truncate,
603 .bdrv_getlength = raw_getlength,
604 .bdrv_get_allocated_file_size
605 = raw_get_allocated_file_size,
607 .create_opts = &raw_create_opts,
610 /***********************************************/
613 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
615 char drives[256], *pdrv = drives;
618 memset(drives, 0, sizeof(drives));
619 GetLogicalDriveStrings(sizeof(drives), drives);
620 while(pdrv[0] != '\0') {
621 type = GetDriveType(pdrv);
624 snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
628 pdrv += lstrlen(pdrv) + 1;
633 static int find_device_type(BlockDriverState *bs, const char *filename)
635 BDRVRawState *s = bs->opaque;
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);
646 case DRIVE_REMOVABLE:
648 return FTYPE_HARDDISK;
659 static int hdev_probe_device(const char *filename)
661 if (strstart(filename, "/dev/cdrom", NULL))
663 if (is_windows_drive(filename))
668 static void hdev_parse_filename(const char *filename, QDict *options,
671 /* The prefix is optional, just as for "file". */
672 strstart(filename, "host_device:", &filename);
674 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
677 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
680 BDRVRawState *s = bs->opaque;
682 int access_flags, create_flags;
689 char device_name[64];
691 Error *local_err = NULL;
692 const char *filename;
694 QemuOpts *opts = qemu_opts_create(&raw_runtime_opts, NULL, 0,
696 qemu_opts_absorb_qdict(opts, options, &local_err);
698 error_propagate(errp, local_err);
703 filename = qemu_opt_get(opts, "filename");
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");
711 filename = device_name;
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;
721 s->type = find_device_type(bs, filename);
724 raw_parse_flags(flags, &access_flags, &overlapped);
726 create_flags = OPEN_EXISTING;
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();
734 if (err == ERROR_ACCESS_DENIED) {
739 error_setg_errno(errp, -ret, "Could not open device");
744 s->hfile = CreateFile(g_win32_locale_filename_from_utf8(filename),
746 FILE_SHARE_READ, NULL,
747 create_flags, overlapped, NULL);
749 open_flags = (O_BINARY & ~O_ACCMODE);
750 if (flags & BDRV_O_RDWR) {
751 open_flags |= O_RDWR;
753 open_flags |= O_RDONLY;
756 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
757 * and O_DIRECT for no caching. */
759 if ((flags & BDRV_O_NOCACHE)) {
760 open_flags |= O_DIRECT;
762 if (!(flags & BDRV_O_CACHE_WB)) {
763 open_flags |= O_DSYNC;
767 ret = qemu_open(filename, open_flags, 0644);
769 error_report("raw_open failed(%d) \n", ret);
772 s->hfile = (HANDLE)_get_osfhandle(ret);
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,
791 .bdrv_aio_readv = raw_aio_readv,
792 .bdrv_aio_writev = raw_aio_writev,
793 .bdrv_aio_flush = raw_aio_flush,
795 .bdrv_detach_aio_context = raw_detach_aio_context,
796 .bdrv_attach_aio_context = raw_attach_aio_context,
798 .bdrv_getlength = raw_getlength,
799 .has_variable_length = true,
801 .bdrv_get_allocated_file_size
802 = raw_get_allocated_file_size,
805 static void bdrv_file_init(void)
807 bdrv_register(&bdrv_file);
808 bdrv_register(&bdrv_host_device);
811 block_init(bdrv_file_init);