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"
32 #include "qapi/qmp/qstring.h"
38 #define FTYPE_HARDDISK 2
40 typedef struct RawWin32AIOData
{
43 struct iovec
*aio_iov
;
50 typedef struct BDRVRawState
{
53 char drive_path
[16]; /* format: "d:\" */
54 QEMUWin32AIOState
*aio
;
58 * Read/writes the data to/from a given linear buffer.
60 * Returns the number of bytes handles or -errno in case of an error. Short
61 * reads are only returned if the end of the file is reached.
63 static size_t handle_aiocb_rw(RawWin32AIOData
*aiocb
)
68 for (i
= 0; i
< aiocb
->aio_niov
; i
++) {
70 DWORD ret
, ret_count
, len
;
72 memset(&ov
, 0, sizeof(ov
));
73 ov
.Offset
= (aiocb
->aio_offset
+ offset
);
74 ov
.OffsetHigh
= (aiocb
->aio_offset
+ offset
) >> 32;
75 len
= aiocb
->aio_iov
[i
].iov_len
;
76 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
77 ret
= WriteFile(aiocb
->hfile
, aiocb
->aio_iov
[i
].iov_base
,
78 len
, &ret_count
, &ov
);
80 ret
= ReadFile(aiocb
->hfile
, aiocb
->aio_iov
[i
].iov_base
,
81 len
, &ret_count
, &ov
);
86 if (ret_count
!= len
) {
96 static int aio_worker(void *arg
)
98 RawWin32AIOData
*aiocb
= arg
;
102 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
104 count
= handle_aiocb_rw(aiocb
);
105 if (count
< aiocb
->aio_nbytes
) {
106 /* A short read means that we have reached EOF. Pad the buffer
107 * with zeros for bytes after EOF. */
108 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, count
,
109 0, aiocb
->aio_nbytes
- count
);
111 count
= aiocb
->aio_nbytes
;
113 if (count
== aiocb
->aio_nbytes
) {
120 count
= handle_aiocb_rw(aiocb
);
121 if (count
== aiocb
->aio_nbytes
) {
128 if (!FlushFileBuffers(aiocb
->hfile
)) {
133 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
138 g_slice_free(RawWin32AIOData
, aiocb
);
142 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, HANDLE hfile
,
143 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
144 BlockCompletionFunc
*cb
, void *opaque
, int type
)
146 RawWin32AIOData
*acb
= g_slice_new(RawWin32AIOData
);
151 acb
->aio_type
= type
;
154 acb
->aio_iov
= qiov
->iov
;
155 acb
->aio_niov
= qiov
->niov
;
157 acb
->aio_nbytes
= nb_sectors
* 512;
158 acb
->aio_offset
= sector_num
* 512;
160 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
161 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
162 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
165 int qemu_ftruncate64(int fd
, int64_t length
)
173 if ((GetVersion() & 0x80000000UL
) && (length
>> 32) != 0)
176 h
= (HANDLE
)_get_osfhandle(fd
);
178 /* get current position, ftruncate do not change position */
180 li
.LowPart
= SetFilePointer (h
, 0, &li
.HighPart
, FILE_CURRENT
);
181 if (li
.LowPart
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
186 dw
= SetFilePointer(h
, (DWORD
) length
, &high
, FILE_BEGIN
);
187 if (dw
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
190 res
= SetEndOfFile(h
);
192 /* back to old position */
193 SetFilePointer(h
, li
.LowPart
, &li
.HighPart
, FILE_BEGIN
);
197 static int set_sparse(int fd
)
200 return (int) DeviceIoControl((HANDLE
)_get_osfhandle(fd
), FSCTL_SET_SPARSE
,
201 NULL
, 0, NULL
, 0, &returned
, NULL
);
204 static void raw_detach_aio_context(BlockDriverState
*bs
)
206 BDRVRawState
*s
= bs
->opaque
;
209 win32_aio_detach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
213 static void raw_attach_aio_context(BlockDriverState
*bs
,
214 AioContext
*new_context
)
216 BDRVRawState
*s
= bs
->opaque
;
219 win32_aio_attach_aio_context(s
->aio
, new_context
);
223 static void raw_probe_alignment(BlockDriverState
*bs
)
225 BDRVRawState
*s
= bs
->opaque
;
226 DWORD sectorsPerCluster
, freeClusters
, totalClusters
, count
;
230 if (s
->type
== FTYPE_CD
) {
231 bs
->request_alignment
= 2048;
234 if (s
->type
== FTYPE_HARDDISK
) {
235 status
= DeviceIoControl(s
->hfile
, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX
,
236 NULL
, 0, &dg
, sizeof(dg
), &count
, NULL
);
238 bs
->request_alignment
= dg
.Geometry
.BytesPerSector
;
241 /* try GetDiskFreeSpace too */
244 if (s
->drive_path
[0]) {
245 GetDiskFreeSpace(s
->drive_path
, §orsPerCluster
,
246 &dg
.Geometry
.BytesPerSector
,
247 &freeClusters
, &totalClusters
);
248 bs
->request_alignment
= dg
.Geometry
.BytesPerSector
;
252 static void raw_parse_flags(int flags
, int *access_flags
, DWORD
*overlapped
)
254 assert(access_flags
!= NULL
);
255 assert(overlapped
!= NULL
);
257 if (flags
& BDRV_O_RDWR
) {
258 *access_flags
= GENERIC_READ
| GENERIC_WRITE
;
260 *access_flags
= GENERIC_READ
;
263 *overlapped
= FILE_ATTRIBUTE_NORMAL
;
264 if (flags
& BDRV_O_NATIVE_AIO
) {
265 *overlapped
|= FILE_FLAG_OVERLAPPED
;
267 if (flags
& BDRV_O_NOCACHE
) {
268 *overlapped
|= FILE_FLAG_NO_BUFFERING
;
272 static void raw_parse_filename(const char *filename
, QDict
*options
,
275 /* The filename does not have to be prefixed by the protocol name, since
276 * "file" is the default protocol; therefore, the return value of this
277 * function call can be ignored. */
278 strstart(filename
, "file:", &filename
);
280 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
283 static QemuOptsList raw_runtime_opts
= {
285 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
289 .type
= QEMU_OPT_STRING
,
290 .help
= "File name of the image",
292 { /* end of list */ }
296 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
299 BDRVRawState
*s
= bs
->opaque
;
303 Error
*local_err
= NULL
;
304 const char *filename
;
307 s
->type
= FTYPE_FILE
;
309 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
310 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
312 error_propagate(errp
, local_err
);
317 filename
= qemu_opt_get(opts
, "filename");
319 raw_parse_flags(flags
, &access_flags
, &overlapped
);
321 if (filename
[0] && filename
[1] == ':') {
322 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", filename
[0]);
323 } else if (filename
[0] == '\\' && filename
[1] == '\\') {
324 s
->drive_path
[0] = 0;
328 GetCurrentDirectory(MAX_PATH
, buf
);
329 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", buf
[0]);
332 s
->hfile
= CreateFile(filename
, access_flags
,
333 FILE_SHARE_READ
, NULL
,
334 OPEN_EXISTING
, overlapped
, NULL
);
335 if (s
->hfile
== INVALID_HANDLE_VALUE
) {
336 int err
= GetLastError();
338 if (err
== ERROR_ACCESS_DENIED
) {
346 if (flags
& BDRV_O_NATIVE_AIO
) {
347 s
->aio
= win32_aio_init();
348 if (s
->aio
== NULL
) {
349 CloseHandle(s
->hfile
);
350 error_setg(errp
, "Could not initialize AIO");
355 ret
= win32_aio_attach(s
->aio
, s
->hfile
);
357 win32_aio_cleanup(s
->aio
);
358 CloseHandle(s
->hfile
);
359 error_setg_errno(errp
, -ret
, "Could not enable AIO");
363 win32_aio_attach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
366 raw_probe_alignment(bs
);
373 static BlockAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
374 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
375 BlockCompletionFunc
*cb
, void *opaque
)
377 BDRVRawState
*s
= bs
->opaque
;
379 return win32_aio_submit(bs
, s
->aio
, s
->hfile
, sector_num
, qiov
,
380 nb_sectors
, cb
, opaque
, QEMU_AIO_READ
);
382 return paio_submit(bs
, s
->hfile
, sector_num
, qiov
, nb_sectors
,
383 cb
, opaque
, QEMU_AIO_READ
);
387 static BlockAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
388 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
389 BlockCompletionFunc
*cb
, void *opaque
)
391 BDRVRawState
*s
= bs
->opaque
;
393 return win32_aio_submit(bs
, s
->aio
, s
->hfile
, sector_num
, qiov
,
394 nb_sectors
, cb
, opaque
, QEMU_AIO_WRITE
);
396 return paio_submit(bs
, s
->hfile
, sector_num
, qiov
, nb_sectors
,
397 cb
, opaque
, QEMU_AIO_WRITE
);
401 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
402 BlockCompletionFunc
*cb
, void *opaque
)
404 BDRVRawState
*s
= bs
->opaque
;
405 return paio_submit(bs
, s
->hfile
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
408 static void raw_close(BlockDriverState
*bs
)
410 BDRVRawState
*s
= bs
->opaque
;
413 win32_aio_detach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
414 win32_aio_cleanup(s
->aio
);
418 CloseHandle(s
->hfile
);
419 if (bs
->open_flags
& BDRV_O_TEMPORARY
) {
420 unlink(bs
->filename
);
424 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
426 BDRVRawState
*s
= bs
->opaque
;
434 * An error has occurred if the return value is INVALID_SET_FILE_POINTER
435 * and GetLastError doesn't return NO_ERROR.
437 dwPtrLow
= SetFilePointer(s
->hfile
, low
, &high
, FILE_BEGIN
);
438 if (dwPtrLow
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
439 fprintf(stderr
, "SetFilePointer error: %lu\n", GetLastError());
442 if (SetEndOfFile(s
->hfile
) == 0) {
443 fprintf(stderr
, "SetEndOfFile error: %lu\n", GetLastError());
449 static int64_t raw_getlength(BlockDriverState
*bs
)
451 BDRVRawState
*s
= bs
->opaque
;
453 ULARGE_INTEGER available
, total
, total_free
;
460 l
.LowPart
= GetFileSize(s
->hfile
, (PDWORD
)&l
.HighPart
);
461 if (l
.LowPart
== 0xffffffffUL
&& GetLastError() != NO_ERROR
)
465 if (!GetDiskFreeSpaceEx(s
->drive_path
, &available
, &total
, &total_free
))
467 l
.QuadPart
= total
.QuadPart
;
470 status
= DeviceIoControl(s
->hfile
, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX
,
471 NULL
, 0, &dg
, sizeof(dg
), &count
, NULL
);
482 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
484 typedef DWORD (WINAPI
* get_compressed_t
)(const char *filename
,
486 get_compressed_t get_compressed
;
488 const char *filename
= bs
->filename
;
489 /* WinNT support GetCompressedFileSize to determine allocate size */
491 (get_compressed_t
) GetProcAddress(GetModuleHandle("kernel32"),
492 "GetCompressedFileSizeA");
493 if (get_compressed
) {
495 low
= get_compressed(filename
, &high
);
496 if (low
!= 0xFFFFFFFFlu
|| GetLastError() == NO_ERROR
) {
497 return (((int64_t) high
) << 32) + low
;
501 if (_stati64(filename
, &st
) < 0) {
507 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
510 int64_t total_size
= 0;
512 strstart(filename
, "file:", &filename
);
514 /* Read out options */
515 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
518 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
521 error_setg_errno(errp
, errno
, "Could not create file");
525 ftruncate(fd
, total_size
);
531 static QemuOptsList raw_create_opts
= {
532 .name
= "raw-create-opts",
533 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
536 .name
= BLOCK_OPT_SIZE
,
537 .type
= QEMU_OPT_SIZE
,
538 .help
= "Virtual disk size"
540 { /* end of list */ }
544 BlockDriver bdrv_file
= {
545 .format_name
= "file",
546 .protocol_name
= "file",
547 .instance_size
= sizeof(BDRVRawState
),
548 .bdrv_needs_filename
= true,
549 .bdrv_parse_filename
= raw_parse_filename
,
550 .bdrv_file_open
= raw_open
,
551 .bdrv_close
= raw_close
,
552 .bdrv_create
= raw_create
,
553 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
555 .bdrv_aio_readv
= raw_aio_readv
,
556 .bdrv_aio_writev
= raw_aio_writev
,
557 .bdrv_aio_flush
= raw_aio_flush
,
559 .bdrv_truncate
= raw_truncate
,
560 .bdrv_getlength
= raw_getlength
,
561 .bdrv_get_allocated_file_size
562 = raw_get_allocated_file_size
,
564 .create_opts
= &raw_create_opts
,
567 /***********************************************/
570 static int find_cdrom(char *cdrom_name
, int cdrom_name_size
)
572 char drives
[256], *pdrv
= drives
;
575 memset(drives
, 0, sizeof(drives
));
576 GetLogicalDriveStrings(sizeof(drives
), drives
);
577 while(pdrv
[0] != '\0') {
578 type
= GetDriveType(pdrv
);
581 snprintf(cdrom_name
, cdrom_name_size
, "\\\\.\\%c:", pdrv
[0]);
585 pdrv
+= lstrlen(pdrv
) + 1;
590 static int find_device_type(BlockDriverState
*bs
, const char *filename
)
592 BDRVRawState
*s
= bs
->opaque
;
596 if (strstart(filename
, "\\\\.\\", &p
) ||
597 strstart(filename
, "//./", &p
)) {
598 if (stristart(p
, "PhysicalDrive", NULL
))
599 return FTYPE_HARDDISK
;
600 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", p
[0]);
601 type
= GetDriveType(s
->drive_path
);
603 case DRIVE_REMOVABLE
:
605 return FTYPE_HARDDISK
;
616 static int hdev_probe_device(const char *filename
)
618 if (strstart(filename
, "/dev/cdrom", NULL
))
620 if (is_windows_drive(filename
))
625 static void hdev_parse_filename(const char *filename
, QDict
*options
,
628 /* The prefix is optional, just as for "file". */
629 strstart(filename
, "host_device:", &filename
);
631 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
634 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
637 BDRVRawState
*s
= bs
->opaque
;
638 int access_flags
, create_flags
;
641 char device_name
[64];
643 Error
*local_err
= NULL
;
644 const char *filename
;
646 QemuOpts
*opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0,
648 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
650 error_propagate(errp
, local_err
);
655 filename
= qemu_opt_get(opts
, "filename");
657 if (strstart(filename
, "/dev/cdrom", NULL
)) {
658 if (find_cdrom(device_name
, sizeof(device_name
)) < 0) {
659 error_setg(errp
, "Could not open CD-ROM drive");
663 filename
= device_name
;
665 /* transform drive letters into device name */
666 if (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
667 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
668 filename
[1] == ':' && filename
[2] == '\0') {
669 snprintf(device_name
, sizeof(device_name
), "\\\\.\\%c:", filename
[0]);
670 filename
= device_name
;
673 s
->type
= find_device_type(bs
, filename
);
675 raw_parse_flags(flags
, &access_flags
, &overlapped
);
677 create_flags
= OPEN_EXISTING
;
679 s
->hfile
= CreateFile(filename
, access_flags
,
680 FILE_SHARE_READ
, NULL
,
681 create_flags
, overlapped
, NULL
);
682 if (s
->hfile
== INVALID_HANDLE_VALUE
) {
683 int err
= GetLastError();
685 if (err
== ERROR_ACCESS_DENIED
) {
690 error_setg_errno(errp
, -ret
, "Could not open device");
699 static BlockDriver bdrv_host_device
= {
700 .format_name
= "host_device",
701 .protocol_name
= "host_device",
702 .instance_size
= sizeof(BDRVRawState
),
703 .bdrv_needs_filename
= true,
704 .bdrv_parse_filename
= hdev_parse_filename
,
705 .bdrv_probe_device
= hdev_probe_device
,
706 .bdrv_file_open
= hdev_open
,
707 .bdrv_close
= raw_close
,
709 .bdrv_aio_readv
= raw_aio_readv
,
710 .bdrv_aio_writev
= raw_aio_writev
,
711 .bdrv_aio_flush
= raw_aio_flush
,
713 .bdrv_detach_aio_context
= raw_detach_aio_context
,
714 .bdrv_attach_aio_context
= raw_attach_aio_context
,
716 .bdrv_getlength
= raw_getlength
,
717 .has_variable_length
= true,
719 .bdrv_get_allocated_file_size
720 = raw_get_allocated_file_size
,
723 static void bdrv_file_init(void)
725 bdrv_register(&bdrv_file
);
726 bdrv_register(&bdrv_host_device
);
729 block_init(bdrv_file_init
);