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"
37 #define FTYPE_HARDDISK 2
39 typedef struct RawWin32AIOData
{
42 struct iovec
*aio_iov
;
49 typedef struct BDRVRawState
{
52 char drive_path
[16]; /* format: "d:\" */
53 QEMUWin32AIOState
*aio
;
57 * Read/writes the data to/from a given linear buffer.
59 * Returns the number of bytes handles or -errno in case of an error. Short
60 * reads are only returned if the end of the file is reached.
62 static size_t handle_aiocb_rw(RawWin32AIOData
*aiocb
)
67 for (i
= 0; i
< aiocb
->aio_niov
; i
++) {
69 DWORD ret
, ret_count
, len
;
71 memset(&ov
, 0, sizeof(ov
));
72 ov
.Offset
= (aiocb
->aio_offset
+ offset
);
73 ov
.OffsetHigh
= (aiocb
->aio_offset
+ offset
) >> 32;
74 len
= aiocb
->aio_iov
[i
].iov_len
;
75 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
76 ret
= WriteFile(aiocb
->hfile
, aiocb
->aio_iov
[i
].iov_base
,
77 len
, &ret_count
, &ov
);
79 ret
= ReadFile(aiocb
->hfile
, aiocb
->aio_iov
[i
].iov_base
,
80 len
, &ret_count
, &ov
);
85 if (ret_count
!= len
) {
95 static int aio_worker(void *arg
)
97 RawWin32AIOData
*aiocb
= arg
;
101 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
103 count
= handle_aiocb_rw(aiocb
);
104 if (count
< aiocb
->aio_nbytes
&& aiocb
->bs
->growable
) {
105 /* A short read means that we have reached EOF. Pad the buffer
106 * with zeros for bytes after EOF. */
107 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, count
,
108 0, aiocb
->aio_nbytes
- count
);
110 count
= aiocb
->aio_nbytes
;
112 if (count
== aiocb
->aio_nbytes
) {
119 count
= handle_aiocb_rw(aiocb
);
120 if (count
== aiocb
->aio_nbytes
) {
127 if (!FlushFileBuffers(aiocb
->hfile
)) {
132 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
137 g_slice_free(RawWin32AIOData
, aiocb
);
141 static BlockDriverAIOCB
*paio_submit(BlockDriverState
*bs
, HANDLE hfile
,
142 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
143 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
145 RawWin32AIOData
*acb
= g_slice_new(RawWin32AIOData
);
150 acb
->aio_type
= type
;
153 acb
->aio_iov
= qiov
->iov
;
154 acb
->aio_niov
= qiov
->niov
;
156 acb
->aio_nbytes
= nb_sectors
* 512;
157 acb
->aio_offset
= sector_num
* 512;
159 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
160 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
161 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
164 int qemu_ftruncate64(int fd
, int64_t length
)
172 if ((GetVersion() & 0x80000000UL
) && (length
>> 32) != 0)
175 h
= (HANDLE
)_get_osfhandle(fd
);
177 /* get current position, ftruncate do not change position */
179 li
.LowPart
= SetFilePointer (h
, 0, &li
.HighPart
, FILE_CURRENT
);
180 if (li
.LowPart
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
185 dw
= SetFilePointer(h
, (DWORD
) length
, &high
, FILE_BEGIN
);
186 if (dw
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
189 res
= SetEndOfFile(h
);
191 /* back to old position */
192 SetFilePointer(h
, li
.LowPart
, &li
.HighPart
, FILE_BEGIN
);
196 static int set_sparse(int fd
)
199 return (int) DeviceIoControl((HANDLE
)_get_osfhandle(fd
), FSCTL_SET_SPARSE
,
200 NULL
, 0, NULL
, 0, &returned
, NULL
);
203 static void raw_detach_aio_context(BlockDriverState
*bs
)
205 BDRVRawState
*s
= bs
->opaque
;
208 win32_aio_detach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
212 static void raw_attach_aio_context(BlockDriverState
*bs
,
213 AioContext
*new_context
)
215 BDRVRawState
*s
= bs
->opaque
;
218 win32_aio_attach_aio_context(s
->aio
, new_context
);
222 static void raw_probe_alignment(BlockDriverState
*bs
)
224 BDRVRawState
*s
= bs
->opaque
;
225 DWORD sectorsPerCluster
, freeClusters
, totalClusters
, count
;
229 if (s
->type
== FTYPE_CD
) {
230 bs
->request_alignment
= 2048;
233 if (s
->type
== FTYPE_HARDDISK
) {
234 status
= DeviceIoControl(s
->hfile
, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX
,
235 NULL
, 0, &dg
, sizeof(dg
), &count
, NULL
);
237 bs
->request_alignment
= dg
.Geometry
.BytesPerSector
;
240 /* try GetDiskFreeSpace too */
243 if (s
->drive_path
[0]) {
244 GetDiskFreeSpace(s
->drive_path
, §orsPerCluster
,
245 &dg
.Geometry
.BytesPerSector
,
246 &freeClusters
, &totalClusters
);
247 bs
->request_alignment
= dg
.Geometry
.BytesPerSector
;
251 static void raw_parse_flags(int flags
, int *access_flags
, DWORD
*overlapped
)
253 assert(access_flags
!= NULL
);
254 assert(overlapped
!= NULL
);
256 if (flags
& BDRV_O_RDWR
) {
257 *access_flags
= GENERIC_READ
| GENERIC_WRITE
;
259 *access_flags
= GENERIC_READ
;
262 *overlapped
= FILE_ATTRIBUTE_NORMAL
;
263 if (flags
& BDRV_O_NATIVE_AIO
) {
264 *overlapped
|= FILE_FLAG_OVERLAPPED
;
266 if (flags
& BDRV_O_NOCACHE
) {
267 *overlapped
|= FILE_FLAG_NO_BUFFERING
;
271 static void raw_parse_filename(const char *filename
, QDict
*options
,
274 /* The filename does not have to be prefixed by the protocol name, since
275 * "file" is the default protocol; therefore, the return value of this
276 * function call can be ignored. */
277 strstart(filename
, "file:", &filename
);
279 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
282 static QemuOptsList raw_runtime_opts
= {
284 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
288 .type
= QEMU_OPT_STRING
,
289 .help
= "File name of the image",
291 { /* end of list */ }
295 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
298 BDRVRawState
*s
= bs
->opaque
;
302 Error
*local_err
= NULL
;
303 const char *filename
;
306 s
->type
= FTYPE_FILE
;
308 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
309 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
311 error_propagate(errp
, local_err
);
316 filename
= qemu_opt_get(opts
, "filename");
318 raw_parse_flags(flags
, &access_flags
, &overlapped
);
320 if (filename
[0] && filename
[1] == ':') {
321 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", filename
[0]);
322 } else if (filename
[0] == '\\' && filename
[1] == '\\') {
323 s
->drive_path
[0] = 0;
327 GetCurrentDirectory(MAX_PATH
, buf
);
328 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", buf
[0]);
331 s
->hfile
= CreateFile(filename
, access_flags
,
332 FILE_SHARE_READ
, NULL
,
333 OPEN_EXISTING
, overlapped
, NULL
);
334 if (s
->hfile
== INVALID_HANDLE_VALUE
) {
335 int err
= GetLastError();
337 if (err
== ERROR_ACCESS_DENIED
) {
345 if (flags
& BDRV_O_NATIVE_AIO
) {
346 s
->aio
= win32_aio_init();
347 if (s
->aio
== NULL
) {
348 CloseHandle(s
->hfile
);
349 error_setg(errp
, "Could not initialize AIO");
354 ret
= win32_aio_attach(s
->aio
, s
->hfile
);
356 win32_aio_cleanup(s
->aio
);
357 CloseHandle(s
->hfile
);
358 error_setg_errno(errp
, -ret
, "Could not enable AIO");
362 win32_aio_attach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
365 raw_probe_alignment(bs
);
372 static BlockDriverAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
373 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
374 BlockDriverCompletionFunc
*cb
, void *opaque
)
376 BDRVRawState
*s
= bs
->opaque
;
378 return win32_aio_submit(bs
, s
->aio
, s
->hfile
, sector_num
, qiov
,
379 nb_sectors
, cb
, opaque
, QEMU_AIO_READ
);
381 return paio_submit(bs
, s
->hfile
, sector_num
, qiov
, nb_sectors
,
382 cb
, opaque
, QEMU_AIO_READ
);
386 static BlockDriverAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
387 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
388 BlockDriverCompletionFunc
*cb
, void *opaque
)
390 BDRVRawState
*s
= bs
->opaque
;
392 return win32_aio_submit(bs
, s
->aio
, s
->hfile
, sector_num
, qiov
,
393 nb_sectors
, cb
, opaque
, QEMU_AIO_WRITE
);
395 return paio_submit(bs
, s
->hfile
, sector_num
, qiov
, nb_sectors
,
396 cb
, opaque
, QEMU_AIO_WRITE
);
400 static BlockDriverAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
401 BlockDriverCompletionFunc
*cb
, void *opaque
)
403 BDRVRawState
*s
= bs
->opaque
;
404 return paio_submit(bs
, s
->hfile
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
407 static void raw_close(BlockDriverState
*bs
)
409 BDRVRawState
*s
= bs
->opaque
;
412 win32_aio_detach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
413 win32_aio_cleanup(s
->aio
);
417 CloseHandle(s
->hfile
);
418 if (bs
->open_flags
& BDRV_O_TEMPORARY
) {
419 unlink(bs
->filename
);
423 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
425 BDRVRawState
*s
= bs
->opaque
;
433 * An error has occurred if the return value is INVALID_SET_FILE_POINTER
434 * and GetLastError doesn't return NO_ERROR.
436 dwPtrLow
= SetFilePointer(s
->hfile
, low
, &high
, FILE_BEGIN
);
437 if (dwPtrLow
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
438 fprintf(stderr
, "SetFilePointer error: %lu\n", GetLastError());
441 if (SetEndOfFile(s
->hfile
) == 0) {
442 fprintf(stderr
, "SetEndOfFile error: %lu\n", GetLastError());
448 static int64_t raw_getlength(BlockDriverState
*bs
)
450 BDRVRawState
*s
= bs
->opaque
;
452 ULARGE_INTEGER available
, total
, total_free
;
459 l
.LowPart
= GetFileSize(s
->hfile
, (PDWORD
)&l
.HighPart
);
460 if (l
.LowPart
== 0xffffffffUL
&& GetLastError() != NO_ERROR
)
464 if (!GetDiskFreeSpaceEx(s
->drive_path
, &available
, &total
, &total_free
))
466 l
.QuadPart
= total
.QuadPart
;
469 status
= DeviceIoControl(s
->hfile
, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX
,
470 NULL
, 0, &dg
, sizeof(dg
), &count
, NULL
);
481 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
483 typedef DWORD (WINAPI
* get_compressed_t
)(const char *filename
,
485 get_compressed_t get_compressed
;
487 const char *filename
= bs
->filename
;
488 /* WinNT support GetCompressedFileSize to determine allocate size */
490 (get_compressed_t
) GetProcAddress(GetModuleHandle("kernel32"),
491 "GetCompressedFileSizeA");
492 if (get_compressed
) {
494 low
= get_compressed(filename
, &high
);
495 if (low
!= 0xFFFFFFFFlu
|| GetLastError() == NO_ERROR
) {
496 return (((int64_t) high
) << 32) + low
;
500 if (_stati64(filename
, &st
) < 0) {
506 static int raw_create(const char *filename
, QEMUOptionParameter
*options
,
510 int64_t total_size
= 0;
512 strstart(filename
, "file:", &filename
);
514 /* Read out options */
515 while (options
&& options
->name
) {
516 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
517 total_size
= options
->value
.n
/ 512;
522 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
525 error_setg_errno(errp
, errno
, "Could not create file");
529 ftruncate(fd
, total_size
* 512);
534 static QEMUOptionParameter raw_create_options
[] = {
536 .name
= BLOCK_OPT_SIZE
,
538 .help
= "Virtual disk size"
543 static BlockDriver bdrv_file
= {
544 .format_name
= "file",
545 .protocol_name
= "file",
546 .instance_size
= sizeof(BDRVRawState
),
547 .bdrv_needs_filename
= true,
548 .bdrv_parse_filename
= raw_parse_filename
,
549 .bdrv_file_open
= raw_open
,
550 .bdrv_close
= raw_close
,
551 .bdrv_create
= raw_create
,
552 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
554 .bdrv_aio_readv
= raw_aio_readv
,
555 .bdrv_aio_writev
= raw_aio_writev
,
556 .bdrv_aio_flush
= raw_aio_flush
,
558 .bdrv_truncate
= raw_truncate
,
559 .bdrv_getlength
= raw_getlength
,
560 .bdrv_get_allocated_file_size
561 = raw_get_allocated_file_size
,
563 .create_options
= raw_create_options
,
566 /***********************************************/
569 static int find_cdrom(char *cdrom_name
, int cdrom_name_size
)
571 char drives
[256], *pdrv
= drives
;
574 memset(drives
, 0, sizeof(drives
));
575 GetLogicalDriveStrings(sizeof(drives
), drives
);
576 while(pdrv
[0] != '\0') {
577 type
= GetDriveType(pdrv
);
580 snprintf(cdrom_name
, cdrom_name_size
, "\\\\.\\%c:", pdrv
[0]);
584 pdrv
+= lstrlen(pdrv
) + 1;
589 static int find_device_type(BlockDriverState
*bs
, const char *filename
)
591 BDRVRawState
*s
= bs
->opaque
;
595 if (strstart(filename
, "\\\\.\\", &p
) ||
596 strstart(filename
, "//./", &p
)) {
597 if (stristart(p
, "PhysicalDrive", NULL
))
598 return FTYPE_HARDDISK
;
599 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", p
[0]);
600 type
= GetDriveType(s
->drive_path
);
602 case DRIVE_REMOVABLE
:
604 return FTYPE_HARDDISK
;
615 static int hdev_probe_device(const char *filename
)
617 if (strstart(filename
, "/dev/cdrom", NULL
))
619 if (is_windows_drive(filename
))
624 static void hdev_parse_filename(const char *filename
, QDict
*options
,
627 /* The prefix is optional, just as for "file". */
628 strstart(filename
, "host_device:", &filename
);
630 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
633 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
636 BDRVRawState
*s
= bs
->opaque
;
637 int access_flags
, create_flags
;
640 char device_name
[64];
642 Error
*local_err
= NULL
;
643 const char *filename
;
645 QemuOpts
*opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0,
647 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
649 error_propagate(errp
, local_err
);
654 filename
= qemu_opt_get(opts
, "filename");
656 if (strstart(filename
, "/dev/cdrom", NULL
)) {
657 if (find_cdrom(device_name
, sizeof(device_name
)) < 0) {
658 error_setg(errp
, "Could not open CD-ROM drive");
662 filename
= device_name
;
664 /* transform drive letters into device name */
665 if (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
666 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
667 filename
[1] == ':' && filename
[2] == '\0') {
668 snprintf(device_name
, sizeof(device_name
), "\\\\.\\%c:", filename
[0]);
669 filename
= device_name
;
672 s
->type
= find_device_type(bs
, filename
);
674 raw_parse_flags(flags
, &access_flags
, &overlapped
);
676 create_flags
= OPEN_EXISTING
;
678 s
->hfile
= CreateFile(filename
, access_flags
,
679 FILE_SHARE_READ
, NULL
,
680 create_flags
, overlapped
, NULL
);
681 if (s
->hfile
== INVALID_HANDLE_VALUE
) {
682 int err
= GetLastError();
684 if (err
== ERROR_ACCESS_DENIED
) {
689 error_setg_errno(errp
, -ret
, "Could not open device");
698 static BlockDriver bdrv_host_device
= {
699 .format_name
= "host_device",
700 .protocol_name
= "host_device",
701 .instance_size
= sizeof(BDRVRawState
),
702 .bdrv_needs_filename
= true,
703 .bdrv_parse_filename
= hdev_parse_filename
,
704 .bdrv_probe_device
= hdev_probe_device
,
705 .bdrv_file_open
= hdev_open
,
706 .bdrv_close
= raw_close
,
708 .bdrv_aio_readv
= raw_aio_readv
,
709 .bdrv_aio_writev
= raw_aio_writev
,
710 .bdrv_aio_flush
= raw_aio_flush
,
712 .bdrv_detach_aio_context
= raw_detach_aio_context
,
713 .bdrv_attach_aio_context
= raw_attach_aio_context
,
715 .bdrv_getlength
= raw_getlength
,
716 .has_variable_length
= true,
718 .bdrv_get_allocated_file_size
719 = raw_get_allocated_file_size
,
722 static void bdrv_file_init(void)
724 bdrv_register(&bdrv_file
);
725 bdrv_register(&bdrv_host_device
);
728 block_init(bdrv_file_init
);