block.c 133 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"
Luiz Capitulino's avatar
Luiz Capitulino committed
35
#include "qmp-commands.h"
36
#include "qemu/timer.h"
bellard's avatar
bellard committed
37

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

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

52
53
#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */

54
55
typedef enum {
    BDRV_REQ_COPY_ON_READ = 0x1,
56
    BDRV_REQ_ZERO_WRITE   = 0x2,
57
58
} BdrvRequestFlags;

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

89
90
91
92
93
94
95
static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
        bool is_write, double elapsed_time, uint64_t *wait);
static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
        double elapsed_time, uint64_t *wait);
static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
        bool is_write, int64_t *wait);

96
97
static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
    QTAILQ_HEAD_INITIALIZER(bdrv_states);
98

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

102
103
104
/* The device to use for VM snapshots */
static BlockDriverState *bs_snapshots;

105
106
107
/* If non-zero, use only whitelisted block drivers */
static int use_bdrv_whitelist;

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#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

128
/* throttling disk I/O limits */
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
void bdrv_io_limits_disable(BlockDriverState *bs)
{
    bs->io_limits_enabled = false;

    while (qemu_co_queue_next(&bs->throttled_reqs));

    if (bs->block_timer) {
        qemu_del_timer(bs->block_timer);
        qemu_free_timer(bs->block_timer);
        bs->block_timer = NULL;
    }

    bs->slice_start = 0;
    bs->slice_end   = 0;
}

145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
static void bdrv_block_timer(void *opaque)
{
    BlockDriverState *bs = opaque;

    qemu_co_queue_next(&bs->throttled_reqs);
}

void bdrv_io_limits_enable(BlockDriverState *bs)
{
    qemu_co_queue_init(&bs->throttled_reqs);
    bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);
    bs->io_limits_enabled = true;
}

bool bdrv_io_limits_enabled(BlockDriverState *bs)
{
    BlockIOLimit *io_limits = &bs->io_limits;
    return io_limits->bps[BLOCK_IO_LIMIT_READ]
         || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
         || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
         || io_limits->iops[BLOCK_IO_LIMIT_READ]
         || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
         || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
}

170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
static void bdrv_io_limits_intercept(BlockDriverState *bs,
                                     bool is_write, int nb_sectors)
{
    int64_t wait_time = -1;

    if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
        qemu_co_queue_wait(&bs->throttled_reqs);
    }

    /* In fact, we hope to keep each request's timing, in FIFO mode. The next
     * throttled requests will not be dequeued until the current request is
     * allowed to be serviced. So if the current request still exceeds the
     * limits, it will be inserted to the head. All requests followed it will
     * be still in throttled_reqs queue.
     */

    while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
        qemu_mod_timer(bs->block_timer,
                       wait_time + qemu_get_clock_ns(vm_clock));
        qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
    }

    qemu_co_queue_next(&bs->throttled_reqs);
}

195
196
197
/* check if the path starts with "<protocol>:" */
static int path_has_protocol(const char *path)
{
198
199
    const char *p;

200
201
202
203
204
#ifdef _WIN32
    if (is_windows_drive(path) ||
        is_windows_drive_prefix(path)) {
        return 0;
    }
205
206
207
    p = path + strcspn(path, ":/\\");
#else
    p = path + strcspn(path, ":/");
208
209
#endif

210
    return *p == ':';
211
212
}

bellard's avatar
bellard committed
213
int path_is_absolute(const char *path)
214
{
bellard's avatar
bellard committed
215
216
#ifdef _WIN32
    /* specific case for names like: "\\.\d:" */
217
    if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard's avatar
bellard committed
218
        return 1;
219
220
    }
    return (*path == '/' || *path == '\\');
221
#else
222
    return (*path == '/');
223
#endif
224
225
}

bellard's avatar
bellard committed
226
227
228
229
230
231
/* 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)
232
{
bellard's avatar
bellard committed
233
234
235
236
237
238
239
240
241
242
243
244
245
    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;
246
247
248
249
250
251
252
253
254
        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
255
256
257
258
259
260
261
262
263
264
265
266
        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);
267
268
269
    }
}

270
271
272
273
274
275
276
277
278
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);
    }
}

279
void bdrv_register(BlockDriver *bdrv)
bellard's avatar
bellard committed
280
{
281
282
    /* Block drivers without coroutine functions need emulation */
    if (!bdrv->bdrv_co_readv) {
283
284
285
        bdrv->bdrv_co_readv = bdrv_co_readv_em;
        bdrv->bdrv_co_writev = bdrv_co_writev_em;

286
287
288
        /* 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.
         */
289
290
291
292
293
        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
294
    }
295

296
    QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellard's avatar
bellard committed
297
}
bellard's avatar
bellard committed
298
299
300
301

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

304
    bs = g_malloc0(sizeof(BlockDriverState));
bellard's avatar
bellard committed
305
    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
bellard's avatar
bellard committed
306
    if (device_name[0] != '\0') {
307
        QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
bellard's avatar
bellard committed
308
    }
309
    bdrv_iostatus_disable(bs);
Paolo Bonzini's avatar
Paolo Bonzini committed
310
311
    notifier_list_init(&bs->close_notifiers);

bellard's avatar
bellard committed
312
313
314
    return bs;
}

Paolo Bonzini's avatar
Paolo Bonzini committed
315
316
317
318
319
void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
{
    notifier_list_add(&bs->close_notifiers, notify);
}

bellard's avatar
bellard committed
320
321
322
BlockDriver *bdrv_find_format(const char *format_name)
{
    BlockDriver *drv1;
323
324
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
        if (!strcmp(drv1->format_name, format_name)) {
bellard's avatar
bellard committed
325
            return drv1;
326
        }
bellard's avatar
bellard committed
327
328
329
330
    }
    return NULL;
}

331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
static int bdrv_is_whitelisted(BlockDriver *drv)
{
    static const char *whitelist[] = {
        CONFIG_BDRV_WHITELIST
    };
    const char **p;

    if (!whitelist[0])
        return 1;               /* no whitelist, anything goes */

    for (p = whitelist; *p; p++) {
        if (!strcmp(drv->format_name, *p)) {
            return 1;
        }
    }
    return 0;
}

BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
{
    BlockDriver *drv = bdrv_find_format(format_name);
    return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
}

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
typedef struct CreateCo {
    BlockDriver *drv;
    char *filename;
    QEMUOptionParameter *options;
    int ret;
} CreateCo;

static void coroutine_fn bdrv_create_co_entry(void *opaque)
{
    CreateCo *cco = opaque;
    assert(cco->drv);

    cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
}

370
371
int bdrv_create(BlockDriver *drv, const char* filename,
    QEMUOptionParameter *options)
bellard's avatar
bellard committed
372
{
373
374
375
376
377
378
379
380
381
382
383
    int ret;

    Coroutine *co;
    CreateCo cco = {
        .drv = drv,
        .filename = g_strdup(filename),
        .options = options,
        .ret = NOT_DONE,
    };

    if (!drv->bdrv_create) {
384
385
        ret = -ENOTSUP;
        goto out;
386
387
388
389
390
391
392
393
394
395
396
397
398
399
    }

    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;
400

401
402
out:
    g_free(cco.filename);
403
    return ret;
bellard's avatar
bellard committed
404
405
}

406
407
408
409
int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
{
    BlockDriver *drv;

410
    drv = bdrv_find_protocol(filename);
411
    if (drv == NULL) {
412
        return -ENOENT;
413
414
415
416
417
    }

    return bdrv_create(drv, filename, options);
}

418
419
420
421
422
/*
 * 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
423
{
424
#ifdef _WIN32
425
    char temp_dir[MAX_PATH];
426
427
428
429
430
431
    /* 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
432
#else
bellard's avatar
bellard committed
433
    int fd;
434
    const char *tmpdir;
aurel32's avatar
aurel32 committed
435
436
437
    tmpdir = getenv("TMPDIR");
    if (!tmpdir)
        tmpdir = "/tmp";
438
439
440
    if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
        return -EOVERFLOW;
    }
bellard's avatar
bellard committed
441
    fd = mkstemp(filename);
442
443
444
445
446
    if (fd < 0) {
        return -errno;
    }
    if (close(fd) != 0) {
        unlink(filename);
447
448
449
        return -errno;
    }
    return 0;
bellard's avatar
bellard committed
450
#endif
451
}
bellard's avatar
bellard committed
452

453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/*
 * 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;
}

475
BlockDriver *bdrv_find_protocol(const char *filename)
bellard's avatar
bellard committed
476
477
478
{
    BlockDriver *drv1;
    char protocol[128];
479
    int len;
bellard's avatar
bellard committed
480
    const char *p;
bellard's avatar
bellard committed
481

482
483
    /* TODO Drivers without bdrv_file_open must be specified explicitly */

484
485
486
487
488
489
490
491
492
493
494
495
    /*
     * 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;
    }

496
    if (!path_has_protocol(filename)) {
497
        return bdrv_find_format("file");
498
    }
499
500
    p = strchr(filename, ':');
    assert(p != NULL);
501
502
503
504
505
    len = p - filename;
    if (len > sizeof(protocol) - 1)
        len = sizeof(protocol) - 1;
    memcpy(protocol, filename, len);
    protocol[len] = '\0';
506
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
507
        if (drv1->protocol_name &&
508
            !strcmp(drv1->protocol_name, protocol)) {
bellard's avatar
bellard committed
509
            return drv1;
510
        }
bellard's avatar
bellard committed
511
512
513
514
    }
    return NULL;
}

515
516
static int find_image_format(BlockDriverState *bs, const char *filename,
                             BlockDriver **pdrv)
517
{
518
    int score, score_max;
519
520
    BlockDriver *drv1, *drv;
    uint8_t buf[2048];
521
    int ret = 0;
522

523
    /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
524
    if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
525
526
527
528
529
530
        drv = bdrv_find_format("raw");
        if (!drv) {
            ret = -ENOENT;
        }
        *pdrv = drv;
        return ret;
531
    }
532

bellard's avatar
bellard committed
533
534
    ret = bdrv_pread(bs, 0, buf, sizeof(buf));
    if (ret < 0) {
535
536
        *pdrv = NULL;
        return ret;
bellard's avatar
bellard committed
537
538
    }

bellard's avatar
bellard committed
539
    score_max = 0;
540
    drv = NULL;
541
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard's avatar
bellard committed
542
543
544
545
546
547
        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
548
        }
bellard's avatar
bellard committed
549
    }
550
551
552
553
554
    if (!drv) {
        ret = -ENOENT;
    }
    *pdrv = drv;
    return ret;
bellard's avatar
bellard committed
555
556
}

557
558
559
560
561
562
563
/**
 * Set the current 'total_sectors' value
 */
static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
{
    BlockDriver *drv = bs->drv;

564
565
566
567
    /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
    if (bs->sg)
        return 0;

568
569
570
571
572
573
574
575
576
577
578
579
580
    /* 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;
        }
        hint = length >> BDRV_SECTOR_BITS;
    }

    bs->total_sectors = hint;
    return 0;
}

Paolo Bonzini's avatar
Paolo Bonzini committed
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
/**
 * 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;
}

601
602
603
604
605
606
607
608
609
610
611
/**
 * 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;
612
613
    } else if (!strcmp(mode, "directsync")) {
        *flags |= BDRV_O_NOCACHE;
614
615
616
617
618
619
620
621
622
623
624
625
626
627
    } 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;
}

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/**
 * 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--;
}

Kevin Wolf's avatar
Kevin Wolf committed
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
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;
}

664
665
/*
 * Common part for opening disk images and files
666
667
 *
 * Removes all processed options from *options.
668
 */
669
static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
670
    const char *filename, QDict *options,
671
672
673
674
675
    int flags, BlockDriver *drv)
{
    int ret, open_flags;

    assert(drv != NULL);
676
    assert(bs->file == NULL);
677
    assert(options != NULL && bs->options != options);
678

679
680
    trace_bdrv_open_common(bs, filename, flags, drv->format_name);

681
682
683
684
685
686
687
688
689
690
691
692
    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
        return -ENOTSUP;
    }

    /* 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;
    }

693
694
695
    bs->open_flags = flags;
    bs->buffer_alignment = 512;

696
697
698
699
700
    assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
    if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {
        bdrv_enable_copy_on_read(bs);
    }

701
702
703
704
705
    if (filename != NULL) {
        pstrcpy(bs->filename, sizeof(bs->filename), filename);
    } else {
        bs->filename[0] = '\0';
    }
706
707

    bs->drv = drv;
708
    bs->opaque = g_malloc0(drv->instance_size);
709

710
    bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
Kevin Wolf's avatar
Kevin Wolf committed
711
    open_flags = bdrv_open_flags(bs, flags);
712

713
    bs->read_only = !(open_flags & BDRV_O_RDWR);
714

715
716
    /* Open the image, either directly or using a protocol */
    if (drv->bdrv_file_open) {
717
718
719
        assert(file == NULL);
        assert(drv->bdrv_parse_filename || filename != NULL);
        ret = drv->bdrv_file_open(bs, filename, options, open_flags);
720
    } else {
721
722
723
724
725
726
727
        if (file == NULL) {
            qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't use '%s' as a "
                          "block driver for the protocol level",
                          drv->format_name);
            ret = -EINVAL;
            goto free_and_fail;
        }
728
729
        assert(file != NULL);
        bs->file = file;
730
        ret = drv->bdrv_open(bs, options, open_flags);
731
732
    }

733
734
735
736
    if (ret < 0) {
        goto free_and_fail;
    }

737
738
739
    ret = refresh_total_sectors(bs, bs->total_sectors);
    if (ret < 0) {
        goto free_and_fail;
740
    }
741

742
743
#ifndef _WIN32
    if (bs->is_temporary) {
744
        assert(filename != NULL);
745
746
747
748
749
750
        unlink(filename);
    }
#endif
    return 0;

free_and_fail:
751
    bs->file = NULL;
752
    g_free(bs->opaque);
753
754
755
756
757
    bs->opaque = NULL;
    bs->drv = NULL;
    return ret;
}

Kevin Wolf's avatar
Kevin Wolf committed
758
759
/*
 * Opens a file using a protocol (file, host_device, nbd, ...)
760
761
762
763
764
 *
 * 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
765
 */
766
767
int bdrv_file_open(BlockDriverState **pbs, const char *filename,
                   QDict *options, int flags)
bellard's avatar
bellard committed
768
{
bellard's avatar
bellard committed
769
    BlockDriverState *bs;
770
    BlockDriver *drv;
771
    const char *drvname;
bellard's avatar
bellard committed
772
773
    int ret;

774
775
776
777
778
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

bellard's avatar
bellard committed
779
    bs = bdrv_new("");
780
781
782
    bs->options = options;
    options = qdict_clone_shallow(options);

783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
    /* Find the right block driver */
    drvname = qdict_get_try_str(options, "driver");
    if (drvname) {
        drv = bdrv_find_whitelisted_format(drvname);
        qdict_del(options, "driver");
    } else if (filename) {
        drv = bdrv_find_protocol(filename);
    } else {
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
                      "Must specify either driver or file");
        drv = NULL;
    }

    if (!drv) {
        ret = -ENOENT;
        goto fail;
    }

    /* Parse the filename and open it */
    if (drv->bdrv_parse_filename && filename) {
803
804
805
806
807
808
809
810
        Error *local_err = NULL;
        drv->bdrv_parse_filename(filename, options, &local_err);
        if (error_is_set(&local_err)) {
            qerror_report_err(local_err);
            error_free(local_err);
            ret = -EINVAL;
            goto fail;
        }
811
812
813
814
815
816
    } else if (!drv->bdrv_parse_filename && !filename) {
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
                      "The '%s' block driver requires a file name",
                      drv->format_name);
        ret = -EINVAL;
        goto fail;
817
818
    }

819
    ret = bdrv_open_common(bs, NULL, filename, options, flags, drv);
bellard's avatar
bellard committed
820
    if (ret < 0) {
821
822
823
824
825
826
827
828
829
830
831
        goto fail;
    }

    /* Check if any unknown options were used */
    if (qdict_size(options) != 0) {
        const QDictEntry *entry = qdict_first(options);
        qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block protocol '%s' doesn't "
                      "support the option '%s'",
                      drv->format_name, entry->key);
        ret = -EINVAL;
        goto fail;
832
    }
833
834
    QDECREF(options);

835
    bs->growable = 1;
bellard's avatar
bellard committed
836
837
    *pbs = bs;
    return 0;
838
839
840
841
842
843
844
845

fail:
    QDECREF(options);
    if (!bs->drv) {
        QDECREF(bs->options);
    }
    bdrv_delete(bs);
    return ret;
bellard's avatar
bellard committed
846
847
}

848
849
850
851
852
853
854
855
856
/*
 * 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.
 */
int bdrv_open_backing_file(BlockDriverState *bs, QDict *options)
857
858
859
860
861
862
{
    char backing_filename[PATH_MAX];
    int back_flags, ret;
    BlockDriver *back_drv = NULL;

    if (bs->backing_hd != NULL) {
863
        QDECREF(options);
864
865
866
        return 0;
    }

867
868
869
870
871
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

872
    bs->open_flags &= ~BDRV_O_NO_BACKING;
873
874
    if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
        QDECREF(options);
875
876
877
878
879
880
881
882
883
884
885
886
887
888
        return 0;
    }

    bs->backing_hd = bdrv_new("");
    bdrv_get_full_backing_filename(bs, backing_filename,
                                   sizeof(backing_filename));

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

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

889
890
    ret = bdrv_open(bs->backing_hd,
                    *backing_filename ? backing_filename : NULL, options,
891
                    back_flags, back_drv);
892
893
894
895
896
897
898
899
900
    if (ret < 0) {
        bdrv_delete(bs->backing_hd);
        bs->backing_hd = NULL;
        bs->open_flags |= BDRV_O_NO_BACKING;
        return ret;
    }
    return 0;
}

901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
static void extract_subqdict(QDict *src, QDict **dst, const char *start)
{
    const QDictEntry *entry, *next;
    const char *p;

    *dst = qdict_new();
    entry = qdict_first(src);

    while (entry != NULL) {
        next = qdict_next(src, entry);
        if (strstart(entry->key, start, &p)) {
            qobject_incref(entry->value);
            qdict_put_obj(*dst, p, entry->value);
            qdict_del(src, entry->key);
        }
        entry = next;
    }
}

Kevin Wolf's avatar
Kevin Wolf committed
920
921
/*
 * Opens a disk image (raw, qcow2, vmdk, ...)
922
923
924
925
926
 *
 * 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
927
 */
928
929
int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
              int flags, BlockDriver *drv)
bellard's avatar
bellard committed
930
{
Kevin Wolf's avatar
Kevin Wolf committed
931
    int ret;
932
933
    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
    char tmp_filename[PATH_MAX + 1];
934
    BlockDriverState *file = NULL;
935
    QDict *file_options = NULL;
bellard's avatar
bellard committed
936

937
938
939
940
941
942
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

    bs->options = options;
943
    options = qdict_clone_shallow(options);
944
945

    /* For snapshot=on, create a temporary qcow2 overlay */
bellard's avatar
bellard committed
946
    if (flags & BDRV_O_SNAPSHOT) {
bellard's avatar
bellard committed
947
948
        BlockDriverState *bs1;
        int64_t total_size;
Kevin Wolf's avatar
Kevin Wolf committed
949
        BlockDriver *bdrv_qcow2;
950
        QEMUOptionParameter *create_options;
Kevin Wolf's avatar
Kevin Wolf committed
951
        char backing_filename[PATH_MAX];
952

953
954
955
956
957
958
959
        if (qdict_size(options) != 0) {
            error_report("Can't use snapshot=on with driver-specific options");
            ret = -EINVAL;
            goto fail;
        }
        assert(filename != NULL);

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

bellard's avatar
bellard committed
963
964
        /* if there is a backing file, use it */
        bs1 = bdrv_new("");
965
        ret = bdrv_open(bs1, filename, NULL, 0, drv);
966
        if (ret < 0) {
bellard's avatar
bellard committed
967
            bdrv_delete(bs1);
968
            goto fail;
bellard's avatar
bellard committed
969
        }
970
        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori's avatar
aliguori committed
971

bellard's avatar
bellard committed
972
        bdrv_delete(bs1);
973

974
975
        ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
        if (ret < 0) {
976
            goto fail;
977
        }
aliguori's avatar
aliguori committed
978
979

        /* Real path is meaningless for protocols */
980
        if (path_has_protocol(filename)) {
aliguori's avatar
aliguori committed
981
982
            snprintf(backing_filename, sizeof(backing_filename),
                     "%s", filename);
983
984
985
986
        } else if (!realpath(filename, backing_filename)) {
            ret = -errno;
            goto fail;
        }
aliguori's avatar
aliguori committed
987

Kevin Wolf's avatar
Kevin Wolf committed
988
        bdrv_qcow2 = bdrv_find_format("qcow2");
989
990
        create_options = parse_option_parameters("", bdrv_qcow2->create_options,
                                                 NULL);
Kevin Wolf's avatar
Kevin Wolf committed
991

992
993
994
        set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
        set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE,
                             backing_filename);
Kevin Wolf's avatar
Kevin Wolf committed
995
        if (drv) {
996
            set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,
Kevin Wolf's avatar
Kevin Wolf committed
997
998
999
                drv->format_name);
        }

1000
1001
        ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options);
        free_option_parameters(create_options);
1002
        if (ret < 0) {
1003
            goto fail;
bellard's avatar
bellard committed
1004
        }
Kevin Wolf's avatar
Kevin Wolf committed
1005

bellard's avatar
bellard committed
1006
        filename = tmp_filename;
Kevin Wolf's avatar
Kevin Wolf committed
1007
        drv = bdrv_qcow2;
bellard's avatar
bellard committed
1008
1009
        bs->is_temporary = 1;
    }
bellard's avatar
bellard committed
1010

1011
1012
1013
1014
1015
    /* Open image file without format layer */
    if (flags & BDRV_O_RDWR) {
        flags |= BDRV_O_ALLOW_RDWR;
    }

1016
1017
1018
1019
    extract_subqdict(options, &file_options, "file.");

    ret = bdrv_file_open(&file, filename, file_options,
                         bdrv_open_flags(bs, flags));
1020
    if (ret < 0) {
1021
        goto fail;
1022
1023
    }

Kevin Wolf's avatar
Kevin Wolf committed
1024
    /* Find the right image format driver */
1025
    if (!drv) {
1026
        ret = find_image_format(file, filename, &drv);
1027
    }
1028

1029
1030
    if (!drv) {
        goto unlink_and_fail;
bellard's avatar
bellard committed
1031
    }
Kevin Wolf's avatar
Kevin Wolf committed
1032
1033

    /* Open the image */
1034
    ret = bdrv_open_common(bs, file, filename, options, flags, drv);
Kevin Wolf's avatar
Kevin Wolf committed
1035
    if (ret < 0) {
1036
1037
1038
        goto unlink_and_fail;
    }

1039
1040
1041
1042
1043
    if (bs->file != file) {
        bdrv_delete(file);
        file = NULL;
    }

Kevin Wolf's avatar
Kevin Wolf committed
1044
    /* If there is a backing file, use it */
1045
    if ((flags & BDRV_O_NO_BACKING) == 0) {
1046
1047
1048
1049
        QDict *backing_options;

        extract_subqdict(options, &backing_options, "backing.");
        ret = bdrv_open_backing_file(bs, backing_options);
Kevin Wolf's avatar
Kevin Wolf committed
1050
        if (ret < 0) {
1051
            goto close_and_fail;
Kevin Wolf's avatar
Kevin Wolf committed
1052
1053
1054
        }
    }

1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
    /* Check if any unknown options were used */
    if (qdict_size(options) != 0) {
        const QDictEntry *entry = qdict_first(options);
        qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by "
            "device '%s' doesn't support the option '%s'",
            drv->format_name, bs->device_name, entry->key);

        ret = -EINVAL;
        goto close_and_fail;
    }
    QDECREF(options);

Kevin Wolf's avatar
Kevin Wolf committed
1067
    if (!bdrv_key_required(bs)) {
1068
        bdrv_dev_change_media_cb(bs, true);
Kevin Wolf's avatar
Kevin Wolf committed
1069
1070
    }

1071
1072
1073
1074
1075
    /* throttling disk I/O limits */
    if (bs->io_limits_enabled) {
        bdrv_io_limits_enable(bs);
    }

Kevin Wolf's avatar
Kevin Wolf committed
1076
1077
1078
    return 0;

unlink_and_fail:
1079
1080
1081
    if (file != NULL) {
        bdrv_delete(file);
    }
Kevin Wolf's avatar
Kevin Wolf committed
1082
1083
1084
    if (bs->is_temporary) {
        unlink(filename);
    }
1085
1086
fail:
    QDECREF(bs->options);
1087
    QDECREF(options);
1088
    bs->options = NULL;
1089
    return ret;
1090

1091
1092
1093
close_and_fail:
    bdrv_close(bs);
    QDECREF(options);
Kevin Wolf's avatar
Kevin Wolf committed
1094
1095
1096
    return ret;
}

1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
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
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
typedef struct BlockReopenQueueEntry {
     bool prepared;
     BDRVReopenState state;
     QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
} BlockReopenQueueEntry;

/*
 * Adds a BlockDriverState to a simple queue for an atomic, transactional
 * reopen of multiple devices.
 *
 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
 * already performed, or alternatively may be NULL a new BlockReopenQueue will
 * be created and initialized. This newly created BlockReopenQueue should be
 * passed back in for subsequent calls that are intended to be of the same
 * atomic 'set'.
 *
 * bs is the BlockDriverState to add to the reopen queue.
 *
 * flags contains the open flags for the associated bs
 *
 * returns a pointer to bs_queue, which is either the newly allocated
 * bs_queue, or the existing bs_queue being used.
 *
 */
BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
                                    BlockDriverState *bs, int flags)
{
    assert(bs != NULL);

    BlockReopenQueueEntry *bs_entry;
    if (bs_queue == NULL) {
        bs_queue = g_new0(BlockReopenQueue, 1);
        QSIMPLEQ_INIT(bs_queue);
    }

    if (bs->file) {
        bdrv_reopen_queue(bs_queue, bs->file, flags);
    }

    bs_entry = g_new0(BlockReopenQueueEntry, 1);
    QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);

    bs_entry->state.bs = bs;
    bs_entry->state.flags = flags;

    return bs_queue;
}

/*
 * Reopen multiple BlockDriverStates atomically & transactionally.
 *
 * The queue passed in (bs_queue) must have been built up previous
 * via bdrv_reopen_queue().
 *
 * Reopens all BDS specified in the queue, with the appropriate
 * flags.  All devices are prepared for reopen, and failure of any
 * device will cause all device changes to be abandonded, and intermediate
 * data cleaned up.
 *
 * If all devices prepare successfully, then the changes are committed
 * to all devices.
 *
 */
int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
{
    int ret = -1;
    BlockReopenQueueEntry *bs_entry, *next;
    Error *local_err = NULL;

    assert(bs_queue != NULL);

    bdrv_drain_all();

    QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
        if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
            error_propagate(errp, local_err);
            goto cleanup;
        }
        bs_entry->prepared = true;
    }

    /* If we reach this point, we have success and just need to apply the
     * changes
     */
    QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
        bdrv_reopen_commit(&bs_entry->state);
    }

    ret = 0;

cleanup:
    QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
        if (ret && bs_entry->prepared) {
            bdrv_reopen_abort(&bs_entry->state);
        }
        g_free(bs_entry);
    }
    g_free(bs_queue);
    return ret;
}


/* Reopen a single BlockDriverState with the specified flags. */
int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
{
    int ret = -1;
    Error *local_err = NULL;
    BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);

    ret = bdrv_reopen_multiple(queue, &local_err);
    if (local_err != NULL) {
        error_propagate(errp, local_err);
    }
    return ret;
}


/*
 * Prepares a BlockDriverState for reopen. All changes are staged in the
 * 'opaque' field of the BDRVReopenState, which is used and allocated by
 * the block driver layer .bdrv_reopen_prepare()
 *
 * bs is the BlockDriverState to reopen
 * flags are the new open flags
 * queue is the reopen queue
 *
 * Returns 0 on success, non-zero on error.  On error errp will be set
 * as well.
 *
 * On failure, bdrv_reopen_abort() will be called to clean up any data.
 * It is the responsibility of the caller to then call the abort() or
 * commit() for any other BDS that have been left in a prepare() state
 *
 */
int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
                        Error **errp)
{
    int ret = -1;
    Error *local_err = NULL;
    BlockDriver *drv;

    assert(reopen_state != NULL);
    assert(reopen_state->bs->drv != NULL);
    drv = reopen_state->bs->drv;

    /* if we are to stay read-only, do not allow permission change
     * to r/w */
    if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
        reopen_state->flags & BDRV_O_RDWR) {
        error_set(errp, QERR_DEVICE_IS_READ_ONLY,
                  reopen_state->bs->device_name);
        goto error;
    }


    ret = bdrv_flush(reopen_state->bs);
    if (ret) {
        error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
                  strerror(-ret));
        goto error;
    }

    if (drv->bdrv_reopen_prepare) {
        ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
        if (ret) {
            if (local_err != NULL) {
                error_propagate(errp, local_err);
            } else {
                error_set(errp, QERR_OPEN_FILE_FAILED,
                          reopen_state->bs->filename);
            }
            goto error;
        }
    } else {
        /* It is currently mandatory to have a bdrv_reopen_prepare()
         * handler for each supported drv. */
        error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
                  drv->format_name, reopen_state->bs->device_name,
                 "reopening of file");
        ret = -1;
        goto error;
    }

    ret = 0;

error:
    return ret;
}

/*
 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
 * makes them final by swapping the staging BlockDriverState contents into
 * the active BlockDriverState contents.
 */
void bdrv_reopen_commit(BDRVReopenState *reopen_state)
{
    BlockDriver *drv;

    assert(reopen_state != NULL);
    drv = reopen_state->bs->drv;
    assert(drv != NULL);

    /* If there are any driver level actions to take */
    if (drv->bdrv_reopen_commit) {
        drv->bdrv_reopen_commit(reopen_state);
    }

    /* set BDS specific flags now */
    reopen_state->bs->open_flags         = reopen_state->flags;
    reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
                                              BDRV_O_CACHE_WB);
    reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
}

/*
 * Abort the reopen, and delete and free the staged changes in
 * reopen_state
 */
void bdrv_reopen_abort(BDRVReopenState *reopen_state)
{
    BlockDriver *drv;

    assert(reopen_state != NULL);
    drv = reopen_state->bs->drv;
    assert(drv != NULL);

    if (drv->bdrv_reopen_abort) {
        drv->bdrv_reopen_abort(reopen_state);
    }
}


bellard's avatar
bellard committed
1329
1330
void bdrv_close(BlockDriverState *bs)
{
1331
    bdrv_flush(bs);
1332
1333
1334
1335
    if (bs->job) {
        block_job_cancel_sync(bs->job);
    }
    bdrv_drain_all();
Paolo Bonzini's avatar
Paolo Bonzini committed
1336
    notifier_list_notify(&bs->close_notifiers, bs);
1337

1338
    if (bs->drv) {
1339
1340
1341
        if (bs == bs_snapshots) {
            bs_snapshots = NULL;
        }
1342
        if (bs->backing_hd) {
bellard's avatar
bellard committed
1343
            bdrv_delete(bs->backing_hd);
1344
1345
            bs->backing_hd = NULL;
        }
bellard's avatar
bellard committed
1346
        bs->drv->bdrv_close(bs);
1347
        g_free(bs->opaque);