xref: /openbmc/qemu/blockdev.c (revision 93c9aea9b42bedb65a03dbb3c6ff7dbfc43ef9a7)
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 "qemu/option.h"
38 #include "qemu/config-file.h"
39 #include "qapi/qmp/types.h"
40 #include "qapi-visit.h"
41 #include "qapi/qmp-output-visitor.h"
42 #include "qapi/util.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 
51 static const char *const if_name[IF_COUNT] = {
52     [IF_NONE] = "none",
53     [IF_IDE] = "ide",
54     [IF_SCSI] = "scsi",
55     [IF_FLOPPY] = "floppy",
56     [IF_PFLASH] = "pflash",
57     [IF_MTD] = "mtd",
58     [IF_SD] = "sd",
59     [IF_VIRTIO] = "virtio",
60     [IF_XEN] = "xen",
61 };
62 
63 static const int if_max_devs[IF_COUNT] = {
64     /*
65      * Do not change these numbers!  They govern how drive option
66      * index maps to unit and bus.  That mapping is ABI.
67      *
68      * All controllers used to imlement if=T drives need to support
69      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
70      * Otherwise, some index values map to "impossible" bus, unit
71      * values.
72      *
73      * For instance, if you change [IF_SCSI] to 255, -drive
74      * if=scsi,index=12 no longer means bus=1,unit=5, but
75      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
76      * the drive can't be set up.  Regression.
77      */
78     [IF_IDE] = 2,
79     [IF_SCSI] = 7,
80 };
81 
82 /*
83  * We automatically delete the drive when a device using it gets
84  * unplugged.  Questionable feature, but we can't just drop it.
85  * Device models call blockdev_mark_auto_del() to schedule the
86  * automatic deletion, and generic qdev code calls blockdev_auto_del()
87  * when deletion is actually safe.
88  */
89 void blockdev_mark_auto_del(BlockDriverState *bs)
90 {
91     DriveInfo *dinfo = drive_get_by_blockdev(bs);
92 
93     if (dinfo && !dinfo->enable_auto_del) {
94         return;
95     }
96 
97     if (bs->job) {
98         block_job_cancel(bs->job);
99     }
100     if (dinfo) {
101         dinfo->auto_del = 1;
102     }
103 }
104 
105 void blockdev_auto_del(BlockDriverState *bs)
106 {
107     DriveInfo *dinfo = drive_get_by_blockdev(bs);
108 
109     if (dinfo && dinfo->auto_del) {
110         drive_del(dinfo);
111     }
112 }
113 
114 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
115 {
116     int max_devs = if_max_devs[type];
117     return max_devs ? index / max_devs : 0;
118 }
119 
120 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
121 {
122     int max_devs = if_max_devs[type];
123     return max_devs ? index % max_devs : index;
124 }
125 
126 QemuOpts *drive_def(const char *optstr)
127 {
128     return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
129 }
130 
131 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
132                     const char *optstr)
133 {
134     QemuOpts *opts;
135     char buf[32];
136 
137     opts = drive_def(optstr);
138     if (!opts) {
139         return NULL;
140     }
141     if (type != IF_DEFAULT) {
142         qemu_opt_set(opts, "if", if_name[type]);
143     }
144     if (index >= 0) {
145         snprintf(buf, sizeof(buf), "%d", index);
146         qemu_opt_set(opts, "index", buf);
147     }
148     if (file)
149         qemu_opt_set(opts, "file", file);
150     return opts;
151 }
152 
153 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
154 {
155     DriveInfo *dinfo;
156 
157     /* seek interface, bus and unit */
158 
159     QTAILQ_FOREACH(dinfo, &drives, next) {
160         if (dinfo->type == type &&
161 	    dinfo->bus == bus &&
162 	    dinfo->unit == unit)
163             return dinfo;
164     }
165 
166     return NULL;
167 }
168 
169 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
170 {
171     return drive_get(type,
172                      drive_index_to_bus_id(type, index),
173                      drive_index_to_unit_id(type, index));
174 }
175 
176 int drive_get_max_bus(BlockInterfaceType type)
177 {
178     int max_bus;
179     DriveInfo *dinfo;
180 
181     max_bus = -1;
182     QTAILQ_FOREACH(dinfo, &drives, next) {
183         if(dinfo->type == type &&
184            dinfo->bus > max_bus)
185             max_bus = dinfo->bus;
186     }
187     return max_bus;
188 }
189 
190 /* Get a block device.  This should only be used for single-drive devices
191    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
192    appropriate bus.  */
193 DriveInfo *drive_get_next(BlockInterfaceType type)
194 {
195     static int next_block_unit[IF_COUNT];
196 
197     return drive_get(type, 0, next_block_unit[type]++);
198 }
199 
200 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
201 {
202     DriveInfo *dinfo;
203 
204     QTAILQ_FOREACH(dinfo, &drives, next) {
205         if (dinfo->bdrv == bs) {
206             return dinfo;
207         }
208     }
209     return NULL;
210 }
211 
212 static void bdrv_format_print(void *opaque, const char *name)
213 {
214     error_printf(" %s", name);
215 }
216 
217 void drive_del(DriveInfo *dinfo)
218 {
219     bdrv_unref(dinfo->bdrv);
220 }
221 
222 void drive_info_del(DriveInfo *dinfo)
223 {
224     if (!dinfo) {
225         return;
226     }
227     if (dinfo->opts) {
228         qemu_opts_del(dinfo->opts);
229     }
230     g_free(dinfo->id);
231     QTAILQ_REMOVE(&drives, dinfo, next);
232     g_free(dinfo->serial);
233     g_free(dinfo);
234 }
235 
236 typedef struct {
237     QEMUBH *bh;
238     BlockDriverState *bs;
239 } BDRVPutRefBH;
240 
241 static void bdrv_put_ref_bh(void *opaque)
242 {
243     BDRVPutRefBH *s = opaque;
244 
245     bdrv_unref(s->bs);
246     qemu_bh_delete(s->bh);
247     g_free(s);
248 }
249 
250 /*
251  * Release a BDS reference in a BH
252  *
253  * It is not safe to use bdrv_unref() from a callback function when the callers
254  * still need the BlockDriverState.  In such cases we schedule a BH to release
255  * the reference.
256  */
257 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
258 {
259     BDRVPutRefBH *s;
260 
261     s = g_new(BDRVPutRefBH, 1);
262     s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
263     s->bs = bs;
264     qemu_bh_schedule(s->bh);
265 }
266 
267 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
268 {
269     if (!strcmp(buf, "ignore")) {
270         return BLOCKDEV_ON_ERROR_IGNORE;
271     } else if (!is_read && !strcmp(buf, "enospc")) {
272         return BLOCKDEV_ON_ERROR_ENOSPC;
273     } else if (!strcmp(buf, "stop")) {
274         return BLOCKDEV_ON_ERROR_STOP;
275     } else if (!strcmp(buf, "report")) {
276         return BLOCKDEV_ON_ERROR_REPORT;
277     } else {
278         error_setg(errp, "'%s' invalid %s error action",
279                    buf, is_read ? "read" : "write");
280         return -1;
281     }
282 }
283 
284 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
285 {
286     if (throttle_conflicting(cfg)) {
287         error_setg(errp, "bps/iops/max total values and read/write values"
288                          " cannot be used at the same time");
289         return false;
290     }
291 
292     if (!throttle_is_valid(cfg)) {
293         error_setg(errp, "bps/iops/maxs values must be 0 or greater");
294         return false;
295     }
296 
297     return true;
298 }
299 
300 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
301 
302 /* Takes the ownership of bs_opts */
303 static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
304                                 Error **errp)
305 {
306     const char *buf;
307     int ro = 0;
308     int bdrv_flags = 0;
309     int on_read_error, on_write_error;
310     BlockDriverState *bs;
311     DriveInfo *dinfo;
312     ThrottleConfig cfg;
313     int snapshot = 0;
314     bool copy_on_read;
315     int ret;
316     Error *error = NULL;
317     QemuOpts *opts;
318     const char *id;
319     bool has_driver_specific_opts;
320     BlockdevDetectZeroesOptions detect_zeroes;
321     BlockDriver *drv = NULL;
322 
323     /* Check common options by copying from bs_opts to opts, all other options
324      * stay in bs_opts for processing by bdrv_open(). */
325     id = qdict_get_try_str(bs_opts, "id");
326     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
327     if (error) {
328         error_propagate(errp, error);
329         goto err_no_opts;
330     }
331 
332     qemu_opts_absorb_qdict(opts, bs_opts, &error);
333     if (error) {
334         error_propagate(errp, error);
335         goto early_err;
336     }
337 
338     if (id) {
339         qdict_del(bs_opts, "id");
340     }
341 
342     has_driver_specific_opts = !!qdict_size(bs_opts);
343 
344     /* extract parameters */
345     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
346     ro = qemu_opt_get_bool(opts, "read-only", 0);
347     copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
348 
349     if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
350         if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
351             error_setg(errp, "invalid discard option");
352             goto early_err;
353         }
354     }
355 
356     if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
357         bdrv_flags |= BDRV_O_CACHE_WB;
358     }
359     if (qemu_opt_get_bool(opts, "cache.direct", false)) {
360         bdrv_flags |= BDRV_O_NOCACHE;
361     }
362     if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
363         bdrv_flags |= BDRV_O_NO_FLUSH;
364     }
365 
366 #ifdef CONFIG_LINUX_AIO
367     if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
368         if (!strcmp(buf, "native")) {
369             bdrv_flags |= BDRV_O_NATIVE_AIO;
370         } else if (!strcmp(buf, "threads")) {
371             /* this is the default */
372         } else {
373            error_setg(errp, "invalid aio option");
374            goto early_err;
375         }
376     }
377 #endif
378 
379     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
380         if (is_help_option(buf)) {
381             error_printf("Supported formats:");
382             bdrv_iterate_format(bdrv_format_print, NULL);
383             error_printf("\n");
384             goto early_err;
385         }
386 
387         drv = bdrv_find_format(buf);
388         if (!drv) {
389             error_setg(errp, "'%s' invalid format", buf);
390             goto early_err;
391         }
392     }
393 
394     /* disk I/O throttling */
395     memset(&cfg, 0, sizeof(cfg));
396     cfg.buckets[THROTTLE_BPS_TOTAL].avg =
397         qemu_opt_get_number(opts, "throttling.bps-total", 0);
398     cfg.buckets[THROTTLE_BPS_READ].avg  =
399         qemu_opt_get_number(opts, "throttling.bps-read", 0);
400     cfg.buckets[THROTTLE_BPS_WRITE].avg =
401         qemu_opt_get_number(opts, "throttling.bps-write", 0);
402     cfg.buckets[THROTTLE_OPS_TOTAL].avg =
403         qemu_opt_get_number(opts, "throttling.iops-total", 0);
404     cfg.buckets[THROTTLE_OPS_READ].avg =
405         qemu_opt_get_number(opts, "throttling.iops-read", 0);
406     cfg.buckets[THROTTLE_OPS_WRITE].avg =
407         qemu_opt_get_number(opts, "throttling.iops-write", 0);
408 
409     cfg.buckets[THROTTLE_BPS_TOTAL].max =
410         qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
411     cfg.buckets[THROTTLE_BPS_READ].max  =
412         qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
413     cfg.buckets[THROTTLE_BPS_WRITE].max =
414         qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
415     cfg.buckets[THROTTLE_OPS_TOTAL].max =
416         qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
417     cfg.buckets[THROTTLE_OPS_READ].max =
418         qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
419     cfg.buckets[THROTTLE_OPS_WRITE].max =
420         qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
421 
422     cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
423 
424     if (!check_throttle_config(&cfg, &error)) {
425         error_propagate(errp, error);
426         goto early_err;
427     }
428 
429     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
430     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
431         on_write_error = parse_block_error_action(buf, 0, &error);
432         if (error) {
433             error_propagate(errp, error);
434             goto early_err;
435         }
436     }
437 
438     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
439     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
440         on_read_error = parse_block_error_action(buf, 1, &error);
441         if (error) {
442             error_propagate(errp, error);
443             goto early_err;
444         }
445     }
446 
447     detect_zeroes =
448         qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
449                         qemu_opt_get(opts, "detect-zeroes"),
450                         BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
451                         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
452                         &error);
453     if (error) {
454         error_propagate(errp, error);
455         goto early_err;
456     }
457 
458     if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
459         !(bdrv_flags & BDRV_O_UNMAP)) {
460         error_setg(errp, "setting detect-zeroes to unmap is not allowed "
461                          "without setting discard operation to unmap");
462         goto early_err;
463     }
464 
465     /* init */
466     bs = bdrv_new(qemu_opts_id(opts), errp);
467     if (!bs) {
468         goto early_err;
469     }
470     bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
471     bs->read_only = ro;
472     bs->detect_zeroes = detect_zeroes;
473 
474     bdrv_set_on_error(bs, on_read_error, on_write_error);
475 
476     /* disk I/O throttling */
477     if (throttle_enabled(&cfg)) {
478         bdrv_io_limits_enable(bs);
479         bdrv_set_io_limits(bs, &cfg);
480     }
481 
482     dinfo = g_malloc0(sizeof(*dinfo));
483     dinfo->id = g_strdup(qemu_opts_id(opts));
484     dinfo->bdrv = bs;
485     QTAILQ_INSERT_TAIL(&drives, dinfo, next);
486 
487     if (!file || !*file) {
488         if (has_driver_specific_opts) {
489             file = NULL;
490         } else {
491             QDECREF(bs_opts);
492             qemu_opts_del(opts);
493             return dinfo;
494         }
495     }
496     if (snapshot) {
497         /* always use cache=unsafe with snapshot */
498         bdrv_flags &= ~BDRV_O_CACHE_MASK;
499         bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
500     }
501 
502     if (copy_on_read) {
503         bdrv_flags |= BDRV_O_COPY_ON_READ;
504     }
505 
506     if (runstate_check(RUN_STATE_INMIGRATE)) {
507         bdrv_flags |= BDRV_O_INCOMING;
508     }
509 
510     bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
511 
512     QINCREF(bs_opts);
513     ret = bdrv_open(&bs, file, NULL, bs_opts, bdrv_flags, drv, &error);
514     assert(bs == dinfo->bdrv);
515 
516     if (ret < 0) {
517         error_setg(errp, "could not open disk image %s: %s",
518                    file ?: dinfo->id, error_get_pretty(error));
519         error_free(error);
520         goto err;
521     }
522 
523     if (bdrv_key_required(bs)) {
524         autostart = 0;
525     }
526 
527     QDECREF(bs_opts);
528     qemu_opts_del(opts);
529 
530     return dinfo;
531 
532 err:
533     bdrv_unref(bs);
534 early_err:
535     qemu_opts_del(opts);
536 err_no_opts:
537     QDECREF(bs_opts);
538     return NULL;
539 }
540 
541 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
542                             Error **errp)
543 {
544     const char *value;
545 
546     value = qemu_opt_get(opts, from);
547     if (value) {
548         if (qemu_opt_find(opts, to)) {
549             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
550                        "same time", to, from);
551             return;
552         }
553         qemu_opt_set(opts, to, value);
554         qemu_opt_unset(opts, from);
555     }
556 }
557 
558 QemuOptsList qemu_legacy_drive_opts = {
559     .name = "drive",
560     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
561     .desc = {
562         {
563             .name = "bus",
564             .type = QEMU_OPT_NUMBER,
565             .help = "bus number",
566         },{
567             .name = "unit",
568             .type = QEMU_OPT_NUMBER,
569             .help = "unit number (i.e. lun for scsi)",
570         },{
571             .name = "index",
572             .type = QEMU_OPT_NUMBER,
573             .help = "index number",
574         },{
575             .name = "media",
576             .type = QEMU_OPT_STRING,
577             .help = "media type (disk, cdrom)",
578         },{
579             .name = "if",
580             .type = QEMU_OPT_STRING,
581             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
582         },{
583             .name = "cyls",
584             .type = QEMU_OPT_NUMBER,
585             .help = "number of cylinders (ide disk geometry)",
586         },{
587             .name = "heads",
588             .type = QEMU_OPT_NUMBER,
589             .help = "number of heads (ide disk geometry)",
590         },{
591             .name = "secs",
592             .type = QEMU_OPT_NUMBER,
593             .help = "number of sectors (ide disk geometry)",
594         },{
595             .name = "trans",
596             .type = QEMU_OPT_STRING,
597             .help = "chs translation (auto, lba, none)",
598         },{
599             .name = "boot",
600             .type = QEMU_OPT_BOOL,
601             .help = "(deprecated, ignored)",
602         },{
603             .name = "addr",
604             .type = QEMU_OPT_STRING,
605             .help = "pci address (virtio only)",
606         },{
607             .name = "serial",
608             .type = QEMU_OPT_STRING,
609             .help = "disk serial number",
610         },{
611             .name = "file",
612             .type = QEMU_OPT_STRING,
613             .help = "file name",
614         },
615 
616         /* Options that are passed on, but have special semantics with -drive */
617         {
618             .name = "read-only",
619             .type = QEMU_OPT_BOOL,
620             .help = "open drive file as read-only",
621         },{
622             .name = "rerror",
623             .type = QEMU_OPT_STRING,
624             .help = "read error action",
625         },{
626             .name = "werror",
627             .type = QEMU_OPT_STRING,
628             .help = "write error action",
629         },{
630             .name = "copy-on-read",
631             .type = QEMU_OPT_BOOL,
632             .help = "copy read data from backing file into image file",
633         },
634 
635         { /* end of list */ }
636     },
637 };
638 
639 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
640 {
641     const char *value;
642     DriveInfo *dinfo = NULL;
643     QDict *bs_opts;
644     QemuOpts *legacy_opts;
645     DriveMediaType media = MEDIA_DISK;
646     BlockInterfaceType type;
647     int cyls, heads, secs, translation;
648     int max_devs, bus_id, unit_id, index;
649     const char *devaddr;
650     const char *werror, *rerror;
651     bool read_only = false;
652     bool copy_on_read;
653     const char *serial;
654     const char *filename;
655     Error *local_err = NULL;
656     int i;
657 
658     /* Change legacy command line options into QMP ones */
659     static const struct {
660         const char *from;
661         const char *to;
662     } opt_renames[] = {
663         { "iops",           "throttling.iops-total" },
664         { "iops_rd",        "throttling.iops-read" },
665         { "iops_wr",        "throttling.iops-write" },
666 
667         { "bps",            "throttling.bps-total" },
668         { "bps_rd",         "throttling.bps-read" },
669         { "bps_wr",         "throttling.bps-write" },
670 
671         { "iops_max",       "throttling.iops-total-max" },
672         { "iops_rd_max",    "throttling.iops-read-max" },
673         { "iops_wr_max",    "throttling.iops-write-max" },
674 
675         { "bps_max",        "throttling.bps-total-max" },
676         { "bps_rd_max",     "throttling.bps-read-max" },
677         { "bps_wr_max",     "throttling.bps-write-max" },
678 
679         { "iops_size",      "throttling.iops-size" },
680 
681         { "readonly",       "read-only" },
682     };
683 
684     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
685         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
686                         &local_err);
687         if (local_err) {
688             error_report("%s", error_get_pretty(local_err));
689             error_free(local_err);
690             return NULL;
691         }
692     }
693 
694     value = qemu_opt_get(all_opts, "cache");
695     if (value) {
696         int flags = 0;
697 
698         if (bdrv_parse_cache_flags(value, &flags) != 0) {
699             error_report("invalid cache option");
700             return NULL;
701         }
702 
703         /* Specific options take precedence */
704         if (!qemu_opt_get(all_opts, "cache.writeback")) {
705             qemu_opt_set_bool(all_opts, "cache.writeback",
706                               !!(flags & BDRV_O_CACHE_WB));
707         }
708         if (!qemu_opt_get(all_opts, "cache.direct")) {
709             qemu_opt_set_bool(all_opts, "cache.direct",
710                               !!(flags & BDRV_O_NOCACHE));
711         }
712         if (!qemu_opt_get(all_opts, "cache.no-flush")) {
713             qemu_opt_set_bool(all_opts, "cache.no-flush",
714                               !!(flags & BDRV_O_NO_FLUSH));
715         }
716         qemu_opt_unset(all_opts, "cache");
717     }
718 
719     /* Get a QDict for processing the options */
720     bs_opts = qdict_new();
721     qemu_opts_to_qdict(all_opts, bs_opts);
722 
723     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
724                                    &error_abort);
725     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
726     if (local_err) {
727         error_report("%s", error_get_pretty(local_err));
728         error_free(local_err);
729         goto fail;
730     }
731 
732     /* Deprecated option boot=[on|off] */
733     if (qemu_opt_get(legacy_opts, "boot") != NULL) {
734         fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
735                 "ignored. Future versions will reject this parameter. Please "
736                 "update your scripts.\n");
737     }
738 
739     /* Media type */
740     value = qemu_opt_get(legacy_opts, "media");
741     if (value) {
742         if (!strcmp(value, "disk")) {
743             media = MEDIA_DISK;
744         } else if (!strcmp(value, "cdrom")) {
745             media = MEDIA_CDROM;
746             read_only = true;
747         } else {
748             error_report("'%s' invalid media", value);
749             goto fail;
750         }
751     }
752 
753     /* copy-on-read is disabled with a warning for read-only devices */
754     read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
755     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
756 
757     if (read_only && copy_on_read) {
758         error_report("warning: disabling copy-on-read on read-only drive");
759         copy_on_read = false;
760     }
761 
762     qdict_put(bs_opts, "read-only",
763               qstring_from_str(read_only ? "on" : "off"));
764     qdict_put(bs_opts, "copy-on-read",
765               qstring_from_str(copy_on_read ? "on" :"off"));
766 
767     /* Controller type */
768     value = qemu_opt_get(legacy_opts, "if");
769     if (value) {
770         for (type = 0;
771              type < IF_COUNT && strcmp(value, if_name[type]);
772              type++) {
773         }
774         if (type == IF_COUNT) {
775             error_report("unsupported bus type '%s'", value);
776             goto fail;
777         }
778     } else {
779         type = block_default_type;
780     }
781 
782     /* Geometry */
783     cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
784     heads = qemu_opt_get_number(legacy_opts, "heads", 0);
785     secs  = qemu_opt_get_number(legacy_opts, "secs", 0);
786 
787     if (cyls || heads || secs) {
788         if (cyls < 1) {
789             error_report("invalid physical cyls number");
790             goto fail;
791         }
792         if (heads < 1) {
793             error_report("invalid physical heads number");
794             goto fail;
795         }
796         if (secs < 1) {
797             error_report("invalid physical secs number");
798             goto fail;
799         }
800     }
801 
802     translation = BIOS_ATA_TRANSLATION_AUTO;
803     value = qemu_opt_get(legacy_opts, "trans");
804     if (value != NULL) {
805         if (!cyls) {
806             error_report("'%s' trans must be used with cyls, heads and secs",
807                          value);
808             goto fail;
809         }
810         if (!strcmp(value, "none")) {
811             translation = BIOS_ATA_TRANSLATION_NONE;
812         } else if (!strcmp(value, "lba")) {
813             translation = BIOS_ATA_TRANSLATION_LBA;
814         } else if (!strcmp(value, "large")) {
815             translation = BIOS_ATA_TRANSLATION_LARGE;
816         } else if (!strcmp(value, "rechs")) {
817             translation = BIOS_ATA_TRANSLATION_RECHS;
818         } else if (!strcmp(value, "auto")) {
819             translation = BIOS_ATA_TRANSLATION_AUTO;
820         } else {
821             error_report("'%s' invalid translation type", value);
822             goto fail;
823         }
824     }
825 
826     if (media == MEDIA_CDROM) {
827         if (cyls || secs || heads) {
828             error_report("CHS can't be set with media=cdrom");
829             goto fail;
830         }
831     }
832 
833     /* Device address specified by bus/unit or index.
834      * If none was specified, try to find the first free one. */
835     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
836     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
837     index   = qemu_opt_get_number(legacy_opts, "index", -1);
838 
839     max_devs = if_max_devs[type];
840 
841     if (index != -1) {
842         if (bus_id != 0 || unit_id != -1) {
843             error_report("index cannot be used with bus and unit");
844             goto fail;
845         }
846         bus_id = drive_index_to_bus_id(type, index);
847         unit_id = drive_index_to_unit_id(type, index);
848     }
849 
850     if (unit_id == -1) {
851        unit_id = 0;
852        while (drive_get(type, bus_id, unit_id) != NULL) {
853            unit_id++;
854            if (max_devs && unit_id >= max_devs) {
855                unit_id -= max_devs;
856                bus_id++;
857            }
858        }
859     }
860 
861     if (max_devs && unit_id >= max_devs) {
862         error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
863         goto fail;
864     }
865 
866     if (drive_get(type, bus_id, unit_id) != NULL) {
867         error_report("drive with bus=%d, unit=%d (index=%d) exists",
868                      bus_id, unit_id, index);
869         goto fail;
870     }
871 
872     /* Serial number */
873     serial = qemu_opt_get(legacy_opts, "serial");
874 
875     /* no id supplied -> create one */
876     if (qemu_opts_id(all_opts) == NULL) {
877         char *new_id;
878         const char *mediastr = "";
879         if (type == IF_IDE || type == IF_SCSI) {
880             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
881         }
882         if (max_devs) {
883             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
884                                      mediastr, unit_id);
885         } else {
886             new_id = g_strdup_printf("%s%s%i", if_name[type],
887                                      mediastr, unit_id);
888         }
889         qdict_put(bs_opts, "id", qstring_from_str(new_id));
890         g_free(new_id);
891     }
892 
893     /* Add virtio block device */
894     devaddr = qemu_opt_get(legacy_opts, "addr");
895     if (devaddr && type != IF_VIRTIO) {
896         error_report("addr is not supported by this bus type");
897         goto fail;
898     }
899 
900     if (type == IF_VIRTIO) {
901         QemuOpts *devopts;
902         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
903                                    &error_abort);
904         if (arch_type == QEMU_ARCH_S390X) {
905             qemu_opt_set(devopts, "driver", "virtio-blk-s390");
906         } else {
907             qemu_opt_set(devopts, "driver", "virtio-blk-pci");
908         }
909         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
910         if (devaddr) {
911             qemu_opt_set(devopts, "addr", devaddr);
912         }
913     }
914 
915     filename = qemu_opt_get(legacy_opts, "file");
916 
917     /* Check werror/rerror compatibility with if=... */
918     werror = qemu_opt_get(legacy_opts, "werror");
919     if (werror != NULL) {
920         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
921             type != IF_NONE) {
922             error_report("werror is not supported by this bus type");
923             goto fail;
924         }
925         qdict_put(bs_opts, "werror", qstring_from_str(werror));
926     }
927 
928     rerror = qemu_opt_get(legacy_opts, "rerror");
929     if (rerror != NULL) {
930         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
931             type != IF_NONE) {
932             error_report("rerror is not supported by this bus type");
933             goto fail;
934         }
935         qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
936     }
937 
938     /* Actual block device init: Functionality shared with blockdev-add */
939     dinfo = blockdev_init(filename, bs_opts, &local_err);
940     bs_opts = NULL;
941     if (dinfo == NULL) {
942         if (local_err) {
943             error_report("%s", error_get_pretty(local_err));
944             error_free(local_err);
945         }
946         goto fail;
947     } else {
948         assert(!local_err);
949     }
950 
951     /* Set legacy DriveInfo fields */
952     dinfo->enable_auto_del = true;
953     dinfo->opts = all_opts;
954 
955     dinfo->cyls = cyls;
956     dinfo->heads = heads;
957     dinfo->secs = secs;
958     dinfo->trans = translation;
959 
960     dinfo->type = type;
961     dinfo->bus = bus_id;
962     dinfo->unit = unit_id;
963     dinfo->devaddr = devaddr;
964 
965     dinfo->serial = g_strdup(serial);
966 
967     switch(type) {
968     case IF_IDE:
969     case IF_SCSI:
970     case IF_XEN:
971     case IF_NONE:
972         dinfo->media_cd = media == MEDIA_CDROM;
973         break;
974     default:
975         break;
976     }
977 
978 fail:
979     qemu_opts_del(legacy_opts);
980     QDECREF(bs_opts);
981     return dinfo;
982 }
983 
984 void do_commit(Monitor *mon, const QDict *qdict)
985 {
986     const char *device = qdict_get_str(qdict, "device");
987     BlockDriverState *bs;
988     int ret;
989 
990     if (!strcmp(device, "all")) {
991         ret = bdrv_commit_all();
992     } else {
993         bs = bdrv_find(device);
994         if (!bs) {
995             monitor_printf(mon, "Device '%s' not found\n", device);
996             return;
997         }
998         ret = bdrv_commit(bs);
999     }
1000     if (ret < 0) {
1001         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1002                        strerror(-ret));
1003     }
1004 }
1005 
1006 static void blockdev_do_action(int kind, void *data, Error **errp)
1007 {
1008     TransactionAction action;
1009     TransactionActionList list;
1010 
1011     action.kind = kind;
1012     action.data = data;
1013     list.value = &action;
1014     list.next = NULL;
1015     qmp_transaction(&list, errp);
1016 }
1017 
1018 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1019                                 bool has_node_name, const char *node_name,
1020                                 const char *snapshot_file,
1021                                 bool has_snapshot_node_name,
1022                                 const char *snapshot_node_name,
1023                                 bool has_format, const char *format,
1024                                 bool has_mode, NewImageMode mode, Error **errp)
1025 {
1026     BlockdevSnapshot snapshot = {
1027         .has_device = has_device,
1028         .device = (char *) device,
1029         .has_node_name = has_node_name,
1030         .node_name = (char *) node_name,
1031         .snapshot_file = (char *) snapshot_file,
1032         .has_snapshot_node_name = has_snapshot_node_name,
1033         .snapshot_node_name = (char *) snapshot_node_name,
1034         .has_format = has_format,
1035         .format = (char *) format,
1036         .has_mode = has_mode,
1037         .mode = mode,
1038     };
1039     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1040                        &snapshot, errp);
1041 }
1042 
1043 void qmp_blockdev_snapshot_internal_sync(const char *device,
1044                                          const char *name,
1045                                          Error **errp)
1046 {
1047     BlockdevSnapshotInternal snapshot = {
1048         .device = (char *) device,
1049         .name = (char *) name
1050     };
1051 
1052     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1053                        &snapshot, errp);
1054 }
1055 
1056 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1057                                                          bool has_id,
1058                                                          const char *id,
1059                                                          bool has_name,
1060                                                          const char *name,
1061                                                          Error **errp)
1062 {
1063     BlockDriverState *bs = bdrv_find(device);
1064     QEMUSnapshotInfo sn;
1065     Error *local_err = NULL;
1066     SnapshotInfo *info = NULL;
1067     int ret;
1068 
1069     if (!bs) {
1070         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1071         return NULL;
1072     }
1073 
1074     if (!has_id) {
1075         id = NULL;
1076     }
1077 
1078     if (!has_name) {
1079         name = NULL;
1080     }
1081 
1082     if (!id && !name) {
1083         error_setg(errp, "Name or id must be provided");
1084         return NULL;
1085     }
1086 
1087     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1088     if (local_err) {
1089         error_propagate(errp, local_err);
1090         return NULL;
1091     }
1092     if (!ret) {
1093         error_setg(errp,
1094                    "Snapshot with id '%s' and name '%s' does not exist on "
1095                    "device '%s'",
1096                    STR_OR_NULL(id), STR_OR_NULL(name), device);
1097         return NULL;
1098     }
1099 
1100     bdrv_snapshot_delete(bs, id, name, &local_err);
1101     if (local_err) {
1102         error_propagate(errp, local_err);
1103         return NULL;
1104     }
1105 
1106     info = g_new0(SnapshotInfo, 1);
1107     info->id = g_strdup(sn.id_str);
1108     info->name = g_strdup(sn.name);
1109     info->date_nsec = sn.date_nsec;
1110     info->date_sec = sn.date_sec;
1111     info->vm_state_size = sn.vm_state_size;
1112     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1113     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1114 
1115     return info;
1116 }
1117 
1118 /* New and old BlockDriverState structs for group snapshots */
1119 
1120 typedef struct BlkTransactionState BlkTransactionState;
1121 
1122 /* Only prepare() may fail. In a single transaction, only one of commit() or
1123    abort() will be called, clean() will always be called if it present. */
1124 typedef struct BdrvActionOps {
1125     /* Size of state struct, in bytes. */
1126     size_t instance_size;
1127     /* Prepare the work, must NOT be NULL. */
1128     void (*prepare)(BlkTransactionState *common, Error **errp);
1129     /* Commit the changes, can be NULL. */
1130     void (*commit)(BlkTransactionState *common);
1131     /* Abort the changes on fail, can be NULL. */
1132     void (*abort)(BlkTransactionState *common);
1133     /* Clean up resource in the end, can be NULL. */
1134     void (*clean)(BlkTransactionState *common);
1135 } BdrvActionOps;
1136 
1137 /*
1138  * This structure must be arranged as first member in child type, assuming
1139  * that compiler will also arrange it to the same address with parent instance.
1140  * Later it will be used in free().
1141  */
1142 struct BlkTransactionState {
1143     TransactionAction *action;
1144     const BdrvActionOps *ops;
1145     QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1146 };
1147 
1148 /* internal snapshot private data */
1149 typedef struct InternalSnapshotState {
1150     BlkTransactionState common;
1151     BlockDriverState *bs;
1152     QEMUSnapshotInfo sn;
1153 } InternalSnapshotState;
1154 
1155 static void internal_snapshot_prepare(BlkTransactionState *common,
1156                                       Error **errp)
1157 {
1158     Error *local_err = NULL;
1159     const char *device;
1160     const char *name;
1161     BlockDriverState *bs;
1162     QEMUSnapshotInfo old_sn, *sn;
1163     bool ret;
1164     qemu_timeval tv;
1165     BlockdevSnapshotInternal *internal;
1166     InternalSnapshotState *state;
1167     int ret1;
1168 
1169     g_assert(common->action->kind ==
1170              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1171     internal = common->action->blockdev_snapshot_internal_sync;
1172     state = DO_UPCAST(InternalSnapshotState, common, common);
1173 
1174     /* 1. parse input */
1175     device = internal->device;
1176     name = internal->name;
1177 
1178     /* 2. check for validation */
1179     bs = bdrv_find(device);
1180     if (!bs) {
1181         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1182         return;
1183     }
1184 
1185     if (!bdrv_is_inserted(bs)) {
1186         error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1187         return;
1188     }
1189 
1190     if (bdrv_is_read_only(bs)) {
1191         error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1192         return;
1193     }
1194 
1195     if (!bdrv_can_snapshot(bs)) {
1196         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1197                   bs->drv->format_name, device, "internal snapshot");
1198         return;
1199     }
1200 
1201     if (!strlen(name)) {
1202         error_setg(errp, "Name is empty");
1203         return;
1204     }
1205 
1206     /* check whether a snapshot with name exist */
1207     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1208                                             &local_err);
1209     if (local_err) {
1210         error_propagate(errp, local_err);
1211         return;
1212     } else if (ret) {
1213         error_setg(errp,
1214                    "Snapshot with name '%s' already exists on device '%s'",
1215                    name, device);
1216         return;
1217     }
1218 
1219     /* 3. take the snapshot */
1220     sn = &state->sn;
1221     pstrcpy(sn->name, sizeof(sn->name), name);
1222     qemu_gettimeofday(&tv);
1223     sn->date_sec = tv.tv_sec;
1224     sn->date_nsec = tv.tv_usec * 1000;
1225     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1226 
1227     ret1 = bdrv_snapshot_create(bs, sn);
1228     if (ret1 < 0) {
1229         error_setg_errno(errp, -ret1,
1230                          "Failed to create snapshot '%s' on device '%s'",
1231                          name, device);
1232         return;
1233     }
1234 
1235     /* 4. succeed, mark a snapshot is created */
1236     state->bs = bs;
1237 }
1238 
1239 static void internal_snapshot_abort(BlkTransactionState *common)
1240 {
1241     InternalSnapshotState *state =
1242                              DO_UPCAST(InternalSnapshotState, common, common);
1243     BlockDriverState *bs = state->bs;
1244     QEMUSnapshotInfo *sn = &state->sn;
1245     Error *local_error = NULL;
1246 
1247     if (!bs) {
1248         return;
1249     }
1250 
1251     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1252         error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1253                      "device '%s' in abort: %s",
1254                      sn->id_str,
1255                      sn->name,
1256                      bdrv_get_device_name(bs),
1257                      error_get_pretty(local_error));
1258         error_free(local_error);
1259     }
1260 }
1261 
1262 /* external snapshot private data */
1263 typedef struct ExternalSnapshotState {
1264     BlkTransactionState common;
1265     BlockDriverState *old_bs;
1266     BlockDriverState *new_bs;
1267 } ExternalSnapshotState;
1268 
1269 static void external_snapshot_prepare(BlkTransactionState *common,
1270                                       Error **errp)
1271 {
1272     BlockDriver *drv;
1273     int flags, ret;
1274     QDict *options = NULL;
1275     Error *local_err = NULL;
1276     bool has_device = false;
1277     const char *device;
1278     bool has_node_name = false;
1279     const char *node_name;
1280     bool has_snapshot_node_name = false;
1281     const char *snapshot_node_name;
1282     const char *new_image_file;
1283     const char *format = "qcow2";
1284     enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1285     ExternalSnapshotState *state =
1286                              DO_UPCAST(ExternalSnapshotState, common, common);
1287     TransactionAction *action = common->action;
1288 
1289     /* get parameters */
1290     g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1291 
1292     has_device = action->blockdev_snapshot_sync->has_device;
1293     device = action->blockdev_snapshot_sync->device;
1294     has_node_name = action->blockdev_snapshot_sync->has_node_name;
1295     node_name = action->blockdev_snapshot_sync->node_name;
1296     has_snapshot_node_name =
1297         action->blockdev_snapshot_sync->has_snapshot_node_name;
1298     snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1299 
1300     new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1301     if (action->blockdev_snapshot_sync->has_format) {
1302         format = action->blockdev_snapshot_sync->format;
1303     }
1304     if (action->blockdev_snapshot_sync->has_mode) {
1305         mode = action->blockdev_snapshot_sync->mode;
1306     }
1307 
1308     /* start processing */
1309     drv = bdrv_find_format(format);
1310     if (!drv) {
1311         error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1312         return;
1313     }
1314 
1315     state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1316                                    has_node_name ? node_name : NULL,
1317                                    &local_err);
1318     if (local_err) {
1319         error_propagate(errp, local_err);
1320         return;
1321     }
1322 
1323     if (has_node_name && !has_snapshot_node_name) {
1324         error_setg(errp, "New snapshot node name missing");
1325         return;
1326     }
1327 
1328     if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1329         error_setg(errp, "New snapshot node name already existing");
1330         return;
1331     }
1332 
1333     if (!bdrv_is_inserted(state->old_bs)) {
1334         error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1335         return;
1336     }
1337 
1338     if (bdrv_op_is_blocked(state->old_bs,
1339                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1340         return;
1341     }
1342 
1343     if (!bdrv_is_read_only(state->old_bs)) {
1344         if (bdrv_flush(state->old_bs)) {
1345             error_set(errp, QERR_IO_ERROR);
1346             return;
1347         }
1348     }
1349 
1350     if (!bdrv_is_first_non_filter(state->old_bs)) {
1351         error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1352         return;
1353     }
1354 
1355     flags = state->old_bs->open_flags;
1356 
1357     /* create new image w/backing file */
1358     if (mode != NEW_IMAGE_MODE_EXISTING) {
1359         bdrv_img_create(new_image_file, format,
1360                         state->old_bs->filename,
1361                         state->old_bs->drv->format_name,
1362                         NULL, -1, flags, &local_err, false);
1363         if (local_err) {
1364             error_propagate(errp, local_err);
1365             return;
1366         }
1367     }
1368 
1369     if (has_snapshot_node_name) {
1370         options = qdict_new();
1371         qdict_put(options, "node-name",
1372                   qstring_from_str(snapshot_node_name));
1373     }
1374 
1375     /* TODO Inherit bs->options or only take explicit options with an
1376      * extended QMP command? */
1377     assert(state->new_bs == NULL);
1378     ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1379                     flags | BDRV_O_NO_BACKING, drv, &local_err);
1380     /* We will manually add the backing_hd field to the bs later */
1381     if (ret != 0) {
1382         error_propagate(errp, local_err);
1383     }
1384 }
1385 
1386 static void external_snapshot_commit(BlkTransactionState *common)
1387 {
1388     ExternalSnapshotState *state =
1389                              DO_UPCAST(ExternalSnapshotState, common, common);
1390 
1391     /* This removes our old bs and adds the new bs */
1392     bdrv_append(state->new_bs, state->old_bs);
1393     /* We don't need (or want) to use the transactional
1394      * bdrv_reopen_multiple() across all the entries at once, because we
1395      * don't want to abort all of them if one of them fails the reopen */
1396     bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1397                 NULL);
1398 }
1399 
1400 static void external_snapshot_abort(BlkTransactionState *common)
1401 {
1402     ExternalSnapshotState *state =
1403                              DO_UPCAST(ExternalSnapshotState, common, common);
1404     if (state->new_bs) {
1405         bdrv_unref(state->new_bs);
1406     }
1407 }
1408 
1409 typedef struct DriveBackupState {
1410     BlkTransactionState common;
1411     BlockDriverState *bs;
1412     BlockJob *job;
1413 } DriveBackupState;
1414 
1415 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1416 {
1417     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1418     DriveBackup *backup;
1419     Error *local_err = NULL;
1420 
1421     assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1422     backup = common->action->drive_backup;
1423 
1424     qmp_drive_backup(backup->device, backup->target,
1425                      backup->has_format, backup->format,
1426                      backup->sync,
1427                      backup->has_mode, backup->mode,
1428                      backup->has_speed, backup->speed,
1429                      backup->has_on_source_error, backup->on_source_error,
1430                      backup->has_on_target_error, backup->on_target_error,
1431                      &local_err);
1432     if (local_err) {
1433         error_propagate(errp, local_err);
1434         state->bs = NULL;
1435         state->job = NULL;
1436         return;
1437     }
1438 
1439     state->bs = bdrv_find(backup->device);
1440     state->job = state->bs->job;
1441 }
1442 
1443 static void drive_backup_abort(BlkTransactionState *common)
1444 {
1445     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1446     BlockDriverState *bs = state->bs;
1447 
1448     /* Only cancel if it's the job we started */
1449     if (bs && bs->job && bs->job == state->job) {
1450         block_job_cancel_sync(bs->job);
1451     }
1452 }
1453 
1454 static void abort_prepare(BlkTransactionState *common, Error **errp)
1455 {
1456     error_setg(errp, "Transaction aborted using Abort action");
1457 }
1458 
1459 static void abort_commit(BlkTransactionState *common)
1460 {
1461     g_assert_not_reached(); /* this action never succeeds */
1462 }
1463 
1464 static const BdrvActionOps actions[] = {
1465     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1466         .instance_size = sizeof(ExternalSnapshotState),
1467         .prepare  = external_snapshot_prepare,
1468         .commit   = external_snapshot_commit,
1469         .abort = external_snapshot_abort,
1470     },
1471     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1472         .instance_size = sizeof(DriveBackupState),
1473         .prepare = drive_backup_prepare,
1474         .abort = drive_backup_abort,
1475     },
1476     [TRANSACTION_ACTION_KIND_ABORT] = {
1477         .instance_size = sizeof(BlkTransactionState),
1478         .prepare = abort_prepare,
1479         .commit = abort_commit,
1480     },
1481     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1482         .instance_size = sizeof(InternalSnapshotState),
1483         .prepare  = internal_snapshot_prepare,
1484         .abort = internal_snapshot_abort,
1485     },
1486 };
1487 
1488 /*
1489  * 'Atomic' group snapshots.  The snapshots are taken as a set, and if any fail
1490  *  then we do not pivot any of the devices in the group, and abandon the
1491  *  snapshots
1492  */
1493 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1494 {
1495     TransactionActionList *dev_entry = dev_list;
1496     BlkTransactionState *state, *next;
1497     Error *local_err = NULL;
1498 
1499     QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1500     QSIMPLEQ_INIT(&snap_bdrv_states);
1501 
1502     /* drain all i/o before any snapshots */
1503     bdrv_drain_all();
1504 
1505     /* We don't do anything in this loop that commits us to the snapshot */
1506     while (NULL != dev_entry) {
1507         TransactionAction *dev_info = NULL;
1508         const BdrvActionOps *ops;
1509 
1510         dev_info = dev_entry->value;
1511         dev_entry = dev_entry->next;
1512 
1513         assert(dev_info->kind < ARRAY_SIZE(actions));
1514 
1515         ops = &actions[dev_info->kind];
1516         assert(ops->instance_size > 0);
1517 
1518         state = g_malloc0(ops->instance_size);
1519         state->ops = ops;
1520         state->action = dev_info;
1521         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1522 
1523         state->ops->prepare(state, &local_err);
1524         if (local_err) {
1525             error_propagate(errp, local_err);
1526             goto delete_and_fail;
1527         }
1528     }
1529 
1530     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1531         if (state->ops->commit) {
1532             state->ops->commit(state);
1533         }
1534     }
1535 
1536     /* success */
1537     goto exit;
1538 
1539 delete_and_fail:
1540     /*
1541     * failure, and it is all-or-none; abandon each new bs, and keep using
1542     * the original bs for all images
1543     */
1544     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1545         if (state->ops->abort) {
1546             state->ops->abort(state);
1547         }
1548     }
1549 exit:
1550     QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1551         if (state->ops->clean) {
1552             state->ops->clean(state);
1553         }
1554         g_free(state);
1555     }
1556 }
1557 
1558 
1559 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1560 {
1561     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1562         return;
1563     }
1564     if (!bdrv_dev_has_removable_media(bs)) {
1565         error_setg(errp, "Device '%s' is not removable",
1566                    bdrv_get_device_name(bs));
1567         return;
1568     }
1569 
1570     if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1571         bdrv_dev_eject_request(bs, force);
1572         if (!force) {
1573             error_setg(errp, "Device '%s' is locked",
1574                        bdrv_get_device_name(bs));
1575             return;
1576         }
1577     }
1578 
1579     bdrv_close(bs);
1580 }
1581 
1582 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1583 {
1584     BlockDriverState *bs;
1585 
1586     bs = bdrv_find(device);
1587     if (!bs) {
1588         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1589         return;
1590     }
1591 
1592     eject_device(bs, force, errp);
1593 }
1594 
1595 void qmp_block_passwd(bool has_device, const char *device,
1596                       bool has_node_name, const char *node_name,
1597                       const char *password, Error **errp)
1598 {
1599     Error *local_err = NULL;
1600     BlockDriverState *bs;
1601     int err;
1602 
1603     bs = bdrv_lookup_bs(has_device ? device : NULL,
1604                         has_node_name ? node_name : NULL,
1605                         &local_err);
1606     if (local_err) {
1607         error_propagate(errp, local_err);
1608         return;
1609     }
1610 
1611     err = bdrv_set_key(bs, password);
1612     if (err == -EINVAL) {
1613         error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1614         return;
1615     } else if (err < 0) {
1616         error_set(errp, QERR_INVALID_PASSWORD);
1617         return;
1618     }
1619 }
1620 
1621 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1622                                     int bdrv_flags, BlockDriver *drv,
1623                                     const char *password, Error **errp)
1624 {
1625     Error *local_err = NULL;
1626     int ret;
1627 
1628     ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1629     if (ret < 0) {
1630         error_propagate(errp, local_err);
1631         return;
1632     }
1633 
1634     if (bdrv_key_required(bs)) {
1635         if (password) {
1636             if (bdrv_set_key(bs, password) < 0) {
1637                 error_set(errp, QERR_INVALID_PASSWORD);
1638             }
1639         } else {
1640             error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1641                       bdrv_get_encrypted_filename(bs));
1642         }
1643     } else if (password) {
1644         error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1645     }
1646 }
1647 
1648 void qmp_change_blockdev(const char *device, const char *filename,
1649                          const char *format, Error **errp)
1650 {
1651     BlockDriverState *bs;
1652     BlockDriver *drv = NULL;
1653     int bdrv_flags;
1654     Error *err = NULL;
1655 
1656     bs = bdrv_find(device);
1657     if (!bs) {
1658         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1659         return;
1660     }
1661 
1662     if (format) {
1663         drv = bdrv_find_whitelisted_format(format, bs->read_only);
1664         if (!drv) {
1665             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1666             return;
1667         }
1668     }
1669 
1670     eject_device(bs, 0, &err);
1671     if (err) {
1672         error_propagate(errp, err);
1673         return;
1674     }
1675 
1676     bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1677     bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1678 
1679     qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1680 }
1681 
1682 /* throttling disk I/O limits */
1683 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1684                                int64_t bps_wr,
1685                                int64_t iops,
1686                                int64_t iops_rd,
1687                                int64_t iops_wr,
1688                                bool has_bps_max,
1689                                int64_t bps_max,
1690                                bool has_bps_rd_max,
1691                                int64_t bps_rd_max,
1692                                bool has_bps_wr_max,
1693                                int64_t bps_wr_max,
1694                                bool has_iops_max,
1695                                int64_t iops_max,
1696                                bool has_iops_rd_max,
1697                                int64_t iops_rd_max,
1698                                bool has_iops_wr_max,
1699                                int64_t iops_wr_max,
1700                                bool has_iops_size,
1701                                int64_t iops_size, Error **errp)
1702 {
1703     ThrottleConfig cfg;
1704     BlockDriverState *bs;
1705     AioContext *aio_context;
1706 
1707     bs = bdrv_find(device);
1708     if (!bs) {
1709         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1710         return;
1711     }
1712 
1713     memset(&cfg, 0, sizeof(cfg));
1714     cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1715     cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;
1716     cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1717 
1718     cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1719     cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;
1720     cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1721 
1722     if (has_bps_max) {
1723         cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1724     }
1725     if (has_bps_rd_max) {
1726         cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1727     }
1728     if (has_bps_wr_max) {
1729         cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1730     }
1731     if (has_iops_max) {
1732         cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1733     }
1734     if (has_iops_rd_max) {
1735         cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1736     }
1737     if (has_iops_wr_max) {
1738         cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1739     }
1740 
1741     if (has_iops_size) {
1742         cfg.op_size = iops_size;
1743     }
1744 
1745     if (!check_throttle_config(&cfg, errp)) {
1746         return;
1747     }
1748 
1749     aio_context = bdrv_get_aio_context(bs);
1750     aio_context_acquire(aio_context);
1751 
1752     if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1753         bdrv_io_limits_enable(bs);
1754     } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1755         bdrv_io_limits_disable(bs);
1756     }
1757 
1758     if (bs->io_limits_enabled) {
1759         bdrv_set_io_limits(bs, &cfg);
1760     }
1761 
1762     aio_context_release(aio_context);
1763 }
1764 
1765 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1766 {
1767     const char *id = qdict_get_str(qdict, "id");
1768     BlockDriverState *bs;
1769     DriveInfo *dinfo;
1770     AioContext *aio_context;
1771     Error *local_err = NULL;
1772 
1773     bs = bdrv_find(id);
1774     if (!bs) {
1775         error_report("Device '%s' not found", id);
1776         return -1;
1777     }
1778 
1779     dinfo = drive_get_by_blockdev(bs);
1780     if (dinfo && !dinfo->enable_auto_del) {
1781         error_report("Deleting device added with blockdev-add"
1782                      " is not supported");
1783         return -1;
1784     }
1785 
1786     aio_context = bdrv_get_aio_context(bs);
1787     aio_context_acquire(aio_context);
1788 
1789     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1790         error_report("%s", error_get_pretty(local_err));
1791         error_free(local_err);
1792         aio_context_release(aio_context);
1793         return -1;
1794     }
1795 
1796     /* quiesce block driver; prevent further io */
1797     bdrv_drain_all();
1798     bdrv_flush(bs);
1799     bdrv_close(bs);
1800 
1801     /* if we have a device attached to this BlockDriverState
1802      * then we need to make the drive anonymous until the device
1803      * can be removed.  If this is a drive with no device backing
1804      * then we can just get rid of the block driver state right here.
1805      */
1806     if (bdrv_get_attached_dev(bs)) {
1807         bdrv_make_anon(bs);
1808 
1809         /* Further I/O must not pause the guest */
1810         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1811                           BLOCKDEV_ON_ERROR_REPORT);
1812     } else {
1813         drive_del(dinfo);
1814     }
1815 
1816     aio_context_release(aio_context);
1817     return 0;
1818 }
1819 
1820 void qmp_block_resize(bool has_device, const char *device,
1821                       bool has_node_name, const char *node_name,
1822                       int64_t size, Error **errp)
1823 {
1824     Error *local_err = NULL;
1825     BlockDriverState *bs;
1826     AioContext *aio_context;
1827     int ret;
1828 
1829     bs = bdrv_lookup_bs(has_device ? device : NULL,
1830                         has_node_name ? node_name : NULL,
1831                         &local_err);
1832     if (local_err) {
1833         error_propagate(errp, local_err);
1834         return;
1835     }
1836 
1837     aio_context = bdrv_get_aio_context(bs);
1838     aio_context_acquire(aio_context);
1839 
1840     if (!bdrv_is_first_non_filter(bs)) {
1841         error_set(errp, QERR_FEATURE_DISABLED, "resize");
1842         goto out;
1843     }
1844 
1845     if (size < 0) {
1846         error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1847         goto out;
1848     }
1849 
1850     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
1851         error_set(errp, QERR_DEVICE_IN_USE, device);
1852         goto out;
1853     }
1854 
1855     /* complete all in-flight operations before resizing the device */
1856     bdrv_drain_all();
1857 
1858     ret = bdrv_truncate(bs, size);
1859     switch (ret) {
1860     case 0:
1861         break;
1862     case -ENOMEDIUM:
1863         error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1864         break;
1865     case -ENOTSUP:
1866         error_set(errp, QERR_UNSUPPORTED);
1867         break;
1868     case -EACCES:
1869         error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1870         break;
1871     case -EBUSY:
1872         error_set(errp, QERR_DEVICE_IN_USE, device);
1873         break;
1874     default:
1875         error_setg_errno(errp, -ret, "Could not resize");
1876         break;
1877     }
1878 
1879 out:
1880     aio_context_release(aio_context);
1881 }
1882 
1883 static void block_job_cb(void *opaque, int ret)
1884 {
1885     BlockDriverState *bs = opaque;
1886     const char *msg = NULL;
1887 
1888     trace_block_job_cb(bs, bs->job, ret);
1889 
1890     assert(bs->job);
1891 
1892     if (ret < 0) {
1893         msg = strerror(-ret);
1894     }
1895 
1896     if (block_job_is_cancelled(bs->job)) {
1897         block_job_event_cancelled(bs->job);
1898     } else {
1899         block_job_event_completed(bs->job, msg);
1900     }
1901 
1902     bdrv_put_ref_bh_schedule(bs);
1903 }
1904 
1905 void qmp_block_stream(const char *device,
1906                       bool has_base, const char *base,
1907                       bool has_backing_file, const char *backing_file,
1908                       bool has_speed, int64_t speed,
1909                       bool has_on_error, BlockdevOnError on_error,
1910                       Error **errp)
1911 {
1912     BlockDriverState *bs;
1913     BlockDriverState *base_bs = NULL;
1914     Error *local_err = NULL;
1915     const char *base_name = NULL;
1916 
1917     if (!has_on_error) {
1918         on_error = BLOCKDEV_ON_ERROR_REPORT;
1919     }
1920 
1921     bs = bdrv_find(device);
1922     if (!bs) {
1923         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1924         return;
1925     }
1926 
1927     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1928         return;
1929     }
1930 
1931     if (has_base) {
1932         base_bs = bdrv_find_backing_image(bs, base);
1933         if (base_bs == NULL) {
1934             error_set(errp, QERR_BASE_NOT_FOUND, base);
1935             return;
1936         }
1937         base_name = base;
1938     }
1939 
1940     /* if we are streaming the entire chain, the result will have no backing
1941      * file, and specifying one is therefore an error */
1942     if (base_bs == NULL && has_backing_file) {
1943         error_setg(errp, "backing file specified, but streaming the "
1944                          "entire chain");
1945         return;
1946     }
1947 
1948     /* backing_file string overrides base bs filename */
1949     base_name = has_backing_file ? backing_file : base_name;
1950 
1951     stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
1952                  on_error, block_job_cb, bs, &local_err);
1953     if (local_err) {
1954         error_propagate(errp, local_err);
1955         return;
1956     }
1957 
1958     trace_qmp_block_stream(bs, bs->job);
1959 }
1960 
1961 void qmp_block_commit(const char *device,
1962                       bool has_base, const char *base,
1963                       bool has_top, const char *top,
1964                       bool has_backing_file, const char *backing_file,
1965                       bool has_speed, int64_t speed,
1966                       Error **errp)
1967 {
1968     BlockDriverState *bs;
1969     BlockDriverState *base_bs, *top_bs;
1970     Error *local_err = NULL;
1971     /* This will be part of the QMP command, if/when the
1972      * BlockdevOnError change for blkmirror makes it in
1973      */
1974     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1975 
1976     if (!has_speed) {
1977         speed = 0;
1978     }
1979 
1980     /* drain all i/o before commits */
1981     bdrv_drain_all();
1982 
1983     /* Important Note:
1984      *  libvirt relies on the DeviceNotFound error class in order to probe for
1985      *  live commit feature versions; for this to work, we must make sure to
1986      *  perform the device lookup before any generic errors that may occur in a
1987      *  scenario in which all optional arguments are omitted. */
1988     bs = bdrv_find(device);
1989     if (!bs) {
1990         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1991         return;
1992     }
1993 
1994     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
1995         return;
1996     }
1997 
1998     /* default top_bs is the active layer */
1999     top_bs = bs;
2000 
2001     if (has_top && top) {
2002         if (strcmp(bs->filename, top) != 0) {
2003             top_bs = bdrv_find_backing_image(bs, top);
2004         }
2005     }
2006 
2007     if (top_bs == NULL) {
2008         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2009         return;
2010     }
2011 
2012     if (has_base && base) {
2013         base_bs = bdrv_find_backing_image(top_bs, base);
2014     } else {
2015         base_bs = bdrv_find_base(top_bs);
2016     }
2017 
2018     if (base_bs == NULL) {
2019         error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2020         return;
2021     }
2022 
2023     /* Do not allow attempts to commit an image into itself */
2024     if (top_bs == base_bs) {
2025         error_setg(errp, "cannot commit an image into itself");
2026         return;
2027     }
2028 
2029     if (top_bs == bs) {
2030         if (has_backing_file) {
2031             error_setg(errp, "'backing-file' specified,"
2032                              " but 'top' is the active layer");
2033             return;
2034         }
2035         commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2036                             bs, &local_err);
2037     } else {
2038         commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2039                      has_backing_file ? backing_file : NULL, &local_err);
2040     }
2041     if (local_err != NULL) {
2042         error_propagate(errp, local_err);
2043         return;
2044     }
2045 }
2046 
2047 void qmp_drive_backup(const char *device, const char *target,
2048                       bool has_format, const char *format,
2049                       enum MirrorSyncMode sync,
2050                       bool has_mode, enum NewImageMode mode,
2051                       bool has_speed, int64_t speed,
2052                       bool has_on_source_error, BlockdevOnError on_source_error,
2053                       bool has_on_target_error, BlockdevOnError on_target_error,
2054                       Error **errp)
2055 {
2056     BlockDriverState *bs;
2057     BlockDriverState *target_bs;
2058     BlockDriverState *source = NULL;
2059     BlockDriver *drv = NULL;
2060     Error *local_err = NULL;
2061     int flags;
2062     int64_t size;
2063     int ret;
2064 
2065     if (!has_speed) {
2066         speed = 0;
2067     }
2068     if (!has_on_source_error) {
2069         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2070     }
2071     if (!has_on_target_error) {
2072         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2073     }
2074     if (!has_mode) {
2075         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2076     }
2077 
2078     bs = bdrv_find(device);
2079     if (!bs) {
2080         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2081         return;
2082     }
2083 
2084     if (!bdrv_is_inserted(bs)) {
2085         error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2086         return;
2087     }
2088 
2089     if (!has_format) {
2090         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2091     }
2092     if (format) {
2093         drv = bdrv_find_format(format);
2094         if (!drv) {
2095             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2096             return;
2097         }
2098     }
2099 
2100     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2101         return;
2102     }
2103 
2104     flags = bs->open_flags | BDRV_O_RDWR;
2105 
2106     /* See if we have a backing HD we can use to create our new image
2107      * on top of. */
2108     if (sync == MIRROR_SYNC_MODE_TOP) {
2109         source = bs->backing_hd;
2110         if (!source) {
2111             sync = MIRROR_SYNC_MODE_FULL;
2112         }
2113     }
2114     if (sync == MIRROR_SYNC_MODE_NONE) {
2115         source = bs;
2116     }
2117 
2118     size = bdrv_getlength(bs);
2119     if (size < 0) {
2120         error_setg_errno(errp, -size, "bdrv_getlength failed");
2121         return;
2122     }
2123 
2124     if (mode != NEW_IMAGE_MODE_EXISTING) {
2125         assert(format && drv);
2126         if (source) {
2127             bdrv_img_create(target, format, source->filename,
2128                             source->drv->format_name, NULL,
2129                             size, flags, &local_err, false);
2130         } else {
2131             bdrv_img_create(target, format, NULL, NULL, NULL,
2132                             size, flags, &local_err, false);
2133         }
2134     }
2135 
2136     if (local_err) {
2137         error_propagate(errp, local_err);
2138         return;
2139     }
2140 
2141     target_bs = NULL;
2142     ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2143     if (ret < 0) {
2144         error_propagate(errp, local_err);
2145         return;
2146     }
2147 
2148     backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2149                  block_job_cb, bs, &local_err);
2150     if (local_err != NULL) {
2151         bdrv_unref(target_bs);
2152         error_propagate(errp, local_err);
2153         return;
2154     }
2155 }
2156 
2157 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2158 {
2159     return bdrv_named_nodes_list();
2160 }
2161 
2162 #define DEFAULT_MIRROR_BUF_SIZE   (10 << 20)
2163 
2164 void qmp_drive_mirror(const char *device, const char *target,
2165                       bool has_format, const char *format,
2166                       bool has_node_name, const char *node_name,
2167                       bool has_replaces, const char *replaces,
2168                       enum MirrorSyncMode sync,
2169                       bool has_mode, enum NewImageMode mode,
2170                       bool has_speed, int64_t speed,
2171                       bool has_granularity, uint32_t granularity,
2172                       bool has_buf_size, int64_t buf_size,
2173                       bool has_on_source_error, BlockdevOnError on_source_error,
2174                       bool has_on_target_error, BlockdevOnError on_target_error,
2175                       Error **errp)
2176 {
2177     BlockDriverState *bs;
2178     BlockDriverState *source, *target_bs;
2179     BlockDriver *drv = NULL;
2180     Error *local_err = NULL;
2181     QDict *options = NULL;
2182     int flags;
2183     int64_t size;
2184     int ret;
2185 
2186     if (!has_speed) {
2187         speed = 0;
2188     }
2189     if (!has_on_source_error) {
2190         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2191     }
2192     if (!has_on_target_error) {
2193         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2194     }
2195     if (!has_mode) {
2196         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2197     }
2198     if (!has_granularity) {
2199         granularity = 0;
2200     }
2201     if (!has_buf_size) {
2202         buf_size = DEFAULT_MIRROR_BUF_SIZE;
2203     }
2204 
2205     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2206         error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2207                   "a value in range [512B, 64MB]");
2208         return;
2209     }
2210     if (granularity & (granularity - 1)) {
2211         error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2212         return;
2213     }
2214 
2215     bs = bdrv_find(device);
2216     if (!bs) {
2217         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2218         return;
2219     }
2220 
2221     if (!bdrv_is_inserted(bs)) {
2222         error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2223         return;
2224     }
2225 
2226     if (!has_format) {
2227         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2228     }
2229     if (format) {
2230         drv = bdrv_find_format(format);
2231         if (!drv) {
2232             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2233             return;
2234         }
2235     }
2236 
2237     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2238         return;
2239     }
2240 
2241     flags = bs->open_flags | BDRV_O_RDWR;
2242     source = bs->backing_hd;
2243     if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2244         sync = MIRROR_SYNC_MODE_FULL;
2245     }
2246     if (sync == MIRROR_SYNC_MODE_NONE) {
2247         source = bs;
2248     }
2249 
2250     size = bdrv_getlength(bs);
2251     if (size < 0) {
2252         error_setg_errno(errp, -size, "bdrv_getlength failed");
2253         return;
2254     }
2255 
2256     if (has_replaces) {
2257         BlockDriverState *to_replace_bs;
2258 
2259         if (!has_node_name) {
2260             error_setg(errp, "a node-name must be provided when replacing a"
2261                              " named node of the graph");
2262             return;
2263         }
2264 
2265         to_replace_bs = check_to_replace_node(replaces, &local_err);
2266 
2267         if (!to_replace_bs) {
2268             error_propagate(errp, local_err);
2269             return;
2270         }
2271 
2272         if (size != bdrv_getlength(to_replace_bs)) {
2273             error_setg(errp, "cannot replace image with a mirror image of "
2274                              "different size");
2275             return;
2276         }
2277     }
2278 
2279     if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2280         && mode != NEW_IMAGE_MODE_EXISTING)
2281     {
2282         /* create new image w/o backing file */
2283         assert(format && drv);
2284         bdrv_img_create(target, format,
2285                         NULL, NULL, NULL, size, flags, &local_err, false);
2286     } else {
2287         switch (mode) {
2288         case NEW_IMAGE_MODE_EXISTING:
2289             break;
2290         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2291             /* create new image with backing file */
2292             bdrv_img_create(target, format,
2293                             source->filename,
2294                             source->drv->format_name,
2295                             NULL, size, flags, &local_err, false);
2296             break;
2297         default:
2298             abort();
2299         }
2300     }
2301 
2302     if (local_err) {
2303         error_propagate(errp, local_err);
2304         return;
2305     }
2306 
2307     if (has_node_name) {
2308         options = qdict_new();
2309         qdict_put(options, "node-name", qstring_from_str(node_name));
2310     }
2311 
2312     /* Mirroring takes care of copy-on-write using the source's backing
2313      * file.
2314      */
2315     target_bs = NULL;
2316     ret = bdrv_open(&target_bs, target, NULL, options,
2317                     flags | BDRV_O_NO_BACKING, drv, &local_err);
2318     if (ret < 0) {
2319         error_propagate(errp, local_err);
2320         return;
2321     }
2322 
2323     /* pass the node name to replace to mirror start since it's loose coupling
2324      * and will allow to check whether the node still exist at mirror completion
2325      */
2326     mirror_start(bs, target_bs,
2327                  has_replaces ? replaces : NULL,
2328                  speed, granularity, buf_size, sync,
2329                  on_source_error, on_target_error,
2330                  block_job_cb, bs, &local_err);
2331     if (local_err != NULL) {
2332         bdrv_unref(target_bs);
2333         error_propagate(errp, local_err);
2334         return;
2335     }
2336 }
2337 
2338 static BlockJob *find_block_job(const char *device)
2339 {
2340     BlockDriverState *bs;
2341 
2342     bs = bdrv_find(device);
2343     if (!bs || !bs->job) {
2344         return NULL;
2345     }
2346     return bs->job;
2347 }
2348 
2349 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2350 {
2351     BlockJob *job = find_block_job(device);
2352 
2353     if (!job) {
2354         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2355         return;
2356     }
2357 
2358     block_job_set_speed(job, speed, errp);
2359 }
2360 
2361 void qmp_block_job_cancel(const char *device,
2362                           bool has_force, bool force, Error **errp)
2363 {
2364     BlockJob *job = find_block_job(device);
2365 
2366     if (!has_force) {
2367         force = false;
2368     }
2369 
2370     if (!job) {
2371         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2372         return;
2373     }
2374     if (job->paused && !force) {
2375         error_setg(errp, "The block job for device '%s' is currently paused",
2376                    device);
2377         return;
2378     }
2379 
2380     trace_qmp_block_job_cancel(job);
2381     block_job_cancel(job);
2382 }
2383 
2384 void qmp_block_job_pause(const char *device, Error **errp)
2385 {
2386     BlockJob *job = find_block_job(device);
2387 
2388     if (!job) {
2389         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2390         return;
2391     }
2392 
2393     trace_qmp_block_job_pause(job);
2394     block_job_pause(job);
2395 }
2396 
2397 void qmp_block_job_resume(const char *device, Error **errp)
2398 {
2399     BlockJob *job = find_block_job(device);
2400 
2401     if (!job) {
2402         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2403         return;
2404     }
2405 
2406     trace_qmp_block_job_resume(job);
2407     block_job_resume(job);
2408 }
2409 
2410 void qmp_block_job_complete(const char *device, Error **errp)
2411 {
2412     BlockJob *job = find_block_job(device);
2413 
2414     if (!job) {
2415         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2416         return;
2417     }
2418 
2419     trace_qmp_block_job_complete(job);
2420     block_job_complete(job, errp);
2421 }
2422 
2423 void qmp_change_backing_file(const char *device,
2424                              const char *image_node_name,
2425                              const char *backing_file,
2426                              Error **errp)
2427 {
2428     BlockDriverState *bs = NULL;
2429     BlockDriverState *image_bs = NULL;
2430     Error *local_err = NULL;
2431     bool ro;
2432     int open_flags;
2433     int ret;
2434 
2435     /* find the top layer BDS of the chain */
2436     bs = bdrv_find(device);
2437     if (!bs) {
2438         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2439         return;
2440     }
2441 
2442     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2443     if (local_err) {
2444         error_propagate(errp, local_err);
2445         return;
2446     }
2447 
2448     if (!image_bs) {
2449         error_setg(errp, "image file not found");
2450         return;
2451     }
2452 
2453     if (bdrv_find_base(image_bs) == image_bs) {
2454         error_setg(errp, "not allowing backing file change on an image "
2455                          "without a backing file");
2456         return;
2457     }
2458 
2459     /* even though we are not necessarily operating on bs, we need it to
2460      * determine if block ops are currently prohibited on the chain */
2461     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2462         return;
2463     }
2464 
2465     /* final sanity check */
2466     if (!bdrv_chain_contains(bs, image_bs)) {
2467         error_setg(errp, "'%s' and image file are not in the same chain",
2468                    device);
2469         return;
2470     }
2471 
2472     /* if not r/w, reopen to make r/w */
2473     open_flags = image_bs->open_flags;
2474     ro = bdrv_is_read_only(image_bs);
2475 
2476     if (ro) {
2477         bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2478         if (local_err) {
2479             error_propagate(errp, local_err);
2480             return;
2481         }
2482     }
2483 
2484     ret = bdrv_change_backing_file(image_bs, backing_file,
2485                                image_bs->drv ? image_bs->drv->format_name : "");
2486 
2487     if (ret < 0) {
2488         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2489                          backing_file);
2490         /* don't exit here, so we can try to restore open flags if
2491          * appropriate */
2492     }
2493 
2494     if (ro) {
2495         bdrv_reopen(image_bs, open_flags, &local_err);
2496         if (local_err) {
2497             error_propagate(errp, local_err); /* will preserve prior errp */
2498         }
2499     }
2500 }
2501 
2502 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2503 {
2504     QmpOutputVisitor *ov = qmp_output_visitor_new();
2505     DriveInfo *dinfo;
2506     QObject *obj;
2507     QDict *qdict;
2508     Error *local_err = NULL;
2509 
2510     /* Require an ID in the top level */
2511     if (!options->has_id) {
2512         error_setg(errp, "Block device needs an ID");
2513         goto fail;
2514     }
2515 
2516     /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2517      * cache.direct=false instead of silently switching to aio=threads, except
2518      * when called from drive_new().
2519      *
2520      * For now, simply forbidding the combination for all drivers will do. */
2521     if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2522         bool direct = options->has_cache &&
2523                       options->cache->has_direct &&
2524                       options->cache->direct;
2525         if (!direct) {
2526             error_setg(errp, "aio=native requires cache.direct=true");
2527             goto fail;
2528         }
2529     }
2530 
2531     visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2532                                &options, NULL, &local_err);
2533     if (local_err) {
2534         error_propagate(errp, local_err);
2535         goto fail;
2536     }
2537 
2538     obj = qmp_output_get_qobject(ov);
2539     qdict = qobject_to_qdict(obj);
2540 
2541     qdict_flatten(qdict);
2542 
2543     dinfo = blockdev_init(NULL, qdict, &local_err);
2544     if (local_err) {
2545         error_propagate(errp, local_err);
2546         goto fail;
2547     }
2548 
2549     if (bdrv_key_required(dinfo->bdrv)) {
2550         drive_del(dinfo);
2551         error_setg(errp, "blockdev-add doesn't support encrypted devices");
2552         goto fail;
2553     }
2554 
2555 fail:
2556     qmp_output_visitor_cleanup(ov);
2557 }
2558 
2559 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2560 {
2561     BlockJobInfoList **prev = opaque;
2562     BlockJob *job = bs->job;
2563 
2564     if (job) {
2565         BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2566         elem->value = block_job_query(bs->job);
2567         (*prev)->next = elem;
2568         *prev = elem;
2569     }
2570 }
2571 
2572 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2573 {
2574     /* Dummy is a fake list element for holding the head pointer */
2575     BlockJobInfoList dummy = {};
2576     BlockJobInfoList *prev = &dummy;
2577     bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2578     return dummy.next;
2579 }
2580 
2581 QemuOptsList qemu_common_drive_opts = {
2582     .name = "drive",
2583     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2584     .desc = {
2585         {
2586             .name = "snapshot",
2587             .type = QEMU_OPT_BOOL,
2588             .help = "enable/disable snapshot mode",
2589         },{
2590             .name = "discard",
2591             .type = QEMU_OPT_STRING,
2592             .help = "discard operation (ignore/off, unmap/on)",
2593         },{
2594             .name = "cache.writeback",
2595             .type = QEMU_OPT_BOOL,
2596             .help = "enables writeback mode for any caches",
2597         },{
2598             .name = "cache.direct",
2599             .type = QEMU_OPT_BOOL,
2600             .help = "enables use of O_DIRECT (bypass the host page cache)",
2601         },{
2602             .name = "cache.no-flush",
2603             .type = QEMU_OPT_BOOL,
2604             .help = "ignore any flush requests for the device",
2605         },{
2606             .name = "aio",
2607             .type = QEMU_OPT_STRING,
2608             .help = "host AIO implementation (threads, native)",
2609         },{
2610             .name = "format",
2611             .type = QEMU_OPT_STRING,
2612             .help = "disk format (raw, qcow2, ...)",
2613         },{
2614             .name = "rerror",
2615             .type = QEMU_OPT_STRING,
2616             .help = "read error action",
2617         },{
2618             .name = "werror",
2619             .type = QEMU_OPT_STRING,
2620             .help = "write error action",
2621         },{
2622             .name = "read-only",
2623             .type = QEMU_OPT_BOOL,
2624             .help = "open drive file as read-only",
2625         },{
2626             .name = "throttling.iops-total",
2627             .type = QEMU_OPT_NUMBER,
2628             .help = "limit total I/O operations per second",
2629         },{
2630             .name = "throttling.iops-read",
2631             .type = QEMU_OPT_NUMBER,
2632             .help = "limit read operations per second",
2633         },{
2634             .name = "throttling.iops-write",
2635             .type = QEMU_OPT_NUMBER,
2636             .help = "limit write operations per second",
2637         },{
2638             .name = "throttling.bps-total",
2639             .type = QEMU_OPT_NUMBER,
2640             .help = "limit total bytes per second",
2641         },{
2642             .name = "throttling.bps-read",
2643             .type = QEMU_OPT_NUMBER,
2644             .help = "limit read bytes per second",
2645         },{
2646             .name = "throttling.bps-write",
2647             .type = QEMU_OPT_NUMBER,
2648             .help = "limit write bytes per second",
2649         },{
2650             .name = "throttling.iops-total-max",
2651             .type = QEMU_OPT_NUMBER,
2652             .help = "I/O operations burst",
2653         },{
2654             .name = "throttling.iops-read-max",
2655             .type = QEMU_OPT_NUMBER,
2656             .help = "I/O operations read burst",
2657         },{
2658             .name = "throttling.iops-write-max",
2659             .type = QEMU_OPT_NUMBER,
2660             .help = "I/O operations write burst",
2661         },{
2662             .name = "throttling.bps-total-max",
2663             .type = QEMU_OPT_NUMBER,
2664             .help = "total bytes burst",
2665         },{
2666             .name = "throttling.bps-read-max",
2667             .type = QEMU_OPT_NUMBER,
2668             .help = "total bytes read burst",
2669         },{
2670             .name = "throttling.bps-write-max",
2671             .type = QEMU_OPT_NUMBER,
2672             .help = "total bytes write burst",
2673         },{
2674             .name = "throttling.iops-size",
2675             .type = QEMU_OPT_NUMBER,
2676             .help = "when limiting by iops max size of an I/O in bytes",
2677         },{
2678             .name = "copy-on-read",
2679             .type = QEMU_OPT_BOOL,
2680             .help = "copy read data from backing file into image file",
2681         },{
2682             .name = "detect-zeroes",
2683             .type = QEMU_OPT_STRING,
2684             .help = "try to optimize zero writes (off, on, unmap)",
2685         },
2686         { /* end of list */ }
2687     },
2688 };
2689 
2690 QemuOptsList qemu_drive_opts = {
2691     .name = "drive",
2692     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2693     .desc = {
2694         /*
2695          * no elements => accept any params
2696          * validation will happen later
2697          */
2698         { /* end of list */ }
2699     },
2700 };
2701