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