block.c 149 KB
Newer Older
bellard's avatar
bellard committed
1 2
/*
 * QEMU System Emulator block driver
3
 *
bellard's avatar
bellard committed
4
 * Copyright (c) 2003 Fabrice Bellard
5
 *
bellard's avatar
bellard committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * 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.
 */
24
#include "config-host.h"
pbrook's avatar
pbrook committed
25
#include "qemu-common.h"
26
#include "trace.h"
27
#include "monitor/monitor.h"
28 29
#include "block/block_int.h"
#include "block/blockjob.h"
30
#include "qemu/module.h"
31
#include "qapi/qmp/qjson.h"
32
#include "sysemu/sysemu.h"
33
#include "qemu/notify.h"
34
#include "block/coroutine.h"
35
#include "block/qapi.h"
36
#include "qmp-commands.h"
37
#include "qemu/timer.h"
bellard's avatar
bellard committed
38

39
#ifdef CONFIG_BSD
bellard's avatar
bellard committed
40 41 42
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
43
#include <sys/queue.h>
44
#ifndef __DragonFly__
bellard's avatar
bellard committed
45 46
#include <sys/disk.h>
#endif
47
#endif
bellard's avatar
bellard committed
48

49 50 51 52
#ifdef _WIN32
#include <windows.h>
#endif

53 54 55 56 57
struct BdrvDirtyBitmap {
    HBitmap *bitmap;
    QLIST_ENTRY(BdrvDirtyBitmap) list;
};

58 59
#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */

60
static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
61 62
static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
63
        BlockDriverCompletionFunc *cb, void *opaque);
64 65
static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
66
        BlockDriverCompletionFunc *cb, void *opaque);
67 68 69 70 71 72
static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
                                         int64_t sector_num, int nb_sectors,
                                         QEMUIOVector *iov);
static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
                                         int64_t sector_num, int nb_sectors,
                                         QEMUIOVector *iov);
73
static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
74 75
    int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
    BdrvRequestFlags flags);
76
static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
77 78
    int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
    BdrvRequestFlags flags);
79 80 81 82
static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
                                               int64_t sector_num,
                                               QEMUIOVector *qiov,
                                               int nb_sectors,
83
                                               BdrvRequestFlags flags,
84 85
                                               BlockDriverCompletionFunc *cb,
                                               void *opaque,
86
                                               bool is_write);
87
static void coroutine_fn bdrv_co_do_rw(void *opaque);
Kevin Wolf's avatar
Kevin Wolf committed
88
static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
89
    int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
bellard's avatar
bellard committed
90

91 92
static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
    QTAILQ_HEAD_INITIALIZER(bdrv_states);
93

94 95 96
static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
    QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);

97 98
static QLIST_HEAD(, BlockDriver) bdrv_drivers =
    QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellard's avatar
bellard committed
99

100 101 102
/* If non-zero, use only whitelisted block drivers */
static int use_bdrv_whitelist;

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
#ifdef _WIN32
static int is_windows_drive_prefix(const char *filename)
{
    return (((filename[0] >= 'a' && filename[0] <= 'z') ||
             (filename[0] >= 'A' && filename[0] <= 'Z')) &&
            filename[1] == ':');
}

int is_windows_drive(const char *filename)
{
    if (is_windows_drive_prefix(filename) &&
        filename[2] == '\0')
        return 1;
    if (strstart(filename, "\\\\.\\", NULL) ||
        strstart(filename, "//./", NULL))
        return 1;
    return 0;
}
#endif

123
/* throttling disk I/O limits */
124 125
void bdrv_set_io_limits(BlockDriverState *bs,
                        ThrottleConfig *cfg)
126
{
127
    int i;
128

129
    throttle_config(&bs->throttle_state, cfg);
130

131 132
    for (i = 0; i < 2; i++) {
        qemu_co_enter_next(&bs->throttled_reqs[i]);
133
    }
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
}

/* this function drain all the throttled IOs */
static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
{
    bool drained = false;
    bool enabled = bs->io_limits_enabled;
    int i;

    bs->io_limits_enabled = false;

    for (i = 0; i < 2; i++) {
        while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
            drained = true;
        }
    }

    bs->io_limits_enabled = enabled;
152

153
    return drained;
154 155
}

156
void bdrv_io_limits_disable(BlockDriverState *bs)
157
{
158
    bs->io_limits_enabled = false;
159

160 161 162
    bdrv_start_throttled_reqs(bs);

    throttle_destroy(&bs->throttle_state);
163 164
}

165
static void bdrv_throttle_read_timer_cb(void *opaque)
166
{
167 168
    BlockDriverState *bs = opaque;
    qemu_co_enter_next(&bs->throttled_reqs[0]);
169 170
}

171
static void bdrv_throttle_write_timer_cb(void *opaque)
172
{
173 174
    BlockDriverState *bs = opaque;
    qemu_co_enter_next(&bs->throttled_reqs[1]);
175 176
}

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
/* should be called before bdrv_set_io_limits if a limit is set */
void bdrv_io_limits_enable(BlockDriverState *bs)
{
    assert(!bs->io_limits_enabled);
    throttle_init(&bs->throttle_state,
                  QEMU_CLOCK_VIRTUAL,
                  bdrv_throttle_read_timer_cb,
                  bdrv_throttle_write_timer_cb,
                  bs);
    bs->io_limits_enabled = true;
}

/* This function makes an IO wait if needed
 *
 * @nb_sectors: the number of sectors of the IO
 * @is_write:   is the IO a write
 */
194
static void bdrv_io_limits_intercept(BlockDriverState *bs,
195 196
                                     int nb_sectors,
                                     bool is_write)
197
{
198 199
    /* does this io must wait */
    bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
200

201 202 203 204
    /* if must wait or any request of this type throttled queue the IO */
    if (must_wait ||
        !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
        qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
205 206
    }

207 208 209 210
    /* the IO will be executed, do the accounting */
    throttle_account(&bs->throttle_state,
                     is_write,
                     nb_sectors * BDRV_SECTOR_SIZE);
211

212 213 214
    /* if the next request must wait -> do nothing */
    if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
        return;
215 216
    }

217 218
    /* else queue next request for execution */
    qemu_co_queue_next(&bs->throttled_reqs[is_write]);
219 220
}

221 222 223 224 225 226 227 228 229 230
size_t bdrv_opt_mem_align(BlockDriverState *bs)
{
    if (!bs || !bs->drv) {
        /* 4k should be on the safe side */
        return 4096;
    }

    return bs->bl.opt_mem_alignment;
}

231 232 233
/* check if the path starts with "<protocol>:" */
static int path_has_protocol(const char *path)
{
234 235
    const char *p;

236 237 238 239 240
#ifdef _WIN32
    if (is_windows_drive(path) ||
        is_windows_drive_prefix(path)) {
        return 0;
    }
241 242 243
    p = path + strcspn(path, ":/\\");
#else
    p = path + strcspn(path, ":/");
244 245
#endif

246
    return *p == ':';
247 248
}

bellard's avatar
bellard committed
249
int path_is_absolute(const char *path)
250
{
251 252
#ifdef _WIN32
    /* specific case for names like: "\\.\d:" */
253
    if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
254
        return 1;
255 256
    }
    return (*path == '/' || *path == '\\');
257
#else
258
    return (*path == '/');
259
#endif
260 261
}

bellard's avatar
bellard committed
262 263 264 265 266 267
/* if filename is absolute, just copy it to dest. Otherwise, build a
   path to it by considering it is relative to base_path. URL are
   supported. */
void path_combine(char *dest, int dest_size,
                  const char *base_path,
                  const char *filename)
268
{
bellard's avatar
bellard committed
269 270 271 272 273 274 275 276 277 278 279 280 281
    const char *p, *p1;
    int len;

    if (dest_size <= 0)
        return;
    if (path_is_absolute(filename)) {
        pstrcpy(dest, dest_size, filename);
    } else {
        p = strchr(base_path, ':');
        if (p)
            p++;
        else
            p = base_path;
282 283 284 285 286 287 288 289 290
        p1 = strrchr(base_path, '/');
#ifdef _WIN32
        {
            const char *p2;
            p2 = strrchr(base_path, '\\');
            if (!p1 || p2 > p1)
                p1 = p2;
        }
#endif
bellard's avatar
bellard committed
291 292 293 294 295 296 297 298 299 300 301 302
        if (p1)
            p1++;
        else
            p1 = base_path;
        if (p1 > p)
            p = p1;
        len = p - base_path;
        if (len > dest_size - 1)
            len = dest_size - 1;
        memcpy(dest, base_path, len);
        dest[len] = '\0';
        pstrcat(dest, dest_size, filename);
303 304 305
    }
}

306 307 308 309 310 311 312 313 314
void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
{
    if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
        pstrcpy(dest, sz, bs->backing_file);
    } else {
        path_combine(dest, sz, bs->filename, bs->backing_file);
    }
}

315
void bdrv_register(BlockDriver *bdrv)
bellard's avatar
bellard committed
316
{
317 318
    /* Block drivers without coroutine functions need emulation */
    if (!bdrv->bdrv_co_readv) {
319 320 321
        bdrv->bdrv_co_readv = bdrv_co_readv_em;
        bdrv->bdrv_co_writev = bdrv_co_writev_em;

322 323 324
        /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
         * the block driver lacks aio we need to emulate that too.
         */
325 326 327 328 329
        if (!bdrv->bdrv_aio_readv) {
            /* add AIO emulation layer */
            bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
            bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
        }
bellard's avatar
bellard committed
330
    }
331

332
    QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellard's avatar
bellard committed
333
}
bellard's avatar
bellard committed
334 335 336 337

/* create a new block device (by default it is empty) */
BlockDriverState *bdrv_new(const char *device_name)
{
338
    BlockDriverState *bs;
bellard's avatar
bellard committed
339

340
    bs = g_malloc0(sizeof(BlockDriverState));
341
    QLIST_INIT(&bs->dirty_bitmaps);
bellard's avatar
bellard committed
342
    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
bellard's avatar
bellard committed
343
    if (device_name[0] != '\0') {
344
        QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
bellard's avatar
bellard committed
345
    }
346
    bdrv_iostatus_disable(bs);
347
    notifier_list_init(&bs->close_notifiers);
348
    notifier_with_return_list_init(&bs->before_write_notifiers);
349 350
    qemu_co_queue_init(&bs->throttled_reqs[0]);
    qemu_co_queue_init(&bs->throttled_reqs[1]);
351
    bs->refcnt = 1;
352

bellard's avatar
bellard committed
353 354 355
    return bs;
}

356 357 358 359 360
void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
{
    notifier_list_add(&bs->close_notifiers, notify);
}

bellard's avatar
bellard committed
361 362 363
BlockDriver *bdrv_find_format(const char *format_name)
{
    BlockDriver *drv1;
364 365
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
        if (!strcmp(drv1->format_name, format_name)) {
bellard's avatar
bellard committed
366
            return drv1;
367
        }
bellard's avatar
bellard committed
368 369 370 371
    }
    return NULL;
}

372
static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
373
{
374 375 376 377 378
    static const char *whitelist_rw[] = {
        CONFIG_BDRV_RW_WHITELIST
    };
    static const char *whitelist_ro[] = {
        CONFIG_BDRV_RO_WHITELIST
379 380 381
    };
    const char **p;

382
    if (!whitelist_rw[0] && !whitelist_ro[0]) {
383
        return 1;               /* no whitelist, anything goes */
384
    }
385

386
    for (p = whitelist_rw; *p; p++) {
387 388 389 390
        if (!strcmp(drv->format_name, *p)) {
            return 1;
        }
    }
391 392 393 394 395 396 397
    if (read_only) {
        for (p = whitelist_ro; *p; p++) {
            if (!strcmp(drv->format_name, *p)) {
                return 1;
            }
        }
    }
398 399 400
    return 0;
}

401 402
BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
                                          bool read_only)
403 404
{
    BlockDriver *drv = bdrv_find_format(format_name);
405
    return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
406 407
}

408 409 410 411 412
typedef struct CreateCo {
    BlockDriver *drv;
    char *filename;
    QEMUOptionParameter *options;
    int ret;
413
    Error *err;
414 415 416 417
} CreateCo;

static void coroutine_fn bdrv_create_co_entry(void *opaque)
{
418 419 420
    Error *local_err = NULL;
    int ret;

421 422 423
    CreateCo *cco = opaque;
    assert(cco->drv);

424 425 426 427 428
    ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(&cco->err, local_err);
    }
    cco->ret = ret;
429 430
}

431
int bdrv_create(BlockDriver *drv, const char* filename,
432
    QEMUOptionParameter *options, Error **errp)
bellard's avatar
bellard committed
433
{
434 435 436 437 438 439 440 441
    int ret;

    Coroutine *co;
    CreateCo cco = {
        .drv = drv,
        .filename = g_strdup(filename),
        .options = options,
        .ret = NOT_DONE,
442
        .err = NULL,
443 444 445
    };

    if (!drv->bdrv_create) {
446
        error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
447 448
        ret = -ENOTSUP;
        goto out;
449 450 451 452 453 454 455 456 457 458 459 460 461 462
    }

    if (qemu_in_coroutine()) {
        /* Fast-path if already in coroutine context */
        bdrv_create_co_entry(&cco);
    } else {
        co = qemu_coroutine_create(bdrv_create_co_entry);
        qemu_coroutine_enter(co, &cco);
        while (cco.ret == NOT_DONE) {
            qemu_aio_wait();
        }
    }

    ret = cco.ret;
463 464 465 466 467 468 469
    if (ret < 0) {
        if (error_is_set(&cco.err)) {
            error_propagate(errp, cco.err);
        } else {
            error_setg_errno(errp, -ret, "Could not create image");
        }
    }
470

471 472
out:
    g_free(cco.filename);
473
    return ret;
bellard's avatar
bellard committed
474 475
}

476 477
int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
                     Error **errp)
478 479
{
    BlockDriver *drv;
480 481
    Error *local_err = NULL;
    int ret;
482

483
    drv = bdrv_find_protocol(filename, true);
484
    if (drv == NULL) {
485
        error_setg(errp, "Could not find protocol for file '%s'", filename);
486
        return -ENOENT;
487 488
    }

489 490 491 492 493
    ret = bdrv_create(drv, filename, options, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(errp, local_err);
    }
    return ret;
494 495
}

496
int bdrv_refresh_limits(BlockDriverState *bs)
497 498 499 500 501
{
    BlockDriver *drv = bs->drv;

    memset(&bs->bl, 0, sizeof(bs->bl));

502 503 504 505 506 507 508 509
    if (!drv) {
        return 0;
    }

    /* Take some limits from the children as a default */
    if (bs->file) {
        bdrv_refresh_limits(bs->file);
        bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
510 511 512
        bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
    } else {
        bs->bl.opt_mem_alignment = 512;
513 514 515 516 517 518 519
    }

    if (bs->backing_hd) {
        bdrv_refresh_limits(bs->backing_hd);
        bs->bl.opt_transfer_length =
            MAX(bs->bl.opt_transfer_length,
                bs->backing_hd->bl.opt_transfer_length);
520 521 522
        bs->bl.opt_mem_alignment =
            MAX(bs->bl.opt_mem_alignment,
                bs->backing_hd->bl.opt_mem_alignment);
523 524 525 526
    }

    /* Then let the driver override it */
    if (drv->bdrv_refresh_limits) {
527 528 529 530 531 532
        return drv->bdrv_refresh_limits(bs);
    }

    return 0;
}

533 534 535 536 537
/*
 * Create a uniquely-named empty temporary file.
 * Return 0 upon success, otherwise a negative errno value.
 */
int get_tmp_filename(char *filename, int size)
bellard's avatar
bellard committed
538
{
539
#ifdef _WIN32
540
    char temp_dir[MAX_PATH];
541 542 543 544 545 546
    /* GetTempFileName requires that its output buffer (4th param)
       have length MAX_PATH or greater.  */
    assert(size >= MAX_PATH);
    return (GetTempPath(MAX_PATH, temp_dir)
            && GetTempFileName(temp_dir, "qem", 0, filename)
            ? 0 : -GetLastError());
bellard's avatar
bellard committed
547
#else
548
    int fd;
549
    const char *tmpdir;
550 551 552
    tmpdir = getenv("TMPDIR");
    if (!tmpdir)
        tmpdir = "/tmp";
553 554 555
    if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
        return -EOVERFLOW;
    }
bellard's avatar
bellard committed
556
    fd = mkstemp(filename);
557 558 559 560 561
    if (fd < 0) {
        return -errno;
    }
    if (close(fd) != 0) {
        unlink(filename);
562 563 564
        return -errno;
    }
    return 0;
bellard's avatar
bellard committed
565
#endif
566
}
bellard's avatar
bellard committed
567

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
/*
 * Detect host devices. By convention, /dev/cdrom[N] is always
 * recognized as a host CDROM.
 */
static BlockDriver *find_hdev_driver(const char *filename)
{
    int score_max = 0, score;
    BlockDriver *drv = NULL, *d;

    QLIST_FOREACH(d, &bdrv_drivers, list) {
        if (d->bdrv_probe_device) {
            score = d->bdrv_probe_device(filename);
            if (score > score_max) {
                score_max = score;
                drv = d;
            }
        }
    }

    return drv;
}

590 591
BlockDriver *bdrv_find_protocol(const char *filename,
                                bool allow_protocol_prefix)
bellard's avatar
bellard committed
592 593 594
{
    BlockDriver *drv1;
    char protocol[128];
595
    int len;
bellard's avatar
bellard committed
596
    const char *p;
bellard's avatar
bellard committed
597

598 599
    /* TODO Drivers without bdrv_file_open must be specified explicitly */

600 601 602 603 604 605 606 607 608 609 610 611
    /*
     * XXX(hch): we really should not let host device detection
     * override an explicit protocol specification, but moving this
     * later breaks access to device names with colons in them.
     * Thanks to the brain-dead persistent naming schemes on udev-
     * based Linux systems those actually are quite common.
     */
    drv1 = find_hdev_driver(filename);
    if (drv1) {
        return drv1;
    }

612
    if (!path_has_protocol(filename) || !allow_protocol_prefix) {
613
        return bdrv_find_format("file");
614
    }
615

616 617
    p = strchr(filename, ':');
    assert(p != NULL);
618 619 620 621 622
    len = p - filename;
    if (len > sizeof(protocol) - 1)
        len = sizeof(protocol) - 1;
    memcpy(protocol, filename, len);
    protocol[len] = '\0';
623
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
624
        if (drv1->protocol_name &&
625
            !strcmp(drv1->protocol_name, protocol)) {
bellard's avatar
bellard committed
626
            return drv1;
627
        }
bellard's avatar
bellard committed
628 629 630 631
    }
    return NULL;
}

632
static int find_image_format(BlockDriverState *bs, const char *filename,
633
                             BlockDriver **pdrv, Error **errp)
634
{
635
    int score, score_max;
636 637
    BlockDriver *drv1, *drv;
    uint8_t buf[2048];
638
    int ret = 0;
639

640
    /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
641
    if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
642 643
        drv = bdrv_find_format("raw");
        if (!drv) {
644
            error_setg(errp, "Could not find raw image format");
645 646 647 648
            ret = -ENOENT;
        }
        *pdrv = drv;
        return ret;
649
    }
650

bellard's avatar
bellard committed
651 652
    ret = bdrv_pread(bs, 0, buf, sizeof(buf));
    if (ret < 0) {
653 654
        error_setg_errno(errp, -ret, "Could not read image for determining its "
                         "format");
655 656
        *pdrv = NULL;
        return ret;
bellard's avatar
bellard committed
657 658
    }

bellard's avatar
bellard committed
659
    score_max = 0;
660
    drv = NULL;
661
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard's avatar
bellard committed
662 663 664 665 666 667
        if (drv1->bdrv_probe) {
            score = drv1->bdrv_probe(buf, ret, filename);
            if (score > score_max) {
                score_max = score;
                drv = drv1;
            }
bellard's avatar
bellard committed
668
        }
bellard's avatar
bellard committed
669
    }
670
    if (!drv) {
671 672
        error_setg(errp, "Could not determine image format: No compatible "
                   "driver found");
673 674 675 676
        ret = -ENOENT;
    }
    *pdrv = drv;
    return ret;
bellard's avatar
bellard committed
677 678
}

679 680 681 682 683 684 685
/**
 * Set the current 'total_sectors' value
 */
static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
{
    BlockDriver *drv = bs->drv;

686 687 688 689
    /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
    if (bs->sg)
        return 0;

690 691 692 693 694 695
    /* query actual device if possible, otherwise just trust the hint */
    if (drv->bdrv_getlength) {
        int64_t length = drv->bdrv_getlength(bs);
        if (length < 0) {
            return length;
        }
696
        hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
697 698 699 700 701 702
    }

    bs->total_sectors = hint;
    return 0;
}

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
/**
 * Set open flags for a given discard mode
 *
 * Return 0 on success, -1 if the discard mode was invalid.
 */
int bdrv_parse_discard_flags(const char *mode, int *flags)
{
    *flags &= ~BDRV_O_UNMAP;

    if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
        /* do nothing */
    } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
        *flags |= BDRV_O_UNMAP;
    } else {
        return -1;
    }

    return 0;
}

723 724 725 726 727 728 729 730 731 732 733
/**
 * Set open flags for a given cache mode
 *
 * Return 0 on success, -1 if the cache mode was invalid.
 */
int bdrv_parse_cache_flags(const char *mode, int *flags)
{
    *flags &= ~BDRV_O_CACHE_MASK;

    if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
        *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
734 735
    } else if (!strcmp(mode, "directsync")) {
        *flags |= BDRV_O_NOCACHE;
736 737 738 739 740 741 742 743 744 745 746 747 748 749
    } else if (!strcmp(mode, "writeback")) {
        *flags |= BDRV_O_CACHE_WB;
    } else if (!strcmp(mode, "unsafe")) {
        *flags |= BDRV_O_CACHE_WB;
        *flags |= BDRV_O_NO_FLUSH;
    } else if (!strcmp(mode, "writethrough")) {
        /* this is the default */
    } else {
        return -1;
    }

    return 0;
}

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
/**
 * The copy-on-read flag is actually a reference count so multiple users may
 * use the feature without worrying about clobbering its previous state.
 * Copy-on-read stays enabled until all users have called to disable it.
 */
void bdrv_enable_copy_on_read(BlockDriverState *bs)
{
    bs->copy_on_read++;
}

void bdrv_disable_copy_on_read(BlockDriverState *bs)
{
    assert(bs->copy_on_read > 0);
    bs->copy_on_read--;
}

766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
static int bdrv_open_flags(BlockDriverState *bs, int flags)
{
    int open_flags = flags | BDRV_O_CACHE_WB;

    /*
     * Clear flags that are internal to the block layer before opening the
     * image.
     */
    open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);

    /*
     * Snapshots should be writable.
     */
    if (bs->is_temporary) {
        open_flags |= BDRV_O_RDWR;
    }

    return open_flags;
}

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
static int bdrv_assign_node_name(BlockDriverState *bs,
                                 const char *node_name,
                                 Error **errp)
{
    if (!node_name) {
        return 0;
    }

    /* empty string node name is invalid */
    if (node_name[0] == '\0') {
        error_setg(errp, "Empty node name");
        return -EINVAL;
    }

    /* takes care of avoiding duplicates node names */
    if (bdrv_find_node(node_name)) {
        error_setg(errp, "Duplicate node name");
        return -EINVAL;
    }

    /* copy node name into the bs and insert it into the graph list */
    pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
    QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);

    return 0;
}

813 814
/*
 * Common part for opening disk images and files
815 816
 *
 * Removes all processed options from *options.
817
 */
818
static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
819
    QDict *options, int flags, BlockDriver *drv, Error **errp)
820 821
{
    int ret, open_flags;
822
    const char *filename;
823
    const char *node_name = NULL;
824
    Error *local_err = NULL;
825 826

    assert(drv != NULL);
827
    assert(bs->file == NULL);
828
    assert(options != NULL && bs->options != options);
829

830 831 832 833 834 835 836
    if (file != NULL) {
        filename = file->filename;
    } else {
        filename = qdict_get_try_str(options, "filename");
    }

    trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
837

838 839 840 841 842 843 844
    node_name = qdict_get_try_str(options, "node-name");
    ret = bdrv_assign_node_name(bs, node_name, errp);
    if (ret < 0) {
        return ret;
    }
    qdict_del(options, "node-name");

845 846 847 848 849 850 851 852
    /* bdrv_open() with directly using a protocol as drv. This layer is already
     * opened, so assign it to bs (while file becomes a closed BlockDriverState)
     * and return immediately. */
    if (file != NULL && drv->bdrv_file_open) {
        bdrv_swap(file, bs);
        return 0;
    }

853
    bs->open_flags = flags;
854
    bs->guest_block_size = 512;
855
    bs->request_alignment = 512;
856
    bs->zero_beyond_eof = true;
857 858 859 860
    open_flags = bdrv_open_flags(bs, flags);
    bs->read_only = !(open_flags & BDRV_O_RDWR);

    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
861 862 863 864 865
        error_setg(errp,
                   !bs->read_only && bdrv_is_whitelisted(drv, true)
                        ? "Driver '%s' can only be used for read-only devices"
                        : "Driver '%s' is not whitelisted",
                   drv->format_name);
866 867
        return -ENOTSUP;
    }
868

869
    assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
870 871 872 873 874 875 876
    if (flags & BDRV_O_COPY_ON_READ) {
        if (!bs->read_only) {
            bdrv_enable_copy_on_read(bs);
        } else {
            error_setg(errp, "Can't use copy-on-read on read-only device");
            return -EINVAL;
        }
877 878
    }

879 880 881 882 883
    if (filename != NULL) {
        pstrcpy(bs->filename, sizeof(bs->filename), filename);
    } else {
        bs->filename[0] = '\0';
    }
884 885

    bs->drv = drv;
886
    bs->opaque = g_malloc0(drv->instance_size);
887

888
    bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
889

890 891
    /* Open the image, either directly or using a protocol */
    if (drv->bdrv_file_open) {
892
        assert(file == NULL);
893
        assert(!drv->bdrv_needs_filename || filename != NULL);
894
        ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
895
    } else {
896
        if (file == NULL) {
897 898
            error_setg(errp, "Can't use '%s' as a block driver for the "
                       "protocol level", drv->format_name);
899 900 901
            ret = -EINVAL;
            goto free_and_fail;
        }
902
        bs->file = file;
903
        ret = drv->bdrv_open(bs, options, open_flags, &local_err);
904 905
    }

906
    if (ret < 0) {
907 908
        if (error_is_set(&local_err)) {
            error_propagate(errp, local_err);
909 910
        } else if (bs->filename[0]) {
            error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
911 912 913
        } else {
            error_setg_errno(errp, -ret, "Could not open image");
        }
914 915 916
        goto free_and_fail;
    }

917 918
    ret = refresh_total_sectors(bs, bs->total_sectors);
    if (ret < 0) {
919
        error_setg_errno(errp, -ret, "Could not refresh total sector count");
920
        goto free_and_fail;
921
    }
922

923
    bdrv_refresh_limits(bs);
924 925
    assert(bdrv_opt_mem_align(bs) != 0);
    assert(bs->request_alignment != 0);
926

927 928
#ifndef _WIN32
    if (bs->is_temporary) {
929 930
        assert(bs->filename[0] != '\0');
        unlink(bs->filename);
931 932 933 934 935
    }
#endif
    return 0;

free_and_fail:
936
    bs->file = NULL;
937
    g_free(bs->opaque);
938 939 940 941 942
    bs->opaque = NULL;
    bs->drv = NULL;
    return ret;
}

Kevin Wolf's avatar
Kevin Wolf committed
943 944
/*
 * Opens a file using a protocol (file, host_device, nbd, ...)
945 946 947 948 949
 *
 * options is a QDict of options to pass to the block drivers, or NULL for an
 * empty set of options. The reference to the QDict belongs to the block layer
 * after the call (even on failure), so if the caller intends to reuse the
 * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
Kevin Wolf's avatar
Kevin Wolf committed
950
 */
951
int bdrv_file_open(BlockDriverState **pbs, const char *filename,
952 953
                   const char *reference, QDict *options, int flags,
                   Error **errp)
bellard's avatar
bellard committed
954
{
955
    BlockDriverState *bs = NULL;
956
    BlockDriver *drv;
957
    const char *drvname;
958
    bool allow_protocol_prefix = false;
959
    Error *local_err = NULL;
bellard's avatar
bellard committed
960 961
    int ret;

962 963 964 965 966
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    if (reference) {
        if (filename || qdict_size(options)) {
            error_setg(errp, "Cannot reference an existing block device with "
                       "additional options or a new filename");
            return -EINVAL;
        }
        QDECREF(options);

        bs = bdrv_find(reference);
        if (!bs) {
            error_setg(errp, "Cannot find block device '%s'", reference);
            return -ENODEV;
        }
        bdrv_ref(bs);
        *pbs = bs;
        return 0;
    }

bellard's avatar
bellard committed
985
    bs = bdrv_new("");
986 987 988
    bs->options = options;
    options = qdict_clone_shallow(options);

989 990 991 992 993
    /* Fetch the file name from the options QDict if necessary */
    if (!filename) {
        filename = qdict_get_try_str(options, "filename");
    } else if (filename && !qdict_haskey(options, "filename")) {
        qdict_put(options, "filename", qstring_from_str(filename));
994
        allow_protocol_prefix = true;
995
    } else {
996 997
        error_setg(errp, "Can't specify 'file' and 'filename' options at the "
                   "same time");
998 999 1000 1001
        ret = -EINVAL;
        goto fail;
    }

1002 1003 1004
    /* Find the right block driver */
    drvname = qdict_get_try_str(options, "driver");
    if (drvname) {
1005
        drv = bdrv_find_format(drvname);
1006 1007 1008
        if (!drv) {
            error_setg(errp, "Unknown driver '%s'", drvname);
        }
1009 1010
        qdict_del(options, "driver");
    } else if (filename) {
1011 1012
        drv = bdrv_find_protocol(filename, allow_protocol_prefix);
        if (!drv) {
1013
            error_setg(errp, "Unknown protocol");
1014
        }
1015
    } else {
1016
        error_setg(errp, "Must specify either driver or file");
1017 1018 1019 1020
        drv = NULL;
    }

    if (!drv) {
1021
        /* errp has been set already */
1022 1023 1024 1025 1026 1027
        ret = -ENOENT;
        goto fail;
    }

    /* Parse the filename and open it */
    if (drv->bdrv_parse_filename && filename) {
1028 1029
        drv->bdrv_parse_filename(filename, options, &local_err);
        if (error_is_set(&local_err)) {
1030
            error_propagate(errp, local_err);
1031 1032 1033
            ret = -EINVAL;
            goto fail;
        }
1034
        qdict_del(options, "filename");
1035
    } else if (drv->bdrv_needs_filename && !filename) {
1036 1037
        error_setg(errp, "The '%s' block driver requires a file name",
                   drv->format_name);
1038 1039
        ret = -EINVAL;
        goto fail;
1040 1041
    }

1042 1043 1044 1045 1046 1047
    if (!drv->bdrv_file_open) {
        ret = bdrv_open(bs, filename, options, flags, drv, &local_err);
        options = NULL;
    } else {
        ret = bdrv_open_common(bs, NULL, options, flags, drv, &local_err);
    }
bellard's avatar
bellard committed
1048
    if (ret < 0) {
1049
        error_propagate(errp, local_err);
1050 1051 1052 1053
        goto fail;
    }

    /* Check if any unknown options were used */
1054
    if (options && (qdict_size(options) != 0)) {
1055
        const QDictEntry *entry = qdict_first(options);
1056 1057
        error_setg(errp, "Block protocol '%s' doesn't support the option '%s'",
                   drv->format_name, entry->key);
1058 1059
        ret = -EINVAL;
        goto fail;
1060
    }
1061 1062
    QDECREF(options);

1063
    bs->growable = 1;
bellard's avatar
bellard committed
1064 1065
    *pbs = bs;
    return 0;
1066 1067 1068 1069 1070 1071

fail:
    QDECREF(options);
    if (!bs->drv) {
        QDECREF(bs->options);
    }
1072
    bdrv_unref(bs);
1073
    return ret;
bellard's avatar
bellard committed
1074 1075
}

1076 1077 1078 1079 1080 1081 1082 1083
/*
 * Opens the backing file for a BlockDriverState if not yet open
 *
 * options is a QDict of options to pass to the block drivers, or NULL for an
 * empty set of options. The reference to the QDict is transferred to this
 * function (even on failure), so if the caller intends to reuse the dictionary,
 * it needs to use QINCREF() before calling bdrv_file_open.
 */
1084
int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
1085 1086 1087 1088
{
    char backing_filename[PATH_MAX];
    int back_flags, ret;
    BlockDriver *back_drv = NULL;
1089
    Error *local_err = NULL;
1090 1091

    if (bs->backing_hd != NULL) {
1092
        QDECREF(options);
1093 1094 1095
        return 0;
    }

1096 1097 1098 1099 1100
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

1101
    bs->open_flags &= ~BDRV_O_NO_BACKING;
1102 1103 1104
    if (qdict_haskey(options, "file.filename")) {
        backing_filename[0] = '\0';
    } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
1105
        QDECREF(options);
1106
        return 0;
1107 1108 1109
    } else {
        bdrv_get_full_backing_filename(bs, backing_filename,
                                       sizeof(backing_filename));
1110 1111 1112 1113 1114 1115 1116 1117 1118
    }

    bs->backing_hd = bdrv_new("");

    if (bs->backing_format[0] != '\0') {
        back_drv = bdrv_find_format(bs->backing_format);
    }

    /* backing files always opened read-only */
1119 1120
    back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT |
                                    BDRV_O_COPY_ON_READ);
1121

1122 1123
    ret = bdrv_open(bs->backing_hd,
                    *backing_filename ? backing_filename : NULL, options,
1124
                    back_flags, back_drv, &local_err);
1125
    if (ret < 0) {
1126
        bdrv_unref(bs->backing_hd);
1127 1128
        bs->backing_hd = NULL;
        bs->open_flags |= BDRV_O_NO_BACKING;
1129 1130 1131
        error_setg(errp, "Could not open backing file: %s",
                   error_get_pretty(local_err));
        error_free(local_err);
1132 1133
        return ret;
    }
1134 1135 1136 1137 1138 1139

    if (bs->backing_hd->file) {
        pstrcpy(bs->backing_file, sizeof(bs->backing_file),
                bs->backing_hd->file->filename);
    }

1140 1141 1142
    /* Recalculate the BlockLimits with the backing file */
    bdrv_refresh_limits(bs);

1143 1144 1145
    return 0;
}

Max Reitz's avatar
Max Reitz committed
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
/*
 * Opens a disk image whose options are given as BlockdevRef in another block
 * device's options.
 *
 * If force_raw is true, bdrv_file_open() will be used, thereby preventing any
 * image format auto-detection. If it is false and a filename is given,
 * bdrv_open() will be used for auto-detection.
 *
 * If allow_none is true, no image will be opened if filename is false and no
 * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
 *
 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
 * itself, all options starting with "${bdref_key}." are considered part of the
 * BlockdevRef.
 *
 * The BlockdevRef will be removed from the options QDict.
 */
int bdrv_open_image(BlockDriverState **pbs, const char *filename,
                    QDict *options, const char *bdref_key, int flags,
                    bool force_raw, bool allow_none, Error **errp)
{
    QDict *image_options;
    int ret;
    char *bdref_key_dot;
    const char *reference;

    bdref_key_dot = g_strdup_printf("%s.", bdref_key);
    qdict_extract_subqdict(options, &image_options, bdref_key_dot);
    g_free(bdref_key_dot);

    reference = qdict_get_try_str(options, bdref_key);
    if (!filename && !reference && !qdict_size(image_options)) {
        if (allow_none) {
            ret = 0;
        } else {
            error_setg(errp, "A block device must be specified for \"%s\"",
                       bdref_key);
            ret = -EINVAL;
        }
        goto done;
    }

    if (filename && !force_raw) {
        /* If a filename is given and the block driver should be detected
           automatically (instead of using none), use bdrv_open() in order to do
           that auto-detection. */
        BlockDriverState *bs;

        if (reference) {
            error_setg(errp, "Cannot reference an existing block device while "
                       "giving a filename");
            ret = -EINVAL;
            goto done;
        }

        bs = bdrv_new("");
        ret = bdrv_open(bs, filename, image_options, flags, NULL, errp);
        if (ret < 0) {
            bdrv_unref(bs);
        } else {
            *pbs = bs;
        }
    } else {
        ret = bdrv_file_open(pbs, filename, reference, image_options, flags,
                             errp);
    }

done:
    qdict_del(options, bdref_key);
    return ret;
}

Kevin Wolf's avatar
Kevin Wolf committed
1219 1220
/*
 * Opens a disk image (raw, qcow2, vmdk, ...)
1221 1222 1223 1224 1225
 *
 * options is a QDict of options to pass to the block drivers, or NULL for an
 * empty set of options. The reference to the QDict belongs to the block layer
 * after the call (even on failure), so if the caller intends to reuse the
 * dictionary, it needs to use QINCREF() before calling bdrv_open.
Kevin Wolf's avatar
Kevin Wolf committed
1226
 */
1227
int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
1228
              int flags, BlockDriver *drv, Error **errp)
bellard's avatar
bellard committed
1229
{
Kevin Wolf's avatar
Kevin Wolf committed
1230
    int ret;
1231 1232
    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
    char tmp_filename[PATH_MAX + 1];
1233
    BlockDriverState *file = NULL;
1234
    const char *drvname;
1235
    Error *local_err = NULL;
bellard's avatar
bellard committed
1236

1237 1238 1239 1240 1241 1242
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

    bs->options = options;
1243
    options = qdict_clone_shallow(options);
1244 1245

    /* For snapshot=on, create a temporary qcow2 overlay */
bellard's avatar
bellard committed
1246
    if (flags & BDRV_O_SNAPSHOT) {
bellard's avatar
bellard committed
1247 1248
        BlockDriverState *bs1;
        int64_t total_size;
Kevin Wolf's avatar
Kevin Wolf committed
1249
        BlockDriver *bdrv_qcow2;
1250
        QEMUOptionParameter *create_options;
1251
        QDict *snapshot_options;
1252

bellard's avatar
bellard committed
1253 1254
        /* if snapshot, we create a temporary backing file and open it
           instead of opening 'filename' directly */
1255

1256
        /* Get the required size from the image */
bellard's avatar
bellard committed
1257
        bs1 = bdrv_new("");
1258
        QINCREF(options);
1259 1260
        ret = bdrv_open(bs1, filename, options, BDRV_O_NO_BACKING,
                        drv, &local_err);
1261
        if (ret < 0) {
1262
            bdrv_unref(bs1);
1263
            goto fail;
bellard's avatar
bellard committed
1264
        }
1265
        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
1266

1267
        bdrv_unref(bs1);
1268

1269
        /* Create the temporary image */
1270 1271
        ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
        if (ret < 0) {
1272
            error_setg_errno(errp, -ret, "Could not get temporary filename");
1273
            goto fail;
1274
        }
1275

Kevin Wolf's avatar
Kevin Wolf committed
1276
        bdrv_qcow2 = bdrv_find_format("qcow2");
1277 1278
        create_options = parse_option_parameters("", bdrv_qcow2->create_options,
                                                 NULL);
Kevin Wolf's avatar
Kevin Wolf committed
1279

1280
        set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf's avatar
Kevin Wolf committed
1281

1282
        ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
1283
        free_option_parameters(create_options);
1284
        if (ret < 0) {
1285
            error_setg_errno(errp, -ret, "Could not create temporary overlay "
1286 1287 1288 1289
                             "'%s': %s", tmp_filename,
                             error_get_pretty(local_err));
            error_free(local_err);
            local_err = NULL;
1290
            goto fail;
bellard's avatar
bellard committed
1291
        }
Kevin Wolf's avatar
Kevin Wolf committed
1292

1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
        /* Prepare a new options QDict for the temporary file, where user
         * options refer to the backing file */
        if (filename) {
            qdict_put(options, "file.filename", qstring_from_str(filename));
        }
        if (drv) {
            qdict_put(options, "driver", qstring_from_str(drv->format_name));
        }

        snapshot_options = qdict_new();
        qdict_put(snapshot_options, "backing", options);
        qdict_flatten(snapshot_options);

        bs->options = snapshot_options;
        options = qdict_clone_shallow(bs->options);

bellard's avatar
bellard committed
1309
        filename = tmp_filename;
Kevin Wolf's avatar
Kevin Wolf committed
1310
        drv = bdrv_qcow2;
bellard's avatar
bellard committed
1311 1312
        bs->is_temporary = 1;
    }
bellard's avatar
bellard committed
1313

1314 1315 1316 1317 1318
    /* Open image file without format layer */
    if (flags & BDRV_O_RDWR) {
        flags |= BDRV_O_ALLOW_RDWR;
    }

1319 1320 1321 1322 1323
    ret = bdrv_open_image(&file, filename, options, "file",
                          bdrv_open_flags(bs, flags | BDRV_O_UNMAP), true, true,
                          &local_err);
    if (ret < 0) {
        goto fail;
1324 1325
    }

Kevin Wolf's avatar
Kevin Wolf committed
1326
    /* Find the right image format driver */
1327 1328
    drvname = qdict_get_try_str(options, "driver");
    if (drvname) {
1329
        drv = bdrv_find_format(drvname);
1330
        qdict_del(options, "driver");
1331 1332 1333 1334 1335
        if (!drv) {
            error_setg(errp, "Invalid driver: '%s'", drvname);
            ret = -EINVAL;
            goto unlink_and_fail;
        }
1336 1337
    }

1338
    if (!drv) {
1339 1340 1341 1342 1343 1344 1345
        if (file) {
            ret = find_image_format(file, filename, &drv, &local_err);
        } else {
            error_setg(errp, "Must specify either driver or file");
            ret = -EINVAL;
            goto unlink_and_fail;
        }
1346
    }
1347

1348 1349
    if (!drv) {
        goto unlink_and_fail;
bellard's avatar
bellard committed
1350
    }
Kevin Wolf's avatar
Kevin Wolf committed
1351 1352