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