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