block.c 127 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
145
146
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;
    bs->slice_time  = 0;
    memset(&bs->io_base, 0, sizeof(bs->io_base));
}

147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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];
}

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

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

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

212
    return *p == ':';
213
214
}

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

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

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

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

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

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

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

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

bellard's avatar
bellard committed
314
315
316
    return bs;
}

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

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

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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;
}

357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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);
}

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

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

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

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

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

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

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

    return bdrv_create(drv, filename, options);
}

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

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

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

484
485
    /* TODO Drivers without bdrv_file_open must be specified explicitly */

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

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

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

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

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

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

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

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

570
571
572
573
574
575
576
577
578
579
580
581
582
    /* 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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
/**
 * 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;
}

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

630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/**
 * 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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
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;
}

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

    assert(drv != NULL);
678
    assert(bs->file == NULL);
679
    assert(options == NULL || bs->options != options);
680

681
682
    trace_bdrv_open_common(bs, filename, flags, drv->format_name);

683
684
685
    bs->open_flags = flags;
    bs->buffer_alignment = 512;

686
687
688
689
690
    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);
    }

691
692
693
694
695
696
697
    pstrcpy(bs->filename, sizeof(bs->filename), filename);

    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
        return -ENOTSUP;
    }

    bs->drv = drv;
698
    bs->opaque = g_malloc0(drv->instance_size);
699

700
    bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
Kevin Wolf's avatar
Kevin Wolf committed
701
    open_flags = bdrv_open_flags(bs, flags);
702

703
    bs->read_only = !(open_flags & BDRV_O_RDWR);
704

705
706
    /* Open the image, either directly or using a protocol */
    if (drv->bdrv_file_open) {
707
708
709
710
711
        if (file != NULL) {
            bdrv_swap(file, bs);
            ret = 0;
        } else {
            ret = drv->bdrv_file_open(bs, filename, open_flags);
712
        }
713
714
715
    } else {
        assert(file != NULL);
        bs->file = file;
716
        ret = drv->bdrv_open(bs, options, open_flags);
717
718
    }

719
720
721
722
    if (ret < 0) {
        goto free_and_fail;
    }

723
724
725
    ret = refresh_total_sectors(bs, bs->total_sectors);
    if (ret < 0) {
        goto free_and_fail;
726
    }
727

728
729
730
731
732
733
734
735
#ifndef _WIN32
    if (bs->is_temporary) {
        unlink(filename);
    }
#endif
    return 0;

free_and_fail:
736
    bs->file = NULL;
737
    g_free(bs->opaque);
738
739
740
741
742
    bs->opaque = NULL;
    bs->drv = NULL;
    return ret;
}

Kevin Wolf's avatar
Kevin Wolf committed
743
744
745
/*
 * Opens a file using a protocol (file, host_device, nbd, ...)
 */
bellard's avatar
bellard committed
746
int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
bellard's avatar
bellard committed
747
{
bellard's avatar
bellard committed
748
    BlockDriverState *bs;
749
    BlockDriver *drv;
bellard's avatar
bellard committed
750
751
    int ret;

752
    drv = bdrv_find_protocol(filename);
753
754
755
756
    if (!drv) {
        return -ENOENT;
    }

bellard's avatar
bellard committed
757
    bs = bdrv_new("");
758
    ret = bdrv_open_common(bs, NULL, filename, NULL, flags, drv);
bellard's avatar
bellard committed
759
760
761
    if (ret < 0) {
        bdrv_delete(bs);
        return ret;
762
    }
763
    bs->growable = 1;
bellard's avatar
bellard committed
764
765
766
767
    *pbs = bs;
    return 0;
}

768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
int bdrv_open_backing_file(BlockDriverState *bs)
{
    char backing_filename[PATH_MAX];
    int back_flags, ret;
    BlockDriver *back_drv = NULL;

    if (bs->backing_hd != NULL) {
        return 0;
    }

    bs->open_flags &= ~BDRV_O_NO_BACKING;
    if (bs->backing_file[0] == '\0') {
        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);

794
795
    ret = bdrv_open(bs->backing_hd, backing_filename, NULL,
                    back_flags, back_drv);
796
797
798
799
800
801
802
803
804
    if (ret < 0) {
        bdrv_delete(bs->backing_hd);
        bs->backing_hd = NULL;
        bs->open_flags |= BDRV_O_NO_BACKING;
        return ret;
    }
    return 0;
}

Kevin Wolf's avatar
Kevin Wolf committed
805
806
/*
 * Opens a disk image (raw, qcow2, vmdk, ...)
807
808
809
810
811
 *
 * 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
812
 */
813
814
int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
              int flags, BlockDriver *drv)
bellard's avatar
bellard committed
815
{
Kevin Wolf's avatar
Kevin Wolf committed
816
    int ret;
817
818
    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
    char tmp_filename[PATH_MAX + 1];
819
    BlockDriverState *file = NULL;
bellard's avatar
bellard committed
820

821
822
823
824
825
826
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

    bs->options = options;
827
    options = qdict_clone_shallow(options);
828
829

    /* For snapshot=on, create a temporary qcow2 overlay */
bellard's avatar
bellard committed
830
    if (flags & BDRV_O_SNAPSHOT) {
bellard's avatar
bellard committed
831
832
        BlockDriverState *bs1;
        int64_t total_size;
aliguori's avatar
aliguori committed
833
        int is_protocol = 0;
Kevin Wolf's avatar
Kevin Wolf committed
834
835
        BlockDriver *bdrv_qcow2;
        QEMUOptionParameter *options;
Kevin Wolf's avatar
Kevin Wolf committed
836
        char backing_filename[PATH_MAX];
837

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

bellard's avatar
bellard committed
841
842
        /* if there is a backing file, use it */
        bs1 = bdrv_new("");
843
        ret = bdrv_open(bs1, filename, NULL, 0, drv);
844
        if (ret < 0) {
bellard's avatar
bellard committed
845
            bdrv_delete(bs1);
846
            goto fail;
bellard's avatar
bellard committed
847
        }
848
        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori's avatar
aliguori committed
849
850
851
852

        if (bs1->drv && bs1->drv->protocol_name)
            is_protocol = 1;

bellard's avatar
bellard committed
853
        bdrv_delete(bs1);
854

855
856
        ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
        if (ret < 0) {
857
            goto fail;
858
        }
aliguori's avatar
aliguori committed
859
860

        /* Real path is meaningless for protocols */
861
        if (is_protocol) {
aliguori's avatar
aliguori committed
862
863
            snprintf(backing_filename, sizeof(backing_filename),
                     "%s", filename);
864
865
866
867
        } else if (!realpath(filename, backing_filename)) {
            ret = -errno;
            goto fail;
        }
aliguori's avatar
aliguori committed
868

Kevin Wolf's avatar
Kevin Wolf committed
869
870
871
        bdrv_qcow2 = bdrv_find_format("qcow2");
        options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);

872
        set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf's avatar
Kevin Wolf committed
873
874
875
876
877
878
879
        set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
        if (drv) {
            set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
                drv->format_name);
        }

        ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
880
        free_option_parameters(options);
881
        if (ret < 0) {
882
            goto fail;
bellard's avatar
bellard committed
883
        }
Kevin Wolf's avatar
Kevin Wolf committed
884

bellard's avatar
bellard committed
885
        filename = tmp_filename;
Kevin Wolf's avatar
Kevin Wolf committed
886
        drv = bdrv_qcow2;
bellard's avatar
bellard committed
887
888
        bs->is_temporary = 1;
    }
bellard's avatar
bellard committed
889

890
891
892
893
894
895
896
    /* Open image file without format layer */
    if (flags & BDRV_O_RDWR) {
        flags |= BDRV_O_ALLOW_RDWR;
    }

    ret = bdrv_file_open(&file, filename, bdrv_open_flags(bs, flags));
    if (ret < 0) {
897
        goto fail;
898
899
    }

Kevin Wolf's avatar
Kevin Wolf committed
900
    /* Find the right image format driver */
901
    if (!drv) {
902
        ret = find_image_format(file, filename, &drv);
903
    }
904

905
906
    if (!drv) {
        goto unlink_and_fail;
bellard's avatar
bellard committed
907
    }
Kevin Wolf's avatar
Kevin Wolf committed
908
909

    /* Open the image */
910
    ret = bdrv_open_common(bs, file, filename, options, flags, drv);
Kevin Wolf's avatar
Kevin Wolf committed
911
    if (ret < 0) {
912
913
914
        goto unlink_and_fail;
    }

915
916
917
918
919
    if (bs->file != file) {
        bdrv_delete(file);
        file = NULL;
    }

Kevin Wolf's avatar
Kevin Wolf committed
920
    /* If there is a backing file, use it */
921
922
    if ((flags & BDRV_O_NO_BACKING) == 0) {
        ret = bdrv_open_backing_file(bs);
Kevin Wolf's avatar
Kevin Wolf committed
923
        if (ret < 0) {
924
            goto close_and_fail;
Kevin Wolf's avatar
Kevin Wolf committed
925
926
927
        }
    }

928
929
930
931
932
933
934
935
936
937
938
939
    /* 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
940
    if (!bdrv_key_required(bs)) {
941
        bdrv_dev_change_media_cb(bs, true);
Kevin Wolf's avatar
Kevin Wolf committed
942
943
    }

944
945
946
947
948
    /* throttling disk I/O limits */
    if (bs->io_limits_enabled) {
        bdrv_io_limits_enable(bs);
    }

Kevin Wolf's avatar
Kevin Wolf committed
949
950
951
    return 0;

unlink_and_fail:
952
953
954
    if (file != NULL) {
        bdrv_delete(file);
    }
Kevin Wolf's avatar
Kevin Wolf committed
955
956
957
    if (bs->is_temporary) {
        unlink(filename);
    }
958
959
fail:
    QDECREF(bs->options);
960
    QDECREF(options);
961
    bs->options = NULL;
962
    return ret;
963

964
965
966
close_and_fail:
    bdrv_close(bs);
    QDECREF(options);
Kevin Wolf's avatar
Kevin Wolf committed
967
968
969
    return ret;
}

970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
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
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
1202
1203
void bdrv_close(BlockDriverState *bs)
{
1204
    bdrv_flush(bs);
1205
1206
1207
1208
    if (bs->job) {
        block_job_cancel_sync(bs->job);
    }
    bdrv_drain_all();
Paolo Bonzini's avatar
Paolo Bonzini committed
1209
    notifier_list_notify(&bs->close_notifiers, bs);
1210

1211
    if (bs->drv) {
1212
1213
1214
        if (bs == bs_snapshots) {
            bs_snapshots = NULL;
        }
1215
        if (bs->backing_hd) {
bellard's avatar
bellard committed
1216
            bdrv_delete(bs->backing_hd);
1217
1218
            bs->backing_hd = NULL;
        }
bellard's avatar
bellard committed
1219
        bs->drv->bdrv_close(bs);
1220
        g_free(bs->opaque);
bellard's avatar
bellard committed
1221
1222
1223
1224
#ifdef _WIN32
        if (bs->is_temporary) {
            unlink(bs->filename);
        }
bellard's avatar
bellard committed
1225
#endif
bellard's avatar
bellard committed
1226
1227
        bs->opaque = NULL;
        bs->drv = NULL;
1228
        bs->copy_on_read = 0;
1229
1230
        bs->backing_file[0] = '\0';
        bs->backing_format[0] = '\0';
1231
1232
1233
1234
1235
        bs->total_sectors = 0;
        bs->encrypted = 0;
        bs->valid_key = 0;
        bs->sg = 0;
        bs->growable = 0;
1236
1237
        QDECREF(bs->options);
        bs->options = NULL;
bellard's avatar
bellard committed
1238

1239
        if (bs->file != NULL) {
1240
1241
            bdrv_delete(bs->file);
            bs->file = NULL;
1242
        }
bellard's avatar
bellard committed
1243
    }
1244

Pavel Hrdina's avatar
Pavel Hrdina committed
1245
1246
    bdrv_dev_change_media_cb(bs, false);

1247
1248
1249
1250
    /*throttling disk I/O limits*/
    if (bs->io_limits_enabled) {
        bdrv_io_limits_disable(bs);
    }
bellard's avatar
bellard committed
1251
1252
}

1253
1254
1255
1256
1257
1258
1259
1260
1261
void bdrv_close_all(void)
{
    BlockDriverState *bs;

    QTAILQ_FOREACH(bs, &bdrv_states, list) {
        bdrv_close(bs);
    }
}

1262
1263
1264
1265
1266
/*
 * Wait for pending requests to complete across all BlockDriverStates
 *
 * This function does not flush data to disk, use bdrv_flush_all() for that
 * after calling this function.
1267
1268
1269
1270
1271
1272
 *
 * Note that completion of an asynchronous I/O operation can trigger any
 * number of other I/O operations on other devices---for example a coroutine
 * can be arbitrarily complex and a constant flow of I/O can come until the
 * coroutine is complete.  Because of this, it is not possible to have a
 * function to drain a single device's I/O queue.
1273
1274
1275
1276
 */
void bdrv_drain_all(void)
{
    BlockDriverState *bs;
1277
1278
1279
1280
    bool busy;

    do {
        busy = qemu_aio_wait();
1281

1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
        /* FIXME: We do not have timer support here, so this is effectively
         * a busy wait.
         */
        QTAILQ_FOREACH(bs, &bdrv_states, list) {
            if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
                qemu_co_queue_restart_all(&bs->throttled_reqs);
                busy = true;
            }
        }
    } while (busy);
1292
1293
1294
1295
1296
1297
1298
1299

    /* If requests are still pending there is a bug somewhere */
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
        assert(QLIST_EMPTY(&bs->tracked_requests));
        assert(qemu_co_queue_empty(&bs->throttled_reqs));
    }
}

1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
/* make a BlockDriverState anonymous by removing from bdrv_state list.
   Also, NULL terminate the device_name to prevent double remove */
void bdrv_make_anon(BlockDriverState *bs)
{
    if (bs->device_name[0] != '\0') {
        QTAILQ_REMOVE(&bdrv_states, bs, list);
    }
    bs->device_name[0] = '\0';
}

Paolo Bonzini's avatar
Paolo Bonzini committed
1310
1311
1312
1313
1314
1315
1316
static void bdrv_rebind(BlockDriverState *bs)
{
    if (bs->drv && bs->drv->bdrv_rebind) {
        bs->drv->bdrv_rebind(bs);
    }
}

1317
1318
static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
                                     BlockDriverState *bs_src)
1319
{
1320
1321
    /* move some fields that need to stay attached to the device */
    bs_dest->open_flags         = bs_src->open_flags;
1322
1323

    /* dev info */
1324
1325
1326
1327
1328
    bs_dest->dev_ops            = bs_src->dev_ops;
    bs_dest->dev_opaque         = bs_src->dev_opaque;
    bs_dest->dev                = bs_src->dev;
    bs_dest->buffer_alignment   = bs_src->buffer_alignment;
    bs_dest->copy_on_read       = bs_src->copy_on_read;
1329

1330
    bs_dest->enable_write_cache = bs_src->enable_write_cache;
1331

1332
    /* i/o timing parameters */
1333
1334
1335
1336
1337
1338
1339
1340
    bs_dest->slice_time         = bs_src->slice_time;
    bs_dest->slice_start        = bs_src->slice_start;
    bs_dest->slice_end          = bs_src->slice_end;
    bs_dest->io_limits          = bs_src->io_limits;
    bs_dest->io_base            = bs_src->io_base;
    bs_dest->throttled_reqs     = bs_src->throttled_reqs;
    bs_dest->block_timer        = bs_src->block_timer;
    bs_dest->io_limits_enabled  = bs_src