block.c 153 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.
 */
Peter Maydell's avatar
Peter Maydell committed
24
#include "qemu/osdep.h"
25
#include "block/trace.h"
26 27
#include "block/block_int.h"
#include "block/blockjob.h"
28
#include "block/nbd.h"
29
#include "qemu/error-report.h"
30
#include "module_block.h"
31
#include "qemu/module.h"
32
#include "qapi/qmp/qerror.h"
33
#include "qapi/qmp/qbool.h"
34
#include "qapi/qmp/qjson.h"
35
#include "sysemu/block-backend.h"
36
#include "sysemu/sysemu.h"
37
#include "qemu/notify.h"
38
#include "qemu/coroutine.h"
39
#include "block/qapi.h"
40
#include "qmp-commands.h"
41
#include "qemu/timer.h"
42
#include "qapi-event.h"
43 44
#include "qemu/cutils.h"
#include "qemu/id.h"
bellard's avatar
bellard committed
45

46
#ifdef CONFIG_BSD
bellard's avatar
bellard committed
47
#include <sys/ioctl.h>
48
#include <sys/queue.h>
49
#ifndef __DragonFly__
bellard's avatar
bellard committed
50 51
#include <sys/disk.h>
#endif
52
#endif
bellard's avatar
bellard committed
53

54 55 56 57
#ifdef _WIN32
#include <windows.h>
#endif

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

60 61 62
static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
    QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);

63 64 65
static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
    QTAILQ_HEAD_INITIALIZER(all_bdrv_states);

66 67
static QLIST_HEAD(, BlockDriver) bdrv_drivers =
    QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellard's avatar
bellard committed
68

69 70 71 72 73 74
static BlockDriverState *bdrv_open_inherit(const char *filename,
                                           const char *reference,
                                           QDict *options, int flags,
                                           BlockDriverState *parent,
                                           const BdrvChildRole *child_role,
                                           Error **errp);
75

76 77 78
/* If non-zero, use only whitelisted block drivers */
static int use_bdrv_whitelist;

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
#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

99 100 101
size_t bdrv_opt_mem_align(BlockDriverState *bs)
{
    if (!bs || !bs->drv) {
102 103
        /* page size or 4k (hdd sector size) should be on the safe side */
        return MAX(4096, getpagesize());
104 105 106 107 108
    }

    return bs->bl.opt_mem_alignment;
}

109 110 111
size_t bdrv_min_mem_align(BlockDriverState *bs)
{
    if (!bs || !bs->drv) {
112 113
        /* page size or 4k (hdd sector size) should be on the safe side */
        return MAX(4096, getpagesize());
114 115 116 117 118
    }

    return bs->bl.min_mem_alignment;
}

119
/* check if the path starts with "<protocol>:" */
120
int path_has_protocol(const char *path)
121
{
122 123
    const char *p;

124 125 126 127 128
#ifdef _WIN32
    if (is_windows_drive(path) ||
        is_windows_drive_prefix(path)) {
        return 0;
    }
129 130 131
    p = path + strcspn(path, ":/\\");
#else
    p = path + strcspn(path, ":/");
132 133
#endif

134
    return *p == ':';
135 136
}

bellard's avatar
bellard committed
137
int path_is_absolute(const char *path)
138
{
139 140
#ifdef _WIN32
    /* specific case for names like: "\\.\d:" */
141
    if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
142
        return 1;
143 144
    }
    return (*path == '/' || *path == '\\');
145
#else
146
    return (*path == '/');
147
#endif
148 149
}

bellard's avatar
bellard committed
150 151 152 153 154 155
/* 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)
156
{
bellard's avatar
bellard committed
157 158 159 160 161 162 163 164
    const char *p, *p1;
    int len;

    if (dest_size <= 0)
        return;
    if (path_is_absolute(filename)) {
        pstrcpy(dest, dest_size, filename);
    } else {
165 166 167 168 169 170 171 172 173 174
        const char *protocol_stripped = NULL;

        if (path_has_protocol(base_path)) {
            protocol_stripped = strchr(base_path, ':');
            if (protocol_stripped) {
                protocol_stripped++;
            }
        }
        p = protocol_stripped ?: base_path;

175 176 177 178 179 180 181 182 183
        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
184 185 186 187 188 189 190 191 192 193 194 195
        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);
196 197 198
    }
}

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
/*
 * Helper function for bdrv_parse_filename() implementations to remove optional
 * protocol prefixes (especially "file:") from a filename and for putting the
 * stripped filename into the options QDict if there is such a prefix.
 */
void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
                                      QDict *options)
{
    if (strstart(filename, prefix, &filename)) {
        /* Stripping the explicit protocol prefix may result in a protocol
         * prefix being (wrongly) detected (if the filename contains a colon) */
        if (path_has_protocol(filename)) {
            QString *fat_filename;

            /* This means there is some colon before the first slash; therefore,
             * this cannot be an absolute path */
            assert(!path_is_absolute(filename));

            /* And we can thus fix the protocol detection issue by prefixing it
             * by "./" */
            fat_filename = qstring_from_str("./");
            qstring_append(fat_filename, filename);

            assert(!path_has_protocol(qstring_get_str(fat_filename)));

            qdict_put(options, "filename", fat_filename);
        } else {
            /* If no protocol prefix was detected, we can use the shortened
             * filename as-is */
            qdict_put_str(options, "filename", filename);
        }
    }
}


234 235 236
/* Returns whether the image file is opened as read-only. Note that this can
 * return false and writing to the image file is still not possible because the
 * image is inactivated. */
Jeff Cody's avatar
Jeff Cody committed
237 238 239 240 241
bool bdrv_is_read_only(BlockDriverState *bs)
{
    return bs->read_only;
}

242 243
int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
                           bool ignore_allow_rdw, Error **errp)
244
{
245 246 247 248 249 250 251
    /* Do not set read_only if copy_on_read is enabled */
    if (bs->copy_on_read && read_only) {
        error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
                   bdrv_get_device_or_node_name(bs));
        return -EINVAL;
    }

252
    /* Do not clear read_only if it is prohibited */
253 254 255
    if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
        !ignore_allow_rdw)
    {
256 257 258 259 260
        error_setg(errp, "Node '%s' is read only",
                   bdrv_get_device_or_node_name(bs));
        return -EPERM;
    }

261 262 263
    return 0;
}

264 265 266 267 268
/* TODO Remove (deprecated since 2.11)
 * Block drivers are not supposed to automatically change bs->read_only.
 * Instead, they should just check whether they can provide what the user
 * explicitly requested and error out if read-write is requested, but they can
 * only provide read-only access. */
269 270 271 272
int bdrv_set_read_only(BlockDriverState *bs, bool read_only, Error **errp)
{
    int ret = 0;

273
    ret = bdrv_can_set_read_only(bs, read_only, false, errp);
274 275 276 277
    if (ret < 0) {
        return ret;
    }

278
    bs->read_only = read_only;
279
    return 0;
280 281
}

282 283
void bdrv_get_full_backing_filename_from_filename(const char *backed,
                                                  const char *backing,
284 285
                                                  char *dest, size_t sz,
                                                  Error **errp)
286
{
287 288 289
    if (backing[0] == '\0' || path_has_protocol(backing) ||
        path_is_absolute(backing))
    {
290
        pstrcpy(dest, sz, backing);
291 292 293
    } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
        error_setg(errp, "Cannot use relative backing file names for '%s'",
                   backed);
294
    } else {
295
        path_combine(dest, sz, backed, backing);
296 297 298
    }
}

299 300
void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
                                    Error **errp)
301
{
302 303 304 305
    char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;

    bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
                                                 dest, sz, errp);
306 307
}

308 309
void bdrv_register(BlockDriver *bdrv)
{
310
    QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellard's avatar
bellard committed
311
}
bellard's avatar
bellard committed
312

313 314 315 316 317
BlockDriverState *bdrv_new(void)
{
    BlockDriverState *bs;
    int i;

318
    bs = g_new0(BlockDriverState, 1);
319
    QLIST_INIT(&bs->dirty_bitmaps);
320 321 322
    for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
        QLIST_INIT(&bs->op_blockers[i]);
    }
323
    notifier_with_return_list_init(&bs->before_write_notifiers);
324
    qemu_co_mutex_init(&bs->reqs_lock);
325
    qemu_mutex_init(&bs->dirty_bitmap_mutex);
326
    bs->refcnt = 1;
327
    bs->aio_context = qemu_get_aio_context();
328

329 330
    qemu_co_queue_init(&bs->flush_queue);

331 332
    QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);

bellard's avatar
bellard committed
333 334 335
    return bs;
}

336
static BlockDriver *bdrv_do_find_format(const char *format_name)
bellard's avatar
bellard committed
337 338
{
    BlockDriver *drv1;
339

340 341
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
        if (!strcmp(drv1->format_name, format_name)) {
bellard's avatar
bellard committed
342
            return drv1;
343
        }
bellard's avatar
bellard committed
344
    }
345

bellard's avatar
bellard committed
346 347 348
    return NULL;
}

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
BlockDriver *bdrv_find_format(const char *format_name)
{
    BlockDriver *drv1;
    int i;

    drv1 = bdrv_do_find_format(format_name);
    if (drv1) {
        return drv1;
    }

    /* The driver isn't registered, maybe we need to load a module */
    for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
        if (!strcmp(block_driver_modules[i].format_name, format_name)) {
            block_module_load_one(block_driver_modules[i].library_name);
            break;
        }
    }

    return bdrv_do_find_format(format_name);
}

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

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

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

399 400 401 402 403
bool bdrv_uses_whitelist(void)
{
    return use_bdrv_whitelist;
}

404 405 406
typedef struct CreateCo {
    BlockDriver *drv;
    char *filename;
407
    QemuOpts *opts;
408
    int ret;
409
    Error *err;
410 411 412 413
} CreateCo;

static void coroutine_fn bdrv_create_co_entry(void *opaque)
{
414 415 416
    Error *local_err = NULL;
    int ret;

417 418 419
    CreateCo *cco = opaque;
    assert(cco->drv);

420
    ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
421
    error_propagate(&cco->err, local_err);
422
    cco->ret = ret;
423 424
}

425
int bdrv_create(BlockDriver *drv, const char* filename,
426
                QemuOpts *opts, Error **errp)
bellard's avatar
bellard committed
427
{
428 429 430 431 432 433
    int ret;

    Coroutine *co;
    CreateCo cco = {
        .drv = drv,
        .filename = g_strdup(filename),
434
        .opts = opts,
435
        .ret = NOT_DONE,
436
        .err = NULL,
437 438
    };

439
    if (!drv->bdrv_create) {
440
        error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
441 442
        ret = -ENOTSUP;
        goto out;
443 444 445 446 447 448
    }

    if (qemu_in_coroutine()) {
        /* Fast-path if already in coroutine context */
        bdrv_create_co_entry(&cco);
    } else {
449 450
        co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
        qemu_coroutine_enter(co);
451
        while (cco.ret == NOT_DONE) {
452
            aio_poll(qemu_get_aio_context(), true);
453 454 455 456
        }
    }

    ret = cco.ret;
457
    if (ret < 0) {
458
        if (cco.err) {
459 460 461 462 463
            error_propagate(errp, cco.err);
        } else {
            error_setg_errno(errp, -ret, "Could not create image");
        }
    }
464

465 466
out:
    g_free(cco.filename);
467
    return ret;
bellard's avatar
bellard committed
468 469
}

470
int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
471 472
{
    BlockDriver *drv;
473 474
    Error *local_err = NULL;
    int ret;
475

476
    drv = bdrv_find_protocol(filename, true, errp);
477
    if (drv == NULL) {
478
        return -ENOENT;
479 480
    }

481
    ret = bdrv_create(drv, filename, opts, &local_err);
482
    error_propagate(errp, local_err);
483
    return ret;
484 485
}

486 487 488 489 490 491 492 493 494 495 496 497
/**
 * Try to get @bs's logical and physical block size.
 * On success, store them in @bsz struct and return 0.
 * On failure return -errno.
 * @bs must not be empty.
 */
int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
{
    BlockDriver *drv = bs->drv;

    if (drv && drv->bdrv_probe_blocksizes) {
        return drv->bdrv_probe_blocksizes(bs, bsz);
498 499
    } else if (drv && drv->is_filter && bs->file) {
        return bdrv_probe_blocksizes(bs->file->bs, bsz);
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    }

    return -ENOTSUP;
}

/**
 * Try to get @bs's geometry (cyls, heads, sectors).
 * On success, store them in @geo struct and return 0.
 * On failure return -errno.
 * @bs must not be empty.
 */
int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
{
    BlockDriver *drv = bs->drv;

    if (drv && drv->bdrv_probe_geometry) {
        return drv->bdrv_probe_geometry(bs, geo);
517 518
    } else if (drv && drv->is_filter && bs->file) {
        return bdrv_probe_geometry(bs->file->bs, geo);
519 520 521 522 523
    }

    return -ENOTSUP;
}

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

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
/*
 * 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;
}

582 583 584 585 586 587 588 589 590 591 592 593 594
static BlockDriver *bdrv_do_find_protocol(const char *protocol)
{
    BlockDriver *drv1;

    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
        if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
            return drv1;
        }
    }

    return NULL;
}

595
BlockDriver *bdrv_find_protocol(const char *filename,
596 597
                                bool allow_protocol_prefix,
                                Error **errp)
bellard's avatar
bellard committed
598 599 600
{
    BlockDriver *drv1;
    char protocol[128];
601
    int len;
bellard's avatar
bellard committed
602
    const char *p;
603
    int i;
bellard's avatar
bellard committed
604

605 606
    /* TODO Drivers without bdrv_file_open must be specified explicitly */

607 608 609 610 611 612 613 614 615 616 617 618
    /*
     * 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;
    }

619
    if (!path_has_protocol(filename) || !allow_protocol_prefix) {
620
        return &bdrv_file;
621
    }
622

623 624
    p = strchr(filename, ':');
    assert(p != NULL);
625 626 627 628 629
    len = p - filename;
    if (len > sizeof(protocol) - 1)
        len = sizeof(protocol) - 1;
    memcpy(protocol, filename, len);
    protocol[len] = '\0';
630 631 632 633 634 635 636 637 638 639 640

    drv1 = bdrv_do_find_protocol(protocol);
    if (drv1) {
        return drv1;
    }

    for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
        if (block_driver_modules[i].protocol_name &&
            !strcmp(block_driver_modules[i].protocol_name, protocol)) {
            block_module_load_one(block_driver_modules[i].library_name);
            break;
641
        }
bellard's avatar
bellard committed
642
    }
643

644 645 646 647 648
    drv1 = bdrv_do_find_protocol(protocol);
    if (!drv1) {
        error_setg(errp, "Unknown protocol '%s'", protocol);
    }
    return drv1;
bellard's avatar
bellard committed
649 650
}

651 652 653 654 655 656
/*
 * Guess image format by probing its contents.
 * This is not a good idea when your image is raw (CVE-2008-2004), but
 * we do it anyway for backward compatibility.
 *
 * @buf         contains the image's first @buf_size bytes.
657 658
 * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
 *              but can be smaller if the image file is smaller)
659 660 661 662 663 664
 * @filename    is its filename.
 *
 * For all block drivers, call the bdrv_probe() method to get its
 * probing score.
 * Return the first block driver with the highest probing score.
 */
665 666
BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
                            const char *filename)
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
{
    int score_max = 0, score;
    BlockDriver *drv = NULL, *d;

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

    return drv;
}

684
static int find_image_format(BlockBackend *file, const char *filename,
685
                             BlockDriver **pdrv, Error **errp)
686
{
687
    BlockDriver *drv;
688
    uint8_t buf[BLOCK_PROBE_BUF_SIZE];
689
    int ret = 0;
690

691
    /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
692
    if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
693
        *pdrv = &bdrv_raw;
694
        return ret;
695
    }
696

697
    ret = blk_pread(file, 0, buf, sizeof(buf));
bellard's avatar
bellard committed
698
    if (ret < 0) {
699 700
        error_setg_errno(errp, -ret, "Could not read image for determining its "
                         "format");
701 702
        *pdrv = NULL;
        return ret;
bellard's avatar
bellard committed
703 704
    }

705
    drv = bdrv_probe_all(buf, ret, filename);
706
    if (!drv) {
707 708
        error_setg(errp, "Could not determine image format: No compatible "
                   "driver found");
709 710 711 712
        ret = -ENOENT;
    }
    *pdrv = drv;
    return ret;
bellard's avatar
bellard committed
713 714
}

715 716
/**
 * Set the current 'total_sectors' value
717
 * Return 0 on success, -errno on error.
718 719 720 721 722
 */
static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
{
    BlockDriver *drv = bs->drv;

723 724 725 726
    if (!drv) {
        return -ENOMEDIUM;
    }

727
    /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
728
    if (bdrv_is_sg(bs))
729 730
        return 0;

731 732 733 734 735 736
    /* 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;
        }
737
        hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
738 739 740 741 742 743
    }

    bs->total_sectors = hint;
    return 0;
}

744 745 746 747 748 749 750 751 752 753 754 755 756 757
/**
 * Combines a QDict of new block driver @options with any missing options taken
 * from @old_options, so that leaving out an option defaults to its old value.
 */
static void bdrv_join_options(BlockDriverState *bs, QDict *options,
                              QDict *old_options)
{
    if (bs->drv && bs->drv->bdrv_join_options) {
        bs->drv->bdrv_join_options(options, old_options);
    } else {
        qdict_join(options, old_options, false);
    }
}

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
/**
 * 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;
}

778 779 780 781 782
/**
 * Set open flags for a given cache mode
 *
 * Return 0 on success, -1 if the cache mode was invalid.
 */
783
int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
784 785 786 787
{
    *flags &= ~BDRV_O_CACHE_MASK;

    if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
788 789
        *writethrough = false;
        *flags |= BDRV_O_NOCACHE;
790
    } else if (!strcmp(mode, "directsync")) {
791
        *writethrough = true;
792
        *flags |= BDRV_O_NOCACHE;
793
    } else if (!strcmp(mode, "writeback")) {
794
        *writethrough = false;
795
    } else if (!strcmp(mode, "unsafe")) {
796
        *writethrough = false;
797 798
        *flags |= BDRV_O_NO_FLUSH;
    } else if (!strcmp(mode, "writethrough")) {
799
        *writethrough = true;
800 801 802 803 804 805 806
    } else {
        return -1;
    }

    return 0;
}

807 808 809 810 811 812
static char *bdrv_child_get_parent_desc(BdrvChild *c)
{
    BlockDriverState *parent = c->opaque;
    return g_strdup(bdrv_get_device_or_node_name(parent));
}

813 814 815 816 817 818 819 820 821 822 823 824
static void bdrv_child_cb_drained_begin(BdrvChild *child)
{
    BlockDriverState *bs = child->opaque;
    bdrv_drained_begin(bs);
}

static void bdrv_child_cb_drained_end(BdrvChild *child)
{
    BlockDriverState *bs = child->opaque;
    bdrv_drained_end(bs);
}

825 826 827 828 829 830 831 832 833 834 835 836
static void bdrv_child_cb_attach(BdrvChild *child)
{
    BlockDriverState *bs = child->opaque;
    bdrv_apply_subtree_drain(child, bs);
}

static void bdrv_child_cb_detach(BdrvChild *child)
{
    BlockDriverState *bs = child->opaque;
    bdrv_unapply_subtree_drain(child, bs);
}

837 838 839 840 841 842 843
static int bdrv_child_cb_inactivate(BdrvChild *child)
{
    BlockDriverState *bs = child->opaque;
    assert(bs->open_flags & BDRV_O_INACTIVE);
    return 0;
}

844
/*
845 846 847
 * Returns the options and flags that a temporary snapshot should get, based on
 * the originally requested flags (the originally requested image will have
 * flags like a backing file)
848
 */
849 850
static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
                                       int parent_flags, QDict *parent_options)
851
{
852 853 854 855 856
    *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;

    /* For temporary files, unconditional cache=unsafe is fine */
    qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
    qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
857

858 859 860
    /* Copy the read-only option from the parent */
    qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);

861 862 863
    /* aio=native doesn't work for cache.direct=off, so disable it for the
     * temporary snapshot */
    *child_flags &= ~BDRV_O_NATIVE_AIO;
864 865
}

866
/*
867 868
 * Returns the options and flags that bs->file should get if a protocol driver
 * is expected, based on the given options and flags for the parent BDS
869
 */
870 871
static void bdrv_inherited_options(int *child_flags, QDict *child_options,
                                   int parent_flags, QDict *parent_options)
872
{
873 874
    int flags = parent_flags;

875 876 877
    /* Enable protocol handling, disable format probing for bs->file */
    flags |= BDRV_O_PROTOCOL;

878 879 880 881
    /* If the cache mode isn't explicitly set, inherit direct and no-flush from
     * the parent. */
    qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
    qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
882
    qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
883

884 885 886
    /* Inherit the read-only option from the parent if it's not set */
    qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);

887
    /* Our block drivers take care to send flushes and respect unmap policy,
888 889
     * so we can default to enable both on lower layers regardless of the
     * corresponding parent options. */
890
    qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
891 892

    /* Clear flags that only apply to the top layer */
893 894
    flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
               BDRV_O_NO_IO);
895

896
    *child_flags = flags;
897 898
}

899
const BdrvChildRole child_file = {
900
    .get_parent_desc = bdrv_child_get_parent_desc,
901
    .inherit_options = bdrv_inherited_options,
902 903
    .drained_begin   = bdrv_child_cb_drained_begin,
    .drained_end     = bdrv_child_cb_drained_end,
904 905
    .attach          = bdrv_child_cb_attach,
    .detach          = bdrv_child_cb_detach,
906
    .inactivate      = bdrv_child_cb_inactivate,
907 908 909
};

/*
910 911 912
 * Returns the options and flags that bs->file should get if the use of formats
 * (and not only protocols) is permitted for it, based on the given options and
 * flags for the parent BDS
913
 */
914 915
static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
                                       int parent_flags, QDict *parent_options)
916
{
917 918 919
    child_file.inherit_options(child_flags, child_options,
                               parent_flags, parent_options);

920
    *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
921 922 923
}

const BdrvChildRole child_format = {
924
    .get_parent_desc = bdrv_child_get_parent_desc,
925
    .inherit_options = bdrv_inherited_fmt_options,
926 927
    .drained_begin   = bdrv_child_cb_drained_begin,
    .drained_end     = bdrv_child_cb_drained_end,
928 929
    .attach          = bdrv_child_cb_attach,
    .detach          = bdrv_child_cb_detach,
930
    .inactivate      = bdrv_child_cb_inactivate,
931 932
};

933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
static void bdrv_backing_attach(BdrvChild *c)
{
    BlockDriverState *parent = c->opaque;
    BlockDriverState *backing_hd = c->bs;

    assert(!parent->backing_blocker);
    error_setg(&parent->backing_blocker,
               "node is used as backing hd of '%s'",
               bdrv_get_device_or_node_name(parent));

    parent->open_flags &= ~BDRV_O_NO_BACKING;
    pstrcpy(parent->backing_file, sizeof(parent->backing_file),
            backing_hd->filename);
    pstrcpy(parent->backing_format, sizeof(parent->backing_format),
            backing_hd->drv ? backing_hd->drv->format_name : "");

    bdrv_op_block_all(backing_hd, parent->backing_blocker);
    /* Otherwise we won't be able to commit or stream */
    bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
                    parent->backing_blocker);
    bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
                    parent->backing_blocker);
    /*
     * We do backup in 3 ways:
     * 1. drive backup
     *    The target bs is new opened, and the source is top BDS
     * 2. blockdev backup
     *    Both the source and the target are top BDSes.
     * 3. internal backup(used for block replication)
     *    Both the source and the target are backing file
     *
     * In case 1 and 2, neither the source nor the target is the backing file.
     * In case 3, we will block the top BDS, so there is only one block job
     * for the top BDS and its backing chain.
     */
    bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
                    parent->backing_blocker);
    bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
                    parent->backing_blocker);
972 973

    bdrv_child_cb_attach(c);
974 975 976 977 978 979 980 981 982 983
}

static void bdrv_backing_detach(BdrvChild *c)
{
    BlockDriverState *parent = c->opaque;

    assert(parent->backing_blocker);
    bdrv_op_unblock_all(c->bs, parent->backing_blocker);
    error_free(parent->backing_blocker);
    parent->backing_blocker = NULL;
984 985

    bdrv_child_cb_detach(c);
986 987
}

988
/*
989 990
 * Returns the options and flags that bs->backing should get, based on the
 * given options and flags for the parent BDS
991
 */
992 993
static void bdrv_backing_options(int *child_flags, QDict *child_options,
                                 int parent_flags, QDict *parent_options)
994
{
995 996
    int flags = parent_flags;

997 998
    /* The cache mode is inherited unmodified for backing files; except WCE,
     * which is only applied on the top level (BlockBackend) */
999 1000
    qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
    qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1001
    qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1002

1003
    /* backing files always opened read-only */
1004 1005
    qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
    flags &= ~BDRV_O_COPY_ON_READ;
1006 1007

    /* snapshot=on is handled on the top layer */
1008
    flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
1009

1010
    *child_flags = flags;
1011 1012
}

1013 1014 1015 1016
static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
                                        const char *filename, Error **errp)
{
    BlockDriverState *parent = c->opaque;
1017
    int orig_flags = bdrv_get_flags(parent);
1018 1019
    int ret;

1020 1021 1022 1023 1024 1025 1026
    if (!(orig_flags & BDRV_O_RDWR)) {
        ret = bdrv_reopen(parent, orig_flags | BDRV_O_RDWR, errp);
        if (ret < 0) {
            return ret;
        }
    }

1027 1028 1029
    ret = bdrv_change_backing_file(parent, filename,
                                   base->drv ? base->drv->format_name : "");
    if (ret < 0) {
1030
        error_setg_errno(errp, -ret, "Could not update backing file link");
1031 1032
    }

1033 1034 1035 1036
    if (!(orig_flags & BDRV_O_RDWR)) {
        bdrv_reopen(parent, orig_flags, NULL);
    }

1037 1038 1039
    return ret;
}

1040
const BdrvChildRole child_backing = {
1041
    .get_parent_desc = bdrv_child_get_parent_desc,
1042 1043
    .attach          = bdrv_backing_attach,
    .detach          = bdrv_backing_detach,
1044
    .inherit_options = bdrv_backing_options,
1045 1046
    .drained_begin   = bdrv_child_cb_drained_begin,
    .drained_end     = bdrv_child_cb_drained_end,
1047
    .inactivate      = bdrv_child_cb_inactivate,
1048
    .update_filename = bdrv_backing_update_filename,
1049 1050
};

1051 1052
static int bdrv_open_flags(BlockDriverState *bs, int flags)
{
1053
    int open_flags = flags;
1054 1055 1056 1057 1058

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

    /*
     * Snapshots should be writable.
     */
1064
    if (flags & BDRV_O_TEMPORARY) {
1065 1066 1067 1068 1069 1070
        open_flags |= BDRV_O_RDWR;
    }

    return open_flags;
}

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
static void update_flags_from_options(int *flags, QemuOpts *opts)
{
    *flags &= ~BDRV_O_CACHE_MASK;

    assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
    if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
        *flags |= BDRV_O_NO_FLUSH;
    }

    assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
    if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
        *flags |= BDRV_O_NOCACHE;
    }
1084 1085 1086 1087 1088 1089 1090 1091

    *flags &= ~BDRV_O_RDWR;

    assert(qemu_opt_find(opts, BDRV_OPT_READ_ONLY));
    if (!qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false)) {
        *flags |= BDRV_O_RDWR;
    }

1092 1093 1094 1095 1096
}

static void update_options_from_flags(QDict *options, int flags)
{
    if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1097
        qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1098 1099
    }
    if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1100 1101
        qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
                       flags & BDRV_O_NO_FLUSH);
1102
    }
1103
    if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1104
        qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1105
    }
1106 1107
}

1108 1109 1110
static void bdrv_assign_node_name(BlockDriverState *bs,
                                  const char *node_name,
                                  Error **errp)
1111
{
1112
    char *gen_node_name = NULL;
1113

1114 1115 1116 1117 1118 1119 1120
    if (!node_name) {
        node_name = gen_node_name = id_generate(ID_BLOCK);
    } else if (!id_wellformed(node_name)) {
        /*
         * Check for empty string or invalid characters, but not if it is
         * generated (generated names use characters not available to the user)
         */
Kevin Wolf's avatar
Kevin Wolf committed
1121
        error_setg(errp, "Invalid node name");
1122
        return;
1123 1124
    }

1125
    /* takes care of avoiding namespaces collisions */
1126
    if (blk_by_name(node_name)) {
1127 1128
        error_setg(errp, "node-name=%s is conflicting with a device id",
                   node_name);
1129
        goto out;
1130 1131
    }

1132 1133 1134
    /* takes care of avoiding duplicates node names */
    if (bdrv_find_node(node_name)) {
        error_setg(errp, "Duplicate node name");
1135
        goto out;
1136 1137 1138 1139 1140
    }

    /* 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);
1141 1142
out:
    g_free(gen_node_name);
1143 1144
}

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
                            const char *node_name, QDict *options,
                            int open_flags, Error **errp)
{
    Error *local_err = NULL;
    int ret;

    bdrv_assign_node_name(bs, node_name, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return -EINVAL;
    }

    bs->drv = drv;
1159
    bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1160 1161 1162 1163 1164
    bs->opaque = g_malloc0(drv->instance_size);

    if (drv->bdrv_file_open) {
        assert(!drv->bdrv_needs_filename || bs->filename[0]);
        ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1165
    } else if (drv->bdrv_open) {
1166
        ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1167 1168
    } else {
        ret = 0;
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    }

    if (ret < 0) {
        if (local_err) {
            error_propagate(errp, local_err);
        } else if (bs->filename[0]) {
            error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
        } else {
            error_setg_errno(errp, -ret, "Could not open image");
        }
1179
        goto open_failed;
1180 1181 1182 1183 1184
    }

    ret = refresh_total_sectors(bs, bs->total_sectors);
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not refresh total sector count");
1185
        return ret;
1186 1187 1188 1189 1190
    }

    bdrv_refresh_limits(bs, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
1191
        return -EINVAL;
1192 1193 1194 1195 1196 1197 1198
    }

    assert(bdrv_opt_mem_align(bs) != 0);
    assert(bdrv_min_mem_align(bs) != 0);
    assert(is_power_of_2(bs->bl.request_alignment));

    return 0;
1199 1200 1201 1202 1203 1204
open_failed:
    bs->drv = NULL;
    if (bs->file != NULL) {
        bdrv_unref_child(bs, bs->file);
        bs->file = NULL;
    }
1205 1206 1207 1208 1209
    g_free(bs->opaque);
    bs->opaque = NULL;
    return ret;
}

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
                                       int flags, Error **errp)
{
    BlockDriverState *bs;
    int ret;

    bs = bdrv_new();
    bs->open_flags = flags;
    bs->explicit_options = qdict_new();
    bs->options = qdict_new();
    bs->opaque = NULL;

    update_options_from_flags(bs->options, flags);

    ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
    if (ret < 0) {
        QDECREF(bs->explicit_options);
1227
        bs->explicit_options = NULL;
1228
        QDECREF(bs->options);
1229
        bs->options = NULL;
1230 1231 1232 1233 1234 1235 1236
        bdrv_unref(bs);
        return NULL;
    }

    return bs;
}

1237
QemuOptsList bdrv_runtime_opts = {
1238 1239 1240 1241 1242 1243 1244 1245
    .name = "bdrv_common",
    .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
    .desc = {
        {
            .name = "node-name",
            .type = QEMU_OPT_STRING,
            .help = "Node name of the block device node",
        },
1246 1247 1248 1249 1250
        {
            .name = "driver",
            .type = QEMU_OPT_STRING,
            .help = "Block driver to use for the node",
        },
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
        {
            .name = BDRV_OPT_CACHE_DIRECT,
            .type = QEMU_OPT_BOOL,
            .help = "Bypass software writeback cache on the host",
        },
        {
            .name = BDRV_OPT_CACHE_NO_FLUSH,
            .type = QEMU_OPT_BOOL,
            .help = "Ignore flush requests",
        },
1261 1262 1263 1264 1265
        {
            .name = BDRV_OPT_READ_ONLY,
            .type = QEMU_OPT_BOOL,
            .help = "Node is opened in read-only mode",
        },
1266 1267 1268 1269 1270
        {
            .name = "detect-zeroes",
            .type = QEMU_OPT_STRING,
            .help = "try to optimize zero writes (off, on, unmap)",
        },
1271 1272 1273 1274 1275
        {
            .name = "discard",
            .type = QEMU_OPT_STRING,
            .help = "discard operation (ignore/off, unmap/on)",
        },
1276 1277 1278 1279 1280
        {
            .name = BDRV_OPT_FORCE_SHARE,
            .type = QEMU_OPT_BOOL,
            .help = "always accept other writers (default: off)",
        },
1281 1282 1283 1284
        { /* end of list */ }
    },
};

1285 1286
/*
 * Common part for opening disk images and files
1287 1288
 *
 * Removes all processed options from *options.
1289
 */
1290
static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf's avatar
Kevin Wolf committed
1291
                            QDict *options, Error **errp)
1292 1293
{
    int ret, open_flags;
1294
    const char *filename;
1295
    const char *driver_name = NULL;
1296
    const char *node_name = NULL;
1297
    const char *discard;
1298
    const char *detect_zeroes;
1299
    QemuOpts *opts;
1300
    BlockDriver *drv;
1301
    Error *local_err = NULL;
1302

1303
    assert(bs->file == NULL);
1304
    assert(options != NULL && bs->options != options);
1305

1306 1307 1308 1309 1310 1311 1312 1313
    opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
    qemu_opts_absorb_qdict(opts, options, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        ret = -EINVAL;
        goto fail_opts;
    }

1314 1315
    update_flags_from_options(&bs->open_flags, opts);

1316 1317 1318 1319
    driver_name = qemu_opt_get(opts, "driver");
    drv = bdrv_find_format(driver_name);
    assert(drv != NULL);

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
    bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);

    if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
        error_setg(errp,
                   BDRV_OPT_FORCE_SHARE
                   "=on can only be used with read-only images");
        ret = -EINVAL;
        goto fail_opts;
    }

1330
    if (file != NULL) {
1331
        filename = blk_bs(file)->filename;
1332
    } else {
1333 1334 1335 1336 1337 1338 1339
        /*
         * Caution: while qdict_get_try_str() is fine, getting
         * non-string types would require more care.  When @options
         * come from -blockdev or blockdev_add, its members are typed
         * according to the QAPI schema, but when they come from
         * -drive, they're all QString.
         */
1340 1341 1342
        filename = qdict_get_try_str(options, "filename");
    }

1343
    if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1344 1345
        error_setg(errp, "The '%s' block driver requires a file name",
                   drv->format_name);
1346 1347
        ret = -EINVAL;
        goto fail_opts;
1348 1349
    }

Kevin Wolf's avatar
Kevin Wolf committed
1350 1351
    trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
                           drv->format_name);
1352

Kevin Wolf's avatar
Kevin Wolf committed
1353
    bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1354 1355

    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1356 1357 1358 1359 1360
        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);
1361 1362
        ret = -ENOTSUP;
        goto fail_opts;
1363
    }
1364

1365 1366 1367
    /* bdrv_new() and bdrv_close() make it so */
    assert(atomic_read(&bs->copy_on_read) == 0);

Kevin Wolf's avatar
Kevin Wolf committed
1368
    if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1369 1370 1371 1372
        if (!bs->read_only) {
            bdrv_enable_copy_on_read(bs);
        } else {
            error_setg(errp, "Can't use copy-on-read on read-only device");
1373 1374
            ret = -EINVAL;
            goto fail_opts;
1375
        }
1376 1377
    }

1378 1379 1380 1381 1382 1383 1384 1385 1386
    discard = qemu_opt_get(opts, "discard");
    if (discard != NULL) {
        if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
            error_setg(errp, "Invalid discard option");
            ret = -EINVAL;
            goto fail_opts;
        }
    }

1387 1388 1389
    detect_zeroes = qemu_opt_get(opts, "detect-zeroes");
    if (detect_zeroes) {
        BlockdevDetectZeroesOptions value =
1390
            qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
                            detect_zeroes,
                            BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
                            &local_err);
        if (local_err) {
            error_propagate(errp, local_err);
            ret = -EINVAL;
            goto fail_opts;
        }

        if (value == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
            !(bs->open_flags & BDRV_O_UNMAP))
        {
            error_setg(errp, "setting detect-zeroes to unmap is not allowed "
                             "without setting discard operation to unmap");
            ret = -EINVAL;
            goto fail_opts;
        }

        bs->detect_zeroes = value;
    }

Kevin Wolf's avatar