block.c 151 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 74
static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
    int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
75
    BdrvRequestFlags flags);
76 77
static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
    int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
78
    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
                                     unsigned int bytes,
196
                                     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
    /* the IO will be executed, do the accounting */
208 209
    throttle_account(&bs->throttle_state, is_write, bytes);

210

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

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

220 221 222 223 224 225 226 227 228 229
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;
}

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

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

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

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

bellard's avatar
bellard committed
261 262 263 264 265 266
/* 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)
267
{
bellard's avatar
bellard committed
268 269 270 271 272 273 274 275 276 277 278 279 280
    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;
281 282 283 284 285 286 287 288 289
        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
290 291 292 293 294 295 296 297 298 299 300 301
        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);
302 303 304
    }
}

305 306 307 308 309 310 311 312 313
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);
    }
}

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

321 322 323
        /* 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.
         */
324 325 326 327 328
        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
329
    }
330

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

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

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

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

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

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

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

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

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

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

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

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

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

423 424 425 426 427
    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;
428 429
}

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

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

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

    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;
462 463 464 465 466 467 468
    if (ret < 0) {
        if (error_is_set(&cco.err)) {
            error_propagate(errp, cco.err);
        } else {
            error_setg_errno(errp, -ret, "Could not create image");
        }
    }
469

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

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

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

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

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

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

501 502 503 504 505 506 507 508
    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;
509 510 511
        bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
    } else {
        bs->bl.opt_mem_alignment = 512;
512 513 514 515 516 517 518
    }

    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);
519 520 521
        bs->bl.opt_mem_alignment =
            MAX(bs->bl.opt_mem_alignment,
                bs->backing_hd->bl.opt_mem_alignment);
522 523 524 525
    }

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

    return 0;
}

532 533 534 535 536
/*
 * 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
537
{
538
#ifdef _WIN32
539
    char temp_dir[MAX_PATH];
540 541 542 543 544 545
    /* 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
546
#else
547
    int fd;
548
    const char *tmpdir;
549 550 551
    tmpdir = getenv("TMPDIR");
    if (!tmpdir)
        tmpdir = "/tmp";
552 553 554
    if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
        return -EOVERFLOW;
    }
bellard's avatar
bellard committed
555
    fd = mkstemp(filename);
556 557 558 559 560
    if (fd < 0) {
        return -errno;
    }
    if (close(fd) != 0) {
        unlink(filename);
561 562 563
        return -errno;
    }
    return 0;
bellard's avatar
bellard committed
564
#endif
565
}
bellard's avatar
bellard committed
566

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
/*
 * 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;
}

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

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

599 600 601 602 603 604 605 606 607 608 609 610
    /*
     * 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;
    }

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

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

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

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

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

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

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

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

689 690 691 692 693 694
    /* 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;
        }
695
        hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
696 697 698 699 700 701
    }

    bs->total_sectors = hint;
    return 0;
}

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
/**
 * 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;
}

722 723 724 725 726 727 728 729 730 731 732
/**
 * 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;
733 734
    } else if (!strcmp(mode, "directsync")) {
        *flags |= BDRV_O_NOCACHE;
735 736 737 738 739 740 741 742 743 744 745 746 747 748
    } 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;
}

749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
/**
 * 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--;
}

765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
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;
}

785 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
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;
}

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

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

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

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

837 838 839 840 841 842 843
    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");

844 845 846 847 848 849 850 851
    /* 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;
    }

852
    bs->open_flags = flags;
853
    bs->guest_block_size = 512;
854
    bs->request_alignment = 512;
855
    bs->zero_beyond_eof = true;
856 857 858 859
    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)) {
860 861 862 863 864
        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);
865 866
        return -ENOTSUP;
    }
867

868
    assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
869 870 871 872 873 874 875
    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;
        }
876 877
    }

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

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

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

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

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

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

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

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

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

Kevin Wolf's avatar
Kevin Wolf committed
942 943
/*
 * Opens a file using a protocol (file, host_device, nbd, ...)
944 945 946 947 948
 *
 * 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
949
 */
950
int bdrv_file_open(BlockDriverState **pbs, const char *filename,
951 952
                   const char *reference, QDict *options, int flags,
                   Error **errp)
bellard's avatar
bellard committed
953
{
954
    BlockDriverState *bs = NULL;
955
    BlockDriver *drv;
956
    const char *drvname;
957
    bool allow_protocol_prefix = false;
958
    Error *local_err = NULL;
bellard's avatar
bellard committed
959 960
    int ret;

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

966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
    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
984
    bs = bdrv_new("");
985 986 987
    bs->options = options;
    options = qdict_clone_shallow(options);

988 989 990 991 992
    /* 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));
993
        allow_protocol_prefix = true;
994
    } else {
995 996
        error_setg(errp, "Can't specify 'file' and 'filename' options at the "
                   "same time");
997 998 999 1000
        ret = -EINVAL;
        goto fail;
    }

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

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

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

1041 1042 1043 1044 1045 1046
    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
1047
    if (ret < 0) {
1048
        error_propagate(errp, local_err);
1049 1050 1051 1052
        goto fail;
    }

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

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

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

1075 1076 1077 1078 1079 1080 1081 1082
/*
 * 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.
 */
1083
int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
1084 1085 1086 1087
{
    char backing_filename[PATH_MAX];
    int back_flags, ret;
    BlockDriver *back_drv = NULL;
1088
    Error *local_err = NULL;
1089 1090

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

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

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

    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 */
1118 1119
    back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT |
                                    BDRV_O_COPY_ON_READ);
1120

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

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

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

1142 1143 1144
    return 0;
}

Max Reitz's avatar
Max Reitz committed
1145 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
/*
 * 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
1218 1219
/*
 * Opens a disk image (raw, qcow2, vmdk, ...)
1220 1221 1222 1223 1224
 *
 * 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
1225
 */
1226
int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
1227
              int flags, BlockDriver *drv, Error **errp)
bellard's avatar
bellard committed
1228
{
Kevin Wolf's avatar
Kevin Wolf committed
1229
    int ret;
1230 1231
    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
    char tmp_filename[PATH_MAX + 1];
1232
    BlockDriverState *file = NULL;
1233
    const char *drvname;
1234
    Error *local_err = NULL;
bellard's avatar
bellard committed
1235

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

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

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

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

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

1266
        bdrv_unref(bs1);
1267

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

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

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

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

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
        /* 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
1308
        filename = tmp_filename;
Kevin Wolf's avatar
Kevin Wolf committed
1309
        drv = bdrv_qcow2;
bellard's avatar
bellard committed
1310 1311
        bs->is_temporary = 1;
    }
bellard's avatar
bellard committed
1312

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

1318 1319 1320 1321 1322
    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;
1323 1324
    }

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

1337
    if (!drv) {
1338 1339 1340 1341 1342 1343 1344
        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;
        }
1345
    }
1346

1347 1348
    if (!drv) {
        goto unlink_and_fail;
bellard's avatar
bellard committed
1349
    }