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