Revert "display: move display functionality to Qt5 GUI"
[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 "qemu/osdep.h"
34 #include "sysemu/block-backend.h"
35 #include "sysemu/blockdev.h"
36 #include "hw/block/block.h"
37 #include "block/blockjob.h"
38 #include "block/throttle-groups.h"
39 #include "monitor/monitor.h"
40 #include "qemu/error-report.h"
41 #include "qemu/option.h"
42 #include "qemu/config-file.h"
43 #include "qapi/qmp/types.h"
44 #include "qapi-visit.h"
45 #include "qapi/qmp/qerror.h"
46 #include "qapi/qmp-output-visitor.h"
47 #include "qapi/util.h"
48 #include "sysemu/sysemu.h"
49 #include "block/block_int.h"
50 #include "qmp-commands.h"
51 #include "trace.h"
52 #include "sysemu/arch_init.h"
53 #include "qemu/cutils.h"
54 #include "qemu/help_option.h"
55
56 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
57     QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
58
59 #ifdef CONFIG_MARU
60 #include "tizen/src/util/exported_strings.h"
61 #endif
62
63 static const char *const if_name[IF_COUNT] = {
64     [IF_NONE] = "none",
65     [IF_IDE] = "ide",
66     [IF_SCSI] = "scsi",
67     [IF_FLOPPY] = "floppy",
68     [IF_PFLASH] = "pflash",
69     [IF_MTD] = "mtd",
70     [IF_SD] = "sd",
71     [IF_VIRTIO] = "virtio",
72     [IF_XEN] = "xen",
73 };
74
75 static int if_max_devs[IF_COUNT] = {
76     /*
77      * Do not change these numbers!  They govern how drive option
78      * index maps to unit and bus.  That mapping is ABI.
79      *
80      * All controllers used to imlement if=T drives need to support
81      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
82      * Otherwise, some index values map to "impossible" bus, unit
83      * values.
84      *
85      * For instance, if you change [IF_SCSI] to 255, -drive
86      * if=scsi,index=12 no longer means bus=1,unit=5, but
87      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
88      * the drive can't be set up.  Regression.
89      */
90     [IF_IDE] = 2,
91     [IF_SCSI] = 7,
92 };
93
94 /**
95  * Boards may call this to offer board-by-board overrides
96  * of the default, global values.
97  */
98 void override_max_devs(BlockInterfaceType type, int max_devs)
99 {
100     BlockBackend *blk;
101     DriveInfo *dinfo;
102
103     if (max_devs <= 0) {
104         return;
105     }
106
107     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
108         dinfo = blk_legacy_dinfo(blk);
109         if (dinfo->type == type) {
110             fprintf(stderr, "Cannot override units-per-bus property of"
111                     " the %s interface, because a drive of that type has"
112                     " already been added.\n", if_name[type]);
113             g_assert_not_reached();
114         }
115     }
116
117     if_max_devs[type] = max_devs;
118 }
119
120 /*
121  * We automatically delete the drive when a device using it gets
122  * unplugged.  Questionable feature, but we can't just drop it.
123  * Device models call blockdev_mark_auto_del() to schedule the
124  * automatic deletion, and generic qdev code calls blockdev_auto_del()
125  * when deletion is actually safe.
126  */
127 void blockdev_mark_auto_del(BlockBackend *blk)
128 {
129     DriveInfo *dinfo = blk_legacy_dinfo(blk);
130     BlockDriverState *bs = blk_bs(blk);
131     AioContext *aio_context;
132
133     if (!dinfo) {
134         return;
135     }
136
137     if (bs) {
138         aio_context = bdrv_get_aio_context(bs);
139         aio_context_acquire(aio_context);
140
141         if (bs->job) {
142             block_job_cancel(bs->job);
143         }
144
145         aio_context_release(aio_context);
146     }
147
148     dinfo->auto_del = 1;
149 }
150
151 void blockdev_auto_del(BlockBackend *blk)
152 {
153     DriveInfo *dinfo = blk_legacy_dinfo(blk);
154
155     if (dinfo && dinfo->auto_del) {
156         monitor_remove_blk(blk);
157         blk_unref(blk);
158     }
159 }
160
161 /**
162  * Returns the current mapping of how many units per bus
163  * a particular interface can support.
164  *
165  *  A positive integer indicates n units per bus.
166  *  0 implies the mapping has not been established.
167  * -1 indicates an invalid BlockInterfaceType was given.
168  */
169 int drive_get_max_devs(BlockInterfaceType type)
170 {
171     if (type >= IF_IDE && type < IF_COUNT) {
172         return if_max_devs[type];
173     }
174
175     return -1;
176 }
177
178 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
179 {
180     int max_devs = if_max_devs[type];
181     return max_devs ? index / max_devs : 0;
182 }
183
184 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
185 {
186     int max_devs = if_max_devs[type];
187     return max_devs ? index % max_devs : index;
188 }
189
190 QemuOpts *drive_def(const char *optstr)
191 {
192     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
193 }
194
195 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
196                     const char *optstr)
197 {
198     QemuOpts *opts;
199
200     opts = drive_def(optstr);
201     if (!opts) {
202         return NULL;
203     }
204     if (type != IF_DEFAULT) {
205         qemu_opt_set(opts, "if", if_name[type], &error_abort);
206     }
207     if (index >= 0) {
208         qemu_opt_set_number(opts, "index", index, &error_abort);
209     }
210     if (file)
211         qemu_opt_set(opts, "file", file, &error_abort);
212     return opts;
213 }
214
215 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
216 {
217     BlockBackend *blk;
218     DriveInfo *dinfo;
219
220     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
221         dinfo = blk_legacy_dinfo(blk);
222         if (dinfo && dinfo->type == type
223             && dinfo->bus == bus && dinfo->unit == unit) {
224             return dinfo;
225         }
226     }
227
228     return NULL;
229 }
230
231 bool drive_check_orphaned(void)
232 {
233     BlockBackend *blk;
234     DriveInfo *dinfo;
235     bool rs = false;
236
237     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
238         dinfo = blk_legacy_dinfo(blk);
239         /* If dinfo->bdrv->dev is NULL, it has no device attached. */
240         /* Unless this is a default drive, this may be an oversight. */
241         if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
242             dinfo->type != IF_NONE) {
243             fprintf(stderr, "Warning: Orphaned drive without device: "
244                     "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
245                     blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
246                     if_name[dinfo->type], dinfo->bus, dinfo->unit);
247             rs = true;
248         }
249     }
250
251     return rs;
252 }
253
254 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
255 {
256     return drive_get(type,
257                      drive_index_to_bus_id(type, index),
258                      drive_index_to_unit_id(type, index));
259 }
260
261 int drive_get_max_bus(BlockInterfaceType type)
262 {
263     int max_bus;
264     BlockBackend *blk;
265     DriveInfo *dinfo;
266
267     max_bus = -1;
268     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
269         dinfo = blk_legacy_dinfo(blk);
270         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
271             max_bus = dinfo->bus;
272         }
273     }
274     return max_bus;
275 }
276
277 /* Get a block device.  This should only be used for single-drive devices
278    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
279    appropriate bus.  */
280 DriveInfo *drive_get_next(BlockInterfaceType type)
281 {
282     static int next_block_unit[IF_COUNT];
283
284     return drive_get(type, 0, next_block_unit[type]++);
285 }
286
287 static void bdrv_format_print(void *opaque, const char *name)
288 {
289     error_printf(" %s", name);
290 }
291
292 typedef struct {
293     QEMUBH *bh;
294     BlockDriverState *bs;
295 } BDRVPutRefBH;
296
297 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
298 {
299     if (!strcmp(buf, "ignore")) {
300         return BLOCKDEV_ON_ERROR_IGNORE;
301     } else if (!is_read && !strcmp(buf, "enospc")) {
302         return BLOCKDEV_ON_ERROR_ENOSPC;
303     } else if (!strcmp(buf, "stop")) {
304         return BLOCKDEV_ON_ERROR_STOP;
305     } else if (!strcmp(buf, "report")) {
306         return BLOCKDEV_ON_ERROR_REPORT;
307     } else {
308         error_setg(errp, "'%s' invalid %s error action",
309                    buf, is_read ? "read" : "write");
310         return -1;
311     }
312 }
313
314 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
315                                   Error **errp)
316 {
317     const QListEntry *entry;
318     for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
319         switch (qobject_type(entry->value)) {
320
321         case QTYPE_QSTRING: {
322             unsigned long long length;
323             const char *str = qstring_get_str(qobject_to_qstring(entry->value));
324             if (parse_uint_full(str, &length, 10) == 0 &&
325                 length > 0 && length <= UINT_MAX) {
326                 block_acct_add_interval(stats, (unsigned) length);
327             } else {
328                 error_setg(errp, "Invalid interval length: %s", str);
329                 return false;
330             }
331             break;
332         }
333
334         case QTYPE_QINT: {
335             int64_t length = qint_get_int(qobject_to_qint(entry->value));
336             if (length > 0 && length <= UINT_MAX) {
337                 block_acct_add_interval(stats, (unsigned) length);
338             } else {
339                 error_setg(errp, "Invalid interval length: %" PRId64, length);
340                 return false;
341             }
342             break;
343         }
344
345         default:
346             error_setg(errp, "The specification of stats-intervals is invalid");
347             return false;
348         }
349     }
350     return true;
351 }
352
353 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
354
355 /* All parameters but @opts are optional and may be set to NULL. */
356 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
357     const char **throttling_group, ThrottleConfig *throttle_cfg,
358     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
359 {
360     const char *discard;
361     Error *local_error = NULL;
362     const char *aio;
363
364     if (bdrv_flags) {
365         if (!qemu_opt_get_bool(opts, "read-only", false)) {
366             *bdrv_flags |= BDRV_O_RDWR;
367         }
368         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
369             *bdrv_flags |= BDRV_O_COPY_ON_READ;
370         }
371
372         if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
373             if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
374                 error_setg(errp, "Invalid discard option");
375                 return;
376             }
377         }
378
379         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
380             if (!strcmp(aio, "native")) {
381                 *bdrv_flags |= BDRV_O_NATIVE_AIO;
382             } else if (!strcmp(aio, "threads")) {
383                 /* this is the default */
384             } else {
385                error_setg(errp, "invalid aio option");
386                return;
387             }
388         }
389     }
390
391     /* disk I/O throttling */
392     if (throttling_group) {
393         *throttling_group = qemu_opt_get(opts, "throttling.group");
394     }
395
396     if (throttle_cfg) {
397         throttle_config_init(throttle_cfg);
398         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
399             qemu_opt_get_number(opts, "throttling.bps-total", 0);
400         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
401             qemu_opt_get_number(opts, "throttling.bps-read", 0);
402         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
403             qemu_opt_get_number(opts, "throttling.bps-write", 0);
404         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
405             qemu_opt_get_number(opts, "throttling.iops-total", 0);
406         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
407             qemu_opt_get_number(opts, "throttling.iops-read", 0);
408         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
409             qemu_opt_get_number(opts, "throttling.iops-write", 0);
410
411         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
412             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
413         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
414             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
415         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
416             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
417         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
418             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
419         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
420             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
421         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
422             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
423
424         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
425             qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
426         throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length  =
427             qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
428         throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
429             qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
430         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
431             qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
432         throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
433             qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
434         throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
435             qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
436
437         throttle_cfg->op_size =
438             qemu_opt_get_number(opts, "throttling.iops-size", 0);
439
440         if (!throttle_is_valid(throttle_cfg, errp)) {
441             return;
442         }
443     }
444
445     if (detect_zeroes) {
446         *detect_zeroes =
447             qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
448                             qemu_opt_get(opts, "detect-zeroes"),
449                             BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
450                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
451                             &local_error);
452         if (local_error) {
453             error_propagate(errp, local_error);
454             return;
455         }
456
457         if (bdrv_flags &&
458             *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
459             !(*bdrv_flags & BDRV_O_UNMAP))
460         {
461             error_setg(errp, "setting detect-zeroes to unmap is not allowed "
462                              "without setting discard operation to unmap");
463             return;
464         }
465     }
466 }
467
468 /* Takes the ownership of bs_opts */
469 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
470                                    Error **errp)
471 {
472     const char *buf;
473     int bdrv_flags = 0;
474     int on_read_error, on_write_error;
475     bool account_invalid, account_failed;
476     bool writethrough;
477     BlockBackend *blk;
478     BlockDriverState *bs;
479     ThrottleConfig cfg;
480     int snapshot = 0;
481     Error *error = NULL;
482     QemuOpts *opts;
483     QDict *interval_dict = NULL;
484     QList *interval_list = NULL;
485     const char *id;
486     BlockdevDetectZeroesOptions detect_zeroes =
487         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
488     const char *throttling_group = NULL;
489
490     /* Check common options by copying from bs_opts to opts, all other options
491      * stay in bs_opts for processing by bdrv_open(). */
492     id = qdict_get_try_str(bs_opts, "id");
493     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
494     if (error) {
495         error_propagate(errp, error);
496         goto err_no_opts;
497     }
498
499     qemu_opts_absorb_qdict(opts, bs_opts, &error);
500     if (error) {
501         error_propagate(errp, error);
502         goto early_err;
503     }
504
505     if (id) {
506         qdict_del(bs_opts, "id");
507     }
508
509     /* extract parameters */
510     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
511
512     account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
513     account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
514
515     writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
516
517     qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
518     qdict_array_split(interval_dict, &interval_list);
519
520     if (qdict_size(interval_dict) != 0) {
521         error_setg(errp, "Invalid option stats-intervals.%s",
522                    qdict_first(interval_dict)->key);
523         goto early_err;
524     }
525
526     extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
527                                     &detect_zeroes, &error);
528     if (error) {
529         error_propagate(errp, error);
530         goto early_err;
531     }
532
533     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
534         if (is_help_option(buf)) {
535             error_printf("Supported formats:");
536             bdrv_iterate_format(bdrv_format_print, NULL);
537             error_printf("\n");
538             goto early_err;
539         }
540
541         if (qdict_haskey(bs_opts, "driver")) {
542             error_setg(errp, "Cannot specify both 'driver' and 'format'");
543             goto early_err;
544         }
545         qdict_put(bs_opts, "driver", qstring_from_str(buf));
546     }
547
548     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
549     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
550         on_write_error = parse_block_error_action(buf, 0, &error);
551         if (error) {
552             error_propagate(errp, error);
553             goto early_err;
554         }
555     }
556
557     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
558     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
559         on_read_error = parse_block_error_action(buf, 1, &error);
560         if (error) {
561             error_propagate(errp, error);
562             goto early_err;
563         }
564     }
565
566     if (snapshot) {
567         bdrv_flags |= BDRV_O_SNAPSHOT;
568     }
569
570     /* init */
571     if ((!file || !*file) && !qdict_size(bs_opts)) {
572         BlockBackendRootState *blk_rs;
573
574         blk = blk_new(errp);
575         if (!blk) {
576             goto early_err;
577         }
578
579         blk_rs = blk_get_root_state(blk);
580         blk_rs->open_flags    = bdrv_flags;
581         blk_rs->read_only     = !(bdrv_flags & BDRV_O_RDWR);
582         blk_rs->detect_zeroes = detect_zeroes;
583
584         if (throttle_enabled(&cfg)) {
585             if (!throttling_group) {
586                 throttling_group = blk_name(blk);
587             }
588             blk_rs->throttle_group = g_strdup(throttling_group);
589             blk_rs->throttle_state = throttle_group_incref(throttling_group);
590             blk_rs->throttle_state->cfg = cfg;
591         }
592
593         QDECREF(bs_opts);
594     } else {
595         if (file && !*file) {
596             file = NULL;
597         }
598
599         /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
600          * with other callers) rather than what we want as the real defaults.
601          * Apply the defaults here instead. */
602         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
603         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
604         assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
605
606         if (runstate_check(RUN_STATE_INMIGRATE)) {
607             bdrv_flags |= BDRV_O_INACTIVE;
608         }
609
610         blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
611         if (!blk) {
612             goto err_no_bs_opts;
613         }
614         bs = blk_bs(blk);
615
616         bs->detect_zeroes = detect_zeroes;
617
618         /* disk I/O throttling */
619         if (throttle_enabled(&cfg)) {
620             if (!throttling_group) {
621                 throttling_group = blk_name(blk);
622             }
623             bdrv_io_limits_enable(bs, throttling_group);
624             bdrv_set_io_limits(bs, &cfg);
625         }
626
627         if (bdrv_key_required(bs)) {
628             autostart = 0;
629         }
630
631         block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
632
633         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
634             blk_unref(blk);
635             blk = NULL;
636             goto err_no_bs_opts;
637         }
638     }
639
640     blk_set_enable_write_cache(blk, !writethrough);
641     blk_set_on_error(blk, on_read_error, on_write_error);
642
643     if (!monitor_add_blk(blk, qemu_opts_id(opts), errp)) {
644         blk_unref(blk);
645         blk = NULL;
646         goto err_no_bs_opts;
647     }
648
649 err_no_bs_opts:
650     qemu_opts_del(opts);
651     QDECREF(interval_dict);
652     QDECREF(interval_list);
653     return blk;
654
655 early_err:
656     qemu_opts_del(opts);
657     QDECREF(interval_dict);
658     QDECREF(interval_list);
659 err_no_opts:
660     QDECREF(bs_opts);
661     return NULL;
662 }
663
664 static QemuOptsList qemu_root_bds_opts;
665
666 /* Takes the ownership of bs_opts */
667 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
668 {
669     BlockDriverState *bs;
670     QemuOpts *opts;
671     Error *local_error = NULL;
672     BlockdevDetectZeroesOptions detect_zeroes;
673     int ret;
674     int bdrv_flags = 0;
675
676     opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
677     if (!opts) {
678         goto fail;
679     }
680
681     qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
682     if (local_error) {
683         error_propagate(errp, local_error);
684         goto fail;
685     }
686
687     extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
688                                     &detect_zeroes, &local_error);
689     if (local_error) {
690         error_propagate(errp, local_error);
691         goto fail;
692     }
693
694     /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
695      * with other callers) rather than what we want as the real defaults.
696      * Apply the defaults here instead. */
697     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
698     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
699
700     if (runstate_check(RUN_STATE_INMIGRATE)) {
701         bdrv_flags |= BDRV_O_INACTIVE;
702     }
703
704     bs = NULL;
705     ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
706     if (ret < 0) {
707         goto fail_no_bs_opts;
708     }
709
710     bs->detect_zeroes = detect_zeroes;
711
712 fail_no_bs_opts:
713     qemu_opts_del(opts);
714     return bs;
715
716 fail:
717     qemu_opts_del(opts);
718     QDECREF(bs_opts);
719     return NULL;
720 }
721
722 void blockdev_close_all_bdrv_states(void)
723 {
724     BlockDriverState *bs, *next_bs;
725
726     QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
727         AioContext *ctx = bdrv_get_aio_context(bs);
728
729         aio_context_acquire(ctx);
730         bdrv_unref(bs);
731         aio_context_release(ctx);
732     }
733 }
734
735 /* Iterates over the list of monitor-owned BlockDriverStates */
736 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
737 {
738     return bs ? QTAILQ_NEXT(bs, monitor_list)
739               : QTAILQ_FIRST(&monitor_bdrv_states);
740 }
741
742 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
743                             Error **errp)
744 {
745     const char *value;
746
747     value = qemu_opt_get(opts, from);
748     if (value) {
749         if (qemu_opt_find(opts, to)) {
750             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
751                        "same time", to, from);
752             return;
753         }
754     }
755
756     /* rename all items in opts */
757     while ((value = qemu_opt_get(opts, from))) {
758         qemu_opt_set(opts, to, value, &error_abort);
759         qemu_opt_unset(opts, from);
760     }
761 }
762
763 QemuOptsList qemu_legacy_drive_opts = {
764     .name = "drive",
765     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
766     .desc = {
767         {
768             .name = "bus",
769             .type = QEMU_OPT_NUMBER,
770             .help = "bus number",
771         },{
772             .name = "unit",
773             .type = QEMU_OPT_NUMBER,
774             .help = "unit number (i.e. lun for scsi)",
775         },{
776             .name = "index",
777             .type = QEMU_OPT_NUMBER,
778             .help = "index number",
779         },{
780             .name = "media",
781             .type = QEMU_OPT_STRING,
782             .help = "media type (disk, cdrom)",
783         },{
784             .name = "if",
785             .type = QEMU_OPT_STRING,
786             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
787         },{
788             .name = "cyls",
789             .type = QEMU_OPT_NUMBER,
790             .help = "number of cylinders (ide disk geometry)",
791         },{
792             .name = "heads",
793             .type = QEMU_OPT_NUMBER,
794             .help = "number of heads (ide disk geometry)",
795         },{
796             .name = "secs",
797             .type = QEMU_OPT_NUMBER,
798             .help = "number of sectors (ide disk geometry)",
799         },{
800             .name = "trans",
801             .type = QEMU_OPT_STRING,
802             .help = "chs translation (auto, lba, none)",
803         },{
804             .name = "boot",
805             .type = QEMU_OPT_BOOL,
806             .help = "(deprecated, ignored)",
807         },{
808             .name = "addr",
809             .type = QEMU_OPT_STRING,
810             .help = "pci address (virtio only)",
811         },{
812             .name = "serial",
813             .type = QEMU_OPT_STRING,
814             .help = "disk serial number",
815         },{
816             .name = "file",
817             .type = QEMU_OPT_STRING,
818             .help = "file name",
819         },
820
821         /* Options that are passed on, but have special semantics with -drive */
822         {
823             .name = "read-only",
824             .type = QEMU_OPT_BOOL,
825             .help = "open drive file as read-only",
826         },{
827             .name = "rerror",
828             .type = QEMU_OPT_STRING,
829             .help = "read error action",
830         },{
831             .name = "werror",
832             .type = QEMU_OPT_STRING,
833             .help = "write error action",
834         },{
835             .name = "copy-on-read",
836             .type = QEMU_OPT_BOOL,
837             .help = "copy read data from backing file into image file",
838         },
839
840         { /* end of list */ }
841     },
842 };
843
844 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
845 {
846     const char *value;
847     BlockBackend *blk;
848     DriveInfo *dinfo = NULL;
849     QDict *bs_opts;
850     QemuOpts *legacy_opts;
851     DriveMediaType media = MEDIA_DISK;
852     BlockInterfaceType type;
853     int cyls, heads, secs, translation;
854     int max_devs, bus_id, unit_id, index;
855     const char *devaddr;
856     const char *werror, *rerror;
857     bool read_only = false;
858     bool copy_on_read;
859     const char *serial;
860     const char *filename;
861     Error *local_err = NULL;
862     int i;
863
864     /* Change legacy command line options into QMP ones */
865     static const struct {
866         const char *from;
867         const char *to;
868     } opt_renames[] = {
869         { "iops",           "throttling.iops-total" },
870         { "iops_rd",        "throttling.iops-read" },
871         { "iops_wr",        "throttling.iops-write" },
872
873         { "bps",            "throttling.bps-total" },
874         { "bps_rd",         "throttling.bps-read" },
875         { "bps_wr",         "throttling.bps-write" },
876
877         { "iops_max",       "throttling.iops-total-max" },
878         { "iops_rd_max",    "throttling.iops-read-max" },
879         { "iops_wr_max",    "throttling.iops-write-max" },
880
881         { "bps_max",        "throttling.bps-total-max" },
882         { "bps_rd_max",     "throttling.bps-read-max" },
883         { "bps_wr_max",     "throttling.bps-write-max" },
884
885         { "iops_size",      "throttling.iops-size" },
886
887         { "group",          "throttling.group" },
888
889         { "readonly",       "read-only" },
890     };
891
892     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
893         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
894                         &local_err);
895         if (local_err) {
896             error_report_err(local_err);
897             return NULL;
898         }
899     }
900
901     value = qemu_opt_get(all_opts, "cache");
902     if (value) {
903         int flags = 0;
904         bool writethrough;
905
906         if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
907             error_report("invalid cache option");
908             return NULL;
909         }
910
911         /* Specific options take precedence */
912         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
913             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
914                               !writethrough, &error_abort);
915         }
916         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
917             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
918                               !!(flags & BDRV_O_NOCACHE), &error_abort);
919         }
920         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
921             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
922                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
923         }
924         qemu_opt_unset(all_opts, "cache");
925     }
926
927     /* Get a QDict for processing the options */
928     bs_opts = qdict_new();
929     qemu_opts_to_qdict(all_opts, bs_opts);
930
931     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
932                                    &error_abort);
933     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
934     if (local_err) {
935         error_report_err(local_err);
936         goto fail;
937     }
938
939     /* Deprecated option boot=[on|off] */
940     if (qemu_opt_get(legacy_opts, "boot") != NULL) {
941         fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
942                 "ignored. Future versions will reject this parameter. Please "
943                 "update your scripts.\n");
944     }
945
946     /* Media type */
947     value = qemu_opt_get(legacy_opts, "media");
948     if (value) {
949         if (!strcmp(value, "disk")) {
950             media = MEDIA_DISK;
951         } else if (!strcmp(value, "cdrom")) {
952             media = MEDIA_CDROM;
953             read_only = true;
954         } else {
955             error_report("'%s' invalid media", value);
956             goto fail;
957         }
958     }
959
960     /* copy-on-read is disabled with a warning for read-only devices */
961     read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
962     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
963
964     if (read_only && copy_on_read) {
965         error_report("warning: disabling copy-on-read on read-only drive");
966         copy_on_read = false;
967     }
968
969     qdict_put(bs_opts, "read-only",
970               qstring_from_str(read_only ? "on" : "off"));
971     qdict_put(bs_opts, "copy-on-read",
972               qstring_from_str(copy_on_read ? "on" :"off"));
973
974     /* Controller type */
975     value = qemu_opt_get(legacy_opts, "if");
976     if (value) {
977         for (type = 0;
978              type < IF_COUNT && strcmp(value, if_name[type]);
979              type++) {
980         }
981         if (type == IF_COUNT) {
982             error_report("unsupported bus type '%s'", value);
983             goto fail;
984         }
985     } else {
986         type = block_default_type;
987     }
988
989     /* Geometry */
990     cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
991     heads = qemu_opt_get_number(legacy_opts, "heads", 0);
992     secs  = qemu_opt_get_number(legacy_opts, "secs", 0);
993
994     if (cyls || heads || secs) {
995         if (cyls < 1) {
996             error_report("invalid physical cyls number");
997             goto fail;
998         }
999         if (heads < 1) {
1000             error_report("invalid physical heads number");
1001             goto fail;
1002         }
1003         if (secs < 1) {
1004             error_report("invalid physical secs number");
1005             goto fail;
1006         }
1007     }
1008
1009     translation = BIOS_ATA_TRANSLATION_AUTO;
1010     value = qemu_opt_get(legacy_opts, "trans");
1011     if (value != NULL) {
1012         if (!cyls) {
1013             error_report("'%s' trans must be used with cyls, heads and secs",
1014                          value);
1015             goto fail;
1016         }
1017         if (!strcmp(value, "none")) {
1018             translation = BIOS_ATA_TRANSLATION_NONE;
1019         } else if (!strcmp(value, "lba")) {
1020             translation = BIOS_ATA_TRANSLATION_LBA;
1021         } else if (!strcmp(value, "large")) {
1022             translation = BIOS_ATA_TRANSLATION_LARGE;
1023         } else if (!strcmp(value, "rechs")) {
1024             translation = BIOS_ATA_TRANSLATION_RECHS;
1025         } else if (!strcmp(value, "auto")) {
1026             translation = BIOS_ATA_TRANSLATION_AUTO;
1027         } else {
1028             error_report("'%s' invalid translation type", value);
1029             goto fail;
1030         }
1031     }
1032
1033     if (media == MEDIA_CDROM) {
1034         if (cyls || secs || heads) {
1035             error_report("CHS can't be set with media=cdrom");
1036             goto fail;
1037         }
1038     }
1039
1040     /* Device address specified by bus/unit or index.
1041      * If none was specified, try to find the first free one. */
1042     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
1043     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1044     index   = qemu_opt_get_number(legacy_opts, "index", -1);
1045
1046     max_devs = if_max_devs[type];
1047
1048     if (index != -1) {
1049         if (bus_id != 0 || unit_id != -1) {
1050             error_report("index cannot be used with bus and unit");
1051             goto fail;
1052         }
1053         bus_id = drive_index_to_bus_id(type, index);
1054         unit_id = drive_index_to_unit_id(type, index);
1055     }
1056
1057     if (unit_id == -1) {
1058        unit_id = 0;
1059        while (drive_get(type, bus_id, unit_id) != NULL) {
1060            unit_id++;
1061            if (max_devs && unit_id >= max_devs) {
1062                unit_id -= max_devs;
1063                bus_id++;
1064            }
1065        }
1066     }
1067
1068     if (max_devs && unit_id >= max_devs) {
1069         error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1070         goto fail;
1071     }
1072
1073     if (drive_get(type, bus_id, unit_id) != NULL) {
1074         error_report("drive with bus=%d, unit=%d (index=%d) exists",
1075                      bus_id, unit_id, index);
1076         goto fail;
1077     }
1078
1079     /* Serial number */
1080     serial = qemu_opt_get(legacy_opts, "serial");
1081
1082     /* no id supplied -> create one */
1083     if (qemu_opts_id(all_opts) == NULL) {
1084         char *new_id;
1085         const char *mediastr = "";
1086         if (type == IF_IDE || type == IF_SCSI) {
1087             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1088         }
1089         if (max_devs) {
1090             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1091                                      mediastr, unit_id);
1092         } else {
1093             new_id = g_strdup_printf("%s%s%i", if_name[type],
1094                                      mediastr, unit_id);
1095         }
1096         qdict_put(bs_opts, "id", qstring_from_str(new_id));
1097         g_free(new_id);
1098     }
1099
1100     /* Add virtio block device */
1101     devaddr = qemu_opt_get(legacy_opts, "addr");
1102     if (devaddr && type != IF_VIRTIO) {
1103         error_report("addr is not supported by this bus type");
1104         goto fail;
1105     }
1106
1107     if (type == IF_VIRTIO) {
1108         QemuOpts *devopts;
1109         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1110                                    &error_abort);
1111         if (arch_type == QEMU_ARCH_S390X) {
1112             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1113         } else {
1114             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1115         }
1116         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1117                      &error_abort);
1118         if (devaddr) {
1119             qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1120         }
1121     }
1122
1123     filename = qemu_opt_get(legacy_opts, "file");
1124
1125     /* Check werror/rerror compatibility with if=... */
1126     werror = qemu_opt_get(legacy_opts, "werror");
1127     if (werror != NULL) {
1128         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1129             type != IF_NONE) {
1130             error_report("werror is not supported by this bus type");
1131             goto fail;
1132         }
1133         qdict_put(bs_opts, "werror", qstring_from_str(werror));
1134     }
1135
1136     rerror = qemu_opt_get(legacy_opts, "rerror");
1137     if (rerror != NULL) {
1138         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1139             type != IF_NONE) {
1140             error_report("rerror is not supported by this bus type");
1141             goto fail;
1142         }
1143         qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1144     }
1145
1146     /* Actual block device init: Functionality shared with blockdev-add */
1147     blk = blockdev_init(filename, bs_opts, &local_err);
1148     bs_opts = NULL;
1149     if (!blk) {
1150         if (local_err) {
1151             error_report_err(local_err);
1152         }
1153         goto fail;
1154     } else {
1155         assert(!local_err);
1156     }
1157
1158     /* Create legacy DriveInfo */
1159     dinfo = g_malloc0(sizeof(*dinfo));
1160     dinfo->opts = all_opts;
1161
1162     dinfo->cyls = cyls;
1163     dinfo->heads = heads;
1164     dinfo->secs = secs;
1165     dinfo->trans = translation;
1166
1167     dinfo->type = type;
1168     dinfo->bus = bus_id;
1169     dinfo->unit = unit_id;
1170     dinfo->devaddr = devaddr;
1171     dinfo->serial = g_strdup(serial);
1172
1173     blk_set_legacy_dinfo(blk, dinfo);
1174
1175     switch(type) {
1176     case IF_IDE:
1177     case IF_SCSI:
1178     case IF_XEN:
1179     case IF_NONE:
1180         dinfo->media_cd = media == MEDIA_CDROM;
1181         break;
1182     default:
1183         break;
1184     }
1185
1186 fail:
1187     qemu_opts_del(legacy_opts);
1188     QDECREF(bs_opts);
1189     return dinfo;
1190 }
1191
1192 void hmp_commit(Monitor *mon, const QDict *qdict)
1193 {
1194     const char *device = qdict_get_str(qdict, "device");
1195     BlockBackend *blk;
1196     int ret;
1197
1198     if (!strcmp(device, "all")) {
1199         ret = blk_commit_all();
1200     } else {
1201         BlockDriverState *bs;
1202         AioContext *aio_context;
1203
1204         blk = blk_by_name(device);
1205         if (!blk) {
1206             monitor_printf(mon, "Device '%s' not found\n", device);
1207             return;
1208         }
1209         if (!blk_is_available(blk)) {
1210             monitor_printf(mon, "Device '%s' has no medium\n", device);
1211             return;
1212         }
1213
1214         bs = blk_bs(blk);
1215         aio_context = bdrv_get_aio_context(bs);
1216         aio_context_acquire(aio_context);
1217
1218         ret = bdrv_commit(bs);
1219
1220         aio_context_release(aio_context);
1221     }
1222     if (ret < 0) {
1223         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1224                        strerror(-ret));
1225     }
1226 }
1227
1228 static void blockdev_do_action(TransactionAction *action, Error **errp)
1229 {
1230     TransactionActionList list;
1231
1232     list.value = action;
1233     list.next = NULL;
1234     qmp_transaction(&list, false, NULL, errp);
1235 }
1236
1237 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1238                                 bool has_node_name, const char *node_name,
1239                                 const char *snapshot_file,
1240                                 bool has_snapshot_node_name,
1241                                 const char *snapshot_node_name,
1242                                 bool has_format, const char *format,
1243                                 bool has_mode, NewImageMode mode, Error **errp)
1244 {
1245     BlockdevSnapshotSync snapshot = {
1246         .has_device = has_device,
1247         .device = (char *) device,
1248         .has_node_name = has_node_name,
1249         .node_name = (char *) node_name,
1250         .snapshot_file = (char *) snapshot_file,
1251         .has_snapshot_node_name = has_snapshot_node_name,
1252         .snapshot_node_name = (char *) snapshot_node_name,
1253         .has_format = has_format,
1254         .format = (char *) format,
1255         .has_mode = has_mode,
1256         .mode = mode,
1257     };
1258     TransactionAction action = {
1259         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1260         .u.blockdev_snapshot_sync.data = &snapshot,
1261     };
1262     blockdev_do_action(&action, errp);
1263 }
1264
1265 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1266                            Error **errp)
1267 {
1268     BlockdevSnapshot snapshot_data = {
1269         .node = (char *) node,
1270         .overlay = (char *) overlay
1271     };
1272     TransactionAction action = {
1273         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1274         .u.blockdev_snapshot.data = &snapshot_data,
1275     };
1276     blockdev_do_action(&action, errp);
1277 }
1278
1279 void qmp_blockdev_snapshot_internal_sync(const char *device,
1280                                          const char *name,
1281                                          Error **errp)
1282 {
1283     BlockdevSnapshotInternal snapshot = {
1284         .device = (char *) device,
1285         .name = (char *) name
1286     };
1287     TransactionAction action = {
1288         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1289         .u.blockdev_snapshot_internal_sync.data = &snapshot,
1290     };
1291     blockdev_do_action(&action, errp);
1292 }
1293
1294 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1295                                                          bool has_id,
1296                                                          const char *id,
1297                                                          bool has_name,
1298                                                          const char *name,
1299                                                          Error **errp)
1300 {
1301     BlockDriverState *bs;
1302     BlockBackend *blk;
1303     AioContext *aio_context;
1304     QEMUSnapshotInfo sn;
1305     Error *local_err = NULL;
1306     SnapshotInfo *info = NULL;
1307     int ret;
1308
1309     blk = blk_by_name(device);
1310     if (!blk) {
1311         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1312                   "Device '%s' not found", device);
1313         return NULL;
1314     }
1315
1316     aio_context = blk_get_aio_context(blk);
1317     aio_context_acquire(aio_context);
1318
1319     if (!has_id) {
1320         id = NULL;
1321     }
1322
1323     if (!has_name) {
1324         name = NULL;
1325     }
1326
1327     if (!id && !name) {
1328         error_setg(errp, "Name or id must be provided");
1329         goto out_aio_context;
1330     }
1331
1332     if (!blk_is_available(blk)) {
1333         error_setg(errp, "Device '%s' has no medium", device);
1334         goto out_aio_context;
1335     }
1336     bs = blk_bs(blk);
1337
1338     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1339         goto out_aio_context;
1340     }
1341
1342     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1343     if (local_err) {
1344         error_propagate(errp, local_err);
1345         goto out_aio_context;
1346     }
1347     if (!ret) {
1348         error_setg(errp,
1349                    "Snapshot with id '%s' and name '%s' does not exist on "
1350                    "device '%s'",
1351                    STR_OR_NULL(id), STR_OR_NULL(name), device);
1352         goto out_aio_context;
1353     }
1354
1355     bdrv_snapshot_delete(bs, id, name, &local_err);
1356     if (local_err) {
1357         error_propagate(errp, local_err);
1358         goto out_aio_context;
1359     }
1360
1361     aio_context_release(aio_context);
1362
1363     info = g_new0(SnapshotInfo, 1);
1364     info->id = g_strdup(sn.id_str);
1365     info->name = g_strdup(sn.name);
1366     info->date_nsec = sn.date_nsec;
1367     info->date_sec = sn.date_sec;
1368     info->vm_state_size = sn.vm_state_size;
1369     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1370     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1371
1372     return info;
1373
1374 out_aio_context:
1375     aio_context_release(aio_context);
1376     return NULL;
1377 }
1378
1379 /**
1380  * block_dirty_bitmap_lookup:
1381  * Return a dirty bitmap (if present), after validating
1382  * the node reference and bitmap names.
1383  *
1384  * @node: The name of the BDS node to search for bitmaps
1385  * @name: The name of the bitmap to search for
1386  * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1387  * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1388  * @errp: Output pointer for error information. Can be NULL.
1389  *
1390  * @return: A bitmap object on success, or NULL on failure.
1391  */
1392 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1393                                                   const char *name,
1394                                                   BlockDriverState **pbs,
1395                                                   AioContext **paio,
1396                                                   Error **errp)
1397 {
1398     BlockDriverState *bs;
1399     BdrvDirtyBitmap *bitmap;
1400     AioContext *aio_context;
1401
1402     if (!node) {
1403         error_setg(errp, "Node cannot be NULL");
1404         return NULL;
1405     }
1406     if (!name) {
1407         error_setg(errp, "Bitmap name cannot be NULL");
1408         return NULL;
1409     }
1410     bs = bdrv_lookup_bs(node, node, NULL);
1411     if (!bs) {
1412         error_setg(errp, "Node '%s' not found", node);
1413         return NULL;
1414     }
1415
1416     aio_context = bdrv_get_aio_context(bs);
1417     aio_context_acquire(aio_context);
1418
1419     bitmap = bdrv_find_dirty_bitmap(bs, name);
1420     if (!bitmap) {
1421         error_setg(errp, "Dirty bitmap '%s' not found", name);
1422         goto fail;
1423     }
1424
1425     if (pbs) {
1426         *pbs = bs;
1427     }
1428     if (paio) {
1429         *paio = aio_context;
1430     } else {
1431         aio_context_release(aio_context);
1432     }
1433
1434     return bitmap;
1435
1436  fail:
1437     aio_context_release(aio_context);
1438     return NULL;
1439 }
1440
1441 /* New and old BlockDriverState structs for atomic group operations */
1442
1443 typedef struct BlkActionState BlkActionState;
1444
1445 /**
1446  * BlkActionOps:
1447  * Table of operations that define an Action.
1448  *
1449  * @instance_size: Size of state struct, in bytes.
1450  * @prepare: Prepare the work, must NOT be NULL.
1451  * @commit: Commit the changes, can be NULL.
1452  * @abort: Abort the changes on fail, can be NULL.
1453  * @clean: Clean up resources after all transaction actions have called
1454  *         commit() or abort(). Can be NULL.
1455  *
1456  * Only prepare() may fail. In a single transaction, only one of commit() or
1457  * abort() will be called. clean() will always be called if it is present.
1458  */
1459 typedef struct BlkActionOps {
1460     size_t instance_size;
1461     void (*prepare)(BlkActionState *common, Error **errp);
1462     void (*commit)(BlkActionState *common);
1463     void (*abort)(BlkActionState *common);
1464     void (*clean)(BlkActionState *common);
1465 } BlkActionOps;
1466
1467 /**
1468  * BlkActionState:
1469  * Describes one Action's state within a Transaction.
1470  *
1471  * @action: QAPI-defined enum identifying which Action to perform.
1472  * @ops: Table of ActionOps this Action can perform.
1473  * @block_job_txn: Transaction which this action belongs to.
1474  * @entry: List membership for all Actions in this Transaction.
1475  *
1476  * This structure must be arranged as first member in a subclassed type,
1477  * assuming that the compiler will also arrange it to the same offsets as the
1478  * base class.
1479  */
1480 struct BlkActionState {
1481     TransactionAction *action;
1482     const BlkActionOps *ops;
1483     BlockJobTxn *block_job_txn;
1484     TransactionProperties *txn_props;
1485     QSIMPLEQ_ENTRY(BlkActionState) entry;
1486 };
1487
1488 /* internal snapshot private data */
1489 typedef struct InternalSnapshotState {
1490     BlkActionState common;
1491     BlockDriverState *bs;
1492     AioContext *aio_context;
1493     QEMUSnapshotInfo sn;
1494     bool created;
1495 } InternalSnapshotState;
1496
1497
1498 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1499 {
1500     if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1501         error_setg(errp,
1502                    "Action '%s' does not support Transaction property "
1503                    "completion-mode = %s",
1504                    TransactionActionKind_lookup[s->action->type],
1505                    ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1506         return -1;
1507     }
1508     return 0;
1509 }
1510
1511 static void internal_snapshot_prepare(BlkActionState *common,
1512                                       Error **errp)
1513 {
1514     Error *local_err = NULL;
1515     const char *device;
1516     const char *name;
1517     BlockBackend *blk;
1518     BlockDriverState *bs;
1519     QEMUSnapshotInfo old_sn, *sn;
1520     bool ret;
1521     qemu_timeval tv;
1522     BlockdevSnapshotInternal *internal;
1523     InternalSnapshotState *state;
1524     int ret1;
1525
1526     g_assert(common->action->type ==
1527              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1528     internal = common->action->u.blockdev_snapshot_internal_sync.data;
1529     state = DO_UPCAST(InternalSnapshotState, common, common);
1530
1531     /* 1. parse input */
1532     device = internal->device;
1533     name = internal->name;
1534
1535     /* 2. check for validation */
1536     if (action_check_completion_mode(common, errp) < 0) {
1537         return;
1538     }
1539
1540     blk = blk_by_name(device);
1541     if (!blk) {
1542         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1543                   "Device '%s' not found", device);
1544         return;
1545     }
1546
1547     /* AioContext is released in .clean() */
1548     state->aio_context = blk_get_aio_context(blk);
1549     aio_context_acquire(state->aio_context);
1550
1551     if (!blk_is_available(blk)) {
1552         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1553         return;
1554     }
1555     bs = blk_bs(blk);
1556
1557     state->bs = bs;
1558     bdrv_drained_begin(bs);
1559
1560     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1561         return;
1562     }
1563
1564     if (bdrv_is_read_only(bs)) {
1565         error_setg(errp, "Device '%s' is read only", device);
1566         return;
1567     }
1568
1569     if (!bdrv_can_snapshot(bs)) {
1570         error_setg(errp, "Block format '%s' used by device '%s' "
1571                    "does not support internal snapshots",
1572                    bs->drv->format_name, device);
1573         return;
1574     }
1575
1576     if (!strlen(name)) {
1577         error_setg(errp, "Name is empty");
1578         return;
1579     }
1580
1581     /* check whether a snapshot with name exist */
1582     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1583                                             &local_err);
1584     if (local_err) {
1585         error_propagate(errp, local_err);
1586         return;
1587     } else if (ret) {
1588         error_setg(errp,
1589                    "Snapshot with name '%s' already exists on device '%s'",
1590                    name, device);
1591         return;
1592     }
1593
1594     /* 3. take the snapshot */
1595     sn = &state->sn;
1596     pstrcpy(sn->name, sizeof(sn->name), name);
1597     qemu_gettimeofday(&tv);
1598     sn->date_sec = tv.tv_sec;
1599     sn->date_nsec = tv.tv_usec * 1000;
1600     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1601
1602     ret1 = bdrv_snapshot_create(bs, sn);
1603     if (ret1 < 0) {
1604         error_setg_errno(errp, -ret1,
1605                          "Failed to create snapshot '%s' on device '%s'",
1606                          name, device);
1607         return;
1608     }
1609
1610     /* 4. succeed, mark a snapshot is created */
1611     state->created = true;
1612 }
1613
1614 static void internal_snapshot_abort(BlkActionState *common)
1615 {
1616     InternalSnapshotState *state =
1617                              DO_UPCAST(InternalSnapshotState, common, common);
1618     BlockDriverState *bs = state->bs;
1619     QEMUSnapshotInfo *sn = &state->sn;
1620     Error *local_error = NULL;
1621
1622     if (!state->created) {
1623         return;
1624     }
1625
1626     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1627         error_reportf_err(local_error,
1628                           "Failed to delete snapshot with id '%s' and "
1629                           "name '%s' on device '%s' in abort: ",
1630                           sn->id_str, sn->name,
1631                           bdrv_get_device_name(bs));
1632     }
1633 }
1634
1635 static void internal_snapshot_clean(BlkActionState *common)
1636 {
1637     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1638                                              common, common);
1639
1640     if (state->aio_context) {
1641         if (state->bs) {
1642             bdrv_drained_end(state->bs);
1643         }
1644         aio_context_release(state->aio_context);
1645     }
1646 }
1647
1648 /* external snapshot private data */
1649 typedef struct ExternalSnapshotState {
1650     BlkActionState common;
1651     BlockDriverState *old_bs;
1652     BlockDriverState *new_bs;
1653     AioContext *aio_context;
1654 } ExternalSnapshotState;
1655
1656 static void external_snapshot_prepare(BlkActionState *common,
1657                                       Error **errp)
1658 {
1659     int flags = 0, ret;
1660     QDict *options = NULL;
1661     Error *local_err = NULL;
1662     /* Device and node name of the image to generate the snapshot from */
1663     const char *device;
1664     const char *node_name;
1665     /* Reference to the new image (for 'blockdev-snapshot') */
1666     const char *snapshot_ref;
1667     /* File name of the new image (for 'blockdev-snapshot-sync') */
1668     const char *new_image_file;
1669     ExternalSnapshotState *state =
1670                              DO_UPCAST(ExternalSnapshotState, common, common);
1671     TransactionAction *action = common->action;
1672
1673     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1674      * purpose but a different set of parameters */
1675     switch (action->type) {
1676     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1677         {
1678             BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1679             device = s->node;
1680             node_name = s->node;
1681             new_image_file = NULL;
1682             snapshot_ref = s->overlay;
1683         }
1684         break;
1685     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1686         {
1687             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1688             device = s->has_device ? s->device : NULL;
1689             node_name = s->has_node_name ? s->node_name : NULL;
1690             new_image_file = s->snapshot_file;
1691             snapshot_ref = NULL;
1692         }
1693         break;
1694     default:
1695         g_assert_not_reached();
1696     }
1697
1698     /* start processing */
1699     if (action_check_completion_mode(common, errp) < 0) {
1700         return;
1701     }
1702
1703     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1704     if (!state->old_bs) {
1705         return;
1706     }
1707
1708     /* Acquire AioContext now so any threads operating on old_bs stop */
1709     state->aio_context = bdrv_get_aio_context(state->old_bs);
1710     aio_context_acquire(state->aio_context);
1711     bdrv_drained_begin(state->old_bs);
1712
1713     if (!bdrv_is_inserted(state->old_bs)) {
1714         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1715         return;
1716     }
1717
1718     if (bdrv_op_is_blocked(state->old_bs,
1719                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1720         return;
1721     }
1722
1723     if (!bdrv_is_read_only(state->old_bs)) {
1724         if (bdrv_flush(state->old_bs)) {
1725             error_setg(errp, QERR_IO_ERROR);
1726             return;
1727         }
1728     }
1729
1730     if (!bdrv_is_first_non_filter(state->old_bs)) {
1731         error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1732         return;
1733     }
1734
1735     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1736         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1737         const char *format = s->has_format ? s->format : "qcow2";
1738         enum NewImageMode mode;
1739         const char *snapshot_node_name =
1740             s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1741
1742         if (node_name && !snapshot_node_name) {
1743             error_setg(errp, "New snapshot node name missing");
1744             return;
1745         }
1746
1747         if (snapshot_node_name &&
1748             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1749             error_setg(errp, "New snapshot node name already in use");
1750             return;
1751         }
1752
1753         flags = state->old_bs->open_flags;
1754         flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1755
1756         /* create new image w/backing file */
1757         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1758         if (mode != NEW_IMAGE_MODE_EXISTING) {
1759             int64_t size = bdrv_getlength(state->old_bs);
1760             if (size < 0) {
1761                 error_setg_errno(errp, -size, "bdrv_getlength failed");
1762                 return;
1763             }
1764             bdrv_img_create(new_image_file, format,
1765                             state->old_bs->filename,
1766                             state->old_bs->drv->format_name,
1767                             NULL, size, flags, &local_err, false);
1768             if (local_err) {
1769                 error_propagate(errp, local_err);
1770                 return;
1771             }
1772         }
1773
1774         options = qdict_new();
1775         if (s->has_snapshot_node_name) {
1776             qdict_put(options, "node-name",
1777                       qstring_from_str(snapshot_node_name));
1778         }
1779         qdict_put(options, "driver", qstring_from_str(format));
1780
1781         flags |= BDRV_O_NO_BACKING;
1782     }
1783
1784     assert(state->new_bs == NULL);
1785     ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
1786                     flags, errp);
1787     /* We will manually add the backing_hd field to the bs later */
1788     if (ret != 0) {
1789         return;
1790     }
1791
1792     if (state->new_bs->blk != NULL) {
1793         error_setg(errp, "The snapshot is already in use by %s",
1794                    blk_name(state->new_bs->blk));
1795         return;
1796     }
1797
1798     if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1799                            errp)) {
1800         return;
1801     }
1802
1803     if (state->new_bs->backing != NULL) {
1804         error_setg(errp, "The snapshot already has a backing image");
1805         return;
1806     }
1807
1808     if (!state->new_bs->drv->supports_backing) {
1809         error_setg(errp, "The snapshot does not support backing images");
1810     }
1811 }
1812
1813 static void external_snapshot_commit(BlkActionState *common)
1814 {
1815     ExternalSnapshotState *state =
1816                              DO_UPCAST(ExternalSnapshotState, common, common);
1817
1818     bdrv_set_aio_context(state->new_bs, state->aio_context);
1819
1820     /* This removes our old bs and adds the new bs */
1821     bdrv_append(state->new_bs, state->old_bs);
1822     /* We don't need (or want) to use the transactional
1823      * bdrv_reopen_multiple() across all the entries at once, because we
1824      * don't want to abort all of them if one of them fails the reopen */
1825     if (!state->old_bs->copy_on_read) {
1826         bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1827                     NULL);
1828     }
1829 }
1830
1831 static void external_snapshot_abort(BlkActionState *common)
1832 {
1833     ExternalSnapshotState *state =
1834                              DO_UPCAST(ExternalSnapshotState, common, common);
1835     if (state->new_bs) {
1836         bdrv_unref(state->new_bs);
1837     }
1838 }
1839
1840 static void external_snapshot_clean(BlkActionState *common)
1841 {
1842     ExternalSnapshotState *state =
1843                              DO_UPCAST(ExternalSnapshotState, common, common);
1844     if (state->aio_context) {
1845         bdrv_drained_end(state->old_bs);
1846         aio_context_release(state->aio_context);
1847     }
1848 }
1849
1850 typedef struct DriveBackupState {
1851     BlkActionState common;
1852     BlockDriverState *bs;
1853     AioContext *aio_context;
1854     BlockJob *job;
1855 } DriveBackupState;
1856
1857 static void do_drive_backup(const char *device, const char *target,
1858                             bool has_format, const char *format,
1859                             enum MirrorSyncMode sync,
1860                             bool has_mode, enum NewImageMode mode,
1861                             bool has_speed, int64_t speed,
1862                             bool has_bitmap, const char *bitmap,
1863                             bool has_on_source_error,
1864                             BlockdevOnError on_source_error,
1865                             bool has_on_target_error,
1866                             BlockdevOnError on_target_error,
1867                             BlockJobTxn *txn, Error **errp);
1868
1869 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1870 {
1871     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1872     BlockBackend *blk;
1873     DriveBackup *backup;
1874     Error *local_err = NULL;
1875
1876     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1877     backup = common->action->u.drive_backup.data;
1878
1879     blk = blk_by_name(backup->device);
1880     if (!blk) {
1881         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1882                   "Device '%s' not found", backup->device);
1883         return;
1884     }
1885
1886     if (!blk_is_available(blk)) {
1887         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1888         return;
1889     }
1890
1891     /* AioContext is released in .clean() */
1892     state->aio_context = blk_get_aio_context(blk);
1893     aio_context_acquire(state->aio_context);
1894     bdrv_drained_begin(blk_bs(blk));
1895     state->bs = blk_bs(blk);
1896
1897     do_drive_backup(backup->device, backup->target,
1898                     backup->has_format, backup->format,
1899                     backup->sync,
1900                     backup->has_mode, backup->mode,
1901                     backup->has_speed, backup->speed,
1902                     backup->has_bitmap, backup->bitmap,
1903                     backup->has_on_source_error, backup->on_source_error,
1904                     backup->has_on_target_error, backup->on_target_error,
1905                     common->block_job_txn, &local_err);
1906     if (local_err) {
1907         error_propagate(errp, local_err);
1908         return;
1909     }
1910
1911     state->job = state->bs->job;
1912 }
1913
1914 static void drive_backup_abort(BlkActionState *common)
1915 {
1916     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1917     BlockDriverState *bs = state->bs;
1918
1919     /* Only cancel if it's the job we started */
1920     if (bs && bs->job && bs->job == state->job) {
1921         block_job_cancel_sync(bs->job);
1922     }
1923 }
1924
1925 static void drive_backup_clean(BlkActionState *common)
1926 {
1927     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1928
1929     if (state->aio_context) {
1930         bdrv_drained_end(state->bs);
1931         aio_context_release(state->aio_context);
1932     }
1933 }
1934
1935 typedef struct BlockdevBackupState {
1936     BlkActionState common;
1937     BlockDriverState *bs;
1938     BlockJob *job;
1939     AioContext *aio_context;
1940 } BlockdevBackupState;
1941
1942 static void do_blockdev_backup(const char *device, const char *target,
1943                                enum MirrorSyncMode sync,
1944                                bool has_speed, int64_t speed,
1945                                bool has_on_source_error,
1946                                BlockdevOnError on_source_error,
1947                                bool has_on_target_error,
1948                                BlockdevOnError on_target_error,
1949                                BlockJobTxn *txn, Error **errp);
1950
1951 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1952 {
1953     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1954     BlockdevBackup *backup;
1955     BlockBackend *blk, *target;
1956     Error *local_err = NULL;
1957
1958     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1959     backup = common->action->u.blockdev_backup.data;
1960
1961     blk = blk_by_name(backup->device);
1962     if (!blk) {
1963         error_setg(errp, "Device '%s' not found", backup->device);
1964         return;
1965     }
1966
1967     if (!blk_is_available(blk)) {
1968         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1969         return;
1970     }
1971
1972     target = blk_by_name(backup->target);
1973     if (!target) {
1974         error_setg(errp, "Device '%s' not found", backup->target);
1975         return;
1976     }
1977
1978     /* AioContext is released in .clean() */
1979     state->aio_context = blk_get_aio_context(blk);
1980     if (state->aio_context != blk_get_aio_context(target)) {
1981         state->aio_context = NULL;
1982         error_setg(errp, "Backup between two IO threads is not implemented");
1983         return;
1984     }
1985     aio_context_acquire(state->aio_context);
1986     state->bs = blk_bs(blk);
1987     bdrv_drained_begin(state->bs);
1988
1989     do_blockdev_backup(backup->device, backup->target,
1990                        backup->sync,
1991                        backup->has_speed, backup->speed,
1992                        backup->has_on_source_error, backup->on_source_error,
1993                        backup->has_on_target_error, backup->on_target_error,
1994                        common->block_job_txn, &local_err);
1995     if (local_err) {
1996         error_propagate(errp, local_err);
1997         return;
1998     }
1999
2000     state->job = state->bs->job;
2001 }
2002
2003 static void blockdev_backup_abort(BlkActionState *common)
2004 {
2005     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2006     BlockDriverState *bs = state->bs;
2007
2008     /* Only cancel if it's the job we started */
2009     if (bs && bs->job && bs->job == state->job) {
2010         block_job_cancel_sync(bs->job);
2011     }
2012 }
2013
2014 static void blockdev_backup_clean(BlkActionState *common)
2015 {
2016     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2017
2018     if (state->aio_context) {
2019         bdrv_drained_end(state->bs);
2020         aio_context_release(state->aio_context);
2021     }
2022 }
2023
2024 typedef struct BlockDirtyBitmapState {
2025     BlkActionState common;
2026     BdrvDirtyBitmap *bitmap;
2027     BlockDriverState *bs;
2028     AioContext *aio_context;
2029     HBitmap *backup;
2030     bool prepared;
2031 } BlockDirtyBitmapState;
2032
2033 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2034                                            Error **errp)
2035 {
2036     Error *local_err = NULL;
2037     BlockDirtyBitmapAdd *action;
2038     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2039                                              common, common);
2040
2041     if (action_check_completion_mode(common, errp) < 0) {
2042         return;
2043     }
2044
2045     action = common->action->u.block_dirty_bitmap_add.data;
2046     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2047     qmp_block_dirty_bitmap_add(action->node, action->name,
2048                                action->has_granularity, action->granularity,
2049                                &local_err);
2050
2051     if (!local_err) {
2052         state->prepared = true;
2053     } else {
2054         error_propagate(errp, local_err);
2055     }
2056 }
2057
2058 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2059 {
2060     BlockDirtyBitmapAdd *action;
2061     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2062                                              common, common);
2063
2064     action = common->action->u.block_dirty_bitmap_add.data;
2065     /* Should not be able to fail: IF the bitmap was added via .prepare(),
2066      * then the node reference and bitmap name must have been valid.
2067      */
2068     if (state->prepared) {
2069         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2070     }
2071 }
2072
2073 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2074                                              Error **errp)
2075 {
2076     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2077                                              common, common);
2078     BlockDirtyBitmap *action;
2079
2080     if (action_check_completion_mode(common, errp) < 0) {
2081         return;
2082     }
2083
2084     action = common->action->u.block_dirty_bitmap_clear.data;
2085     state->bitmap = block_dirty_bitmap_lookup(action->node,
2086                                               action->name,
2087                                               &state->bs,
2088                                               &state->aio_context,
2089                                               errp);
2090     if (!state->bitmap) {
2091         return;
2092     }
2093
2094     if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2095         error_setg(errp, "Cannot modify a frozen bitmap");
2096         return;
2097     } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2098         error_setg(errp, "Cannot clear a disabled bitmap");
2099         return;
2100     }
2101
2102     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2103     /* AioContext is released in .clean() */
2104 }
2105
2106 static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2107 {
2108     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2109                                              common, common);
2110
2111     bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2112 }
2113
2114 static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2115 {
2116     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2117                                              common, common);
2118
2119     hbitmap_free(state->backup);
2120 }
2121
2122 static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2123 {
2124     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2125                                              common, common);
2126
2127     if (state->aio_context) {
2128         aio_context_release(state->aio_context);
2129     }
2130 }
2131
2132 static void abort_prepare(BlkActionState *common, Error **errp)
2133 {
2134     error_setg(errp, "Transaction aborted using Abort action");
2135 }
2136
2137 static void abort_commit(BlkActionState *common)
2138 {
2139     g_assert_not_reached(); /* this action never succeeds */
2140 }
2141
2142 static const BlkActionOps actions[] = {
2143     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2144         .instance_size = sizeof(ExternalSnapshotState),
2145         .prepare  = external_snapshot_prepare,
2146         .commit   = external_snapshot_commit,
2147         .abort = external_snapshot_abort,
2148         .clean = external_snapshot_clean,
2149     },
2150     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2151         .instance_size = sizeof(ExternalSnapshotState),
2152         .prepare  = external_snapshot_prepare,
2153         .commit   = external_snapshot_commit,
2154         .abort = external_snapshot_abort,
2155         .clean = external_snapshot_clean,
2156     },
2157     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2158         .instance_size = sizeof(DriveBackupState),
2159         .prepare = drive_backup_prepare,
2160         .abort = drive_backup_abort,
2161         .clean = drive_backup_clean,
2162     },
2163     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2164         .instance_size = sizeof(BlockdevBackupState),
2165         .prepare = blockdev_backup_prepare,
2166         .abort = blockdev_backup_abort,
2167         .clean = blockdev_backup_clean,
2168     },
2169     [TRANSACTION_ACTION_KIND_ABORT] = {
2170         .instance_size = sizeof(BlkActionState),
2171         .prepare = abort_prepare,
2172         .commit = abort_commit,
2173     },
2174     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2175         .instance_size = sizeof(InternalSnapshotState),
2176         .prepare  = internal_snapshot_prepare,
2177         .abort = internal_snapshot_abort,
2178         .clean = internal_snapshot_clean,
2179     },
2180     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2181         .instance_size = sizeof(BlockDirtyBitmapState),
2182         .prepare = block_dirty_bitmap_add_prepare,
2183         .abort = block_dirty_bitmap_add_abort,
2184     },
2185     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2186         .instance_size = sizeof(BlockDirtyBitmapState),
2187         .prepare = block_dirty_bitmap_clear_prepare,
2188         .commit = block_dirty_bitmap_clear_commit,
2189         .abort = block_dirty_bitmap_clear_abort,
2190         .clean = block_dirty_bitmap_clear_clean,
2191     }
2192 };
2193
2194 /**
2195  * Allocate a TransactionProperties structure if necessary, and fill
2196  * that structure with desired defaults if they are unset.
2197  */
2198 static TransactionProperties *get_transaction_properties(
2199     TransactionProperties *props)
2200 {
2201     if (!props) {
2202         props = g_new0(TransactionProperties, 1);
2203     }
2204
2205     if (!props->has_completion_mode) {
2206         props->has_completion_mode = true;
2207         props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2208     }
2209
2210     return props;
2211 }
2212
2213 /*
2214  * 'Atomic' group operations.  The operations are performed as a set, and if
2215  * any fail then we roll back all operations in the group.
2216  */
2217 void qmp_transaction(TransactionActionList *dev_list,
2218                      bool has_props,
2219                      struct TransactionProperties *props,
2220                      Error **errp)
2221 {
2222     TransactionActionList *dev_entry = dev_list;
2223     BlockJobTxn *block_job_txn = NULL;
2224     BlkActionState *state, *next;
2225     Error *local_err = NULL;
2226
2227     QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
2228     QSIMPLEQ_INIT(&snap_bdrv_states);
2229
2230     /* Does this transaction get canceled as a group on failure?
2231      * If not, we don't really need to make a BlockJobTxn.
2232      */
2233     props = get_transaction_properties(props);
2234     if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2235         block_job_txn = block_job_txn_new();
2236     }
2237
2238     /* drain all i/o before any operations */
2239     bdrv_drain_all();
2240
2241     /* We don't do anything in this loop that commits us to the operations */
2242     while (NULL != dev_entry) {
2243         TransactionAction *dev_info = NULL;
2244         const BlkActionOps *ops;
2245
2246         dev_info = dev_entry->value;
2247         dev_entry = dev_entry->next;
2248
2249         assert(dev_info->type < ARRAY_SIZE(actions));
2250
2251         ops = &actions[dev_info->type];
2252         assert(ops->instance_size > 0);
2253
2254         state = g_malloc0(ops->instance_size);
2255         state->ops = ops;
2256         state->action = dev_info;
2257         state->block_job_txn = block_job_txn;
2258         state->txn_props = props;
2259         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2260
2261         state->ops->prepare(state, &local_err);
2262         if (local_err) {
2263             error_propagate(errp, local_err);
2264             goto delete_and_fail;
2265         }
2266     }
2267
2268     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2269         if (state->ops->commit) {
2270             state->ops->commit(state);
2271         }
2272     }
2273
2274     /* success */
2275     goto exit;
2276
2277 delete_and_fail:
2278     /* failure, and it is all-or-none; roll back all operations */
2279     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2280         if (state->ops->abort) {
2281             state->ops->abort(state);
2282         }
2283     }
2284 exit:
2285     QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2286         if (state->ops->clean) {
2287             state->ops->clean(state);
2288         }
2289         g_free(state);
2290     }
2291     if (!has_props) {
2292         qapi_free_TransactionProperties(props);
2293     }
2294     block_job_txn_unref(block_job_txn);
2295 }
2296
2297 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2298 {
2299     Error *local_err = NULL;
2300
2301     qmp_blockdev_open_tray(device, has_force, force, &local_err);
2302     if (local_err) {
2303         error_propagate(errp, local_err);
2304         return;
2305     }
2306
2307     qmp_x_blockdev_remove_medium(device, errp);
2308 }
2309
2310 void qmp_block_passwd(bool has_device, const char *device,
2311                       bool has_node_name, const char *node_name,
2312                       const char *password, Error **errp)
2313 {
2314     Error *local_err = NULL;
2315     BlockDriverState *bs;
2316     AioContext *aio_context;
2317
2318     bs = bdrv_lookup_bs(has_device ? device : NULL,
2319                         has_node_name ? node_name : NULL,
2320                         &local_err);
2321     if (local_err) {
2322         error_propagate(errp, local_err);
2323         return;
2324     }
2325
2326     aio_context = bdrv_get_aio_context(bs);
2327     aio_context_acquire(aio_context);
2328
2329     bdrv_add_key(bs, password, errp);
2330
2331     aio_context_release(aio_context);
2332 }
2333
2334 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2335                             Error **errp)
2336 {
2337     BlockBackend *blk;
2338     bool locked;
2339
2340     if (!has_force) {
2341         force = false;
2342     }
2343
2344     blk = blk_by_name(device);
2345     if (!blk) {
2346         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2347                   "Device '%s' not found", device);
2348         return;
2349     }
2350
2351     if (!blk_dev_has_removable_media(blk)) {
2352         error_setg(errp, "Device '%s' is not removable", device);
2353         return;
2354     }
2355
2356     if (!blk_dev_has_tray(blk)) {
2357         /* Ignore this command on tray-less devices */
2358         return;
2359     }
2360
2361     if (blk_dev_is_tray_open(blk)) {
2362         return;
2363     }
2364
2365     locked = blk_dev_is_medium_locked(blk);
2366     if (locked) {
2367         blk_dev_eject_request(blk, force);
2368     }
2369
2370     if (!locked || force) {
2371         blk_dev_change_media_cb(blk, false);
2372     }
2373 }
2374
2375 void qmp_blockdev_close_tray(const char *device, Error **errp)
2376 {
2377     BlockBackend *blk;
2378
2379     blk = blk_by_name(device);
2380     if (!blk) {
2381         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2382                   "Device '%s' not found", device);
2383         return;
2384     }
2385
2386     if (!blk_dev_has_removable_media(blk)) {
2387         error_setg(errp, "Device '%s' is not removable", device);
2388         return;
2389     }
2390
2391     if (!blk_dev_has_tray(blk)) {
2392         /* Ignore this command on tray-less devices */
2393         return;
2394     }
2395
2396     if (!blk_dev_is_tray_open(blk)) {
2397         return;
2398     }
2399
2400     blk_dev_change_media_cb(blk, true);
2401 }
2402
2403 void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2404 {
2405     BlockBackend *blk;
2406     BlockDriverState *bs;
2407     AioContext *aio_context;
2408     bool has_device;
2409
2410     blk = blk_by_name(device);
2411     if (!blk) {
2412         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2413                   "Device '%s' not found", device);
2414         return;
2415     }
2416
2417     /* For BBs without a device, we can exchange the BDS tree at will */
2418     has_device = blk_get_attached_dev(blk);
2419
2420     if (has_device && !blk_dev_has_removable_media(blk)) {
2421         error_setg(errp, "Device '%s' is not removable", device);
2422         return;
2423     }
2424
2425     if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2426         error_setg(errp, "Tray of device '%s' is not open", device);
2427         return;
2428     }
2429
2430     bs = blk_bs(blk);
2431     if (!bs) {
2432         return;
2433     }
2434
2435     aio_context = bdrv_get_aio_context(bs);
2436     aio_context_acquire(aio_context);
2437
2438     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2439         goto out;
2440     }
2441
2442     blk_remove_bs(blk);
2443
2444     if (!blk_dev_has_tray(blk)) {
2445         /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2446          * called at all); therefore, the medium needs to be ejected here.
2447          * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2448          * value passed here (i.e. false). */
2449         blk_dev_change_media_cb(blk, false);
2450     }
2451
2452 out:
2453     aio_context_release(aio_context);
2454 }
2455
2456 static void qmp_blockdev_insert_anon_medium(const char *device,
2457                                             BlockDriverState *bs, Error **errp)
2458 {
2459     BlockBackend *blk;
2460     bool has_device;
2461
2462     blk = blk_by_name(device);
2463     if (!blk) {
2464         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2465                   "Device '%s' not found", device);
2466         return;
2467     }
2468
2469     /* For BBs without a device, we can exchange the BDS tree at will */
2470     has_device = blk_get_attached_dev(blk);
2471
2472     if (has_device && !blk_dev_has_removable_media(blk)) {
2473         error_setg(errp, "Device '%s' is not removable", device);
2474         return;
2475     }
2476
2477     if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2478         error_setg(errp, "Tray of device '%s' is not open", device);
2479         return;
2480     }
2481
2482     if (blk_bs(blk)) {
2483         error_setg(errp, "There already is a medium in device '%s'", device);
2484         return;
2485     }
2486
2487     blk_insert_bs(blk, bs);
2488
2489     if (!blk_dev_has_tray(blk)) {
2490         /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2491          * called at all); therefore, the medium needs to be pushed into the
2492          * slot here.
2493          * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2494          * value passed here (i.e. true). */
2495         blk_dev_change_media_cb(blk, true);
2496     }
2497 }
2498
2499 void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2500                                   Error **errp)
2501 {
2502     BlockDriverState *bs;
2503
2504     bs = bdrv_find_node(node_name);
2505     if (!bs) {
2506         error_setg(errp, "Node '%s' not found", node_name);
2507         return;
2508     }
2509
2510     if (bs->blk) {
2511         error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2512                    blk_name(bs->blk));
2513         return;
2514     }
2515
2516     qmp_blockdev_insert_anon_medium(device, bs, errp);
2517 }
2518
2519 void qmp_blockdev_change_medium(const char *device, const char *filename,
2520                                 bool has_format, const char *format,
2521                                 bool has_read_only,
2522                                 BlockdevChangeReadOnlyMode read_only,
2523                                 Error **errp)
2524 {
2525     BlockBackend *blk;
2526     BlockDriverState *medium_bs = NULL;
2527     int bdrv_flags, ret;
2528     QDict *options = NULL;
2529     Error *err = NULL;
2530
2531     blk = blk_by_name(device);
2532     if (!blk) {
2533         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2534                   "Device '%s' not found", device);
2535         goto fail;
2536     }
2537
2538     if (blk_bs(blk)) {
2539         blk_update_root_state(blk);
2540     }
2541
2542     bdrv_flags = blk_get_open_flags_from_root_state(blk);
2543     bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2544         BDRV_O_PROTOCOL);
2545
2546     if (!has_read_only) {
2547         read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2548     }
2549
2550     switch (read_only) {
2551     case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2552         break;
2553
2554     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2555         bdrv_flags &= ~BDRV_O_RDWR;
2556         break;
2557
2558     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2559         bdrv_flags |= BDRV_O_RDWR;
2560         break;
2561
2562     default:
2563         abort();
2564     }
2565
2566     if (has_format) {
2567         options = qdict_new();
2568         qdict_put(options, "driver", qstring_from_str(format));
2569     }
2570
2571     assert(!medium_bs);
2572     ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2573     if (ret < 0) {
2574         goto fail;
2575     }
2576
2577     blk_apply_root_state(blk, medium_bs);
2578
2579     bdrv_add_key(medium_bs, NULL, &err);
2580     if (err) {
2581         error_propagate(errp, err);
2582         goto fail;
2583     }
2584
2585     qmp_blockdev_open_tray(device, false, false, &err);
2586     if (err) {
2587         error_propagate(errp, err);
2588         goto fail;
2589     }
2590
2591     qmp_x_blockdev_remove_medium(device, &err);
2592     if (err) {
2593         error_propagate(errp, err);
2594         goto fail;
2595     }
2596
2597     qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2598     if (err) {
2599         error_propagate(errp, err);
2600         goto fail;
2601     }
2602
2603     qmp_blockdev_close_tray(device, errp);
2604
2605 fail:
2606     /* If the medium has been inserted, the device has its own reference, so
2607      * ours must be relinquished; and if it has not been inserted successfully,
2608      * the reference must be relinquished anyway */
2609     bdrv_unref(medium_bs);
2610 }
2611
2612 /* throttling disk I/O limits */
2613 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
2614                                int64_t bps_wr,
2615                                int64_t iops,
2616                                int64_t iops_rd,
2617                                int64_t iops_wr,
2618                                bool has_bps_max,
2619                                int64_t bps_max,
2620                                bool has_bps_rd_max,
2621                                int64_t bps_rd_max,
2622                                bool has_bps_wr_max,
2623                                int64_t bps_wr_max,
2624                                bool has_iops_max,
2625                                int64_t iops_max,
2626                                bool has_iops_rd_max,
2627                                int64_t iops_rd_max,
2628                                bool has_iops_wr_max,
2629                                int64_t iops_wr_max,
2630                                bool has_bps_max_length,
2631                                int64_t bps_max_length,
2632                                bool has_bps_rd_max_length,
2633                                int64_t bps_rd_max_length,
2634                                bool has_bps_wr_max_length,
2635                                int64_t bps_wr_max_length,
2636                                bool has_iops_max_length,
2637                                int64_t iops_max_length,
2638                                bool has_iops_rd_max_length,
2639                                int64_t iops_rd_max_length,
2640                                bool has_iops_wr_max_length,
2641                                int64_t iops_wr_max_length,
2642                                bool has_iops_size,
2643                                int64_t iops_size,
2644                                bool has_group,
2645                                const char *group, Error **errp)
2646 {
2647     ThrottleConfig cfg;
2648     BlockDriverState *bs;
2649     BlockBackend *blk;
2650     AioContext *aio_context;
2651
2652     blk = blk_by_name(device);
2653     if (!blk) {
2654         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2655                   "Device '%s' not found", device);
2656         return;
2657     }
2658
2659     aio_context = blk_get_aio_context(blk);
2660     aio_context_acquire(aio_context);
2661
2662     bs = blk_bs(blk);
2663     if (!bs) {
2664         error_setg(errp, "Device '%s' has no medium", device);
2665         goto out;
2666     }
2667
2668     /* The BlockBackend must be the only parent */
2669     assert(QLIST_FIRST(&bs->parents));
2670     if (QLIST_NEXT(QLIST_FIRST(&bs->parents), next_parent)) {
2671         error_setg(errp, "Cannot throttle device with multiple parents");
2672         goto out;
2673     }
2674
2675     throttle_config_init(&cfg);
2676     cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2677     cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;
2678     cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2679
2680     cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2681     cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;
2682     cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2683
2684     if (has_bps_max) {
2685         cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2686     }
2687     if (has_bps_rd_max) {
2688         cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2689     }
2690     if (has_bps_wr_max) {
2691         cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2692     }
2693     if (has_iops_max) {
2694         cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2695     }
2696     if (has_iops_rd_max) {
2697         cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2698     }
2699     if (has_iops_wr_max) {
2700         cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2701     }
2702
2703     if (has_bps_max_length) {
2704         cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = bps_max_length;
2705     }
2706     if (has_bps_rd_max_length) {
2707         cfg.buckets[THROTTLE_BPS_READ].burst_length = bps_rd_max_length;
2708     }
2709     if (has_bps_wr_max_length) {
2710         cfg.buckets[THROTTLE_BPS_WRITE].burst_length = bps_wr_max_length;
2711     }
2712     if (has_iops_max_length) {
2713         cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = iops_max_length;
2714     }
2715     if (has_iops_rd_max_length) {
2716         cfg.buckets[THROTTLE_OPS_READ].burst_length = iops_rd_max_length;
2717     }
2718     if (has_iops_wr_max_length) {
2719         cfg.buckets[THROTTLE_OPS_WRITE].burst_length = iops_wr_max_length;
2720     }
2721
2722     if (has_iops_size) {
2723         cfg.op_size = iops_size;
2724     }
2725
2726     if (!throttle_is_valid(&cfg, errp)) {
2727         goto out;
2728     }
2729
2730     if (throttle_enabled(&cfg)) {
2731         /* Enable I/O limits if they're not enabled yet, otherwise
2732          * just update the throttling group. */
2733         if (!bs->throttle_state) {
2734             bdrv_io_limits_enable(bs, has_group ? group : device);
2735         } else if (has_group) {
2736             bdrv_io_limits_update_group(bs, group);
2737         }
2738         /* Set the new throttling configuration */
2739         bdrv_set_io_limits(bs, &cfg);
2740     } else if (bs->throttle_state) {
2741         /* If all throttling settings are set to 0, disable I/O limits */
2742         bdrv_io_limits_disable(bs);
2743     }
2744
2745 out:
2746     aio_context_release(aio_context);
2747 }
2748
2749 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2750                                 bool has_granularity, uint32_t granularity,
2751                                 Error **errp)
2752 {
2753     AioContext *aio_context;
2754     BlockDriverState *bs;
2755
2756     if (!name || name[0] == '\0') {
2757         error_setg(errp, "Bitmap name cannot be empty");
2758         return;
2759     }
2760
2761     bs = bdrv_lookup_bs(node, node, errp);
2762     if (!bs) {
2763         return;
2764     }
2765
2766     aio_context = bdrv_get_aio_context(bs);
2767     aio_context_acquire(aio_context);
2768
2769     if (has_granularity) {
2770         if (granularity < 512 || !is_power_of_2(granularity)) {
2771             error_setg(errp, "Granularity must be power of 2 "
2772                              "and at least 512");
2773             goto out;
2774         }
2775     } else {
2776         /* Default to cluster size, if available: */
2777         granularity = bdrv_get_default_bitmap_granularity(bs);
2778     }
2779
2780     bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2781
2782  out:
2783     aio_context_release(aio_context);
2784 }
2785
2786 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2787                                    Error **errp)
2788 {
2789     AioContext *aio_context;
2790     BlockDriverState *bs;
2791     BdrvDirtyBitmap *bitmap;
2792
2793     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2794     if (!bitmap || !bs) {
2795         return;
2796     }
2797
2798     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2799         error_setg(errp,
2800                    "Bitmap '%s' is currently frozen and cannot be removed",
2801                    name);
2802         goto out;
2803     }
2804     bdrv_dirty_bitmap_make_anon(bitmap);
2805     bdrv_release_dirty_bitmap(bs, bitmap);
2806
2807  out:
2808     aio_context_release(aio_context);
2809 }
2810
2811 /**
2812  * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2813  * immediately after a full backup operation.
2814  */
2815 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2816                                   Error **errp)
2817 {
2818     AioContext *aio_context;
2819     BdrvDirtyBitmap *bitmap;
2820     BlockDriverState *bs;
2821
2822     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2823     if (!bitmap || !bs) {
2824         return;
2825     }
2826
2827     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2828         error_setg(errp,
2829                    "Bitmap '%s' is currently frozen and cannot be modified",
2830                    name);
2831         goto out;
2832     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2833         error_setg(errp,
2834                    "Bitmap '%s' is currently disabled and cannot be cleared",
2835                    name);
2836         goto out;
2837     }
2838
2839     bdrv_clear_dirty_bitmap(bitmap, NULL);
2840
2841  out:
2842     aio_context_release(aio_context);
2843 }
2844
2845 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2846 {
2847     const char *id = qdict_get_str(qdict, "id");
2848     BlockBackend *blk;
2849     BlockDriverState *bs;
2850     AioContext *aio_context;
2851     Error *local_err = NULL;
2852
2853     bs = bdrv_find_node(id);
2854     if (bs) {
2855         qmp_x_blockdev_del(false, NULL, true, id, &local_err);
2856         if (local_err) {
2857             error_report_err(local_err);
2858         }
2859         return;
2860     }
2861
2862     blk = blk_by_name(id);
2863     if (!blk) {
2864         error_report("Device '%s' not found", id);
2865         return;
2866     }
2867
2868     if (!blk_legacy_dinfo(blk)) {
2869         error_report("Deleting device added with blockdev-add"
2870                      " is not supported");
2871         return;
2872     }
2873
2874     aio_context = blk_get_aio_context(blk);
2875     aio_context_acquire(aio_context);
2876
2877     bs = blk_bs(blk);
2878     if (bs) {
2879         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2880             error_report_err(local_err);
2881             aio_context_release(aio_context);
2882             return;
2883         }
2884
2885         blk_remove_bs(blk);
2886     }
2887
2888     /* Make the BlockBackend and the attached BlockDriverState anonymous */
2889     monitor_remove_blk(blk);
2890
2891     /* If this BlockBackend has a device attached to it, its refcount will be
2892      * decremented when the device is removed; otherwise we have to do so here.
2893      */
2894     if (blk_get_attached_dev(blk)) {
2895         /* Further I/O must not pause the guest */
2896         blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2897                          BLOCKDEV_ON_ERROR_REPORT);
2898     } else {
2899         blk_unref(blk);
2900     }
2901
2902     aio_context_release(aio_context);
2903 }
2904
2905 void qmp_block_resize(bool has_device, const char *device,
2906                       bool has_node_name, const char *node_name,
2907                       int64_t size, Error **errp)
2908 {
2909     Error *local_err = NULL;
2910     BlockDriverState *bs;
2911     AioContext *aio_context;
2912     int ret;
2913
2914     bs = bdrv_lookup_bs(has_device ? device : NULL,
2915                         has_node_name ? node_name : NULL,
2916                         &local_err);
2917     if (local_err) {
2918         error_propagate(errp, local_err);
2919         return;
2920     }
2921
2922     aio_context = bdrv_get_aio_context(bs);
2923     aio_context_acquire(aio_context);
2924
2925     if (!bdrv_is_first_non_filter(bs)) {
2926         error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2927         goto out;
2928     }
2929
2930     if (size < 0) {
2931         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2932         goto out;
2933     }
2934
2935     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2936         error_setg(errp, QERR_DEVICE_IN_USE, device);
2937         goto out;
2938     }
2939
2940     /* complete all in-flight operations before resizing the device */
2941     bdrv_drain_all();
2942
2943     ret = bdrv_truncate(bs, size);
2944     switch (ret) {
2945     case 0:
2946         break;
2947     case -ENOMEDIUM:
2948         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2949         break;
2950     case -ENOTSUP:
2951         error_setg(errp, QERR_UNSUPPORTED);
2952         break;
2953     case -EACCES:
2954         error_setg(errp, "Device '%s' is read only", device);
2955         break;
2956     case -EBUSY:
2957         error_setg(errp, QERR_DEVICE_IN_USE, device);
2958         break;
2959     default:
2960         error_setg_errno(errp, -ret, "Could not resize");
2961         break;
2962     }
2963
2964 out:
2965     aio_context_release(aio_context);
2966 }
2967
2968 static void block_job_cb(void *opaque, int ret)
2969 {
2970     /* Note that this function may be executed from another AioContext besides
2971      * the QEMU main loop.  If you need to access anything that assumes the
2972      * QEMU global mutex, use a BH or introduce a mutex.
2973      */
2974
2975     BlockDriverState *bs = opaque;
2976     const char *msg = NULL;
2977
2978     trace_block_job_cb(bs, bs->job, ret);
2979
2980     assert(bs->job);
2981
2982     if (ret < 0) {
2983         msg = strerror(-ret);
2984     }
2985
2986     if (block_job_is_cancelled(bs->job)) {
2987         block_job_event_cancelled(bs->job);
2988     } else {
2989         block_job_event_completed(bs->job, msg);
2990     }
2991 }
2992
2993 void qmp_block_stream(const char *device,
2994                       bool has_base, const char *base,
2995                       bool has_backing_file, const char *backing_file,
2996                       bool has_speed, int64_t speed,
2997                       bool has_on_error, BlockdevOnError on_error,
2998                       Error **errp)
2999 {
3000     BlockBackend *blk;
3001     BlockDriverState *bs;
3002     BlockDriverState *base_bs = NULL;
3003     AioContext *aio_context;
3004     Error *local_err = NULL;
3005     const char *base_name = NULL;
3006
3007     if (!has_on_error) {
3008         on_error = BLOCKDEV_ON_ERROR_REPORT;
3009     }
3010
3011     blk = blk_by_name(device);
3012     if (!blk) {
3013         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3014                   "Device '%s' not found", device);
3015         return;
3016     }
3017
3018     aio_context = blk_get_aio_context(blk);
3019     aio_context_acquire(aio_context);
3020
3021     if (!blk_is_available(blk)) {
3022         error_setg(errp, "Device '%s' has no medium", device);
3023         goto out;
3024     }
3025     bs = blk_bs(blk);
3026
3027     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3028         goto out;
3029     }
3030
3031     if (has_base) {
3032         base_bs = bdrv_find_backing_image(bs, base);
3033         if (base_bs == NULL) {
3034             error_setg(errp, QERR_BASE_NOT_FOUND, base);
3035             goto out;
3036         }
3037         assert(bdrv_get_aio_context(base_bs) == aio_context);
3038         base_name = base;
3039     }
3040
3041     /* if we are streaming the entire chain, the result will have no backing
3042      * file, and specifying one is therefore an error */
3043     if (base_bs == NULL && has_backing_file) {
3044         error_setg(errp, "backing file specified, but streaming the "
3045                          "entire chain");
3046         goto out;
3047     }
3048
3049     /* backing_file string overrides base bs filename */
3050     base_name = has_backing_file ? backing_file : base_name;
3051
3052     stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
3053                  on_error, block_job_cb, bs, &local_err);
3054     if (local_err) {
3055         error_propagate(errp, local_err);
3056         goto out;
3057     }
3058
3059     trace_qmp_block_stream(bs, bs->job);
3060
3061 out:
3062     aio_context_release(aio_context);
3063 }
3064
3065 void qmp_block_commit(const char *device,
3066                       bool has_base, const char *base,
3067                       bool has_top, const char *top,
3068                       bool has_backing_file, const char *backing_file,
3069                       bool has_speed, int64_t speed,
3070                       Error **errp)
3071 {
3072     BlockBackend *blk;
3073     BlockDriverState *bs;
3074     BlockDriverState *base_bs, *top_bs;
3075     AioContext *aio_context;
3076     Error *local_err = NULL;
3077     /* This will be part of the QMP command, if/when the
3078      * BlockdevOnError change for blkmirror makes it in
3079      */
3080     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3081
3082     if (!has_speed) {
3083         speed = 0;
3084     }
3085
3086     /* Important Note:
3087      *  libvirt relies on the DeviceNotFound error class in order to probe for
3088      *  live commit feature versions; for this to work, we must make sure to
3089      *  perform the device lookup before any generic errors that may occur in a
3090      *  scenario in which all optional arguments are omitted. */
3091     blk = blk_by_name(device);
3092     if (!blk) {
3093         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3094                   "Device '%s' not found", device);
3095         return;
3096     }
3097
3098     aio_context = blk_get_aio_context(blk);
3099     aio_context_acquire(aio_context);
3100
3101     if (!blk_is_available(blk)) {
3102         error_setg(errp, "Device '%s' has no medium", device);
3103         goto out;
3104     }
3105     bs = blk_bs(blk);
3106
3107     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3108         goto out;
3109     }
3110
3111     /* default top_bs is the active layer */
3112     top_bs = bs;
3113
3114     if (has_top && top) {
3115         if (strcmp(bs->filename, top) != 0) {
3116             top_bs = bdrv_find_backing_image(bs, top);
3117         }
3118     }
3119
3120     if (top_bs == NULL) {
3121         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3122         goto out;
3123     }
3124
3125     assert(bdrv_get_aio_context(top_bs) == aio_context);
3126
3127     if (has_base && base) {
3128         base_bs = bdrv_find_backing_image(top_bs, base);
3129     } else {
3130         base_bs = bdrv_find_base(top_bs);
3131     }
3132
3133     if (base_bs == NULL) {
3134         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3135         goto out;
3136     }
3137
3138     assert(bdrv_get_aio_context(base_bs) == aio_context);
3139
3140     if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3141         goto out;
3142     }
3143
3144     /* Do not allow attempts to commit an image into itself */
3145     if (top_bs == base_bs) {
3146         error_setg(errp, "cannot commit an image into itself");
3147         goto out;
3148     }
3149
3150     if (top_bs == bs) {
3151         if (has_backing_file) {
3152             error_setg(errp, "'backing-file' specified,"
3153                              " but 'top' is the active layer");
3154             goto out;
3155         }
3156         commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
3157                             bs, &local_err);
3158     } else {
3159         commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
3160                      has_backing_file ? backing_file : NULL, &local_err);
3161     }
3162     if (local_err != NULL) {
3163         error_propagate(errp, local_err);
3164         goto out;
3165     }
3166
3167 out:
3168     aio_context_release(aio_context);
3169 }
3170
3171 static void do_drive_backup(const char *device, const char *target,
3172                             bool has_format, const char *format,
3173                             enum MirrorSyncMode sync,
3174                             bool has_mode, enum NewImageMode mode,
3175                             bool has_speed, int64_t speed,
3176                             bool has_bitmap, const char *bitmap,
3177                             bool has_on_source_error,
3178                             BlockdevOnError on_source_error,
3179                             bool has_on_target_error,
3180                             BlockdevOnError on_target_error,
3181                             BlockJobTxn *txn, Error **errp)
3182 {
3183     BlockBackend *blk;
3184     BlockDriverState *bs;
3185     BlockDriverState *target_bs;
3186     BlockDriverState *source = NULL;
3187     BdrvDirtyBitmap *bmap = NULL;
3188     AioContext *aio_context;
3189     QDict *options = NULL;
3190     Error *local_err = NULL;
3191     int flags;
3192     int64_t size;
3193     int ret;
3194
3195     if (!has_speed) {
3196         speed = 0;
3197     }
3198     if (!has_on_source_error) {
3199         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3200     }
3201     if (!has_on_target_error) {
3202         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3203     }
3204     if (!has_mode) {
3205         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3206     }
3207
3208     blk = blk_by_name(device);
3209     if (!blk) {
3210         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3211                   "Device '%s' not found", device);
3212         return;
3213     }
3214
3215     aio_context = blk_get_aio_context(blk);
3216     aio_context_acquire(aio_context);
3217
3218     /* Although backup_run has this check too, we need to use bs->drv below, so
3219      * do an early check redundantly. */
3220     if (!blk_is_available(blk)) {
3221         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3222         goto out;
3223     }
3224     bs = blk_bs(blk);
3225
3226     if (!has_format) {
3227         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3228     }
3229
3230     /* Early check to avoid creating target */
3231     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3232         goto out;
3233     }
3234
3235     flags = bs->open_flags | BDRV_O_RDWR;
3236
3237     /* See if we have a backing HD we can use to create our new image
3238      * on top of. */
3239     if (sync == MIRROR_SYNC_MODE_TOP) {
3240         source = backing_bs(bs);
3241         if (!source) {
3242             sync = MIRROR_SYNC_MODE_FULL;
3243         }
3244     }
3245     if (sync == MIRROR_SYNC_MODE_NONE) {
3246         source = bs;
3247     }
3248
3249     size = bdrv_getlength(bs);
3250     if (size < 0) {
3251         error_setg_errno(errp, -size, "bdrv_getlength failed");
3252         goto out;
3253     }
3254
3255     if (mode != NEW_IMAGE_MODE_EXISTING) {
3256         assert(format);
3257         if (source) {
3258             bdrv_img_create(target, format, source->filename,
3259                             source->drv->format_name, NULL,
3260                             size, flags, &local_err, false);
3261         } else {
3262             bdrv_img_create(target, format, NULL, NULL, NULL,
3263                             size, flags, &local_err, false);
3264         }
3265     }
3266
3267     if (local_err) {
3268         error_propagate(errp, local_err);
3269         goto out;
3270     }
3271
3272     if (format) {
3273         options = qdict_new();
3274         qdict_put(options, "driver", qstring_from_str(format));
3275     }
3276
3277     target_bs = NULL;
3278     ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
3279     if (ret < 0) {
3280         error_propagate(errp, local_err);
3281         goto out;
3282     }
3283
3284     bdrv_set_aio_context(target_bs, aio_context);
3285
3286     if (has_bitmap) {
3287         bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3288         if (!bmap) {
3289             error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3290             bdrv_unref(target_bs);
3291             goto out;
3292         }
3293     }
3294
3295     backup_start(bs, target_bs, speed, sync, bmap,
3296                  on_source_error, on_target_error,
3297                  block_job_cb, bs, txn, &local_err);
3298     if (local_err != NULL) {
3299         bdrv_unref(target_bs);
3300         error_propagate(errp, local_err);
3301         goto out;
3302     }
3303
3304 out:
3305     aio_context_release(aio_context);
3306 }
3307
3308 void qmp_drive_backup(const char *device, const char *target,
3309                       bool has_format, const char *format,
3310                       enum MirrorSyncMode sync,
3311                       bool has_mode, enum NewImageMode mode,
3312                       bool has_speed, int64_t speed,
3313                       bool has_bitmap, const char *bitmap,
3314                       bool has_on_source_error, BlockdevOnError on_source_error,
3315                       bool has_on_target_error, BlockdevOnError on_target_error,
3316                       Error **errp)
3317 {
3318     return do_drive_backup(device, target, has_format, format, sync,
3319                            has_mode, mode, has_speed, speed,
3320                            has_bitmap, bitmap,
3321                            has_on_source_error, on_source_error,
3322                            has_on_target_error, on_target_error,
3323                            NULL, errp);
3324 }
3325
3326 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3327 {
3328     return bdrv_named_nodes_list(errp);
3329 }
3330
3331 void do_blockdev_backup(const char *device, const char *target,
3332                          enum MirrorSyncMode sync,
3333                          bool has_speed, int64_t speed,
3334                          bool has_on_source_error,
3335                          BlockdevOnError on_source_error,
3336                          bool has_on_target_error,
3337                          BlockdevOnError on_target_error,
3338                          BlockJobTxn *txn, Error **errp)
3339 {
3340     BlockBackend *blk, *target_blk;
3341     BlockDriverState *bs;
3342     BlockDriverState *target_bs;
3343     Error *local_err = NULL;
3344     AioContext *aio_context;
3345
3346     if (!has_speed) {
3347         speed = 0;
3348     }
3349     if (!has_on_source_error) {
3350         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3351     }
3352     if (!has_on_target_error) {
3353         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3354     }
3355
3356     blk = blk_by_name(device);
3357     if (!blk) {
3358         error_setg(errp, "Device '%s' not found", device);
3359         return;
3360     }
3361
3362     aio_context = blk_get_aio_context(blk);
3363     aio_context_acquire(aio_context);
3364
3365     if (!blk_is_available(blk)) {
3366         error_setg(errp, "Device '%s' has no medium", device);
3367         goto out;
3368     }
3369     bs = blk_bs(blk);
3370
3371     target_blk = blk_by_name(target);
3372     if (!target_blk) {
3373         error_setg(errp, "Device '%s' not found", target);
3374         goto out;
3375     }
3376
3377     if (!blk_is_available(target_blk)) {
3378         error_setg(errp, "Device '%s' has no medium", target);
3379         goto out;
3380     }
3381     target_bs = blk_bs(target_blk);
3382
3383     bdrv_ref(target_bs);
3384     bdrv_set_aio_context(target_bs, aio_context);
3385     backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
3386                  on_target_error, block_job_cb, bs, txn, &local_err);
3387     if (local_err != NULL) {
3388         bdrv_unref(target_bs);
3389         error_propagate(errp, local_err);
3390     }
3391 out:
3392     aio_context_release(aio_context);
3393 }
3394
3395 void qmp_blockdev_backup(const char *device, const char *target,
3396                          enum MirrorSyncMode sync,
3397                          bool has_speed, int64_t speed,
3398                          bool has_on_source_error,
3399                          BlockdevOnError on_source_error,
3400                          bool has_on_target_error,
3401                          BlockdevOnError on_target_error,
3402                          Error **errp)
3403 {
3404     do_blockdev_backup(device, target, sync, has_speed, speed,
3405                        has_on_source_error, on_source_error,
3406                        has_on_target_error, on_target_error,
3407                        NULL, errp);
3408 }
3409
3410 /* Parameter check and block job starting for drive mirroring.
3411  * Caller should hold @device and @target's aio context (must be the same).
3412  **/
3413 static void blockdev_mirror_common(BlockDriverState *bs,
3414                                    BlockDriverState *target,
3415                                    bool has_replaces, const char *replaces,
3416                                    enum MirrorSyncMode sync,
3417                                    bool has_speed, int64_t speed,
3418                                    bool has_granularity, uint32_t granularity,
3419                                    bool has_buf_size, int64_t buf_size,
3420                                    bool has_on_source_error,
3421                                    BlockdevOnError on_source_error,
3422                                    bool has_on_target_error,
3423                                    BlockdevOnError on_target_error,
3424                                    bool has_unmap, bool unmap,
3425                                    Error **errp)
3426 {
3427
3428     if (!has_speed) {
3429         speed = 0;
3430     }
3431     if (!has_on_source_error) {
3432         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3433     }
3434     if (!has_on_target_error) {
3435         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3436     }
3437     if (!has_granularity) {
3438         granularity = 0;
3439     }
3440     if (!has_buf_size) {
3441         buf_size = 0;
3442     }
3443     if (!has_unmap) {
3444         unmap = true;
3445     }
3446
3447     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3448         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3449                    "a value in range [512B, 64MB]");
3450         return;
3451     }
3452     if (granularity & (granularity - 1)) {
3453         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3454                    "power of 2");
3455         return;
3456     }
3457
3458     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3459         return;
3460     }
3461     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3462         return;
3463     }
3464     if (target->blk) {
3465         error_setg(errp, "Cannot mirror to an attached block device");
3466         return;
3467     }
3468
3469     if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3470         sync = MIRROR_SYNC_MODE_FULL;
3471     }
3472
3473     /* pass the node name to replace to mirror start since it's loose coupling
3474      * and will allow to check whether the node still exist at mirror completion
3475      */
3476     mirror_start(bs, target,
3477                  has_replaces ? replaces : NULL,
3478                  speed, granularity, buf_size, sync,
3479                  on_source_error, on_target_error, unmap,
3480                  block_job_cb, bs, errp);
3481 }
3482
3483 void qmp_drive_mirror(const char *device, const char *target,
3484                       bool has_format, const char *format,
3485                       bool has_node_name, const char *node_name,
3486                       bool has_replaces, const char *replaces,
3487                       enum MirrorSyncMode sync,
3488                       bool has_mode, enum NewImageMode mode,
3489                       bool has_speed, int64_t speed,
3490                       bool has_granularity, uint32_t granularity,
3491                       bool has_buf_size, int64_t buf_size,
3492                       bool has_on_source_error, BlockdevOnError on_source_error,
3493                       bool has_on_target_error, BlockdevOnError on_target_error,
3494                       bool has_unmap, bool unmap,
3495                       Error **errp)
3496 {
3497     BlockDriverState *bs;
3498     BlockBackend *blk;
3499     BlockDriverState *source, *target_bs;
3500     AioContext *aio_context;
3501     Error *local_err = NULL;
3502     QDict *options = NULL;
3503     int flags;
3504     int64_t size;
3505     int ret;
3506
3507     blk = blk_by_name(device);
3508     if (!blk) {
3509         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3510                   "Device '%s' not found", device);
3511         return;
3512     }
3513
3514     aio_context = blk_get_aio_context(blk);
3515     aio_context_acquire(aio_context);
3516
3517     if (!blk_is_available(blk)) {
3518         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3519         goto out;
3520     }
3521     bs = blk_bs(blk);
3522     if (!has_mode) {
3523         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3524     }
3525
3526     if (!has_format) {
3527         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3528     }
3529
3530     flags = bs->open_flags | BDRV_O_RDWR;
3531     source = backing_bs(bs);
3532     if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3533         sync = MIRROR_SYNC_MODE_FULL;
3534     }
3535     if (sync == MIRROR_SYNC_MODE_NONE) {
3536         source = bs;
3537     }
3538
3539     size = bdrv_getlength(bs);
3540     if (size < 0) {
3541         error_setg_errno(errp, -size, "bdrv_getlength failed");
3542         goto out;
3543     }
3544
3545     if (has_replaces) {
3546         BlockDriverState *to_replace_bs;
3547         AioContext *replace_aio_context;
3548         int64_t replace_size;
3549
3550         if (!has_node_name) {
3551             error_setg(errp, "a node-name must be provided when replacing a"
3552                              " named node of the graph");
3553             goto out;
3554         }
3555
3556         to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
3557
3558         if (!to_replace_bs) {
3559             error_propagate(errp, local_err);
3560             goto out;
3561         }
3562
3563         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3564         aio_context_acquire(replace_aio_context);
3565         replace_size = bdrv_getlength(to_replace_bs);
3566         aio_context_release(replace_aio_context);
3567
3568         if (size != replace_size) {
3569             error_setg(errp, "cannot replace image with a mirror image of "
3570                              "different size");
3571             goto out;
3572         }
3573     }
3574
3575     if ((sync == MIRROR_SYNC_MODE_FULL || !source)
3576         && mode != NEW_IMAGE_MODE_EXISTING)
3577     {
3578         /* create new image w/o backing file */
3579         assert(format);
3580         bdrv_img_create(target, format,
3581                         NULL, NULL, NULL, size, flags, &local_err, false);
3582     } else {
3583         switch (mode) {
3584         case NEW_IMAGE_MODE_EXISTING:
3585             break;
3586         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3587             /* create new image with backing file */
3588             bdrv_img_create(target, format,
3589                             source->filename,
3590                             source->drv->format_name,
3591                             NULL, size, flags, &local_err, false);
3592             break;
3593         default:
3594             abort();
3595         }
3596     }
3597
3598     if (local_err) {
3599         error_propagate(errp, local_err);
3600         goto out;
3601     }
3602
3603     options = qdict_new();
3604     if (has_node_name) {
3605         qdict_put(options, "node-name", qstring_from_str(node_name));
3606     }
3607     if (format) {
3608         qdict_put(options, "driver", qstring_from_str(format));
3609     }
3610
3611     /* Mirroring takes care of copy-on-write using the source's backing
3612      * file.
3613      */
3614     target_bs = NULL;
3615     ret = bdrv_open(&target_bs, target, NULL, options,
3616                     flags | BDRV_O_NO_BACKING, &local_err);
3617     if (ret < 0) {
3618         error_propagate(errp, local_err);
3619         goto out;
3620     }
3621
3622     bdrv_set_aio_context(target_bs, aio_context);
3623
3624     blockdev_mirror_common(bs, target_bs,
3625                            has_replaces, replaces, sync,
3626                            has_speed, speed,
3627                            has_granularity, granularity,
3628                            has_buf_size, buf_size,
3629                            has_on_source_error, on_source_error,
3630                            has_on_target_error, on_target_error,
3631                            has_unmap, unmap,
3632                            &local_err);
3633     if (local_err) {
3634         error_propagate(errp, local_err);
3635         bdrv_unref(target_bs);
3636     }
3637 out:
3638     aio_context_release(aio_context);
3639 }
3640
3641 void qmp_blockdev_mirror(const char *device, const char *target,
3642                          bool has_replaces, const char *replaces,
3643                          MirrorSyncMode sync,
3644                          bool has_speed, int64_t speed,
3645                          bool has_granularity, uint32_t granularity,
3646                          bool has_buf_size, int64_t buf_size,
3647                          bool has_on_source_error,
3648                          BlockdevOnError on_source_error,
3649                          bool has_on_target_error,
3650                          BlockdevOnError on_target_error,
3651                          Error **errp)
3652 {
3653     BlockDriverState *bs;
3654     BlockBackend *blk;
3655     BlockDriverState *target_bs;
3656     AioContext *aio_context;
3657     Error *local_err = NULL;
3658
3659     blk = blk_by_name(device);
3660     if (!blk) {
3661         error_setg(errp, "Device '%s' not found", device);
3662         return;
3663     }
3664     bs = blk_bs(blk);
3665
3666     if (!bs) {
3667         error_setg(errp, "Device '%s' has no media", device);
3668         return;
3669     }
3670
3671     target_bs = bdrv_lookup_bs(target, target, errp);
3672     if (!target_bs) {
3673         return;
3674     }
3675
3676     aio_context = bdrv_get_aio_context(bs);
3677     aio_context_acquire(aio_context);
3678
3679     bdrv_ref(target_bs);
3680     bdrv_set_aio_context(target_bs, aio_context);
3681
3682     blockdev_mirror_common(bs, target_bs,
3683                            has_replaces, replaces, sync,
3684                            has_speed, speed,
3685                            has_granularity, granularity,
3686                            has_buf_size, buf_size,
3687                            has_on_source_error, on_source_error,
3688                            has_on_target_error, on_target_error,
3689                            true, true,
3690                            &local_err);
3691     if (local_err) {
3692         error_propagate(errp, local_err);
3693         bdrv_unref(target_bs);
3694     }
3695
3696     aio_context_release(aio_context);
3697 }
3698
3699 /* Get the block job for a given device name and acquire its AioContext */
3700 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
3701                                 Error **errp)
3702 {
3703     BlockBackend *blk;
3704     BlockDriverState *bs;
3705
3706     *aio_context = NULL;
3707
3708     blk = blk_by_name(device);
3709     if (!blk) {
3710         goto notfound;
3711     }
3712
3713     *aio_context = blk_get_aio_context(blk);
3714     aio_context_acquire(*aio_context);
3715
3716     if (!blk_is_available(blk)) {
3717         goto notfound;
3718     }
3719     bs = blk_bs(blk);
3720
3721     if (!bs->job) {
3722         goto notfound;
3723     }
3724
3725     return bs->job;
3726
3727 notfound:
3728     error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3729               "No active block job on device '%s'", device);
3730     if (*aio_context) {
3731         aio_context_release(*aio_context);
3732         *aio_context = NULL;
3733     }
3734     return NULL;
3735 }
3736
3737 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3738 {
3739     AioContext *aio_context;
3740     BlockJob *job = find_block_job(device, &aio_context, errp);
3741
3742     if (!job) {
3743         return;
3744     }
3745
3746     block_job_set_speed(job, speed, errp);
3747     aio_context_release(aio_context);
3748 }
3749
3750 void qmp_block_job_cancel(const char *device,
3751                           bool has_force, bool force, Error **errp)
3752 {
3753     AioContext *aio_context;
3754     BlockJob *job = find_block_job(device, &aio_context, errp);
3755
3756     if (!job) {
3757         return;
3758     }
3759
3760     if (!has_force) {
3761         force = false;
3762     }
3763
3764     if (job->user_paused && !force) {
3765         error_setg(errp, "The block job for device '%s' is currently paused",
3766                    device);
3767         goto out;
3768     }
3769
3770     trace_qmp_block_job_cancel(job);
3771     block_job_cancel(job);
3772 out:
3773     aio_context_release(aio_context);
3774 }
3775
3776 void qmp_block_job_pause(const char *device, Error **errp)
3777 {
3778     AioContext *aio_context;
3779     BlockJob *job = find_block_job(device, &aio_context, errp);
3780
3781     if (!job || job->user_paused) {
3782         return;
3783     }
3784
3785     job->user_paused = true;
3786     trace_qmp_block_job_pause(job);
3787     block_job_pause(job);
3788     aio_context_release(aio_context);
3789 }
3790
3791 void qmp_block_job_resume(const char *device, Error **errp)
3792 {
3793     AioContext *aio_context;
3794     BlockJob *job = find_block_job(device, &aio_context, errp);
3795
3796     if (!job || !job->user_paused) {
3797         return;
3798     }
3799
3800     job->user_paused = false;
3801     trace_qmp_block_job_resume(job);
3802     block_job_resume(job);
3803     aio_context_release(aio_context);
3804 }
3805
3806 void qmp_block_job_complete(const char *device, Error **errp)
3807 {
3808     AioContext *aio_context;
3809     BlockJob *job = find_block_job(device, &aio_context, errp);
3810
3811     if (!job) {
3812         return;
3813     }
3814
3815     trace_qmp_block_job_complete(job);
3816     block_job_complete(job, errp);
3817     aio_context_release(aio_context);
3818 }
3819
3820 void qmp_change_backing_file(const char *device,
3821                              const char *image_node_name,
3822                              const char *backing_file,
3823                              Error **errp)
3824 {
3825     BlockBackend *blk;
3826     BlockDriverState *bs = NULL;
3827     AioContext *aio_context;
3828     BlockDriverState *image_bs = NULL;
3829     Error *local_err = NULL;
3830     bool ro;
3831     int open_flags;
3832     int ret;
3833
3834     blk = blk_by_name(device);
3835     if (!blk) {
3836         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3837                   "Device '%s' not found", device);
3838         return;
3839     }
3840
3841     aio_context = blk_get_aio_context(blk);
3842     aio_context_acquire(aio_context);
3843
3844     if (!blk_is_available(blk)) {
3845         error_setg(errp, "Device '%s' has no medium", device);
3846         goto out;
3847     }
3848     bs = blk_bs(blk);
3849
3850     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3851     if (local_err) {
3852         error_propagate(errp, local_err);
3853         goto out;
3854     }
3855
3856     if (!image_bs) {
3857         error_setg(errp, "image file not found");
3858         goto out;
3859     }
3860
3861     if (bdrv_find_base(image_bs) == image_bs) {
3862         error_setg(errp, "not allowing backing file change on an image "
3863                          "without a backing file");
3864         goto out;
3865     }
3866
3867     /* even though we are not necessarily operating on bs, we need it to
3868      * determine if block ops are currently prohibited on the chain */
3869     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3870         goto out;
3871     }
3872
3873     /* final sanity check */
3874     if (!bdrv_chain_contains(bs, image_bs)) {
3875         error_setg(errp, "'%s' and image file are not in the same chain",
3876                    device);
3877         goto out;
3878     }
3879
3880     /* if not r/w, reopen to make r/w */
3881     open_flags = image_bs->open_flags;
3882     ro = bdrv_is_read_only(image_bs);
3883
3884     if (ro) {
3885         bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3886         if (local_err) {
3887             error_propagate(errp, local_err);
3888             goto out;
3889         }
3890     }
3891
3892     ret = bdrv_change_backing_file(image_bs, backing_file,
3893                                image_bs->drv ? image_bs->drv->format_name : "");
3894
3895     if (ret < 0) {
3896         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3897                          backing_file);
3898         /* don't exit here, so we can try to restore open flags if
3899          * appropriate */
3900     }
3901
3902     if (ro) {
3903         bdrv_reopen(image_bs, open_flags, &local_err);
3904         if (local_err) {
3905             error_propagate(errp, local_err); /* will preserve prior errp */
3906         }
3907     }
3908
3909 out:
3910     aio_context_release(aio_context);
3911 }
3912
3913 void hmp_drive_add_node(Monitor *mon, const char *optstr)
3914 {
3915     QemuOpts *opts;
3916     QDict *qdict;
3917     Error *local_err = NULL;
3918
3919     opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3920     if (!opts) {
3921         return;
3922     }
3923
3924     qdict = qemu_opts_to_qdict(opts, NULL);
3925
3926     if (!qdict_get_try_str(qdict, "node-name")) {
3927         QDECREF(qdict);
3928         error_report("'node-name' needs to be specified");
3929         goto out;
3930     }
3931
3932     BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3933     if (!bs) {
3934         error_report_err(local_err);
3935         goto out;
3936     }
3937
3938     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3939
3940 out:
3941     qemu_opts_del(opts);
3942 }
3943
3944 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3945 {
3946     QmpOutputVisitor *ov = qmp_output_visitor_new();
3947     BlockDriverState *bs;
3948     BlockBackend *blk = NULL;
3949     QObject *obj;
3950     QDict *qdict;
3951     Error *local_err = NULL;
3952
3953     /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3954      * cache.direct=false instead of silently switching to aio=threads, except
3955      * when called from drive_new().
3956      *
3957      * For now, simply forbidding the combination for all drivers will do. */
3958     if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3959         bool direct = options->has_cache &&
3960                       options->cache->has_direct &&
3961                       options->cache->direct;
3962         if (!direct) {
3963             error_setg(errp, "aio=native requires cache.direct=true");
3964             goto fail;
3965         }
3966     }
3967
3968     visit_type_BlockdevOptions(qmp_output_get_visitor(ov), NULL, &options,
3969                                &local_err);
3970     if (local_err) {
3971         error_propagate(errp, local_err);
3972         goto fail;
3973     }
3974
3975     obj = qmp_output_get_qobject(ov);
3976     qdict = qobject_to_qdict(obj);
3977
3978     qdict_flatten(qdict);
3979
3980     if (options->has_id) {
3981         blk = blockdev_init(NULL, qdict, &local_err);
3982         if (local_err) {
3983             error_propagate(errp, local_err);
3984             goto fail;
3985         }
3986
3987         bs = blk_bs(blk);
3988     } else {
3989         if (!qdict_get_try_str(qdict, "node-name")) {
3990             error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3991                        "the root node");
3992             goto fail;
3993         }
3994
3995         bs = bds_tree_init(qdict, errp);
3996         if (!bs) {
3997             goto fail;
3998         }
3999
4000         QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4001     }
4002
4003     if (bs && bdrv_key_required(bs)) {
4004         if (blk) {
4005             monitor_remove_blk(blk);
4006             blk_unref(blk);
4007         } else {
4008             QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4009             bdrv_unref(bs);
4010         }
4011         error_setg(errp, "blockdev-add doesn't support encrypted devices");
4012         goto fail;
4013     }
4014
4015 fail:
4016     qmp_output_visitor_cleanup(ov);
4017 }
4018
4019 void qmp_x_blockdev_del(bool has_id, const char *id,
4020                         bool has_node_name, const char *node_name, Error **errp)
4021 {
4022     AioContext *aio_context;
4023     BlockBackend *blk;
4024     BlockDriverState *bs;
4025
4026     if (has_id && has_node_name) {
4027         error_setg(errp, "Only one of id and node-name must be specified");
4028         return;
4029     } else if (!has_id && !has_node_name) {
4030         error_setg(errp, "No block device specified");
4031         return;
4032     }
4033
4034     if (has_id) {
4035         /* blk_by_name() never returns a BB that is not owned by the monitor */
4036         blk = blk_by_name(id);
4037         if (!blk) {
4038             error_setg(errp, "Cannot find block backend %s", id);
4039             return;
4040         }
4041         if (blk_legacy_dinfo(blk)) {
4042             error_setg(errp, "Deleting block backend added with drive-add"
4043                        " is not supported");
4044             return;
4045         }
4046         if (blk_get_refcnt(blk) > 1) {
4047             error_setg(errp, "Block backend %s is in use", id);
4048             return;
4049         }
4050         bs = blk_bs(blk);
4051         aio_context = blk_get_aio_context(blk);
4052     } else {
4053         bs = bdrv_find_node(node_name);
4054         if (!bs) {
4055             error_setg(errp, "Cannot find node %s", node_name);
4056             return;
4057         }
4058         blk = bs->blk;
4059         if (blk) {
4060             error_setg(errp, "Node %s is in use by %s",
4061                        node_name, blk_name(blk));
4062             return;
4063         }
4064         aio_context = bdrv_get_aio_context(bs);
4065     }
4066
4067     aio_context_acquire(aio_context);
4068
4069     if (bs) {
4070         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4071             goto out;
4072         }
4073
4074         if (!blk && !bs->monitor_list.tqe_prev) {
4075             error_setg(errp, "Node %s is not owned by the monitor",
4076                        bs->node_name);
4077             goto out;
4078         }
4079
4080         if (bs->refcnt > 1) {
4081             error_setg(errp, "Block device %s is in use",
4082                        bdrv_get_device_or_node_name(bs));
4083             goto out;
4084         }
4085     }
4086
4087     if (blk) {
4088         monitor_remove_blk(blk);
4089         blk_unref(blk);
4090     } else {
4091         QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4092         bdrv_unref(bs);
4093     }
4094
4095 out:
4096     aio_context_release(aio_context);
4097 }
4098
4099 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4100 {
4101     BlockJobInfoList *head = NULL, **p_next = &head;
4102     BlockDriverState *bs;
4103
4104     for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
4105         AioContext *aio_context = bdrv_get_aio_context(bs);
4106
4107         aio_context_acquire(aio_context);
4108
4109         if (bs->job) {
4110             BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4111             elem->value = block_job_query(bs->job);
4112             *p_next = elem;
4113             p_next = &elem->next;
4114         }
4115
4116         aio_context_release(aio_context);
4117     }
4118
4119     return head;
4120 }
4121
4122 QemuOptsList qemu_common_drive_opts = {
4123     .name = "drive",
4124     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4125     .desc = {
4126         {
4127             .name = "snapshot",
4128             .type = QEMU_OPT_BOOL,
4129             .help = "enable/disable snapshot mode",
4130         },{
4131             .name = "discard",
4132             .type = QEMU_OPT_STRING,
4133             .help = "discard operation (ignore/off, unmap/on)",
4134         },{
4135             .name = "aio",
4136             .type = QEMU_OPT_STRING,
4137             .help = "host AIO implementation (threads, native)",
4138         },{
4139             .name = BDRV_OPT_CACHE_WB,
4140             .type = QEMU_OPT_BOOL,
4141             .help = "Enable writeback mode",
4142         },{
4143             .name = "format",
4144             .type = QEMU_OPT_STRING,
4145             .help = "disk format (raw, qcow2, ...)",
4146         },{
4147             .name = "rerror",
4148             .type = QEMU_OPT_STRING,
4149             .help = "read error action",
4150         },{
4151             .name = "werror",
4152             .type = QEMU_OPT_STRING,
4153             .help = "write error action",
4154         },{
4155             .name = "read-only",
4156             .type = QEMU_OPT_BOOL,
4157             .help = "open drive file as read-only",
4158         },{
4159             .name = "throttling.iops-total",
4160             .type = QEMU_OPT_NUMBER,
4161             .help = "limit total I/O operations per second",
4162         },{
4163             .name = "throttling.iops-read",
4164             .type = QEMU_OPT_NUMBER,
4165             .help = "limit read operations per second",
4166         },{
4167             .name = "throttling.iops-write",
4168             .type = QEMU_OPT_NUMBER,
4169             .help = "limit write operations per second",
4170         },{
4171             .name = "throttling.bps-total",
4172             .type = QEMU_OPT_NUMBER,
4173             .help = "limit total bytes per second",
4174         },{
4175             .name = "throttling.bps-read",
4176             .type = QEMU_OPT_NUMBER,
4177             .help = "limit read bytes per second",
4178         },{
4179             .name = "throttling.bps-write",
4180             .type = QEMU_OPT_NUMBER,
4181             .help = "limit write bytes per second",
4182         },{
4183             .name = "throttling.iops-total-max",
4184             .type = QEMU_OPT_NUMBER,
4185             .help = "I/O operations burst",
4186         },{
4187             .name = "throttling.iops-read-max",
4188             .type = QEMU_OPT_NUMBER,
4189             .help = "I/O operations read burst",
4190         },{
4191             .name = "throttling.iops-write-max",
4192             .type = QEMU_OPT_NUMBER,
4193             .help = "I/O operations write burst",
4194         },{
4195             .name = "throttling.bps-total-max",
4196             .type = QEMU_OPT_NUMBER,
4197             .help = "total bytes burst",
4198         },{
4199             .name = "throttling.bps-read-max",
4200             .type = QEMU_OPT_NUMBER,
4201             .help = "total bytes read burst",
4202         },{
4203             .name = "throttling.bps-write-max",
4204             .type = QEMU_OPT_NUMBER,
4205             .help = "total bytes write burst",
4206         },{
4207             .name = "throttling.iops-total-max-length",
4208             .type = QEMU_OPT_NUMBER,
4209             .help = "length of the iops-total-max burst period, in seconds",
4210         },{
4211             .name = "throttling.iops-read-max-length",
4212             .type = QEMU_OPT_NUMBER,
4213             .help = "length of the iops-read-max burst period, in seconds",
4214         },{
4215             .name = "throttling.iops-write-max-length",
4216             .type = QEMU_OPT_NUMBER,
4217             .help = "length of the iops-write-max burst period, in seconds",
4218         },{
4219             .name = "throttling.bps-total-max-length",
4220             .type = QEMU_OPT_NUMBER,
4221             .help = "length of the bps-total-max burst period, in seconds",
4222         },{
4223             .name = "throttling.bps-read-max-length",
4224             .type = QEMU_OPT_NUMBER,
4225             .help = "length of the bps-read-max burst period, in seconds",
4226         },{
4227             .name = "throttling.bps-write-max-length",
4228             .type = QEMU_OPT_NUMBER,
4229             .help = "length of the bps-write-max burst period, in seconds",
4230         },{
4231             .name = "throttling.iops-size",
4232             .type = QEMU_OPT_NUMBER,
4233             .help = "when limiting by iops max size of an I/O in bytes",
4234         },{
4235             .name = "throttling.group",
4236             .type = QEMU_OPT_STRING,
4237             .help = "name of the block throttling group",
4238         },{
4239             .name = "copy-on-read",
4240             .type = QEMU_OPT_BOOL,
4241             .help = "copy read data from backing file into image file",
4242         },{
4243             .name = "detect-zeroes",
4244             .type = QEMU_OPT_STRING,
4245             .help = "try to optimize zero writes (off, on, unmap)",
4246         },{
4247             .name = "stats-account-invalid",
4248             .type = QEMU_OPT_BOOL,
4249             .help = "whether to account for invalid I/O operations "
4250                     "in the statistics",
4251         },{
4252             .name = "stats-account-failed",
4253             .type = QEMU_OPT_BOOL,
4254             .help = "whether to account for failed I/O operations "
4255                     "in the statistics",
4256         },
4257         { /* end of list */ }
4258     },
4259 };
4260
4261 static QemuOptsList qemu_root_bds_opts = {
4262     .name = "root-bds",
4263     .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4264     .desc = {
4265         {
4266             .name = "discard",
4267             .type = QEMU_OPT_STRING,
4268             .help = "discard operation (ignore/off, unmap/on)",
4269         },{
4270             .name = "aio",
4271             .type = QEMU_OPT_STRING,
4272             .help = "host AIO implementation (threads, native)",
4273         },{
4274             .name = "read-only",
4275             .type = QEMU_OPT_BOOL,
4276             .help = "open drive file as read-only",
4277         },{
4278             .name = "copy-on-read",
4279             .type = QEMU_OPT_BOOL,
4280             .help = "copy read data from backing file into image file",
4281         },{
4282             .name = "detect-zeroes",
4283             .type = QEMU_OPT_STRING,
4284             .help = "try to optimize zero writes (off, on, unmap)",
4285         },
4286         { /* end of list */ }
4287     },
4288 };
4289
4290 QemuOptsList qemu_drive_opts = {
4291     .name = "drive",
4292     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4293     .desc = {
4294         /*
4295          * no elements => accept any params
4296          * validation will happen later
4297          */
4298         { /* end of list */ }
4299     },
4300 };