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 "qemu-common.h"
26 #include "qemu/timer.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
31 #include "block/thread-pool.h"
33 #include "qapi/qmp/qstring.h"
39 #define FTYPE_HARDDISK 2
41 typedef struct RawWin32AIOData
{
44 struct iovec
*aio_iov
;
51 typedef struct BDRVRawState
{
54 char drive_path
[16]; /* format: "d:\" */
55 QEMUWin32AIOState
*aio
;
59 * Read/writes the data to/from a given linear buffer.
61 * Returns the number of bytes handles or -errno in case of an error. Short
62 * reads are only returned if the end of the file is reached.
64 static size_t handle_aiocb_rw(RawWin32AIOData
*aiocb
)
69 for (i
= 0; i
< aiocb
->aio_niov
; i
++) {
71 DWORD ret
, ret_count
, len
;
73 memset(&ov
, 0, sizeof(ov
));
74 ov
.Offset
= (aiocb
->aio_offset
+ offset
);
75 ov
.OffsetHigh
= (aiocb
->aio_offset
+ offset
) >> 32;
76 len
= aiocb
->aio_iov
[i
].iov_len
;
77 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
78 ret
= WriteFile(aiocb
->hfile
, aiocb
->aio_iov
[i
].iov_base
,
79 len
, &ret_count
, &ov
);
81 ret
= ReadFile(aiocb
->hfile
, aiocb
->aio_iov
[i
].iov_base
,
82 len
, &ret_count
, &ov
);
87 if (ret_count
!= len
) {
97 static int aio_worker(void *arg
)
99 RawWin32AIOData
*aiocb
= arg
;
103 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
105 count
= handle_aiocb_rw(aiocb
);
106 if (count
< aiocb
->aio_nbytes
) {
107 /* A short read means that we have reached EOF. Pad the buffer
108 * with zeros for bytes after EOF. */
109 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, count
,
110 0, aiocb
->aio_nbytes
- count
);
112 count
= aiocb
->aio_nbytes
;
114 if (count
== aiocb
->aio_nbytes
) {
121 count
= handle_aiocb_rw(aiocb
);
122 if (count
== aiocb
->aio_nbytes
) {
129 if (!FlushFileBuffers(aiocb
->hfile
)) {
134 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
143 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, HANDLE hfile
,
144 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
145 BlockCompletionFunc
*cb
, void *opaque
, int type
)
147 RawWin32AIOData
*acb
= g_new(RawWin32AIOData
, 1);
152 acb
->aio_type
= type
;
155 acb
->aio_iov
= qiov
->iov
;
156 acb
->aio_niov
= qiov
->niov
;
158 acb
->aio_nbytes
= nb_sectors
* 512;
159 acb
->aio_offset
= sector_num
* 512;
161 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
162 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
163 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
166 int qemu_ftruncate64(int fd
, int64_t length
)
174 if ((GetVersion() & 0x80000000UL
) && (length
>> 32) != 0)
177 h
= (HANDLE
)_get_osfhandle(fd
);
179 /* get current position, ftruncate do not change position */
181 li
.LowPart
= SetFilePointer (h
, 0, &li
.HighPart
, FILE_CURRENT
);
182 if (li
.LowPart
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
187 dw
= SetFilePointer(h
, (DWORD
) length
, &high
, FILE_BEGIN
);
188 if (dw
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
191 res
= SetEndOfFile(h
);
193 /* back to old position */
194 SetFilePointer(h
, li
.LowPart
, &li
.HighPart
, FILE_BEGIN
);
198 static int set_sparse(int fd
)
201 return (int) DeviceIoControl((HANDLE
)_get_osfhandle(fd
), FSCTL_SET_SPARSE
,
202 NULL
, 0, NULL
, 0, &returned
, NULL
);
205 static void raw_detach_aio_context(BlockDriverState
*bs
)
207 BDRVRawState
*s
= bs
->opaque
;
210 win32_aio_detach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
214 static void raw_attach_aio_context(BlockDriverState
*bs
,
215 AioContext
*new_context
)
217 BDRVRawState
*s
= bs
->opaque
;
220 win32_aio_attach_aio_context(s
->aio
, new_context
);
224 static void raw_probe_alignment(BlockDriverState
*bs
)
226 BDRVRawState
*s
= bs
->opaque
;
227 DWORD sectorsPerCluster
, freeClusters
, totalClusters
, count
;
231 if (s
->type
== FTYPE_CD
) {
232 bs
->request_alignment
= 2048;
235 if (s
->type
== FTYPE_HARDDISK
) {
236 status
= DeviceIoControl(s
->hfile
, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX
,
237 NULL
, 0, &dg
, sizeof(dg
), &count
, NULL
);
239 bs
->request_alignment
= dg
.Geometry
.BytesPerSector
;
242 /* try GetDiskFreeSpace too */
245 if (s
->drive_path
[0]) {
246 GetDiskFreeSpace(s
->drive_path
, §orsPerCluster
,
247 &dg
.Geometry
.BytesPerSector
,
248 &freeClusters
, &totalClusters
);
249 bs
->request_alignment
= dg
.Geometry
.BytesPerSector
;
253 static void raw_parse_flags(int flags
, int *access_flags
, DWORD
*overlapped
)
255 assert(access_flags
!= NULL
);
256 assert(overlapped
!= NULL
);
258 if (flags
& BDRV_O_RDWR
) {
259 *access_flags
= GENERIC_READ
| GENERIC_WRITE
;
261 *access_flags
= GENERIC_READ
;
264 *overlapped
= FILE_ATTRIBUTE_NORMAL
;
265 if (flags
& BDRV_O_NATIVE_AIO
) {
266 *overlapped
|= FILE_FLAG_OVERLAPPED
;
268 if (flags
& BDRV_O_NOCACHE
) {
269 *overlapped
|= FILE_FLAG_NO_BUFFERING
;
273 static void raw_parse_filename(const char *filename
, QDict
*options
,
276 /* The filename does not have to be prefixed by the protocol name, since
277 * "file" is the default protocol; therefore, the return value of this
278 * function call can be ignored. */
279 strstart(filename
, "file:", &filename
);
281 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
284 static QemuOptsList raw_runtime_opts
= {
286 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
290 .type
= QEMU_OPT_STRING
,
291 .help
= "File name of the image",
293 { /* end of list */ }
297 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
300 BDRVRawState
*s
= bs
->opaque
;
304 Error
*local_err
= NULL
;
305 const char *filename
;
308 s
->type
= FTYPE_FILE
;
310 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
311 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
313 error_propagate(errp
, local_err
);
318 filename
= qemu_opt_get(opts
, "filename");
320 raw_parse_flags(flags
, &access_flags
, &overlapped
);
322 if (filename
[0] && filename
[1] == ':') {
323 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", filename
[0]);
324 } else if (filename
[0] == '\\' && filename
[1] == '\\') {
325 s
->drive_path
[0] = 0;
329 GetCurrentDirectory(MAX_PATH
, buf
);
330 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", buf
[0]);
333 s
->hfile
= CreateFile(filename
, access_flags
,
334 FILE_SHARE_READ
, NULL
,
335 OPEN_EXISTING
, overlapped
, NULL
);
336 if (s
->hfile
== INVALID_HANDLE_VALUE
) {
337 int err
= GetLastError();
339 if (err
== ERROR_ACCESS_DENIED
) {
347 if (flags
& BDRV_O_NATIVE_AIO
) {
348 s
->aio
= win32_aio_init();
349 if (s
->aio
== NULL
) {
350 CloseHandle(s
->hfile
);
351 error_setg(errp
, "Could not initialize AIO");
356 ret
= win32_aio_attach(s
->aio
, s
->hfile
);
358 win32_aio_cleanup(s
->aio
);
359 CloseHandle(s
->hfile
);
360 error_setg_errno(errp
, -ret
, "Could not enable AIO");
364 win32_aio_attach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
367 raw_probe_alignment(bs
);
374 static BlockAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
375 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
376 BlockCompletionFunc
*cb
, void *opaque
)
378 BDRVRawState
*s
= bs
->opaque
;
380 return win32_aio_submit(bs
, s
->aio
, s
->hfile
, sector_num
, qiov
,
381 nb_sectors
, cb
, opaque
, QEMU_AIO_READ
);
383 return paio_submit(bs
, s
->hfile
, sector_num
, qiov
, nb_sectors
,
384 cb
, opaque
, QEMU_AIO_READ
);
388 static BlockAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
389 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
390 BlockCompletionFunc
*cb
, void *opaque
)
392 BDRVRawState
*s
= bs
->opaque
;
394 return win32_aio_submit(bs
, s
->aio
, s
->hfile
, sector_num
, qiov
,
395 nb_sectors
, cb
, opaque
, QEMU_AIO_WRITE
);
397 return paio_submit(bs
, s
->hfile
, sector_num
, qiov
, nb_sectors
,
398 cb
, opaque
, QEMU_AIO_WRITE
);
402 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
403 BlockCompletionFunc
*cb
, void *opaque
)
405 BDRVRawState
*s
= bs
->opaque
;
406 return paio_submit(bs
, s
->hfile
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
409 static void raw_close(BlockDriverState
*bs
)
411 BDRVRawState
*s
= bs
->opaque
;
414 win32_aio_detach_aio_context(s
->aio
, bdrv_get_aio_context(bs
));
415 win32_aio_cleanup(s
->aio
);
419 CloseHandle(s
->hfile
);
420 if (bs
->open_flags
& BDRV_O_TEMPORARY
) {
421 unlink(bs
->filename
);
425 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
427 BDRVRawState
*s
= bs
->opaque
;
435 * An error has occurred if the return value is INVALID_SET_FILE_POINTER
436 * and GetLastError doesn't return NO_ERROR.
438 dwPtrLow
= SetFilePointer(s
->hfile
, low
, &high
, FILE_BEGIN
);
439 if (dwPtrLow
== INVALID_SET_FILE_POINTER
&& GetLastError() != NO_ERROR
) {
440 fprintf(stderr
, "SetFilePointer error: %lu\n", GetLastError());
443 if (SetEndOfFile(s
->hfile
) == 0) {
444 fprintf(stderr
, "SetEndOfFile error: %lu\n", GetLastError());
450 static int64_t raw_getlength(BlockDriverState
*bs
)
452 BDRVRawState
*s
= bs
->opaque
;
454 ULARGE_INTEGER available
, total
, total_free
;
461 l
.LowPart
= GetFileSize(s
->hfile
, (PDWORD
)&l
.HighPart
);
462 if (l
.LowPart
== 0xffffffffUL
&& GetLastError() != NO_ERROR
)
466 if (!GetDiskFreeSpaceEx(s
->drive_path
, &available
, &total
, &total_free
))
468 l
.QuadPart
= total
.QuadPart
;
471 status
= DeviceIoControl(s
->hfile
, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX
,
472 NULL
, 0, &dg
, sizeof(dg
), &count
, NULL
);
483 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
485 typedef DWORD (WINAPI
* get_compressed_t
)(const char *filename
,
487 get_compressed_t get_compressed
;
489 const char *filename
= bs
->filename
;
490 /* WinNT support GetCompressedFileSize to determine allocate size */
492 (get_compressed_t
) GetProcAddress(GetModuleHandle("kernel32"),
493 "GetCompressedFileSizeA");
494 if (get_compressed
) {
496 low
= get_compressed(filename
, &high
);
497 if (low
!= 0xFFFFFFFFlu
|| GetLastError() == NO_ERROR
) {
498 return (((int64_t) high
) << 32) + low
;
502 if (_stati64(filename
, &st
) < 0) {
508 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
511 int64_t total_size
= 0;
513 strstart(filename
, "file:", &filename
);
515 /* Read out options */
516 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
519 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
522 error_setg_errno(errp
, errno
, "Could not create file");
526 ftruncate(fd
, total_size
);
532 static QemuOptsList raw_create_opts
= {
533 .name
= "raw-create-opts",
534 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
537 .name
= BLOCK_OPT_SIZE
,
538 .type
= QEMU_OPT_SIZE
,
539 .help
= "Virtual disk size"
541 { /* end of list */ }
545 BlockDriver bdrv_file
= {
546 .format_name
= "file",
547 .protocol_name
= "file",
548 .instance_size
= sizeof(BDRVRawState
),
549 .bdrv_needs_filename
= true,
550 .bdrv_parse_filename
= raw_parse_filename
,
551 .bdrv_file_open
= raw_open
,
552 .bdrv_close
= raw_close
,
553 .bdrv_create
= raw_create
,
554 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
556 .bdrv_aio_readv
= raw_aio_readv
,
557 .bdrv_aio_writev
= raw_aio_writev
,
558 .bdrv_aio_flush
= raw_aio_flush
,
560 .bdrv_truncate
= raw_truncate
,
561 .bdrv_getlength
= raw_getlength
,
562 .bdrv_get_allocated_file_size
563 = raw_get_allocated_file_size
,
565 .create_opts
= &raw_create_opts
,
568 /***********************************************/
571 static int find_cdrom(char *cdrom_name
, int cdrom_name_size
)
573 char drives
[256], *pdrv
= drives
;
576 memset(drives
, 0, sizeof(drives
));
577 GetLogicalDriveStrings(sizeof(drives
), drives
);
578 while(pdrv
[0] != '\0') {
579 type
= GetDriveType(pdrv
);
582 snprintf(cdrom_name
, cdrom_name_size
, "\\\\.\\%c:", pdrv
[0]);
586 pdrv
+= lstrlen(pdrv
) + 1;
591 static int find_device_type(BlockDriverState
*bs
, const char *filename
)
593 BDRVRawState
*s
= bs
->opaque
;
597 if (strstart(filename
, "\\\\.\\", &p
) ||
598 strstart(filename
, "//./", &p
)) {
599 if (stristart(p
, "PhysicalDrive", NULL
))
600 return FTYPE_HARDDISK
;
601 snprintf(s
->drive_path
, sizeof(s
->drive_path
), "%c:\\", p
[0]);
602 type
= GetDriveType(s
->drive_path
);
604 case DRIVE_REMOVABLE
:
606 return FTYPE_HARDDISK
;
617 static int hdev_probe_device(const char *filename
)
619 if (strstart(filename
, "/dev/cdrom", NULL
))
621 if (is_windows_drive(filename
))
626 static void hdev_parse_filename(const char *filename
, QDict
*options
,
629 /* The prefix is optional, just as for "file". */
630 strstart(filename
, "host_device:", &filename
);
632 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
635 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
638 BDRVRawState
*s
= bs
->opaque
;
639 int access_flags
, create_flags
;
642 char device_name
[64];
644 Error
*local_err
= NULL
;
645 const char *filename
;
647 QemuOpts
*opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0,
649 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
651 error_propagate(errp
, local_err
);
656 filename
= qemu_opt_get(opts
, "filename");
658 if (strstart(filename
, "/dev/cdrom", NULL
)) {
659 if (find_cdrom(device_name
, sizeof(device_name
)) < 0) {
660 error_setg(errp
, "Could not open CD-ROM drive");
664 filename
= device_name
;
666 /* transform drive letters into device name */
667 if (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
668 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
669 filename
[1] == ':' && filename
[2] == '\0') {
670 snprintf(device_name
, sizeof(device_name
), "\\\\.\\%c:", filename
[0]);
671 filename
= device_name
;
674 s
->type
= find_device_type(bs
, filename
);
676 raw_parse_flags(flags
, &access_flags
, &overlapped
);
678 create_flags
= OPEN_EXISTING
;
680 s
->hfile
= CreateFile(filename
, access_flags
,
681 FILE_SHARE_READ
, NULL
,
682 create_flags
, overlapped
, NULL
);
683 if (s
->hfile
== INVALID_HANDLE_VALUE
) {
684 int err
= GetLastError();
686 if (err
== ERROR_ACCESS_DENIED
) {
691 error_setg_errno(errp
, -ret
, "Could not open device");
700 static BlockDriver bdrv_host_device
= {
701 .format_name
= "host_device",
702 .protocol_name
= "host_device",
703 .instance_size
= sizeof(BDRVRawState
),
704 .bdrv_needs_filename
= true,
705 .bdrv_parse_filename
= hdev_parse_filename
,
706 .bdrv_probe_device
= hdev_probe_device
,
707 .bdrv_file_open
= hdev_open
,
708 .bdrv_close
= raw_close
,
710 .bdrv_aio_readv
= raw_aio_readv
,
711 .bdrv_aio_writev
= raw_aio_writev
,
712 .bdrv_aio_flush
= raw_aio_flush
,
714 .bdrv_detach_aio_context
= raw_detach_aio_context
,
715 .bdrv_attach_aio_context
= raw_attach_aio_context
,
717 .bdrv_getlength
= raw_getlength
,
718 .has_variable_length
= true,
720 .bdrv_get_allocated_file_size
721 = raw_get_allocated_file_size
,
724 static void bdrv_file_init(void)
726 bdrv_register(&bdrv_file
);
727 bdrv_register(&bdrv_host_device
);
730 block_init(bdrv_file_init
);