Statistics
| Branch: | Revision:

root / blockdev.c @ f298d071

History | View | Annotate | Download (65.6 kB)

1
/*
2
 * QEMU host block devices
3
 *
4
 * Copyright (c) 2003-2008 Fabrice Bellard
5
 *
6
 * This work is licensed under the terms of the GNU GPL, version 2 or
7
 * later.  See the COPYING file in the top-level directory.
8
 *
9
 * This file incorporates work covered by the following copyright and
10
 * permission notice:
11
 *
12
 * Copyright (c) 2003-2008 Fabrice Bellard
13
 *
14
 * Permission is hereby granted, free of charge, to any person obtaining a copy
15
 * of this software and associated documentation files (the "Software"), to deal
16
 * in the Software without restriction, including without limitation the rights
17
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
 * copies of the Software, and to permit persons to whom the Software is
19
 * furnished to do so, subject to the following conditions:
20
 *
21
 * The above copyright notice and this permission notice shall be included in
22
 * all copies or substantial portions of the Software.
23
 *
24
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30
 * THE SOFTWARE.
31
 */
32

    
33
#include "sysemu/blockdev.h"
34
#include "hw/block/block.h"
35
#include "block/blockjob.h"
36
#include "monitor/monitor.h"
37
#include "qapi/qmp/qerror.h"
38
#include "qemu/option.h"
39
#include "qemu/config-file.h"
40
#include "qapi/qmp/types.h"
41
#include "qapi-visit.h"
42
#include "qapi/qmp-output-visitor.h"
43
#include "sysemu/sysemu.h"
44
#include "block/block_int.h"
45
#include "qmp-commands.h"
46
#include "trace.h"
47
#include "sysemu/arch_init.h"
48

    
49
static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
50
extern QemuOptsList qemu_common_drive_opts;
51

    
52
static const char *const if_name[IF_COUNT] = {
53
    [IF_NONE] = "none",
54
    [IF_IDE] = "ide",
55
    [IF_SCSI] = "scsi",
56
    [IF_FLOPPY] = "floppy",
57
    [IF_PFLASH] = "pflash",
58
    [IF_MTD] = "mtd",
59
    [IF_SD] = "sd",
60
    [IF_VIRTIO] = "virtio",
61
    [IF_XEN] = "xen",
62
};
63

    
64
static const int if_max_devs[IF_COUNT] = {
65
    /*
66
     * Do not change these numbers!  They govern how drive option
67
     * index maps to unit and bus.  That mapping is ABI.
68
     *
69
     * All controllers used to imlement if=T drives need to support
70
     * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
71
     * Otherwise, some index values map to "impossible" bus, unit
72
     * values.
73
     *
74
     * For instance, if you change [IF_SCSI] to 255, -drive
75
     * if=scsi,index=12 no longer means bus=1,unit=5, but
76
     * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
77
     * the drive can't be set up.  Regression.
78
     */
79
    [IF_IDE] = 2,
80
    [IF_SCSI] = 7,
81
};
82

    
83
/*
84
 * We automatically delete the drive when a device using it gets
85
 * unplugged.  Questionable feature, but we can't just drop it.
86
 * Device models call blockdev_mark_auto_del() to schedule the
87
 * automatic deletion, and generic qdev code calls blockdev_auto_del()
88
 * when deletion is actually safe.
89
 */
90
void blockdev_mark_auto_del(BlockDriverState *bs)
91
{
92
    DriveInfo *dinfo = drive_get_by_blockdev(bs);
93

    
94
    if (dinfo && !dinfo->enable_auto_del) {
95
        return;
96
    }
97

    
98
    if (bs->job) {
99
        block_job_cancel(bs->job);
100
    }
101
    if (dinfo) {
102
        dinfo->auto_del = 1;
103
    }
104
}
105

    
106
void blockdev_auto_del(BlockDriverState *bs)
107
{
108
    DriveInfo *dinfo = drive_get_by_blockdev(bs);
109

    
110
    if (dinfo && dinfo->auto_del) {
111
        drive_put_ref(dinfo);
112
    }
113
}
114

    
115
static int drive_index_to_bus_id(BlockInterfaceType type, int index)
116
{
117
    int max_devs = if_max_devs[type];
118
    return max_devs ? index / max_devs : 0;
119
}
120

    
121
static int drive_index_to_unit_id(BlockInterfaceType type, int index)
122
{
123
    int max_devs = if_max_devs[type];
124
    return max_devs ? index % max_devs : index;
125
}
126

    
127
QemuOpts *drive_def(const char *optstr)
128
{
129
    return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
130
}
131

    
132
QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
133
                    const char *optstr)
134
{
135
    QemuOpts *opts;
136
    char buf[32];
137

    
138
    opts = drive_def(optstr);
139
    if (!opts) {
140
        return NULL;
141
    }
142
    if (type != IF_DEFAULT) {
143
        qemu_opt_set(opts, "if", if_name[type]);
144
    }
145
    if (index >= 0) {
146
        snprintf(buf, sizeof(buf), "%d", index);
147
        qemu_opt_set(opts, "index", buf);
148
    }
149
    if (file)
150
        qemu_opt_set(opts, "file", file);
151
    return opts;
152
}
153

    
154
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
155
{
156
    DriveInfo *dinfo;
157

    
158
    /* seek interface, bus and unit */
159

    
160
    QTAILQ_FOREACH(dinfo, &drives, next) {
161
        if (dinfo->type == type &&
162
            dinfo->bus == bus &&
163
            dinfo->unit == unit)
164
            return dinfo;
165
    }
166

    
167
    return NULL;
168
}
169

    
170
DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
171
{
172
    return drive_get(type,
173
                     drive_index_to_bus_id(type, index),
174
                     drive_index_to_unit_id(type, index));
175
}
176

    
177
int drive_get_max_bus(BlockInterfaceType type)
178
{
179
    int max_bus;
180
    DriveInfo *dinfo;
181

    
182
    max_bus = -1;
183
    QTAILQ_FOREACH(dinfo, &drives, next) {
184
        if(dinfo->type == type &&
185
           dinfo->bus > max_bus)
186
            max_bus = dinfo->bus;
187
    }
188
    return max_bus;
189
}
190

    
191
/* Get a block device.  This should only be used for single-drive devices
192
   (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
193
   appropriate bus.  */
194
DriveInfo *drive_get_next(BlockInterfaceType type)
195
{
196
    static int next_block_unit[IF_COUNT];
197

    
198
    return drive_get(type, 0, next_block_unit[type]++);
199
}
200

    
201
DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
202
{
203
    DriveInfo *dinfo;
204

    
205
    QTAILQ_FOREACH(dinfo, &drives, next) {
206
        if (dinfo->bdrv == bs) {
207
            return dinfo;
208
        }
209
    }
210
    return NULL;
211
}
212

    
213
static void bdrv_format_print(void *opaque, const char *name)
214
{
215
    error_printf(" %s", name);
216
}
217

    
218
static void drive_uninit(DriveInfo *dinfo)
219
{
220
    if (dinfo->opts) {
221
        qemu_opts_del(dinfo->opts);
222
    }
223

    
224
    bdrv_unref(dinfo->bdrv);
225
    g_free(dinfo->id);
226
    QTAILQ_REMOVE(&drives, dinfo, next);
227
    g_free(dinfo->serial);
228
    g_free(dinfo);
229
}
230

    
231
void drive_put_ref(DriveInfo *dinfo)
232
{
233
    assert(dinfo->refcount);
234
    if (--dinfo->refcount == 0) {
235
        drive_uninit(dinfo);
236
    }
237
}
238

    
239
void drive_get_ref(DriveInfo *dinfo)
240
{
241
    dinfo->refcount++;
242
}
243

    
244
typedef struct {
245
    QEMUBH *bh;
246
    BlockDriverState *bs;
247
} BDRVPutRefBH;
248

    
249
static void bdrv_put_ref_bh(void *opaque)
250
{
251
    BDRVPutRefBH *s = opaque;
252

    
253
    bdrv_unref(s->bs);
254
    qemu_bh_delete(s->bh);
255
    g_free(s);
256
}
257

    
258
/*
259
 * Release a BDS reference in a BH
260
 *
261
 * It is not safe to use bdrv_unref() from a callback function when the callers
262
 * still need the BlockDriverState.  In such cases we schedule a BH to release
263
 * the reference.
264
 */
265
static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
266
{
267
    BDRVPutRefBH *s;
268

    
269
    s = g_new(BDRVPutRefBH, 1);
270
    s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
271
    s->bs = bs;
272
    qemu_bh_schedule(s->bh);
273
}
274

    
275
static int parse_block_error_action(const char *buf, bool is_read)
276
{
277
    if (!strcmp(buf, "ignore")) {
278
        return BLOCKDEV_ON_ERROR_IGNORE;
279
    } else if (!is_read && !strcmp(buf, "enospc")) {
280
        return BLOCKDEV_ON_ERROR_ENOSPC;
281
    } else if (!strcmp(buf, "stop")) {
282
        return BLOCKDEV_ON_ERROR_STOP;
283
    } else if (!strcmp(buf, "report")) {
284
        return BLOCKDEV_ON_ERROR_REPORT;
285
    } else {
286
        error_report("'%s' invalid %s error action",
287
                     buf, is_read ? "read" : "write");
288
        return -1;
289
    }
290
}
291

    
292
static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
293
{
294
    if (throttle_conflicting(cfg)) {
295
        error_setg(errp, "bps/iops/max total values and read/write values"
296
                         " cannot be used at the same time");
297
        return false;
298
    }
299

    
300
    if (!throttle_is_valid(cfg)) {
301
        error_setg(errp, "bps/iops/maxs values must be 0 or greater");
302
        return false;
303
    }
304

    
305
    return true;
306
}
307

    
308
/* Takes the ownership of bs_opts */
309
static DriveInfo *blockdev_init(QDict *bs_opts,
310
                                BlockInterfaceType block_default_type)
311
{
312
    const char *buf;
313
    const char *file = NULL;
314
    const char *serial;
315
    const char *mediastr = "";
316
    BlockInterfaceType type;
317
    enum { MEDIA_DISK, MEDIA_CDROM } media;
318
    int bus_id, unit_id;
319
    int cyls, heads, secs, translation;
320
    int max_devs;
321
    int index;
322
    int ro = 0;
323
    int bdrv_flags = 0;
324
    int on_read_error, on_write_error;
325
    const char *devaddr;
326
    DriveInfo *dinfo;
327
    ThrottleConfig cfg;
328
    int snapshot = 0;
329
    bool copy_on_read;
330
    int ret;
331
    Error *error = NULL;
332
    QemuOpts *opts;
333
    const char *id;
334
    bool has_driver_specific_opts;
335
    BlockDriver *drv = NULL;
336

    
337
    translation = BIOS_ATA_TRANSLATION_AUTO;
338
    media = MEDIA_DISK;
339

    
340
    /* Check common options by copying from bs_opts to opts, all other options
341
     * stay in bs_opts for processing by bdrv_open(). */
342
    id = qdict_get_try_str(bs_opts, "id");
343
    opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
344
    if (error_is_set(&error)) {
345
        qerror_report_err(error);
346
        error_free(error);
347
        return NULL;
348
    }
349

    
350
    qemu_opts_absorb_qdict(opts, bs_opts, &error);
351
    if (error_is_set(&error)) {
352
        qerror_report_err(error);
353
        error_free(error);
354
        return NULL;
355
    }
356

    
357
    if (id) {
358
        qdict_del(bs_opts, "id");
359
    }
360

    
361
    has_driver_specific_opts = !!qdict_size(bs_opts);
362

    
363
    /* extract parameters */
364
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
365
    unit_id = qemu_opt_get_number(opts, "unit", -1);
366
    index   = qemu_opt_get_number(opts, "index", -1);
367

    
368
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
369
    heads = qemu_opt_get_number(opts, "heads", 0);
370
    secs  = qemu_opt_get_number(opts, "secs", 0);
371

    
372
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
373
    ro = qemu_opt_get_bool(opts, "read-only", 0);
374
    copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
375

    
376
    file = qemu_opt_get(opts, "file");
377
    serial = qemu_opt_get(opts, "serial");
378

    
379
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
380
        for (type = 0; type < IF_COUNT && strcmp(buf, if_name[type]); type++)
381
            ;
382
        if (type == IF_COUNT) {
383
            error_report("unsupported bus type '%s'", buf);
384
            return NULL;
385
        }
386
    } else {
387
        type = block_default_type;
388
    }
389

    
390
    max_devs = if_max_devs[type];
391

    
392
    if (cyls || heads || secs) {
393
        if (cyls < 1) {
394
            error_report("invalid physical cyls number");
395
            return NULL;
396
        }
397
        if (heads < 1) {
398
            error_report("invalid physical heads number");
399
            return NULL;
400
        }
401
        if (secs < 1) {
402
            error_report("invalid physical secs number");
403
            return NULL;
404
        }
405
    }
406

    
407
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
408
        if (!cyls) {
409
            error_report("'%s' trans must be used with cyls, heads and secs",
410
                         buf);
411
            return NULL;
412
        }
413
        if (!strcmp(buf, "none"))
414
            translation = BIOS_ATA_TRANSLATION_NONE;
415
        else if (!strcmp(buf, "lba"))
416
            translation = BIOS_ATA_TRANSLATION_LBA;
417
        else if (!strcmp(buf, "auto"))
418
            translation = BIOS_ATA_TRANSLATION_AUTO;
419
        else {
420
            error_report("'%s' invalid translation type", buf);
421
            return NULL;
422
        }
423
    }
424

    
425
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
426
        if (!strcmp(buf, "disk")) {
427
            media = MEDIA_DISK;
428
        } else if (!strcmp(buf, "cdrom")) {
429
            if (cyls || secs || heads) {
430
                error_report("CHS can't be set with media=%s", buf);
431
                return NULL;
432
            }
433
            media = MEDIA_CDROM;
434
        } else {
435
            error_report("'%s' invalid media", buf);
436
            return NULL;
437
        }
438
    }
439

    
440
    if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
441
        if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
442
            error_report("invalid discard option");
443
            return NULL;
444
        }
445
    }
446

    
447
    if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
448
        bdrv_flags |= BDRV_O_CACHE_WB;
449
    }
450
    if (qemu_opt_get_bool(opts, "cache.direct", false)) {
451
        bdrv_flags |= BDRV_O_NOCACHE;
452
    }
453
    if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
454
        bdrv_flags |= BDRV_O_NO_FLUSH;
455
    }
456

    
457
#ifdef CONFIG_LINUX_AIO
458
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
459
        if (!strcmp(buf, "native")) {
460
            bdrv_flags |= BDRV_O_NATIVE_AIO;
461
        } else if (!strcmp(buf, "threads")) {
462
            /* this is the default */
463
        } else {
464
           error_report("invalid aio option");
465
           return NULL;
466
        }
467
    }
468
#endif
469

    
470
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
471
        if (is_help_option(buf)) {
472
            error_printf("Supported formats:");
473
            bdrv_iterate_format(bdrv_format_print, NULL);
474
            error_printf("\n");
475
            return NULL;
476
        }
477

    
478
        drv = bdrv_find_format(buf);
479
        if (!drv) {
480
            error_report("'%s' invalid format", buf);
481
            return NULL;
482
        }
483
    }
484

    
485
    /* disk I/O throttling */
486
    memset(&cfg, 0, sizeof(cfg));
487
    cfg.buckets[THROTTLE_BPS_TOTAL].avg =
488
        qemu_opt_get_number(opts, "throttling.bps-total", 0);
489
    cfg.buckets[THROTTLE_BPS_READ].avg  =
490
        qemu_opt_get_number(opts, "throttling.bps-read", 0);
491
    cfg.buckets[THROTTLE_BPS_WRITE].avg =
492
        qemu_opt_get_number(opts, "throttling.bps-write", 0);
493
    cfg.buckets[THROTTLE_OPS_TOTAL].avg =
494
        qemu_opt_get_number(opts, "throttling.iops-total", 0);
495
    cfg.buckets[THROTTLE_OPS_READ].avg =
496
        qemu_opt_get_number(opts, "throttling.iops-read", 0);
497
    cfg.buckets[THROTTLE_OPS_WRITE].avg =
498
        qemu_opt_get_number(opts, "throttling.iops-write", 0);
499

    
500
    cfg.buckets[THROTTLE_BPS_TOTAL].max =
501
        qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
502
    cfg.buckets[THROTTLE_BPS_READ].max  =
503
        qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
504
    cfg.buckets[THROTTLE_BPS_WRITE].max =
505
        qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
506
    cfg.buckets[THROTTLE_OPS_TOTAL].max =
507
        qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
508
    cfg.buckets[THROTTLE_OPS_READ].max =
509
        qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
510
    cfg.buckets[THROTTLE_OPS_WRITE].max =
511
        qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
512

    
513
    cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
514

    
515
    if (!check_throttle_config(&cfg, &error)) {
516
        error_report("%s", error_get_pretty(error));
517
        error_free(error);
518
        return NULL;
519
    }
520

    
521
    if (qemu_opt_get(opts, "boot") != NULL) {
522
        fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
523
                "ignored. Future versions will reject this parameter. Please "
524
                "update your scripts.\n");
525
    }
526

    
527
    on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
528
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
529
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {
530
            error_report("werror is not supported by this bus type");
531
            return NULL;
532
        }
533

    
534
        on_write_error = parse_block_error_action(buf, 0);
535
        if (on_write_error < 0) {
536
            return NULL;
537
        }
538
    }
539

    
540
    on_read_error = BLOCKDEV_ON_ERROR_REPORT;
541
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
542
        if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {
543
            error_report("rerror is not supported by this bus type");
544
            return NULL;
545
        }
546

    
547
        on_read_error = parse_block_error_action(buf, 1);
548
        if (on_read_error < 0) {
549
            return NULL;
550
        }
551
    }
552

    
553
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
554
        if (type != IF_VIRTIO) {
555
            error_report("addr is not supported by this bus type");
556
            return NULL;
557
        }
558
    }
559

    
560
    /* compute bus and unit according index */
561

    
562
    if (index != -1) {
563
        if (bus_id != 0 || unit_id != -1) {
564
            error_report("index cannot be used with bus and unit");
565
            return NULL;
566
        }
567
        bus_id = drive_index_to_bus_id(type, index);
568
        unit_id = drive_index_to_unit_id(type, index);
569
    }
570

    
571
    /* if user doesn't specify a unit_id,
572
     * try to find the first free
573
     */
574

    
575
    if (unit_id == -1) {
576
       unit_id = 0;
577
       while (drive_get(type, bus_id, unit_id) != NULL) {
578
           unit_id++;
579
           if (max_devs && unit_id >= max_devs) {
580
               unit_id -= max_devs;
581
               bus_id++;
582
           }
583
       }
584
    }
585

    
586
    /* check unit id */
587

    
588
    if (max_devs && unit_id >= max_devs) {
589
        error_report("unit %d too big (max is %d)",
590
                     unit_id, max_devs - 1);
591
        return NULL;
592
    }
593

    
594
    /*
595
     * catch multiple definitions
596
     */
597

    
598
    if (drive_get(type, bus_id, unit_id) != NULL) {
599
        error_report("drive with bus=%d, unit=%d (index=%d) exists",
600
                     bus_id, unit_id, index);
601
        return NULL;
602
    }
603

    
604
    /* no id supplied -> create one */
605
    if (qemu_opts_id(opts) == NULL) {
606
        char *new_id;
607
        if (type == IF_IDE || type == IF_SCSI) {
608
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
609
        }
610
        if (max_devs) {
611
            new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
612
                                     mediastr, unit_id);
613
        } else {
614
            new_id = g_strdup_printf("%s%s%i", if_name[type],
615
                                     mediastr, unit_id);
616
        }
617
        qemu_opts_set_id(opts, new_id);
618
    }
619

    
620
    /* init */
621
    dinfo = g_malloc0(sizeof(*dinfo));
622
    dinfo->id = g_strdup(qemu_opts_id(opts));
623
    dinfo->bdrv = bdrv_new(dinfo->id);
624
    dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
625
    dinfo->bdrv->read_only = ro;
626
    dinfo->devaddr = devaddr;
627
    dinfo->type = type;
628
    dinfo->bus = bus_id;
629
    dinfo->unit = unit_id;
630
    dinfo->cyls = cyls;
631
    dinfo->heads = heads;
632
    dinfo->secs = secs;
633
    dinfo->trans = translation;
634
    dinfo->refcount = 1;
635
    if (serial != NULL) {
636
        dinfo->serial = g_strdup(serial);
637
    }
638
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
639

    
640
    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
641

    
642
    /* disk I/O throttling */
643
    if (throttle_enabled(&cfg)) {
644
        bdrv_io_limits_enable(dinfo->bdrv);
645
        bdrv_set_io_limits(dinfo->bdrv, &cfg);
646
    }
647

    
648
    switch(type) {
649
    case IF_IDE:
650
    case IF_SCSI:
651
    case IF_XEN:
652
    case IF_NONE:
653
        dinfo->media_cd = media == MEDIA_CDROM;
654
        break;
655
    case IF_SD:
656
    case IF_FLOPPY:
657
    case IF_PFLASH:
658
    case IF_MTD:
659
        break;
660
    case IF_VIRTIO:
661
    {
662
        /* add virtio block device */
663
        QemuOpts *devopts;
664
        devopts = qemu_opts_create_nofail(qemu_find_opts("device"));
665
        if (arch_type == QEMU_ARCH_S390X) {
666
            qemu_opt_set(devopts, "driver", "virtio-blk-s390");
667
        } else {
668
            qemu_opt_set(devopts, "driver", "virtio-blk-pci");
669
        }
670
        qemu_opt_set(devopts, "drive", dinfo->id);
671
        if (devaddr)
672
            qemu_opt_set(devopts, "addr", devaddr);
673
        break;
674
    }
675
    default:
676
        abort();
677
    }
678
    if (!file || !*file) {
679
        if (has_driver_specific_opts) {
680
            file = NULL;
681
        } else {
682
            return dinfo;
683
        }
684
    }
685
    if (snapshot) {
686
        /* always use cache=unsafe with snapshot */
687
        bdrv_flags &= ~BDRV_O_CACHE_MASK;
688
        bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
689
    }
690

    
691
    if (copy_on_read) {
692
        bdrv_flags |= BDRV_O_COPY_ON_READ;
693
    }
694

    
695
    if (runstate_check(RUN_STATE_INMIGRATE)) {
696
        bdrv_flags |= BDRV_O_INCOMING;
697
    }
698

    
699
    if (media == MEDIA_CDROM) {
700
        /* CDROM is fine for any interface, don't check.  */
701
        ro = 1;
702
    } else if (ro == 1) {
703
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY &&
704
            type != IF_NONE && type != IF_PFLASH) {
705
            error_report("read-only not supported by this bus type");
706
            goto err;
707
        }
708
    }
709

    
710
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
711

    
712
    if (ro && copy_on_read) {
713
        error_report("warning: disabling copy_on_read on read-only drive");
714
    }
715

    
716
    QINCREF(bs_opts);
717
    ret = bdrv_open(dinfo->bdrv, file, bs_opts, bdrv_flags, drv, &error);
718

    
719
    if (ret < 0) {
720
        error_report("could not open disk image %s: %s",
721
                     file ?: dinfo->id, error_get_pretty(error));
722
        goto err;
723
    }
724

    
725
    if (bdrv_key_required(dinfo->bdrv))
726
        autostart = 0;
727

    
728
    QDECREF(bs_opts);
729
    qemu_opts_del(opts);
730

    
731
    return dinfo;
732

    
733
err:
734
    qemu_opts_del(opts);
735
    QDECREF(bs_opts);
736
    bdrv_unref(dinfo->bdrv);
737
    g_free(dinfo->id);
738
    QTAILQ_REMOVE(&drives, dinfo, next);
739
    g_free(dinfo);
740
    return NULL;
741
}
742

    
743
static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to)
744
{
745
    const char *value;
746

    
747
    value = qemu_opt_get(opts, from);
748
    if (value) {
749
        qemu_opt_set(opts, to, value);
750
        qemu_opt_unset(opts, from);
751
    }
752
}
753

    
754
DriveInfo *drive_init(QemuOpts *all_opts, BlockInterfaceType block_default_type)
755
{
756
    const char *value;
757
    DriveInfo *dinfo;
758
    QDict *bs_opts;
759

    
760
    /* Change legacy command line options into QMP ones */
761
    qemu_opt_rename(all_opts, "iops", "throttling.iops-total");
762
    qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read");
763
    qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write");
764

    
765
    qemu_opt_rename(all_opts, "bps", "throttling.bps-total");
766
    qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read");
767
    qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write");
768

    
769
    qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max");
770
    qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max");
771
    qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max");
772

    
773
    qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max");
774
    qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max");
775
    qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max");
776

    
777
    qemu_opt_rename(all_opts,
778
                    "iops_size", "throttling.iops-size");
779

    
780
    qemu_opt_rename(all_opts, "readonly", "read-only");
781

    
782
    value = qemu_opt_get(all_opts, "cache");
783
    if (value) {
784
        int flags = 0;
785

    
786
        if (bdrv_parse_cache_flags(value, &flags) != 0) {
787
            error_report("invalid cache option");
788
            return NULL;
789
        }
790

    
791
        /* Specific options take precedence */
792
        if (!qemu_opt_get(all_opts, "cache.writeback")) {
793
            qemu_opt_set_bool(all_opts, "cache.writeback",
794
                              !!(flags & BDRV_O_CACHE_WB));
795
        }
796
        if (!qemu_opt_get(all_opts, "cache.direct")) {
797
            qemu_opt_set_bool(all_opts, "cache.direct",
798
                              !!(flags & BDRV_O_NOCACHE));
799
        }
800
        if (!qemu_opt_get(all_opts, "cache.no-flush")) {
801
            qemu_opt_set_bool(all_opts, "cache.no-flush",
802
                              !!(flags & BDRV_O_NO_FLUSH));
803
        }
804
        qemu_opt_unset(all_opts, "cache");
805
    }
806

    
807
    /* Get a QDict for processing the options */
808
    bs_opts = qdict_new();
809
    qemu_opts_to_qdict(all_opts, bs_opts);
810

    
811
    /* Actual block device init: Functionality shared with blockdev-add */
812
    dinfo = blockdev_init(bs_opts, block_default_type);
813
    if (dinfo == NULL) {
814
        goto fail;
815
    }
816

    
817
    /* Set legacy DriveInfo fields */
818
    dinfo->enable_auto_del = true;
819
    dinfo->opts = all_opts;
820

    
821
fail:
822
    return dinfo;
823
}
824

    
825
void do_commit(Monitor *mon, const QDict *qdict)
826
{
827
    const char *device = qdict_get_str(qdict, "device");
828
    BlockDriverState *bs;
829
    int ret;
830

    
831
    if (!strcmp(device, "all")) {
832
        ret = bdrv_commit_all();
833
    } else {
834
        bs = bdrv_find(device);
835
        if (!bs) {
836
            monitor_printf(mon, "Device '%s' not found\n", device);
837
            return;
838
        }
839
        ret = bdrv_commit(bs);
840
    }
841
    if (ret < 0) {
842
        monitor_printf(mon, "'commit' error for '%s': %s\n", device,
843
                       strerror(-ret));
844
    }
845
}
846

    
847
static void blockdev_do_action(int kind, void *data, Error **errp)
848
{
849
    TransactionAction action;
850
    TransactionActionList list;
851

    
852
    action.kind = kind;
853
    action.data = data;
854
    list.value = &action;
855
    list.next = NULL;
856
    qmp_transaction(&list, errp);
857
}
858

    
859
void qmp_blockdev_snapshot_sync(const char *device, const char *snapshot_file,
860
                                bool has_format, const char *format,
861
                                bool has_mode, enum NewImageMode mode,
862
                                Error **errp)
863
{
864
    BlockdevSnapshot snapshot = {
865
        .device = (char *) device,
866
        .snapshot_file = (char *) snapshot_file,
867
        .has_format = has_format,
868
        .format = (char *) format,
869
        .has_mode = has_mode,
870
        .mode = mode,
871
    };
872
    blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
873
                       &snapshot, errp);
874
}
875

    
876
void qmp_blockdev_snapshot_internal_sync(const char *device,
877
                                         const char *name,
878
                                         Error **errp)
879
{
880
    BlockdevSnapshotInternal snapshot = {
881
        .device = (char *) device,
882
        .name = (char *) name
883
    };
884

    
885
    blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
886
                       &snapshot, errp);
887
}
888

    
889
SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
890
                                                         bool has_id,
891
                                                         const char *id,
892
                                                         bool has_name,
893
                                                         const char *name,
894
                                                         Error **errp)
895
{
896
    BlockDriverState *bs = bdrv_find(device);
897
    QEMUSnapshotInfo sn;
898
    Error *local_err = NULL;
899
    SnapshotInfo *info = NULL;
900
    int ret;
901

    
902
    if (!bs) {
903
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
904
        return NULL;
905
    }
906

    
907
    if (!has_id) {
908
        id = NULL;
909
    }
910

    
911
    if (!has_name) {
912
        name = NULL;
913
    }
914

    
915
    if (!id && !name) {
916
        error_setg(errp, "Name or id must be provided");
917
        return NULL;
918
    }
919

    
920
    ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
921
    if (error_is_set(&local_err)) {
922
        error_propagate(errp, local_err);
923
        return NULL;
924
    }
925
    if (!ret) {
926
        error_setg(errp,
927
                   "Snapshot with id '%s' and name '%s' does not exist on "
928
                   "device '%s'",
929
                   STR_OR_NULL(id), STR_OR_NULL(name), device);
930
        return NULL;
931
    }
932

    
933
    bdrv_snapshot_delete(bs, id, name, &local_err);
934
    if (error_is_set(&local_err)) {
935
        error_propagate(errp, local_err);
936
        return NULL;
937
    }
938

    
939
    info = g_malloc0(sizeof(SnapshotInfo));
940
    info->id = g_strdup(sn.id_str);
941
    info->name = g_strdup(sn.name);
942
    info->date_nsec = sn.date_nsec;
943
    info->date_sec = sn.date_sec;
944
    info->vm_state_size = sn.vm_state_size;
945
    info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
946
    info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
947

    
948
    return info;
949
}
950

    
951
/* New and old BlockDriverState structs for group snapshots */
952

    
953
typedef struct BlkTransactionState BlkTransactionState;
954

    
955
/* Only prepare() may fail. In a single transaction, only one of commit() or
956
   abort() will be called, clean() will always be called if it present. */
957
typedef struct BdrvActionOps {
958
    /* Size of state struct, in bytes. */
959
    size_t instance_size;
960
    /* Prepare the work, must NOT be NULL. */
961
    void (*prepare)(BlkTransactionState *common, Error **errp);
962
    /* Commit the changes, can be NULL. */
963
    void (*commit)(BlkTransactionState *common);
964
    /* Abort the changes on fail, can be NULL. */
965
    void (*abort)(BlkTransactionState *common);
966
    /* Clean up resource in the end, can be NULL. */
967
    void (*clean)(BlkTransactionState *common);
968
} BdrvActionOps;
969

    
970
/*
971
 * This structure must be arranged as first member in child type, assuming
972
 * that compiler will also arrange it to the same address with parent instance.
973
 * Later it will be used in free().
974
 */
975
struct BlkTransactionState {
976
    TransactionAction *action;
977
    const BdrvActionOps *ops;
978
    QSIMPLEQ_ENTRY(BlkTransactionState) entry;
979
};
980

    
981
/* internal snapshot private data */
982
typedef struct InternalSnapshotState {
983
    BlkTransactionState common;
984
    BlockDriverState *bs;
985
    QEMUSnapshotInfo sn;
986
} InternalSnapshotState;
987

    
988
static void internal_snapshot_prepare(BlkTransactionState *common,
989
                                      Error **errp)
990
{
991
    const char *device;
992
    const char *name;
993
    BlockDriverState *bs;
994
    QEMUSnapshotInfo old_sn, *sn;
995
    bool ret;
996
    qemu_timeval tv;
997
    BlockdevSnapshotInternal *internal;
998
    InternalSnapshotState *state;
999
    int ret1;
1000

    
1001
    g_assert(common->action->kind ==
1002
             TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1003
    internal = common->action->blockdev_snapshot_internal_sync;
1004
    state = DO_UPCAST(InternalSnapshotState, common, common);
1005

    
1006
    /* 1. parse input */
1007
    device = internal->device;
1008
    name = internal->name;
1009

    
1010
    /* 2. check for validation */
1011
    bs = bdrv_find(device);
1012
    if (!bs) {
1013
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1014
        return;
1015
    }
1016

    
1017
    if (!bdrv_is_inserted(bs)) {
1018
        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1019
        return;
1020
    }
1021

    
1022
    if (bdrv_is_read_only(bs)) {
1023
        error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1024
        return;
1025
    }
1026

    
1027
    if (!bdrv_can_snapshot(bs)) {
1028
        error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1029
                  bs->drv->format_name, device, "internal snapshot");
1030
        return;
1031
    }
1032

    
1033
    if (!strlen(name)) {
1034
        error_setg(errp, "Name is empty");
1035
        return;
1036
    }
1037

    
1038
    /* check whether a snapshot with name exist */
1039
    ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn, errp);
1040
    if (error_is_set(errp)) {
1041
        return;
1042
    } else if (ret) {
1043
        error_setg(errp,
1044
                   "Snapshot with name '%s' already exists on device '%s'",
1045
                   name, device);
1046
        return;
1047
    }
1048

    
1049
    /* 3. take the snapshot */
1050
    sn = &state->sn;
1051
    pstrcpy(sn->name, sizeof(sn->name), name);
1052
    qemu_gettimeofday(&tv);
1053
    sn->date_sec = tv.tv_sec;
1054
    sn->date_nsec = tv.tv_usec * 1000;
1055
    sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1056

    
1057
    ret1 = bdrv_snapshot_create(bs, sn);
1058
    if (ret1 < 0) {
1059
        error_setg_errno(errp, -ret1,
1060
                         "Failed to create snapshot '%s' on device '%s'",
1061
                         name, device);
1062
        return;
1063
    }
1064

    
1065
    /* 4. succeed, mark a snapshot is created */
1066
    state->bs = bs;
1067
}
1068

    
1069
static void internal_snapshot_abort(BlkTransactionState *common)
1070
{
1071
    InternalSnapshotState *state =
1072
                             DO_UPCAST(InternalSnapshotState, common, common);
1073
    BlockDriverState *bs = state->bs;
1074
    QEMUSnapshotInfo *sn = &state->sn;
1075
    Error *local_error = NULL;
1076

    
1077
    if (!bs) {
1078
        return;
1079
    }
1080

    
1081
    if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1082
        error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1083
                     "device '%s' in abort: %s",
1084
                     sn->id_str,
1085
                     sn->name,
1086
                     bdrv_get_device_name(bs),
1087
                     error_get_pretty(local_error));
1088
        error_free(local_error);
1089
    }
1090
}
1091

    
1092
/* external snapshot private data */
1093
typedef struct ExternalSnapshotState {
1094
    BlkTransactionState common;
1095
    BlockDriverState *old_bs;
1096
    BlockDriverState *new_bs;
1097
} ExternalSnapshotState;
1098

    
1099
static void external_snapshot_prepare(BlkTransactionState *common,
1100
                                      Error **errp)
1101
{
1102
    BlockDriver *drv;
1103
    int flags, ret;
1104
    Error *local_err = NULL;
1105
    const char *device;
1106
    const char *new_image_file;
1107
    const char *format = "qcow2";
1108
    enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1109
    ExternalSnapshotState *state =
1110
                             DO_UPCAST(ExternalSnapshotState, common, common);
1111
    TransactionAction *action = common->action;
1112

    
1113
    /* get parameters */
1114
    g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1115

    
1116
    device = action->blockdev_snapshot_sync->device;
1117
    new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1118
    if (action->blockdev_snapshot_sync->has_format) {
1119
        format = action->blockdev_snapshot_sync->format;
1120
    }
1121
    if (action->blockdev_snapshot_sync->has_mode) {
1122
        mode = action->blockdev_snapshot_sync->mode;
1123
    }
1124

    
1125
    /* start processing */
1126
    drv = bdrv_find_format(format);
1127
    if (!drv) {
1128
        error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1129
        return;
1130
    }
1131

    
1132
    state->old_bs = bdrv_find(device);
1133
    if (!state->old_bs) {
1134
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1135
        return;
1136
    }
1137

    
1138
    if (!bdrv_is_inserted(state->old_bs)) {
1139
        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1140
        return;
1141
    }
1142

    
1143
    if (bdrv_in_use(state->old_bs)) {
1144
        error_set(errp, QERR_DEVICE_IN_USE, device);
1145
        return;
1146
    }
1147

    
1148
    if (!bdrv_is_read_only(state->old_bs)) {
1149
        if (bdrv_flush(state->old_bs)) {
1150
            error_set(errp, QERR_IO_ERROR);
1151
            return;
1152
        }
1153
    }
1154

    
1155
    if (bdrv_check_ext_snapshot(state->old_bs) != EXT_SNAPSHOT_ALLOWED) {
1156
        error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1157
        return;
1158
    }
1159

    
1160
    flags = state->old_bs->open_flags;
1161

    
1162
    /* create new image w/backing file */
1163
    if (mode != NEW_IMAGE_MODE_EXISTING) {
1164
        bdrv_img_create(new_image_file, format,
1165
                        state->old_bs->filename,
1166
                        state->old_bs->drv->format_name,
1167
                        NULL, -1, flags, &local_err, false);
1168
        if (error_is_set(&local_err)) {
1169
            error_propagate(errp, local_err);
1170
            return;
1171
        }
1172
    }
1173

    
1174
    /* We will manually add the backing_hd field to the bs later */
1175
    state->new_bs = bdrv_new("");
1176
    /* TODO Inherit bs->options or only take explicit options with an
1177
     * extended QMP command? */
1178
    ret = bdrv_open(state->new_bs, new_image_file, NULL,
1179
                    flags | BDRV_O_NO_BACKING, drv, &local_err);
1180
    if (ret != 0) {
1181
        error_propagate(errp, local_err);
1182
    }
1183
}
1184

    
1185
static void external_snapshot_commit(BlkTransactionState *common)
1186
{
1187
    ExternalSnapshotState *state =
1188
                             DO_UPCAST(ExternalSnapshotState, common, common);
1189

    
1190
    /* This removes our old bs and adds the new bs */
1191
    bdrv_append(state->new_bs, state->old_bs);
1192
    /* We don't need (or want) to use the transactional
1193
     * bdrv_reopen_multiple() across all the entries at once, because we
1194
     * don't want to abort all of them if one of them fails the reopen */
1195
    bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1196
                NULL);
1197
}
1198

    
1199
static void external_snapshot_abort(BlkTransactionState *common)
1200
{
1201
    ExternalSnapshotState *state =
1202
                             DO_UPCAST(ExternalSnapshotState, common, common);
1203
    if (state->new_bs) {
1204
        bdrv_unref(state->new_bs);
1205
    }
1206
}
1207

    
1208
typedef struct DriveBackupState {
1209
    BlkTransactionState common;
1210
    BlockDriverState *bs;
1211
    BlockJob *job;
1212
} DriveBackupState;
1213

    
1214
static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1215
{
1216
    DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1217
    DriveBackup *backup;
1218
    Error *local_err = NULL;
1219

    
1220
    assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1221
    backup = common->action->drive_backup;
1222

    
1223
    qmp_drive_backup(backup->device, backup->target,
1224
                     backup->has_format, backup->format,
1225
                     backup->sync,
1226
                     backup->has_mode, backup->mode,
1227
                     backup->has_speed, backup->speed,
1228
                     backup->has_on_source_error, backup->on_source_error,
1229
                     backup->has_on_target_error, backup->on_target_error,
1230
                     &local_err);
1231
    if (error_is_set(&local_err)) {
1232
        error_propagate(errp, local_err);
1233
        state->bs = NULL;
1234
        state->job = NULL;
1235
        return;
1236
    }
1237

    
1238
    state->bs = bdrv_find(backup->device);
1239
    state->job = state->bs->job;
1240
}
1241

    
1242
static void drive_backup_abort(BlkTransactionState *common)
1243
{
1244
    DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1245
    BlockDriverState *bs = state->bs;
1246

    
1247
    /* Only cancel if it's the job we started */
1248
    if (bs && bs->job && bs->job == state->job) {
1249
        block_job_cancel_sync(bs->job);
1250
    }
1251
}
1252

    
1253
static void abort_prepare(BlkTransactionState *common, Error **errp)
1254
{
1255
    error_setg(errp, "Transaction aborted using Abort action");
1256
}
1257

    
1258
static void abort_commit(BlkTransactionState *common)
1259
{
1260
    g_assert_not_reached(); /* this action never succeeds */
1261
}
1262

    
1263
static const BdrvActionOps actions[] = {
1264
    [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1265
        .instance_size = sizeof(ExternalSnapshotState),
1266
        .prepare  = external_snapshot_prepare,
1267
        .commit   = external_snapshot_commit,
1268
        .abort = external_snapshot_abort,
1269
    },
1270
    [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1271
        .instance_size = sizeof(DriveBackupState),
1272
        .prepare = drive_backup_prepare,
1273
        .abort = drive_backup_abort,
1274
    },
1275
    [TRANSACTION_ACTION_KIND_ABORT] = {
1276
        .instance_size = sizeof(BlkTransactionState),
1277
        .prepare = abort_prepare,
1278
        .commit = abort_commit,
1279
    },
1280
    [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1281
        .instance_size = sizeof(InternalSnapshotState),
1282
        .prepare  = internal_snapshot_prepare,
1283
        .abort = internal_snapshot_abort,
1284
    },
1285
};
1286

    
1287
/*
1288
 * 'Atomic' group snapshots.  The snapshots are taken as a set, and if any fail
1289
 *  then we do not pivot any of the devices in the group, and abandon the
1290
 *  snapshots
1291
 */
1292
void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1293
{
1294
    TransactionActionList *dev_entry = dev_list;
1295
    BlkTransactionState *state, *next;
1296
    Error *local_err = NULL;
1297

    
1298
    QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1299
    QSIMPLEQ_INIT(&snap_bdrv_states);
1300

    
1301
    /* drain all i/o before any snapshots */
1302
    bdrv_drain_all();
1303

    
1304
    /* We don't do anything in this loop that commits us to the snapshot */
1305
    while (NULL != dev_entry) {
1306
        TransactionAction *dev_info = NULL;
1307
        const BdrvActionOps *ops;
1308

    
1309
        dev_info = dev_entry->value;
1310
        dev_entry = dev_entry->next;
1311

    
1312
        assert(dev_info->kind < ARRAY_SIZE(actions));
1313

    
1314
        ops = &actions[dev_info->kind];
1315
        assert(ops->instance_size > 0);
1316

    
1317
        state = g_malloc0(ops->instance_size);
1318
        state->ops = ops;
1319
        state->action = dev_info;
1320
        QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1321

    
1322
        state->ops->prepare(state, &local_err);
1323
        if (error_is_set(&local_err)) {
1324
            error_propagate(errp, local_err);
1325
            goto delete_and_fail;
1326
        }
1327
    }
1328

    
1329
    QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1330
        if (state->ops->commit) {
1331
            state->ops->commit(state);
1332
        }
1333
    }
1334

    
1335
    /* success */
1336
    goto exit;
1337

    
1338
delete_and_fail:
1339
    /*
1340
    * failure, and it is all-or-none; abandon each new bs, and keep using
1341
    * the original bs for all images
1342
    */
1343
    QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1344
        if (state->ops->abort) {
1345
            state->ops->abort(state);
1346
        }
1347
    }
1348
exit:
1349
    QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1350
        if (state->ops->clean) {
1351
            state->ops->clean(state);
1352
        }
1353
        g_free(state);
1354
    }
1355
}
1356

    
1357

    
1358
static void eject_device(BlockDriverState *bs, int force, Error **errp)
1359
{
1360
    if (bdrv_in_use(bs)) {
1361
        error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
1362
        return;
1363
    }
1364
    if (!bdrv_dev_has_removable_media(bs)) {
1365
        error_set(errp, QERR_DEVICE_NOT_REMOVABLE, bdrv_get_device_name(bs));
1366
        return;
1367
    }
1368

    
1369
    if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1370
        bdrv_dev_eject_request(bs, force);
1371
        if (!force) {
1372
            error_set(errp, QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
1373
            return;
1374
        }
1375
    }
1376

    
1377
    bdrv_close(bs);
1378
}
1379

    
1380
void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1381
{
1382
    BlockDriverState *bs;
1383

    
1384
    bs = bdrv_find(device);
1385
    if (!bs) {
1386
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1387
        return;
1388
    }
1389

    
1390
    eject_device(bs, force, errp);
1391
}
1392

    
1393
void qmp_block_passwd(const char *device, const char *password, Error **errp)
1394
{
1395
    BlockDriverState *bs;
1396
    int err;
1397

    
1398
    bs = bdrv_find(device);
1399
    if (!bs) {
1400
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1401
        return;
1402
    }
1403

    
1404
    err = bdrv_set_key(bs, password);
1405
    if (err == -EINVAL) {
1406
        error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1407
        return;
1408
    } else if (err < 0) {
1409
        error_set(errp, QERR_INVALID_PASSWORD);
1410
        return;
1411
    }
1412
}
1413

    
1414
static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1415
                                    int bdrv_flags, BlockDriver *drv,
1416
                                    const char *password, Error **errp)
1417
{
1418
    Error *local_err = NULL;
1419
    int ret;
1420

    
1421
    ret = bdrv_open(bs, filename, NULL, bdrv_flags, drv, &local_err);
1422
    if (ret < 0) {
1423
        error_propagate(errp, local_err);
1424
        return;
1425
    }
1426

    
1427
    if (bdrv_key_required(bs)) {
1428
        if (password) {
1429
            if (bdrv_set_key(bs, password) < 0) {
1430
                error_set(errp, QERR_INVALID_PASSWORD);
1431
            }
1432
        } else {
1433
            error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1434
                      bdrv_get_encrypted_filename(bs));
1435
        }
1436
    } else if (password) {
1437
        error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1438
    }
1439
}
1440

    
1441
void qmp_change_blockdev(const char *device, const char *filename,
1442
                         bool has_format, const char *format, Error **errp)
1443
{
1444
    BlockDriverState *bs;
1445
    BlockDriver *drv = NULL;
1446
    int bdrv_flags;
1447
    Error *err = NULL;
1448

    
1449
    bs = bdrv_find(device);
1450
    if (!bs) {
1451
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1452
        return;
1453
    }
1454

    
1455
    if (format) {
1456
        drv = bdrv_find_whitelisted_format(format, bs->read_only);
1457
        if (!drv) {
1458
            error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1459
            return;
1460
        }
1461
    }
1462

    
1463
    eject_device(bs, 0, &err);
1464
    if (error_is_set(&err)) {
1465
        error_propagate(errp, err);
1466
        return;
1467
    }
1468

    
1469
    bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1470
    bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1471

    
1472
    qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1473
}
1474

    
1475
/* throttling disk I/O limits */
1476
void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1477
                               int64_t bps_wr,
1478
                               int64_t iops,
1479
                               int64_t iops_rd,
1480
                               int64_t iops_wr,
1481
                               bool has_bps_max,
1482
                               int64_t bps_max,
1483
                               bool has_bps_rd_max,
1484
                               int64_t bps_rd_max,
1485
                               bool has_bps_wr_max,
1486
                               int64_t bps_wr_max,
1487
                               bool has_iops_max,
1488
                               int64_t iops_max,
1489
                               bool has_iops_rd_max,
1490
                               int64_t iops_rd_max,
1491
                               bool has_iops_wr_max,
1492
                               int64_t iops_wr_max,
1493
                               bool has_iops_size,
1494
                               int64_t iops_size, Error **errp)
1495
{
1496
    ThrottleConfig cfg;
1497
    BlockDriverState *bs;
1498

    
1499
    bs = bdrv_find(device);
1500
    if (!bs) {
1501
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1502
        return;
1503
    }
1504

    
1505
    memset(&cfg, 0, sizeof(cfg));
1506
    cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1507
    cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;
1508
    cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1509

    
1510
    cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1511
    cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;
1512
    cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1513

    
1514
    if (has_bps_max) {
1515
        cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1516
    }
1517
    if (has_bps_rd_max) {
1518
        cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1519
    }
1520
    if (has_bps_wr_max) {
1521
        cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1522
    }
1523
    if (has_iops_max) {
1524
        cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1525
    }
1526
    if (has_iops_rd_max) {
1527
        cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1528
    }
1529
    if (has_iops_wr_max) {
1530
        cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1531
    }
1532

    
1533
    if (has_iops_size) {
1534
        cfg.op_size = iops_size;
1535
    }
1536

    
1537
    if (!check_throttle_config(&cfg, errp)) {
1538
        return;
1539
    }
1540

    
1541
    if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1542
        bdrv_io_limits_enable(bs);
1543
    } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1544
        bdrv_io_limits_disable(bs);
1545
    }
1546

    
1547
    if (bs->io_limits_enabled) {
1548
        bdrv_set_io_limits(bs, &cfg);
1549
    }
1550
}
1551

    
1552
int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1553
{
1554
    const char *id = qdict_get_str(qdict, "id");
1555
    BlockDriverState *bs;
1556

    
1557
    bs = bdrv_find(id);
1558
    if (!bs) {
1559
        qerror_report(QERR_DEVICE_NOT_FOUND, id);
1560
        return -1;
1561
    }
1562
    if (bdrv_in_use(bs)) {
1563
        qerror_report(QERR_DEVICE_IN_USE, id);
1564
        return -1;
1565
    }
1566

    
1567
    /* quiesce block driver; prevent further io */
1568
    bdrv_drain_all();
1569
    bdrv_flush(bs);
1570
    bdrv_close(bs);
1571

    
1572
    /* if we have a device attached to this BlockDriverState
1573
     * then we need to make the drive anonymous until the device
1574
     * can be removed.  If this is a drive with no device backing
1575
     * then we can just get rid of the block driver state right here.
1576
     */
1577
    if (bdrv_get_attached_dev(bs)) {
1578
        bdrv_make_anon(bs);
1579

    
1580
        /* Further I/O must not pause the guest */
1581
        bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1582
                          BLOCKDEV_ON_ERROR_REPORT);
1583
    } else {
1584
        drive_uninit(drive_get_by_blockdev(bs));
1585
    }
1586

    
1587
    return 0;
1588
}
1589

    
1590
void qmp_block_resize(const char *device, int64_t size, Error **errp)
1591
{
1592
    BlockDriverState *bs;
1593
    int ret;
1594

    
1595
    bs = bdrv_find(device);
1596
    if (!bs) {
1597
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1598
        return;
1599
    }
1600

    
1601
    if (size < 0) {
1602
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1603
        return;
1604
    }
1605

    
1606
    /* complete all in-flight operations before resizing the device */
1607
    bdrv_drain_all();
1608

    
1609
    ret = bdrv_truncate(bs, size);
1610
    switch (ret) {
1611
    case 0:
1612
        break;
1613
    case -ENOMEDIUM:
1614
        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1615
        break;
1616
    case -ENOTSUP:
1617
        error_set(errp, QERR_UNSUPPORTED);
1618
        break;
1619
    case -EACCES:
1620
        error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1621
        break;
1622
    case -EBUSY:
1623
        error_set(errp, QERR_DEVICE_IN_USE, device);
1624
        break;
1625
    default:
1626
        error_setg_errno(errp, -ret, "Could not resize");
1627
        break;
1628
    }
1629
}
1630

    
1631
static void block_job_cb(void *opaque, int ret)
1632
{
1633
    BlockDriverState *bs = opaque;
1634
    QObject *obj;
1635

    
1636
    trace_block_job_cb(bs, bs->job, ret);
1637

    
1638
    assert(bs->job);
1639
    obj = qobject_from_block_job(bs->job);
1640
    if (ret < 0) {
1641
        QDict *dict = qobject_to_qdict(obj);
1642
        qdict_put(dict, "error", qstring_from_str(strerror(-ret)));
1643
    }
1644

    
1645
    if (block_job_is_cancelled(bs->job)) {
1646
        monitor_protocol_event(QEVENT_BLOCK_JOB_CANCELLED, obj);
1647
    } else {
1648
        monitor_protocol_event(QEVENT_BLOCK_JOB_COMPLETED, obj);
1649
    }
1650
    qobject_decref(obj);
1651

    
1652
    bdrv_put_ref_bh_schedule(bs);
1653
}
1654

    
1655
void qmp_block_stream(const char *device, bool has_base,
1656
                      const char *base, bool has_speed, int64_t speed,
1657
                      bool has_on_error, BlockdevOnError on_error,
1658
                      Error **errp)
1659
{
1660
    BlockDriverState *bs;
1661
    BlockDriverState *base_bs = NULL;
1662
    Error *local_err = NULL;
1663

    
1664
    if (!has_on_error) {
1665
        on_error = BLOCKDEV_ON_ERROR_REPORT;
1666
    }
1667

    
1668
    bs = bdrv_find(device);
1669
    if (!bs) {
1670
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1671
        return;
1672
    }
1673

    
1674
    if (base) {
1675
        base_bs = bdrv_find_backing_image(bs, base);
1676
        if (base_bs == NULL) {
1677
            error_set(errp, QERR_BASE_NOT_FOUND, base);
1678
            return;
1679
        }
1680
    }
1681

    
1682
    stream_start(bs, base_bs, base, has_speed ? speed : 0,
1683
                 on_error, block_job_cb, bs, &local_err);
1684
    if (error_is_set(&local_err)) {
1685
        error_propagate(errp, local_err);
1686
        return;
1687
    }
1688

    
1689
    trace_qmp_block_stream(bs, bs->job);
1690
}
1691

    
1692
void qmp_block_commit(const char *device,
1693
                      bool has_base, const char *base, const char *top,
1694
                      bool has_speed, int64_t speed,
1695
                      Error **errp)
1696
{
1697
    BlockDriverState *bs;
1698
    BlockDriverState *base_bs, *top_bs;
1699
    Error *local_err = NULL;
1700
    /* This will be part of the QMP command, if/when the
1701
     * BlockdevOnError change for blkmirror makes it in
1702
     */
1703
    BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1704

    
1705
    /* drain all i/o before commits */
1706
    bdrv_drain_all();
1707

    
1708
    bs = bdrv_find(device);
1709
    if (!bs) {
1710
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1711
        return;
1712
    }
1713

    
1714
    /* default top_bs is the active layer */
1715
    top_bs = bs;
1716

    
1717
    if (top) {
1718
        if (strcmp(bs->filename, top) != 0) {
1719
            top_bs = bdrv_find_backing_image(bs, top);
1720
        }
1721
    }
1722

    
1723
    if (top_bs == NULL) {
1724
        error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1725
        return;
1726
    }
1727

    
1728
    if (has_base && base) {
1729
        base_bs = bdrv_find_backing_image(top_bs, base);
1730
    } else {
1731
        base_bs = bdrv_find_base(top_bs);
1732
    }
1733

    
1734
    if (base_bs == NULL) {
1735
        error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1736
        return;
1737
    }
1738

    
1739
    commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
1740
                &local_err);
1741
    if (local_err != NULL) {
1742
        error_propagate(errp, local_err);
1743
        return;
1744
    }
1745
}
1746

    
1747
void qmp_drive_backup(const char *device, const char *target,
1748
                      bool has_format, const char *format,
1749
                      enum MirrorSyncMode sync,
1750
                      bool has_mode, enum NewImageMode mode,
1751
                      bool has_speed, int64_t speed,
1752
                      bool has_on_source_error, BlockdevOnError on_source_error,
1753
                      bool has_on_target_error, BlockdevOnError on_target_error,
1754
                      Error **errp)
1755
{
1756
    BlockDriverState *bs;
1757
    BlockDriverState *target_bs;
1758
    BlockDriverState *source = NULL;
1759
    BlockDriver *drv = NULL;
1760
    Error *local_err = NULL;
1761
    int flags;
1762
    int64_t size;
1763
    int ret;
1764

    
1765
    if (!has_speed) {
1766
        speed = 0;
1767
    }
1768
    if (!has_on_source_error) {
1769
        on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1770
    }
1771
    if (!has_on_target_error) {
1772
        on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1773
    }
1774
    if (!has_mode) {
1775
        mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1776
    }
1777

    
1778
    bs = bdrv_find(device);
1779
    if (!bs) {
1780
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1781
        return;
1782
    }
1783

    
1784
    if (!bdrv_is_inserted(bs)) {
1785
        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1786
        return;
1787
    }
1788

    
1789
    if (!has_format) {
1790
        format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
1791
    }
1792
    if (format) {
1793
        drv = bdrv_find_format(format);
1794
        if (!drv) {
1795
            error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1796
            return;
1797
        }
1798
    }
1799

    
1800
    if (bdrv_in_use(bs)) {
1801
        error_set(errp, QERR_DEVICE_IN_USE, device);
1802
        return;
1803
    }
1804

    
1805
    flags = bs->open_flags | BDRV_O_RDWR;
1806

    
1807
    /* See if we have a backing HD we can use to create our new image
1808
     * on top of. */
1809
    if (sync == MIRROR_SYNC_MODE_TOP) {
1810
        source = bs->backing_hd;
1811
        if (!source) {
1812
            sync = MIRROR_SYNC_MODE_FULL;
1813
        }
1814
    }
1815
    if (sync == MIRROR_SYNC_MODE_NONE) {
1816
        source = bs;
1817
    }
1818

    
1819
    size = bdrv_getlength(bs);
1820
    if (size < 0) {
1821
        error_setg_errno(errp, -size, "bdrv_getlength failed");
1822
        return;
1823
    }
1824

    
1825
    if (mode != NEW_IMAGE_MODE_EXISTING) {
1826
        assert(format && drv);
1827
        if (source) {
1828
            bdrv_img_create(target, format, source->filename,
1829
                            source->drv->format_name, NULL,
1830
                            size, flags, &local_err, false);
1831
        } else {
1832
            bdrv_img_create(target, format, NULL, NULL, NULL,
1833
                            size, flags, &local_err, false);
1834
        }
1835
    }
1836

    
1837
    if (error_is_set(&local_err)) {
1838
        error_propagate(errp, local_err);
1839
        return;
1840
    }
1841

    
1842
    target_bs = bdrv_new("");
1843
    ret = bdrv_open(target_bs, target, NULL, flags, drv, &local_err);
1844
    if (ret < 0) {
1845
        bdrv_unref(target_bs);
1846
        error_propagate(errp, local_err);
1847
        return;
1848
    }
1849

    
1850
    backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
1851
                 block_job_cb, bs, &local_err);
1852
    if (local_err != NULL) {
1853
        bdrv_unref(target_bs);
1854
        error_propagate(errp, local_err);
1855
        return;
1856
    }
1857
}
1858

    
1859
#define DEFAULT_MIRROR_BUF_SIZE   (10 << 20)
1860

    
1861
void qmp_drive_mirror(const char *device, const char *target,
1862
                      bool has_format, const char *format,
1863
                      enum MirrorSyncMode sync,
1864
                      bool has_mode, enum NewImageMode mode,
1865
                      bool has_speed, int64_t speed,
1866
                      bool has_granularity, uint32_t granularity,
1867
                      bool has_buf_size, int64_t buf_size,
1868
                      bool has_on_source_error, BlockdevOnError on_source_error,
1869
                      bool has_on_target_error, BlockdevOnError on_target_error,
1870
                      Error **errp)
1871
{
1872
    BlockDriverState *bs;
1873
    BlockDriverState *source, *target_bs;
1874
    BlockDriver *drv = NULL;
1875
    Error *local_err = NULL;
1876
    int flags;
1877
    int64_t size;
1878
    int ret;
1879

    
1880
    if (!has_speed) {
1881
        speed = 0;
1882
    }
1883
    if (!has_on_source_error) {
1884
        on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1885
    }
1886
    if (!has_on_target_error) {
1887
        on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1888
    }
1889
    if (!has_mode) {
1890
        mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1891
    }
1892
    if (!has_granularity) {
1893
        granularity = 0;
1894
    }
1895
    if (!has_buf_size) {
1896
        buf_size = DEFAULT_MIRROR_BUF_SIZE;
1897
    }
1898

    
1899
    if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
1900
        error_set(errp, QERR_INVALID_PARAMETER, device);
1901
        return;
1902
    }
1903
    if (granularity & (granularity - 1)) {
1904
        error_set(errp, QERR_INVALID_PARAMETER, device);
1905
        return;
1906
    }
1907

    
1908
    bs = bdrv_find(device);
1909
    if (!bs) {
1910
        error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1911
        return;
1912
    }
1913

    
1914
    if (!bdrv_is_inserted(bs)) {
1915
        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1916
        return;
1917
    }
1918

    
1919
    if (!has_format) {
1920
        format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
1921
    }
1922
    if (format) {
1923
        drv = bdrv_find_format(format);
1924
        if (!drv) {
1925
            error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1926
            return;
1927
        }
1928
    }
1929

    
1930
    if (bdrv_in_use(bs)) {
1931
        error_set(errp, QERR_DEVICE_IN_USE, device);
1932
        return;
1933
    }
1934

    
1935
    flags = bs->open_flags | BDRV_O_RDWR;
1936
    source = bs->backing_hd;
1937
    if (!source && sync == MIRROR_SYNC_MODE_TOP) {
1938
        sync = MIRROR_SYNC_MODE_FULL;
1939
    }
1940

    
1941
    size = bdrv_getlength(bs);
1942
    if (size < 0) {
1943
        error_setg_errno(errp, -size, "bdrv_getlength failed");
1944
        return;
1945
    }
1946

    
1947
    if (sync == MIRROR_SYNC_MODE_FULL && mode != NEW_IMAGE_MODE_EXISTING) {
1948
        /* create new image w/o backing file */
1949
        assert(format && drv);
1950
        bdrv_img_create(target, format,
1951
                        NULL, NULL, NULL, size, flags, &local_err, false);
1952
    } else {
1953
        switch (mode) {
1954
        case NEW_IMAGE_MODE_EXISTING:
1955
            break;
1956
        case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
1957
            /* create new image with backing file */
1958
            bdrv_img_create(target, format,
1959
                            source->filename,
1960
                            source->drv->format_name,
1961
                            NULL, size, flags, &local_err, false);
1962
            break;
1963
        default:
1964
            abort();
1965
        }
1966
    }
1967

    
1968
    if (error_is_set(&local_err)) {
1969
        error_propagate(errp, local_err);
1970
        return;
1971
    }
1972

    
1973
    /* Mirroring takes care of copy-on-write using the source's backing
1974
     * file.
1975
     */
1976
    target_bs = bdrv_new("");
1977
    ret = bdrv_open(target_bs, target, NULL, flags | BDRV_O_NO_BACKING, drv,
1978
                    &local_err);
1979
    if (ret < 0) {
1980
        bdrv_unref(target_bs);
1981
        error_propagate(errp, local_err);
1982
        return;
1983
    }
1984

    
1985
    mirror_start(bs, target_bs, speed, granularity, buf_size, sync,
1986
                 on_source_error, on_target_error,
1987
                 block_job_cb, bs, &local_err);
1988
    if (local_err != NULL) {
1989
        bdrv_unref(target_bs);
1990
        error_propagate(errp, local_err);
1991
        return;
1992
    }
1993
}
1994

    
1995
static BlockJob *find_block_job(const char *device)
1996
{
1997
    BlockDriverState *bs;
1998

    
1999
    bs = bdrv_find(device);
2000
    if (!bs || !bs->job) {
2001
        return NULL;
2002
    }
2003
    return bs->job;
2004
}
2005

    
2006
void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2007
{
2008
    BlockJob *job = find_block_job(device);
2009

    
2010
    if (!job) {
2011
        error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2012
        return;
2013
    }
2014

    
2015
    block_job_set_speed(job, speed, errp);
2016
}
2017

    
2018
void qmp_block_job_cancel(const char *device,
2019
                          bool has_force, bool force, Error **errp)
2020
{
2021
    BlockJob *job = find_block_job(device);
2022

    
2023
    if (!has_force) {
2024
        force = false;
2025
    }
2026

    
2027
    if (!job) {
2028
        error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2029
        return;
2030
    }
2031
    if (job->paused && !force) {
2032
        error_set(errp, QERR_BLOCK_JOB_PAUSED, device);
2033
        return;
2034
    }
2035

    
2036
    trace_qmp_block_job_cancel(job);
2037
    block_job_cancel(job);
2038
}
2039

    
2040
void qmp_block_job_pause(const char *device, Error **errp)
2041
{
2042
    BlockJob *job = find_block_job(device);
2043

    
2044
    if (!job) {
2045
        error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2046
        return;
2047
    }
2048

    
2049
    trace_qmp_block_job_pause(job);
2050
    block_job_pause(job);
2051
}
2052

    
2053
void qmp_block_job_resume(const char *device, Error **errp)
2054
{
2055
    BlockJob *job = find_block_job(device);
2056

    
2057
    if (!job) {
2058
        error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2059
        return;
2060
    }
2061

    
2062
    trace_qmp_block_job_resume(job);
2063
    block_job_resume(job);
2064
}
2065

    
2066
void qmp_block_job_complete(const char *device, Error **errp)
2067
{
2068
    BlockJob *job = find_block_job(device);
2069

    
2070
    if (!job) {
2071
        error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2072
        return;
2073
    }
2074

    
2075
    trace_qmp_block_job_complete(job);
2076
    block_job_complete(job, errp);
2077
}
2078

    
2079
void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2080
{
2081
    QmpOutputVisitor *ov = qmp_output_visitor_new();
2082
    QObject *obj;
2083
    QDict *qdict;
2084
    DriveInfo *dinfo;
2085
    Error *local_err = NULL;
2086

    
2087
    /* Require an ID in the top level */
2088
    if (!options->has_id) {
2089
        error_setg(errp, "Block device needs an ID");
2090
        goto fail;
2091
    }
2092

    
2093
    /* TODO Sort it out in raw-posix and drive_init: Reject aio=native with
2094
     * cache.direct=false instead of silently switching to aio=threads, except
2095
     * if called from drive_init.
2096
     *
2097
     * For now, simply forbidding the combination for all drivers will do. */
2098
    if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2099
        bool direct = options->cache->has_direct && options->cache->direct;
2100
        if (!options->has_cache && !direct) {
2101
            error_setg(errp, "aio=native requires cache.direct=true");
2102
            goto fail;
2103
        }
2104
    }
2105

    
2106
    visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2107
                               &options, NULL, &local_err);
2108
    if (error_is_set(&local_err)) {
2109
        error_propagate(errp, local_err);
2110
        goto fail;
2111
    }
2112

    
2113
    obj = qmp_output_get_qobject(ov);
2114
    qdict = qobject_to_qdict(obj);
2115

    
2116
    qdict_flatten(qdict);
2117

    
2118
    dinfo = blockdev_init(qdict, IF_NONE);
2119
    if (!dinfo) {
2120
        error_setg(errp, "Could not open image");
2121
        goto fail;
2122
    }
2123

    
2124
fail:
2125
    qmp_output_visitor_cleanup(ov);
2126
}
2127

    
2128
static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2129
{
2130
    BlockJobInfoList **prev = opaque;
2131
    BlockJob *job = bs->job;
2132

    
2133
    if (job) {
2134
        BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2135
        elem->value = block_job_query(bs->job);
2136
        (*prev)->next = elem;
2137
        *prev = elem;
2138
    }
2139
}
2140

    
2141
BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2142
{
2143
    /* Dummy is a fake list element for holding the head pointer */
2144
    BlockJobInfoList dummy = {};
2145
    BlockJobInfoList *prev = &dummy;
2146
    bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2147
    return dummy.next;
2148
}
2149

    
2150
QemuOptsList qemu_common_drive_opts = {
2151
    .name = "drive",
2152
    .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2153
    .desc = {
2154
        {
2155
            .name = "bus",
2156
            .type = QEMU_OPT_NUMBER,
2157
            .help = "bus number",
2158
        },{
2159
            .name = "unit",
2160
            .type = QEMU_OPT_NUMBER,
2161
            .help = "unit number (i.e. lun for scsi)",
2162
        },{
2163
            .name = "if",
2164
            .type = QEMU_OPT_STRING,
2165
            .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
2166
        },{
2167
            .name = "index",
2168
            .type = QEMU_OPT_NUMBER,
2169
            .help = "index number",
2170
        },{
2171
            .name = "cyls",
2172
            .type = QEMU_OPT_NUMBER,
2173
            .help = "number of cylinders (ide disk geometry)",
2174
        },{
2175
            .name = "heads",
2176
            .type = QEMU_OPT_NUMBER,
2177
            .help = "number of heads (ide disk geometry)",
2178
        },{
2179
            .name = "secs",
2180
            .type = QEMU_OPT_NUMBER,
2181
            .help = "number of sectors (ide disk geometry)",
2182
        },{
2183
            .name = "trans",
2184
            .type = QEMU_OPT_STRING,
2185
            .help = "chs translation (auto, lba. none)",
2186
        },{
2187
            .name = "media",
2188
            .type = QEMU_OPT_STRING,
2189
            .help = "media type (disk, cdrom)",
2190
        },{
2191
            .name = "snapshot",
2192
            .type = QEMU_OPT_BOOL,
2193
            .help = "enable/disable snapshot mode",
2194
        },{
2195
            .name = "file",
2196
            .type = QEMU_OPT_STRING,
2197
            .help = "disk image",
2198
        },{
2199
            .name = "discard",
2200
            .type = QEMU_OPT_STRING,
2201
            .help = "discard operation (ignore/off, unmap/on)",
2202
        },{
2203
            .name = "cache.writeback",
2204
            .type = QEMU_OPT_BOOL,
2205
            .help = "enables writeback mode for any caches",
2206
        },{
2207
            .name = "cache.direct",
2208
            .type = QEMU_OPT_BOOL,
2209
            .help = "enables use of O_DIRECT (bypass the host page cache)",
2210
        },{
2211
            .name = "cache.no-flush",
2212
            .type = QEMU_OPT_BOOL,
2213
            .help = "ignore any flush requests for the device",
2214
        },{
2215
            .name = "aio",
2216
            .type = QEMU_OPT_STRING,
2217
            .help = "host AIO implementation (threads, native)",
2218
        },{
2219
            .name = "format",
2220
            .type = QEMU_OPT_STRING,
2221
            .help = "disk format (raw, qcow2, ...)",
2222
        },{
2223
            .name = "serial",
2224
            .type = QEMU_OPT_STRING,
2225
            .help = "disk serial number",
2226
        },{
2227
            .name = "rerror",
2228
            .type = QEMU_OPT_STRING,
2229
            .help = "read error action",
2230
        },{
2231
            .name = "werror",
2232
            .type = QEMU_OPT_STRING,
2233
            .help = "write error action",
2234
        },{
2235
            .name = "addr",
2236
            .type = QEMU_OPT_STRING,
2237
            .help = "pci address (virtio only)",
2238
        },{
2239
            .name = "read-only",
2240
            .type = QEMU_OPT_BOOL,
2241
            .help = "open drive file as read-only",
2242
        },{
2243
            .name = "throttling.iops-total",
2244
            .type = QEMU_OPT_NUMBER,
2245
            .help = "limit total I/O operations per second",
2246
        },{
2247
            .name = "throttling.iops-read",
2248
            .type = QEMU_OPT_NUMBER,
2249
            .help = "limit read operations per second",
2250
        },{
2251
            .name = "throttling.iops-write",
2252
            .type = QEMU_OPT_NUMBER,
2253
            .help = "limit write operations per second",
2254
        },{
2255
            .name = "throttling.bps-total",
2256
            .type = QEMU_OPT_NUMBER,
2257
            .help = "limit total bytes per second",
2258
        },{
2259
            .name = "throttling.bps-read",
2260
            .type = QEMU_OPT_NUMBER,
2261
            .help = "limit read bytes per second",
2262
        },{
2263
            .name = "throttling.bps-write",
2264
            .type = QEMU_OPT_NUMBER,
2265
            .help = "limit write bytes per second",
2266
        },{
2267
            .name = "throttling.iops-total-max",
2268
            .type = QEMU_OPT_NUMBER,
2269
            .help = "I/O operations burst",
2270
        },{
2271
            .name = "throttling.iops-read-max",
2272
            .type = QEMU_OPT_NUMBER,
2273
            .help = "I/O operations read burst",
2274
        },{
2275
            .name = "throttling.iops-write-max",
2276
            .type = QEMU_OPT_NUMBER,
2277
            .help = "I/O operations write burst",
2278
        },{
2279
            .name = "throttling.bps-total-max",
2280
            .type = QEMU_OPT_NUMBER,
2281
            .help = "total bytes burst",
2282
        },{
2283
            .name = "throttling.bps-read-max",
2284
            .type = QEMU_OPT_NUMBER,
2285
            .help = "total bytes read burst",
2286
        },{
2287
            .name = "throttling.bps-write-max",
2288
            .type = QEMU_OPT_NUMBER,
2289
            .help = "total bytes write burst",
2290
        },{
2291
            .name = "throttling.iops-size",
2292
            .type = QEMU_OPT_NUMBER,
2293
            .help = "when limiting by iops max size of an I/O in bytes",
2294
        },{
2295
            .name = "copy-on-read",
2296
            .type = QEMU_OPT_BOOL,
2297
            .help = "copy read data from backing file into image file",
2298
        },{
2299
            .name = "boot",
2300
            .type = QEMU_OPT_BOOL,
2301
            .help = "(deprecated, ignored)",
2302
        },
2303
        { /* end of list */ }
2304
    },
2305
};
2306

    
2307
QemuOptsList qemu_drive_opts = {
2308
    .name = "drive",
2309
    .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2310
    .desc = {
2311
        /*
2312
         * no elements => accept any params
2313
         * validation will happen later
2314
         */
2315
        { /* end of list */ }
2316
    },
2317
};