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 "block/block_int.h"
28 #include "qemu/module.h"
29 #include "block/raw-aio.h"
31 #include "block/thread-pool.h"
33 #include "qapi/qmp/qstring.h"
34 #include "qapi/util.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
) {
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
);
144 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, HANDLE hfile
,
145 int64_t offset
, QEMUIOVector
*qiov
, int count
,
146 BlockCompletionFunc
*cb
, void *opaque
, int type
)
148 RawWin32AIOData
*acb
= g_new(RawWin32AIOData
, 1);
153 acb
->aio_type
= type
;
156 acb
->aio_iov
= qiov
->iov
;
157 acb
->aio_niov
= qiov
->niov
;
158 assert(qiov
->size
== count
);
160 acb
->aio_nbytes
= count
;
161 acb
->aio_offset
= offset
;
163 trace_paio_submit(acb
, opaque
, offset
, count
, type
);
164 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
165 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
168 int qemu_ftruncate64(int fd
, int64_t length
)
176 if ((GetVersion() & 0x80000000UL
) && (length
>> 32) != 0)
179 h
= (HANDLE
)_get_osfhandle(fd
);
181 /* get current position, ftruncate do not change position */
183 li
.LowPart
= SetFilePointer (h
, 0, &li
.HighPart
, FILE_CURRENT
);
184 if (li
.LowPart
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
189 dw
= SetFilePointer(h
, (DWORD
) length
, &high
, FILE_BEGIN
);
190 if (dw
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
193 res
= SetEndOfFile(h
);
195 /* back to old position */
196 SetFilePointer(h
, li
.LowPart
, &li
.HighPart
, FILE_BEGIN
);
200 static int set_sparse(int fd
)
203 return (int) DeviceIoControl((HANDLE
)_get_osfhandle(fd
), FSCTL_SET_SPARSE
,
204 NULL
, 0, NULL
, 0, &returned
, NULL
);
207 static void raw_detach_aio_context(BlockDriverState
*bs
)
209 BDRVRawState
*s
= bs
->opaque
;
212 win32_aio_detach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
216 static void raw_attach_aio_context(BlockDriverState
*bs
,
217 AioContext
*new_context
)
219 BDRVRawState
*s
= bs
->opaque
;
222 win32_aio_attach_aio_context(s
->aio
, new_context
);
226 static void raw_probe_alignment(BlockDriverState
*bs
, Error
**errp
)
228 BDRVRawState
*s
= bs
->opaque
;
229 DWORD sectorsPerCluster
, freeClusters
, totalClusters
, count
;
233 if (s
->type
== FTYPE_CD
) {
234 bs
->bl
.request_alignment
= 2048;
237 if (s
->type
== FTYPE_HARDDISK
) {
238 status
= DeviceIoControl(s
->hfile
, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX
,
239 NULL
, 0, &dg
, sizeof(dg
), &count
, NULL
);
241 bs
->bl
.request_alignment
= dg
.Geometry
.BytesPerSector
;
244 /* try GetDiskFreeSpace too */
247 if (s
->drive_path
[0]) {
248 GetDiskFreeSpace(s
->drive_path
, §orsPerCluster
,
249 &dg
.Geometry
.BytesPerSector
,
250 &freeClusters
, &totalClusters
);
251 bs
->bl
.request_alignment
= dg
.Geometry
.BytesPerSector
;
255 static void raw_parse_flags(int flags
, bool use_aio
, int *access_flags
,
258 assert(access_flags
!= NULL
);
259 assert(overlapped
!= NULL
);
261 if (flags
& BDRV_O_RDWR
) {
262 *access_flags
= GENERIC_READ
| GENERIC_WRITE
;
264 *access_flags
= GENERIC_READ
;
267 *overlapped
= FILE_ATTRIBUTE_NORMAL
;
269 *overlapped
|= FILE_FLAG_OVERLAPPED
;
271 if (flags
& BDRV_O_NOCACHE
) {
272 *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_str(options
, "filename", 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",
298 .type
= QEMU_OPT_STRING
,
299 .help
= "host AIO implementation (threads, native)",
301 { /* end of list */ }
305 static bool get_aio_option(QemuOpts
*opts
, int flags
, Error
**errp
)
307 BlockdevAioOptions aio
, aio_default
;
309 aio_default
= (flags
& BDRV_O_NATIVE_AIO
) ? BLOCKDEV_AIO_OPTIONS_NATIVE
310 : BLOCKDEV_AIO_OPTIONS_THREADS
;
311 aio
= qapi_enum_parse(BlockdevAioOptions_lookup
, qemu_opt_get(opts
, "aio"),
312 BLOCKDEV_AIO_OPTIONS__MAX
, aio_default
, errp
);
315 case BLOCKDEV_AIO_OPTIONS_NATIVE
:
317 case BLOCKDEV_AIO_OPTIONS_THREADS
:
320 error_setg(errp
, "Invalid AIO option");
325 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
328 BDRVRawState
*s
= bs
->opaque
;
332 Error
*local_err
= NULL
;
333 const char *filename
;
337 s
->type
= FTYPE_FILE
;
339 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
340 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
342 error_propagate(errp
, local_err
);
347 if (qdict_get_try_bool(options
, "locking", false)) {
348 error_setg(errp
, "locking=on is not supported on Windows");
352 filename
= qemu_opt_get(opts
, "filename");
354 use_aio
= get_aio_option(opts
, flags
, &local_err
);
356 error_propagate(errp
, local_err
);
361 raw_parse_flags(flags
, use_aio
, &access_flags
, &overlapped
);
363 if (filename
[0] && filename
[1] == ':') {
364 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", filename
[0]);
365 } else if (filename
[0] == '\\' && filename
[1] == '\\') {
366 s
->drive_path
[0] = 0;
370 GetCurrentDirectory(MAX_PATH
, buf
);
371 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", buf
[0]);
374 s
->hfile
= CreateFile(filename
, access_flags
,
375 FILE_SHARE_READ
, NULL
,
376 OPEN_EXISTING
, overlapped
, NULL
);
377 if (s
->hfile
== INVALID_HANDLE_VALUE
) {
378 int err
= GetLastError();
380 error_setg_win32(errp
, err
, "Could not open '%s'", filename
);
381 if (err
== ERROR_ACCESS_DENIED
) {
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
));
415 static BlockAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
416 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
417 BlockCompletionFunc
*cb
, void *opaque
)
419 BDRVRawState
*s
= bs
->opaque
;
421 return win32_aio_submit(bs
, s
->aio
, s
->hfile
, sector_num
, qiov
,
422 nb_sectors
, cb
, opaque
, QEMU_AIO_READ
);
424 return paio_submit(bs
, s
->hfile
, sector_num
<< BDRV_SECTOR_BITS
, qiov
,
425 nb_sectors
<< BDRV_SECTOR_BITS
,
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
<< BDRV_SECTOR_BITS
, qiov
,
440 nb_sectors
<< BDRV_SECTOR_BITS
,
441 cb
, opaque
, QEMU_AIO_WRITE
);
445 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
446 BlockCompletionFunc
*cb
, void *opaque
)
448 BDRVRawState
*s
= bs
->opaque
;
449 return paio_submit(bs
, s
->hfile
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
452 static void raw_close(BlockDriverState
*bs
)
454 BDRVRawState
*s
= bs
->opaque
;
457 win32_aio_detach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
458 win32_aio_cleanup(s
->aio
);
462 CloseHandle(s
->hfile
);
463 if (bs
->open_flags
& BDRV_O_TEMPORARY
) {
464 unlink(bs
->filename
);
468 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
, Error
**errp
)
470 BDRVRawState
*s
= bs
->opaque
;
478 * An error has occurred if the return value is INVALID_SET_FILE_POINTER
479 * and GetLastError doesn't return NO_ERROR.
481 dwPtrLow
= SetFilePointer(s
->hfile
, low
, &high
, FILE_BEGIN
);
482 if (dwPtrLow
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
483 error_setg_win32(errp
, GetLastError(), "SetFilePointer error");
486 if (SetEndOfFile(s
->hfile
) == 0) {
487 error_setg_win32(errp
, GetLastError(), "SetEndOfFile error");
493 static int64_t raw_getlength(BlockDriverState
*bs
)
495 BDRVRawState
*s
= bs
->opaque
;
497 ULARGE_INTEGER available
, total
, total_free
;
504 l
.LowPart
= GetFileSize(s
->hfile
, (PDWORD
)&l
.HighPart
);
505 if (l
.LowPart
== 0xffffffffUL
&& GetLastError() != NO_ERROR
)
509 if (!GetDiskFreeSpaceEx(s
->drive_path
, &available
, &total
, &total_free
))
511 l
.QuadPart
= total
.QuadPart
;
514 status
= DeviceIoControl(s
->hfile
, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX
,
515 NULL
, 0, &dg
, sizeof(dg
), &count
, NULL
);
526 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
528 typedef DWORD (WINAPI
* get_compressed_t
)(const char *filename
,
530 get_compressed_t get_compressed
;
532 const char *filename
= bs
->filename
;
533 /* WinNT support GetCompressedFileSize to determine allocate size */
535 (get_compressed_t
) GetProcAddress(GetModuleHandle("kernel32"),
536 "GetCompressedFileSizeA");
537 if (get_compressed
) {
539 low
= get_compressed(filename
, &high
);
540 if (low
!= 0xFFFFFFFFlu
|| GetLastError() == NO_ERROR
) {
541 return (((int64_t) high
) << 32) + low
;
545 if (_stati64(filename
, &st
) < 0) {
551 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
554 int64_t total_size
= 0;
556 strstart(filename
, "file:", &filename
);
558 /* Read out options */
559 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
562 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
565 error_setg_errno(errp
, errno
, "Could not create file");
569 ftruncate(fd
, total_size
);
575 static QemuOptsList raw_create_opts
= {
576 .name
= "raw-create-opts",
577 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
580 .name
= BLOCK_OPT_SIZE
,
581 .type
= QEMU_OPT_SIZE
,
582 .help
= "Virtual disk size"
584 { /* end of list */ }
588 BlockDriver bdrv_file
= {
589 .format_name
= "file",
590 .protocol_name
= "file",
591 .instance_size
= sizeof(BDRVRawState
),
592 .bdrv_needs_filename
= true,
593 .bdrv_parse_filename
= raw_parse_filename
,
594 .bdrv_file_open
= raw_open
,
595 .bdrv_refresh_limits
= raw_probe_alignment
,
596 .bdrv_close
= raw_close
,
597 .bdrv_create
= raw_create
,
598 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
600 .bdrv_aio_readv
= raw_aio_readv
,
601 .bdrv_aio_writev
= raw_aio_writev
,
602 .bdrv_aio_flush
= raw_aio_flush
,
604 .bdrv_truncate
= raw_truncate
,
605 .bdrv_getlength
= raw_getlength
,
606 .bdrv_get_allocated_file_size
607 = raw_get_allocated_file_size
,
609 .create_opts
= &raw_create_opts
,
612 /***********************************************/
615 static int find_cdrom(char *cdrom_name
, int cdrom_name_size
)
617 char drives
[256], *pdrv
= drives
;
620 memset(drives
, 0, sizeof(drives
));
621 GetLogicalDriveStrings(sizeof(drives
), drives
);
622 while(pdrv
[0] != '\0') {
623 type
= GetDriveType(pdrv
);
626 snprintf(cdrom_name
, cdrom_name_size
, "\\\\.\\%c:", pdrv
[0]);
630 pdrv
+= lstrlen(pdrv
) + 1;
635 static int find_device_type(BlockDriverState
*bs
, const char *filename
)
637 BDRVRawState
*s
= bs
->opaque
;
641 if (strstart(filename
, "\\\\.\\", &p
) ||
642 strstart(filename
, "//./", &p
)) {
643 if (stristart(p
, "PhysicalDrive", NULL
))
644 return FTYPE_HARDDISK
;
645 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", p
[0]);
646 type
= GetDriveType(s
->drive_path
);
648 case DRIVE_REMOVABLE
:
650 return FTYPE_HARDDISK
;
661 static int hdev_probe_device(const char *filename
)
663 if (strstart(filename
, "/dev/cdrom", NULL
))
665 if (is_windows_drive(filename
))
670 static void hdev_parse_filename(const char *filename
, QDict
*options
,
673 /* The prefix is optional, just as for "file". */
674 strstart(filename
, "host_device:", &filename
);
676 qdict_put_str(options
, "filename", filename
);
679 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
682 BDRVRawState
*s
= bs
->opaque
;
683 int access_flags
, create_flags
;
686 char device_name
[64];
688 Error
*local_err
= NULL
;
689 const char *filename
;
692 QemuOpts
*opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0,
694 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
696 error_propagate(errp
, local_err
);
701 filename
= qemu_opt_get(opts
, "filename");
703 use_aio
= get_aio_option(opts
, flags
, &local_err
);
704 if (!local_err
&& use_aio
) {
705 error_setg(&local_err
, "AIO is not supported on Windows host devices");
708 error_propagate(errp
, local_err
);
713 if (strstart(filename
, "/dev/cdrom", NULL
)) {
714 if (find_cdrom(device_name
, sizeof(device_name
)) < 0) {
715 error_setg(errp
, "Could not open CD-ROM drive");
719 filename
= device_name
;
721 /* transform drive letters into device name */
722 if (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
723 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
724 filename
[1] == ':' && filename
[2] == '\0') {
725 snprintf(device_name
, sizeof(device_name
), "\\\\.\\%c:", filename
[0]);
726 filename
= device_name
;
729 s
->type
= find_device_type(bs
, filename
);
731 raw_parse_flags(flags
, use_aio
, &access_flags
, &overlapped
);
733 create_flags
= OPEN_EXISTING
;
735 s
->hfile
= CreateFile(filename
, access_flags
,
736 FILE_SHARE_READ
, NULL
,
737 create_flags
, overlapped
, NULL
);
738 if (s
->hfile
== INVALID_HANDLE_VALUE
) {
739 int err
= GetLastError();
741 if (err
== ERROR_ACCESS_DENIED
) {
746 error_setg_errno(errp
, -ret
, "Could not open device");
755 static BlockDriver bdrv_host_device
= {
756 .format_name
= "host_device",
757 .protocol_name
= "host_device",
758 .instance_size
= sizeof(BDRVRawState
),
759 .bdrv_needs_filename
= true,
760 .bdrv_parse_filename
= hdev_parse_filename
,
761 .bdrv_probe_device
= hdev_probe_device
,
762 .bdrv_file_open
= hdev_open
,
763 .bdrv_close
= raw_close
,
765 .bdrv_aio_readv
= raw_aio_readv
,
766 .bdrv_aio_writev
= raw_aio_writev
,
767 .bdrv_aio_flush
= raw_aio_flush
,
769 .bdrv_detach_aio_context
= raw_detach_aio_context
,
770 .bdrv_attach_aio_context
= raw_attach_aio_context
,
772 .bdrv_getlength
= raw_getlength
,
773 .has_variable_length
= true,
775 .bdrv_get_allocated_file_size
776 = raw_get_allocated_file_size
,
779 static void bdrv_file_init(void)
781 bdrv_register(&bdrv_file
);
782 bdrv_register(&bdrv_host_device
);
785 block_init(bdrv_file_init
);