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/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu/cutils.h"
27 #include "qemu/timer.h"
28 #include "block/block_int.h"
29 #include "qemu/module.h"
30 #include "block/raw-aio.h"
32 #include "block/thread-pool.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qapi/util.h"
41 #define FTYPE_HARDDISK 2
43 typedef struct RawWin32AIOData {
46 struct iovec *aio_iov;
53 typedef struct BDRVRawState {
56 char drive_path[16]; /* format: "d:\" */
57 QEMUWin32AIOState *aio;
61 * Read/writes the data to/from a given linear buffer.
63 * Returns the number of bytes handles or -errno in case of an error. Short
64 * reads are only returned if the end of the file is reached.
66 static size_t handle_aiocb_rw(RawWin32AIOData *aiocb)
71 for (i = 0; i < aiocb->aio_niov; i++) {
73 DWORD ret, ret_count, len;
75 memset(&ov, 0, sizeof(ov));
76 ov.Offset = (aiocb->aio_offset + offset);
77 ov.OffsetHigh = (aiocb->aio_offset + offset) >> 32;
78 len = aiocb->aio_iov[i].iov_len;
79 if (aiocb->aio_type & QEMU_AIO_WRITE) {
80 ret = WriteFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
81 len, &ret_count, &ov);
83 ret = ReadFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
84 len, &ret_count, &ov);
89 if (ret_count != len) {
99 static int aio_worker(void *arg)
101 RawWin32AIOData *aiocb = arg;
105 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
107 count = handle_aiocb_rw(aiocb);
108 if (count < aiocb->aio_nbytes) {
109 /* A short read means that we have reached EOF. Pad the buffer
110 * with zeros for bytes after EOF. */
111 iov_memset(aiocb->aio_iov, aiocb->aio_niov, count,
112 0, aiocb->aio_nbytes - count);
114 count = aiocb->aio_nbytes;
116 if (count == aiocb->aio_nbytes) {
123 count = handle_aiocb_rw(aiocb);
124 if (count == aiocb->aio_nbytes) {
131 if (!FlushFileBuffers(aiocb->hfile)) {
136 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
145 static BlockAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
146 int64_t offset, QEMUIOVector *qiov, int count,
147 BlockCompletionFunc *cb, void *opaque, int type)
149 RawWin32AIOData *acb = g_new(RawWin32AIOData, 1);
154 acb->aio_type = type;
157 acb->aio_iov = qiov->iov;
158 acb->aio_niov = qiov->niov;
159 assert(qiov->size == count);
161 acb->aio_nbytes = count;
162 acb->aio_offset = offset;
164 trace_paio_submit(acb, opaque, offset, count, type);
165 pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
166 return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
169 int qemu_ftruncate64(int fd, int64_t length)
177 if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
180 h = (HANDLE)_get_osfhandle(fd);
182 /* get current position, ftruncate do not change position */
184 li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
185 if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
190 dw = SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN);
191 if (dw == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
194 res = SetEndOfFile(h);
196 /* back to old position */
197 SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
201 static int set_sparse(int fd)
204 return (int) DeviceIoControl((HANDLE)_get_osfhandle(fd), FSCTL_SET_SPARSE,
205 NULL, 0, NULL, 0, &returned, NULL);
208 static void raw_detach_aio_context(BlockDriverState *bs)
210 BDRVRawState *s = bs->opaque;
213 win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
217 static void raw_attach_aio_context(BlockDriverState *bs,
218 AioContext *new_context)
220 BDRVRawState *s = bs->opaque;
223 win32_aio_attach_aio_context(s->aio, new_context);
227 static void raw_probe_alignment(BlockDriverState *bs, Error **errp)
229 BDRVRawState *s = bs->opaque;
230 DWORD sectorsPerCluster, freeClusters, totalClusters, count;
234 if (s->type == FTYPE_CD) {
235 bs->bl.request_alignment = 2048;
238 if (s->type == FTYPE_HARDDISK) {
239 status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
240 NULL, 0, &dg, sizeof(dg), &count, NULL);
242 bs->bl.request_alignment = dg.Geometry.BytesPerSector;
245 /* try GetDiskFreeSpace too */
248 if (s->drive_path[0]) {
249 GetDiskFreeSpace(s->drive_path, §orsPerCluster,
250 &dg.Geometry.BytesPerSector,
251 &freeClusters, &totalClusters);
252 bs->bl.request_alignment = dg.Geometry.BytesPerSector;
256 static void raw_parse_flags(int flags, bool use_aio, int *access_flags,
259 assert(access_flags != NULL);
260 assert(overlapped != NULL);
262 if (flags & BDRV_O_RDWR) {
263 *access_flags = GENERIC_READ | GENERIC_WRITE;
265 *access_flags = GENERIC_READ;
268 *overlapped = FILE_ATTRIBUTE_NORMAL;
270 *overlapped |= FILE_FLAG_OVERLAPPED;
272 if (flags & BDRV_O_NOCACHE) {
273 *overlapped |= FILE_FLAG_NO_BUFFERING;
277 static void raw_parse_filename(const char *filename, QDict *options,
280 /* The filename does not have to be prefixed by the protocol name, since
281 * "file" is the default protocol; therefore, the return value of this
282 * function call can be ignored. */
283 strstart(filename, "file:", &filename);
285 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
288 static QemuOptsList raw_runtime_opts = {
290 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
294 .type = QEMU_OPT_STRING,
295 .help = "File name of the image",
299 .type = QEMU_OPT_STRING,
300 .help = "host AIO implementation (threads, native)",
302 { /* end of list */ }
306 static bool get_aio_option(QemuOpts *opts, int flags, Error **errp)
308 BlockdevAioOptions aio, aio_default;
310 aio_default = (flags & BDRV_O_NATIVE_AIO) ? BLOCKDEV_AIO_OPTIONS_NATIVE
311 : BLOCKDEV_AIO_OPTIONS_THREADS;
312 aio = qapi_enum_parse(BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"),
313 BLOCKDEV_AIO_OPTIONS__MAX, aio_default, errp);
316 case BLOCKDEV_AIO_OPTIONS_NATIVE:
318 case BLOCKDEV_AIO_OPTIONS_THREADS:
321 error_setg(errp, "Invalid AIO option");
326 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
329 BDRVRawState *s = bs->opaque;
333 Error *local_err = NULL;
334 const char *filename;
338 s->type = FTYPE_FILE;
340 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
341 qemu_opts_absorb_qdict(opts, options, &local_err);
343 error_propagate(errp, local_err);
348 filename = qemu_opt_get(opts, "filename");
350 use_aio = get_aio_option(opts, flags, &local_err);
352 error_propagate(errp, local_err);
357 raw_parse_flags(flags, use_aio, &access_flags, &overlapped);
359 if (filename[0] && filename[1] == ':') {
360 snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", filename[0]);
361 } else if (filename[0] == '\\' && filename[1] == '\\') {
362 s->drive_path[0] = 0;
366 GetCurrentDirectory(MAX_PATH, buf);
367 snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]);
370 s->hfile = CreateFile(filename, access_flags,
371 FILE_SHARE_READ, NULL,
372 OPEN_EXISTING, overlapped, NULL);
373 if (s->hfile == INVALID_HANDLE_VALUE) {
374 int err = GetLastError();
376 error_setg_win32(errp, err, "Could not open '%s'", filename);
377 if (err == ERROR_ACCESS_DENIED) {
386 s->aio = win32_aio_init();
387 if (s->aio == NULL) {
388 CloseHandle(s->hfile);
389 error_setg(errp, "Could not initialize AIO");
394 ret = win32_aio_attach(s->aio, s->hfile);
396 win32_aio_cleanup(s->aio);
397 CloseHandle(s->hfile);
398 error_setg_errno(errp, -ret, "Could not enable AIO");
402 win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));
411 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
412 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
413 BlockCompletionFunc *cb, void *opaque)
415 BDRVRawState *s = bs->opaque;
417 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
418 nb_sectors, cb, opaque, QEMU_AIO_READ);
420 return paio_submit(bs, s->hfile, sector_num << BDRV_SECTOR_BITS, qiov,
421 nb_sectors << BDRV_SECTOR_BITS,
422 cb, opaque, QEMU_AIO_READ);
426 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
427 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
428 BlockCompletionFunc *cb, void *opaque)
430 BDRVRawState *s = bs->opaque;
432 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
433 nb_sectors, cb, opaque, QEMU_AIO_WRITE);
435 return paio_submit(bs, s->hfile, sector_num << BDRV_SECTOR_BITS, qiov,
436 nb_sectors << BDRV_SECTOR_BITS,
437 cb, opaque, QEMU_AIO_WRITE);
441 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
442 BlockCompletionFunc *cb, void *opaque)
444 BDRVRawState *s = bs->opaque;
445 return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
448 static void raw_close(BlockDriverState *bs)
450 BDRVRawState *s = bs->opaque;
453 win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
454 win32_aio_cleanup(s->aio);
458 CloseHandle(s->hfile);
459 if (bs->open_flags & BDRV_O_TEMPORARY) {
460 unlink(bs->filename);
464 static int raw_truncate(BlockDriverState *bs, int64_t offset)
466 BDRVRawState *s = bs->opaque;
474 * An error has occurred if the return value is INVALID_SET_FILE_POINTER
475 * and GetLastError doesn't return NO_ERROR.
477 dwPtrLow = SetFilePointer(s->hfile, low, &high, FILE_BEGIN);
478 if (dwPtrLow == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
479 fprintf(stderr, "SetFilePointer error: %lu\n", GetLastError());
482 if (SetEndOfFile(s->hfile) == 0) {
483 fprintf(stderr, "SetEndOfFile error: %lu\n", GetLastError());
489 static int64_t raw_getlength(BlockDriverState *bs)
491 BDRVRawState *s = bs->opaque;
493 ULARGE_INTEGER available, total, total_free;
500 l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
501 if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
505 if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
507 l.QuadPart = total.QuadPart;
510 status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
511 NULL, 0, &dg, sizeof(dg), &count, NULL);
522 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
524 typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
526 get_compressed_t get_compressed;
528 const char *filename = bs->filename;
529 /* WinNT support GetCompressedFileSize to determine allocate size */
531 (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
532 "GetCompressedFileSizeA");
533 if (get_compressed) {
535 low = get_compressed(filename, &high);
536 if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR) {
537 return (((int64_t) high) << 32) + low;
541 if (_stati64(filename, &st) < 0) {
547 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
550 int64_t total_size = 0;
552 strstart(filename, "file:", &filename);
554 /* Read out options */
555 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
558 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
561 error_setg_errno(errp, errno, "Could not create file");
565 ftruncate(fd, total_size);
571 static QemuOptsList raw_create_opts = {
572 .name = "raw-create-opts",
573 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
576 .name = BLOCK_OPT_SIZE,
577 .type = QEMU_OPT_SIZE,
578 .help = "Virtual disk size"
580 { /* end of list */ }
584 BlockDriver bdrv_file = {
585 .format_name = "file",
586 .protocol_name = "file",
587 .instance_size = sizeof(BDRVRawState),
588 .bdrv_needs_filename = true,
589 .bdrv_parse_filename = raw_parse_filename,
590 .bdrv_file_open = raw_open,
591 .bdrv_refresh_limits = raw_probe_alignment,
592 .bdrv_close = raw_close,
593 .bdrv_create = raw_create,
594 .bdrv_has_zero_init = bdrv_has_zero_init_1,
596 .bdrv_aio_readv = raw_aio_readv,
597 .bdrv_aio_writev = raw_aio_writev,
598 .bdrv_aio_flush = raw_aio_flush,
600 .bdrv_truncate = raw_truncate,
601 .bdrv_getlength = raw_getlength,
602 .bdrv_get_allocated_file_size
603 = raw_get_allocated_file_size,
605 .create_opts = &raw_create_opts,
608 /***********************************************/
611 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
613 char drives[256], *pdrv = drives;
616 memset(drives, 0, sizeof(drives));
617 GetLogicalDriveStrings(sizeof(drives), drives);
618 while(pdrv[0] != '\0') {
619 type = GetDriveType(pdrv);
622 snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
626 pdrv += lstrlen(pdrv) + 1;
631 static int find_device_type(BlockDriverState *bs, const char *filename)
633 BDRVRawState *s = bs->opaque;
637 if (strstart(filename, "\\\\.\\", &p) ||
638 strstart(filename, "//./", &p)) {
639 if (stristart(p, "PhysicalDrive", NULL))
640 return FTYPE_HARDDISK;
641 snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", p[0]);
642 type = GetDriveType(s->drive_path);
644 case DRIVE_REMOVABLE:
646 return FTYPE_HARDDISK;
657 static int hdev_probe_device(const char *filename)
659 if (strstart(filename, "/dev/cdrom", NULL))
661 if (is_windows_drive(filename))
666 static void hdev_parse_filename(const char *filename, QDict *options,
669 /* The prefix is optional, just as for "file". */
670 strstart(filename, "host_device:", &filename);
672 qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
675 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
678 BDRVRawState *s = bs->opaque;
679 int access_flags, create_flags;
682 char device_name[64];
684 Error *local_err = NULL;
685 const char *filename;
688 QemuOpts *opts = qemu_opts_create(&raw_runtime_opts, NULL, 0,
690 qemu_opts_absorb_qdict(opts, options, &local_err);
692 error_propagate(errp, local_err);
697 filename = qemu_opt_get(opts, "filename");
699 use_aio = get_aio_option(opts, flags, &local_err);
700 if (!local_err && use_aio) {
701 error_setg(&local_err, "AIO is not supported on Windows host devices");
704 error_propagate(errp, local_err);
709 if (strstart(filename, "/dev/cdrom", NULL)) {
710 if (find_cdrom(device_name, sizeof(device_name)) < 0) {
711 error_setg(errp, "Could not open CD-ROM drive");
715 filename = device_name;
717 /* transform drive letters into device name */
718 if (((filename[0] >= 'a' && filename[0] <= 'z') ||
719 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
720 filename[1] == ':' && filename[2] == '\0') {
721 snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
722 filename = device_name;
725 s->type = find_device_type(bs, filename);
727 raw_parse_flags(flags, use_aio, &access_flags, &overlapped);
729 create_flags = OPEN_EXISTING;
731 s->hfile = CreateFile(filename, access_flags,
732 FILE_SHARE_READ, NULL,
733 create_flags, overlapped, NULL);
734 if (s->hfile == INVALID_HANDLE_VALUE) {
735 int err = GetLastError();
737 if (err == ERROR_ACCESS_DENIED) {
742 error_setg_errno(errp, -ret, "Could not open device");
751 static BlockDriver bdrv_host_device = {
752 .format_name = "host_device",
753 .protocol_name = "host_device",
754 .instance_size = sizeof(BDRVRawState),
755 .bdrv_needs_filename = true,
756 .bdrv_parse_filename = hdev_parse_filename,
757 .bdrv_probe_device = hdev_probe_device,
758 .bdrv_file_open = hdev_open,
759 .bdrv_close = raw_close,
761 .bdrv_aio_readv = raw_aio_readv,
762 .bdrv_aio_writev = raw_aio_writev,
763 .bdrv_aio_flush = raw_aio_flush,
765 .bdrv_detach_aio_context = raw_detach_aio_context,
766 .bdrv_attach_aio_context = raw_attach_aio_context,
768 .bdrv_getlength = raw_getlength,
769 .has_variable_length = true,
771 .bdrv_get_allocated_file_size
772 = raw_get_allocated_file_size,
775 static void bdrv_file_init(void)
777 bdrv_register(&bdrv_file);
778 bdrv_register(&bdrv_host_device);
781 block_init(bdrv_file_init);