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