xref: /openbmc/qemu/blockdev.c (revision 97148076e8beebbcab11e5cb581d8508722143fc)
1666daa68SMarkus Armbruster /*
2666daa68SMarkus Armbruster  * QEMU host block devices
3666daa68SMarkus Armbruster  *
4666daa68SMarkus Armbruster  * Copyright (c) 2003-2008 Fabrice Bellard
5666daa68SMarkus Armbruster  *
6666daa68SMarkus Armbruster  * This work is licensed under the terms of the GNU GPL, version 2 or
7666daa68SMarkus Armbruster  * later.  See the COPYING file in the top-level directory.
83618a094SMarkus Armbruster  *
93618a094SMarkus Armbruster  * This file incorporates work covered by the following copyright and
103618a094SMarkus Armbruster  * permission notice:
113618a094SMarkus Armbruster  *
123618a094SMarkus Armbruster  * Copyright (c) 2003-2008 Fabrice Bellard
133618a094SMarkus Armbruster  *
143618a094SMarkus Armbruster  * Permission is hereby granted, free of charge, to any person obtaining a copy
153618a094SMarkus Armbruster  * of this software and associated documentation files (the "Software"), to deal
163618a094SMarkus Armbruster  * in the Software without restriction, including without limitation the rights
173618a094SMarkus Armbruster  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
183618a094SMarkus Armbruster  * copies of the Software, and to permit persons to whom the Software is
193618a094SMarkus Armbruster  * furnished to do so, subject to the following conditions:
203618a094SMarkus Armbruster  *
213618a094SMarkus Armbruster  * The above copyright notice and this permission notice shall be included in
223618a094SMarkus Armbruster  * all copies or substantial portions of the Software.
233618a094SMarkus Armbruster  *
243618a094SMarkus Armbruster  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
253618a094SMarkus Armbruster  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
263618a094SMarkus Armbruster  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
273618a094SMarkus Armbruster  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
283618a094SMarkus Armbruster  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
293618a094SMarkus Armbruster  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
303618a094SMarkus Armbruster  * THE SOFTWARE.
31666daa68SMarkus Armbruster  */
32666daa68SMarkus Armbruster 
33d38ea87aSPeter Maydell #include "qemu/osdep.h"
3426f54e9aSMarkus Armbruster #include "sysemu/block-backend.h"
359c17d615SPaolo Bonzini #include "sysemu/blockdev.h"
360d09e41aSPaolo Bonzini #include "hw/block/block.h"
37737e150eSPaolo Bonzini #include "block/blockjob.h"
3876f4afb4SAlberto Garcia #include "block/throttle-groups.h"
3983c9089eSPaolo Bonzini #include "monitor/monitor.h"
40d49b6836SMarkus Armbruster #include "qemu/error-report.h"
411de7afc9SPaolo Bonzini #include "qemu/option.h"
421de7afc9SPaolo Bonzini #include "qemu/config-file.h"
437b1b5d19SPaolo Bonzini #include "qapi/qmp/types.h"
44d26c9a15SKevin Wolf #include "qapi-visit.h"
45cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
46d26c9a15SKevin Wolf #include "qapi/qmp-output-visitor.h"
479e7dac7cSPeter Lieven #include "qapi/util.h"
489c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
49737e150eSPaolo Bonzini #include "block/block_int.h"
50a4dea8a9SLuiz Capitulino #include "qmp-commands.h"
5112bd451fSStefan Hajnoczi #include "trace.h"
529c17d615SPaolo Bonzini #include "sysemu/arch_init.h"
53f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
54f348b6d1SVeronia Bahaa #include "qemu/help_option.h"
55666daa68SMarkus Armbruster 
569c4218e9SMax Reitz static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
579c4218e9SMax Reitz     QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
589c4218e9SMax Reitz 
591960966dSMarkus Armbruster static const char *const if_name[IF_COUNT] = {
601960966dSMarkus Armbruster     [IF_NONE] = "none",
611960966dSMarkus Armbruster     [IF_IDE] = "ide",
621960966dSMarkus Armbruster     [IF_SCSI] = "scsi",
631960966dSMarkus Armbruster     [IF_FLOPPY] = "floppy",
641960966dSMarkus Armbruster     [IF_PFLASH] = "pflash",
651960966dSMarkus Armbruster     [IF_MTD] = "mtd",
661960966dSMarkus Armbruster     [IF_SD] = "sd",
671960966dSMarkus Armbruster     [IF_VIRTIO] = "virtio",
681960966dSMarkus Armbruster     [IF_XEN] = "xen",
691960966dSMarkus Armbruster };
701960966dSMarkus Armbruster 
7121dff8cfSJohn Snow static int if_max_devs[IF_COUNT] = {
7227d6bf40SMarkus Armbruster     /*
7327d6bf40SMarkus Armbruster      * Do not change these numbers!  They govern how drive option
7427d6bf40SMarkus Armbruster      * index maps to unit and bus.  That mapping is ABI.
7527d6bf40SMarkus Armbruster      *
76547cb157SWei Jiangang      * All controllers used to implement if=T drives need to support
7727d6bf40SMarkus Armbruster      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
7827d6bf40SMarkus Armbruster      * Otherwise, some index values map to "impossible" bus, unit
7927d6bf40SMarkus Armbruster      * values.
8027d6bf40SMarkus Armbruster      *
8127d6bf40SMarkus Armbruster      * For instance, if you change [IF_SCSI] to 255, -drive
8227d6bf40SMarkus Armbruster      * if=scsi,index=12 no longer means bus=1,unit=5, but
8327d6bf40SMarkus Armbruster      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
8427d6bf40SMarkus Armbruster      * the drive can't be set up.  Regression.
8527d6bf40SMarkus Armbruster      */
8627d6bf40SMarkus Armbruster     [IF_IDE] = 2,
8727d6bf40SMarkus Armbruster     [IF_SCSI] = 7,
881960966dSMarkus Armbruster };
891960966dSMarkus Armbruster 
9021dff8cfSJohn Snow /**
9121dff8cfSJohn Snow  * Boards may call this to offer board-by-board overrides
9221dff8cfSJohn Snow  * of the default, global values.
9321dff8cfSJohn Snow  */
9421dff8cfSJohn Snow void override_max_devs(BlockInterfaceType type, int max_devs)
9521dff8cfSJohn Snow {
9618e46a03SMarkus Armbruster     BlockBackend *blk;
9721dff8cfSJohn Snow     DriveInfo *dinfo;
9821dff8cfSJohn Snow 
9921dff8cfSJohn Snow     if (max_devs <= 0) {
10021dff8cfSJohn Snow         return;
10121dff8cfSJohn Snow     }
10221dff8cfSJohn Snow 
10318e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
10418e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
10521dff8cfSJohn Snow         if (dinfo->type == type) {
10621dff8cfSJohn Snow             fprintf(stderr, "Cannot override units-per-bus property of"
10721dff8cfSJohn Snow                     " the %s interface, because a drive of that type has"
10821dff8cfSJohn Snow                     " already been added.\n", if_name[type]);
10921dff8cfSJohn Snow             g_assert_not_reached();
11021dff8cfSJohn Snow         }
11121dff8cfSJohn Snow     }
11221dff8cfSJohn Snow 
11321dff8cfSJohn Snow     if_max_devs[type] = max_devs;
11421dff8cfSJohn Snow }
11521dff8cfSJohn Snow 
11614bafc54SMarkus Armbruster /*
11714bafc54SMarkus Armbruster  * We automatically delete the drive when a device using it gets
11814bafc54SMarkus Armbruster  * unplugged.  Questionable feature, but we can't just drop it.
11914bafc54SMarkus Armbruster  * Device models call blockdev_mark_auto_del() to schedule the
12014bafc54SMarkus Armbruster  * automatic deletion, and generic qdev code calls blockdev_auto_del()
12114bafc54SMarkus Armbruster  * when deletion is actually safe.
12214bafc54SMarkus Armbruster  */
1234be74634SMarkus Armbruster void blockdev_mark_auto_del(BlockBackend *blk)
12414bafc54SMarkus Armbruster {
12518e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
1264be74634SMarkus Armbruster     BlockDriverState *bs = blk_bs(blk);
12791fddb0dSStefan Hajnoczi     AioContext *aio_context;
12814bafc54SMarkus Armbruster 
12926f8b3a8SMarkus Armbruster     if (!dinfo) {
1302d246f01SKevin Wolf         return;
1312d246f01SKevin Wolf     }
1322d246f01SKevin Wolf 
1335433c24fSMax Reitz     if (bs) {
13491fddb0dSStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
13591fddb0dSStefan Hajnoczi         aio_context_acquire(aio_context);
13691fddb0dSStefan Hajnoczi 
13712bde0eeSPaolo Bonzini         if (bs->job) {
13812bde0eeSPaolo Bonzini             block_job_cancel(bs->job);
13912bde0eeSPaolo Bonzini         }
14091fddb0dSStefan Hajnoczi 
14191fddb0dSStefan Hajnoczi         aio_context_release(aio_context);
1425433c24fSMax Reitz     }
14391fddb0dSStefan Hajnoczi 
14414bafc54SMarkus Armbruster     dinfo->auto_del = 1;
14514bafc54SMarkus Armbruster }
14614bafc54SMarkus Armbruster 
1474be74634SMarkus Armbruster void blockdev_auto_del(BlockBackend *blk)
14814bafc54SMarkus Armbruster {
14918e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
15014bafc54SMarkus Armbruster 
1510fc0f1faSRyan Harper     if (dinfo && dinfo->auto_del) {
152efaa7c4eSMax Reitz         monitor_remove_blk(blk);
153b9fe8a7aSMarkus Armbruster         blk_unref(blk);
15414bafc54SMarkus Armbruster     }
15514bafc54SMarkus Armbruster }
15614bafc54SMarkus Armbruster 
157d8f94e1bSJohn Snow /**
158d8f94e1bSJohn Snow  * Returns the current mapping of how many units per bus
159d8f94e1bSJohn Snow  * a particular interface can support.
160d8f94e1bSJohn Snow  *
161d8f94e1bSJohn Snow  *  A positive integer indicates n units per bus.
162d8f94e1bSJohn Snow  *  0 implies the mapping has not been established.
163d8f94e1bSJohn Snow  * -1 indicates an invalid BlockInterfaceType was given.
164d8f94e1bSJohn Snow  */
165d8f94e1bSJohn Snow int drive_get_max_devs(BlockInterfaceType type)
166d8f94e1bSJohn Snow {
167d8f94e1bSJohn Snow     if (type >= IF_IDE && type < IF_COUNT) {
168d8f94e1bSJohn Snow         return if_max_devs[type];
169d8f94e1bSJohn Snow     }
170d8f94e1bSJohn Snow 
171d8f94e1bSJohn Snow     return -1;
172d8f94e1bSJohn Snow }
173d8f94e1bSJohn Snow 
174505a7fb1SMarkus Armbruster static int drive_index_to_bus_id(BlockInterfaceType type, int index)
175505a7fb1SMarkus Armbruster {
176505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
177505a7fb1SMarkus Armbruster     return max_devs ? index / max_devs : 0;
178505a7fb1SMarkus Armbruster }
179505a7fb1SMarkus Armbruster 
180505a7fb1SMarkus Armbruster static int drive_index_to_unit_id(BlockInterfaceType type, int index)
181505a7fb1SMarkus Armbruster {
182505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
183505a7fb1SMarkus Armbruster     return max_devs ? index % max_devs : index;
184505a7fb1SMarkus Armbruster }
185505a7fb1SMarkus Armbruster 
1862292ddaeSMarkus Armbruster QemuOpts *drive_def(const char *optstr)
1872292ddaeSMarkus Armbruster {
18870b94331SMarkus Armbruster     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
1892292ddaeSMarkus Armbruster }
1902292ddaeSMarkus Armbruster 
1912292ddaeSMarkus Armbruster QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
1925645b0f4SMarkus Armbruster                     const char *optstr)
193666daa68SMarkus Armbruster {
194666daa68SMarkus Armbruster     QemuOpts *opts;
195666daa68SMarkus Armbruster 
1962292ddaeSMarkus Armbruster     opts = drive_def(optstr);
197666daa68SMarkus Armbruster     if (!opts) {
198666daa68SMarkus Armbruster         return NULL;
199666daa68SMarkus Armbruster     }
2002292ddaeSMarkus Armbruster     if (type != IF_DEFAULT) {
201f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "if", if_name[type], &error_abort);
2022292ddaeSMarkus Armbruster     }
2032292ddaeSMarkus Armbruster     if (index >= 0) {
204a8b18f8fSMarkus Armbruster         qemu_opt_set_number(opts, "index", index, &error_abort);
2052292ddaeSMarkus Armbruster     }
206666daa68SMarkus Armbruster     if (file)
207f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "file", file, &error_abort);
208666daa68SMarkus Armbruster     return opts;
209666daa68SMarkus Armbruster }
210666daa68SMarkus Armbruster 
211666daa68SMarkus Armbruster DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
212666daa68SMarkus Armbruster {
21318e46a03SMarkus Armbruster     BlockBackend *blk;
214666daa68SMarkus Armbruster     DriveInfo *dinfo;
215666daa68SMarkus Armbruster 
21618e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
21718e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
21818e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type
21918e46a03SMarkus Armbruster             && dinfo->bus == bus && dinfo->unit == unit) {
220666daa68SMarkus Armbruster             return dinfo;
221666daa68SMarkus Armbruster         }
22218e46a03SMarkus Armbruster     }
223666daa68SMarkus Armbruster 
224666daa68SMarkus Armbruster     return NULL;
225666daa68SMarkus Armbruster }
226666daa68SMarkus Armbruster 
227a66c9dc7SJohn Snow bool drive_check_orphaned(void)
228a66c9dc7SJohn Snow {
22918e46a03SMarkus Armbruster     BlockBackend *blk;
230a66c9dc7SJohn Snow     DriveInfo *dinfo;
231a66c9dc7SJohn Snow     bool rs = false;
232a66c9dc7SJohn Snow 
23318e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
23418e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
235a66c9dc7SJohn Snow         /* If dinfo->bdrv->dev is NULL, it has no device attached. */
236a66c9dc7SJohn Snow         /* Unless this is a default drive, this may be an oversight. */
237a7f53e26SMarkus Armbruster         if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
238a66c9dc7SJohn Snow             dinfo->type != IF_NONE) {
239a66c9dc7SJohn Snow             fprintf(stderr, "Warning: Orphaned drive without device: "
240a66c9dc7SJohn Snow                     "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
2415433c24fSMax Reitz                     blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
2425433c24fSMax Reitz                     if_name[dinfo->type], dinfo->bus, dinfo->unit);
243a66c9dc7SJohn Snow             rs = true;
244a66c9dc7SJohn Snow         }
245a66c9dc7SJohn Snow     }
246a66c9dc7SJohn Snow 
247a66c9dc7SJohn Snow     return rs;
248a66c9dc7SJohn Snow }
249a66c9dc7SJohn Snow 
250f1bd51acSMarkus Armbruster DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
251f1bd51acSMarkus Armbruster {
252f1bd51acSMarkus Armbruster     return drive_get(type,
253f1bd51acSMarkus Armbruster                      drive_index_to_bus_id(type, index),
254f1bd51acSMarkus Armbruster                      drive_index_to_unit_id(type, index));
255f1bd51acSMarkus Armbruster }
256f1bd51acSMarkus Armbruster 
257666daa68SMarkus Armbruster int drive_get_max_bus(BlockInterfaceType type)
258666daa68SMarkus Armbruster {
259666daa68SMarkus Armbruster     int max_bus;
26018e46a03SMarkus Armbruster     BlockBackend *blk;
261666daa68SMarkus Armbruster     DriveInfo *dinfo;
262666daa68SMarkus Armbruster 
263666daa68SMarkus Armbruster     max_bus = -1;
26418e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
26518e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
26618e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
267666daa68SMarkus Armbruster             max_bus = dinfo->bus;
268666daa68SMarkus Armbruster         }
26918e46a03SMarkus Armbruster     }
270666daa68SMarkus Armbruster     return max_bus;
271666daa68SMarkus Armbruster }
272666daa68SMarkus Armbruster 
27313839974SMarkus Armbruster /* Get a block device.  This should only be used for single-drive devices
27413839974SMarkus Armbruster    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
27513839974SMarkus Armbruster    appropriate bus.  */
27613839974SMarkus Armbruster DriveInfo *drive_get_next(BlockInterfaceType type)
27713839974SMarkus Armbruster {
27813839974SMarkus Armbruster     static int next_block_unit[IF_COUNT];
27913839974SMarkus Armbruster 
28013839974SMarkus Armbruster     return drive_get(type, 0, next_block_unit[type]++);
28113839974SMarkus Armbruster }
28213839974SMarkus Armbruster 
283666daa68SMarkus Armbruster static void bdrv_format_print(void *opaque, const char *name)
284666daa68SMarkus Armbruster {
285807105a7SMarkus Armbruster     error_printf(" %s", name);
286666daa68SMarkus Armbruster }
287666daa68SMarkus Armbruster 
288aa398a5cSStefan Hajnoczi typedef struct {
289aa398a5cSStefan Hajnoczi     QEMUBH *bh;
290fa510ebfSFam Zheng     BlockDriverState *bs;
291fa510ebfSFam Zheng } BDRVPutRefBH;
292aa398a5cSStefan Hajnoczi 
293b681072dSKevin Wolf static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
294666daa68SMarkus Armbruster {
295666daa68SMarkus Armbruster     if (!strcmp(buf, "ignore")) {
29692aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_IGNORE;
297666daa68SMarkus Armbruster     } else if (!is_read && !strcmp(buf, "enospc")) {
29892aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_ENOSPC;
299666daa68SMarkus Armbruster     } else if (!strcmp(buf, "stop")) {
30092aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_STOP;
301666daa68SMarkus Armbruster     } else if (!strcmp(buf, "report")) {
30292aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_REPORT;
303666daa68SMarkus Armbruster     } else {
304b681072dSKevin Wolf         error_setg(errp, "'%s' invalid %s error action",
305666daa68SMarkus Armbruster                    buf, is_read ? "read" : "write");
306666daa68SMarkus Armbruster         return -1;
307666daa68SMarkus Armbruster     }
308666daa68SMarkus Armbruster }
309666daa68SMarkus Armbruster 
31040119effSAlberto Garcia static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
31140119effSAlberto Garcia                                   Error **errp)
31240119effSAlberto Garcia {
31340119effSAlberto Garcia     const QListEntry *entry;
31440119effSAlberto Garcia     for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
31540119effSAlberto Garcia         switch (qobject_type(entry->value)) {
31640119effSAlberto Garcia 
31740119effSAlberto Garcia         case QTYPE_QSTRING: {
31840119effSAlberto Garcia             unsigned long long length;
31940119effSAlberto Garcia             const char *str = qstring_get_str(qobject_to_qstring(entry->value));
32040119effSAlberto Garcia             if (parse_uint_full(str, &length, 10) == 0 &&
32140119effSAlberto Garcia                 length > 0 && length <= UINT_MAX) {
32240119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
32340119effSAlberto Garcia             } else {
32440119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %s", str);
32540119effSAlberto Garcia                 return false;
32640119effSAlberto Garcia             }
32740119effSAlberto Garcia             break;
32840119effSAlberto Garcia         }
32940119effSAlberto Garcia 
33040119effSAlberto Garcia         case QTYPE_QINT: {
33140119effSAlberto Garcia             int64_t length = qint_get_int(qobject_to_qint(entry->value));
33240119effSAlberto Garcia             if (length > 0 && length <= UINT_MAX) {
33340119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
33440119effSAlberto Garcia             } else {
33540119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %" PRId64, length);
33640119effSAlberto Garcia                 return false;
33740119effSAlberto Garcia             }
33840119effSAlberto Garcia             break;
33940119effSAlberto Garcia         }
34040119effSAlberto Garcia 
34140119effSAlberto Garcia         default:
34240119effSAlberto Garcia             error_setg(errp, "The specification of stats-intervals is invalid");
34340119effSAlberto Garcia             return false;
34440119effSAlberto Garcia         }
34540119effSAlberto Garcia     }
34640119effSAlberto Garcia     return true;
34740119effSAlberto Garcia }
34840119effSAlberto Garcia 
34933cb7dc8SKevin Wolf typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
35033cb7dc8SKevin Wolf 
351fbf8175eSMax Reitz /* All parameters but @opts are optional and may be set to NULL. */
352fbf8175eSMax Reitz static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
353fbf8175eSMax Reitz     const char **throttling_group, ThrottleConfig *throttle_cfg,
354fbf8175eSMax Reitz     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
355fbf8175eSMax Reitz {
356fbf8175eSMax Reitz     const char *discard;
357fbf8175eSMax Reitz     Error *local_error = NULL;
358fbf8175eSMax Reitz     const char *aio;
359fbf8175eSMax Reitz 
360fbf8175eSMax Reitz     if (bdrv_flags) {
361fbf8175eSMax Reitz         if (!qemu_opt_get_bool(opts, "read-only", false)) {
362fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_RDWR;
363fbf8175eSMax Reitz         }
364fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
365fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_COPY_ON_READ;
366fbf8175eSMax Reitz         }
367fbf8175eSMax Reitz 
368fbf8175eSMax Reitz         if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
369fbf8175eSMax Reitz             if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
370fbf8175eSMax Reitz                 error_setg(errp, "Invalid discard option");
371fbf8175eSMax Reitz                 return;
372fbf8175eSMax Reitz             }
373fbf8175eSMax Reitz         }
374fbf8175eSMax Reitz 
375fbf8175eSMax Reitz         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
376fbf8175eSMax Reitz             if (!strcmp(aio, "native")) {
377fbf8175eSMax Reitz                 *bdrv_flags |= BDRV_O_NATIVE_AIO;
378fbf8175eSMax Reitz             } else if (!strcmp(aio, "threads")) {
379fbf8175eSMax Reitz                 /* this is the default */
380fbf8175eSMax Reitz             } else {
381fbf8175eSMax Reitz                error_setg(errp, "invalid aio option");
382fbf8175eSMax Reitz                return;
383fbf8175eSMax Reitz             }
384fbf8175eSMax Reitz         }
385fbf8175eSMax Reitz     }
386fbf8175eSMax Reitz 
387fbf8175eSMax Reitz     /* disk I/O throttling */
388fbf8175eSMax Reitz     if (throttling_group) {
389fbf8175eSMax Reitz         *throttling_group = qemu_opt_get(opts, "throttling.group");
390fbf8175eSMax Reitz     }
391fbf8175eSMax Reitz 
392fbf8175eSMax Reitz     if (throttle_cfg) {
3931588ab5dSAlberto Garcia         throttle_config_init(throttle_cfg);
394fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
395fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total", 0);
396fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
397fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read", 0);
398fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
399fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write", 0);
400fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
401fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total", 0);
402fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
403fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read", 0);
404fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
405fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write", 0);
406fbf8175eSMax Reitz 
407fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
408fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
409fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
410fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
411fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
412fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
413fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
414fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
415fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
416fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
417fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
418fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
419fbf8175eSMax Reitz 
4208a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
4218a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
4228a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length  =
4238a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
4248a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
4258a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
4268a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
4278a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
4288a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
4298a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
4308a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
4318a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
4328a0fc18dSAlberto Garcia 
433fbf8175eSMax Reitz         throttle_cfg->op_size =
434fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-size", 0);
435fbf8175eSMax Reitz 
436d5851089SAlberto Garcia         if (!throttle_is_valid(throttle_cfg, errp)) {
437fbf8175eSMax Reitz             return;
438fbf8175eSMax Reitz         }
439fbf8175eSMax Reitz     }
440fbf8175eSMax Reitz 
441fbf8175eSMax Reitz     if (detect_zeroes) {
442fbf8175eSMax Reitz         *detect_zeroes =
443fbf8175eSMax Reitz             qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
444fbf8175eSMax Reitz                             qemu_opt_get(opts, "detect-zeroes"),
4457fb1cf16SEric Blake                             BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
446fbf8175eSMax Reitz                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
447fbf8175eSMax Reitz                             &local_error);
448fbf8175eSMax Reitz         if (local_error) {
449fbf8175eSMax Reitz             error_propagate(errp, local_error);
450fbf8175eSMax Reitz             return;
451fbf8175eSMax Reitz         }
452fbf8175eSMax Reitz 
453fbf8175eSMax Reitz         if (bdrv_flags &&
454fbf8175eSMax Reitz             *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
455fbf8175eSMax Reitz             !(*bdrv_flags & BDRV_O_UNMAP))
456fbf8175eSMax Reitz         {
457fbf8175eSMax Reitz             error_setg(errp, "setting detect-zeroes to unmap is not allowed "
458fbf8175eSMax Reitz                              "without setting discard operation to unmap");
459fbf8175eSMax Reitz             return;
460fbf8175eSMax Reitz         }
461fbf8175eSMax Reitz     }
462fbf8175eSMax Reitz }
463fbf8175eSMax Reitz 
464f298d071SKevin Wolf /* Takes the ownership of bs_opts */
46518e46a03SMarkus Armbruster static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
466b681072dSKevin Wolf                                    Error **errp)
467666daa68SMarkus Armbruster {
468666daa68SMarkus Armbruster     const char *buf;
469666daa68SMarkus Armbruster     int bdrv_flags = 0;
470666daa68SMarkus Armbruster     int on_read_error, on_write_error;
471362e9299SAlberto Garcia     bool account_invalid, account_failed;
472e4b24b49SKevin Wolf     bool writethrough;
47326f54e9aSMarkus Armbruster     BlockBackend *blk;
474a0f1eab1SMarkus Armbruster     BlockDriverState *bs;
475cc0681c4SBenoît Canet     ThrottleConfig cfg;
476666daa68SMarkus Armbruster     int snapshot = 0;
477c546194fSStefan Hajnoczi     Error *error = NULL;
4780006383eSKevin Wolf     QemuOpts *opts;
47940119effSAlberto Garcia     QDict *interval_dict = NULL;
48040119effSAlberto Garcia     QList *interval_list = NULL;
4810006383eSKevin Wolf     const char *id;
482fbf8175eSMax Reitz     BlockdevDetectZeroesOptions detect_zeroes =
483fbf8175eSMax Reitz         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
484fbf8175eSMax Reitz     const char *throttling_group = NULL;
485666daa68SMarkus Armbruster 
486f298d071SKevin Wolf     /* Check common options by copying from bs_opts to opts, all other options
487f298d071SKevin Wolf      * stay in bs_opts for processing by bdrv_open(). */
488f298d071SKevin Wolf     id = qdict_get_try_str(bs_opts, "id");
4890006383eSKevin Wolf     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
49084d18f06SMarkus Armbruster     if (error) {
491b681072dSKevin Wolf         error_propagate(errp, error);
4926376f952SMarkus Armbruster         goto err_no_opts;
4930006383eSKevin Wolf     }
4940006383eSKevin Wolf 
4950006383eSKevin Wolf     qemu_opts_absorb_qdict(opts, bs_opts, &error);
49684d18f06SMarkus Armbruster     if (error) {
497b681072dSKevin Wolf         error_propagate(errp, error);
498ec9c10d2SStefan Hajnoczi         goto early_err;
4990006383eSKevin Wolf     }
5000006383eSKevin Wolf 
5010006383eSKevin Wolf     if (id) {
5020006383eSKevin Wolf         qdict_del(bs_opts, "id");
5030006383eSKevin Wolf     }
5040006383eSKevin Wolf 
505666daa68SMarkus Armbruster     /* extract parameters */
506666daa68SMarkus Armbruster     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
507666daa68SMarkus Armbruster 
508362e9299SAlberto Garcia     account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
509362e9299SAlberto Garcia     account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
510362e9299SAlberto Garcia 
511e4b24b49SKevin Wolf     writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
512e4b24b49SKevin Wolf 
51340119effSAlberto Garcia     qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
51440119effSAlberto Garcia     qdict_array_split(interval_dict, &interval_list);
51540119effSAlberto Garcia 
51640119effSAlberto Garcia     if (qdict_size(interval_dict) != 0) {
51740119effSAlberto Garcia         error_setg(errp, "Invalid option stats-intervals.%s",
51840119effSAlberto Garcia                    qdict_first(interval_dict)->key);
51940119effSAlberto Garcia         goto early_err;
52040119effSAlberto Garcia     }
5212be5506fSAlberto Garcia 
522fbf8175eSMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
523fbf8175eSMax Reitz                                     &detect_zeroes, &error);
524fbf8175eSMax Reitz     if (error) {
525fbf8175eSMax Reitz         error_propagate(errp, error);
526ec9c10d2SStefan Hajnoczi         goto early_err;
527a9384affSPaolo Bonzini     }
528666daa68SMarkus Armbruster 
529666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
530c8057f95SPeter Maydell         if (is_help_option(buf)) {
531807105a7SMarkus Armbruster             error_printf("Supported formats:");
532666daa68SMarkus Armbruster             bdrv_iterate_format(bdrv_format_print, NULL);
533807105a7SMarkus Armbruster             error_printf("\n");
534ec9c10d2SStefan Hajnoczi             goto early_err;
535666daa68SMarkus Armbruster         }
53674fe54f2SKevin Wolf 
537e4342ce5SMax Reitz         if (qdict_haskey(bs_opts, "driver")) {
538e4342ce5SMax Reitz             error_setg(errp, "Cannot specify both 'driver' and 'format'");
539ec9c10d2SStefan Hajnoczi             goto early_err;
5406db5f5d6SMike Qiu         }
541e4342ce5SMax Reitz         qdict_put(bs_opts, "driver", qstring_from_str(buf));
542666daa68SMarkus Armbruster     }
543666daa68SMarkus Armbruster 
54492aa5c6dSPaolo Bonzini     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
545666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
546b681072dSKevin Wolf         on_write_error = parse_block_error_action(buf, 0, &error);
54784d18f06SMarkus Armbruster         if (error) {
548b681072dSKevin Wolf             error_propagate(errp, error);
549ec9c10d2SStefan Hajnoczi             goto early_err;
550666daa68SMarkus Armbruster         }
551666daa68SMarkus Armbruster     }
552666daa68SMarkus Armbruster 
55392aa5c6dSPaolo Bonzini     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
554666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
555b681072dSKevin Wolf         on_read_error = parse_block_error_action(buf, 1, &error);
55684d18f06SMarkus Armbruster         if (error) {
557b681072dSKevin Wolf             error_propagate(errp, error);
558ec9c10d2SStefan Hajnoczi             goto early_err;
559666daa68SMarkus Armbruster         }
560666daa68SMarkus Armbruster     }
561666daa68SMarkus Armbruster 
562666daa68SMarkus Armbruster     if (snapshot) {
56391a097e7SKevin Wolf         bdrv_flags |= BDRV_O_SNAPSHOT;
564666daa68SMarkus Armbruster     }
565666daa68SMarkus Armbruster 
5665ec18f8cSMax Reitz     /* init */
56739c4ae94SKevin Wolf     if ((!file || !*file) && !qdict_size(bs_opts)) {
5685ec18f8cSMax Reitz         BlockBackendRootState *blk_rs;
5695ec18f8cSMax Reitz 
570efaa7c4eSMax Reitz         blk = blk_new(errp);
5715ec18f8cSMax Reitz         if (!blk) {
5725ec18f8cSMax Reitz             goto early_err;
5735ec18f8cSMax Reitz         }
5745ec18f8cSMax Reitz 
5755ec18f8cSMax Reitz         blk_rs = blk_get_root_state(blk);
5765ec18f8cSMax Reitz         blk_rs->open_flags    = bdrv_flags;
577fbf8175eSMax Reitz         blk_rs->read_only     = !(bdrv_flags & BDRV_O_RDWR);
5785ec18f8cSMax Reitz         blk_rs->detect_zeroes = detect_zeroes;
5795ec18f8cSMax Reitz 
5805ec18f8cSMax Reitz         if (throttle_enabled(&cfg)) {
5815ec18f8cSMax Reitz             if (!throttling_group) {
5825ec18f8cSMax Reitz                 throttling_group = blk_name(blk);
5835ec18f8cSMax Reitz             }
5845ec18f8cSMax Reitz             blk_rs->throttle_group = g_strdup(throttling_group);
5855ec18f8cSMax Reitz             blk_rs->throttle_state = throttle_group_incref(throttling_group);
5865ec18f8cSMax Reitz             blk_rs->throttle_state->cfg = cfg;
5875ec18f8cSMax Reitz         }
5885ec18f8cSMax Reitz 
5895ec18f8cSMax Reitz         QDECREF(bs_opts);
5905ec18f8cSMax Reitz     } else {
5915ec18f8cSMax Reitz         if (file && !*file) {
5925ec18f8cSMax Reitz             file = NULL;
5935ec18f8cSMax Reitz         }
5945ec18f8cSMax Reitz 
59591a097e7SKevin Wolf         /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
59691a097e7SKevin Wolf          * with other callers) rather than what we want as the real defaults.
59791a097e7SKevin Wolf          * Apply the defaults here instead. */
59891a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
59991a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
60072e775c7SKevin Wolf         assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
60191a097e7SKevin Wolf 
60212d5ee3aSKevin Wolf         if (runstate_check(RUN_STATE_INMIGRATE)) {
60312d5ee3aSKevin Wolf             bdrv_flags |= BDRV_O_INACTIVE;
60412d5ee3aSKevin Wolf         }
60512d5ee3aSKevin Wolf 
606efaa7c4eSMax Reitz         blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
607e4342ce5SMax Reitz         if (!blk) {
608e4342ce5SMax Reitz             goto err_no_bs_opts;
609e4342ce5SMax Reitz         }
610e4342ce5SMax Reitz         bs = blk_bs(blk);
6110006383eSKevin Wolf 
612e4342ce5SMax Reitz         bs->detect_zeroes = detect_zeroes;
613e4342ce5SMax Reitz 
614e4342ce5SMax Reitz         /* disk I/O throttling */
615e4342ce5SMax Reitz         if (throttle_enabled(&cfg)) {
61676f4afb4SAlberto Garcia             if (!throttling_group) {
61776f4afb4SAlberto Garcia                 throttling_group = blk_name(blk);
61876f4afb4SAlberto Garcia             }
619*97148076SKevin Wolf             blk_io_limits_enable(blk, throttling_group);
620*97148076SKevin Wolf             blk_set_io_limits(blk, &cfg);
621666daa68SMarkus Armbruster         }
622666daa68SMarkus Armbruster 
623a0f1eab1SMarkus Armbruster         if (bdrv_key_required(bs)) {
624666daa68SMarkus Armbruster             autostart = 0;
625a0f1eab1SMarkus Armbruster         }
626362e9299SAlberto Garcia 
627362e9299SAlberto Garcia         block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
6282be5506fSAlberto Garcia 
62940119effSAlberto Garcia         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
6302be5506fSAlberto Garcia             blk_unref(blk);
6312be5506fSAlberto Garcia             blk = NULL;
6322be5506fSAlberto Garcia             goto err_no_bs_opts;
6332be5506fSAlberto Garcia         }
6342be5506fSAlberto Garcia     }
6355ec18f8cSMax Reitz 
636e4b24b49SKevin Wolf     blk_set_enable_write_cache(blk, !writethrough);
6375ec18f8cSMax Reitz     blk_set_on_error(blk, on_read_error, on_write_error);
6380006383eSKevin Wolf 
639efaa7c4eSMax Reitz     if (!monitor_add_blk(blk, qemu_opts_id(opts), errp)) {
640efaa7c4eSMax Reitz         blk_unref(blk);
641efaa7c4eSMax Reitz         blk = NULL;
642efaa7c4eSMax Reitz         goto err_no_bs_opts;
643efaa7c4eSMax Reitz     }
644efaa7c4eSMax Reitz 
645e4342ce5SMax Reitz err_no_bs_opts:
6460006383eSKevin Wolf     qemu_opts_del(opts);
64740119effSAlberto Garcia     QDECREF(interval_dict);
64840119effSAlberto Garcia     QDECREF(interval_list);
64918e46a03SMarkus Armbruster     return blk;
650a9ae2bffSMarkus Armbruster 
651ec9c10d2SStefan Hajnoczi early_err:
652ec9c10d2SStefan Hajnoczi     qemu_opts_del(opts);
65340119effSAlberto Garcia     QDECREF(interval_dict);
65440119effSAlberto Garcia     QDECREF(interval_list);
6556376f952SMarkus Armbruster err_no_opts:
6566376f952SMarkus Armbruster     QDECREF(bs_opts);
657a9ae2bffSMarkus Armbruster     return NULL;
658666daa68SMarkus Armbruster }
659666daa68SMarkus Armbruster 
660bd745e23SMax Reitz static QemuOptsList qemu_root_bds_opts;
661bd745e23SMax Reitz 
662bd745e23SMax Reitz /* Takes the ownership of bs_opts */
663bd745e23SMax Reitz static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
664bd745e23SMax Reitz {
665bd745e23SMax Reitz     BlockDriverState *bs;
666bd745e23SMax Reitz     QemuOpts *opts;
667bd745e23SMax Reitz     Error *local_error = NULL;
668bd745e23SMax Reitz     BlockdevDetectZeroesOptions detect_zeroes;
669bd745e23SMax Reitz     int ret;
670bd745e23SMax Reitz     int bdrv_flags = 0;
671bd745e23SMax Reitz 
672bd745e23SMax Reitz     opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
673bd745e23SMax Reitz     if (!opts) {
674bd745e23SMax Reitz         goto fail;
675bd745e23SMax Reitz     }
676bd745e23SMax Reitz 
677bd745e23SMax Reitz     qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
678bd745e23SMax Reitz     if (local_error) {
679bd745e23SMax Reitz         error_propagate(errp, local_error);
680bd745e23SMax Reitz         goto fail;
681bd745e23SMax Reitz     }
682bd745e23SMax Reitz 
683bd745e23SMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
684bd745e23SMax Reitz                                     &detect_zeroes, &local_error);
685bd745e23SMax Reitz     if (local_error) {
686bd745e23SMax Reitz         error_propagate(errp, local_error);
687bd745e23SMax Reitz         goto fail;
688bd745e23SMax Reitz     }
689bd745e23SMax Reitz 
690a81d6164SKevin Wolf     /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
691a81d6164SKevin Wolf      * with other callers) rather than what we want as the real defaults.
692a81d6164SKevin Wolf      * Apply the defaults here instead. */
693a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
694a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
695a81d6164SKevin Wolf 
69612d5ee3aSKevin Wolf     if (runstate_check(RUN_STATE_INMIGRATE)) {
69712d5ee3aSKevin Wolf         bdrv_flags |= BDRV_O_INACTIVE;
69812d5ee3aSKevin Wolf     }
69912d5ee3aSKevin Wolf 
700bd745e23SMax Reitz     bs = NULL;
701bd745e23SMax Reitz     ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
702bd745e23SMax Reitz     if (ret < 0) {
703bd745e23SMax Reitz         goto fail_no_bs_opts;
704bd745e23SMax Reitz     }
705bd745e23SMax Reitz 
706bd745e23SMax Reitz     bs->detect_zeroes = detect_zeroes;
707bd745e23SMax Reitz 
708bd745e23SMax Reitz fail_no_bs_opts:
709bd745e23SMax Reitz     qemu_opts_del(opts);
710bd745e23SMax Reitz     return bs;
711bd745e23SMax Reitz 
712bd745e23SMax Reitz fail:
713bd745e23SMax Reitz     qemu_opts_del(opts);
714bd745e23SMax Reitz     QDECREF(bs_opts);
715bd745e23SMax Reitz     return NULL;
716bd745e23SMax Reitz }
717bd745e23SMax Reitz 
7189c4218e9SMax Reitz void blockdev_close_all_bdrv_states(void)
7199c4218e9SMax Reitz {
7209c4218e9SMax Reitz     BlockDriverState *bs, *next_bs;
7219c4218e9SMax Reitz 
7229c4218e9SMax Reitz     QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
7239c4218e9SMax Reitz         AioContext *ctx = bdrv_get_aio_context(bs);
7249c4218e9SMax Reitz 
7259c4218e9SMax Reitz         aio_context_acquire(ctx);
7269c4218e9SMax Reitz         bdrv_unref(bs);
7279c4218e9SMax Reitz         aio_context_release(ctx);
7289c4218e9SMax Reitz     }
7299c4218e9SMax Reitz }
7309c4218e9SMax Reitz 
731262b4e8fSMax Reitz /* Iterates over the list of monitor-owned BlockDriverStates */
732262b4e8fSMax Reitz BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
733262b4e8fSMax Reitz {
734262b4e8fSMax Reitz     return bs ? QTAILQ_NEXT(bs, monitor_list)
735262b4e8fSMax Reitz               : QTAILQ_FIRST(&monitor_bdrv_states);
736262b4e8fSMax Reitz }
737262b4e8fSMax Reitz 
7385abbf0eeSKevin Wolf static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
7395abbf0eeSKevin Wolf                             Error **errp)
74057975222SKevin Wolf {
74157975222SKevin Wolf     const char *value;
74257975222SKevin Wolf 
74357975222SKevin Wolf     value = qemu_opt_get(opts, from);
74457975222SKevin Wolf     if (value) {
7455abbf0eeSKevin Wolf         if (qemu_opt_find(opts, to)) {
7465abbf0eeSKevin Wolf             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
7475abbf0eeSKevin Wolf                        "same time", to, from);
7485abbf0eeSKevin Wolf             return;
7495abbf0eeSKevin Wolf         }
75020d6cd47SJun Li     }
75120d6cd47SJun Li 
75220d6cd47SJun Li     /* rename all items in opts */
75320d6cd47SJun Li     while ((value = qemu_opt_get(opts, from))) {
754f43e47dbSMarkus Armbruster         qemu_opt_set(opts, to, value, &error_abort);
75557975222SKevin Wolf         qemu_opt_unset(opts, from);
75657975222SKevin Wolf     }
75757975222SKevin Wolf }
75857975222SKevin Wolf 
75933cb7dc8SKevin Wolf QemuOptsList qemu_legacy_drive_opts = {
76033cb7dc8SKevin Wolf     .name = "drive",
76133cb7dc8SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
76233cb7dc8SKevin Wolf     .desc = {
76333cb7dc8SKevin Wolf         {
76487a899c5SKevin Wolf             .name = "bus",
76587a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
76687a899c5SKevin Wolf             .help = "bus number",
76787a899c5SKevin Wolf         },{
76887a899c5SKevin Wolf             .name = "unit",
76987a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
77087a899c5SKevin Wolf             .help = "unit number (i.e. lun for scsi)",
77187a899c5SKevin Wolf         },{
77287a899c5SKevin Wolf             .name = "index",
77387a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
77487a899c5SKevin Wolf             .help = "index number",
77587a899c5SKevin Wolf         },{
77633cb7dc8SKevin Wolf             .name = "media",
77733cb7dc8SKevin Wolf             .type = QEMU_OPT_STRING,
77833cb7dc8SKevin Wolf             .help = "media type (disk, cdrom)",
779593d464bSKevin Wolf         },{
780593d464bSKevin Wolf             .name = "if",
781593d464bSKevin Wolf             .type = QEMU_OPT_STRING,
782593d464bSKevin Wolf             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
783b41a7338SKevin Wolf         },{
784b41a7338SKevin Wolf             .name = "cyls",
785b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
786b41a7338SKevin Wolf             .help = "number of cylinders (ide disk geometry)",
787b41a7338SKevin Wolf         },{
788b41a7338SKevin Wolf             .name = "heads",
789b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
790b41a7338SKevin Wolf             .help = "number of heads (ide disk geometry)",
791b41a7338SKevin Wolf         },{
792b41a7338SKevin Wolf             .name = "secs",
793b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
794b41a7338SKevin Wolf             .help = "number of sectors (ide disk geometry)",
795b41a7338SKevin Wolf         },{
796b41a7338SKevin Wolf             .name = "trans",
797b41a7338SKevin Wolf             .type = QEMU_OPT_STRING,
798b41a7338SKevin Wolf             .help = "chs translation (auto, lba, none)",
79926929298SKevin Wolf         },{
80026929298SKevin Wolf             .name = "boot",
80126929298SKevin Wolf             .type = QEMU_OPT_BOOL,
80226929298SKevin Wolf             .help = "(deprecated, ignored)",
803394c7d4dSKevin Wolf         },{
804394c7d4dSKevin Wolf             .name = "addr",
805394c7d4dSKevin Wolf             .type = QEMU_OPT_STRING,
806394c7d4dSKevin Wolf             .help = "pci address (virtio only)",
807d095b465SMax Reitz         },{
808bcf83158SKevin Wolf             .name = "serial",
809bcf83158SKevin Wolf             .type = QEMU_OPT_STRING,
810bcf83158SKevin Wolf             .help = "disk serial number",
811bcf83158SKevin Wolf         },{
812d095b465SMax Reitz             .name = "file",
813d095b465SMax Reitz             .type = QEMU_OPT_STRING,
814d095b465SMax Reitz             .help = "file name",
81533cb7dc8SKevin Wolf         },
8160ebd24e0SKevin Wolf 
8170ebd24e0SKevin Wolf         /* Options that are passed on, but have special semantics with -drive */
8180ebd24e0SKevin Wolf         {
8190ebd24e0SKevin Wolf             .name = "read-only",
8200ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
8210ebd24e0SKevin Wolf             .help = "open drive file as read-only",
8220ebd24e0SKevin Wolf         },{
823ee13ed1cSKevin Wolf             .name = "rerror",
824ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
825ee13ed1cSKevin Wolf             .help = "read error action",
826ee13ed1cSKevin Wolf         },{
827ee13ed1cSKevin Wolf             .name = "werror",
828ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
829ee13ed1cSKevin Wolf             .help = "write error action",
830ee13ed1cSKevin Wolf         },{
8310ebd24e0SKevin Wolf             .name = "copy-on-read",
8320ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
8330ebd24e0SKevin Wolf             .help = "copy read data from backing file into image file",
8340ebd24e0SKevin Wolf         },
8350ebd24e0SKevin Wolf 
83633cb7dc8SKevin Wolf         { /* end of list */ }
83733cb7dc8SKevin Wolf     },
83833cb7dc8SKevin Wolf };
83933cb7dc8SKevin Wolf 
84060e19e06SMarkus Armbruster DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
84157975222SKevin Wolf {
84229c4e2b5SKevin Wolf     const char *value;
84318e46a03SMarkus Armbruster     BlockBackend *blk;
84433cb7dc8SKevin Wolf     DriveInfo *dinfo = NULL;
845f298d071SKevin Wolf     QDict *bs_opts;
84633cb7dc8SKevin Wolf     QemuOpts *legacy_opts;
84733cb7dc8SKevin Wolf     DriveMediaType media = MEDIA_DISK;
848593d464bSKevin Wolf     BlockInterfaceType type;
849b41a7338SKevin Wolf     int cyls, heads, secs, translation;
85087a899c5SKevin Wolf     int max_devs, bus_id, unit_id, index;
851394c7d4dSKevin Wolf     const char *devaddr;
852ee13ed1cSKevin Wolf     const char *werror, *rerror;
853a7fdbcf0SFam Zheng     bool read_only = false;
854a7fdbcf0SFam Zheng     bool copy_on_read;
855bcf83158SKevin Wolf     const char *serial;
856d095b465SMax Reitz     const char *filename;
85733cb7dc8SKevin Wolf     Error *local_err = NULL;
858247147fbSKevin Wolf     int i;
85929c4e2b5SKevin Wolf 
86057975222SKevin Wolf     /* Change legacy command line options into QMP ones */
861247147fbSKevin Wolf     static const struct {
862247147fbSKevin Wolf         const char *from;
863247147fbSKevin Wolf         const char *to;
864247147fbSKevin Wolf     } opt_renames[] = {
865247147fbSKevin Wolf         { "iops",           "throttling.iops-total" },
866247147fbSKevin Wolf         { "iops_rd",        "throttling.iops-read" },
867247147fbSKevin Wolf         { "iops_wr",        "throttling.iops-write" },
86857975222SKevin Wolf 
869247147fbSKevin Wolf         { "bps",            "throttling.bps-total" },
870247147fbSKevin Wolf         { "bps_rd",         "throttling.bps-read" },
871247147fbSKevin Wolf         { "bps_wr",         "throttling.bps-write" },
87257975222SKevin Wolf 
873247147fbSKevin Wolf         { "iops_max",       "throttling.iops-total-max" },
874247147fbSKevin Wolf         { "iops_rd_max",    "throttling.iops-read-max" },
875247147fbSKevin Wolf         { "iops_wr_max",    "throttling.iops-write-max" },
8763e9fab69SBenoît Canet 
877247147fbSKevin Wolf         { "bps_max",        "throttling.bps-total-max" },
878247147fbSKevin Wolf         { "bps_rd_max",     "throttling.bps-read-max" },
879247147fbSKevin Wolf         { "bps_wr_max",     "throttling.bps-write-max" },
8803e9fab69SBenoît Canet 
881247147fbSKevin Wolf         { "iops_size",      "throttling.iops-size" },
8822024c1dfSBenoît Canet 
88376f4afb4SAlberto Garcia         { "group",          "throttling.group" },
88476f4afb4SAlberto Garcia 
885247147fbSKevin Wolf         { "readonly",       "read-only" },
886247147fbSKevin Wolf     };
887247147fbSKevin Wolf 
888247147fbSKevin Wolf     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
8895abbf0eeSKevin Wolf         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
8905abbf0eeSKevin Wolf                         &local_err);
8915abbf0eeSKevin Wolf         if (local_err) {
892565f65d2SMarkus Armbruster             error_report_err(local_err);
8935abbf0eeSKevin Wolf             return NULL;
8945abbf0eeSKevin Wolf         }
895247147fbSKevin Wolf     }
8960f227a94SKevin Wolf 
89729c4e2b5SKevin Wolf     value = qemu_opt_get(all_opts, "cache");
89829c4e2b5SKevin Wolf     if (value) {
89929c4e2b5SKevin Wolf         int flags = 0;
90004feb4a5SKevin Wolf         bool writethrough;
90129c4e2b5SKevin Wolf 
90204feb4a5SKevin Wolf         if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
90329c4e2b5SKevin Wolf             error_report("invalid cache option");
90429c4e2b5SKevin Wolf             return NULL;
90529c4e2b5SKevin Wolf         }
90629c4e2b5SKevin Wolf 
90729c4e2b5SKevin Wolf         /* Specific options take precedence */
90854861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
90954861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
91004feb4a5SKevin Wolf                               !writethrough, &error_abort);
91129c4e2b5SKevin Wolf         }
91254861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
91354861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
914cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NOCACHE), &error_abort);
91529c4e2b5SKevin Wolf         }
91654861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
91754861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
918cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
91929c4e2b5SKevin Wolf         }
92029c4e2b5SKevin Wolf         qemu_opt_unset(all_opts, "cache");
92129c4e2b5SKevin Wolf     }
92229c4e2b5SKevin Wolf 
923f298d071SKevin Wolf     /* Get a QDict for processing the options */
924f298d071SKevin Wolf     bs_opts = qdict_new();
925f298d071SKevin Wolf     qemu_opts_to_qdict(all_opts, bs_opts);
926f298d071SKevin Wolf 
92787ea75d5SPeter Crosthwaite     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
92887ea75d5SPeter Crosthwaite                                    &error_abort);
92933cb7dc8SKevin Wolf     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
93084d18f06SMarkus Armbruster     if (local_err) {
931565f65d2SMarkus Armbruster         error_report_err(local_err);
93233cb7dc8SKevin Wolf         goto fail;
93333cb7dc8SKevin Wolf     }
93433cb7dc8SKevin Wolf 
93526929298SKevin Wolf     /* Deprecated option boot=[on|off] */
93626929298SKevin Wolf     if (qemu_opt_get(legacy_opts, "boot") != NULL) {
93726929298SKevin Wolf         fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
93826929298SKevin Wolf                 "ignored. Future versions will reject this parameter. Please "
93926929298SKevin Wolf                 "update your scripts.\n");
94026929298SKevin Wolf     }
94126929298SKevin Wolf 
94233cb7dc8SKevin Wolf     /* Media type */
94333cb7dc8SKevin Wolf     value = qemu_opt_get(legacy_opts, "media");
94433cb7dc8SKevin Wolf     if (value) {
94533cb7dc8SKevin Wolf         if (!strcmp(value, "disk")) {
94633cb7dc8SKevin Wolf             media = MEDIA_DISK;
94733cb7dc8SKevin Wolf         } else if (!strcmp(value, "cdrom")) {
94833cb7dc8SKevin Wolf             media = MEDIA_CDROM;
949a7fdbcf0SFam Zheng             read_only = true;
95033cb7dc8SKevin Wolf         } else {
95133cb7dc8SKevin Wolf             error_report("'%s' invalid media", value);
95233cb7dc8SKevin Wolf             goto fail;
95333cb7dc8SKevin Wolf         }
95433cb7dc8SKevin Wolf     }
95533cb7dc8SKevin Wolf 
9560ebd24e0SKevin Wolf     /* copy-on-read is disabled with a warning for read-only devices */
957a7fdbcf0SFam Zheng     read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
9580ebd24e0SKevin Wolf     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
9590ebd24e0SKevin Wolf 
9600ebd24e0SKevin Wolf     if (read_only && copy_on_read) {
9610ebd24e0SKevin Wolf         error_report("warning: disabling copy-on-read on read-only drive");
9620ebd24e0SKevin Wolf         copy_on_read = false;
9630ebd24e0SKevin Wolf     }
9640ebd24e0SKevin Wolf 
9650ebd24e0SKevin Wolf     qdict_put(bs_opts, "read-only",
9660ebd24e0SKevin Wolf               qstring_from_str(read_only ? "on" : "off"));
9670ebd24e0SKevin Wolf     qdict_put(bs_opts, "copy-on-read",
9680ebd24e0SKevin Wolf               qstring_from_str(copy_on_read ? "on" :"off"));
9690ebd24e0SKevin Wolf 
970593d464bSKevin Wolf     /* Controller type */
971593d464bSKevin Wolf     value = qemu_opt_get(legacy_opts, "if");
972593d464bSKevin Wolf     if (value) {
973593d464bSKevin Wolf         for (type = 0;
974593d464bSKevin Wolf              type < IF_COUNT && strcmp(value, if_name[type]);
975593d464bSKevin Wolf              type++) {
976593d464bSKevin Wolf         }
977593d464bSKevin Wolf         if (type == IF_COUNT) {
978593d464bSKevin Wolf             error_report("unsupported bus type '%s'", value);
979593d464bSKevin Wolf             goto fail;
980593d464bSKevin Wolf         }
981593d464bSKevin Wolf     } else {
982593d464bSKevin Wolf         type = block_default_type;
983593d464bSKevin Wolf     }
984593d464bSKevin Wolf 
985b41a7338SKevin Wolf     /* Geometry */
986b41a7338SKevin Wolf     cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
987b41a7338SKevin Wolf     heads = qemu_opt_get_number(legacy_opts, "heads", 0);
988b41a7338SKevin Wolf     secs  = qemu_opt_get_number(legacy_opts, "secs", 0);
989b41a7338SKevin Wolf 
990b41a7338SKevin Wolf     if (cyls || heads || secs) {
991b41a7338SKevin Wolf         if (cyls < 1) {
992b41a7338SKevin Wolf             error_report("invalid physical cyls number");
993b41a7338SKevin Wolf             goto fail;
994b41a7338SKevin Wolf         }
995b41a7338SKevin Wolf         if (heads < 1) {
996b41a7338SKevin Wolf             error_report("invalid physical heads number");
997b41a7338SKevin Wolf             goto fail;
998b41a7338SKevin Wolf         }
999b41a7338SKevin Wolf         if (secs < 1) {
1000b41a7338SKevin Wolf             error_report("invalid physical secs number");
1001b41a7338SKevin Wolf             goto fail;
1002b41a7338SKevin Wolf         }
1003b41a7338SKevin Wolf     }
1004b41a7338SKevin Wolf 
1005b41a7338SKevin Wolf     translation = BIOS_ATA_TRANSLATION_AUTO;
1006b41a7338SKevin Wolf     value = qemu_opt_get(legacy_opts, "trans");
1007b41a7338SKevin Wolf     if (value != NULL) {
1008b41a7338SKevin Wolf         if (!cyls) {
1009b41a7338SKevin Wolf             error_report("'%s' trans must be used with cyls, heads and secs",
1010b41a7338SKevin Wolf                          value);
1011b41a7338SKevin Wolf             goto fail;
1012b41a7338SKevin Wolf         }
1013b41a7338SKevin Wolf         if (!strcmp(value, "none")) {
1014b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_NONE;
1015b41a7338SKevin Wolf         } else if (!strcmp(value, "lba")) {
1016b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_LBA;
1017f31c41ffSPaolo Bonzini         } else if (!strcmp(value, "large")) {
1018f31c41ffSPaolo Bonzini             translation = BIOS_ATA_TRANSLATION_LARGE;
1019f31c41ffSPaolo Bonzini         } else if (!strcmp(value, "rechs")) {
1020f31c41ffSPaolo Bonzini             translation = BIOS_ATA_TRANSLATION_RECHS;
1021b41a7338SKevin Wolf         } else if (!strcmp(value, "auto")) {
1022b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_AUTO;
1023b41a7338SKevin Wolf         } else {
1024b41a7338SKevin Wolf             error_report("'%s' invalid translation type", value);
1025b41a7338SKevin Wolf             goto fail;
1026b41a7338SKevin Wolf         }
1027b41a7338SKevin Wolf     }
1028b41a7338SKevin Wolf 
1029b41a7338SKevin Wolf     if (media == MEDIA_CDROM) {
1030b41a7338SKevin Wolf         if (cyls || secs || heads) {
1031b41a7338SKevin Wolf             error_report("CHS can't be set with media=cdrom");
1032b41a7338SKevin Wolf             goto fail;
1033b41a7338SKevin Wolf         }
1034b41a7338SKevin Wolf     }
1035b41a7338SKevin Wolf 
103687a899c5SKevin Wolf     /* Device address specified by bus/unit or index.
103787a899c5SKevin Wolf      * If none was specified, try to find the first free one. */
103887a899c5SKevin Wolf     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
103987a899c5SKevin Wolf     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
104087a899c5SKevin Wolf     index   = qemu_opt_get_number(legacy_opts, "index", -1);
104187a899c5SKevin Wolf 
104287a899c5SKevin Wolf     max_devs = if_max_devs[type];
104387a899c5SKevin Wolf 
104487a899c5SKevin Wolf     if (index != -1) {
104587a899c5SKevin Wolf         if (bus_id != 0 || unit_id != -1) {
104687a899c5SKevin Wolf             error_report("index cannot be used with bus and unit");
104787a899c5SKevin Wolf             goto fail;
104887a899c5SKevin Wolf         }
104987a899c5SKevin Wolf         bus_id = drive_index_to_bus_id(type, index);
105087a899c5SKevin Wolf         unit_id = drive_index_to_unit_id(type, index);
105187a899c5SKevin Wolf     }
105287a899c5SKevin Wolf 
105387a899c5SKevin Wolf     if (unit_id == -1) {
105487a899c5SKevin Wolf        unit_id = 0;
105587a899c5SKevin Wolf        while (drive_get(type, bus_id, unit_id) != NULL) {
105687a899c5SKevin Wolf            unit_id++;
105787a899c5SKevin Wolf            if (max_devs && unit_id >= max_devs) {
105887a899c5SKevin Wolf                unit_id -= max_devs;
105987a899c5SKevin Wolf                bus_id++;
106087a899c5SKevin Wolf            }
106187a899c5SKevin Wolf        }
106287a899c5SKevin Wolf     }
106387a899c5SKevin Wolf 
106487a899c5SKevin Wolf     if (max_devs && unit_id >= max_devs) {
106587a899c5SKevin Wolf         error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
106687a899c5SKevin Wolf         goto fail;
106787a899c5SKevin Wolf     }
106887a899c5SKevin Wolf 
106987a899c5SKevin Wolf     if (drive_get(type, bus_id, unit_id) != NULL) {
107087a899c5SKevin Wolf         error_report("drive with bus=%d, unit=%d (index=%d) exists",
107187a899c5SKevin Wolf                      bus_id, unit_id, index);
107287a899c5SKevin Wolf         goto fail;
107387a899c5SKevin Wolf     }
107487a899c5SKevin Wolf 
1075bcf83158SKevin Wolf     /* Serial number */
1076bcf83158SKevin Wolf     serial = qemu_opt_get(legacy_opts, "serial");
1077bcf83158SKevin Wolf 
107887a899c5SKevin Wolf     /* no id supplied -> create one */
107987a899c5SKevin Wolf     if (qemu_opts_id(all_opts) == NULL) {
108087a899c5SKevin Wolf         char *new_id;
108187a899c5SKevin Wolf         const char *mediastr = "";
108287a899c5SKevin Wolf         if (type == IF_IDE || type == IF_SCSI) {
108387a899c5SKevin Wolf             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
108487a899c5SKevin Wolf         }
108587a899c5SKevin Wolf         if (max_devs) {
108687a899c5SKevin Wolf             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
108787a899c5SKevin Wolf                                      mediastr, unit_id);
108887a899c5SKevin Wolf         } else {
108987a899c5SKevin Wolf             new_id = g_strdup_printf("%s%s%i", if_name[type],
109087a899c5SKevin Wolf                                      mediastr, unit_id);
109187a899c5SKevin Wolf         }
109287a899c5SKevin Wolf         qdict_put(bs_opts, "id", qstring_from_str(new_id));
109387a899c5SKevin Wolf         g_free(new_id);
109487a899c5SKevin Wolf     }
109587a899c5SKevin Wolf 
1096394c7d4dSKevin Wolf     /* Add virtio block device */
1097394c7d4dSKevin Wolf     devaddr = qemu_opt_get(legacy_opts, "addr");
1098394c7d4dSKevin Wolf     if (devaddr && type != IF_VIRTIO) {
1099394c7d4dSKevin Wolf         error_report("addr is not supported by this bus type");
1100394c7d4dSKevin Wolf         goto fail;
1101394c7d4dSKevin Wolf     }
1102394c7d4dSKevin Wolf 
1103394c7d4dSKevin Wolf     if (type == IF_VIRTIO) {
1104394c7d4dSKevin Wolf         QemuOpts *devopts;
110587ea75d5SPeter Crosthwaite         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
110687ea75d5SPeter Crosthwaite                                    &error_abort);
1107394c7d4dSKevin Wolf         if (arch_type == QEMU_ARCH_S390X) {
11081f68f1d3SAlexander Graf             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1109394c7d4dSKevin Wolf         } else {
1110f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1111394c7d4dSKevin Wolf         }
1112f43e47dbSMarkus Armbruster         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1113f43e47dbSMarkus Armbruster                      &error_abort);
1114394c7d4dSKevin Wolf         if (devaddr) {
1115f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1116394c7d4dSKevin Wolf         }
1117394c7d4dSKevin Wolf     }
1118394c7d4dSKevin Wolf 
1119d095b465SMax Reitz     filename = qemu_opt_get(legacy_opts, "file");
1120d095b465SMax Reitz 
1121ee13ed1cSKevin Wolf     /* Check werror/rerror compatibility with if=... */
1122ee13ed1cSKevin Wolf     werror = qemu_opt_get(legacy_opts, "werror");
1123ee13ed1cSKevin Wolf     if (werror != NULL) {
1124ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1125ee13ed1cSKevin Wolf             type != IF_NONE) {
1126ee13ed1cSKevin Wolf             error_report("werror is not supported by this bus type");
1127ee13ed1cSKevin Wolf             goto fail;
1128ee13ed1cSKevin Wolf         }
1129ee13ed1cSKevin Wolf         qdict_put(bs_opts, "werror", qstring_from_str(werror));
1130ee13ed1cSKevin Wolf     }
1131ee13ed1cSKevin Wolf 
1132ee13ed1cSKevin Wolf     rerror = qemu_opt_get(legacy_opts, "rerror");
1133ee13ed1cSKevin Wolf     if (rerror != NULL) {
1134ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1135ee13ed1cSKevin Wolf             type != IF_NONE) {
1136ee13ed1cSKevin Wolf             error_report("rerror is not supported by this bus type");
1137ee13ed1cSKevin Wolf             goto fail;
1138ee13ed1cSKevin Wolf         }
1139ee13ed1cSKevin Wolf         qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1140ee13ed1cSKevin Wolf     }
1141ee13ed1cSKevin Wolf 
11422d246f01SKevin Wolf     /* Actual block device init: Functionality shared with blockdev-add */
114318e46a03SMarkus Armbruster     blk = blockdev_init(filename, bs_opts, &local_err);
11443cb0e25cSMarkus Armbruster     bs_opts = NULL;
114518e46a03SMarkus Armbruster     if (!blk) {
114684d18f06SMarkus Armbruster         if (local_err) {
1147565f65d2SMarkus Armbruster             error_report_err(local_err);
1148b681072dSKevin Wolf         }
11492d246f01SKevin Wolf         goto fail;
1150b681072dSKevin Wolf     } else {
115184d18f06SMarkus Armbruster         assert(!local_err);
11522d246f01SKevin Wolf     }
11532d246f01SKevin Wolf 
115426f8b3a8SMarkus Armbruster     /* Create legacy DriveInfo */
115526f8b3a8SMarkus Armbruster     dinfo = g_malloc0(sizeof(*dinfo));
1156f298d071SKevin Wolf     dinfo->opts = all_opts;
11572d246f01SKevin Wolf 
1158b41a7338SKevin Wolf     dinfo->cyls = cyls;
1159b41a7338SKevin Wolf     dinfo->heads = heads;
1160b41a7338SKevin Wolf     dinfo->secs = secs;
1161b41a7338SKevin Wolf     dinfo->trans = translation;
1162b41a7338SKevin Wolf 
1163ee13ed1cSKevin Wolf     dinfo->type = type;
116487a899c5SKevin Wolf     dinfo->bus = bus_id;
116587a899c5SKevin Wolf     dinfo->unit = unit_id;
1166394c7d4dSKevin Wolf     dinfo->devaddr = devaddr;
1167bcf83158SKevin Wolf     dinfo->serial = g_strdup(serial);
1168bcf83158SKevin Wolf 
116926f8b3a8SMarkus Armbruster     blk_set_legacy_dinfo(blk, dinfo);
117026f8b3a8SMarkus Armbruster 
1171e34ef046SKevin Wolf     switch(type) {
1172e34ef046SKevin Wolf     case IF_IDE:
1173e34ef046SKevin Wolf     case IF_SCSI:
1174e34ef046SKevin Wolf     case IF_XEN:
1175e34ef046SKevin Wolf     case IF_NONE:
1176e34ef046SKevin Wolf         dinfo->media_cd = media == MEDIA_CDROM;
1177e34ef046SKevin Wolf         break;
1178e34ef046SKevin Wolf     default:
1179e34ef046SKevin Wolf         break;
1180e34ef046SKevin Wolf     }
1181e34ef046SKevin Wolf 
11822d246f01SKevin Wolf fail:
118333cb7dc8SKevin Wolf     qemu_opts_del(legacy_opts);
11843cb0e25cSMarkus Armbruster     QDECREF(bs_opts);
11852d246f01SKevin Wolf     return dinfo;
118657975222SKevin Wolf }
118757975222SKevin Wolf 
11883e5a50d6SMarkus Armbruster void hmp_commit(Monitor *mon, const QDict *qdict)
1189666daa68SMarkus Armbruster {
1190666daa68SMarkus Armbruster     const char *device = qdict_get_str(qdict, "device");
1191a0e8544cSFam Zheng     BlockBackend *blk;
11922d3735d3SStefan Hajnoczi     int ret;
11932d3735d3SStefan Hajnoczi 
1194e8877497SStefan Hajnoczi     if (!strcmp(device, "all")) {
1195da31d594SMax Reitz         ret = blk_commit_all();
1196e8877497SStefan Hajnoczi     } else {
119784aa0140SStefan Hajnoczi         BlockDriverState *bs;
119884aa0140SStefan Hajnoczi         AioContext *aio_context;
119984aa0140SStefan Hajnoczi 
1200a0e8544cSFam Zheng         blk = blk_by_name(device);
1201a0e8544cSFam Zheng         if (!blk) {
120258513bdeSJeff Cody             monitor_printf(mon, "Device '%s' not found\n", device);
1203ac59eb95SMarkus Armbruster             return;
12046ab4b5abSMarkus Armbruster         }
12055433c24fSMax Reitz         if (!blk_is_available(blk)) {
12065433c24fSMax Reitz             monitor_printf(mon, "Device '%s' has no medium\n", device);
12075433c24fSMax Reitz             return;
12085433c24fSMax Reitz         }
120984aa0140SStefan Hajnoczi 
121084aa0140SStefan Hajnoczi         bs = blk_bs(blk);
121184aa0140SStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
121284aa0140SStefan Hajnoczi         aio_context_acquire(aio_context);
121384aa0140SStefan Hajnoczi 
121484aa0140SStefan Hajnoczi         ret = bdrv_commit(bs);
121584aa0140SStefan Hajnoczi 
121684aa0140SStefan Hajnoczi         aio_context_release(aio_context);
12172d3735d3SStefan Hajnoczi     }
121858513bdeSJeff Cody     if (ret < 0) {
121958513bdeSJeff Cody         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
122058513bdeSJeff Cody                        strerror(-ret));
1221666daa68SMarkus Armbruster     }
1222666daa68SMarkus Armbruster }
1223666daa68SMarkus Armbruster 
122410f75907SEric Blake static void blockdev_do_action(TransactionAction *action, Error **errp)
12256cc2a415SPaolo Bonzini {
1226c8a83e85SKevin Wolf     TransactionActionList list;
12276cc2a415SPaolo Bonzini 
122810f75907SEric Blake     list.value = action;
12296cc2a415SPaolo Bonzini     list.next = NULL;
123094d16a64SJohn Snow     qmp_transaction(&list, false, NULL, errp);
12316cc2a415SPaolo Bonzini }
12326cc2a415SPaolo Bonzini 
12330901f67eSBenoît Canet void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
12340901f67eSBenoît Canet                                 bool has_node_name, const char *node_name,
12350901f67eSBenoît Canet                                 const char *snapshot_file,
12360901f67eSBenoît Canet                                 bool has_snapshot_node_name,
12370901f67eSBenoît Canet                                 const char *snapshot_node_name,
12386106e249SLuiz Capitulino                                 bool has_format, const char *format,
12390901f67eSBenoît Canet                                 bool has_mode, NewImageMode mode, Error **errp)
1240f8882568SJes Sorensen {
1241a911e6aeSAlberto Garcia     BlockdevSnapshotSync snapshot = {
12420901f67eSBenoît Canet         .has_device = has_device,
12436cc2a415SPaolo Bonzini         .device = (char *) device,
12440901f67eSBenoît Canet         .has_node_name = has_node_name,
12450901f67eSBenoît Canet         .node_name = (char *) node_name,
12466cc2a415SPaolo Bonzini         .snapshot_file = (char *) snapshot_file,
12470901f67eSBenoît Canet         .has_snapshot_node_name = has_snapshot_node_name,
12480901f67eSBenoît Canet         .snapshot_node_name = (char *) snapshot_node_name,
12496cc2a415SPaolo Bonzini         .has_format = has_format,
12506cc2a415SPaolo Bonzini         .format = (char *) format,
12516cc2a415SPaolo Bonzini         .has_mode = has_mode,
12526cc2a415SPaolo Bonzini         .mode = mode,
12536cc2a415SPaolo Bonzini     };
125410f75907SEric Blake     TransactionAction action = {
125510f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
125632bafa8fSEric Blake         .u.blockdev_snapshot_sync.data = &snapshot,
125710f75907SEric Blake     };
125810f75907SEric Blake     blockdev_do_action(&action, errp);
1259f8882568SJes Sorensen }
1260f8882568SJes Sorensen 
126143de7e2dSAlberto Garcia void qmp_blockdev_snapshot(const char *node, const char *overlay,
126243de7e2dSAlberto Garcia                            Error **errp)
126343de7e2dSAlberto Garcia {
126443de7e2dSAlberto Garcia     BlockdevSnapshot snapshot_data = {
126543de7e2dSAlberto Garcia         .node = (char *) node,
126643de7e2dSAlberto Garcia         .overlay = (char *) overlay
126743de7e2dSAlberto Garcia     };
126810f75907SEric Blake     TransactionAction action = {
126910f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
127032bafa8fSEric Blake         .u.blockdev_snapshot.data = &snapshot_data,
127110f75907SEric Blake     };
127210f75907SEric Blake     blockdev_do_action(&action, errp);
127343de7e2dSAlberto Garcia }
127443de7e2dSAlberto Garcia 
1275f323bc9eSWenchao Xia void qmp_blockdev_snapshot_internal_sync(const char *device,
1276f323bc9eSWenchao Xia                                          const char *name,
1277f323bc9eSWenchao Xia                                          Error **errp)
1278f323bc9eSWenchao Xia {
1279f323bc9eSWenchao Xia     BlockdevSnapshotInternal snapshot = {
1280f323bc9eSWenchao Xia         .device = (char *) device,
1281f323bc9eSWenchao Xia         .name = (char *) name
1282f323bc9eSWenchao Xia     };
128310f75907SEric Blake     TransactionAction action = {
128410f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
128532bafa8fSEric Blake         .u.blockdev_snapshot_internal_sync.data = &snapshot,
128610f75907SEric Blake     };
128710f75907SEric Blake     blockdev_do_action(&action, errp);
1288f323bc9eSWenchao Xia }
1289f323bc9eSWenchao Xia 
129044e3e053SWenchao Xia SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
129144e3e053SWenchao Xia                                                          bool has_id,
129244e3e053SWenchao Xia                                                          const char *id,
129344e3e053SWenchao Xia                                                          bool has_name,
129444e3e053SWenchao Xia                                                          const char *name,
129544e3e053SWenchao Xia                                                          Error **errp)
129644e3e053SWenchao Xia {
1297a0e8544cSFam Zheng     BlockDriverState *bs;
1298a0e8544cSFam Zheng     BlockBackend *blk;
12994ef3982aSStefan Hajnoczi     AioContext *aio_context;
130044e3e053SWenchao Xia     QEMUSnapshotInfo sn;
130144e3e053SWenchao Xia     Error *local_err = NULL;
130244e3e053SWenchao Xia     SnapshotInfo *info = NULL;
130344e3e053SWenchao Xia     int ret;
130444e3e053SWenchao Xia 
1305a0e8544cSFam Zheng     blk = blk_by_name(device);
1306a0e8544cSFam Zheng     if (!blk) {
130775158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
130875158ebbSMarkus Armbruster                   "Device '%s' not found", device);
130944e3e053SWenchao Xia         return NULL;
131044e3e053SWenchao Xia     }
13115433c24fSMax Reitz 
13125433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
13135433c24fSMax Reitz     aio_context_acquire(aio_context);
131444e3e053SWenchao Xia 
131544e3e053SWenchao Xia     if (!has_id) {
131644e3e053SWenchao Xia         id = NULL;
131744e3e053SWenchao Xia     }
131844e3e053SWenchao Xia 
131944e3e053SWenchao Xia     if (!has_name) {
132044e3e053SWenchao Xia         name = NULL;
132144e3e053SWenchao Xia     }
132244e3e053SWenchao Xia 
132344e3e053SWenchao Xia     if (!id && !name) {
132444e3e053SWenchao Xia         error_setg(errp, "Name or id must be provided");
13255433c24fSMax Reitz         goto out_aio_context;
132644e3e053SWenchao Xia     }
132744e3e053SWenchao Xia 
13285433c24fSMax Reitz     if (!blk_is_available(blk)) {
13295433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
13305433c24fSMax Reitz         goto out_aio_context;
13315433c24fSMax Reitz     }
13325433c24fSMax Reitz     bs = blk_bs(blk);
13334ef3982aSStefan Hajnoczi 
13340b928854SStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
13350b928854SStefan Hajnoczi         goto out_aio_context;
13360b928854SStefan Hajnoczi     }
13370b928854SStefan Hajnoczi 
133844e3e053SWenchao Xia     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
133984d18f06SMarkus Armbruster     if (local_err) {
134044e3e053SWenchao Xia         error_propagate(errp, local_err);
13414ef3982aSStefan Hajnoczi         goto out_aio_context;
134244e3e053SWenchao Xia     }
134344e3e053SWenchao Xia     if (!ret) {
134444e3e053SWenchao Xia         error_setg(errp,
134544e3e053SWenchao Xia                    "Snapshot with id '%s' and name '%s' does not exist on "
134644e3e053SWenchao Xia                    "device '%s'",
134744e3e053SWenchao Xia                    STR_OR_NULL(id), STR_OR_NULL(name), device);
13484ef3982aSStefan Hajnoczi         goto out_aio_context;
134944e3e053SWenchao Xia     }
135044e3e053SWenchao Xia 
135144e3e053SWenchao Xia     bdrv_snapshot_delete(bs, id, name, &local_err);
135284d18f06SMarkus Armbruster     if (local_err) {
135344e3e053SWenchao Xia         error_propagate(errp, local_err);
13544ef3982aSStefan Hajnoczi         goto out_aio_context;
135544e3e053SWenchao Xia     }
135644e3e053SWenchao Xia 
13574ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
13584ef3982aSStefan Hajnoczi 
13595839e53bSMarkus Armbruster     info = g_new0(SnapshotInfo, 1);
136044e3e053SWenchao Xia     info->id = g_strdup(sn.id_str);
136144e3e053SWenchao Xia     info->name = g_strdup(sn.name);
136244e3e053SWenchao Xia     info->date_nsec = sn.date_nsec;
136344e3e053SWenchao Xia     info->date_sec = sn.date_sec;
136444e3e053SWenchao Xia     info->vm_state_size = sn.vm_state_size;
136544e3e053SWenchao Xia     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
136644e3e053SWenchao Xia     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
136744e3e053SWenchao Xia 
136844e3e053SWenchao Xia     return info;
13694ef3982aSStefan Hajnoczi 
13704ef3982aSStefan Hajnoczi out_aio_context:
13714ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
13724ef3982aSStefan Hajnoczi     return NULL;
137344e3e053SWenchao Xia }
13748802d1fdSJeff Cody 
1375341ebc2fSJohn Snow /**
1376341ebc2fSJohn Snow  * block_dirty_bitmap_lookup:
1377341ebc2fSJohn Snow  * Return a dirty bitmap (if present), after validating
1378341ebc2fSJohn Snow  * the node reference and bitmap names.
1379341ebc2fSJohn Snow  *
1380341ebc2fSJohn Snow  * @node: The name of the BDS node to search for bitmaps
1381341ebc2fSJohn Snow  * @name: The name of the bitmap to search for
1382341ebc2fSJohn Snow  * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1383341ebc2fSJohn Snow  * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1384341ebc2fSJohn Snow  * @errp: Output pointer for error information. Can be NULL.
1385341ebc2fSJohn Snow  *
1386341ebc2fSJohn Snow  * @return: A bitmap object on success, or NULL on failure.
1387341ebc2fSJohn Snow  */
1388341ebc2fSJohn Snow static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1389341ebc2fSJohn Snow                                                   const char *name,
1390341ebc2fSJohn Snow                                                   BlockDriverState **pbs,
1391341ebc2fSJohn Snow                                                   AioContext **paio,
1392341ebc2fSJohn Snow                                                   Error **errp)
1393341ebc2fSJohn Snow {
1394341ebc2fSJohn Snow     BlockDriverState *bs;
1395341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
1396341ebc2fSJohn Snow     AioContext *aio_context;
1397341ebc2fSJohn Snow 
1398341ebc2fSJohn Snow     if (!node) {
1399341ebc2fSJohn Snow         error_setg(errp, "Node cannot be NULL");
1400341ebc2fSJohn Snow         return NULL;
1401341ebc2fSJohn Snow     }
1402341ebc2fSJohn Snow     if (!name) {
1403341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be NULL");
1404341ebc2fSJohn Snow         return NULL;
1405341ebc2fSJohn Snow     }
1406341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, NULL);
1407341ebc2fSJohn Snow     if (!bs) {
1408341ebc2fSJohn Snow         error_setg(errp, "Node '%s' not found", node);
1409341ebc2fSJohn Snow         return NULL;
1410341ebc2fSJohn Snow     }
1411341ebc2fSJohn Snow 
1412341ebc2fSJohn Snow     aio_context = bdrv_get_aio_context(bs);
1413341ebc2fSJohn Snow     aio_context_acquire(aio_context);
1414341ebc2fSJohn Snow 
1415341ebc2fSJohn Snow     bitmap = bdrv_find_dirty_bitmap(bs, name);
1416341ebc2fSJohn Snow     if (!bitmap) {
1417341ebc2fSJohn Snow         error_setg(errp, "Dirty bitmap '%s' not found", name);
1418341ebc2fSJohn Snow         goto fail;
1419341ebc2fSJohn Snow     }
1420341ebc2fSJohn Snow 
1421341ebc2fSJohn Snow     if (pbs) {
1422341ebc2fSJohn Snow         *pbs = bs;
1423341ebc2fSJohn Snow     }
1424341ebc2fSJohn Snow     if (paio) {
1425341ebc2fSJohn Snow         *paio = aio_context;
1426341ebc2fSJohn Snow     } else {
1427341ebc2fSJohn Snow         aio_context_release(aio_context);
1428341ebc2fSJohn Snow     }
1429341ebc2fSJohn Snow 
1430341ebc2fSJohn Snow     return bitmap;
1431341ebc2fSJohn Snow 
1432341ebc2fSJohn Snow  fail:
1433341ebc2fSJohn Snow     aio_context_release(aio_context);
1434341ebc2fSJohn Snow     return NULL;
1435341ebc2fSJohn Snow }
1436341ebc2fSJohn Snow 
1437b756b9ceSStefan Hajnoczi /* New and old BlockDriverState structs for atomic group operations */
1438ba0c86a3SWenchao Xia 
143950f43f0fSJohn Snow typedef struct BlkActionState BlkActionState;
1440ba0c86a3SWenchao Xia 
144150f43f0fSJohn Snow /**
144250f43f0fSJohn Snow  * BlkActionOps:
144350f43f0fSJohn Snow  * Table of operations that define an Action.
144450f43f0fSJohn Snow  *
144550f43f0fSJohn Snow  * @instance_size: Size of state struct, in bytes.
144650f43f0fSJohn Snow  * @prepare: Prepare the work, must NOT be NULL.
144750f43f0fSJohn Snow  * @commit: Commit the changes, can be NULL.
144850f43f0fSJohn Snow  * @abort: Abort the changes on fail, can be NULL.
144950f43f0fSJohn Snow  * @clean: Clean up resources after all transaction actions have called
145050f43f0fSJohn Snow  *         commit() or abort(). Can be NULL.
145150f43f0fSJohn Snow  *
145250f43f0fSJohn Snow  * Only prepare() may fail. In a single transaction, only one of commit() or
145350f43f0fSJohn Snow  * abort() will be called. clean() will always be called if it is present.
1454ba0c86a3SWenchao Xia  */
145550f43f0fSJohn Snow typedef struct BlkActionOps {
145650f43f0fSJohn Snow     size_t instance_size;
145750f43f0fSJohn Snow     void (*prepare)(BlkActionState *common, Error **errp);
145850f43f0fSJohn Snow     void (*commit)(BlkActionState *common);
145950f43f0fSJohn Snow     void (*abort)(BlkActionState *common);
146050f43f0fSJohn Snow     void (*clean)(BlkActionState *common);
146150f43f0fSJohn Snow } BlkActionOps;
146250f43f0fSJohn Snow 
146350f43f0fSJohn Snow /**
146450f43f0fSJohn Snow  * BlkActionState:
146550f43f0fSJohn Snow  * Describes one Action's state within a Transaction.
146650f43f0fSJohn Snow  *
146750f43f0fSJohn Snow  * @action: QAPI-defined enum identifying which Action to perform.
146850f43f0fSJohn Snow  * @ops: Table of ActionOps this Action can perform.
146994d16a64SJohn Snow  * @block_job_txn: Transaction which this action belongs to.
147050f43f0fSJohn Snow  * @entry: List membership for all Actions in this Transaction.
147150f43f0fSJohn Snow  *
147250f43f0fSJohn Snow  * This structure must be arranged as first member in a subclassed type,
147350f43f0fSJohn Snow  * assuming that the compiler will also arrange it to the same offsets as the
147450f43f0fSJohn Snow  * base class.
147550f43f0fSJohn Snow  */
147650f43f0fSJohn Snow struct BlkActionState {
1477c8a83e85SKevin Wolf     TransactionAction *action;
147850f43f0fSJohn Snow     const BlkActionOps *ops;
147994d16a64SJohn Snow     BlockJobTxn *block_job_txn;
148094d16a64SJohn Snow     TransactionProperties *txn_props;
148150f43f0fSJohn Snow     QSIMPLEQ_ENTRY(BlkActionState) entry;
1482ba0c86a3SWenchao Xia };
1483ba0c86a3SWenchao Xia 
1484bbe86010SWenchao Xia /* internal snapshot private data */
1485bbe86010SWenchao Xia typedef struct InternalSnapshotState {
148650f43f0fSJohn Snow     BlkActionState common;
1487bbe86010SWenchao Xia     BlockDriverState *bs;
14885d6e96efSStefan Hajnoczi     AioContext *aio_context;
1489bbe86010SWenchao Xia     QEMUSnapshotInfo sn;
1490507306ccSFam Zheng     bool created;
1491bbe86010SWenchao Xia } InternalSnapshotState;
1492bbe86010SWenchao Xia 
149394d16a64SJohn Snow 
149494d16a64SJohn Snow static int action_check_completion_mode(BlkActionState *s, Error **errp)
149594d16a64SJohn Snow {
149694d16a64SJohn Snow     if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
149794d16a64SJohn Snow         error_setg(errp,
149894d16a64SJohn Snow                    "Action '%s' does not support Transaction property "
149994d16a64SJohn Snow                    "completion-mode = %s",
150094d16a64SJohn Snow                    TransactionActionKind_lookup[s->action->type],
150194d16a64SJohn Snow                    ActionCompletionMode_lookup[s->txn_props->completion_mode]);
150294d16a64SJohn Snow         return -1;
150394d16a64SJohn Snow     }
150494d16a64SJohn Snow     return 0;
150594d16a64SJohn Snow }
150694d16a64SJohn Snow 
150750f43f0fSJohn Snow static void internal_snapshot_prepare(BlkActionState *common,
1508bbe86010SWenchao Xia                                       Error **errp)
1509bbe86010SWenchao Xia {
1510f70edf99SMarkus Armbruster     Error *local_err = NULL;
1511bbe86010SWenchao Xia     const char *device;
1512bbe86010SWenchao Xia     const char *name;
1513a0e8544cSFam Zheng     BlockBackend *blk;
1514bbe86010SWenchao Xia     BlockDriverState *bs;
1515bbe86010SWenchao Xia     QEMUSnapshotInfo old_sn, *sn;
1516bbe86010SWenchao Xia     bool ret;
1517bbe86010SWenchao Xia     qemu_timeval tv;
1518bbe86010SWenchao Xia     BlockdevSnapshotInternal *internal;
1519bbe86010SWenchao Xia     InternalSnapshotState *state;
1520bbe86010SWenchao Xia     int ret1;
1521bbe86010SWenchao Xia 
15226a8f9661SEric Blake     g_assert(common->action->type ==
1523bbe86010SWenchao Xia              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
152432bafa8fSEric Blake     internal = common->action->u.blockdev_snapshot_internal_sync.data;
1525bbe86010SWenchao Xia     state = DO_UPCAST(InternalSnapshotState, common, common);
1526bbe86010SWenchao Xia 
1527bbe86010SWenchao Xia     /* 1. parse input */
1528bbe86010SWenchao Xia     device = internal->device;
1529bbe86010SWenchao Xia     name = internal->name;
1530bbe86010SWenchao Xia 
1531bbe86010SWenchao Xia     /* 2. check for validation */
153294d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
153394d16a64SJohn Snow         return;
153494d16a64SJohn Snow     }
153594d16a64SJohn Snow 
1536a0e8544cSFam Zheng     blk = blk_by_name(device);
1537a0e8544cSFam Zheng     if (!blk) {
153875158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
153975158ebbSMarkus Armbruster                   "Device '%s' not found", device);
1540bbe86010SWenchao Xia         return;
1541bbe86010SWenchao Xia     }
1542bbe86010SWenchao Xia 
15435d6e96efSStefan Hajnoczi     /* AioContext is released in .clean() */
15445433c24fSMax Reitz     state->aio_context = blk_get_aio_context(blk);
15455d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
15465d6e96efSStefan Hajnoczi 
15475433c24fSMax Reitz     if (!blk_is_available(blk)) {
1548c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1549bbe86010SWenchao Xia         return;
1550bbe86010SWenchao Xia     }
15515433c24fSMax Reitz     bs = blk_bs(blk);
1552bbe86010SWenchao Xia 
1553507306ccSFam Zheng     state->bs = bs;
1554507306ccSFam Zheng     bdrv_drained_begin(bs);
1555507306ccSFam Zheng 
15563dc7ca3cSStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
15573dc7ca3cSStefan Hajnoczi         return;
15583dc7ca3cSStefan Hajnoczi     }
15593dc7ca3cSStefan Hajnoczi 
1560bbe86010SWenchao Xia     if (bdrv_is_read_only(bs)) {
156181e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
1562bbe86010SWenchao Xia         return;
1563bbe86010SWenchao Xia     }
1564bbe86010SWenchao Xia 
1565bbe86010SWenchao Xia     if (!bdrv_can_snapshot(bs)) {
156681e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by device '%s' "
156781e5f78aSAlberto Garcia                    "does not support internal snapshots",
156881e5f78aSAlberto Garcia                    bs->drv->format_name, device);
1569bbe86010SWenchao Xia         return;
1570bbe86010SWenchao Xia     }
1571bbe86010SWenchao Xia 
1572bbe86010SWenchao Xia     if (!strlen(name)) {
1573bbe86010SWenchao Xia         error_setg(errp, "Name is empty");
1574bbe86010SWenchao Xia         return;
1575bbe86010SWenchao Xia     }
1576bbe86010SWenchao Xia 
1577bbe86010SWenchao Xia     /* check whether a snapshot with name exist */
1578f70edf99SMarkus Armbruster     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1579f70edf99SMarkus Armbruster                                             &local_err);
1580f70edf99SMarkus Armbruster     if (local_err) {
1581f70edf99SMarkus Armbruster         error_propagate(errp, local_err);
1582bbe86010SWenchao Xia         return;
1583bbe86010SWenchao Xia     } else if (ret) {
1584bbe86010SWenchao Xia         error_setg(errp,
1585bbe86010SWenchao Xia                    "Snapshot with name '%s' already exists on device '%s'",
1586bbe86010SWenchao Xia                    name, device);
1587bbe86010SWenchao Xia         return;
1588bbe86010SWenchao Xia     }
1589bbe86010SWenchao Xia 
1590bbe86010SWenchao Xia     /* 3. take the snapshot */
1591bbe86010SWenchao Xia     sn = &state->sn;
1592bbe86010SWenchao Xia     pstrcpy(sn->name, sizeof(sn->name), name);
1593bbe86010SWenchao Xia     qemu_gettimeofday(&tv);
1594bbe86010SWenchao Xia     sn->date_sec = tv.tv_sec;
1595bbe86010SWenchao Xia     sn->date_nsec = tv.tv_usec * 1000;
1596bbe86010SWenchao Xia     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1597bbe86010SWenchao Xia 
1598bbe86010SWenchao Xia     ret1 = bdrv_snapshot_create(bs, sn);
1599bbe86010SWenchao Xia     if (ret1 < 0) {
1600bbe86010SWenchao Xia         error_setg_errno(errp, -ret1,
1601bbe86010SWenchao Xia                          "Failed to create snapshot '%s' on device '%s'",
1602bbe86010SWenchao Xia                          name, device);
1603bbe86010SWenchao Xia         return;
1604bbe86010SWenchao Xia     }
1605bbe86010SWenchao Xia 
1606bbe86010SWenchao Xia     /* 4. succeed, mark a snapshot is created */
1607507306ccSFam Zheng     state->created = true;
1608bbe86010SWenchao Xia }
1609bbe86010SWenchao Xia 
161050f43f0fSJohn Snow static void internal_snapshot_abort(BlkActionState *common)
1611bbe86010SWenchao Xia {
1612bbe86010SWenchao Xia     InternalSnapshotState *state =
1613bbe86010SWenchao Xia                              DO_UPCAST(InternalSnapshotState, common, common);
1614bbe86010SWenchao Xia     BlockDriverState *bs = state->bs;
1615bbe86010SWenchao Xia     QEMUSnapshotInfo *sn = &state->sn;
1616bbe86010SWenchao Xia     Error *local_error = NULL;
1617bbe86010SWenchao Xia 
1618507306ccSFam Zheng     if (!state->created) {
1619bbe86010SWenchao Xia         return;
1620bbe86010SWenchao Xia     }
1621bbe86010SWenchao Xia 
1622bbe86010SWenchao Xia     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1623c29b77f9SMarkus Armbruster         error_reportf_err(local_error,
1624c29b77f9SMarkus Armbruster                           "Failed to delete snapshot with id '%s' and "
1625c29b77f9SMarkus Armbruster                           "name '%s' on device '%s' in abort: ",
1626c29b77f9SMarkus Armbruster                           sn->id_str, sn->name,
1627c29b77f9SMarkus Armbruster                           bdrv_get_device_name(bs));
1628bbe86010SWenchao Xia     }
1629bbe86010SWenchao Xia }
1630bbe86010SWenchao Xia 
163150f43f0fSJohn Snow static void internal_snapshot_clean(BlkActionState *common)
16325d6e96efSStefan Hajnoczi {
16335d6e96efSStefan Hajnoczi     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
16345d6e96efSStefan Hajnoczi                                              common, common);
16355d6e96efSStefan Hajnoczi 
16365d6e96efSStefan Hajnoczi     if (state->aio_context) {
1637507306ccSFam Zheng         if (state->bs) {
1638507306ccSFam Zheng             bdrv_drained_end(state->bs);
1639507306ccSFam Zheng         }
16405d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
16415d6e96efSStefan Hajnoczi     }
16425d6e96efSStefan Hajnoczi }
16435d6e96efSStefan Hajnoczi 
1644ba0c86a3SWenchao Xia /* external snapshot private data */
1645ba5d6ab6SStefan Hajnoczi typedef struct ExternalSnapshotState {
164650f43f0fSJohn Snow     BlkActionState common;
16478802d1fdSJeff Cody     BlockDriverState *old_bs;
16488802d1fdSJeff Cody     BlockDriverState *new_bs;
16495d6e96efSStefan Hajnoczi     AioContext *aio_context;
1650ba5d6ab6SStefan Hajnoczi } ExternalSnapshotState;
16518802d1fdSJeff Cody 
165250f43f0fSJohn Snow static void external_snapshot_prepare(BlkActionState *common,
16539b9877eeSWenchao Xia                                       Error **errp)
16549b9877eeSWenchao Xia {
165543de7e2dSAlberto Garcia     int flags = 0, ret;
165643de7e2dSAlberto Garcia     QDict *options = NULL;
16579b9877eeSWenchao Xia     Error *local_err = NULL;
165843de7e2dSAlberto Garcia     /* Device and node name of the image to generate the snapshot from */
1659e2a31e87SWenchao Xia     const char *device;
16600901f67eSBenoît Canet     const char *node_name;
166143de7e2dSAlberto Garcia     /* Reference to the new image (for 'blockdev-snapshot') */
166243de7e2dSAlberto Garcia     const char *snapshot_ref;
166343de7e2dSAlberto Garcia     /* File name of the new image (for 'blockdev-snapshot-sync') */
1664e2a31e87SWenchao Xia     const char *new_image_file;
1665ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1666ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1667c8a83e85SKevin Wolf     TransactionAction *action = common->action;
16689b9877eeSWenchao Xia 
166943de7e2dSAlberto Garcia     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
167043de7e2dSAlberto Garcia      * purpose but a different set of parameters */
167143de7e2dSAlberto Garcia     switch (action->type) {
167243de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
167343de7e2dSAlberto Garcia         {
167432bafa8fSEric Blake             BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
167543de7e2dSAlberto Garcia             device = s->node;
167643de7e2dSAlberto Garcia             node_name = s->node;
167743de7e2dSAlberto Garcia             new_image_file = NULL;
167843de7e2dSAlberto Garcia             snapshot_ref = s->overlay;
1679e2a31e87SWenchao Xia         }
168043de7e2dSAlberto Garcia         break;
168143de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
168243de7e2dSAlberto Garcia         {
168332bafa8fSEric Blake             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
168443de7e2dSAlberto Garcia             device = s->has_device ? s->device : NULL;
168543de7e2dSAlberto Garcia             node_name = s->has_node_name ? s->node_name : NULL;
168643de7e2dSAlberto Garcia             new_image_file = s->snapshot_file;
168743de7e2dSAlberto Garcia             snapshot_ref = NULL;
168843de7e2dSAlberto Garcia         }
168943de7e2dSAlberto Garcia         break;
169043de7e2dSAlberto Garcia     default:
169143de7e2dSAlberto Garcia         g_assert_not_reached();
1692e2a31e87SWenchao Xia     }
1693e2a31e87SWenchao Xia 
1694e2a31e87SWenchao Xia     /* start processing */
169594d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
169694d16a64SJohn Snow         return;
169794d16a64SJohn Snow     }
169894d16a64SJohn Snow 
169943de7e2dSAlberto Garcia     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
170043de7e2dSAlberto Garcia     if (!state->old_bs) {
17019b9877eeSWenchao Xia         return;
17029b9877eeSWenchao Xia     }
17039b9877eeSWenchao Xia 
17045d6e96efSStefan Hajnoczi     /* Acquire AioContext now so any threads operating on old_bs stop */
17055d6e96efSStefan Hajnoczi     state->aio_context = bdrv_get_aio_context(state->old_bs);
17065d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
1707da763e83SFam Zheng     bdrv_drained_begin(state->old_bs);
17085d6e96efSStefan Hajnoczi 
1709ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_inserted(state->old_bs)) {
1710c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
17119b9877eeSWenchao Xia         return;
17129b9877eeSWenchao Xia     }
17139b9877eeSWenchao Xia 
17143718d8abSFam Zheng     if (bdrv_op_is_blocked(state->old_bs,
17153718d8abSFam Zheng                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
17169b9877eeSWenchao Xia         return;
17179b9877eeSWenchao Xia     }
17189b9877eeSWenchao Xia 
1719ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_read_only(state->old_bs)) {
1720ba5d6ab6SStefan Hajnoczi         if (bdrv_flush(state->old_bs)) {
1721c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_IO_ERROR);
17229b9877eeSWenchao Xia             return;
17239b9877eeSWenchao Xia         }
17249b9877eeSWenchao Xia     }
17259b9877eeSWenchao Xia 
1726212a5a8fSBenoît Canet     if (!bdrv_is_first_non_filter(state->old_bs)) {
1727c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1728f6186f49SBenoît Canet         return;
1729f6186f49SBenoît Canet     }
1730f6186f49SBenoît Canet 
173143de7e2dSAlberto Garcia     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
173232bafa8fSEric Blake         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
173343de7e2dSAlberto Garcia         const char *format = s->has_format ? s->format : "qcow2";
173443de7e2dSAlberto Garcia         enum NewImageMode mode;
173543de7e2dSAlberto Garcia         const char *snapshot_node_name =
173643de7e2dSAlberto Garcia             s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
173743de7e2dSAlberto Garcia 
173843de7e2dSAlberto Garcia         if (node_name && !snapshot_node_name) {
173943de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name missing");
174043de7e2dSAlberto Garcia             return;
174143de7e2dSAlberto Garcia         }
174243de7e2dSAlberto Garcia 
174343de7e2dSAlberto Garcia         if (snapshot_node_name &&
174443de7e2dSAlberto Garcia             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
174543de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name already in use");
174643de7e2dSAlberto Garcia             return;
174743de7e2dSAlberto Garcia         }
174843de7e2dSAlberto Garcia 
1749ba5d6ab6SStefan Hajnoczi         flags = state->old_bs->open_flags;
17504c844983SKevin Wolf         flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
17519b9877eeSWenchao Xia 
17529b9877eeSWenchao Xia         /* create new image w/backing file */
175343de7e2dSAlberto Garcia         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
17549b9877eeSWenchao Xia         if (mode != NEW_IMAGE_MODE_EXISTING) {
1755f86b8b58SKevin Wolf             int64_t size = bdrv_getlength(state->old_bs);
1756f86b8b58SKevin Wolf             if (size < 0) {
1757f86b8b58SKevin Wolf                 error_setg_errno(errp, -size, "bdrv_getlength failed");
1758f86b8b58SKevin Wolf                 return;
1759f86b8b58SKevin Wolf             }
17609b9877eeSWenchao Xia             bdrv_img_create(new_image_file, format,
1761ba5d6ab6SStefan Hajnoczi                             state->old_bs->filename,
1762ba5d6ab6SStefan Hajnoczi                             state->old_bs->drv->format_name,
1763f86b8b58SKevin Wolf                             NULL, size, flags, &local_err, false);
176484d18f06SMarkus Armbruster             if (local_err) {
17659b9877eeSWenchao Xia                 error_propagate(errp, local_err);
17669b9877eeSWenchao Xia                 return;
17679b9877eeSWenchao Xia             }
17689b9877eeSWenchao Xia         }
17699b9877eeSWenchao Xia 
17700901f67eSBenoît Canet         options = qdict_new();
177143de7e2dSAlberto Garcia         if (s->has_snapshot_node_name) {
17720901f67eSBenoît Canet             qdict_put(options, "node-name",
17730901f67eSBenoît Canet                       qstring_from_str(snapshot_node_name));
17740901f67eSBenoît Canet         }
1775e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
17760901f67eSBenoît Canet 
177743de7e2dSAlberto Garcia         flags |= BDRV_O_NO_BACKING;
177843de7e2dSAlberto Garcia     }
177943de7e2dSAlberto Garcia 
1780f67503e5SMax Reitz     assert(state->new_bs == NULL);
178143de7e2dSAlberto Garcia     ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
178243de7e2dSAlberto Garcia                     flags, errp);
1783f67503e5SMax Reitz     /* We will manually add the backing_hd field to the bs later */
17849b9877eeSWenchao Xia     if (ret != 0) {
178543de7e2dSAlberto Garcia         return;
178643de7e2dSAlberto Garcia     }
178743de7e2dSAlberto Garcia 
178843de7e2dSAlberto Garcia     if (state->new_bs->blk != NULL) {
178943de7e2dSAlberto Garcia         error_setg(errp, "The snapshot is already in use by %s",
179043de7e2dSAlberto Garcia                    blk_name(state->new_bs->blk));
179143de7e2dSAlberto Garcia         return;
179243de7e2dSAlberto Garcia     }
179343de7e2dSAlberto Garcia 
179443de7e2dSAlberto Garcia     if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
179543de7e2dSAlberto Garcia                            errp)) {
179643de7e2dSAlberto Garcia         return;
179743de7e2dSAlberto Garcia     }
179843de7e2dSAlberto Garcia 
179943de7e2dSAlberto Garcia     if (state->new_bs->backing != NULL) {
180043de7e2dSAlberto Garcia         error_setg(errp, "The snapshot already has a backing image");
180108b24cfeSAlberto Garcia         return;
180208b24cfeSAlberto Garcia     }
180308b24cfeSAlberto Garcia 
180408b24cfeSAlberto Garcia     if (!state->new_bs->drv->supports_backing) {
180508b24cfeSAlberto Garcia         error_setg(errp, "The snapshot does not support backing images");
18069b9877eeSWenchao Xia     }
18079b9877eeSWenchao Xia }
18089b9877eeSWenchao Xia 
180950f43f0fSJohn Snow static void external_snapshot_commit(BlkActionState *common)
18103b0047e8SWenchao Xia {
1811ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1812ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1813ba0c86a3SWenchao Xia 
18145d6e96efSStefan Hajnoczi     bdrv_set_aio_context(state->new_bs, state->aio_context);
18155d6e96efSStefan Hajnoczi 
1816ba5d6ab6SStefan Hajnoczi     /* This removes our old bs and adds the new bs */
1817ba5d6ab6SStefan Hajnoczi     bdrv_append(state->new_bs, state->old_bs);
18183b0047e8SWenchao Xia     /* We don't need (or want) to use the transactional
18193b0047e8SWenchao Xia      * bdrv_reopen_multiple() across all the entries at once, because we
18203b0047e8SWenchao Xia      * don't want to abort all of them if one of them fails the reopen */
18214c844983SKevin Wolf     if (!state->old_bs->copy_on_read) {
1822dd62f1caSKevin Wolf         bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
18233b0047e8SWenchao Xia                     NULL);
18243b0047e8SWenchao Xia     }
18254c844983SKevin Wolf }
18263b0047e8SWenchao Xia 
182750f43f0fSJohn Snow static void external_snapshot_abort(BlkActionState *common)
182896b86bf7SWenchao Xia {
1829ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1830ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1831ba5d6ab6SStefan Hajnoczi     if (state->new_bs) {
18324f6fd349SFam Zheng         bdrv_unref(state->new_bs);
183396b86bf7SWenchao Xia     }
1834da763e83SFam Zheng }
1835da763e83SFam Zheng 
183650f43f0fSJohn Snow static void external_snapshot_clean(BlkActionState *common)
1837da763e83SFam Zheng {
1838da763e83SFam Zheng     ExternalSnapshotState *state =
1839da763e83SFam Zheng                              DO_UPCAST(ExternalSnapshotState, common, common);
18405d6e96efSStefan Hajnoczi     if (state->aio_context) {
1841da763e83SFam Zheng         bdrv_drained_end(state->old_bs);
18425d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
18435d6e96efSStefan Hajnoczi     }
184496b86bf7SWenchao Xia }
184596b86bf7SWenchao Xia 
18463037f364SStefan Hajnoczi typedef struct DriveBackupState {
184750f43f0fSJohn Snow     BlkActionState common;
18483037f364SStefan Hajnoczi     BlockDriverState *bs;
18495d6e96efSStefan Hajnoczi     AioContext *aio_context;
18503037f364SStefan Hajnoczi     BlockJob *job;
18513037f364SStefan Hajnoczi } DriveBackupState;
18523037f364SStefan Hajnoczi 
185378f51fdeSJohn Snow static void do_drive_backup(const char *device, const char *target,
185478f51fdeSJohn Snow                             bool has_format, const char *format,
185578f51fdeSJohn Snow                             enum MirrorSyncMode sync,
185678f51fdeSJohn Snow                             bool has_mode, enum NewImageMode mode,
185778f51fdeSJohn Snow                             bool has_speed, int64_t speed,
185878f51fdeSJohn Snow                             bool has_bitmap, const char *bitmap,
185978f51fdeSJohn Snow                             bool has_on_source_error,
186078f51fdeSJohn Snow                             BlockdevOnError on_source_error,
186178f51fdeSJohn Snow                             bool has_on_target_error,
186278f51fdeSJohn Snow                             BlockdevOnError on_target_error,
186378f51fdeSJohn Snow                             BlockJobTxn *txn, Error **errp);
186478f51fdeSJohn Snow 
186550f43f0fSJohn Snow static void drive_backup_prepare(BlkActionState *common, Error **errp)
18663037f364SStefan Hajnoczi {
18673037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1868a0e8544cSFam Zheng     BlockBackend *blk;
18693037f364SStefan Hajnoczi     DriveBackup *backup;
18703037f364SStefan Hajnoczi     Error *local_err = NULL;
18713037f364SStefan Hajnoczi 
18726a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
187332bafa8fSEric Blake     backup = common->action->u.drive_backup.data;
18743037f364SStefan Hajnoczi 
1875a0e8544cSFam Zheng     blk = blk_by_name(backup->device);
1876a0e8544cSFam Zheng     if (!blk) {
187775158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
187875158ebbSMarkus Armbruster                   "Device '%s' not found", backup->device);
18795d6e96efSStefan Hajnoczi         return;
18805d6e96efSStefan Hajnoczi     }
18815d6e96efSStefan Hajnoczi 
18821fdd4b7bSFam Zheng     if (!blk_is_available(blk)) {
18831fdd4b7bSFam Zheng         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
18841fdd4b7bSFam Zheng         return;
18851fdd4b7bSFam Zheng     }
18861fdd4b7bSFam Zheng 
18875d6e96efSStefan Hajnoczi     /* AioContext is released in .clean() */
18885433c24fSMax Reitz     state->aio_context = blk_get_aio_context(blk);
18895d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
18901fdd4b7bSFam Zheng     bdrv_drained_begin(blk_bs(blk));
18911fdd4b7bSFam Zheng     state->bs = blk_bs(blk);
18925d6e96efSStefan Hajnoczi 
189378f51fdeSJohn Snow     do_drive_backup(backup->device, backup->target,
18943037f364SStefan Hajnoczi                     backup->has_format, backup->format,
1895b53169eaSStefan Hajnoczi                     backup->sync,
18963037f364SStefan Hajnoczi                     backup->has_mode, backup->mode,
18973037f364SStefan Hajnoczi                     backup->has_speed, backup->speed,
1898d58d8453SJohn Snow                     backup->has_bitmap, backup->bitmap,
18993037f364SStefan Hajnoczi                     backup->has_on_source_error, backup->on_source_error,
19003037f364SStefan Hajnoczi                     backup->has_on_target_error, backup->on_target_error,
190194d16a64SJohn Snow                     common->block_job_txn, &local_err);
190284d18f06SMarkus Armbruster     if (local_err) {
19033037f364SStefan Hajnoczi         error_propagate(errp, local_err);
19043037f364SStefan Hajnoczi         return;
19053037f364SStefan Hajnoczi     }
19063037f364SStefan Hajnoczi 
19073037f364SStefan Hajnoczi     state->job = state->bs->job;
19083037f364SStefan Hajnoczi }
19093037f364SStefan Hajnoczi 
191050f43f0fSJohn Snow static void drive_backup_abort(BlkActionState *common)
19113037f364SStefan Hajnoczi {
19123037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
19133037f364SStefan Hajnoczi     BlockDriverState *bs = state->bs;
19143037f364SStefan Hajnoczi 
19153037f364SStefan Hajnoczi     /* Only cancel if it's the job we started */
19163037f364SStefan Hajnoczi     if (bs && bs->job && bs->job == state->job) {
19173037f364SStefan Hajnoczi         block_job_cancel_sync(bs->job);
19183037f364SStefan Hajnoczi     }
19193037f364SStefan Hajnoczi }
19203037f364SStefan Hajnoczi 
192150f43f0fSJohn Snow static void drive_backup_clean(BlkActionState *common)
19225d6e96efSStefan Hajnoczi {
19235d6e96efSStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
19245d6e96efSStefan Hajnoczi 
19255d6e96efSStefan Hajnoczi     if (state->aio_context) {
19261fdd4b7bSFam Zheng         bdrv_drained_end(state->bs);
19275d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
19285d6e96efSStefan Hajnoczi     }
19295d6e96efSStefan Hajnoczi }
19305d6e96efSStefan Hajnoczi 
1931bd8baecdSFam Zheng typedef struct BlockdevBackupState {
193250f43f0fSJohn Snow     BlkActionState common;
1933bd8baecdSFam Zheng     BlockDriverState *bs;
1934bd8baecdSFam Zheng     BlockJob *job;
1935bd8baecdSFam Zheng     AioContext *aio_context;
1936bd8baecdSFam Zheng } BlockdevBackupState;
1937bd8baecdSFam Zheng 
193878f51fdeSJohn Snow static void do_blockdev_backup(const char *device, const char *target,
193978f51fdeSJohn Snow                                enum MirrorSyncMode sync,
194078f51fdeSJohn Snow                                bool has_speed, int64_t speed,
194178f51fdeSJohn Snow                                bool has_on_source_error,
194278f51fdeSJohn Snow                                BlockdevOnError on_source_error,
194378f51fdeSJohn Snow                                bool has_on_target_error,
194478f51fdeSJohn Snow                                BlockdevOnError on_target_error,
194578f51fdeSJohn Snow                                BlockJobTxn *txn, Error **errp);
194678f51fdeSJohn Snow 
194750f43f0fSJohn Snow static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1948bd8baecdSFam Zheng {
1949bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1950bd8baecdSFam Zheng     BlockdevBackup *backup;
19515433c24fSMax Reitz     BlockBackend *blk, *target;
1952bd8baecdSFam Zheng     Error *local_err = NULL;
1953bd8baecdSFam Zheng 
19546a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
195532bafa8fSEric Blake     backup = common->action->u.blockdev_backup.data;
1956bd8baecdSFam Zheng 
1957a0e8544cSFam Zheng     blk = blk_by_name(backup->device);
1958a0e8544cSFam Zheng     if (!blk) {
19595b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", backup->device);
1960bd8baecdSFam Zheng         return;
1961bd8baecdSFam Zheng     }
1962bd8baecdSFam Zheng 
1963ff52bf36SFam Zheng     if (!blk_is_available(blk)) {
1964ff52bf36SFam Zheng         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1965ff52bf36SFam Zheng         return;
1966ff52bf36SFam Zheng     }
1967ff52bf36SFam Zheng 
19685433c24fSMax Reitz     target = blk_by_name(backup->target);
19695433c24fSMax Reitz     if (!target) {
19705b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", backup->target);
1971bd8baecdSFam Zheng         return;
1972bd8baecdSFam Zheng     }
1973bd8baecdSFam Zheng 
1974bd8baecdSFam Zheng     /* AioContext is released in .clean() */
19755433c24fSMax Reitz     state->aio_context = blk_get_aio_context(blk);
19765433c24fSMax Reitz     if (state->aio_context != blk_get_aio_context(target)) {
1977bd8baecdSFam Zheng         state->aio_context = NULL;
1978bd8baecdSFam Zheng         error_setg(errp, "Backup between two IO threads is not implemented");
1979bd8baecdSFam Zheng         return;
1980bd8baecdSFam Zheng     }
1981bd8baecdSFam Zheng     aio_context_acquire(state->aio_context);
1982ff52bf36SFam Zheng     state->bs = blk_bs(blk);
1983ff52bf36SFam Zheng     bdrv_drained_begin(state->bs);
1984bd8baecdSFam Zheng 
198578f51fdeSJohn Snow     do_blockdev_backup(backup->device, backup->target,
1986bd8baecdSFam Zheng                        backup->sync,
1987bd8baecdSFam Zheng                        backup->has_speed, backup->speed,
1988bd8baecdSFam Zheng                        backup->has_on_source_error, backup->on_source_error,
1989bd8baecdSFam Zheng                        backup->has_on_target_error, backup->on_target_error,
199094d16a64SJohn Snow                        common->block_job_txn, &local_err);
1991bd8baecdSFam Zheng     if (local_err) {
1992bd8baecdSFam Zheng         error_propagate(errp, local_err);
1993bd8baecdSFam Zheng         return;
1994bd8baecdSFam Zheng     }
1995bd8baecdSFam Zheng 
1996bd8baecdSFam Zheng     state->job = state->bs->job;
1997bd8baecdSFam Zheng }
1998bd8baecdSFam Zheng 
199950f43f0fSJohn Snow static void blockdev_backup_abort(BlkActionState *common)
2000bd8baecdSFam Zheng {
2001bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2002bd8baecdSFam Zheng     BlockDriverState *bs = state->bs;
2003bd8baecdSFam Zheng 
2004bd8baecdSFam Zheng     /* Only cancel if it's the job we started */
2005bd8baecdSFam Zheng     if (bs && bs->job && bs->job == state->job) {
2006bd8baecdSFam Zheng         block_job_cancel_sync(bs->job);
2007bd8baecdSFam Zheng     }
2008bd8baecdSFam Zheng }
2009bd8baecdSFam Zheng 
201050f43f0fSJohn Snow static void blockdev_backup_clean(BlkActionState *common)
2011bd8baecdSFam Zheng {
2012bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2013bd8baecdSFam Zheng 
2014bd8baecdSFam Zheng     if (state->aio_context) {
2015ff52bf36SFam Zheng         bdrv_drained_end(state->bs);
2016bd8baecdSFam Zheng         aio_context_release(state->aio_context);
2017bd8baecdSFam Zheng     }
2018bd8baecdSFam Zheng }
2019bd8baecdSFam Zheng 
2020df9a681dSFam Zheng typedef struct BlockDirtyBitmapState {
202150f43f0fSJohn Snow     BlkActionState common;
2022df9a681dSFam Zheng     BdrvDirtyBitmap *bitmap;
2023df9a681dSFam Zheng     BlockDriverState *bs;
2024df9a681dSFam Zheng     AioContext *aio_context;
2025df9a681dSFam Zheng     HBitmap *backup;
2026df9a681dSFam Zheng     bool prepared;
2027df9a681dSFam Zheng } BlockDirtyBitmapState;
2028df9a681dSFam Zheng 
202950f43f0fSJohn Snow static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2030df9a681dSFam Zheng                                            Error **errp)
2031df9a681dSFam Zheng {
2032df9a681dSFam Zheng     Error *local_err = NULL;
2033df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
2034df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2035df9a681dSFam Zheng                                              common, common);
2036df9a681dSFam Zheng 
203794d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
203894d16a64SJohn Snow         return;
203994d16a64SJohn Snow     }
204094d16a64SJohn Snow 
204132bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
2042df9a681dSFam Zheng     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2043df9a681dSFam Zheng     qmp_block_dirty_bitmap_add(action->node, action->name,
2044df9a681dSFam Zheng                                action->has_granularity, action->granularity,
2045df9a681dSFam Zheng                                &local_err);
2046df9a681dSFam Zheng 
2047df9a681dSFam Zheng     if (!local_err) {
2048df9a681dSFam Zheng         state->prepared = true;
2049df9a681dSFam Zheng     } else {
2050df9a681dSFam Zheng         error_propagate(errp, local_err);
2051df9a681dSFam Zheng     }
2052df9a681dSFam Zheng }
2053df9a681dSFam Zheng 
205450f43f0fSJohn Snow static void block_dirty_bitmap_add_abort(BlkActionState *common)
2055df9a681dSFam Zheng {
2056df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
2057df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2058df9a681dSFam Zheng                                              common, common);
2059df9a681dSFam Zheng 
206032bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
2061df9a681dSFam Zheng     /* Should not be able to fail: IF the bitmap was added via .prepare(),
2062df9a681dSFam Zheng      * then the node reference and bitmap name must have been valid.
2063df9a681dSFam Zheng      */
2064df9a681dSFam Zheng     if (state->prepared) {
2065df9a681dSFam Zheng         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2066df9a681dSFam Zheng     }
2067df9a681dSFam Zheng }
2068df9a681dSFam Zheng 
206950f43f0fSJohn Snow static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2070df9a681dSFam Zheng                                              Error **errp)
2071df9a681dSFam Zheng {
2072df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2073df9a681dSFam Zheng                                              common, common);
2074df9a681dSFam Zheng     BlockDirtyBitmap *action;
2075df9a681dSFam Zheng 
207694d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
207794d16a64SJohn Snow         return;
207894d16a64SJohn Snow     }
207994d16a64SJohn Snow 
208032bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_clear.data;
2081df9a681dSFam Zheng     state->bitmap = block_dirty_bitmap_lookup(action->node,
2082df9a681dSFam Zheng                                               action->name,
2083df9a681dSFam Zheng                                               &state->bs,
2084df9a681dSFam Zheng                                               &state->aio_context,
2085df9a681dSFam Zheng                                               errp);
2086df9a681dSFam Zheng     if (!state->bitmap) {
2087df9a681dSFam Zheng         return;
2088df9a681dSFam Zheng     }
2089df9a681dSFam Zheng 
2090df9a681dSFam Zheng     if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2091df9a681dSFam Zheng         error_setg(errp, "Cannot modify a frozen bitmap");
2092df9a681dSFam Zheng         return;
2093df9a681dSFam Zheng     } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2094df9a681dSFam Zheng         error_setg(errp, "Cannot clear a disabled bitmap");
2095df9a681dSFam Zheng         return;
2096df9a681dSFam Zheng     }
2097df9a681dSFam Zheng 
2098df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2099df9a681dSFam Zheng     /* AioContext is released in .clean() */
2100df9a681dSFam Zheng }
2101df9a681dSFam Zheng 
210250f43f0fSJohn Snow static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2103df9a681dSFam Zheng {
2104df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2105df9a681dSFam Zheng                                              common, common);
2106df9a681dSFam Zheng 
2107df9a681dSFam Zheng     bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2108df9a681dSFam Zheng }
2109df9a681dSFam Zheng 
211050f43f0fSJohn Snow static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2111df9a681dSFam Zheng {
2112df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2113df9a681dSFam Zheng                                              common, common);
2114df9a681dSFam Zheng 
2115df9a681dSFam Zheng     hbitmap_free(state->backup);
2116df9a681dSFam Zheng }
2117df9a681dSFam Zheng 
211850f43f0fSJohn Snow static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2119df9a681dSFam Zheng {
2120df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2121df9a681dSFam Zheng                                              common, common);
2122df9a681dSFam Zheng 
2123df9a681dSFam Zheng     if (state->aio_context) {
2124df9a681dSFam Zheng         aio_context_release(state->aio_context);
2125df9a681dSFam Zheng     }
2126df9a681dSFam Zheng }
2127df9a681dSFam Zheng 
212850f43f0fSJohn Snow static void abort_prepare(BlkActionState *common, Error **errp)
212978b18b78SStefan Hajnoczi {
213078b18b78SStefan Hajnoczi     error_setg(errp, "Transaction aborted using Abort action");
213178b18b78SStefan Hajnoczi }
213278b18b78SStefan Hajnoczi 
213350f43f0fSJohn Snow static void abort_commit(BlkActionState *common)
213478b18b78SStefan Hajnoczi {
2135dfc6f865SStefan Weil     g_assert_not_reached(); /* this action never succeeds */
213678b18b78SStefan Hajnoczi }
213778b18b78SStefan Hajnoczi 
213850f43f0fSJohn Snow static const BlkActionOps actions[] = {
213943de7e2dSAlberto Garcia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
214043de7e2dSAlberto Garcia         .instance_size = sizeof(ExternalSnapshotState),
214143de7e2dSAlberto Garcia         .prepare  = external_snapshot_prepare,
214243de7e2dSAlberto Garcia         .commit   = external_snapshot_commit,
214343de7e2dSAlberto Garcia         .abort = external_snapshot_abort,
21444ad6f3dbSAlberto Garcia         .clean = external_snapshot_clean,
214543de7e2dSAlberto Garcia     },
2146c8a83e85SKevin Wolf     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2147ba5d6ab6SStefan Hajnoczi         .instance_size = sizeof(ExternalSnapshotState),
2148ba0c86a3SWenchao Xia         .prepare  = external_snapshot_prepare,
2149ba0c86a3SWenchao Xia         .commit   = external_snapshot_commit,
2150ba0c86a3SWenchao Xia         .abort = external_snapshot_abort,
2151da763e83SFam Zheng         .clean = external_snapshot_clean,
2152ba0c86a3SWenchao Xia     },
21533037f364SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
21543037f364SStefan Hajnoczi         .instance_size = sizeof(DriveBackupState),
21553037f364SStefan Hajnoczi         .prepare = drive_backup_prepare,
21563037f364SStefan Hajnoczi         .abort = drive_backup_abort,
21575d6e96efSStefan Hajnoczi         .clean = drive_backup_clean,
21583037f364SStefan Hajnoczi     },
2159bd8baecdSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2160bd8baecdSFam Zheng         .instance_size = sizeof(BlockdevBackupState),
2161bd8baecdSFam Zheng         .prepare = blockdev_backup_prepare,
2162bd8baecdSFam Zheng         .abort = blockdev_backup_abort,
2163bd8baecdSFam Zheng         .clean = blockdev_backup_clean,
2164bd8baecdSFam Zheng     },
216578b18b78SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_ABORT] = {
216650f43f0fSJohn Snow         .instance_size = sizeof(BlkActionState),
216778b18b78SStefan Hajnoczi         .prepare = abort_prepare,
216878b18b78SStefan Hajnoczi         .commit = abort_commit,
216978b18b78SStefan Hajnoczi     },
2170bbe86010SWenchao Xia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2171bbe86010SWenchao Xia         .instance_size = sizeof(InternalSnapshotState),
2172bbe86010SWenchao Xia         .prepare  = internal_snapshot_prepare,
2173bbe86010SWenchao Xia         .abort = internal_snapshot_abort,
21745d6e96efSStefan Hajnoczi         .clean = internal_snapshot_clean,
2175bbe86010SWenchao Xia     },
2176df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2177df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2178df9a681dSFam Zheng         .prepare = block_dirty_bitmap_add_prepare,
2179df9a681dSFam Zheng         .abort = block_dirty_bitmap_add_abort,
2180df9a681dSFam Zheng     },
2181df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2182df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2183df9a681dSFam Zheng         .prepare = block_dirty_bitmap_clear_prepare,
2184df9a681dSFam Zheng         .commit = block_dirty_bitmap_clear_commit,
2185df9a681dSFam Zheng         .abort = block_dirty_bitmap_clear_abort,
2186df9a681dSFam Zheng         .clean = block_dirty_bitmap_clear_clean,
2187df9a681dSFam Zheng     }
2188ba0c86a3SWenchao Xia };
2189ba0c86a3SWenchao Xia 
219094d16a64SJohn Snow /**
219194d16a64SJohn Snow  * Allocate a TransactionProperties structure if necessary, and fill
219294d16a64SJohn Snow  * that structure with desired defaults if they are unset.
219394d16a64SJohn Snow  */
219494d16a64SJohn Snow static TransactionProperties *get_transaction_properties(
219594d16a64SJohn Snow     TransactionProperties *props)
219694d16a64SJohn Snow {
219794d16a64SJohn Snow     if (!props) {
219894d16a64SJohn Snow         props = g_new0(TransactionProperties, 1);
219994d16a64SJohn Snow     }
220094d16a64SJohn Snow 
220194d16a64SJohn Snow     if (!props->has_completion_mode) {
220294d16a64SJohn Snow         props->has_completion_mode = true;
220394d16a64SJohn Snow         props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
220494d16a64SJohn Snow     }
220594d16a64SJohn Snow 
220694d16a64SJohn Snow     return props;
220794d16a64SJohn Snow }
220894d16a64SJohn Snow 
22098802d1fdSJeff Cody /*
2210b756b9ceSStefan Hajnoczi  * 'Atomic' group operations.  The operations are performed as a set, and if
2211b756b9ceSStefan Hajnoczi  * any fail then we roll back all operations in the group.
22128802d1fdSJeff Cody  */
221394d16a64SJohn Snow void qmp_transaction(TransactionActionList *dev_list,
221494d16a64SJohn Snow                      bool has_props,
221594d16a64SJohn Snow                      struct TransactionProperties *props,
221694d16a64SJohn Snow                      Error **errp)
22178802d1fdSJeff Cody {
2218c8a83e85SKevin Wolf     TransactionActionList *dev_entry = dev_list;
221994d16a64SJohn Snow     BlockJobTxn *block_job_txn = NULL;
222050f43f0fSJohn Snow     BlkActionState *state, *next;
222143e17041SLuiz Capitulino     Error *local_err = NULL;
22228802d1fdSJeff Cody 
222350f43f0fSJohn Snow     QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
22248802d1fdSJeff Cody     QSIMPLEQ_INIT(&snap_bdrv_states);
22258802d1fdSJeff Cody 
222694d16a64SJohn Snow     /* Does this transaction get canceled as a group on failure?
222794d16a64SJohn Snow      * If not, we don't really need to make a BlockJobTxn.
222894d16a64SJohn Snow      */
222994d16a64SJohn Snow     props = get_transaction_properties(props);
223094d16a64SJohn Snow     if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
223194d16a64SJohn Snow         block_job_txn = block_job_txn_new();
223294d16a64SJohn Snow     }
223394d16a64SJohn Snow 
2234b756b9ceSStefan Hajnoczi     /* drain all i/o before any operations */
22358802d1fdSJeff Cody     bdrv_drain_all();
22368802d1fdSJeff Cody 
2237b756b9ceSStefan Hajnoczi     /* We don't do anything in this loop that commits us to the operations */
22388802d1fdSJeff Cody     while (NULL != dev_entry) {
2239c8a83e85SKevin Wolf         TransactionAction *dev_info = NULL;
224050f43f0fSJohn Snow         const BlkActionOps *ops;
224152e7c241SPaolo Bonzini 
22428802d1fdSJeff Cody         dev_info = dev_entry->value;
22438802d1fdSJeff Cody         dev_entry = dev_entry->next;
22448802d1fdSJeff Cody 
22456a8f9661SEric Blake         assert(dev_info->type < ARRAY_SIZE(actions));
2246ba0c86a3SWenchao Xia 
22476a8f9661SEric Blake         ops = &actions[dev_info->type];
2248aa3fe714SMax Reitz         assert(ops->instance_size > 0);
2249aa3fe714SMax Reitz 
2250ba5d6ab6SStefan Hajnoczi         state = g_malloc0(ops->instance_size);
2251ba5d6ab6SStefan Hajnoczi         state->ops = ops;
2252ba5d6ab6SStefan Hajnoczi         state->action = dev_info;
225394d16a64SJohn Snow         state->block_job_txn = block_job_txn;
225494d16a64SJohn Snow         state->txn_props = props;
2255ba5d6ab6SStefan Hajnoczi         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
22568802d1fdSJeff Cody 
2257ba5d6ab6SStefan Hajnoczi         state->ops->prepare(state, &local_err);
225884d18f06SMarkus Armbruster         if (local_err) {
22599b9877eeSWenchao Xia             error_propagate(errp, local_err);
22609b9877eeSWenchao Xia             goto delete_and_fail;
22619b9877eeSWenchao Xia         }
226252e7c241SPaolo Bonzini     }
22638802d1fdSJeff Cody 
2264ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2265f9ea81e8SStefan Hajnoczi         if (state->ops->commit) {
2266ba5d6ab6SStefan Hajnoczi             state->ops->commit(state);
22678802d1fdSJeff Cody         }
2268f9ea81e8SStefan Hajnoczi     }
22698802d1fdSJeff Cody 
22708802d1fdSJeff Cody     /* success */
22718802d1fdSJeff Cody     goto exit;
22728802d1fdSJeff Cody 
22738802d1fdSJeff Cody delete_and_fail:
2274b756b9ceSStefan Hajnoczi     /* failure, and it is all-or-none; roll back all operations */
2275ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2276ba5d6ab6SStefan Hajnoczi         if (state->ops->abort) {
2277ba5d6ab6SStefan Hajnoczi             state->ops->abort(state);
2278ba0c86a3SWenchao Xia         }
22798802d1fdSJeff Cody     }
22808802d1fdSJeff Cody exit:
2281ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2282ba5d6ab6SStefan Hajnoczi         if (state->ops->clean) {
2283ba5d6ab6SStefan Hajnoczi             state->ops->clean(state);
2284ba0c86a3SWenchao Xia         }
2285ba5d6ab6SStefan Hajnoczi         g_free(state);
22868802d1fdSJeff Cody     }
228794d16a64SJohn Snow     if (!has_props) {
228894d16a64SJohn Snow         qapi_free_TransactionProperties(props);
228994d16a64SJohn Snow     }
229094d16a64SJohn Snow     block_job_txn_unref(block_job_txn);
22918802d1fdSJeff Cody }
22928802d1fdSJeff Cody 
2293c245b6a3SLuiz Capitulino void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2294666daa68SMarkus Armbruster {
229538f54bd1SMax Reitz     Error *local_err = NULL;
2296666daa68SMarkus Armbruster 
229738f54bd1SMax Reitz     qmp_blockdev_open_tray(device, has_force, force, &local_err);
229838f54bd1SMax Reitz     if (local_err) {
229938f54bd1SMax Reitz         error_propagate(errp, local_err);
2300c245b6a3SLuiz Capitulino         return;
2301666daa68SMarkus Armbruster     }
230292d48558SLuiz Capitulino 
23036e0abc25SMax Reitz     qmp_x_blockdev_remove_medium(device, errp);
2304666daa68SMarkus Armbruster }
2305666daa68SMarkus Armbruster 
230612d3ba82SBenoît Canet void qmp_block_passwd(bool has_device, const char *device,
230712d3ba82SBenoît Canet                       bool has_node_name, const char *node_name,
230812d3ba82SBenoît Canet                       const char *password, Error **errp)
2309666daa68SMarkus Armbruster {
231012d3ba82SBenoît Canet     Error *local_err = NULL;
2311666daa68SMarkus Armbruster     BlockDriverState *bs;
2312e3442099SStefan Hajnoczi     AioContext *aio_context;
2313666daa68SMarkus Armbruster 
231412d3ba82SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
231512d3ba82SBenoît Canet                         has_node_name ? node_name : NULL,
231612d3ba82SBenoît Canet                         &local_err);
231784d18f06SMarkus Armbruster     if (local_err) {
231812d3ba82SBenoît Canet         error_propagate(errp, local_err);
2319a4dea8a9SLuiz Capitulino         return;
2320666daa68SMarkus Armbruster     }
2321666daa68SMarkus Armbruster 
2322e3442099SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
2323e3442099SStefan Hajnoczi     aio_context_acquire(aio_context);
2324e3442099SStefan Hajnoczi 
23254d2855a3SMarkus Armbruster     bdrv_add_key(bs, password, errp);
2326666daa68SMarkus Armbruster 
2327e3442099SStefan Hajnoczi     aio_context_release(aio_context);
2328e3442099SStefan Hajnoczi }
2329e3442099SStefan Hajnoczi 
23307d8a9f71SMax Reitz void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
23317d8a9f71SMax Reitz                             Error **errp)
23327d8a9f71SMax Reitz {
23337d8a9f71SMax Reitz     BlockBackend *blk;
23347d8a9f71SMax Reitz     bool locked;
23357d8a9f71SMax Reitz 
23367d8a9f71SMax Reitz     if (!has_force) {
23377d8a9f71SMax Reitz         force = false;
23387d8a9f71SMax Reitz     }
23397d8a9f71SMax Reitz 
23407d8a9f71SMax Reitz     blk = blk_by_name(device);
23417d8a9f71SMax Reitz     if (!blk) {
23427d8a9f71SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
23437d8a9f71SMax Reitz                   "Device '%s' not found", device);
23447d8a9f71SMax Reitz         return;
23457d8a9f71SMax Reitz     }
23467d8a9f71SMax Reitz 
23477d8a9f71SMax Reitz     if (!blk_dev_has_removable_media(blk)) {
23487d8a9f71SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
23497d8a9f71SMax Reitz         return;
23507d8a9f71SMax Reitz     }
23517d8a9f71SMax Reitz 
235212c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
235312c7ec87SMax Reitz         /* Ignore this command on tray-less devices */
235412c7ec87SMax Reitz         return;
235512c7ec87SMax Reitz     }
235612c7ec87SMax Reitz 
23577d8a9f71SMax Reitz     if (blk_dev_is_tray_open(blk)) {
23587d8a9f71SMax Reitz         return;
23597d8a9f71SMax Reitz     }
23607d8a9f71SMax Reitz 
23617d8a9f71SMax Reitz     locked = blk_dev_is_medium_locked(blk);
23627d8a9f71SMax Reitz     if (locked) {
23637d8a9f71SMax Reitz         blk_dev_eject_request(blk, force);
23647d8a9f71SMax Reitz     }
23657d8a9f71SMax Reitz 
23667d8a9f71SMax Reitz     if (!locked || force) {
23677d8a9f71SMax Reitz         blk_dev_change_media_cb(blk, false);
23687d8a9f71SMax Reitz     }
23697d8a9f71SMax Reitz }
23707d8a9f71SMax Reitz 
2371abaaf59dSMax Reitz void qmp_blockdev_close_tray(const char *device, Error **errp)
2372abaaf59dSMax Reitz {
2373abaaf59dSMax Reitz     BlockBackend *blk;
2374abaaf59dSMax Reitz 
2375abaaf59dSMax Reitz     blk = blk_by_name(device);
2376abaaf59dSMax Reitz     if (!blk) {
2377abaaf59dSMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2378abaaf59dSMax Reitz                   "Device '%s' not found", device);
2379abaaf59dSMax Reitz         return;
2380abaaf59dSMax Reitz     }
2381abaaf59dSMax Reitz 
2382abaaf59dSMax Reitz     if (!blk_dev_has_removable_media(blk)) {
2383abaaf59dSMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
2384abaaf59dSMax Reitz         return;
2385abaaf59dSMax Reitz     }
2386abaaf59dSMax Reitz 
238712c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
238812c7ec87SMax Reitz         /* Ignore this command on tray-less devices */
238912c7ec87SMax Reitz         return;
239012c7ec87SMax Reitz     }
239112c7ec87SMax Reitz 
2392abaaf59dSMax Reitz     if (!blk_dev_is_tray_open(blk)) {
2393abaaf59dSMax Reitz         return;
2394abaaf59dSMax Reitz     }
2395abaaf59dSMax Reitz 
2396abaaf59dSMax Reitz     blk_dev_change_media_cb(blk, true);
2397abaaf59dSMax Reitz }
2398abaaf59dSMax Reitz 
23996e0abc25SMax Reitz void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
24002814f672SMax Reitz {
24012814f672SMax Reitz     BlockBackend *blk;
24022814f672SMax Reitz     BlockDriverState *bs;
24032814f672SMax Reitz     AioContext *aio_context;
24042814f672SMax Reitz     bool has_device;
24052814f672SMax Reitz 
24062814f672SMax Reitz     blk = blk_by_name(device);
24072814f672SMax Reitz     if (!blk) {
24082814f672SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
24092814f672SMax Reitz                   "Device '%s' not found", device);
24102814f672SMax Reitz         return;
24112814f672SMax Reitz     }
24122814f672SMax Reitz 
24132814f672SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
24142814f672SMax Reitz     has_device = blk_get_attached_dev(blk);
24152814f672SMax Reitz 
24162814f672SMax Reitz     if (has_device && !blk_dev_has_removable_media(blk)) {
24172814f672SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
24182814f672SMax Reitz         return;
24192814f672SMax Reitz     }
24202814f672SMax Reitz 
242112c7ec87SMax Reitz     if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
24222814f672SMax Reitz         error_setg(errp, "Tray of device '%s' is not open", device);
24232814f672SMax Reitz         return;
24242814f672SMax Reitz     }
24252814f672SMax Reitz 
24262814f672SMax Reitz     bs = blk_bs(blk);
24272814f672SMax Reitz     if (!bs) {
24282814f672SMax Reitz         return;
24292814f672SMax Reitz     }
24302814f672SMax Reitz 
24312814f672SMax Reitz     aio_context = bdrv_get_aio_context(bs);
24322814f672SMax Reitz     aio_context_acquire(aio_context);
24332814f672SMax Reitz 
24342814f672SMax Reitz     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
24352814f672SMax Reitz         goto out;
24362814f672SMax Reitz     }
24372814f672SMax Reitz 
24382814f672SMax Reitz     blk_remove_bs(blk);
24392814f672SMax Reitz 
244012c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
244112c7ec87SMax Reitz         /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
244212c7ec87SMax Reitz          * called at all); therefore, the medium needs to be ejected here.
244312c7ec87SMax Reitz          * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
244412c7ec87SMax Reitz          * value passed here (i.e. false). */
244512c7ec87SMax Reitz         blk_dev_change_media_cb(blk, false);
244612c7ec87SMax Reitz     }
244712c7ec87SMax Reitz 
24482814f672SMax Reitz out:
24492814f672SMax Reitz     aio_context_release(aio_context);
24502814f672SMax Reitz }
24512814f672SMax Reitz 
2452d1299882SMax Reitz static void qmp_blockdev_insert_anon_medium(const char *device,
2453d1299882SMax Reitz                                             BlockDriverState *bs, Error **errp)
2454d1299882SMax Reitz {
2455d1299882SMax Reitz     BlockBackend *blk;
2456d1299882SMax Reitz     bool has_device;
2457d1299882SMax Reitz 
2458d1299882SMax Reitz     blk = blk_by_name(device);
2459d1299882SMax Reitz     if (!blk) {
2460d1299882SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2461d1299882SMax Reitz                   "Device '%s' not found", device);
2462d1299882SMax Reitz         return;
2463d1299882SMax Reitz     }
2464d1299882SMax Reitz 
2465d1299882SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
2466d1299882SMax Reitz     has_device = blk_get_attached_dev(blk);
2467d1299882SMax Reitz 
2468d1299882SMax Reitz     if (has_device && !blk_dev_has_removable_media(blk)) {
2469d1299882SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
2470d1299882SMax Reitz         return;
2471d1299882SMax Reitz     }
2472d1299882SMax Reitz 
247312c7ec87SMax Reitz     if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2474d1299882SMax Reitz         error_setg(errp, "Tray of device '%s' is not open", device);
2475d1299882SMax Reitz         return;
2476d1299882SMax Reitz     }
2477d1299882SMax Reitz 
2478d1299882SMax Reitz     if (blk_bs(blk)) {
2479d1299882SMax Reitz         error_setg(errp, "There already is a medium in device '%s'", device);
2480d1299882SMax Reitz         return;
2481d1299882SMax Reitz     }
2482d1299882SMax Reitz 
2483d1299882SMax Reitz     blk_insert_bs(blk, bs);
2484d1299882SMax Reitz 
248512c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
248612c7ec87SMax Reitz         /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
248712c7ec87SMax Reitz          * called at all); therefore, the medium needs to be pushed into the
248812c7ec87SMax Reitz          * slot here.
248912c7ec87SMax Reitz          * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
249012c7ec87SMax Reitz          * value passed here (i.e. true). */
249112c7ec87SMax Reitz         blk_dev_change_media_cb(blk, true);
249212c7ec87SMax Reitz     }
2493d1299882SMax Reitz }
2494d1299882SMax Reitz 
24956e0abc25SMax Reitz void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2496d1299882SMax Reitz                                   Error **errp)
2497d1299882SMax Reitz {
2498d1299882SMax Reitz     BlockDriverState *bs;
2499d1299882SMax Reitz 
2500d1299882SMax Reitz     bs = bdrv_find_node(node_name);
2501d1299882SMax Reitz     if (!bs) {
2502d1299882SMax Reitz         error_setg(errp, "Node '%s' not found", node_name);
2503d1299882SMax Reitz         return;
2504d1299882SMax Reitz     }
2505d1299882SMax Reitz 
2506d1299882SMax Reitz     if (bs->blk) {
2507d1299882SMax Reitz         error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2508d1299882SMax Reitz                    blk_name(bs->blk));
2509d1299882SMax Reitz         return;
2510d1299882SMax Reitz     }
2511d1299882SMax Reitz 
2512d1299882SMax Reitz     qmp_blockdev_insert_anon_medium(device, bs, errp);
2513d1299882SMax Reitz }
2514d1299882SMax Reitz 
251524fb4133SMax Reitz void qmp_blockdev_change_medium(const char *device, const char *filename,
251624fb4133SMax Reitz                                 bool has_format, const char *format,
251739ff43d9SMax Reitz                                 bool has_read_only,
251839ff43d9SMax Reitz                                 BlockdevChangeReadOnlyMode read_only,
251924fb4133SMax Reitz                                 Error **errp)
2520de2c6c05SMax Reitz {
2521de2c6c05SMax Reitz     BlockBackend *blk;
2522de2c6c05SMax Reitz     BlockDriverState *medium_bs = NULL;
2523de2c6c05SMax Reitz     int bdrv_flags, ret;
2524de2c6c05SMax Reitz     QDict *options = NULL;
2525de2c6c05SMax Reitz     Error *err = NULL;
2526de2c6c05SMax Reitz 
2527de2c6c05SMax Reitz     blk = blk_by_name(device);
2528de2c6c05SMax Reitz     if (!blk) {
2529de2c6c05SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2530de2c6c05SMax Reitz                   "Device '%s' not found", device);
2531de2c6c05SMax Reitz         goto fail;
2532de2c6c05SMax Reitz     }
2533de2c6c05SMax Reitz 
2534de2c6c05SMax Reitz     if (blk_bs(blk)) {
2535de2c6c05SMax Reitz         blk_update_root_state(blk);
2536de2c6c05SMax Reitz     }
2537de2c6c05SMax Reitz 
2538de2c6c05SMax Reitz     bdrv_flags = blk_get_open_flags_from_root_state(blk);
2539156abc2fSAlyssa Milburn     bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2540156abc2fSAlyssa Milburn         BDRV_O_PROTOCOL);
2541de2c6c05SMax Reitz 
254239ff43d9SMax Reitz     if (!has_read_only) {
254339ff43d9SMax Reitz         read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
254439ff43d9SMax Reitz     }
254539ff43d9SMax Reitz 
254639ff43d9SMax Reitz     switch (read_only) {
254739ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
254839ff43d9SMax Reitz         break;
254939ff43d9SMax Reitz 
255039ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
255139ff43d9SMax Reitz         bdrv_flags &= ~BDRV_O_RDWR;
255239ff43d9SMax Reitz         break;
255339ff43d9SMax Reitz 
255439ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
255539ff43d9SMax Reitz         bdrv_flags |= BDRV_O_RDWR;
255639ff43d9SMax Reitz         break;
255739ff43d9SMax Reitz 
255839ff43d9SMax Reitz     default:
255939ff43d9SMax Reitz         abort();
256039ff43d9SMax Reitz     }
256139ff43d9SMax Reitz 
256224fb4133SMax Reitz     if (has_format) {
2563de2c6c05SMax Reitz         options = qdict_new();
2564de2c6c05SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
2565de2c6c05SMax Reitz     }
2566de2c6c05SMax Reitz 
2567de2c6c05SMax Reitz     assert(!medium_bs);
2568de2c6c05SMax Reitz     ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2569de2c6c05SMax Reitz     if (ret < 0) {
2570de2c6c05SMax Reitz         goto fail;
2571de2c6c05SMax Reitz     }
2572de2c6c05SMax Reitz 
2573de2c6c05SMax Reitz     bdrv_add_key(medium_bs, NULL, &err);
2574de2c6c05SMax Reitz     if (err) {
2575de2c6c05SMax Reitz         error_propagate(errp, err);
2576de2c6c05SMax Reitz         goto fail;
2577de2c6c05SMax Reitz     }
2578de2c6c05SMax Reitz 
2579de2c6c05SMax Reitz     qmp_blockdev_open_tray(device, false, false, &err);
2580de2c6c05SMax Reitz     if (err) {
2581de2c6c05SMax Reitz         error_propagate(errp, err);
2582de2c6c05SMax Reitz         goto fail;
2583de2c6c05SMax Reitz     }
2584de2c6c05SMax Reitz 
25856e0abc25SMax Reitz     qmp_x_blockdev_remove_medium(device, &err);
2586de2c6c05SMax Reitz     if (err) {
2587de2c6c05SMax Reitz         error_propagate(errp, err);
2588de2c6c05SMax Reitz         goto fail;
2589de2c6c05SMax Reitz     }
2590de2c6c05SMax Reitz 
2591de2c6c05SMax Reitz     qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2592de2c6c05SMax Reitz     if (err) {
2593de2c6c05SMax Reitz         error_propagate(errp, err);
2594de2c6c05SMax Reitz         goto fail;
2595de2c6c05SMax Reitz     }
2596de2c6c05SMax Reitz 
2597a5614993SKevin Wolf     blk_apply_root_state(blk, medium_bs);
2598a5614993SKevin Wolf 
2599de2c6c05SMax Reitz     qmp_blockdev_close_tray(device, errp);
2600de2c6c05SMax Reitz 
2601de2c6c05SMax Reitz fail:
2602de2c6c05SMax Reitz     /* If the medium has been inserted, the device has its own reference, so
2603de2c6c05SMax Reitz      * ours must be relinquished; and if it has not been inserted successfully,
2604de2c6c05SMax Reitz      * the reference must be relinquished anyway */
2605de2c6c05SMax Reitz     bdrv_unref(medium_bs);
2606de2c6c05SMax Reitz }
2607de2c6c05SMax Reitz 
2608727f005eSZhi Yong Wu /* throttling disk I/O limits */
260980047da5SLuiz Capitulino void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
26103e9fab69SBenoît Canet                                int64_t bps_wr,
26113e9fab69SBenoît Canet                                int64_t iops,
26123e9fab69SBenoît Canet                                int64_t iops_rd,
26133e9fab69SBenoît Canet                                int64_t iops_wr,
26143e9fab69SBenoît Canet                                bool has_bps_max,
26153e9fab69SBenoît Canet                                int64_t bps_max,
26163e9fab69SBenoît Canet                                bool has_bps_rd_max,
26173e9fab69SBenoît Canet                                int64_t bps_rd_max,
26183e9fab69SBenoît Canet                                bool has_bps_wr_max,
26193e9fab69SBenoît Canet                                int64_t bps_wr_max,
26203e9fab69SBenoît Canet                                bool has_iops_max,
26213e9fab69SBenoît Canet                                int64_t iops_max,
26223e9fab69SBenoît Canet                                bool has_iops_rd_max,
26233e9fab69SBenoît Canet                                int64_t iops_rd_max,
26243e9fab69SBenoît Canet                                bool has_iops_wr_max,
26252024c1dfSBenoît Canet                                int64_t iops_wr_max,
2626dce13204SAlberto Garcia                                bool has_bps_max_length,
2627dce13204SAlberto Garcia                                int64_t bps_max_length,
2628dce13204SAlberto Garcia                                bool has_bps_rd_max_length,
2629dce13204SAlberto Garcia                                int64_t bps_rd_max_length,
2630dce13204SAlberto Garcia                                bool has_bps_wr_max_length,
2631dce13204SAlberto Garcia                                int64_t bps_wr_max_length,
2632dce13204SAlberto Garcia                                bool has_iops_max_length,
2633dce13204SAlberto Garcia                                int64_t iops_max_length,
2634dce13204SAlberto Garcia                                bool has_iops_rd_max_length,
2635dce13204SAlberto Garcia                                int64_t iops_rd_max_length,
2636dce13204SAlberto Garcia                                bool has_iops_wr_max_length,
2637dce13204SAlberto Garcia                                int64_t iops_wr_max_length,
26382024c1dfSBenoît Canet                                bool has_iops_size,
263976f4afb4SAlberto Garcia                                int64_t iops_size,
264076f4afb4SAlberto Garcia                                bool has_group,
264176f4afb4SAlberto Garcia                                const char *group, Error **errp)
2642727f005eSZhi Yong Wu {
2643cc0681c4SBenoît Canet     ThrottleConfig cfg;
2644727f005eSZhi Yong Wu     BlockDriverState *bs;
2645a0e8544cSFam Zheng     BlockBackend *blk;
2646b15446fdSStefan Hajnoczi     AioContext *aio_context;
2647727f005eSZhi Yong Wu 
2648a0e8544cSFam Zheng     blk = blk_by_name(device);
2649a0e8544cSFam Zheng     if (!blk) {
265075158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
265175158ebbSMarkus Armbruster                   "Device '%s' not found", device);
265280047da5SLuiz Capitulino         return;
2653727f005eSZhi Yong Wu     }
26545433c24fSMax Reitz 
26555433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
26565433c24fSMax Reitz     aio_context_acquire(aio_context);
26575433c24fSMax Reitz 
2658a0e8544cSFam Zheng     bs = blk_bs(blk);
26595433c24fSMax Reitz     if (!bs) {
26605433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
26615433c24fSMax Reitz         goto out;
26625433c24fSMax Reitz     }
2663727f005eSZhi Yong Wu 
266476b22320SKevin Wolf     /* The BlockBackend must be the only parent */
266576b22320SKevin Wolf     assert(QLIST_FIRST(&bs->parents));
266676b22320SKevin Wolf     if (QLIST_NEXT(QLIST_FIRST(&bs->parents), next_parent)) {
266776b22320SKevin Wolf         error_setg(errp, "Cannot throttle device with multiple parents");
266876b22320SKevin Wolf         goto out;
266976b22320SKevin Wolf     }
267076b22320SKevin Wolf 
26711588ab5dSAlberto Garcia     throttle_config_init(&cfg);
2672cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2673cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;
2674cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2675727f005eSZhi Yong Wu 
2676cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2677cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;
2678cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2679cc0681c4SBenoît Canet 
26803e9fab69SBenoît Canet     if (has_bps_max) {
26813e9fab69SBenoît Canet         cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
26823e9fab69SBenoît Canet     }
26833e9fab69SBenoît Canet     if (has_bps_rd_max) {
26843e9fab69SBenoît Canet         cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
26853e9fab69SBenoît Canet     }
26863e9fab69SBenoît Canet     if (has_bps_wr_max) {
26873e9fab69SBenoît Canet         cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
26883e9fab69SBenoît Canet     }
26893e9fab69SBenoît Canet     if (has_iops_max) {
26903e9fab69SBenoît Canet         cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
26913e9fab69SBenoît Canet     }
26923e9fab69SBenoît Canet     if (has_iops_rd_max) {
26933e9fab69SBenoît Canet         cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
26943e9fab69SBenoît Canet     }
26953e9fab69SBenoît Canet     if (has_iops_wr_max) {
26963e9fab69SBenoît Canet         cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
26973e9fab69SBenoît Canet     }
2698cc0681c4SBenoît Canet 
2699dce13204SAlberto Garcia     if (has_bps_max_length) {
2700dce13204SAlberto Garcia         cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = bps_max_length;
2701dce13204SAlberto Garcia     }
2702dce13204SAlberto Garcia     if (has_bps_rd_max_length) {
2703dce13204SAlberto Garcia         cfg.buckets[THROTTLE_BPS_READ].burst_length = bps_rd_max_length;
2704dce13204SAlberto Garcia     }
2705dce13204SAlberto Garcia     if (has_bps_wr_max_length) {
2706dce13204SAlberto Garcia         cfg.buckets[THROTTLE_BPS_WRITE].burst_length = bps_wr_max_length;
2707dce13204SAlberto Garcia     }
2708dce13204SAlberto Garcia     if (has_iops_max_length) {
2709dce13204SAlberto Garcia         cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = iops_max_length;
2710dce13204SAlberto Garcia     }
2711dce13204SAlberto Garcia     if (has_iops_rd_max_length) {
2712dce13204SAlberto Garcia         cfg.buckets[THROTTLE_OPS_READ].burst_length = iops_rd_max_length;
2713dce13204SAlberto Garcia     }
2714dce13204SAlberto Garcia     if (has_iops_wr_max_length) {
2715dce13204SAlberto Garcia         cfg.buckets[THROTTLE_OPS_WRITE].burst_length = iops_wr_max_length;
2716dce13204SAlberto Garcia     }
2717dce13204SAlberto Garcia 
27182024c1dfSBenoît Canet     if (has_iops_size) {
27192024c1dfSBenoît Canet         cfg.op_size = iops_size;
27202024c1dfSBenoît Canet     }
2721cc0681c4SBenoît Canet 
2722d5851089SAlberto Garcia     if (!throttle_is_valid(&cfg, errp)) {
27235433c24fSMax Reitz         goto out;
2724727f005eSZhi Yong Wu     }
2725727f005eSZhi Yong Wu 
272676f4afb4SAlberto Garcia     if (throttle_enabled(&cfg)) {
272776f4afb4SAlberto Garcia         /* Enable I/O limits if they're not enabled yet, otherwise
272876f4afb4SAlberto Garcia          * just update the throttling group. */
2729*97148076SKevin Wolf         if (!blk_get_public(blk)->throttle_state) {
2730*97148076SKevin Wolf             blk_io_limits_enable(blk, has_group ? group : device);
273176f4afb4SAlberto Garcia         } else if (has_group) {
2732*97148076SKevin Wolf             blk_io_limits_update_group(blk, group);
2733727f005eSZhi Yong Wu         }
273476f4afb4SAlberto Garcia         /* Set the new throttling configuration */
2735*97148076SKevin Wolf         blk_set_io_limits(blk, &cfg);
2736*97148076SKevin Wolf     } else if (blk_get_public(blk)->throttle_state) {
273776f4afb4SAlberto Garcia         /* If all throttling settings are set to 0, disable I/O limits */
2738*97148076SKevin Wolf         blk_io_limits_disable(blk);
2739727f005eSZhi Yong Wu     }
2740b15446fdSStefan Hajnoczi 
27415433c24fSMax Reitz out:
2742b15446fdSStefan Hajnoczi     aio_context_release(aio_context);
2743727f005eSZhi Yong Wu }
2744727f005eSZhi Yong Wu 
2745341ebc2fSJohn Snow void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2746341ebc2fSJohn Snow                                 bool has_granularity, uint32_t granularity,
2747341ebc2fSJohn Snow                                 Error **errp)
2748341ebc2fSJohn Snow {
2749341ebc2fSJohn Snow     AioContext *aio_context;
2750341ebc2fSJohn Snow     BlockDriverState *bs;
2751341ebc2fSJohn Snow 
2752341ebc2fSJohn Snow     if (!name || name[0] == '\0') {
2753341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be empty");
2754341ebc2fSJohn Snow         return;
2755341ebc2fSJohn Snow     }
2756341ebc2fSJohn Snow 
2757341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, errp);
2758341ebc2fSJohn Snow     if (!bs) {
2759341ebc2fSJohn Snow         return;
2760341ebc2fSJohn Snow     }
2761341ebc2fSJohn Snow 
2762341ebc2fSJohn Snow     aio_context = bdrv_get_aio_context(bs);
2763341ebc2fSJohn Snow     aio_context_acquire(aio_context);
2764341ebc2fSJohn Snow 
2765341ebc2fSJohn Snow     if (has_granularity) {
2766341ebc2fSJohn Snow         if (granularity < 512 || !is_power_of_2(granularity)) {
2767341ebc2fSJohn Snow             error_setg(errp, "Granularity must be power of 2 "
2768341ebc2fSJohn Snow                              "and at least 512");
2769341ebc2fSJohn Snow             goto out;
2770341ebc2fSJohn Snow         }
2771341ebc2fSJohn Snow     } else {
2772341ebc2fSJohn Snow         /* Default to cluster size, if available: */
2773341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(bs);
2774341ebc2fSJohn Snow     }
2775341ebc2fSJohn Snow 
2776341ebc2fSJohn Snow     bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2777341ebc2fSJohn Snow 
2778341ebc2fSJohn Snow  out:
2779341ebc2fSJohn Snow     aio_context_release(aio_context);
2780341ebc2fSJohn Snow }
2781341ebc2fSJohn Snow 
2782341ebc2fSJohn Snow void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2783341ebc2fSJohn Snow                                    Error **errp)
2784341ebc2fSJohn Snow {
2785341ebc2fSJohn Snow     AioContext *aio_context;
2786341ebc2fSJohn Snow     BlockDriverState *bs;
2787341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
2788341ebc2fSJohn Snow 
2789341ebc2fSJohn Snow     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2790341ebc2fSJohn Snow     if (!bitmap || !bs) {
2791341ebc2fSJohn Snow         return;
2792341ebc2fSJohn Snow     }
2793341ebc2fSJohn Snow 
27949bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
27959bd2b08fSJohn Snow         error_setg(errp,
27969bd2b08fSJohn Snow                    "Bitmap '%s' is currently frozen and cannot be removed",
27979bd2b08fSJohn Snow                    name);
27989bd2b08fSJohn Snow         goto out;
27999bd2b08fSJohn Snow     }
280020dca810SJohn Snow     bdrv_dirty_bitmap_make_anon(bitmap);
2801341ebc2fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
2802341ebc2fSJohn Snow 
28039bd2b08fSJohn Snow  out:
2804341ebc2fSJohn Snow     aio_context_release(aio_context);
2805341ebc2fSJohn Snow }
2806341ebc2fSJohn Snow 
2807e74e6b78SJohn Snow /**
2808e74e6b78SJohn Snow  * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2809e74e6b78SJohn Snow  * immediately after a full backup operation.
2810e74e6b78SJohn Snow  */
2811e74e6b78SJohn Snow void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2812e74e6b78SJohn Snow                                   Error **errp)
2813e74e6b78SJohn Snow {
2814e74e6b78SJohn Snow     AioContext *aio_context;
2815e74e6b78SJohn Snow     BdrvDirtyBitmap *bitmap;
2816e74e6b78SJohn Snow     BlockDriverState *bs;
2817e74e6b78SJohn Snow 
2818e74e6b78SJohn Snow     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2819e74e6b78SJohn Snow     if (!bitmap || !bs) {
2820e74e6b78SJohn Snow         return;
2821e74e6b78SJohn Snow     }
2822e74e6b78SJohn Snow 
2823e74e6b78SJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2824e74e6b78SJohn Snow         error_setg(errp,
2825e74e6b78SJohn Snow                    "Bitmap '%s' is currently frozen and cannot be modified",
2826e74e6b78SJohn Snow                    name);
2827e74e6b78SJohn Snow         goto out;
2828e74e6b78SJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2829e74e6b78SJohn Snow         error_setg(errp,
2830e74e6b78SJohn Snow                    "Bitmap '%s' is currently disabled and cannot be cleared",
2831e74e6b78SJohn Snow                    name);
2832e74e6b78SJohn Snow         goto out;
2833e74e6b78SJohn Snow     }
2834e74e6b78SJohn Snow 
2835df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(bitmap, NULL);
2836e74e6b78SJohn Snow 
2837e74e6b78SJohn Snow  out:
2838e74e6b78SJohn Snow     aio_context_release(aio_context);
2839e74e6b78SJohn Snow }
2840e74e6b78SJohn Snow 
2841072ebe6bSMarkus Armbruster void hmp_drive_del(Monitor *mon, const QDict *qdict)
28429063f814SRyan Harper {
28439063f814SRyan Harper     const char *id = qdict_get_str(qdict, "id");
28447e7d56d9SMarkus Armbruster     BlockBackend *blk;
28459063f814SRyan Harper     BlockDriverState *bs;
28468ad4202bSStefan Hajnoczi     AioContext *aio_context;
28473718d8abSFam Zheng     Error *local_err = NULL;
28489063f814SRyan Harper 
28492073d410SKevin Wolf     bs = bdrv_find_node(id);
28502073d410SKevin Wolf     if (bs) {
28512073d410SKevin Wolf         qmp_x_blockdev_del(false, NULL, true, id, &local_err);
28522073d410SKevin Wolf         if (local_err) {
28532073d410SKevin Wolf             error_report_err(local_err);
28542073d410SKevin Wolf         }
28552073d410SKevin Wolf         return;
28562073d410SKevin Wolf     }
28572073d410SKevin Wolf 
28587e7d56d9SMarkus Armbruster     blk = blk_by_name(id);
28597e7d56d9SMarkus Armbruster     if (!blk) {
2860b1422f20SMarkus Armbruster         error_report("Device '%s' not found", id);
2861072ebe6bSMarkus Armbruster         return;
28629063f814SRyan Harper     }
28638ad4202bSStefan Hajnoczi 
286426f8b3a8SMarkus Armbruster     if (!blk_legacy_dinfo(blk)) {
286548f364ddSMarkus Armbruster         error_report("Deleting device added with blockdev-add"
286648f364ddSMarkus Armbruster                      " is not supported");
2867072ebe6bSMarkus Armbruster         return;
286848f364ddSMarkus Armbruster     }
286948f364ddSMarkus Armbruster 
28705433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
28718ad4202bSStefan Hajnoczi     aio_context_acquire(aio_context);
28728ad4202bSStefan Hajnoczi 
28735433c24fSMax Reitz     bs = blk_bs(blk);
28745433c24fSMax Reitz     if (bs) {
28753718d8abSFam Zheng         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2876565f65d2SMarkus Armbruster             error_report_err(local_err);
28778ad4202bSStefan Hajnoczi             aio_context_release(aio_context);
2878072ebe6bSMarkus Armbruster             return;
28798591675fSMarcelo Tosatti         }
28809063f814SRyan Harper 
2881938abd43SMax Reitz         blk_remove_bs(blk);
28825433c24fSMax Reitz     }
28839063f814SRyan Harper 
28847c735873SMax Reitz     /* Make the BlockBackend and the attached BlockDriverState anonymous */
2885efaa7c4eSMax Reitz     monitor_remove_blk(blk);
2886efaa7c4eSMax Reitz 
28877c735873SMax Reitz     /* If this BlockBackend has a device attached to it, its refcount will be
28887c735873SMax Reitz      * decremented when the device is removed; otherwise we have to do so here.
2889d22b2f41SRyan Harper      */
2890a7f53e26SMarkus Armbruster     if (blk_get_attached_dev(blk)) {
2891293c51a6SStefan Hajnoczi         /* Further I/O must not pause the guest */
2892373340b2SMax Reitz         blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2893293c51a6SStefan Hajnoczi                          BLOCKDEV_ON_ERROR_REPORT);
2894d22b2f41SRyan Harper     } else {
2895b9fe8a7aSMarkus Armbruster         blk_unref(blk);
2896d22b2f41SRyan Harper     }
28979063f814SRyan Harper 
28988ad4202bSStefan Hajnoczi     aio_context_release(aio_context);
28999063f814SRyan Harper }
29006d4a2b3aSChristoph Hellwig 
29013b1dbd11SBenoît Canet void qmp_block_resize(bool has_device, const char *device,
29023b1dbd11SBenoît Canet                       bool has_node_name, const char *node_name,
29033b1dbd11SBenoît Canet                       int64_t size, Error **errp)
29046d4a2b3aSChristoph Hellwig {
29053b1dbd11SBenoît Canet     Error *local_err = NULL;
29066d4a2b3aSChristoph Hellwig     BlockDriverState *bs;
2907927e0e76SStefan Hajnoczi     AioContext *aio_context;
29088732901eSKevin Wolf     int ret;
29096d4a2b3aSChristoph Hellwig 
29103b1dbd11SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
29113b1dbd11SBenoît Canet                         has_node_name ? node_name : NULL,
29123b1dbd11SBenoît Canet                         &local_err);
291384d18f06SMarkus Armbruster     if (local_err) {
29143b1dbd11SBenoît Canet         error_propagate(errp, local_err);
29153b1dbd11SBenoît Canet         return;
29163b1dbd11SBenoît Canet     }
29173b1dbd11SBenoît Canet 
2918927e0e76SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
2919927e0e76SStefan Hajnoczi     aio_context_acquire(aio_context);
2920927e0e76SStefan Hajnoczi 
29213b1dbd11SBenoît Canet     if (!bdrv_is_first_non_filter(bs)) {
2922c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2923927e0e76SStefan Hajnoczi         goto out;
29246d4a2b3aSChristoph Hellwig     }
29256d4a2b3aSChristoph Hellwig 
29266d4a2b3aSChristoph Hellwig     if (size < 0) {
2927c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2928927e0e76SStefan Hajnoczi         goto out;
29296d4a2b3aSChristoph Hellwig     }
29306d4a2b3aSChristoph Hellwig 
29319c75e168SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2932c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2933927e0e76SStefan Hajnoczi         goto out;
29349c75e168SJeff Cody     }
29359c75e168SJeff Cody 
293692b7a08dSPeter Lieven     /* complete all in-flight operations before resizing the device */
293792b7a08dSPeter Lieven     bdrv_drain_all();
293892b7a08dSPeter Lieven 
29398732901eSKevin Wolf     ret = bdrv_truncate(bs, size);
29408732901eSKevin Wolf     switch (ret) {
2941939a1cc3SStefan Hajnoczi     case 0:
2942939a1cc3SStefan Hajnoczi         break;
2943939a1cc3SStefan Hajnoczi     case -ENOMEDIUM:
2944c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2945939a1cc3SStefan Hajnoczi         break;
2946939a1cc3SStefan Hajnoczi     case -ENOTSUP:
2947c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_UNSUPPORTED);
2948939a1cc3SStefan Hajnoczi         break;
2949939a1cc3SStefan Hajnoczi     case -EACCES:
295081e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
2951939a1cc3SStefan Hajnoczi         break;
2952939a1cc3SStefan Hajnoczi     case -EBUSY:
2953c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2954939a1cc3SStefan Hajnoczi         break;
2955939a1cc3SStefan Hajnoczi     default:
29568732901eSKevin Wolf         error_setg_errno(errp, -ret, "Could not resize");
2957939a1cc3SStefan Hajnoczi         break;
29586d4a2b3aSChristoph Hellwig     }
2959927e0e76SStefan Hajnoczi 
2960927e0e76SStefan Hajnoczi out:
2961927e0e76SStefan Hajnoczi     aio_context_release(aio_context);
29626d4a2b3aSChristoph Hellwig }
296312bd451fSStefan Hajnoczi 
29649abf2dbaSJeff Cody static void block_job_cb(void *opaque, int ret)
296512bd451fSStefan Hajnoczi {
2966723c5d93SStefan Hajnoczi     /* Note that this function may be executed from another AioContext besides
2967723c5d93SStefan Hajnoczi      * the QEMU main loop.  If you need to access anything that assumes the
2968723c5d93SStefan Hajnoczi      * QEMU global mutex, use a BH or introduce a mutex.
2969723c5d93SStefan Hajnoczi      */
2970723c5d93SStefan Hajnoczi 
297112bd451fSStefan Hajnoczi     BlockDriverState *bs = opaque;
2972bcada37bSWenchao Xia     const char *msg = NULL;
297312bd451fSStefan Hajnoczi 
29749abf2dbaSJeff Cody     trace_block_job_cb(bs, bs->job, ret);
297512bd451fSStefan Hajnoczi 
297612bd451fSStefan Hajnoczi     assert(bs->job);
2977bcada37bSWenchao Xia 
297812bd451fSStefan Hajnoczi     if (ret < 0) {
2979bcada37bSWenchao Xia         msg = strerror(-ret);
298012bd451fSStefan Hajnoczi     }
298112bd451fSStefan Hajnoczi 
2982370521a1SStefan Hajnoczi     if (block_job_is_cancelled(bs->job)) {
2983bcada37bSWenchao Xia         block_job_event_cancelled(bs->job);
2984370521a1SStefan Hajnoczi     } else {
2985bcada37bSWenchao Xia         block_job_event_completed(bs->job, msg);
2986370521a1SStefan Hajnoczi     }
298712bd451fSStefan Hajnoczi }
298812bd451fSStefan Hajnoczi 
298913d8cc51SJeff Cody void qmp_block_stream(const char *device,
299013d8cc51SJeff Cody                       bool has_base, const char *base,
299113d8cc51SJeff Cody                       bool has_backing_file, const char *backing_file,
299213d8cc51SJeff Cody                       bool has_speed, int64_t speed,
29931d809098SPaolo Bonzini                       bool has_on_error, BlockdevOnError on_error,
29941d809098SPaolo Bonzini                       Error **errp)
299512bd451fSStefan Hajnoczi {
2996a0e8544cSFam Zheng     BlockBackend *blk;
299712bd451fSStefan Hajnoczi     BlockDriverState *bs;
2998c8c3080fSMarcelo Tosatti     BlockDriverState *base_bs = NULL;
2999f3e69bebSStefan Hajnoczi     AioContext *aio_context;
3000fd7f8c65SStefan Hajnoczi     Error *local_err = NULL;
300113d8cc51SJeff Cody     const char *base_name = NULL;
300212bd451fSStefan Hajnoczi 
30031d809098SPaolo Bonzini     if (!has_on_error) {
30041d809098SPaolo Bonzini         on_error = BLOCKDEV_ON_ERROR_REPORT;
30051d809098SPaolo Bonzini     }
30061d809098SPaolo Bonzini 
3007a0e8544cSFam Zheng     blk = blk_by_name(device);
3008a0e8544cSFam Zheng     if (!blk) {
300975158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
301075158ebbSMarkus Armbruster                   "Device '%s' not found", device);
301112bd451fSStefan Hajnoczi         return;
301212bd451fSStefan Hajnoczi     }
301312bd451fSStefan Hajnoczi 
30145433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3015f3e69bebSStefan Hajnoczi     aio_context_acquire(aio_context);
3016f3e69bebSStefan Hajnoczi 
30175433c24fSMax Reitz     if (!blk_is_available(blk)) {
30185433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
30195433c24fSMax Reitz         goto out;
30205433c24fSMax Reitz     }
30215433c24fSMax Reitz     bs = blk_bs(blk);
30225433c24fSMax Reitz 
3023628ff683SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3024f3e69bebSStefan Hajnoczi         goto out;
3025628ff683SFam Zheng     }
3026628ff683SFam Zheng 
302713d8cc51SJeff Cody     if (has_base) {
3028c8c3080fSMarcelo Tosatti         base_bs = bdrv_find_backing_image(bs, base);
3029c8c3080fSMarcelo Tosatti         if (base_bs == NULL) {
3030c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_BASE_NOT_FOUND, base);
3031f3e69bebSStefan Hajnoczi             goto out;
303212bd451fSStefan Hajnoczi         }
3033f3e69bebSStefan Hajnoczi         assert(bdrv_get_aio_context(base_bs) == aio_context);
303413d8cc51SJeff Cody         base_name = base;
3035c8c3080fSMarcelo Tosatti     }
303612bd451fSStefan Hajnoczi 
303713d8cc51SJeff Cody     /* if we are streaming the entire chain, the result will have no backing
303813d8cc51SJeff Cody      * file, and specifying one is therefore an error */
303913d8cc51SJeff Cody     if (base_bs == NULL && has_backing_file) {
304013d8cc51SJeff Cody         error_setg(errp, "backing file specified, but streaming the "
304113d8cc51SJeff Cody                          "entire chain");
3042f3e69bebSStefan Hajnoczi         goto out;
304313d8cc51SJeff Cody     }
304413d8cc51SJeff Cody 
304513d8cc51SJeff Cody     /* backing_file string overrides base bs filename */
304613d8cc51SJeff Cody     base_name = has_backing_file ? backing_file : base_name;
304713d8cc51SJeff Cody 
304813d8cc51SJeff Cody     stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
30491d809098SPaolo Bonzini                  on_error, block_job_cb, bs, &local_err);
305084d18f06SMarkus Armbruster     if (local_err) {
3051fd7f8c65SStefan Hajnoczi         error_propagate(errp, local_err);
3052f3e69bebSStefan Hajnoczi         goto out;
305312bd451fSStefan Hajnoczi     }
305412bd451fSStefan Hajnoczi 
305512bd451fSStefan Hajnoczi     trace_qmp_block_stream(bs, bs->job);
3056f3e69bebSStefan Hajnoczi 
3057f3e69bebSStefan Hajnoczi out:
3058f3e69bebSStefan Hajnoczi     aio_context_release(aio_context);
305912bd451fSStefan Hajnoczi }
30602d47c6e9SStefan Hajnoczi 
3061ed61fc10SJeff Cody void qmp_block_commit(const char *device,
30627676e2c5SJeff Cody                       bool has_base, const char *base,
30637676e2c5SJeff Cody                       bool has_top, const char *top,
306454e26900SJeff Cody                       bool has_backing_file, const char *backing_file,
3065ed61fc10SJeff Cody                       bool has_speed, int64_t speed,
3066ed61fc10SJeff Cody                       Error **errp)
3067ed61fc10SJeff Cody {
3068a0e8544cSFam Zheng     BlockBackend *blk;
3069ed61fc10SJeff Cody     BlockDriverState *bs;
3070ed61fc10SJeff Cody     BlockDriverState *base_bs, *top_bs;
30719e85cd5cSStefan Hajnoczi     AioContext *aio_context;
3072ed61fc10SJeff Cody     Error *local_err = NULL;
3073ed61fc10SJeff Cody     /* This will be part of the QMP command, if/when the
3074ed61fc10SJeff Cody      * BlockdevOnError change for blkmirror makes it in
3075ed61fc10SJeff Cody      */
307692aa5c6dSPaolo Bonzini     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3077ed61fc10SJeff Cody 
307854504663SMax Reitz     if (!has_speed) {
307954504663SMax Reitz         speed = 0;
308054504663SMax Reitz     }
308154504663SMax Reitz 
30827676e2c5SJeff Cody     /* Important Note:
30837676e2c5SJeff Cody      *  libvirt relies on the DeviceNotFound error class in order to probe for
30847676e2c5SJeff Cody      *  live commit feature versions; for this to work, we must make sure to
30857676e2c5SJeff Cody      *  perform the device lookup before any generic errors that may occur in a
30867676e2c5SJeff Cody      *  scenario in which all optional arguments are omitted. */
3087a0e8544cSFam Zheng     blk = blk_by_name(device);
3088a0e8544cSFam Zheng     if (!blk) {
308975158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
309075158ebbSMarkus Armbruster                   "Device '%s' not found", device);
3091ed61fc10SJeff Cody         return;
3092ed61fc10SJeff Cody     }
3093ed61fc10SJeff Cody 
30945433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
30959e85cd5cSStefan Hajnoczi     aio_context_acquire(aio_context);
30969e85cd5cSStefan Hajnoczi 
30975433c24fSMax Reitz     if (!blk_is_available(blk)) {
30985433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
30995433c24fSMax Reitz         goto out;
31005433c24fSMax Reitz     }
31015433c24fSMax Reitz     bs = blk_bs(blk);
31025433c24fSMax Reitz 
3103bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
31049e85cd5cSStefan Hajnoczi         goto out;
3105628ff683SFam Zheng     }
3106628ff683SFam Zheng 
3107ed61fc10SJeff Cody     /* default top_bs is the active layer */
3108ed61fc10SJeff Cody     top_bs = bs;
3109ed61fc10SJeff Cody 
31107676e2c5SJeff Cody     if (has_top && top) {
3111ed61fc10SJeff Cody         if (strcmp(bs->filename, top) != 0) {
3112ed61fc10SJeff Cody             top_bs = bdrv_find_backing_image(bs, top);
3113ed61fc10SJeff Cody         }
3114ed61fc10SJeff Cody     }
3115ed61fc10SJeff Cody 
3116ed61fc10SJeff Cody     if (top_bs == NULL) {
3117ed61fc10SJeff Cody         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
31189e85cd5cSStefan Hajnoczi         goto out;
3119ed61fc10SJeff Cody     }
3120ed61fc10SJeff Cody 
31219e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(top_bs) == aio_context);
31229e85cd5cSStefan Hajnoczi 
3123d5208c45SJeff Cody     if (has_base && base) {
3124d5208c45SJeff Cody         base_bs = bdrv_find_backing_image(top_bs, base);
3125d5208c45SJeff Cody     } else {
3126d5208c45SJeff Cody         base_bs = bdrv_find_base(top_bs);
3127d5208c45SJeff Cody     }
3128d5208c45SJeff Cody 
3129d5208c45SJeff Cody     if (base_bs == NULL) {
3130c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
31319e85cd5cSStefan Hajnoczi         goto out;
3132d5208c45SJeff Cody     }
3133d5208c45SJeff Cody 
31349e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(base_bs) == aio_context);
31359e85cd5cSStefan Hajnoczi 
3136bb00021dSFam Zheng     if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3137bb00021dSFam Zheng         goto out;
3138bb00021dSFam Zheng     }
3139bb00021dSFam Zheng 
31407676e2c5SJeff Cody     /* Do not allow attempts to commit an image into itself */
31417676e2c5SJeff Cody     if (top_bs == base_bs) {
31427676e2c5SJeff Cody         error_setg(errp, "cannot commit an image into itself");
31439e85cd5cSStefan Hajnoczi         goto out;
31447676e2c5SJeff Cody     }
31457676e2c5SJeff Cody 
314620a63d2cSFam Zheng     if (top_bs == bs) {
314754e26900SJeff Cody         if (has_backing_file) {
314854e26900SJeff Cody             error_setg(errp, "'backing-file' specified,"
314954e26900SJeff Cody                              " but 'top' is the active layer");
31509e85cd5cSStefan Hajnoczi             goto out;
315154e26900SJeff Cody         }
315220a63d2cSFam Zheng         commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
315320a63d2cSFam Zheng                             bs, &local_err);
315420a63d2cSFam Zheng     } else {
3155ed61fc10SJeff Cody         commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
315654e26900SJeff Cody                      has_backing_file ? backing_file : NULL, &local_err);
315720a63d2cSFam Zheng     }
3158ed61fc10SJeff Cody     if (local_err != NULL) {
3159ed61fc10SJeff Cody         error_propagate(errp, local_err);
31609e85cd5cSStefan Hajnoczi         goto out;
3161ed61fc10SJeff Cody     }
31629e85cd5cSStefan Hajnoczi 
31639e85cd5cSStefan Hajnoczi out:
31649e85cd5cSStefan Hajnoczi     aio_context_release(aio_context);
3165ed61fc10SJeff Cody }
3166ed61fc10SJeff Cody 
316778f51fdeSJohn Snow static void do_drive_backup(const char *device, const char *target,
316899a9addfSStefan Hajnoczi                             bool has_format, const char *format,
3169b53169eaSStefan Hajnoczi                             enum MirrorSyncMode sync,
317099a9addfSStefan Hajnoczi                             bool has_mode, enum NewImageMode mode,
317199a9addfSStefan Hajnoczi                             bool has_speed, int64_t speed,
3172d58d8453SJohn Snow                             bool has_bitmap, const char *bitmap,
317378f51fdeSJohn Snow                             bool has_on_source_error,
317478f51fdeSJohn Snow                             BlockdevOnError on_source_error,
317578f51fdeSJohn Snow                             bool has_on_target_error,
317678f51fdeSJohn Snow                             BlockdevOnError on_target_error,
317778f51fdeSJohn Snow                             BlockJobTxn *txn, Error **errp)
317899a9addfSStefan Hajnoczi {
3179a0e8544cSFam Zheng     BlockBackend *blk;
318099a9addfSStefan Hajnoczi     BlockDriverState *bs;
318199a9addfSStefan Hajnoczi     BlockDriverState *target_bs;
3182fc5d3f84SIan Main     BlockDriverState *source = NULL;
3183d58d8453SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
3184761731b1SStefan Hajnoczi     AioContext *aio_context;
3185e6641719SMax Reitz     QDict *options = NULL;
318699a9addfSStefan Hajnoczi     Error *local_err = NULL;
318799a9addfSStefan Hajnoczi     int flags;
318899a9addfSStefan Hajnoczi     int64_t size;
318999a9addfSStefan Hajnoczi     int ret;
319099a9addfSStefan Hajnoczi 
319199a9addfSStefan Hajnoczi     if (!has_speed) {
319299a9addfSStefan Hajnoczi         speed = 0;
319399a9addfSStefan Hajnoczi     }
319499a9addfSStefan Hajnoczi     if (!has_on_source_error) {
319599a9addfSStefan Hajnoczi         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
319699a9addfSStefan Hajnoczi     }
319799a9addfSStefan Hajnoczi     if (!has_on_target_error) {
319899a9addfSStefan Hajnoczi         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
319999a9addfSStefan Hajnoczi     }
320099a9addfSStefan Hajnoczi     if (!has_mode) {
320199a9addfSStefan Hajnoczi         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
320299a9addfSStefan Hajnoczi     }
320399a9addfSStefan Hajnoczi 
3204a0e8544cSFam Zheng     blk = blk_by_name(device);
3205a0e8544cSFam Zheng     if (!blk) {
320675158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
320775158ebbSMarkus Armbruster                   "Device '%s' not found", device);
320899a9addfSStefan Hajnoczi         return;
320999a9addfSStefan Hajnoczi     }
321099a9addfSStefan Hajnoczi 
32115433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3212761731b1SStefan Hajnoczi     aio_context_acquire(aio_context);
3213761731b1SStefan Hajnoczi 
3214c29c1dd3SFam Zheng     /* Although backup_run has this check too, we need to use bs->drv below, so
3215c29c1dd3SFam Zheng      * do an early check redundantly. */
32165433c24fSMax Reitz     if (!blk_is_available(blk)) {
3217c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3218761731b1SStefan Hajnoczi         goto out;
321999a9addfSStefan Hajnoczi     }
32205433c24fSMax Reitz     bs = blk_bs(blk);
322199a9addfSStefan Hajnoczi 
322299a9addfSStefan Hajnoczi     if (!has_format) {
322399a9addfSStefan Hajnoczi         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
322499a9addfSStefan Hajnoczi     }
322599a9addfSStefan Hajnoczi 
3226c29c1dd3SFam Zheng     /* Early check to avoid creating target */
32273718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3228761731b1SStefan Hajnoczi         goto out;
322999a9addfSStefan Hajnoczi     }
323099a9addfSStefan Hajnoczi 
323161de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
323299a9addfSStefan Hajnoczi 
3233fc5d3f84SIan Main     /* See if we have a backing HD we can use to create our new image
3234fc5d3f84SIan Main      * on top of. */
3235fc5d3f84SIan Main     if (sync == MIRROR_SYNC_MODE_TOP) {
3236760e0063SKevin Wolf         source = backing_bs(bs);
3237fc5d3f84SIan Main         if (!source) {
3238fc5d3f84SIan Main             sync = MIRROR_SYNC_MODE_FULL;
3239fc5d3f84SIan Main         }
3240fc5d3f84SIan Main     }
3241fc5d3f84SIan Main     if (sync == MIRROR_SYNC_MODE_NONE) {
3242fc5d3f84SIan Main         source = bs;
3243fc5d3f84SIan Main     }
3244fc5d3f84SIan Main 
324599a9addfSStefan Hajnoczi     size = bdrv_getlength(bs);
324699a9addfSStefan Hajnoczi     if (size < 0) {
324799a9addfSStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
3248761731b1SStefan Hajnoczi         goto out;
324999a9addfSStefan Hajnoczi     }
325099a9addfSStefan Hajnoczi 
325199a9addfSStefan Hajnoczi     if (mode != NEW_IMAGE_MODE_EXISTING) {
3252e6641719SMax Reitz         assert(format);
3253fc5d3f84SIan Main         if (source) {
3254fc5d3f84SIan Main             bdrv_img_create(target, format, source->filename,
3255fc5d3f84SIan Main                             source->drv->format_name, NULL,
3256fc5d3f84SIan Main                             size, flags, &local_err, false);
3257fc5d3f84SIan Main         } else {
3258fc5d3f84SIan Main             bdrv_img_create(target, format, NULL, NULL, NULL,
3259fc5d3f84SIan Main                             size, flags, &local_err, false);
3260fc5d3f84SIan Main         }
326199a9addfSStefan Hajnoczi     }
326299a9addfSStefan Hajnoczi 
326384d18f06SMarkus Armbruster     if (local_err) {
326499a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3265761731b1SStefan Hajnoczi         goto out;
326699a9addfSStefan Hajnoczi     }
326799a9addfSStefan Hajnoczi 
3268e6641719SMax Reitz     if (format) {
3269e6641719SMax Reitz         options = qdict_new();
3270e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
3271e6641719SMax Reitz     }
3272e6641719SMax Reitz 
3273f67503e5SMax Reitz     target_bs = NULL;
32746ebf9aa2SMax Reitz     ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
327599a9addfSStefan Hajnoczi     if (ret < 0) {
327634b5d2c6SMax Reitz         error_propagate(errp, local_err);
3277761731b1SStefan Hajnoczi         goto out;
327899a9addfSStefan Hajnoczi     }
327999a9addfSStefan Hajnoczi 
3280761731b1SStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
3281761731b1SStefan Hajnoczi 
3282d58d8453SJohn Snow     if (has_bitmap) {
3283d58d8453SJohn Snow         bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3284d58d8453SJohn Snow         if (!bmap) {
3285d58d8453SJohn Snow             error_setg(errp, "Bitmap '%s' could not be found", bitmap);
32860702d3d8SMax Reitz             bdrv_unref(target_bs);
3287d58d8453SJohn Snow             goto out;
3288d58d8453SJohn Snow         }
3289d58d8453SJohn Snow     }
3290d58d8453SJohn Snow 
3291d58d8453SJohn Snow     backup_start(bs, target_bs, speed, sync, bmap,
3292d58d8453SJohn Snow                  on_source_error, on_target_error,
329378f51fdeSJohn Snow                  block_job_cb, bs, txn, &local_err);
329499a9addfSStefan Hajnoczi     if (local_err != NULL) {
32954f6fd349SFam Zheng         bdrv_unref(target_bs);
329699a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3297761731b1SStefan Hajnoczi         goto out;
329899a9addfSStefan Hajnoczi     }
3299761731b1SStefan Hajnoczi 
3300761731b1SStefan Hajnoczi out:
3301761731b1SStefan Hajnoczi     aio_context_release(aio_context);
330299a9addfSStefan Hajnoczi }
330399a9addfSStefan Hajnoczi 
330478f51fdeSJohn Snow void qmp_drive_backup(const char *device, const char *target,
330578f51fdeSJohn Snow                       bool has_format, const char *format,
330678f51fdeSJohn Snow                       enum MirrorSyncMode sync,
330778f51fdeSJohn Snow                       bool has_mode, enum NewImageMode mode,
330878f51fdeSJohn Snow                       bool has_speed, int64_t speed,
330978f51fdeSJohn Snow                       bool has_bitmap, const char *bitmap,
331078f51fdeSJohn Snow                       bool has_on_source_error, BlockdevOnError on_source_error,
331178f51fdeSJohn Snow                       bool has_on_target_error, BlockdevOnError on_target_error,
331278f51fdeSJohn Snow                       Error **errp)
331378f51fdeSJohn Snow {
331478f51fdeSJohn Snow     return do_drive_backup(device, target, has_format, format, sync,
331578f51fdeSJohn Snow                            has_mode, mode, has_speed, speed,
331678f51fdeSJohn Snow                            has_bitmap, bitmap,
331778f51fdeSJohn Snow                            has_on_source_error, on_source_error,
331878f51fdeSJohn Snow                            has_on_target_error, on_target_error,
331978f51fdeSJohn Snow                            NULL, errp);
332078f51fdeSJohn Snow }
332178f51fdeSJohn Snow 
3322c13163fbSBenoît Canet BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3323c13163fbSBenoît Canet {
3324d5a8ee60SAlberto Garcia     return bdrv_named_nodes_list(errp);
3325c13163fbSBenoît Canet }
3326c13163fbSBenoît Canet 
332778f51fdeSJohn Snow void do_blockdev_backup(const char *device, const char *target,
3328c29c1dd3SFam Zheng                          enum MirrorSyncMode sync,
3329c29c1dd3SFam Zheng                          bool has_speed, int64_t speed,
3330c29c1dd3SFam Zheng                          bool has_on_source_error,
3331c29c1dd3SFam Zheng                          BlockdevOnError on_source_error,
3332c29c1dd3SFam Zheng                          bool has_on_target_error,
3333c29c1dd3SFam Zheng                          BlockdevOnError on_target_error,
333478f51fdeSJohn Snow                          BlockJobTxn *txn, Error **errp)
3335c29c1dd3SFam Zheng {
33365433c24fSMax Reitz     BlockBackend *blk, *target_blk;
3337c29c1dd3SFam Zheng     BlockDriverState *bs;
3338c29c1dd3SFam Zheng     BlockDriverState *target_bs;
3339c29c1dd3SFam Zheng     Error *local_err = NULL;
3340c29c1dd3SFam Zheng     AioContext *aio_context;
3341c29c1dd3SFam Zheng 
3342c29c1dd3SFam Zheng     if (!has_speed) {
3343c29c1dd3SFam Zheng         speed = 0;
3344c29c1dd3SFam Zheng     }
3345c29c1dd3SFam Zheng     if (!has_on_source_error) {
3346c29c1dd3SFam Zheng         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3347c29c1dd3SFam Zheng     }
3348c29c1dd3SFam Zheng     if (!has_on_target_error) {
3349c29c1dd3SFam Zheng         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3350c29c1dd3SFam Zheng     }
3351c29c1dd3SFam Zheng 
3352a0e8544cSFam Zheng     blk = blk_by_name(device);
3353a0e8544cSFam Zheng     if (!blk) {
33545b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", device);
3355c29c1dd3SFam Zheng         return;
3356c29c1dd3SFam Zheng     }
3357c29c1dd3SFam Zheng 
33585433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3359c29c1dd3SFam Zheng     aio_context_acquire(aio_context);
3360c29c1dd3SFam Zheng 
33615433c24fSMax Reitz     if (!blk_is_available(blk)) {
33625433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
33635433c24fSMax Reitz         goto out;
33645433c24fSMax Reitz     }
33655433c24fSMax Reitz     bs = blk_bs(blk);
33665433c24fSMax Reitz 
33675433c24fSMax Reitz     target_blk = blk_by_name(target);
33685433c24fSMax Reitz     if (!target_blk) {
33695b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", target);
3370c29c1dd3SFam Zheng         goto out;
3371c29c1dd3SFam Zheng     }
33725433c24fSMax Reitz 
33735433c24fSMax Reitz     if (!blk_is_available(target_blk)) {
33745433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", target);
33755433c24fSMax Reitz         goto out;
33765433c24fSMax Reitz     }
33775433c24fSMax Reitz     target_bs = blk_bs(target_blk);
3378c29c1dd3SFam Zheng 
3379c29c1dd3SFam Zheng     bdrv_ref(target_bs);
3380c29c1dd3SFam Zheng     bdrv_set_aio_context(target_bs, aio_context);
3381d58d8453SJohn Snow     backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
338278f51fdeSJohn Snow                  on_target_error, block_job_cb, bs, txn, &local_err);
3383c29c1dd3SFam Zheng     if (local_err != NULL) {
3384c29c1dd3SFam Zheng         bdrv_unref(target_bs);
3385c29c1dd3SFam Zheng         error_propagate(errp, local_err);
3386c29c1dd3SFam Zheng     }
3387c29c1dd3SFam Zheng out:
3388c29c1dd3SFam Zheng     aio_context_release(aio_context);
3389c29c1dd3SFam Zheng }
3390c29c1dd3SFam Zheng 
339178f51fdeSJohn Snow void qmp_blockdev_backup(const char *device, const char *target,
339278f51fdeSJohn Snow                          enum MirrorSyncMode sync,
339378f51fdeSJohn Snow                          bool has_speed, int64_t speed,
339478f51fdeSJohn Snow                          bool has_on_source_error,
339578f51fdeSJohn Snow                          BlockdevOnError on_source_error,
339678f51fdeSJohn Snow                          bool has_on_target_error,
339778f51fdeSJohn Snow                          BlockdevOnError on_target_error,
339878f51fdeSJohn Snow                          Error **errp)
339978f51fdeSJohn Snow {
340078f51fdeSJohn Snow     do_blockdev_backup(device, target, sync, has_speed, speed,
340178f51fdeSJohn Snow                        has_on_source_error, on_source_error,
340278f51fdeSJohn Snow                        has_on_target_error, on_target_error,
340378f51fdeSJohn Snow                        NULL, errp);
340478f51fdeSJohn Snow }
340578f51fdeSJohn Snow 
34064193cdd7SFam Zheng /* Parameter check and block job starting for drive mirroring.
34074193cdd7SFam Zheng  * Caller should hold @device and @target's aio context (must be the same).
34084193cdd7SFam Zheng  **/
34094193cdd7SFam Zheng static void blockdev_mirror_common(BlockDriverState *bs,
34104193cdd7SFam Zheng                                    BlockDriverState *target,
341109158f00SBenoît Canet                                    bool has_replaces, const char *replaces,
3412d9b902dbSPaolo Bonzini                                    enum MirrorSyncMode sync,
3413b952b558SPaolo Bonzini                                    bool has_speed, int64_t speed,
3414eee13dfeSPaolo Bonzini                                    bool has_granularity, uint32_t granularity,
341508e4ed6cSPaolo Bonzini                                    bool has_buf_size, int64_t buf_size,
34164193cdd7SFam Zheng                                    bool has_on_source_error,
34174193cdd7SFam Zheng                                    BlockdevOnError on_source_error,
34184193cdd7SFam Zheng                                    bool has_on_target_error,
34194193cdd7SFam Zheng                                    BlockdevOnError on_target_error,
34200fc9f8eaSFam Zheng                                    bool has_unmap, bool unmap,
3421b952b558SPaolo Bonzini                                    Error **errp)
3422d9b902dbSPaolo Bonzini {
3423d9b902dbSPaolo Bonzini 
3424d9b902dbSPaolo Bonzini     if (!has_speed) {
3425d9b902dbSPaolo Bonzini         speed = 0;
3426d9b902dbSPaolo Bonzini     }
3427b952b558SPaolo Bonzini     if (!has_on_source_error) {
3428b952b558SPaolo Bonzini         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3429b952b558SPaolo Bonzini     }
3430b952b558SPaolo Bonzini     if (!has_on_target_error) {
3431b952b558SPaolo Bonzini         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3432b952b558SPaolo Bonzini     }
3433eee13dfeSPaolo Bonzini     if (!has_granularity) {
3434eee13dfeSPaolo Bonzini         granularity = 0;
3435eee13dfeSPaolo Bonzini     }
343608e4ed6cSPaolo Bonzini     if (!has_buf_size) {
343748ac0a4dSWen Congyang         buf_size = 0;
343808e4ed6cSPaolo Bonzini     }
34390fc9f8eaSFam Zheng     if (!has_unmap) {
34400fc9f8eaSFam Zheng         unmap = true;
34410fc9f8eaSFam Zheng     }
344208e4ed6cSPaolo Bonzini 
3443eee13dfeSPaolo Bonzini     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3444c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
34453cbbe9fdSStefan Hajnoczi                    "a value in range [512B, 64MB]");
3446eee13dfeSPaolo Bonzini         return;
3447eee13dfeSPaolo Bonzini     }
3448eee13dfeSPaolo Bonzini     if (granularity & (granularity - 1)) {
3449c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3450c6bd8c70SMarkus Armbruster                    "power of 2");
3451eee13dfeSPaolo Bonzini         return;
3452eee13dfeSPaolo Bonzini     }
3453d9b902dbSPaolo Bonzini 
34544193cdd7SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
34554193cdd7SFam Zheng         return;
34564193cdd7SFam Zheng     }
3457e40e5027SFam Zheng     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3458e40e5027SFam Zheng         return;
3459e40e5027SFam Zheng     }
3460df92562eSFam Zheng     if (target->blk) {
3461df92562eSFam Zheng         error_setg(errp, "Cannot mirror to an attached block device");
3462df92562eSFam Zheng         return;
3463df92562eSFam Zheng     }
34644193cdd7SFam Zheng 
34654193cdd7SFam Zheng     if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
34664193cdd7SFam Zheng         sync = MIRROR_SYNC_MODE_FULL;
34674193cdd7SFam Zheng     }
34684193cdd7SFam Zheng 
34694193cdd7SFam Zheng     /* pass the node name to replace to mirror start since it's loose coupling
34704193cdd7SFam Zheng      * and will allow to check whether the node still exist at mirror completion
34714193cdd7SFam Zheng      */
34724193cdd7SFam Zheng     mirror_start(bs, target,
34734193cdd7SFam Zheng                  has_replaces ? replaces : NULL,
34744193cdd7SFam Zheng                  speed, granularity, buf_size, sync,
34754193cdd7SFam Zheng                  on_source_error, on_target_error, unmap,
34764193cdd7SFam Zheng                  block_job_cb, bs, errp);
34774193cdd7SFam Zheng }
34784193cdd7SFam Zheng 
34794193cdd7SFam Zheng void qmp_drive_mirror(const char *device, const char *target,
34804193cdd7SFam Zheng                       bool has_format, const char *format,
34814193cdd7SFam Zheng                       bool has_node_name, const char *node_name,
34824193cdd7SFam Zheng                       bool has_replaces, const char *replaces,
34834193cdd7SFam Zheng                       enum MirrorSyncMode sync,
34844193cdd7SFam Zheng                       bool has_mode, enum NewImageMode mode,
34854193cdd7SFam Zheng                       bool has_speed, int64_t speed,
34864193cdd7SFam Zheng                       bool has_granularity, uint32_t granularity,
34874193cdd7SFam Zheng                       bool has_buf_size, int64_t buf_size,
34884193cdd7SFam Zheng                       bool has_on_source_error, BlockdevOnError on_source_error,
34894193cdd7SFam Zheng                       bool has_on_target_error, BlockdevOnError on_target_error,
34904193cdd7SFam Zheng                       bool has_unmap, bool unmap,
34914193cdd7SFam Zheng                       Error **errp)
34924193cdd7SFam Zheng {
34934193cdd7SFam Zheng     BlockDriverState *bs;
34944193cdd7SFam Zheng     BlockBackend *blk;
34954193cdd7SFam Zheng     BlockDriverState *source, *target_bs;
34964193cdd7SFam Zheng     AioContext *aio_context;
34974193cdd7SFam Zheng     Error *local_err = NULL;
34984193cdd7SFam Zheng     QDict *options = NULL;
34994193cdd7SFam Zheng     int flags;
35004193cdd7SFam Zheng     int64_t size;
35014193cdd7SFam Zheng     int ret;
35024193cdd7SFam Zheng 
3503a0e8544cSFam Zheng     blk = blk_by_name(device);
3504a0e8544cSFam Zheng     if (!blk) {
350575158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
350675158ebbSMarkus Armbruster                   "Device '%s' not found", device);
3507d9b902dbSPaolo Bonzini         return;
3508d9b902dbSPaolo Bonzini     }
3509d9b902dbSPaolo Bonzini 
35105433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
35115a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
35125a7e7a0bSStefan Hajnoczi 
35135433c24fSMax Reitz     if (!blk_is_available(blk)) {
3514c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
35155a7e7a0bSStefan Hajnoczi         goto out;
3516d9b902dbSPaolo Bonzini     }
35175433c24fSMax Reitz     bs = blk_bs(blk);
35184193cdd7SFam Zheng     if (!has_mode) {
35194193cdd7SFam Zheng         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
35204193cdd7SFam Zheng     }
3521d9b902dbSPaolo Bonzini 
3522d9b902dbSPaolo Bonzini     if (!has_format) {
3523d9b902dbSPaolo Bonzini         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3524d9b902dbSPaolo Bonzini     }
3525d9b902dbSPaolo Bonzini 
352661de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
3527760e0063SKevin Wolf     source = backing_bs(bs);
3528d9b902dbSPaolo Bonzini     if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3529d9b902dbSPaolo Bonzini         sync = MIRROR_SYNC_MODE_FULL;
3530d9b902dbSPaolo Bonzini     }
3531117e0c82SMax Reitz     if (sync == MIRROR_SYNC_MODE_NONE) {
3532117e0c82SMax Reitz         source = bs;
3533117e0c82SMax Reitz     }
3534d9b902dbSPaolo Bonzini 
3535ac3c5d83SStefan Hajnoczi     size = bdrv_getlength(bs);
3536ac3c5d83SStefan Hajnoczi     if (size < 0) {
3537ac3c5d83SStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
35385a7e7a0bSStefan Hajnoczi         goto out;
3539ac3c5d83SStefan Hajnoczi     }
3540ac3c5d83SStefan Hajnoczi 
354109158f00SBenoît Canet     if (has_replaces) {
354209158f00SBenoît Canet         BlockDriverState *to_replace_bs;
35435a7e7a0bSStefan Hajnoczi         AioContext *replace_aio_context;
35445a7e7a0bSStefan Hajnoczi         int64_t replace_size;
354509158f00SBenoît Canet 
354609158f00SBenoît Canet         if (!has_node_name) {
354709158f00SBenoît Canet             error_setg(errp, "a node-name must be provided when replacing a"
354809158f00SBenoît Canet                              " named node of the graph");
35495a7e7a0bSStefan Hajnoczi             goto out;
355009158f00SBenoît Canet         }
355109158f00SBenoît Canet 
3552e12f3784SWen Congyang         to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
355309158f00SBenoît Canet 
355409158f00SBenoît Canet         if (!to_replace_bs) {
355509158f00SBenoît Canet             error_propagate(errp, local_err);
35565a7e7a0bSStefan Hajnoczi             goto out;
355709158f00SBenoît Canet         }
355809158f00SBenoît Canet 
35595a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
35605a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
35615a7e7a0bSStefan Hajnoczi         replace_size = bdrv_getlength(to_replace_bs);
35625a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
35635a7e7a0bSStefan Hajnoczi 
35645a7e7a0bSStefan Hajnoczi         if (size != replace_size) {
356509158f00SBenoît Canet             error_setg(errp, "cannot replace image with a mirror image of "
356609158f00SBenoît Canet                              "different size");
35675a7e7a0bSStefan Hajnoczi             goto out;
356809158f00SBenoît Canet         }
356909158f00SBenoît Canet     }
357009158f00SBenoît Canet 
357114526864SMax Reitz     if ((sync == MIRROR_SYNC_MODE_FULL || !source)
357214526864SMax Reitz         && mode != NEW_IMAGE_MODE_EXISTING)
357314526864SMax Reitz     {
3574d9b902dbSPaolo Bonzini         /* create new image w/o backing file */
3575e6641719SMax Reitz         assert(format);
3576cf8f2426SLuiz Capitulino         bdrv_img_create(target, format,
3577f382d43aSMiroslav Rezanina                         NULL, NULL, NULL, size, flags, &local_err, false);
3578d9b902dbSPaolo Bonzini     } else {
3579d9b902dbSPaolo Bonzini         switch (mode) {
3580d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_EXISTING:
3581d9b902dbSPaolo Bonzini             break;
3582d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3583d9b902dbSPaolo Bonzini             /* create new image with backing file */
3584cf8f2426SLuiz Capitulino             bdrv_img_create(target, format,
3585d9b902dbSPaolo Bonzini                             source->filename,
3586d9b902dbSPaolo Bonzini                             source->drv->format_name,
3587f382d43aSMiroslav Rezanina                             NULL, size, flags, &local_err, false);
3588d9b902dbSPaolo Bonzini             break;
3589d9b902dbSPaolo Bonzini         default:
3590d9b902dbSPaolo Bonzini             abort();
3591d9b902dbSPaolo Bonzini         }
3592d9b902dbSPaolo Bonzini     }
3593d9b902dbSPaolo Bonzini 
359484d18f06SMarkus Armbruster     if (local_err) {
3595cf8f2426SLuiz Capitulino         error_propagate(errp, local_err);
35965a7e7a0bSStefan Hajnoczi         goto out;
3597d9b902dbSPaolo Bonzini     }
3598d9b902dbSPaolo Bonzini 
35994c828dc6SBenoît Canet     options = qdict_new();
3600e6641719SMax Reitz     if (has_node_name) {
36014c828dc6SBenoît Canet         qdict_put(options, "node-name", qstring_from_str(node_name));
36024c828dc6SBenoît Canet     }
3603e6641719SMax Reitz     if (format) {
3604e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
3605e6641719SMax Reitz     }
36064c828dc6SBenoît Canet 
3607b812f671SPaolo Bonzini     /* Mirroring takes care of copy-on-write using the source's backing
3608b812f671SPaolo Bonzini      * file.
3609b812f671SPaolo Bonzini      */
3610f67503e5SMax Reitz     target_bs = NULL;
36114c828dc6SBenoît Canet     ret = bdrv_open(&target_bs, target, NULL, options,
36126ebf9aa2SMax Reitz                     flags | BDRV_O_NO_BACKING, &local_err);
3613d9b902dbSPaolo Bonzini     if (ret < 0) {
361434b5d2c6SMax Reitz         error_propagate(errp, local_err);
36155a7e7a0bSStefan Hajnoczi         goto out;
3616d9b902dbSPaolo Bonzini     }
3617d9b902dbSPaolo Bonzini 
36185a7e7a0bSStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
36195a7e7a0bSStefan Hajnoczi 
36204193cdd7SFam Zheng     blockdev_mirror_common(bs, target_bs,
36214193cdd7SFam Zheng                            has_replaces, replaces, sync,
36224193cdd7SFam Zheng                            has_speed, speed,
36234193cdd7SFam Zheng                            has_granularity, granularity,
36244193cdd7SFam Zheng                            has_buf_size, buf_size,
36254193cdd7SFam Zheng                            has_on_source_error, on_source_error,
36264193cdd7SFam Zheng                            has_on_target_error, on_target_error,
36274193cdd7SFam Zheng                            has_unmap, unmap,
36284193cdd7SFam Zheng                            &local_err);
36294193cdd7SFam Zheng     if (local_err) {
3630d9b902dbSPaolo Bonzini         error_propagate(errp, local_err);
36314193cdd7SFam Zheng         bdrv_unref(target_bs);
3632d9b902dbSPaolo Bonzini     }
36335a7e7a0bSStefan Hajnoczi out:
36345a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
3635d9b902dbSPaolo Bonzini }
3636d9b902dbSPaolo Bonzini 
3637df92562eSFam Zheng void qmp_blockdev_mirror(const char *device, const char *target,
3638df92562eSFam Zheng                          bool has_replaces, const char *replaces,
3639df92562eSFam Zheng                          MirrorSyncMode sync,
3640df92562eSFam Zheng                          bool has_speed, int64_t speed,
3641df92562eSFam Zheng                          bool has_granularity, uint32_t granularity,
3642df92562eSFam Zheng                          bool has_buf_size, int64_t buf_size,
3643df92562eSFam Zheng                          bool has_on_source_error,
3644df92562eSFam Zheng                          BlockdevOnError on_source_error,
3645df92562eSFam Zheng                          bool has_on_target_error,
3646df92562eSFam Zheng                          BlockdevOnError on_target_error,
3647df92562eSFam Zheng                          Error **errp)
3648df92562eSFam Zheng {
3649df92562eSFam Zheng     BlockDriverState *bs;
3650df92562eSFam Zheng     BlockBackend *blk;
3651df92562eSFam Zheng     BlockDriverState *target_bs;
3652df92562eSFam Zheng     AioContext *aio_context;
3653df92562eSFam Zheng     Error *local_err = NULL;
3654df92562eSFam Zheng 
3655df92562eSFam Zheng     blk = blk_by_name(device);
3656df92562eSFam Zheng     if (!blk) {
3657df92562eSFam Zheng         error_setg(errp, "Device '%s' not found", device);
3658df92562eSFam Zheng         return;
3659df92562eSFam Zheng     }
3660df92562eSFam Zheng     bs = blk_bs(blk);
3661df92562eSFam Zheng 
3662df92562eSFam Zheng     if (!bs) {
3663df92562eSFam Zheng         error_setg(errp, "Device '%s' has no media", device);
3664df92562eSFam Zheng         return;
3665df92562eSFam Zheng     }
3666df92562eSFam Zheng 
3667df92562eSFam Zheng     target_bs = bdrv_lookup_bs(target, target, errp);
3668df92562eSFam Zheng     if (!target_bs) {
3669df92562eSFam Zheng         return;
3670df92562eSFam Zheng     }
3671df92562eSFam Zheng 
3672df92562eSFam Zheng     aio_context = bdrv_get_aio_context(bs);
3673df92562eSFam Zheng     aio_context_acquire(aio_context);
3674df92562eSFam Zheng 
3675df92562eSFam Zheng     bdrv_ref(target_bs);
3676df92562eSFam Zheng     bdrv_set_aio_context(target_bs, aio_context);
3677df92562eSFam Zheng 
3678df92562eSFam Zheng     blockdev_mirror_common(bs, target_bs,
3679df92562eSFam Zheng                            has_replaces, replaces, sync,
3680df92562eSFam Zheng                            has_speed, speed,
3681df92562eSFam Zheng                            has_granularity, granularity,
3682df92562eSFam Zheng                            has_buf_size, buf_size,
3683df92562eSFam Zheng                            has_on_source_error, on_source_error,
3684df92562eSFam Zheng                            has_on_target_error, on_target_error,
3685df92562eSFam Zheng                            true, true,
3686df92562eSFam Zheng                            &local_err);
3687df92562eSFam Zheng     if (local_err) {
3688df92562eSFam Zheng         error_propagate(errp, local_err);
3689df92562eSFam Zheng         bdrv_unref(target_bs);
3690df92562eSFam Zheng     }
3691df92562eSFam Zheng 
3692df92562eSFam Zheng     aio_context_release(aio_context);
3693df92562eSFam Zheng }
3694df92562eSFam Zheng 
36953d948cdfSStefan Hajnoczi /* Get the block job for a given device name and acquire its AioContext */
369624d6bffeSMarkus Armbruster static BlockJob *find_block_job(const char *device, AioContext **aio_context,
369724d6bffeSMarkus Armbruster                                 Error **errp)
36982d47c6e9SStefan Hajnoczi {
3699a0e8544cSFam Zheng     BlockBackend *blk;
37002d47c6e9SStefan Hajnoczi     BlockDriverState *bs;
37012d47c6e9SStefan Hajnoczi 
37025433c24fSMax Reitz     *aio_context = NULL;
37035433c24fSMax Reitz 
3704a0e8544cSFam Zheng     blk = blk_by_name(device);
3705a0e8544cSFam Zheng     if (!blk) {
37063d948cdfSStefan Hajnoczi         goto notfound;
37072d47c6e9SStefan Hajnoczi     }
37083d948cdfSStefan Hajnoczi 
37095433c24fSMax Reitz     *aio_context = blk_get_aio_context(blk);
37103d948cdfSStefan Hajnoczi     aio_context_acquire(*aio_context);
37113d948cdfSStefan Hajnoczi 
37125433c24fSMax Reitz     if (!blk_is_available(blk)) {
37135433c24fSMax Reitz         goto notfound;
37145433c24fSMax Reitz     }
37155433c24fSMax Reitz     bs = blk_bs(blk);
37165433c24fSMax Reitz 
37173d948cdfSStefan Hajnoczi     if (!bs->job) {
37183d948cdfSStefan Hajnoczi         goto notfound;
37193d948cdfSStefan Hajnoczi     }
37203d948cdfSStefan Hajnoczi 
37212d47c6e9SStefan Hajnoczi     return bs->job;
37223d948cdfSStefan Hajnoczi 
37233d948cdfSStefan Hajnoczi notfound:
37242e3a0266SMarkus Armbruster     error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
37252e3a0266SMarkus Armbruster               "No active block job on device '%s'", device);
37265433c24fSMax Reitz     if (*aio_context) {
37275433c24fSMax Reitz         aio_context_release(*aio_context);
37283d948cdfSStefan Hajnoczi         *aio_context = NULL;
37295433c24fSMax Reitz     }
37303d948cdfSStefan Hajnoczi     return NULL;
37312d47c6e9SStefan Hajnoczi }
37322d47c6e9SStefan Hajnoczi 
3733882ec7ceSStefan Hajnoczi void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
37342d47c6e9SStefan Hajnoczi {
37353d948cdfSStefan Hajnoczi     AioContext *aio_context;
373624d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
37372d47c6e9SStefan Hajnoczi 
37382d47c6e9SStefan Hajnoczi     if (!job) {
37392d47c6e9SStefan Hajnoczi         return;
37402d47c6e9SStefan Hajnoczi     }
37412d47c6e9SStefan Hajnoczi 
3742882ec7ceSStefan Hajnoczi     block_job_set_speed(job, speed, errp);
37433d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
37442d47c6e9SStefan Hajnoczi }
3745370521a1SStefan Hajnoczi 
37466e37fb81SPaolo Bonzini void qmp_block_job_cancel(const char *device,
37476e37fb81SPaolo Bonzini                           bool has_force, bool force, Error **errp)
37486e37fb81SPaolo Bonzini {
37493d948cdfSStefan Hajnoczi     AioContext *aio_context;
375024d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
37516e37fb81SPaolo Bonzini 
37526e37fb81SPaolo Bonzini     if (!job) {
37536e37fb81SPaolo Bonzini         return;
37546e37fb81SPaolo Bonzini     }
37553d948cdfSStefan Hajnoczi 
37563d948cdfSStefan Hajnoczi     if (!has_force) {
37573d948cdfSStefan Hajnoczi         force = false;
37583d948cdfSStefan Hajnoczi     }
37593d948cdfSStefan Hajnoczi 
3760751ebd76SFam Zheng     if (job->user_paused && !force) {
3761f231b88dSCole Robinson         error_setg(errp, "The block job for device '%s' is currently paused",
3762f231b88dSCole Robinson                    device);
37633d948cdfSStefan Hajnoczi         goto out;
37646e37fb81SPaolo Bonzini     }
37656e37fb81SPaolo Bonzini 
37666e37fb81SPaolo Bonzini     trace_qmp_block_job_cancel(job);
37676e37fb81SPaolo Bonzini     block_job_cancel(job);
37683d948cdfSStefan Hajnoczi out:
37693d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
37706e37fb81SPaolo Bonzini }
37716e37fb81SPaolo Bonzini 
37726e37fb81SPaolo Bonzini void qmp_block_job_pause(const char *device, Error **errp)
3773370521a1SStefan Hajnoczi {
37743d948cdfSStefan Hajnoczi     AioContext *aio_context;
377524d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3776370521a1SStefan Hajnoczi 
3777751ebd76SFam Zheng     if (!job || job->user_paused) {
3778370521a1SStefan Hajnoczi         return;
3779370521a1SStefan Hajnoczi     }
37806e37fb81SPaolo Bonzini 
3781751ebd76SFam Zheng     job->user_paused = true;
37826e37fb81SPaolo Bonzini     trace_qmp_block_job_pause(job);
37836e37fb81SPaolo Bonzini     block_job_pause(job);
37843d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
37856e37fb81SPaolo Bonzini }
37866e37fb81SPaolo Bonzini 
37876e37fb81SPaolo Bonzini void qmp_block_job_resume(const char *device, Error **errp)
37886e37fb81SPaolo Bonzini {
37893d948cdfSStefan Hajnoczi     AioContext *aio_context;
379024d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
37916e37fb81SPaolo Bonzini 
3792751ebd76SFam Zheng     if (!job || !job->user_paused) {
37938acc72a4SPaolo Bonzini         return;
37948acc72a4SPaolo Bonzini     }
3795370521a1SStefan Hajnoczi 
3796751ebd76SFam Zheng     job->user_paused = false;
37976e37fb81SPaolo Bonzini     trace_qmp_block_job_resume(job);
37986e37fb81SPaolo Bonzini     block_job_resume(job);
37993d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3800370521a1SStefan Hajnoczi }
3801fb5458cdSStefan Hajnoczi 
3802aeae883bSPaolo Bonzini void qmp_block_job_complete(const char *device, Error **errp)
3803aeae883bSPaolo Bonzini {
38043d948cdfSStefan Hajnoczi     AioContext *aio_context;
380524d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3806aeae883bSPaolo Bonzini 
3807aeae883bSPaolo Bonzini     if (!job) {
3808aeae883bSPaolo Bonzini         return;
3809aeae883bSPaolo Bonzini     }
3810aeae883bSPaolo Bonzini 
3811aeae883bSPaolo Bonzini     trace_qmp_block_job_complete(job);
3812aeae883bSPaolo Bonzini     block_job_complete(job, errp);
38133d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3814aeae883bSPaolo Bonzini }
3815aeae883bSPaolo Bonzini 
3816fa40e656SJeff Cody void qmp_change_backing_file(const char *device,
3817fa40e656SJeff Cody                              const char *image_node_name,
3818fa40e656SJeff Cody                              const char *backing_file,
3819fa40e656SJeff Cody                              Error **errp)
3820fa40e656SJeff Cody {
3821a0e8544cSFam Zheng     BlockBackend *blk;
3822fa40e656SJeff Cody     BlockDriverState *bs = NULL;
3823729962f6SStefan Hajnoczi     AioContext *aio_context;
3824fa40e656SJeff Cody     BlockDriverState *image_bs = NULL;
3825fa40e656SJeff Cody     Error *local_err = NULL;
3826fa40e656SJeff Cody     bool ro;
3827fa40e656SJeff Cody     int open_flags;
3828fa40e656SJeff Cody     int ret;
3829fa40e656SJeff Cody 
3830a0e8544cSFam Zheng     blk = blk_by_name(device);
3831a0e8544cSFam Zheng     if (!blk) {
383275158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
383375158ebbSMarkus Armbruster                   "Device '%s' not found", device);
3834fa40e656SJeff Cody         return;
3835fa40e656SJeff Cody     }
3836fa40e656SJeff Cody 
38375433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3838729962f6SStefan Hajnoczi     aio_context_acquire(aio_context);
3839729962f6SStefan Hajnoczi 
38405433c24fSMax Reitz     if (!blk_is_available(blk)) {
38415433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
38425433c24fSMax Reitz         goto out;
38435433c24fSMax Reitz     }
38445433c24fSMax Reitz     bs = blk_bs(blk);
38455433c24fSMax Reitz 
3846fa40e656SJeff Cody     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3847fa40e656SJeff Cody     if (local_err) {
3848fa40e656SJeff Cody         error_propagate(errp, local_err);
3849729962f6SStefan Hajnoczi         goto out;
3850fa40e656SJeff Cody     }
3851fa40e656SJeff Cody 
3852fa40e656SJeff Cody     if (!image_bs) {
3853fa40e656SJeff Cody         error_setg(errp, "image file not found");
3854729962f6SStefan Hajnoczi         goto out;
3855fa40e656SJeff Cody     }
3856fa40e656SJeff Cody 
3857fa40e656SJeff Cody     if (bdrv_find_base(image_bs) == image_bs) {
3858fa40e656SJeff Cody         error_setg(errp, "not allowing backing file change on an image "
3859fa40e656SJeff Cody                          "without a backing file");
3860729962f6SStefan Hajnoczi         goto out;
3861fa40e656SJeff Cody     }
3862fa40e656SJeff Cody 
3863fa40e656SJeff Cody     /* even though we are not necessarily operating on bs, we need it to
3864fa40e656SJeff Cody      * determine if block ops are currently prohibited on the chain */
3865fa40e656SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3866729962f6SStefan Hajnoczi         goto out;
3867fa40e656SJeff Cody     }
3868fa40e656SJeff Cody 
3869fa40e656SJeff Cody     /* final sanity check */
3870fa40e656SJeff Cody     if (!bdrv_chain_contains(bs, image_bs)) {
3871fa40e656SJeff Cody         error_setg(errp, "'%s' and image file are not in the same chain",
3872fa40e656SJeff Cody                    device);
3873729962f6SStefan Hajnoczi         goto out;
3874fa40e656SJeff Cody     }
3875fa40e656SJeff Cody 
3876fa40e656SJeff Cody     /* if not r/w, reopen to make r/w */
3877fa40e656SJeff Cody     open_flags = image_bs->open_flags;
3878fa40e656SJeff Cody     ro = bdrv_is_read_only(image_bs);
3879fa40e656SJeff Cody 
3880fa40e656SJeff Cody     if (ro) {
3881fa40e656SJeff Cody         bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3882fa40e656SJeff Cody         if (local_err) {
3883fa40e656SJeff Cody             error_propagate(errp, local_err);
3884729962f6SStefan Hajnoczi             goto out;
3885fa40e656SJeff Cody         }
3886fa40e656SJeff Cody     }
3887fa40e656SJeff Cody 
3888fa40e656SJeff Cody     ret = bdrv_change_backing_file(image_bs, backing_file,
3889fa40e656SJeff Cody                                image_bs->drv ? image_bs->drv->format_name : "");
3890fa40e656SJeff Cody 
3891fa40e656SJeff Cody     if (ret < 0) {
3892fa40e656SJeff Cody         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3893fa40e656SJeff Cody                          backing_file);
3894fa40e656SJeff Cody         /* don't exit here, so we can try to restore open flags if
3895fa40e656SJeff Cody          * appropriate */
3896fa40e656SJeff Cody     }
3897fa40e656SJeff Cody 
3898fa40e656SJeff Cody     if (ro) {
3899fa40e656SJeff Cody         bdrv_reopen(image_bs, open_flags, &local_err);
3900fa40e656SJeff Cody         if (local_err) {
3901fa40e656SJeff Cody             error_propagate(errp, local_err); /* will preserve prior errp */
3902fa40e656SJeff Cody         }
3903fa40e656SJeff Cody     }
3904729962f6SStefan Hajnoczi 
3905729962f6SStefan Hajnoczi out:
3906729962f6SStefan Hajnoczi     aio_context_release(aio_context);
3907fa40e656SJeff Cody }
3908fa40e656SJeff Cody 
3909abb21ac3SKevin Wolf void hmp_drive_add_node(Monitor *mon, const char *optstr)
3910abb21ac3SKevin Wolf {
3911abb21ac3SKevin Wolf     QemuOpts *opts;
3912abb21ac3SKevin Wolf     QDict *qdict;
3913abb21ac3SKevin Wolf     Error *local_err = NULL;
3914abb21ac3SKevin Wolf 
3915abb21ac3SKevin Wolf     opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3916abb21ac3SKevin Wolf     if (!opts) {
3917abb21ac3SKevin Wolf         return;
3918abb21ac3SKevin Wolf     }
3919abb21ac3SKevin Wolf 
3920abb21ac3SKevin Wolf     qdict = qemu_opts_to_qdict(opts, NULL);
3921abb21ac3SKevin Wolf 
3922abb21ac3SKevin Wolf     if (!qdict_get_try_str(qdict, "node-name")) {
3923f8746fb8SKevin Wolf         QDECREF(qdict);
3924abb21ac3SKevin Wolf         error_report("'node-name' needs to be specified");
3925abb21ac3SKevin Wolf         goto out;
3926abb21ac3SKevin Wolf     }
3927abb21ac3SKevin Wolf 
3928abb21ac3SKevin Wolf     BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3929abb21ac3SKevin Wolf     if (!bs) {
3930abb21ac3SKevin Wolf         error_report_err(local_err);
3931abb21ac3SKevin Wolf         goto out;
3932abb21ac3SKevin Wolf     }
3933abb21ac3SKevin Wolf 
3934abb21ac3SKevin Wolf     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3935abb21ac3SKevin Wolf 
3936abb21ac3SKevin Wolf out:
3937abb21ac3SKevin Wolf     qemu_opts_del(opts);
3938abb21ac3SKevin Wolf }
3939abb21ac3SKevin Wolf 
3940d26c9a15SKevin Wolf void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3941d26c9a15SKevin Wolf {
3942d26c9a15SKevin Wolf     QmpOutputVisitor *ov = qmp_output_visitor_new();
3943be4b67bcSMax Reitz     BlockDriverState *bs;
3944be4b67bcSMax Reitz     BlockBackend *blk = NULL;
3945d26c9a15SKevin Wolf     QObject *obj;
3946d26c9a15SKevin Wolf     QDict *qdict;
3947d26c9a15SKevin Wolf     Error *local_err = NULL;
3948d26c9a15SKevin Wolf 
394960e19e06SMarkus Armbruster     /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3950d26c9a15SKevin Wolf      * cache.direct=false instead of silently switching to aio=threads, except
395160e19e06SMarkus Armbruster      * when called from drive_new().
3952d26c9a15SKevin Wolf      *
3953d26c9a15SKevin Wolf      * For now, simply forbidding the combination for all drivers will do. */
3954d26c9a15SKevin Wolf     if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3955c6e0bd9bSKevin Wolf         bool direct = options->has_cache &&
3956c6e0bd9bSKevin Wolf                       options->cache->has_direct &&
3957c6e0bd9bSKevin Wolf                       options->cache->direct;
3958c6e0bd9bSKevin Wolf         if (!direct) {
3959d26c9a15SKevin Wolf             error_setg(errp, "aio=native requires cache.direct=true");
3960d26c9a15SKevin Wolf             goto fail;
3961d26c9a15SKevin Wolf         }
3962d26c9a15SKevin Wolf     }
3963d26c9a15SKevin Wolf 
396451e72bc1SEric Blake     visit_type_BlockdevOptions(qmp_output_get_visitor(ov), NULL, &options,
396551e72bc1SEric Blake                                &local_err);
396684d18f06SMarkus Armbruster     if (local_err) {
3967d26c9a15SKevin Wolf         error_propagate(errp, local_err);
3968d26c9a15SKevin Wolf         goto fail;
3969d26c9a15SKevin Wolf     }
3970d26c9a15SKevin Wolf 
3971d26c9a15SKevin Wolf     obj = qmp_output_get_qobject(ov);
3972d26c9a15SKevin Wolf     qdict = qobject_to_qdict(obj);
3973d26c9a15SKevin Wolf 
3974d26c9a15SKevin Wolf     qdict_flatten(qdict);
3975d26c9a15SKevin Wolf 
3976be4b67bcSMax Reitz     if (options->has_id) {
397718e46a03SMarkus Armbruster         blk = blockdev_init(NULL, qdict, &local_err);
397884d18f06SMarkus Armbruster         if (local_err) {
3979b681072dSKevin Wolf             error_propagate(errp, local_err);
3980d26c9a15SKevin Wolf             goto fail;
3981d26c9a15SKevin Wolf         }
3982d26c9a15SKevin Wolf 
3983be4b67bcSMax Reitz         bs = blk_bs(blk);
3984be4b67bcSMax Reitz     } else {
3985be4b67bcSMax Reitz         if (!qdict_get_try_str(qdict, "node-name")) {
3986be4b67bcSMax Reitz             error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3987be4b67bcSMax Reitz                        "the root node");
3988be4b67bcSMax Reitz             goto fail;
3989be4b67bcSMax Reitz         }
3990be4b67bcSMax Reitz 
3991bd745e23SMax Reitz         bs = bds_tree_init(qdict, errp);
3992bd745e23SMax Reitz         if (!bs) {
3993be4b67bcSMax Reitz             goto fail;
3994be4b67bcSMax Reitz         }
39959c4218e9SMax Reitz 
39969c4218e9SMax Reitz         QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3997be4b67bcSMax Reitz     }
3998be4b67bcSMax Reitz 
3999be4b67bcSMax Reitz     if (bs && bdrv_key_required(bs)) {
4000be4b67bcSMax Reitz         if (blk) {
4001efaa7c4eSMax Reitz             monitor_remove_blk(blk);
400218e46a03SMarkus Armbruster             blk_unref(blk);
4003be4b67bcSMax Reitz         } else {
40049c4218e9SMax Reitz             QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4005be4b67bcSMax Reitz             bdrv_unref(bs);
4006be4b67bcSMax Reitz         }
40078ae8e904SKevin Wolf         error_setg(errp, "blockdev-add doesn't support encrypted devices");
40088ae8e904SKevin Wolf         goto fail;
40098ae8e904SKevin Wolf     }
40108ae8e904SKevin Wolf 
4011d26c9a15SKevin Wolf fail:
4012d26c9a15SKevin Wolf     qmp_output_visitor_cleanup(ov);
4013d26c9a15SKevin Wolf }
4014d26c9a15SKevin Wolf 
401581b936aeSAlberto Garcia void qmp_x_blockdev_del(bool has_id, const char *id,
401681b936aeSAlberto Garcia                         bool has_node_name, const char *node_name, Error **errp)
401781b936aeSAlberto Garcia {
401881b936aeSAlberto Garcia     AioContext *aio_context;
401981b936aeSAlberto Garcia     BlockBackend *blk;
402081b936aeSAlberto Garcia     BlockDriverState *bs;
402181b936aeSAlberto Garcia 
402281b936aeSAlberto Garcia     if (has_id && has_node_name) {
402381b936aeSAlberto Garcia         error_setg(errp, "Only one of id and node-name must be specified");
402481b936aeSAlberto Garcia         return;
402581b936aeSAlberto Garcia     } else if (!has_id && !has_node_name) {
402681b936aeSAlberto Garcia         error_setg(errp, "No block device specified");
402781b936aeSAlberto Garcia         return;
402881b936aeSAlberto Garcia     }
402981b936aeSAlberto Garcia 
403081b936aeSAlberto Garcia     if (has_id) {
4031efaa7c4eSMax Reitz         /* blk_by_name() never returns a BB that is not owned by the monitor */
403281b936aeSAlberto Garcia         blk = blk_by_name(id);
403381b936aeSAlberto Garcia         if (!blk) {
403481b936aeSAlberto Garcia             error_setg(errp, "Cannot find block backend %s", id);
403581b936aeSAlberto Garcia             return;
403681b936aeSAlberto Garcia         }
40375cf87fd6SPaolo Bonzini         if (blk_legacy_dinfo(blk)) {
40385cf87fd6SPaolo Bonzini             error_setg(errp, "Deleting block backend added with drive-add"
40395cf87fd6SPaolo Bonzini                        " is not supported");
40405cf87fd6SPaolo Bonzini             return;
40415cf87fd6SPaolo Bonzini         }
404281b936aeSAlberto Garcia         if (blk_get_refcnt(blk) > 1) {
404381b936aeSAlberto Garcia             error_setg(errp, "Block backend %s is in use", id);
404481b936aeSAlberto Garcia             return;
404581b936aeSAlberto Garcia         }
404681b936aeSAlberto Garcia         bs = blk_bs(blk);
404781b936aeSAlberto Garcia         aio_context = blk_get_aio_context(blk);
404881b936aeSAlberto Garcia     } else {
404981b936aeSAlberto Garcia         bs = bdrv_find_node(node_name);
405081b936aeSAlberto Garcia         if (!bs) {
405181b936aeSAlberto Garcia             error_setg(errp, "Cannot find node %s", node_name);
405281b936aeSAlberto Garcia             return;
405381b936aeSAlberto Garcia         }
405481b936aeSAlberto Garcia         blk = bs->blk;
405581b936aeSAlberto Garcia         if (blk) {
405681b936aeSAlberto Garcia             error_setg(errp, "Node %s is in use by %s",
405781b936aeSAlberto Garcia                        node_name, blk_name(blk));
405881b936aeSAlberto Garcia             return;
405981b936aeSAlberto Garcia         }
406081b936aeSAlberto Garcia         aio_context = bdrv_get_aio_context(bs);
406181b936aeSAlberto Garcia     }
406281b936aeSAlberto Garcia 
406381b936aeSAlberto Garcia     aio_context_acquire(aio_context);
406481b936aeSAlberto Garcia 
406581b936aeSAlberto Garcia     if (bs) {
406681b936aeSAlberto Garcia         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
406781b936aeSAlberto Garcia             goto out;
406881b936aeSAlberto Garcia         }
406981b936aeSAlberto Garcia 
40709c4218e9SMax Reitz         if (!blk && !bs->monitor_list.tqe_prev) {
40719c4218e9SMax Reitz             error_setg(errp, "Node %s is not owned by the monitor",
40729c4218e9SMax Reitz                        bs->node_name);
40739c4218e9SMax Reitz             goto out;
40749c4218e9SMax Reitz         }
40759c4218e9SMax Reitz 
40769c4218e9SMax Reitz         if (bs->refcnt > 1) {
407781b936aeSAlberto Garcia             error_setg(errp, "Block device %s is in use",
407881b936aeSAlberto Garcia                        bdrv_get_device_or_node_name(bs));
407981b936aeSAlberto Garcia             goto out;
408081b936aeSAlberto Garcia         }
408181b936aeSAlberto Garcia     }
408281b936aeSAlberto Garcia 
408381b936aeSAlberto Garcia     if (blk) {
4084efaa7c4eSMax Reitz         monitor_remove_blk(blk);
408581b936aeSAlberto Garcia         blk_unref(blk);
408681b936aeSAlberto Garcia     } else {
40879c4218e9SMax Reitz         QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
408881b936aeSAlberto Garcia         bdrv_unref(bs);
408981b936aeSAlberto Garcia     }
409081b936aeSAlberto Garcia 
409181b936aeSAlberto Garcia out:
409281b936aeSAlberto Garcia     aio_context_release(aio_context);
409381b936aeSAlberto Garcia }
409481b936aeSAlberto Garcia 
40957f821597SWen Congyang static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
40967f821597SWen Congyang                                   const char *child_name)
40977f821597SWen Congyang {
40987f821597SWen Congyang     BdrvChild *child;
40997f821597SWen Congyang 
41007f821597SWen Congyang     QLIST_FOREACH(child, &parent_bs->children, next) {
41017f821597SWen Congyang         if (strcmp(child->name, child_name) == 0) {
41027f821597SWen Congyang             return child;
41037f821597SWen Congyang         }
41047f821597SWen Congyang     }
41057f821597SWen Congyang 
41067f821597SWen Congyang     return NULL;
41077f821597SWen Congyang }
41087f821597SWen Congyang 
41097f821597SWen Congyang void qmp_x_blockdev_change(const char *parent, bool has_child,
41107f821597SWen Congyang                            const char *child, bool has_node,
41117f821597SWen Congyang                            const char *node, Error **errp)
41127f821597SWen Congyang {
41137f821597SWen Congyang     BlockDriverState *parent_bs, *new_bs = NULL;
41147f821597SWen Congyang     BdrvChild *p_child;
41157f821597SWen Congyang 
41167f821597SWen Congyang     parent_bs = bdrv_lookup_bs(parent, parent, errp);
41177f821597SWen Congyang     if (!parent_bs) {
41187f821597SWen Congyang         return;
41197f821597SWen Congyang     }
41207f821597SWen Congyang 
41217f821597SWen Congyang     if (has_child == has_node) {
41227f821597SWen Congyang         if (has_child) {
41237f821597SWen Congyang             error_setg(errp, "The parameters child and node are in conflict");
41247f821597SWen Congyang         } else {
41257f821597SWen Congyang             error_setg(errp, "Either child or node must be specified");
41267f821597SWen Congyang         }
41277f821597SWen Congyang         return;
41287f821597SWen Congyang     }
41297f821597SWen Congyang 
41307f821597SWen Congyang     if (has_child) {
41317f821597SWen Congyang         p_child = bdrv_find_child(parent_bs, child);
41327f821597SWen Congyang         if (!p_child) {
41337f821597SWen Congyang             error_setg(errp, "Node '%s' does not have child '%s'",
41347f821597SWen Congyang                        parent, child);
41357f821597SWen Congyang             return;
41367f821597SWen Congyang         }
41377f821597SWen Congyang         bdrv_del_child(parent_bs, p_child, errp);
41387f821597SWen Congyang     }
41397f821597SWen Congyang 
41407f821597SWen Congyang     if (has_node) {
41417f821597SWen Congyang         new_bs = bdrv_find_node(node);
41427f821597SWen Congyang         if (!new_bs) {
41437f821597SWen Congyang             error_setg(errp, "Node '%s' not found", node);
41447f821597SWen Congyang             return;
41457f821597SWen Congyang         }
41467f821597SWen Congyang         bdrv_add_child(parent_bs, new_bs, errp);
41477f821597SWen Congyang     }
41487f821597SWen Congyang }
41497f821597SWen Congyang 
4150fb5458cdSStefan Hajnoczi BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4151fb5458cdSStefan Hajnoczi {
4152fea68bb6SMarkus Armbruster     BlockJobInfoList *head = NULL, **p_next = &head;
4153fea68bb6SMarkus Armbruster     BlockDriverState *bs;
4154fea68bb6SMarkus Armbruster 
4155fea68bb6SMarkus Armbruster     for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
415669691e72SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
415769691e72SStefan Hajnoczi 
415869691e72SStefan Hajnoczi         aio_context_acquire(aio_context);
415969691e72SStefan Hajnoczi 
4160fea68bb6SMarkus Armbruster         if (bs->job) {
4161fea68bb6SMarkus Armbruster             BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4162fea68bb6SMarkus Armbruster             elem->value = block_job_query(bs->job);
4163fea68bb6SMarkus Armbruster             *p_next = elem;
4164fea68bb6SMarkus Armbruster             p_next = &elem->next;
4165fea68bb6SMarkus Armbruster         }
416669691e72SStefan Hajnoczi 
416769691e72SStefan Hajnoczi         aio_context_release(aio_context);
4168fea68bb6SMarkus Armbruster     }
4169fea68bb6SMarkus Armbruster 
4170fea68bb6SMarkus Armbruster     return head;
4171fb5458cdSStefan Hajnoczi }
41724d454574SPaolo Bonzini 
41730006383eSKevin Wolf QemuOptsList qemu_common_drive_opts = {
41744d454574SPaolo Bonzini     .name = "drive",
41750006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
41764d454574SPaolo Bonzini     .desc = {
41774d454574SPaolo Bonzini         {
41784d454574SPaolo Bonzini             .name = "snapshot",
41794d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
41804d454574SPaolo Bonzini             .help = "enable/disable snapshot mode",
41814d454574SPaolo Bonzini         },{
4182a9384affSPaolo Bonzini             .name = "discard",
4183a9384affSPaolo Bonzini             .type = QEMU_OPT_STRING,
4184a9384affSPaolo Bonzini             .help = "discard operation (ignore/off, unmap/on)",
4185a9384affSPaolo Bonzini         },{
41864d454574SPaolo Bonzini             .name = "aio",
41874d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
41884d454574SPaolo Bonzini             .help = "host AIO implementation (threads, native)",
41894d454574SPaolo Bonzini         },{
4190e4b24b49SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
4191e4b24b49SKevin Wolf             .type = QEMU_OPT_BOOL,
4192e4b24b49SKevin Wolf             .help = "Enable writeback mode",
4193e4b24b49SKevin Wolf         },{
41944d454574SPaolo Bonzini             .name = "format",
41954d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
41964d454574SPaolo Bonzini             .help = "disk format (raw, qcow2, ...)",
41974d454574SPaolo Bonzini         },{
41984d454574SPaolo Bonzini             .name = "rerror",
41994d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
42004d454574SPaolo Bonzini             .help = "read error action",
42014d454574SPaolo Bonzini         },{
42024d454574SPaolo Bonzini             .name = "werror",
42034d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
42044d454574SPaolo Bonzini             .help = "write error action",
42054d454574SPaolo Bonzini         },{
42060f227a94SKevin Wolf             .name = "read-only",
42074d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
42084d454574SPaolo Bonzini             .help = "open drive file as read-only",
42094d454574SPaolo Bonzini         },{
421057975222SKevin Wolf             .name = "throttling.iops-total",
42114d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
42124d454574SPaolo Bonzini             .help = "limit total I/O operations per second",
42134d454574SPaolo Bonzini         },{
421457975222SKevin Wolf             .name = "throttling.iops-read",
42154d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
42164d454574SPaolo Bonzini             .help = "limit read operations per second",
42174d454574SPaolo Bonzini         },{
421857975222SKevin Wolf             .name = "throttling.iops-write",
42194d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
42204d454574SPaolo Bonzini             .help = "limit write operations per second",
42214d454574SPaolo Bonzini         },{
422257975222SKevin Wolf             .name = "throttling.bps-total",
42234d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
42244d454574SPaolo Bonzini             .help = "limit total bytes per second",
42254d454574SPaolo Bonzini         },{
422657975222SKevin Wolf             .name = "throttling.bps-read",
42274d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
42284d454574SPaolo Bonzini             .help = "limit read bytes per second",
42294d454574SPaolo Bonzini         },{
423057975222SKevin Wolf             .name = "throttling.bps-write",
42314d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
42324d454574SPaolo Bonzini             .help = "limit write bytes per second",
42334d454574SPaolo Bonzini         },{
42343e9fab69SBenoît Canet             .name = "throttling.iops-total-max",
42353e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
42363e9fab69SBenoît Canet             .help = "I/O operations burst",
42373e9fab69SBenoît Canet         },{
42383e9fab69SBenoît Canet             .name = "throttling.iops-read-max",
42393e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
42403e9fab69SBenoît Canet             .help = "I/O operations read burst",
42413e9fab69SBenoît Canet         },{
42423e9fab69SBenoît Canet             .name = "throttling.iops-write-max",
42433e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
42443e9fab69SBenoît Canet             .help = "I/O operations write burst",
42453e9fab69SBenoît Canet         },{
42463e9fab69SBenoît Canet             .name = "throttling.bps-total-max",
42473e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
42483e9fab69SBenoît Canet             .help = "total bytes burst",
42493e9fab69SBenoît Canet         },{
42503e9fab69SBenoît Canet             .name = "throttling.bps-read-max",
42513e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
42523e9fab69SBenoît Canet             .help = "total bytes read burst",
42533e9fab69SBenoît Canet         },{
42543e9fab69SBenoît Canet             .name = "throttling.bps-write-max",
42553e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
42563e9fab69SBenoît Canet             .help = "total bytes write burst",
42573e9fab69SBenoît Canet         },{
42588a0fc18dSAlberto Garcia             .name = "throttling.iops-total-max-length",
42598a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
42608a0fc18dSAlberto Garcia             .help = "length of the iops-total-max burst period, in seconds",
42618a0fc18dSAlberto Garcia         },{
42628a0fc18dSAlberto Garcia             .name = "throttling.iops-read-max-length",
42638a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
42648a0fc18dSAlberto Garcia             .help = "length of the iops-read-max burst period, in seconds",
42658a0fc18dSAlberto Garcia         },{
42668a0fc18dSAlberto Garcia             .name = "throttling.iops-write-max-length",
42678a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
42688a0fc18dSAlberto Garcia             .help = "length of the iops-write-max burst period, in seconds",
42698a0fc18dSAlberto Garcia         },{
42708a0fc18dSAlberto Garcia             .name = "throttling.bps-total-max-length",
42718a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
42728a0fc18dSAlberto Garcia             .help = "length of the bps-total-max burst period, in seconds",
42738a0fc18dSAlberto Garcia         },{
42748a0fc18dSAlberto Garcia             .name = "throttling.bps-read-max-length",
42758a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
42768a0fc18dSAlberto Garcia             .help = "length of the bps-read-max burst period, in seconds",
42778a0fc18dSAlberto Garcia         },{
42788a0fc18dSAlberto Garcia             .name = "throttling.bps-write-max-length",
42798a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
42808a0fc18dSAlberto Garcia             .help = "length of the bps-write-max burst period, in seconds",
42818a0fc18dSAlberto Garcia         },{
42822024c1dfSBenoît Canet             .name = "throttling.iops-size",
42832024c1dfSBenoît Canet             .type = QEMU_OPT_NUMBER,
42842024c1dfSBenoît Canet             .help = "when limiting by iops max size of an I/O in bytes",
42852024c1dfSBenoît Canet         },{
428676f4afb4SAlberto Garcia             .name = "throttling.group",
428776f4afb4SAlberto Garcia             .type = QEMU_OPT_STRING,
428876f4afb4SAlberto Garcia             .help = "name of the block throttling group",
428976f4afb4SAlberto Garcia         },{
42904d454574SPaolo Bonzini             .name = "copy-on-read",
42914d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
42924d454574SPaolo Bonzini             .help = "copy read data from backing file into image file",
4293465bee1dSPeter Lieven         },{
4294465bee1dSPeter Lieven             .name = "detect-zeroes",
4295465bee1dSPeter Lieven             .type = QEMU_OPT_STRING,
4296465bee1dSPeter Lieven             .help = "try to optimize zero writes (off, on, unmap)",
4297362e9299SAlberto Garcia         },{
4298362e9299SAlberto Garcia             .name = "stats-account-invalid",
4299362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4300362e9299SAlberto Garcia             .help = "whether to account for invalid I/O operations "
4301362e9299SAlberto Garcia                     "in the statistics",
4302362e9299SAlberto Garcia         },{
4303362e9299SAlberto Garcia             .name = "stats-account-failed",
4304362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4305362e9299SAlberto Garcia             .help = "whether to account for failed I/O operations "
4306362e9299SAlberto Garcia                     "in the statistics",
43074d454574SPaolo Bonzini         },
43084d454574SPaolo Bonzini         { /* end of list */ }
43094d454574SPaolo Bonzini     },
43104d454574SPaolo Bonzini };
43110006383eSKevin Wolf 
4312bd745e23SMax Reitz static QemuOptsList qemu_root_bds_opts = {
4313bd745e23SMax Reitz     .name = "root-bds",
431423f7fcb2SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4315bd745e23SMax Reitz     .desc = {
4316bd745e23SMax Reitz         {
4317bd745e23SMax Reitz             .name = "discard",
4318bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
4319bd745e23SMax Reitz             .help = "discard operation (ignore/off, unmap/on)",
4320bd745e23SMax Reitz         },{
4321bd745e23SMax Reitz             .name = "aio",
4322bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
4323bd745e23SMax Reitz             .help = "host AIO implementation (threads, native)",
4324bd745e23SMax Reitz         },{
4325bd745e23SMax Reitz             .name = "read-only",
4326bd745e23SMax Reitz             .type = QEMU_OPT_BOOL,
4327bd745e23SMax Reitz             .help = "open drive file as read-only",
4328bd745e23SMax Reitz         },{
4329bd745e23SMax Reitz             .name = "copy-on-read",
4330bd745e23SMax Reitz             .type = QEMU_OPT_BOOL,
4331bd745e23SMax Reitz             .help = "copy read data from backing file into image file",
4332bd745e23SMax Reitz         },{
4333bd745e23SMax Reitz             .name = "detect-zeroes",
4334bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
4335bd745e23SMax Reitz             .help = "try to optimize zero writes (off, on, unmap)",
4336bd745e23SMax Reitz         },
4337bd745e23SMax Reitz         { /* end of list */ }
4338bd745e23SMax Reitz     },
4339bd745e23SMax Reitz };
4340bd745e23SMax Reitz 
43410006383eSKevin Wolf QemuOptsList qemu_drive_opts = {
43420006383eSKevin Wolf     .name = "drive",
43430006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
43440006383eSKevin Wolf     .desc = {
4345492fdc6fSKevin Wolf         /*
4346492fdc6fSKevin Wolf          * no elements => accept any params
4347492fdc6fSKevin Wolf          * validation will happen later
4348492fdc6fSKevin Wolf          */
43490006383eSKevin Wolf         { /* end of list */ }
43500006383eSKevin Wolf     },
43510006383eSKevin Wolf };
4352