file-win32.c 21.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * Block driver for RAW files (win32)
 *
 * Copyright (c) 2006 Fabrice Bellard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
P
Peter Maydell 已提交
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"
30
#include "trace.h"
31
#include "block/thread-pool.h"
32
#include "qemu/iov.h"
33
#include "qapi/qmp/qstring.h"
34
#include "qapi/util.h"
35
#include <windows.h>
36 37 38 39 40 41
#include <winioctl.h>

#define FTYPE_FILE 0
#define FTYPE_CD     1
#define FTYPE_HARDDISK 2

42 43 44 45 46 47 48 49 50 51
typedef struct RawWin32AIOData {
    BlockDriverState *bs;
    HANDLE hfile;
    struct iovec *aio_iov;
    int aio_niov;
    size_t aio_nbytes;
    off64_t aio_offset;
    int aio_type;
} RawWin32AIOData;

52 53 54 55
typedef struct BDRVRawState {
    HANDLE hfile;
    int type;
    char drive_path[16]; /* format: "d:\" */
56
    QEMUWin32AIOState *aio;
57 58
} BDRVRawState;

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
/*
 * Read/writes the data to/from a given linear buffer.
 *
 * Returns the number of bytes handles or -errno in case of an error. Short
 * reads are only returned if the end of the file is reached.
 */
static size_t handle_aiocb_rw(RawWin32AIOData *aiocb)
{
    size_t offset = 0;
    int i;

    for (i = 0; i < aiocb->aio_niov; i++) {
        OVERLAPPED ov;
        DWORD ret, ret_count, len;

        memset(&ov, 0, sizeof(ov));
        ov.Offset = (aiocb->aio_offset + offset);
        ov.OffsetHigh = (aiocb->aio_offset + offset) >> 32;
        len = aiocb->aio_iov[i].iov_len;
        if (aiocb->aio_type & QEMU_AIO_WRITE) {
            ret = WriteFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
                            len, &ret_count, &ov);
        } else {
            ret = ReadFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
                           len, &ret_count, &ov);
        }
        if (!ret) {
            ret_count = 0;
        }
        if (ret_count != len) {
89
            offset += ret_count;
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
            break;
        }
        offset += len;
    }

    return offset;
}

static int aio_worker(void *arg)
{
    RawWin32AIOData *aiocb = arg;
    ssize_t ret = 0;
    size_t count;

    switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
    case QEMU_AIO_READ:
        count = handle_aiocb_rw(aiocb);
M
Max Reitz 已提交
107
        if (count < aiocb->aio_nbytes) {
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
            /* A short read means that we have reached EOF. Pad the buffer
             * with zeros for bytes after EOF. */
            iov_memset(aiocb->aio_iov, aiocb->aio_niov, count,
                      0, aiocb->aio_nbytes - count);

            count = aiocb->aio_nbytes;
        }
        if (count == aiocb->aio_nbytes) {
            ret = 0;
        } else {
            ret = -EINVAL;
        }
        break;
    case QEMU_AIO_WRITE:
        count = handle_aiocb_rw(aiocb);
        if (count == aiocb->aio_nbytes) {
124
            ret = 0;
125
        } else {
126
            ret = -EINVAL;
127 128 129 130 131 132 133 134 135 136 137 138 139
        }
        break;
    case QEMU_AIO_FLUSH:
        if (!FlushFileBuffers(aiocb->hfile)) {
            return -EIO;
        }
        break;
    default:
        fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
        ret = -EINVAL;
        break;
    }

140
    g_free(aiocb);
141 142 143
    return ret;
}

144
static BlockAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
145
        int64_t offset, QEMUIOVector *qiov, int count,
146
        BlockCompletionFunc *cb, void *opaque, int type)
147
{
148
    RawWin32AIOData *acb = g_new(RawWin32AIOData, 1);
149
    ThreadPool *pool;
150 151 152 153 154 155 156 157

    acb->bs = bs;
    acb->hfile = hfile;
    acb->aio_type = type;

    if (qiov) {
        acb->aio_iov = qiov->iov;
        acb->aio_niov = qiov->niov;
158
        assert(qiov->size == count);
159
    }
160 161
    acb->aio_nbytes = count;
    acb->aio_offset = offset;
162

163
    trace_paio_submit(acb, opaque, offset, count, type);
164 165
    pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
    return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
166 167
}

168 169 170
int qemu_ftruncate64(int fd, int64_t length)
{
    LARGE_INTEGER li;
S
Stefan Weil 已提交
171
    DWORD dw;
172 173 174 175 176 177 178 179 180 181 182 183
    LONG high;
    HANDLE h;
    BOOL res;

    if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
	return -1;

    h = (HANDLE)_get_osfhandle(fd);

    /* get current position, ftruncate do not change position */
    li.HighPart = 0;
    li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
S
Stefan Weil 已提交
184
    if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
185
	return -1;
S
Stefan Weil 已提交
186
    }
187 188

    high = length >> 32;
S
Stefan Weil 已提交
189 190
    dw = SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN);
    if (dw == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
191
	return -1;
S
Stefan Weil 已提交
192
    }
193 194 195 196 197 198 199 200 201 202 203 204 205 206
    res = SetEndOfFile(h);

    /* back to old position */
    SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
    return res ? 0 : -1;
}

static int set_sparse(int fd)
{
    DWORD returned;
    return (int) DeviceIoControl((HANDLE)_get_osfhandle(fd), FSCTL_SET_SPARSE,
				 NULL, 0, NULL, 0, &returned, NULL);
}

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
static void raw_detach_aio_context(BlockDriverState *bs)
{
    BDRVRawState *s = bs->opaque;

    if (s->aio) {
        win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
    }
}

static void raw_attach_aio_context(BlockDriverState *bs,
                                   AioContext *new_context)
{
    BDRVRawState *s = bs->opaque;

    if (s->aio) {
        win32_aio_attach_aio_context(s->aio, new_context);
    }
}

226
static void raw_probe_alignment(BlockDriverState *bs, Error **errp)
227 228 229 230 231 232 233
{
    BDRVRawState *s = bs->opaque;
    DWORD sectorsPerCluster, freeClusters, totalClusters, count;
    DISK_GEOMETRY_EX dg;
    BOOL status;

    if (s->type == FTYPE_CD) {
234
        bs->bl.request_alignment = 2048;
235 236 237 238 239 240
        return;
    }
    if (s->type == FTYPE_HARDDISK) {
        status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
                                 NULL, 0, &dg, sizeof(dg), &count, NULL);
        if (status != 0) {
241
            bs->bl.request_alignment = dg.Geometry.BytesPerSector;
242 243 244 245 246 247 248 249 250
            return;
        }
        /* try GetDiskFreeSpace too */
    }

    if (s->drive_path[0]) {
        GetDiskFreeSpace(s->drive_path, &sectorsPerCluster,
                         &dg.Geometry.BytesPerSector,
                         &freeClusters, &totalClusters);
251
        bs->bl.request_alignment = dg.Geometry.BytesPerSector;
252 253 254
    }
}

255 256
static void raw_parse_flags(int flags, bool use_aio, int *access_flags,
                            DWORD *overlapped)
257 258 259 260 261 262 263 264 265 266 267
{
    assert(access_flags != NULL);
    assert(overlapped != NULL);

    if (flags & BDRV_O_RDWR) {
        *access_flags = GENERIC_READ | GENERIC_WRITE;
    } else {
        *access_flags = GENERIC_READ;
    }

    *overlapped = FILE_ATTRIBUTE_NORMAL;
268
    if (use_aio) {
269 270
        *overlapped |= FILE_FLAG_OVERLAPPED;
    }
271 272 273 274 275
    if (flags & BDRV_O_NOCACHE) {
        *overlapped |= FILE_FLAG_NO_BUFFERING;
    }
}

276 277 278
static void raw_parse_filename(const char *filename, QDict *options,
                               Error **errp)
{
279
    bdrv_parse_filename_strip_prefix(filename, "file:", options);
280 281
}

282 283 284 285 286 287 288 289 290
static QemuOptsList raw_runtime_opts = {
    .name = "raw",
    .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
    .desc = {
        {
            .name = "filename",
            .type = QEMU_OPT_STRING,
            .help = "File name of the image",
        },
291 292 293 294 295
        {
            .name = "aio",
            .type = QEMU_OPT_STRING,
            .help = "host AIO implementation (threads, native)",
        },
296 297 298 299
        { /* end of list */ }
    },
};

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
static bool get_aio_option(QemuOpts *opts, int flags, Error **errp)
{
    BlockdevAioOptions aio, aio_default;

    aio_default = (flags & BDRV_O_NATIVE_AIO) ? BLOCKDEV_AIO_OPTIONS_NATIVE
                                              : BLOCKDEV_AIO_OPTIONS_THREADS;
    aio = qapi_enum_parse(BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"),
                          BLOCKDEV_AIO_OPTIONS__MAX, aio_default, errp);

    switch (aio) {
    case BLOCKDEV_AIO_OPTIONS_NATIVE:
        return true;
    case BLOCKDEV_AIO_OPTIONS_THREADS:
        return false;
    default:
        error_setg(errp, "Invalid AIO option");
    }
    return false;
}

M
Max Reitz 已提交
320 321
static int raw_open(BlockDriverState *bs, QDict *options, int flags,
                    Error **errp)
322 323
{
    BDRVRawState *s = bs->opaque;
C
Christoph Hellwig 已提交
324
    int access_flags;
325
    DWORD overlapped;
326 327 328
    QemuOpts *opts;
    Error *local_err = NULL;
    const char *filename;
329
    bool use_aio;
330
    int ret;
331 332 333

    s->type = FTYPE_FILE;

334
    opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
335
    qemu_opts_absorb_qdict(opts, options, &local_err);
336
    if (local_err) {
337
        error_propagate(errp, local_err);
338 339 340 341
        ret = -EINVAL;
        goto fail;
    }

F
Fam Zheng 已提交
342 343
    if (qdict_get_try_bool(options, "locking", false)) {
        error_setg(errp, "locking=on is not supported on Windows");
344
        ret = -EINVAL;
F
Fam Zheng 已提交
345 346 347
        goto fail;
    }

348 349
    filename = qemu_opt_get(opts, "filename");

350 351 352 353 354 355 356 357
    use_aio = get_aio_option(opts, flags, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        ret = -EINVAL;
        goto fail;
    }

    raw_parse_flags(flags, use_aio, &access_flags, &overlapped);
358

359 360 361 362 363 364 365 366 367 368 369
    if (filename[0] && filename[1] == ':') {
        snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", filename[0]);
    } else if (filename[0] == '\\' && filename[1] == '\\') {
        s->drive_path[0] = 0;
    } else {
        /* Relative path.  */
        char buf[MAX_PATH];
        GetCurrentDirectory(MAX_PATH, buf);
        snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]);
    }

370 371
    s->hfile = CreateFile(filename, access_flags,
                          FILE_SHARE_READ, NULL,
C
Christoph Hellwig 已提交
372
                          OPEN_EXISTING, overlapped, NULL);
373 374 375
    if (s->hfile == INVALID_HANDLE_VALUE) {
        int err = GetLastError();

376
        error_setg_win32(errp, err, "Could not open '%s'", filename);
377 378 379 380 381 382
        if (err == ERROR_ACCESS_DENIED) {
            ret = -EACCES;
        } else {
            ret = -EINVAL;
        }
        goto fail;
383 384
    }

385
    if (use_aio) {
386 387 388 389 390 391 392 393 394
        s->aio = win32_aio_init();
        if (s->aio == NULL) {
            CloseHandle(s->hfile);
            error_setg(errp, "Could not initialize AIO");
            ret = -EINVAL;
            goto fail;
        }

        ret = win32_aio_attach(s->aio, s->hfile);
395
        if (ret < 0) {
396
            win32_aio_cleanup(s->aio);
397
            CloseHandle(s->hfile);
398
            error_setg_errno(errp, -ret, "Could not enable AIO");
399
            goto fail;
400
        }
401 402

        win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));
403
    }
404 405 406 407 408

    ret = 0;
fail:
    qemu_opts_del(opts);
    return ret;
409 410
}

411
static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
412
                         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
413
                         BlockCompletionFunc *cb, void *opaque)
414 415
{
    BDRVRawState *s = bs->opaque;
416 417
    if (s->aio) {
        return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
418
                                nb_sectors, cb, opaque, QEMU_AIO_READ);
419
    } else {
420 421
        return paio_submit(bs, s->hfile, sector_num << BDRV_SECTOR_BITS, qiov,
                           nb_sectors << BDRV_SECTOR_BITS,
422 423
                           cb, opaque, QEMU_AIO_READ);
    }
424 425
}

426
static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
427
                          int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
428
                          BlockCompletionFunc *cb, void *opaque)
429 430
{
    BDRVRawState *s = bs->opaque;
431 432
    if (s->aio) {
        return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
433
                                nb_sectors, cb, opaque, QEMU_AIO_WRITE);
434
    } else {
435 436
        return paio_submit(bs, s->hfile, sector_num << BDRV_SECTOR_BITS, qiov,
                           nb_sectors << BDRV_SECTOR_BITS,
437 438
                           cb, opaque, QEMU_AIO_WRITE);
    }
439 440
}

441
static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
442
                         BlockCompletionFunc *cb, void *opaque)
443 444
{
    BDRVRawState *s = bs->opaque;
445
    return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
446 447 448 449 450
}

static void raw_close(BlockDriverState *bs)
{
    BDRVRawState *s = bs->opaque;
451 452

    if (s->aio) {
453
        win32_aio_detach_aio_context(s->aio, bdrv_get_aio_context(bs));
454 455 456 457
        win32_aio_cleanup(s->aio);
        s->aio = NULL;
    }

458
    CloseHandle(s->hfile);
459 460 461
    if (bs->open_flags & BDRV_O_TEMPORARY) {
        unlink(bs->filename);
    }
462 463
}

464
static int raw_truncate(BlockDriverState *bs, int64_t offset, Error **errp)
465 466
{
    BDRVRawState *s = bs->opaque;
B
blueswir1 已提交
467
    LONG low, high;
468
    DWORD dwPtrLow;
469 470 471

    low = offset;
    high = offset >> 32;
472 473 474 475 476 477 478

    /*
     * An error has occurred if the return value is INVALID_SET_FILE_POINTER
     * and GetLastError doesn't return NO_ERROR.
     */
    dwPtrLow = SetFilePointer(s->hfile, low, &high, FILE_BEGIN);
    if (dwPtrLow == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
479
        error_setg_win32(errp, GetLastError(), "SetFilePointer error");
480 481 482
        return -EIO;
    }
    if (SetEndOfFile(s->hfile) == 0) {
483
        error_setg_win32(errp, GetLastError(), "SetEndOfFile error");
484
        return -EIO;
485
    }
486 487 488 489 490 491 492 493 494 495 496 497 498 499
    return 0;
}

static int64_t raw_getlength(BlockDriverState *bs)
{
    BDRVRawState *s = bs->opaque;
    LARGE_INTEGER l;
    ULARGE_INTEGER available, total, total_free;
    DISK_GEOMETRY_EX dg;
    DWORD count;
    BOOL status;

    switch(s->type) {
    case FTYPE_FILE:
B
blueswir1 已提交
500
        l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
            return -EIO;
        break;
    case FTYPE_CD:
        if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
            return -EIO;
        l.QuadPart = total.QuadPart;
        break;
    case FTYPE_HARDDISK:
        status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
                                 NULL, 0, &dg, sizeof(dg), &count, NULL);
        if (status != 0) {
            l = dg.DiskSize;
        }
        break;
    default:
        return -EIO;
    }
    return l.QuadPart;
}

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
{
    typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
                                              DWORD * high);
    get_compressed_t get_compressed;
    struct _stati64 st;
    const char *filename = bs->filename;
    /* WinNT support GetCompressedFileSize to determine allocate size */
    get_compressed =
        (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
                                            "GetCompressedFileSizeA");
    if (get_compressed) {
        DWORD high, low;
        low = get_compressed(filename, &high);
        if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR) {
            return (((int64_t) high) << 32) + low;
        }
    }

    if (_stati64(filename, &st) < 0) {
        return -1;
    }
    return st.st_size;
}

547
static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
548 549
{
    int fd;
550
    int64_t total_size = 0;
551

552 553
    strstart(filename, "file:", &filename);

554
    /* Read out options */
555 556
    total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
                          BDRV_SECTOR_SIZE);
557

558 559
    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
                   0644);
560 561
    if (fd < 0) {
        error_setg_errno(errp, errno, "Could not create file");
562
        return -EIO;
563
    }
564
    set_sparse(fd);
565
    ftruncate(fd, total_size);
566
    qemu_close(fd);
567 568 569
    return 0;
}

570 571 572 573 574 575 576 577 578 579 580 581

static QemuOptsList raw_create_opts = {
    .name = "raw-create-opts",
    .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
    .desc = {
        {
            .name = BLOCK_OPT_SIZE,
            .type = QEMU_OPT_SIZE,
            .help = "Virtual disk size"
        },
        { /* end of list */ }
    }
582 583
};

584
BlockDriver bdrv_file = {
585 586
    .format_name	= "file",
    .protocol_name	= "file",
587
    .instance_size	= sizeof(BDRVRawState),
588
    .bdrv_needs_filename = true,
589
    .bdrv_parse_filename = raw_parse_filename,
590
    .bdrv_file_open     = raw_open,
591
    .bdrv_refresh_limits = raw_probe_alignment,
592
    .bdrv_close         = raw_close,
C
Chunyan Liu 已提交
593
    .bdrv_create        = raw_create,
594
    .bdrv_has_zero_init = bdrv_has_zero_init_1,
595

596 597 598
    .bdrv_aio_readv     = raw_aio_readv,
    .bdrv_aio_writev    = raw_aio_writev,
    .bdrv_aio_flush     = raw_aio_flush,
599

600 601
    .bdrv_truncate	= raw_truncate,
    .bdrv_getlength	= raw_getlength,
602 603
    .bdrv_get_allocated_file_size
                        = raw_get_allocated_file_size,
604

605
    .create_opts        = &raw_create_opts,
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
};

/***********************************************/
/* host device */

static int find_cdrom(char *cdrom_name, int cdrom_name_size)
{
    char drives[256], *pdrv = drives;
    UINT type;

    memset(drives, 0, sizeof(drives));
    GetLogicalDriveStrings(sizeof(drives), drives);
    while(pdrv[0] != '\0') {
        type = GetDriveType(pdrv);
        switch(type) {
        case DRIVE_CDROM:
            snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
            return 0;
            break;
        }
        pdrv += lstrlen(pdrv) + 1;
    }
    return -1;
}

static int find_device_type(BlockDriverState *bs, const char *filename)
{
    BDRVRawState *s = bs->opaque;
    UINT type;
    const char *p;

    if (strstart(filename, "\\\\.\\", &p) ||
        strstart(filename, "//./", &p)) {
        if (stristart(p, "PhysicalDrive", NULL))
            return FTYPE_HARDDISK;
        snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", p[0]);
        type = GetDriveType(s->drive_path);
643 644 645 646 647
        switch (type) {
        case DRIVE_REMOVABLE:
        case DRIVE_FIXED:
            return FTYPE_HARDDISK;
        case DRIVE_CDROM:
648
            return FTYPE_CD;
649
        default:
650
            return FTYPE_FILE;
651
        }
652 653 654 655 656
    } else {
        return FTYPE_FILE;
    }
}

657 658 659 660 661 662 663 664 665
static int hdev_probe_device(const char *filename)
{
    if (strstart(filename, "/dev/cdrom", NULL))
        return 100;
    if (is_windows_drive(filename))
        return 100;
    return 0;
}

666 667 668
static void hdev_parse_filename(const char *filename, QDict *options,
                                Error **errp)
{
669
    bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
670 671
}

M
Max Reitz 已提交
672 673
static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
                     Error **errp)
674 675 676
{
    BDRVRawState *s = bs->opaque;
    int access_flags, create_flags;
677
    int ret = 0;
678 679
    DWORD overlapped;
    char device_name[64];
680 681 682

    Error *local_err = NULL;
    const char *filename;
683
    bool use_aio;
684

685 686
    QemuOpts *opts = qemu_opts_create(&raw_runtime_opts, NULL, 0,
                                      &error_abort);
687
    qemu_opts_absorb_qdict(opts, options, &local_err);
688
    if (local_err) {
689
        error_propagate(errp, local_err);
690 691 692 693 694
        ret = -EINVAL;
        goto done;
    }

    filename = qemu_opt_get(opts, "filename");
695

696 697 698 699 700 701 702 703 704 705
    use_aio = get_aio_option(opts, flags, &local_err);
    if (!local_err && use_aio) {
        error_setg(&local_err, "AIO is not supported on Windows host devices");
    }
    if (local_err) {
        error_propagate(errp, local_err);
        ret = -EINVAL;
        goto done;
    }

706
    if (strstart(filename, "/dev/cdrom", NULL)) {
707
        if (find_cdrom(device_name, sizeof(device_name)) < 0) {
708
            error_setg(errp, "Could not open CD-ROM drive");
709 710 711
            ret = -ENOENT;
            goto done;
        }
712 713 714 715 716 717 718 719 720 721 722 723
        filename = device_name;
    } else {
        /* transform drive letters into device name */
        if (((filename[0] >= 'a' && filename[0] <= 'z') ||
             (filename[0] >= 'A' && filename[0] <= 'Z')) &&
            filename[1] == ':' && filename[2] == '\0') {
            snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
            filename = device_name;
        }
    }
    s->type = find_device_type(bs, filename);

724
    raw_parse_flags(flags, use_aio, &access_flags, &overlapped);
725

726 727 728 729 730 731 732 733
    create_flags = OPEN_EXISTING;

    s->hfile = CreateFile(filename, access_flags,
                          FILE_SHARE_READ, NULL,
                          create_flags, overlapped, NULL);
    if (s->hfile == INVALID_HANDLE_VALUE) {
        int err = GetLastError();

734 735 736
        if (err == ERROR_ACCESS_DENIED) {
            ret = -EACCES;
        } else {
737
            ret = -EINVAL;
738
        }
739
        error_setg_errno(errp, -ret, "Could not open device");
740
        goto done;
741
    }
742 743 744 745

done:
    qemu_opts_del(opts);
    return ret;
746 747
}

748
static BlockDriver bdrv_host_device = {
749
    .format_name	= "host_device",
750
    .protocol_name	= "host_device",
751
    .instance_size	= sizeof(BDRVRawState),
752
    .bdrv_needs_filename = true,
753
    .bdrv_parse_filename = hdev_parse_filename,
754
    .bdrv_probe_device	= hdev_probe_device,
755
    .bdrv_file_open	= hdev_open,
756
    .bdrv_close		= raw_close,
757

758 759 760
    .bdrv_aio_readv     = raw_aio_readv,
    .bdrv_aio_writev    = raw_aio_writev,
    .bdrv_aio_flush     = raw_aio_flush,
761

762 763 764
    .bdrv_detach_aio_context = raw_detach_aio_context,
    .bdrv_attach_aio_context = raw_attach_aio_context,

765 766 767
    .bdrv_getlength      = raw_getlength,
    .has_variable_length = true,

768 769
    .bdrv_get_allocated_file_size
                        = raw_get_allocated_file_size,
770
};
771

772
static void bdrv_file_init(void)
773
{
774
    bdrv_register(&bdrv_file);
775 776 777
    bdrv_register(&bdrv_host_device);
}

778
block_init(bdrv_file_init);