OSDN Git Service

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