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