net: remove all cleanup methods from NIC NetClientInfos
[qemu/rayw.git] / block / raw-win32.c
blob06243d76df61d3dff9a134a4c32b05fd49955cbc
1 /*
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
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "qemu/timer.h"
26 #include "block/block_int.h"
27 #include "qemu/module.h"
28 #include "raw-aio.h"
29 #include "trace.h"
30 #include "block/thread-pool.h"
31 #include "qemu/iov.h"
32 #include <windows.h>
33 #include <winioctl.h>
35 #define FTYPE_FILE 0
36 #define FTYPE_CD 1
37 #define FTYPE_HARDDISK 2
39 typedef struct RawWin32AIOData {
40 BlockDriverState *bs;
41 HANDLE hfile;
42 struct iovec *aio_iov;
43 int aio_niov;
44 size_t aio_nbytes;
45 off64_t aio_offset;
46 int aio_type;
47 } RawWin32AIOData;
49 typedef struct BDRVRawState {
50 HANDLE hfile;
51 int type;
52 char drive_path[16]; /* format: "d:\" */
53 QEMUWin32AIOState *aio;
54 } BDRVRawState;
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)
64 size_t offset = 0;
65 int i;
67 for (i = 0; i < aiocb->aio_niov; i++) {
68 OVERLAPPED ov;
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);
78 } else {
79 ret = ReadFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
80 len, &ret_count, &ov);
82 if (!ret) {
83 ret_count = 0;
85 if (ret_count != len) {
86 offset += ret_count;
87 break;
89 offset += len;
92 return offset;
95 static int aio_worker(void *arg)
97 RawWin32AIOData *aiocb = arg;
98 ssize_t ret = 0;
99 size_t count;
101 switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
102 case QEMU_AIO_READ:
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) {
113 ret = 0;
114 } else {
115 ret = -EINVAL;
117 break;
118 case QEMU_AIO_WRITE:
119 count = handle_aiocb_rw(aiocb);
120 if (count == aiocb->aio_nbytes) {
121 count = 0;
122 } else {
123 count = -EINVAL;
125 break;
126 case QEMU_AIO_FLUSH:
127 if (!FlushFileBuffers(aiocb->hfile)) {
128 return -EIO;
130 break;
131 default:
132 fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
133 ret = -EINVAL;
134 break;
137 g_slice_free(RawWin32AIOData, aiocb);
138 return ret;
141 static BlockAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
142 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
143 BlockCompletionFunc *cb, void *opaque, int type)
145 RawWin32AIOData *acb = g_slice_new(RawWin32AIOData);
146 ThreadPool *pool;
148 acb->bs = bs;
149 acb->hfile = hfile;
150 acb->aio_type = type;
152 if (qiov) {
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)
166 LARGE_INTEGER li;
167 DWORD dw;
168 LONG high;
169 HANDLE h;
170 BOOL res;
172 if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
173 return -1;
175 h = (HANDLE)_get_osfhandle(fd);
177 /* get current position, ftruncate do not change position */
178 li.HighPart = 0;
179 li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
180 if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
181 return -1;
184 high = length >> 32;
185 dw = SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN);
186 if (dw == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
187 return -1;
189 res = SetEndOfFile(h);
191 /* back to old position */
192 SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
193 return res ? 0 : -1;
196 static int set_sparse(int fd)
198 DWORD returned;
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;
207 if (s->aio) {
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;
217 if (s->aio) {
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;
226 DISK_GEOMETRY_EX dg;
227 BOOL status;
229 if (s->type == FTYPE_CD) {
230 bs->request_alignment = 2048;
231 return;
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);
236 if (status != 0) {
237 bs->request_alignment = dg.Geometry.BytesPerSector;
238 return;
240 /* try GetDiskFreeSpace too */
243 if (s->drive_path[0]) {
244 GetDiskFreeSpace(s->drive_path, &sectorsPerCluster,
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;
258 } else {
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,
272 Error **errp)
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 = {
283 .name = "raw",
284 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
285 .desc = {
287 .name = "filename",
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,
296 Error **errp)
298 BDRVRawState *s = bs->opaque;
299 int access_flags;
300 DWORD overlapped;
301 QemuOpts *opts;
302 Error *local_err = NULL;
303 const char *filename;
304 int ret;
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);
310 if (local_err) {
311 error_propagate(errp, local_err);
312 ret = -EINVAL;
313 goto fail;
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;
324 } else {
325 /* Relative path. */
326 char buf[MAX_PATH];
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) {
338 ret = -EACCES;
339 } else {
340 ret = -EINVAL;
342 goto fail;
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");
350 ret = -EINVAL;
351 goto fail;
354 ret = win32_aio_attach(s->aio, s->hfile);
355 if (ret < 0) {
356 win32_aio_cleanup(s->aio);
357 CloseHandle(s->hfile);
358 error_setg_errno(errp, -ret, "Could not enable AIO");
359 goto fail;
362 win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));
365 raw_probe_alignment(bs);
366 ret = 0;
367 fail:
368 qemu_opts_del(opts);
369 return ret;
372 static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
373 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
374 BlockCompletionFunc *cb, void *opaque)
376 BDRVRawState *s = bs->opaque;
377 if (s->aio) {
378 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
379 nb_sectors, cb, opaque, QEMU_AIO_READ);
380 } else {
381 return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
382 cb, opaque, QEMU_AIO_READ);
386 static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
387 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
388 BlockCompletionFunc *cb, void *opaque)
390 BDRVRawState *s = bs->opaque;
391 if (s->aio) {
392 return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
393 nb_sectors, cb, opaque, QEMU_AIO_WRITE);
394 } else {
395 return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
396 cb, opaque, QEMU_AIO_WRITE);
400 static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
401 BlockCompletionFunc *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;
411 if (s->aio) {
412 win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
413 win32_aio_cleanup(s->aio);
414 s->aio = NULL;
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;
426 LONG low, high;
427 DWORD dwPtrLow;
429 low = offset;
430 high = offset >> 32;
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());
439 return -EIO;
441 if (SetEndOfFile(s->hfile) == 0) {
442 fprintf(stderr, "SetEndOfFile error: %lu\n", GetLastError());
443 return -EIO;
445 return 0;
448 static int64_t raw_getlength(BlockDriverState *bs)
450 BDRVRawState *s = bs->opaque;
451 LARGE_INTEGER l;
452 ULARGE_INTEGER available, total, total_free;
453 DISK_GEOMETRY_EX dg;
454 DWORD count;
455 BOOL status;
457 switch(s->type) {
458 case FTYPE_FILE:
459 l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
460 if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
461 return -EIO;
462 break;
463 case FTYPE_CD:
464 if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
465 return -EIO;
466 l.QuadPart = total.QuadPart;
467 break;
468 case FTYPE_HARDDISK:
469 status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
470 NULL, 0, &dg, sizeof(dg), &count, NULL);
471 if (status != 0) {
472 l = dg.DiskSize;
474 break;
475 default:
476 return -EIO;
478 return l.QuadPart;
481 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
483 typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
484 DWORD * high);
485 get_compressed_t get_compressed;
486 struct _stati64 st;
487 const char *filename = bs->filename;
488 /* WinNT support GetCompressedFileSize to determine allocate size */
489 get_compressed =
490 (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
491 "GetCompressedFileSizeA");
492 if (get_compressed) {
493 DWORD high, low;
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) {
501 return -1;
503 return st.st_size;
506 static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
508 int fd;
509 int64_t total_size = 0;
511 strstart(filename, "file:", &filename);
513 /* Read out options */
514 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
515 BDRV_SECTOR_SIZE);
517 fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
518 0644);
519 if (fd < 0) {
520 error_setg_errno(errp, errno, "Could not create file");
521 return -EIO;
523 set_sparse(fd);
524 ftruncate(fd, total_size);
525 qemu_close(fd);
526 return 0;
530 static QemuOptsList raw_create_opts = {
531 .name = "raw-create-opts",
532 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
533 .desc = {
535 .name = BLOCK_OPT_SIZE,
536 .type = QEMU_OPT_SIZE,
537 .help = "Virtual disk size"
539 { /* end of list */ }
543 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_opts = &raw_create_opts,
566 /***********************************************/
567 /* host device */
569 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
571 char drives[256], *pdrv = drives;
572 UINT type;
574 memset(drives, 0, sizeof(drives));
575 GetLogicalDriveStrings(sizeof(drives), drives);
576 while(pdrv[0] != '\0') {
577 type = GetDriveType(pdrv);
578 switch(type) {
579 case DRIVE_CDROM:
580 snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
581 return 0;
582 break;
584 pdrv += lstrlen(pdrv) + 1;
586 return -1;
589 static int find_device_type(BlockDriverState *bs, const char *filename)
591 BDRVRawState *s = bs->opaque;
592 UINT type;
593 const char *p;
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);
601 switch (type) {
602 case DRIVE_REMOVABLE:
603 case DRIVE_FIXED:
604 return FTYPE_HARDDISK;
605 case DRIVE_CDROM:
606 return FTYPE_CD;
607 default:
608 return FTYPE_FILE;
610 } else {
611 return FTYPE_FILE;
615 static int hdev_probe_device(const char *filename)
617 if (strstart(filename, "/dev/cdrom", NULL))
618 return 100;
619 if (is_windows_drive(filename))
620 return 100;
621 return 0;
624 static void hdev_parse_filename(const char *filename, QDict *options,
625 Error **errp)
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,
634 Error **errp)
636 BDRVRawState *s = bs->opaque;
637 int access_flags, create_flags;
638 int ret = 0;
639 DWORD overlapped;
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,
646 &error_abort);
647 qemu_opts_absorb_qdict(opts, options, &local_err);
648 if (local_err) {
649 error_propagate(errp, local_err);
650 ret = -EINVAL;
651 goto done;
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");
659 ret = -ENOENT;
660 goto done;
662 filename = device_name;
663 } else {
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) {
685 ret = -EACCES;
686 } else {
687 ret = -EINVAL;
689 error_setg_errno(errp, -ret, "Could not open device");
690 goto done;
693 done:
694 qemu_opts_del(opts);
695 return ret;
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);