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