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 // TODO: re-test and re-coding needed
356 open_flags = O_BINARY & ~O_ACCMODE;
357 if (flags & BDRV_O_RDWR) {
358 open_flags |= O_RDWR;
360 open_flags |= O_RDONLY;
363 ret = qemu_open(filename, open_flags, 0644);
365 error_report("raw_open failed(%d) \n", ret);
368 s->hfile = (HANDLE)_get_osfhandle(ret);
371 if (flags & BDRV_O_NATIVE_AIO) {
372 s->aio = win32_aio_init();
373 if (s->aio == NULL) {
374 CloseHandle(s->hfile);
375 error_setg(errp, "Could not initialize AIO");
380 ret = win32_aio_attach(s->aio, s->hfile);
382 win32_aio_cleanup(s->aio);
383 CloseHandle(s->hfile);
384 error_setg_errno(errp, -ret, "Could not enable AIO");
388 win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));
391 raw_probe_alignment(bs);
398 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
399 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
400 BlockCompletionFunc *cb, void *opaque)
402 BDRVRawState *s = bs->opaque;
404 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
405 nb_sectors, cb, opaque, QEMU_AIO_READ);
407 return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
408 cb, opaque, QEMU_AIO_READ);
412 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
413 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
414 BlockCompletionFunc *cb, void *opaque)
416 BDRVRawState *s = bs->opaque;
418 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
419 nb_sectors, cb, opaque, QEMU_AIO_WRITE);
421 return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
422 cb, opaque, QEMU_AIO_WRITE);
426 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
427 BlockCompletionFunc *cb, void *opaque)
429 BDRVRawState *s = bs->opaque;
430 return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
433 static void raw_close(BlockDriverState *bs)
435 BDRVRawState *s = bs->opaque;
438 win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
439 win32_aio_cleanup(s->aio);
443 CloseHandle(s->hfile);
444 if (bs->open_flags & BDRV_O_TEMPORARY) {
445 unlink(bs->filename);
449 static int raw_truncate(BlockDriverState *bs, int64_t offset)
451 BDRVRawState *s = bs->opaque;
459 * An error has occurred if the return value is INVALID_SET_FILE_POINTER
460 * and GetLastError doesn't return NO_ERROR.
462 dwPtrLow = SetFilePointer(s->hfile, low, &high, FILE_BEGIN);
463 if (dwPtrLow == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
464 fprintf(stderr, "SetFilePointer error: %lu\n", GetLastError());
467 if (SetEndOfFile(s->hfile) == 0) {
468 fprintf(stderr, "SetEndOfFile error: %lu\n", GetLastError());
474 static int64_t raw_getlength(BlockDriverState *bs)
476 BDRVRawState *s = bs->opaque;
478 ULARGE_INTEGER available, total, total_free;
485 l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
486 if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
490 if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
492 l.QuadPart = total.QuadPart;
495 status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
496 NULL, 0, &dg, sizeof(dg), &count, NULL);
507 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
509 typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
511 get_compressed_t get_compressed;
513 const char *filename = bs->filename;
514 /* WinNT support GetCompressedFileSize to determine allocate size */
516 (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
517 "GetCompressedFileSizeA");
518 if (get_compressed) {
520 low = get_compressed(filename, &high);
521 if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR) {
522 return (((int64_t) high) << 32) + low;
526 if (_stati64(filename, &st) < 0) {
532 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
535 int64_t total_size = 0;
537 strstart(filename, "file:", &filename);
539 /* Read out options */
540 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
543 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
546 error_setg_errno(errp, errno, "Could not create file");
550 ftruncate(fd, total_size);
556 static QemuOptsList raw_create_opts = {
557 .name = "raw-create-opts",
558 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
561 .name = BLOCK_OPT_SIZE,
562 .type = QEMU_OPT_SIZE,
563 .help = "Virtual disk size"
565 { /* end of list */ }
569 static BlockDriver bdrv_file = {
570 .format_name = "file",
571 .protocol_name = "file",
572 .instance_size = sizeof(BDRVRawState),
573 .bdrv_needs_filename = true,
574 .bdrv_parse_filename = raw_parse_filename,
575 .bdrv_file_open = raw_open,
576 .bdrv_close = raw_close,
577 .bdrv_create = raw_create,
578 .bdrv_has_zero_init = bdrv_has_zero_init_1,
580 .bdrv_aio_readv = raw_aio_readv,
581 .bdrv_aio_writev = raw_aio_writev,
582 .bdrv_aio_flush = raw_aio_flush,
584 .bdrv_truncate = raw_truncate,
585 .bdrv_getlength = raw_getlength,
586 .bdrv_get_allocated_file_size
587 = raw_get_allocated_file_size,
589 .create_opts = &raw_create_opts,
592 /***********************************************/
595 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
597 char drives[256], *pdrv = drives;
600 memset(drives, 0, sizeof(drives));
601 GetLogicalDriveStrings(sizeof(drives), drives);
602 while(pdrv[0] != '\0') {
603 type = GetDriveType(pdrv);
606 snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
610 pdrv += lstrlen(pdrv) + 1;
615 static int find_device_type(BlockDriverState *bs, const char *filename)
617 BDRVRawState *s = bs->opaque;
621 if (strstart(filename, "\\\\.\\", &p) ||
622 strstart(filename, "//./", &p)) {
623 if (stristart(p, "PhysicalDrive", NULL))
624 return FTYPE_HARDDISK;
625 snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", p[0]);
626 type = GetDriveType(s->drive_path);
628 case DRIVE_REMOVABLE:
630 return FTYPE_HARDDISK;
641 static int hdev_probe_device(const char *filename)
643 if (strstart(filename, "/dev/cdrom", NULL))
645 if (is_windows_drive(filename))
650 static void hdev_parse_filename(const char *filename, QDict *options,
653 /* The prefix is optional, just as for "file". */
654 strstart(filename, "host_device:", &filename);
656 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
659 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
662 BDRVRawState *s = bs->opaque;
664 int access_flags, create_flags;
671 char device_name[64];
673 Error *local_err = NULL;
674 const char *filename;
676 QemuOpts *opts = qemu_opts_create(&raw_runtime_opts, NULL, 0,
678 qemu_opts_absorb_qdict(opts, options, &local_err);
680 error_propagate(errp, local_err);
685 filename = qemu_opt_get(opts, "filename");
687 if (strstart(filename, "/dev/cdrom", NULL)) {
688 if (find_cdrom(device_name, sizeof(device_name)) < 0) {
689 error_setg(errp, "Could not open CD-ROM drive");
693 filename = device_name;
695 /* transform drive letters into device name */
696 if (((filename[0] >= 'a' && filename[0] <= 'z') ||
697 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
698 filename[1] == ':' && filename[2] == '\0') {
699 snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
700 filename = device_name;
703 s->type = find_device_type(bs, filename);
706 raw_parse_flags(flags, &access_flags, &overlapped);
708 create_flags = OPEN_EXISTING;
710 s->hfile = CreateFile(filename, access_flags,
711 FILE_SHARE_READ, NULL,
712 create_flags, overlapped, NULL);
713 if (s->hfile == INVALID_HANDLE_VALUE) {
714 int err = GetLastError();
716 if (err == ERROR_ACCESS_DENIED) {
721 error_setg_errno(errp, -ret, "Could not open device");
726 s->hfile = CreateFile(g_win32_locale_filename_from_utf8(filename),
728 FILE_SHARE_READ, NULL,
729 create_flags, overlapped, NULL);
731 open_flags = (O_BINARY & ~O_ACCMODE);
732 if (flags & BDRV_O_RDWR) {
733 open_flags |= O_RDWR;
735 open_flags |= O_RDONLY;
738 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
739 * and O_DIRECT for no caching. */
741 if ((flags & BDRV_O_NOCACHE)) {
742 open_flags |= O_DIRECT;
744 if (!(flags & BDRV_O_CACHE_WB)) {
745 open_flags |= O_DSYNC;
749 ret = qemu_open(filename, open_flags, 0644);
751 error_report("raw_open failed(%d) \n", ret);
754 s->hfile = (HANDLE)_get_osfhandle(ret);
763 static BlockDriver bdrv_host_device = {
764 .format_name = "host_device",
765 .protocol_name = "host_device",
766 .instance_size = sizeof(BDRVRawState),
767 .bdrv_needs_filename = true,
768 .bdrv_parse_filename = hdev_parse_filename,
769 .bdrv_probe_device = hdev_probe_device,
770 .bdrv_file_open = hdev_open,
771 .bdrv_close = raw_close,
773 .bdrv_aio_readv = raw_aio_readv,
774 .bdrv_aio_writev = raw_aio_writev,
775 .bdrv_aio_flush = raw_aio_flush,
777 .bdrv_detach_aio_context = raw_detach_aio_context,
778 .bdrv_attach_aio_context = raw_attach_aio_context,
780 .bdrv_getlength = raw_getlength,
781 .has_variable_length = true,
783 .bdrv_get_allocated_file_size
784 = raw_get_allocated_file_size,
787 static void bdrv_file_init(void)
789 bdrv_register(&bdrv_file);
790 bdrv_register(&bdrv_host_device);
793 block_init(bdrv_file_init);