block.c 128 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
/* If non-zero, use only whitelisted block drivers */
static int use_bdrv_whitelist;

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

125
/* throttling disk I/O limits */
126
127
128
129
void bdrv_io_limits_disable(BlockDriverState *bs)
{
    bs->io_limits_enabled = false;

130
    do {} while (qemu_co_enter_next(&bs->throttled_reqs));
131
132

    if (bs->block_timer) {
133
134
        timer_del(bs->block_timer);
        timer_free(bs->block_timer);
135
136
137
138
139
140
141
        bs->block_timer = NULL;
    }

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

142
143
144
145
static void bdrv_block_timer(void *opaque)
{
    BlockDriverState *bs = opaque;

146
    qemu_co_enter_next(&bs->throttled_reqs);
147
148
149
150
}

void bdrv_io_limits_enable(BlockDriverState *bs)
{
151
    bs->block_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, bdrv_block_timer, bs);
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    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];
}

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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)) {
183
184
        timer_mod(bs->block_timer,
                       wait_time + qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
185
186
187
188
189
190
        qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
    }

    qemu_co_queue_next(&bs->throttled_reqs);
}

191
192
193
/* check if the path starts with "<protocol>:" */
static int path_has_protocol(const char *path)
{
194
195
    const char *p;

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

206
    return *p == ':';
207
208
}

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

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

266
267
268
269
270
271
272
273
274
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);
    }
}

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

282
283
284
        /* 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.
         */
285
286
287
288
289
        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
290
    }
291

292
    QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellard's avatar
bellard committed
293
}
bellard's avatar
bellard committed
294
295
296
297

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

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

bellard's avatar
bellard committed
310
311
312
    return bs;
}

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

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

329
static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
330
{
331
332
333
334
335
    static const char *whitelist_rw[] = {
        CONFIG_BDRV_RW_WHITELIST
    };
    static const char *whitelist_ro[] = {
        CONFIG_BDRV_RO_WHITELIST
336
337
338
    };
    const char **p;

339
    if (!whitelist_rw[0] && !whitelist_ro[0]) {
340
        return 1;               /* no whitelist, anything goes */
341
    }
342

343
    for (p = whitelist_rw; *p; p++) {
344
345
346
347
        if (!strcmp(drv->format_name, *p)) {
            return 1;
        }
    }
348
349
350
351
352
353
354
    if (read_only) {
        for (p = whitelist_ro; *p; p++) {
            if (!strcmp(drv->format_name, *p)) {
                return 1;
            }
        }
    }
355
356
357
    return 0;
}

358
359
BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
                                          bool read_only)
360
361
{
    BlockDriver *drv = bdrv_find_format(format_name);
362
    return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
363
364
}

365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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);
}

380
381
int bdrv_create(BlockDriver *drv, const char* filename,
    QEMUOptionParameter *options)
bellard's avatar
bellard committed
382
{
383
384
385
386
387
388
389
390
391
392
393
    int ret;

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

    if (!drv->bdrv_create) {
394
395
        ret = -ENOTSUP;
        goto out;
396
397
398
399
400
401
402
403
404
405
406
407
408
409
    }

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

411
412
out:
    g_free(cco.filename);
413
    return ret;
bellard's avatar
bellard committed
414
415
}

416
417
418
419
int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
{
    BlockDriver *drv;

420
    drv = bdrv_find_protocol(filename, true);
421
    if (drv == NULL) {
422
        return -ENOENT;
423
424
425
426
427
    }

    return bdrv_create(drv, filename, options);
}

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

463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/*
 * 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;
}

485
486
BlockDriver *bdrv_find_protocol(const char *filename,
                                bool allow_protocol_prefix)
bellard's avatar
bellard committed
487
488
489
{
    BlockDriver *drv1;
    char protocol[128];
490
    int len;
bellard's avatar
bellard committed
491
    const char *p;
bellard's avatar
bellard committed
492

493
494
    /* TODO Drivers without bdrv_file_open must be specified explicitly */

495
496
497
498
499
500
501
502
503
504
505
506
    /*
     * 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;
    }

507
    if (!path_has_protocol(filename) || !allow_protocol_prefix) {
508
        return bdrv_find_format("file");
509
    }
510

511
512
    p = strchr(filename, ':');
    assert(p != NULL);
513
514
515
516
517
    len = p - filename;
    if (len > sizeof(protocol) - 1)
        len = sizeof(protocol) - 1;
    memcpy(protocol, filename, len);
    protocol[len] = '\0';
518
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
519
        if (drv1->protocol_name &&
520
            !strcmp(drv1->protocol_name, protocol)) {
bellard's avatar
bellard committed
521
            return drv1;
522
        }
bellard's avatar
bellard committed
523
524
525
526
    }
    return NULL;
}

527
528
static int find_image_format(BlockDriverState *bs, const char *filename,
                             BlockDriver **pdrv)
529
{
530
    int score, score_max;
531
532
    BlockDriver *drv1, *drv;
    uint8_t buf[2048];
533
    int ret = 0;
534

535
    /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
536
    if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
537
538
539
540
541
542
        drv = bdrv_find_format("raw");
        if (!drv) {
            ret = -ENOENT;
        }
        *pdrv = drv;
        return ret;
543
    }
544

bellard's avatar
bellard committed
545
546
    ret = bdrv_pread(bs, 0, buf, sizeof(buf));
    if (ret < 0) {
547
548
        *pdrv = NULL;
        return ret;
bellard's avatar
bellard committed
549
550
    }

bellard's avatar
bellard committed
551
    score_max = 0;
552
    drv = NULL;
553
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard's avatar
bellard committed
554
555
556
557
558
559
        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
560
        }
bellard's avatar
bellard committed
561
    }
562
563
564
565
566
    if (!drv) {
        ret = -ENOENT;
    }
    *pdrv = drv;
    return ret;
bellard's avatar
bellard committed
567
568
}

569
570
571
572
573
574
575
/**
 * Set the current 'total_sectors' value
 */
static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
{
    BlockDriver *drv = bs->drv;

576
577
578
579
    /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
    if (bs->sg)
        return 0;

580
581
582
583
584
585
586
587
588
589
590
591
592
    /* 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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
/**
 * 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;
}

613
614
615
616
617
618
619
620
621
622
623
/**
 * 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;
624
625
    } else if (!strcmp(mode, "directsync")) {
        *flags |= BDRV_O_NOCACHE;
626
627
628
629
630
631
632
633
634
635
636
637
638
639
    } 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;
}

640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/**
 * 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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
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;
}

676
677
/*
 * Common part for opening disk images and files
678
679
 *
 * Removes all processed options from *options.
680
 */
681
static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
Kevin Wolf's avatar
Kevin Wolf committed
682
    QDict *options, int flags, BlockDriver *drv)
683
684
{
    int ret, open_flags;
Kevin Wolf's avatar
Kevin Wolf committed
685
    const char *filename;
686
687

    assert(drv != NULL);
688
    assert(bs->file == NULL);
689
    assert(options != NULL && bs->options != options);
690

691
692
693
694
695
696
697
    if (file != NULL) {
        filename = file->filename;
    } else {
        filename = qdict_get_try_str(options, "filename");
    }

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

699
700
701
702
703
704
705
706
    /* 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;
    }

707
708
    bs->open_flags = flags;
    bs->buffer_alignment = 512;
709
    bs->zero_beyond_eof = true;
710
711
712
713
714
715
    open_flags = bdrv_open_flags(bs, flags);
    bs->read_only = !(open_flags & BDRV_O_RDWR);

    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
        return -ENOTSUP;
    }
716

717
    assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
718
    if (!bs->read_only && (flags & BDRV_O_COPY_ON_READ)) {
719
720
721
        bdrv_enable_copy_on_read(bs);
    }

722
723
724
725
726
    if (filename != NULL) {
        pstrcpy(bs->filename, sizeof(bs->filename), filename);
    } else {
        bs->filename[0] = '\0';
    }
727
728

    bs->drv = drv;
729
    bs->opaque = g_malloc0(drv->instance_size);
730

731
    bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
732

733
734
    /* Open the image, either directly or using a protocol */
    if (drv->bdrv_file_open) {
735
736
        assert(file == NULL);
        assert(drv->bdrv_parse_filename || filename != NULL);
737
        ret = drv->bdrv_file_open(bs, options, open_flags);
738
    } else {
739
740
741
742
743
744
745
        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;
        }
746
        bs->file = file;
747
        ret = drv->bdrv_open(bs, options, open_flags);
748
749
    }

750
751
752
753
    if (ret < 0) {
        goto free_and_fail;
    }

754
755
756
    ret = refresh_total_sectors(bs, bs->total_sectors);
    if (ret < 0) {
        goto free_and_fail;
757
    }
758

759
760
#ifndef _WIN32
    if (bs->is_temporary) {
761
        assert(filename != NULL);
762
763
764
765
766
767
        unlink(filename);
    }
#endif
    return 0;

free_and_fail:
768
    bs->file = NULL;
769
    g_free(bs->opaque);
770
771
772
773
774
    bs->opaque = NULL;
    bs->drv = NULL;
    return ret;
}

Kevin Wolf's avatar
Kevin Wolf committed
775
776
/*
 * Opens a file using a protocol (file, host_device, nbd, ...)
777
778
779
780
781
 *
 * 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
782
 */
783
784
int bdrv_file_open(BlockDriverState **pbs, const char *filename,
                   QDict *options, int flags)
bellard's avatar
bellard committed
785
{
bellard's avatar
bellard committed
786
    BlockDriverState *bs;
787
    BlockDriver *drv;
788
    const char *drvname;
789
    bool allow_protocol_prefix = false;
bellard's avatar
bellard committed
790
791
    int ret;

792
793
794
795
796
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

bellard's avatar
bellard committed
797
    bs = bdrv_new("");
798
799
800
    bs->options = options;
    options = qdict_clone_shallow(options);

Kevin Wolf's avatar
Kevin Wolf committed
801
802
803
804
805
    /* Fetch the file name from the options QDict if necessary */
    if (!filename) {
        filename = qdict_get_try_str(options, "filename");
    } else if (filename && !qdict_haskey(options, "filename")) {
        qdict_put(options, "filename", qstring_from_str(filename));
806
        allow_protocol_prefix = true;
Kevin Wolf's avatar
Kevin Wolf committed
807
808
809
810
811
812
813
    } else {
        qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't specify 'file' and "
                      "'filename' options at the same time");
        ret = -EINVAL;
        goto fail;
    }

814
815
816
    /* Find the right block driver */
    drvname = qdict_get_try_str(options, "driver");
    if (drvname) {
817
        drv = bdrv_find_whitelisted_format(drvname, !(flags & BDRV_O_RDWR));
818
819
        qdict_del(options, "driver");
    } else if (filename) {
820
821
822
823
        drv = bdrv_find_protocol(filename, allow_protocol_prefix);
        if (!drv) {
            qerror_report(ERROR_CLASS_GENERIC_ERROR, "Unknown protocol");
        }
824
825
826
827
828
829
830
831
832
833
834
835
836
    } 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) {
837
838
839
840
841
842
843
844
        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;
        }
845
        qdict_del(options, "filename");
846
847
848
849
850
851
    } 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;
852
853
    }

Kevin Wolf's avatar
Kevin Wolf committed
854
    ret = bdrv_open_common(bs, NULL, options, flags, drv);
bellard's avatar
bellard committed
855
    if (ret < 0) {
856
857
858
859
860
861
862
863
864
865
866
        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;
867
    }
868
869
    QDECREF(options);

870
    bs->growable = 1;
bellard's avatar
bellard committed
871
872
    *pbs = bs;
    return 0;
873
874
875
876
877
878
879
880

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

883
884
885
886
887
888
889
890
891
/*
 * 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)
892
893
894
895
896
897
{
    char backing_filename[PATH_MAX];
    int back_flags, ret;
    BlockDriver *back_drv = NULL;

    if (bs->backing_hd != NULL) {
898
        QDECREF(options);
899
900
901
        return 0;
    }

902
903
904
905
906
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

907
    bs->open_flags &= ~BDRV_O_NO_BACKING;
908
909
910
    if (qdict_haskey(options, "file.filename")) {
        backing_filename[0] = '\0';
    } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
911
        QDECREF(options);
912
913
914
915
916
917
918
919
920
921
922
923
924
925
        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);

926
927
    ret = bdrv_open(bs->backing_hd,
                    *backing_filename ? backing_filename : NULL, options,
928
                    back_flags, back_drv);
929
930
931
932
933
934
935
936
937
    if (ret < 0) {
        bdrv_delete(bs->backing_hd);
        bs->backing_hd = NULL;
        bs->open_flags |= BDRV_O_NO_BACKING;
        return ret;
    }
    return 0;
}

938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
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
957
958
/*
 * Opens a disk image (raw, qcow2, vmdk, ...)
959
960
961
962
963
 *
 * 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
964
 */
965
966
int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
              int flags, BlockDriver *drv)
bellard's avatar
bellard committed
967
{
Kevin Wolf's avatar
Kevin Wolf committed
968
    int ret;
969
970
    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
    char tmp_filename[PATH_MAX + 1];
971
    BlockDriverState *file = NULL;
972
    QDict *file_options = NULL;
973
    const char *drvname;
bellard's avatar
bellard committed
974

975
976
977
978
979
980
    /* NULL means an empty set of options */
    if (options == NULL) {
        options = qdict_new();
    }

    bs->options = options;
981
    options = qdict_clone_shallow(options);
982
983

    /* For snapshot=on, create a temporary qcow2 overlay */
bellard's avatar
bellard committed
984
    if (flags & BDRV_O_SNAPSHOT) {
bellard's avatar
bellard committed
985
986
        BlockDriverState *bs1;
        int64_t total_size;
Kevin Wolf's avatar
Kevin Wolf committed
987
        BlockDriver *bdrv_qcow2;
988
        QEMUOptionParameter *create_options;
Kevin Wolf's avatar
Kevin Wolf committed
989
        char backing_filename[PATH_MAX];
990

991
992
993
994
995
996
997
        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
998
999
        /* if snapshot, we create a temporary backing file and open it
           instead of opening 'filename' directly */
1000

bellard's avatar
bellard committed
1001
1002
        /* if there is a backing file, use it */
        bs1 = bdrv_new("");
1003
        ret = bdrv_open(bs1, filename, NULL, 0, drv);
1004
        if (ret < 0) {
bellard's avatar
bellard committed
1005
            bdrv_delete(bs1);
1006
            goto fail;
bellard's avatar
bellard committed
1007
        }
1008
        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori's avatar
aliguori committed
1009

bellard's avatar
bellard committed
1010
        bdrv_delete(bs1);
1011

1012
1013
        ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
        if (ret < 0) {
1014
            goto fail;
1015
        }
aliguori's avatar
aliguori committed
1016
1017

        /* Real path is meaningless for protocols */
1018
        if (path_has_protocol(filename)) {
aliguori's avatar
aliguori committed
1019
1020
            snprintf(backing_filename, sizeof(backing_filename),
                     "%s", filename);
1021
1022
1023
1024
        } else if (!realpath(filename, backing_filename)) {
            ret = -errno;
            goto fail;
        }
aliguori's avatar
aliguori committed
1025

Kevin Wolf's avatar
Kevin Wolf committed
1026
        bdrv_qcow2 = bdrv_find_format("qcow2");
1027
1028
        create_options = parse_option_parameters("", bdrv_qcow2->create_options,
                                                 NULL);
Kevin Wolf's avatar
Kevin Wolf committed
1029

1030
1031
1032
        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
1033
        if (drv) {
1034
            set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,
Kevin Wolf's avatar
Kevin Wolf committed
1035
1036
1037
                drv->format_name);
        }

1038
1039
        ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options);
        free_option_parameters(create_options);
1040
        if (ret < 0) {
1041
            goto fail;
bellard's avatar
bellard committed
1042
        }
Kevin Wolf's avatar
Kevin Wolf committed
1043

bellard's avatar
bellard committed
1044
        filename = tmp_filename;
Kevin Wolf's avatar
Kevin Wolf committed
1045
        drv = bdrv_qcow2;
bellard's avatar
bellard committed
1046
1047
        bs->is_temporary = 1;
    }
bellard's avatar
bellard committed
1048

1049
1050
1051
1052
1053
    /* Open image file without format layer */
    if (flags & BDRV_O_RDWR) {
        flags |= BDRV_O_ALLOW_RDWR;
    }

1054
1055
1056
    extract_subqdict(options, &file_options, "file.");

    ret = bdrv_file_open(&file, filename, file_options,
1057
                         bdrv_open_flags(bs, flags | BDRV_O_UNMAP));
1058
    if (ret < 0) {
1059
        goto fail;
1060
1061
    }

Kevin Wolf's avatar
Kevin Wolf committed
1062
    /* Find the right image format driver */
1063
1064
1065
1066
1067
1068
    drvname = qdict_get_try_str(options, "driver");
    if (drvname) {
        drv = bdrv_find_whitelisted_format(drvname, !(flags & BDRV_O_RDWR));
        qdict_del(options, "driver");
    }

1069
    if (!drv) {
1070
        ret = find_image_format(file, filename, &drv);
1071
    }
1072

1073
1074
    if (!drv) {
        goto unlink_and_fail;
bellard's avatar
bellard committed
1075
    }
Kevin Wolf's avatar
Kevin Wolf committed
1076
1077

    /* Open the image */
Kevin Wolf's avatar
Kevin Wolf committed
1078
    ret = bdrv_open_common(bs, file, options, flags, drv);
Kevin Wolf's avatar
Kevin Wolf committed
1079
    if (ret < 0) {
1080
1081
1082
        goto unlink_and_fail;
    }

1083
1084
1085
1086
1087
    if (bs->file != file) {
        bdrv_delete(file);
        file = NULL;
    }

Kevin Wolf's avatar
Kevin Wolf committed
1088
    /* If there is a backing file, use it */
1089
    if ((flags & BDRV_O_NO_BACKING) == 0) {
1090
1091
1092
1093
        QDict *backing_options;

        extract_subqdict(options, &backing_options, "backing.");
        ret = bdrv_open_backing_file(bs, backing_options);
Kevin Wolf's avatar
Kevin Wolf committed
1094
        if (ret < 0) {
1095
            goto close_and_fail;
Kevin Wolf's avatar
Kevin Wolf committed
1096
1097
1098
        }
    }

1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
    /* 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
1111
    if (!bdrv_key_required(bs)) {
1112
        bdrv_dev_change_media_cb(bs, true);
Kevin Wolf's avatar
Kevin Wolf committed
1113
1114
    }

1115
1116
1117
1118
1119
    /* throttling disk I/O limits */
    if (bs->io_limits_enabled) {
        bdrv_io_limits_enable(bs);
    }

Kevin Wolf's avatar
Kevin Wolf committed
1120
1121
1122
    return 0;

unlink_and_fail:
1123
1124
1125
    if (file != NULL) {
        bdrv_delete(file);
    }
Kevin Wolf's avatar
Kevin Wolf committed
1126
1127
1128
    if (bs->is_temporary) {
        unlink(filename);
    }
1129
1130
fail:
    QDECREF(bs->options);
1131
    QDECREF(options);
1132
    bs->options = NULL;
1133
    return ret;
1134

1135
1136
1137
close_and_fail:
    bdrv_close(bs);
    QDECREF(options);
Kevin Wolf's avatar
Kevin Wolf committed
1138
1139
1140
    return ret;
}

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