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