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