xref: /openbmc/qemu/blockdev.c (revision f86b8b584b114d68036bf576057f51caec7b94ba)
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"
53666daa68SMarkus Armbruster 
549c4218e9SMax Reitz static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
559c4218e9SMax Reitz     QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
569c4218e9SMax Reitz 
571960966dSMarkus Armbruster static const char *const if_name[IF_COUNT] = {
581960966dSMarkus Armbruster     [IF_NONE] = "none",
591960966dSMarkus Armbruster     [IF_IDE] = "ide",
601960966dSMarkus Armbruster     [IF_SCSI] = "scsi",
611960966dSMarkus Armbruster     [IF_FLOPPY] = "floppy",
621960966dSMarkus Armbruster     [IF_PFLASH] = "pflash",
631960966dSMarkus Armbruster     [IF_MTD] = "mtd",
641960966dSMarkus Armbruster     [IF_SD] = "sd",
651960966dSMarkus Armbruster     [IF_VIRTIO] = "virtio",
661960966dSMarkus Armbruster     [IF_XEN] = "xen",
671960966dSMarkus Armbruster };
681960966dSMarkus Armbruster 
6921dff8cfSJohn Snow static int if_max_devs[IF_COUNT] = {
7027d6bf40SMarkus Armbruster     /*
7127d6bf40SMarkus Armbruster      * Do not change these numbers!  They govern how drive option
7227d6bf40SMarkus Armbruster      * index maps to unit and bus.  That mapping is ABI.
7327d6bf40SMarkus Armbruster      *
7427d6bf40SMarkus Armbruster      * All controllers used to imlement if=T drives need to support
7527d6bf40SMarkus Armbruster      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
7627d6bf40SMarkus Armbruster      * Otherwise, some index values map to "impossible" bus, unit
7727d6bf40SMarkus Armbruster      * values.
7827d6bf40SMarkus Armbruster      *
7927d6bf40SMarkus Armbruster      * For instance, if you change [IF_SCSI] to 255, -drive
8027d6bf40SMarkus Armbruster      * if=scsi,index=12 no longer means bus=1,unit=5, but
8127d6bf40SMarkus Armbruster      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
8227d6bf40SMarkus Armbruster      * the drive can't be set up.  Regression.
8327d6bf40SMarkus Armbruster      */
8427d6bf40SMarkus Armbruster     [IF_IDE] = 2,
8527d6bf40SMarkus Armbruster     [IF_SCSI] = 7,
861960966dSMarkus Armbruster };
871960966dSMarkus Armbruster 
8821dff8cfSJohn Snow /**
8921dff8cfSJohn Snow  * Boards may call this to offer board-by-board overrides
9021dff8cfSJohn Snow  * of the default, global values.
9121dff8cfSJohn Snow  */
9221dff8cfSJohn Snow void override_max_devs(BlockInterfaceType type, int max_devs)
9321dff8cfSJohn Snow {
9418e46a03SMarkus Armbruster     BlockBackend *blk;
9521dff8cfSJohn Snow     DriveInfo *dinfo;
9621dff8cfSJohn Snow 
9721dff8cfSJohn Snow     if (max_devs <= 0) {
9821dff8cfSJohn Snow         return;
9921dff8cfSJohn Snow     }
10021dff8cfSJohn Snow 
10118e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
10218e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
10321dff8cfSJohn Snow         if (dinfo->type == type) {
10421dff8cfSJohn Snow             fprintf(stderr, "Cannot override units-per-bus property of"
10521dff8cfSJohn Snow                     " the %s interface, because a drive of that type has"
10621dff8cfSJohn Snow                     " already been added.\n", if_name[type]);
10721dff8cfSJohn Snow             g_assert_not_reached();
10821dff8cfSJohn Snow         }
10921dff8cfSJohn Snow     }
11021dff8cfSJohn Snow 
11121dff8cfSJohn Snow     if_max_devs[type] = max_devs;
11221dff8cfSJohn Snow }
11321dff8cfSJohn Snow 
11414bafc54SMarkus Armbruster /*
11514bafc54SMarkus Armbruster  * We automatically delete the drive when a device using it gets
11614bafc54SMarkus Armbruster  * unplugged.  Questionable feature, but we can't just drop it.
11714bafc54SMarkus Armbruster  * Device models call blockdev_mark_auto_del() to schedule the
11814bafc54SMarkus Armbruster  * automatic deletion, and generic qdev code calls blockdev_auto_del()
11914bafc54SMarkus Armbruster  * when deletion is actually safe.
12014bafc54SMarkus Armbruster  */
1214be74634SMarkus Armbruster void blockdev_mark_auto_del(BlockBackend *blk)
12214bafc54SMarkus Armbruster {
12318e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
1244be74634SMarkus Armbruster     BlockDriverState *bs = blk_bs(blk);
12591fddb0dSStefan Hajnoczi     AioContext *aio_context;
12614bafc54SMarkus Armbruster 
12726f8b3a8SMarkus Armbruster     if (!dinfo) {
1282d246f01SKevin Wolf         return;
1292d246f01SKevin Wolf     }
1302d246f01SKevin Wolf 
1315433c24fSMax Reitz     if (bs) {
13291fddb0dSStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
13391fddb0dSStefan Hajnoczi         aio_context_acquire(aio_context);
13491fddb0dSStefan Hajnoczi 
13512bde0eeSPaolo Bonzini         if (bs->job) {
13612bde0eeSPaolo Bonzini             block_job_cancel(bs->job);
13712bde0eeSPaolo Bonzini         }
13891fddb0dSStefan Hajnoczi 
13991fddb0dSStefan Hajnoczi         aio_context_release(aio_context);
1405433c24fSMax Reitz     }
14191fddb0dSStefan Hajnoczi 
14214bafc54SMarkus Armbruster     dinfo->auto_del = 1;
14314bafc54SMarkus Armbruster }
14414bafc54SMarkus Armbruster 
1454be74634SMarkus Armbruster void blockdev_auto_del(BlockBackend *blk)
14614bafc54SMarkus Armbruster {
14718e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
14814bafc54SMarkus Armbruster 
1490fc0f1faSRyan Harper     if (dinfo && dinfo->auto_del) {
150b9fe8a7aSMarkus Armbruster         blk_unref(blk);
15114bafc54SMarkus Armbruster     }
15214bafc54SMarkus Armbruster }
15314bafc54SMarkus Armbruster 
154d8f94e1bSJohn Snow /**
155d8f94e1bSJohn Snow  * Returns the current mapping of how many units per bus
156d8f94e1bSJohn Snow  * a particular interface can support.
157d8f94e1bSJohn Snow  *
158d8f94e1bSJohn Snow  *  A positive integer indicates n units per bus.
159d8f94e1bSJohn Snow  *  0 implies the mapping has not been established.
160d8f94e1bSJohn Snow  * -1 indicates an invalid BlockInterfaceType was given.
161d8f94e1bSJohn Snow  */
162d8f94e1bSJohn Snow int drive_get_max_devs(BlockInterfaceType type)
163d8f94e1bSJohn Snow {
164d8f94e1bSJohn Snow     if (type >= IF_IDE && type < IF_COUNT) {
165d8f94e1bSJohn Snow         return if_max_devs[type];
166d8f94e1bSJohn Snow     }
167d8f94e1bSJohn Snow 
168d8f94e1bSJohn Snow     return -1;
169d8f94e1bSJohn Snow }
170d8f94e1bSJohn Snow 
171505a7fb1SMarkus Armbruster static int drive_index_to_bus_id(BlockInterfaceType type, int index)
172505a7fb1SMarkus Armbruster {
173505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
174505a7fb1SMarkus Armbruster     return max_devs ? index / max_devs : 0;
175505a7fb1SMarkus Armbruster }
176505a7fb1SMarkus Armbruster 
177505a7fb1SMarkus Armbruster static int drive_index_to_unit_id(BlockInterfaceType type, int index)
178505a7fb1SMarkus Armbruster {
179505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
180505a7fb1SMarkus Armbruster     return max_devs ? index % max_devs : index;
181505a7fb1SMarkus Armbruster }
182505a7fb1SMarkus Armbruster 
1832292ddaeSMarkus Armbruster QemuOpts *drive_def(const char *optstr)
1842292ddaeSMarkus Armbruster {
18570b94331SMarkus Armbruster     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
1862292ddaeSMarkus Armbruster }
1872292ddaeSMarkus Armbruster 
1882292ddaeSMarkus Armbruster QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
1895645b0f4SMarkus Armbruster                     const char *optstr)
190666daa68SMarkus Armbruster {
191666daa68SMarkus Armbruster     QemuOpts *opts;
192666daa68SMarkus Armbruster 
1932292ddaeSMarkus Armbruster     opts = drive_def(optstr);
194666daa68SMarkus Armbruster     if (!opts) {
195666daa68SMarkus Armbruster         return NULL;
196666daa68SMarkus Armbruster     }
1972292ddaeSMarkus Armbruster     if (type != IF_DEFAULT) {
198f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "if", if_name[type], &error_abort);
1992292ddaeSMarkus Armbruster     }
2002292ddaeSMarkus Armbruster     if (index >= 0) {
201a8b18f8fSMarkus Armbruster         qemu_opt_set_number(opts, "index", index, &error_abort);
2022292ddaeSMarkus Armbruster     }
203666daa68SMarkus Armbruster     if (file)
204f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "file", file, &error_abort);
205666daa68SMarkus Armbruster     return opts;
206666daa68SMarkus Armbruster }
207666daa68SMarkus Armbruster 
208666daa68SMarkus Armbruster DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
209666daa68SMarkus Armbruster {
21018e46a03SMarkus Armbruster     BlockBackend *blk;
211666daa68SMarkus Armbruster     DriveInfo *dinfo;
212666daa68SMarkus Armbruster 
21318e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
21418e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
21518e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type
21618e46a03SMarkus Armbruster             && dinfo->bus == bus && dinfo->unit == unit) {
217666daa68SMarkus Armbruster             return dinfo;
218666daa68SMarkus Armbruster         }
21918e46a03SMarkus Armbruster     }
220666daa68SMarkus Armbruster 
221666daa68SMarkus Armbruster     return NULL;
222666daa68SMarkus Armbruster }
223666daa68SMarkus Armbruster 
224a66c9dc7SJohn Snow bool drive_check_orphaned(void)
225a66c9dc7SJohn Snow {
22618e46a03SMarkus Armbruster     BlockBackend *blk;
227a66c9dc7SJohn Snow     DriveInfo *dinfo;
228a66c9dc7SJohn Snow     bool rs = false;
229a66c9dc7SJohn Snow 
23018e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
23118e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
232a66c9dc7SJohn Snow         /* If dinfo->bdrv->dev is NULL, it has no device attached. */
233a66c9dc7SJohn Snow         /* Unless this is a default drive, this may be an oversight. */
234a7f53e26SMarkus Armbruster         if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
235a66c9dc7SJohn Snow             dinfo->type != IF_NONE) {
236a66c9dc7SJohn Snow             fprintf(stderr, "Warning: Orphaned drive without device: "
237a66c9dc7SJohn Snow                     "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
2385433c24fSMax Reitz                     blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
2395433c24fSMax Reitz                     if_name[dinfo->type], dinfo->bus, dinfo->unit);
240a66c9dc7SJohn Snow             rs = true;
241a66c9dc7SJohn Snow         }
242a66c9dc7SJohn Snow     }
243a66c9dc7SJohn Snow 
244a66c9dc7SJohn Snow     return rs;
245a66c9dc7SJohn Snow }
246a66c9dc7SJohn Snow 
247f1bd51acSMarkus Armbruster DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
248f1bd51acSMarkus Armbruster {
249f1bd51acSMarkus Armbruster     return drive_get(type,
250f1bd51acSMarkus Armbruster                      drive_index_to_bus_id(type, index),
251f1bd51acSMarkus Armbruster                      drive_index_to_unit_id(type, index));
252f1bd51acSMarkus Armbruster }
253f1bd51acSMarkus Armbruster 
254666daa68SMarkus Armbruster int drive_get_max_bus(BlockInterfaceType type)
255666daa68SMarkus Armbruster {
256666daa68SMarkus Armbruster     int max_bus;
25718e46a03SMarkus Armbruster     BlockBackend *blk;
258666daa68SMarkus Armbruster     DriveInfo *dinfo;
259666daa68SMarkus Armbruster 
260666daa68SMarkus Armbruster     max_bus = -1;
26118e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
26218e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
26318e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
264666daa68SMarkus Armbruster             max_bus = dinfo->bus;
265666daa68SMarkus Armbruster         }
26618e46a03SMarkus Armbruster     }
267666daa68SMarkus Armbruster     return max_bus;
268666daa68SMarkus Armbruster }
269666daa68SMarkus Armbruster 
27013839974SMarkus Armbruster /* Get a block device.  This should only be used for single-drive devices
27113839974SMarkus Armbruster    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
27213839974SMarkus Armbruster    appropriate bus.  */
27313839974SMarkus Armbruster DriveInfo *drive_get_next(BlockInterfaceType type)
27413839974SMarkus Armbruster {
27513839974SMarkus Armbruster     static int next_block_unit[IF_COUNT];
27613839974SMarkus Armbruster 
27713839974SMarkus Armbruster     return drive_get(type, 0, next_block_unit[type]++);
27813839974SMarkus Armbruster }
27913839974SMarkus Armbruster 
280666daa68SMarkus Armbruster static void bdrv_format_print(void *opaque, const char *name)
281666daa68SMarkus Armbruster {
282807105a7SMarkus Armbruster     error_printf(" %s", name);
283666daa68SMarkus Armbruster }
284666daa68SMarkus Armbruster 
285aa398a5cSStefan Hajnoczi typedef struct {
286aa398a5cSStefan Hajnoczi     QEMUBH *bh;
287fa510ebfSFam Zheng     BlockDriverState *bs;
288fa510ebfSFam Zheng } BDRVPutRefBH;
289aa398a5cSStefan Hajnoczi 
290b681072dSKevin Wolf static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
291666daa68SMarkus Armbruster {
292666daa68SMarkus Armbruster     if (!strcmp(buf, "ignore")) {
29392aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_IGNORE;
294666daa68SMarkus Armbruster     } else if (!is_read && !strcmp(buf, "enospc")) {
29592aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_ENOSPC;
296666daa68SMarkus Armbruster     } else if (!strcmp(buf, "stop")) {
29792aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_STOP;
298666daa68SMarkus Armbruster     } else if (!strcmp(buf, "report")) {
29992aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_REPORT;
300666daa68SMarkus Armbruster     } else {
301b681072dSKevin Wolf         error_setg(errp, "'%s' invalid %s error action",
302666daa68SMarkus Armbruster                    buf, is_read ? "read" : "write");
303666daa68SMarkus Armbruster         return -1;
304666daa68SMarkus Armbruster     }
305666daa68SMarkus Armbruster }
306666daa68SMarkus Armbruster 
30740119effSAlberto Garcia static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
30840119effSAlberto Garcia                                   Error **errp)
30940119effSAlberto Garcia {
31040119effSAlberto Garcia     const QListEntry *entry;
31140119effSAlberto Garcia     for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
31240119effSAlberto Garcia         switch (qobject_type(entry->value)) {
31340119effSAlberto Garcia 
31440119effSAlberto Garcia         case QTYPE_QSTRING: {
31540119effSAlberto Garcia             unsigned long long length;
31640119effSAlberto Garcia             const char *str = qstring_get_str(qobject_to_qstring(entry->value));
31740119effSAlberto Garcia             if (parse_uint_full(str, &length, 10) == 0 &&
31840119effSAlberto Garcia                 length > 0 && length <= UINT_MAX) {
31940119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
32040119effSAlberto Garcia             } else {
32140119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %s", str);
32240119effSAlberto Garcia                 return false;
32340119effSAlberto Garcia             }
32440119effSAlberto Garcia             break;
32540119effSAlberto Garcia         }
32640119effSAlberto Garcia 
32740119effSAlberto Garcia         case QTYPE_QINT: {
32840119effSAlberto Garcia             int64_t length = qint_get_int(qobject_to_qint(entry->value));
32940119effSAlberto Garcia             if (length > 0 && length <= UINT_MAX) {
33040119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
33140119effSAlberto Garcia             } else {
33240119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %" PRId64, length);
33340119effSAlberto Garcia                 return false;
33440119effSAlberto Garcia             }
33540119effSAlberto Garcia             break;
33640119effSAlberto Garcia         }
33740119effSAlberto Garcia 
33840119effSAlberto Garcia         default:
33940119effSAlberto Garcia             error_setg(errp, "The specification of stats-intervals is invalid");
34040119effSAlberto Garcia             return false;
34140119effSAlberto Garcia         }
34240119effSAlberto Garcia     }
34340119effSAlberto Garcia     return true;
34440119effSAlberto Garcia }
34540119effSAlberto Garcia 
34633cb7dc8SKevin Wolf typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
34733cb7dc8SKevin Wolf 
348fbf8175eSMax Reitz /* All parameters but @opts are optional and may be set to NULL. */
349fbf8175eSMax Reitz static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
350fbf8175eSMax Reitz     const char **throttling_group, ThrottleConfig *throttle_cfg,
351fbf8175eSMax Reitz     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
352fbf8175eSMax Reitz {
353fbf8175eSMax Reitz     const char *discard;
354fbf8175eSMax Reitz     Error *local_error = NULL;
355fbf8175eSMax Reitz     const char *aio;
356fbf8175eSMax Reitz 
357fbf8175eSMax Reitz     if (bdrv_flags) {
358fbf8175eSMax Reitz         if (!qemu_opt_get_bool(opts, "read-only", false)) {
359fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_RDWR;
360fbf8175eSMax Reitz         }
361fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
362fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_COPY_ON_READ;
363fbf8175eSMax Reitz         }
364fbf8175eSMax Reitz 
365fbf8175eSMax Reitz         if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
366fbf8175eSMax Reitz             if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
367fbf8175eSMax Reitz                 error_setg(errp, "Invalid discard option");
368fbf8175eSMax Reitz                 return;
369fbf8175eSMax Reitz             }
370fbf8175eSMax Reitz         }
371fbf8175eSMax Reitz 
372fbf8175eSMax Reitz         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
373fbf8175eSMax Reitz             if (!strcmp(aio, "native")) {
374fbf8175eSMax Reitz                 *bdrv_flags |= BDRV_O_NATIVE_AIO;
375fbf8175eSMax Reitz             } else if (!strcmp(aio, "threads")) {
376fbf8175eSMax Reitz                 /* this is the default */
377fbf8175eSMax Reitz             } else {
378fbf8175eSMax Reitz                error_setg(errp, "invalid aio option");
379fbf8175eSMax Reitz                return;
380fbf8175eSMax Reitz             }
381fbf8175eSMax Reitz         }
382fbf8175eSMax Reitz     }
383fbf8175eSMax Reitz 
384fbf8175eSMax Reitz     /* disk I/O throttling */
385fbf8175eSMax Reitz     if (throttling_group) {
386fbf8175eSMax Reitz         *throttling_group = qemu_opt_get(opts, "throttling.group");
387fbf8175eSMax Reitz     }
388fbf8175eSMax Reitz 
389fbf8175eSMax Reitz     if (throttle_cfg) {
3901588ab5dSAlberto Garcia         throttle_config_init(throttle_cfg);
391fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
392fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total", 0);
393fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
394fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read", 0);
395fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
396fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write", 0);
397fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
398fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total", 0);
399fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
400fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read", 0);
401fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
402fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write", 0);
403fbf8175eSMax Reitz 
404fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
405fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
406fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
407fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
408fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
409fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
410fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
411fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
412fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
413fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
414fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
415fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
416fbf8175eSMax Reitz 
4178a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
4188a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
4198a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length  =
4208a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
4218a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
4228a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
4238a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
4248a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
4258a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
4268a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
4278a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
4288a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
4298a0fc18dSAlberto Garcia 
430fbf8175eSMax Reitz         throttle_cfg->op_size =
431fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-size", 0);
432fbf8175eSMax Reitz 
433d5851089SAlberto Garcia         if (!throttle_is_valid(throttle_cfg, errp)) {
434fbf8175eSMax Reitz             return;
435fbf8175eSMax Reitz         }
436fbf8175eSMax Reitz     }
437fbf8175eSMax Reitz 
438fbf8175eSMax Reitz     if (detect_zeroes) {
439fbf8175eSMax Reitz         *detect_zeroes =
440fbf8175eSMax Reitz             qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
441fbf8175eSMax Reitz                             qemu_opt_get(opts, "detect-zeroes"),
4427fb1cf16SEric Blake                             BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
443fbf8175eSMax Reitz                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
444fbf8175eSMax Reitz                             &local_error);
445fbf8175eSMax Reitz         if (local_error) {
446fbf8175eSMax Reitz             error_propagate(errp, local_error);
447fbf8175eSMax Reitz             return;
448fbf8175eSMax Reitz         }
449fbf8175eSMax Reitz 
450fbf8175eSMax Reitz         if (bdrv_flags &&
451fbf8175eSMax Reitz             *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
452fbf8175eSMax Reitz             !(*bdrv_flags & BDRV_O_UNMAP))
453fbf8175eSMax Reitz         {
454fbf8175eSMax Reitz             error_setg(errp, "setting detect-zeroes to unmap is not allowed "
455fbf8175eSMax Reitz                              "without setting discard operation to unmap");
456fbf8175eSMax Reitz             return;
457fbf8175eSMax Reitz         }
458fbf8175eSMax Reitz     }
459fbf8175eSMax Reitz }
460fbf8175eSMax Reitz 
461f298d071SKevin Wolf /* Takes the ownership of bs_opts */
46218e46a03SMarkus Armbruster static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
463b681072dSKevin Wolf                                    Error **errp)
464666daa68SMarkus Armbruster {
465666daa68SMarkus Armbruster     const char *buf;
466666daa68SMarkus Armbruster     int bdrv_flags = 0;
467666daa68SMarkus Armbruster     int on_read_error, on_write_error;
468362e9299SAlberto Garcia     bool account_invalid, account_failed;
46926f54e9aSMarkus Armbruster     BlockBackend *blk;
470a0f1eab1SMarkus Armbruster     BlockDriverState *bs;
471cc0681c4SBenoît Canet     ThrottleConfig cfg;
472666daa68SMarkus Armbruster     int snapshot = 0;
473c546194fSStefan Hajnoczi     Error *error = NULL;
4740006383eSKevin Wolf     QemuOpts *opts;
47540119effSAlberto Garcia     QDict *interval_dict = NULL;
47640119effSAlberto Garcia     QList *interval_list = NULL;
4770006383eSKevin Wolf     const char *id;
478fbf8175eSMax Reitz     BlockdevDetectZeroesOptions detect_zeroes =
479fbf8175eSMax Reitz         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
480fbf8175eSMax Reitz     const char *throttling_group = NULL;
481666daa68SMarkus Armbruster 
482f298d071SKevin Wolf     /* Check common options by copying from bs_opts to opts, all other options
483f298d071SKevin Wolf      * stay in bs_opts for processing by bdrv_open(). */
484f298d071SKevin Wolf     id = qdict_get_try_str(bs_opts, "id");
4850006383eSKevin Wolf     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
48684d18f06SMarkus Armbruster     if (error) {
487b681072dSKevin Wolf         error_propagate(errp, error);
4886376f952SMarkus Armbruster         goto err_no_opts;
4890006383eSKevin Wolf     }
4900006383eSKevin Wolf 
4910006383eSKevin Wolf     qemu_opts_absorb_qdict(opts, bs_opts, &error);
49284d18f06SMarkus Armbruster     if (error) {
493b681072dSKevin Wolf         error_propagate(errp, error);
494ec9c10d2SStefan Hajnoczi         goto early_err;
4950006383eSKevin Wolf     }
4960006383eSKevin Wolf 
4970006383eSKevin Wolf     if (id) {
4980006383eSKevin Wolf         qdict_del(bs_opts, "id");
4990006383eSKevin Wolf     }
5000006383eSKevin Wolf 
501666daa68SMarkus Armbruster     /* extract parameters */
502666daa68SMarkus Armbruster     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
503666daa68SMarkus Armbruster 
504362e9299SAlberto Garcia     account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
505362e9299SAlberto Garcia     account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
506362e9299SAlberto Garcia 
50740119effSAlberto Garcia     qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
50840119effSAlberto Garcia     qdict_array_split(interval_dict, &interval_list);
50940119effSAlberto Garcia 
51040119effSAlberto Garcia     if (qdict_size(interval_dict) != 0) {
51140119effSAlberto Garcia         error_setg(errp, "Invalid option stats-intervals.%s",
51240119effSAlberto Garcia                    qdict_first(interval_dict)->key);
51340119effSAlberto Garcia         goto early_err;
51440119effSAlberto Garcia     }
5152be5506fSAlberto Garcia 
516fbf8175eSMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
517fbf8175eSMax Reitz                                     &detect_zeroes, &error);
518fbf8175eSMax Reitz     if (error) {
519fbf8175eSMax Reitz         error_propagate(errp, error);
520ec9c10d2SStefan Hajnoczi         goto early_err;
521a9384affSPaolo Bonzini     }
522666daa68SMarkus Armbruster 
523666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
524c8057f95SPeter Maydell         if (is_help_option(buf)) {
525807105a7SMarkus Armbruster             error_printf("Supported formats:");
526666daa68SMarkus Armbruster             bdrv_iterate_format(bdrv_format_print, NULL);
527807105a7SMarkus Armbruster             error_printf("\n");
528ec9c10d2SStefan Hajnoczi             goto early_err;
529666daa68SMarkus Armbruster         }
53074fe54f2SKevin Wolf 
531e4342ce5SMax Reitz         if (qdict_haskey(bs_opts, "driver")) {
532e4342ce5SMax Reitz             error_setg(errp, "Cannot specify both 'driver' and 'format'");
533ec9c10d2SStefan Hajnoczi             goto early_err;
5346db5f5d6SMike Qiu         }
535e4342ce5SMax Reitz         qdict_put(bs_opts, "driver", qstring_from_str(buf));
536666daa68SMarkus Armbruster     }
537666daa68SMarkus Armbruster 
53892aa5c6dSPaolo Bonzini     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
539666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
540b681072dSKevin Wolf         on_write_error = parse_block_error_action(buf, 0, &error);
54184d18f06SMarkus Armbruster         if (error) {
542b681072dSKevin Wolf             error_propagate(errp, error);
543ec9c10d2SStefan Hajnoczi             goto early_err;
544666daa68SMarkus Armbruster         }
545666daa68SMarkus Armbruster     }
546666daa68SMarkus Armbruster 
54792aa5c6dSPaolo Bonzini     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
548666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
549b681072dSKevin Wolf         on_read_error = parse_block_error_action(buf, 1, &error);
55084d18f06SMarkus Armbruster         if (error) {
551b681072dSKevin Wolf             error_propagate(errp, error);
552ec9c10d2SStefan Hajnoczi             goto early_err;
553666daa68SMarkus Armbruster         }
554666daa68SMarkus Armbruster     }
555666daa68SMarkus Armbruster 
556666daa68SMarkus Armbruster     if (snapshot) {
55791a097e7SKevin Wolf         bdrv_flags |= BDRV_O_SNAPSHOT;
558666daa68SMarkus Armbruster     }
559666daa68SMarkus Armbruster 
5605ec18f8cSMax Reitz     /* init */
56139c4ae94SKevin Wolf     if ((!file || !*file) && !qdict_size(bs_opts)) {
5625ec18f8cSMax Reitz         BlockBackendRootState *blk_rs;
5635ec18f8cSMax Reitz 
5645ec18f8cSMax Reitz         blk = blk_new(qemu_opts_id(opts), errp);
5655ec18f8cSMax Reitz         if (!blk) {
5665ec18f8cSMax Reitz             goto early_err;
5675ec18f8cSMax Reitz         }
5685ec18f8cSMax Reitz 
5695ec18f8cSMax Reitz         blk_rs = blk_get_root_state(blk);
5705ec18f8cSMax Reitz         blk_rs->open_flags    = bdrv_flags;
571fbf8175eSMax Reitz         blk_rs->read_only     = !(bdrv_flags & BDRV_O_RDWR);
5725ec18f8cSMax Reitz         blk_rs->detect_zeroes = detect_zeroes;
5735ec18f8cSMax Reitz 
5745ec18f8cSMax Reitz         if (throttle_enabled(&cfg)) {
5755ec18f8cSMax Reitz             if (!throttling_group) {
5765ec18f8cSMax Reitz                 throttling_group = blk_name(blk);
5775ec18f8cSMax Reitz             }
5785ec18f8cSMax Reitz             blk_rs->throttle_group = g_strdup(throttling_group);
5795ec18f8cSMax Reitz             blk_rs->throttle_state = throttle_group_incref(throttling_group);
5805ec18f8cSMax Reitz             blk_rs->throttle_state->cfg = cfg;
5815ec18f8cSMax Reitz         }
5825ec18f8cSMax Reitz 
5835ec18f8cSMax Reitz         QDECREF(bs_opts);
5845ec18f8cSMax Reitz     } else {
5855ec18f8cSMax Reitz         if (file && !*file) {
5865ec18f8cSMax Reitz             file = NULL;
5875ec18f8cSMax Reitz         }
5885ec18f8cSMax Reitz 
58991a097e7SKevin Wolf         /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
59091a097e7SKevin Wolf          * with other callers) rather than what we want as the real defaults.
59191a097e7SKevin Wolf          * Apply the defaults here instead. */
59291a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_WB, "on");
59391a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
59491a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
59591a097e7SKevin Wolf 
59691a097e7SKevin Wolf         if (snapshot) {
59791a097e7SKevin Wolf             /* always use cache=unsafe with snapshot */
59891a097e7SKevin Wolf             qdict_put(bs_opts, BDRV_OPT_CACHE_WB, qstring_from_str("on"));
59991a097e7SKevin Wolf             qdict_put(bs_opts, BDRV_OPT_CACHE_DIRECT, qstring_from_str("off"));
60091a097e7SKevin Wolf             qdict_put(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, qstring_from_str("on"));
60191a097e7SKevin Wolf         }
60291a097e7SKevin Wolf 
60312d5ee3aSKevin Wolf         if (runstate_check(RUN_STATE_INMIGRATE)) {
60412d5ee3aSKevin Wolf             bdrv_flags |= BDRV_O_INACTIVE;
60512d5ee3aSKevin Wolf         }
60612d5ee3aSKevin Wolf 
607e4342ce5SMax Reitz         blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
608e4342ce5SMax Reitz                            errp);
609e4342ce5SMax Reitz         if (!blk) {
610e4342ce5SMax Reitz             goto err_no_bs_opts;
611e4342ce5SMax Reitz         }
612e4342ce5SMax Reitz         bs = blk_bs(blk);
6130006383eSKevin Wolf 
614e4342ce5SMax Reitz         bs->detect_zeroes = detect_zeroes;
615e4342ce5SMax Reitz 
616e4342ce5SMax Reitz         /* disk I/O throttling */
617e4342ce5SMax Reitz         if (throttle_enabled(&cfg)) {
61876f4afb4SAlberto Garcia             if (!throttling_group) {
61976f4afb4SAlberto Garcia                 throttling_group = blk_name(blk);
62076f4afb4SAlberto Garcia             }
62176f4afb4SAlberto Garcia             bdrv_io_limits_enable(bs, throttling_group);
622e4342ce5SMax Reitz             bdrv_set_io_limits(bs, &cfg);
623666daa68SMarkus Armbruster         }
624666daa68SMarkus Armbruster 
625a0f1eab1SMarkus Armbruster         if (bdrv_key_required(bs)) {
626666daa68SMarkus Armbruster             autostart = 0;
627a0f1eab1SMarkus Armbruster         }
628362e9299SAlberto Garcia 
629362e9299SAlberto Garcia         block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
6302be5506fSAlberto Garcia 
63140119effSAlberto Garcia         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
6322be5506fSAlberto Garcia             blk_unref(blk);
6332be5506fSAlberto Garcia             blk = NULL;
6342be5506fSAlberto Garcia             goto err_no_bs_opts;
6352be5506fSAlberto Garcia         }
6362be5506fSAlberto Garcia     }
6375ec18f8cSMax Reitz 
6385ec18f8cSMax Reitz     blk_set_on_error(blk, on_read_error, on_write_error);
6390006383eSKevin Wolf 
640e4342ce5SMax Reitz err_no_bs_opts:
6410006383eSKevin Wolf     qemu_opts_del(opts);
64240119effSAlberto Garcia     QDECREF(interval_dict);
64340119effSAlberto Garcia     QDECREF(interval_list);
64418e46a03SMarkus Armbruster     return blk;
645a9ae2bffSMarkus Armbruster 
646ec9c10d2SStefan Hajnoczi early_err:
647ec9c10d2SStefan Hajnoczi     qemu_opts_del(opts);
64840119effSAlberto Garcia     QDECREF(interval_dict);
64940119effSAlberto Garcia     QDECREF(interval_list);
6506376f952SMarkus Armbruster err_no_opts:
6516376f952SMarkus Armbruster     QDECREF(bs_opts);
652a9ae2bffSMarkus Armbruster     return NULL;
653666daa68SMarkus Armbruster }
654666daa68SMarkus Armbruster 
655bd745e23SMax Reitz static QemuOptsList qemu_root_bds_opts;
656bd745e23SMax Reitz 
657bd745e23SMax Reitz /* Takes the ownership of bs_opts */
658bd745e23SMax Reitz static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
659bd745e23SMax Reitz {
660bd745e23SMax Reitz     BlockDriverState *bs;
661bd745e23SMax Reitz     QemuOpts *opts;
662bd745e23SMax Reitz     Error *local_error = NULL;
663bd745e23SMax Reitz     BlockdevDetectZeroesOptions detect_zeroes;
664bd745e23SMax Reitz     int ret;
665bd745e23SMax Reitz     int bdrv_flags = 0;
666bd745e23SMax Reitz 
667bd745e23SMax Reitz     opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
668bd745e23SMax Reitz     if (!opts) {
669bd745e23SMax Reitz         goto fail;
670bd745e23SMax Reitz     }
671bd745e23SMax Reitz 
672bd745e23SMax Reitz     qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
673bd745e23SMax Reitz     if (local_error) {
674bd745e23SMax Reitz         error_propagate(errp, local_error);
675bd745e23SMax Reitz         goto fail;
676bd745e23SMax Reitz     }
677bd745e23SMax Reitz 
678bd745e23SMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
679bd745e23SMax Reitz                                     &detect_zeroes, &local_error);
680bd745e23SMax Reitz     if (local_error) {
681bd745e23SMax Reitz         error_propagate(errp, local_error);
682bd745e23SMax Reitz         goto fail;
683bd745e23SMax Reitz     }
684bd745e23SMax Reitz 
68512d5ee3aSKevin Wolf     if (runstate_check(RUN_STATE_INMIGRATE)) {
68612d5ee3aSKevin Wolf         bdrv_flags |= BDRV_O_INACTIVE;
68712d5ee3aSKevin Wolf     }
68812d5ee3aSKevin Wolf 
689bd745e23SMax Reitz     bs = NULL;
690bd745e23SMax Reitz     ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
691bd745e23SMax Reitz     if (ret < 0) {
692bd745e23SMax Reitz         goto fail_no_bs_opts;
693bd745e23SMax Reitz     }
694bd745e23SMax Reitz 
695bd745e23SMax Reitz     bs->detect_zeroes = detect_zeroes;
696bd745e23SMax Reitz 
697bd745e23SMax Reitz fail_no_bs_opts:
698bd745e23SMax Reitz     qemu_opts_del(opts);
699bd745e23SMax Reitz     return bs;
700bd745e23SMax Reitz 
701bd745e23SMax Reitz fail:
702bd745e23SMax Reitz     qemu_opts_del(opts);
703bd745e23SMax Reitz     QDECREF(bs_opts);
704bd745e23SMax Reitz     return NULL;
705bd745e23SMax Reitz }
706bd745e23SMax Reitz 
7079c4218e9SMax Reitz void blockdev_close_all_bdrv_states(void)
7089c4218e9SMax Reitz {
7099c4218e9SMax Reitz     BlockDriverState *bs, *next_bs;
7109c4218e9SMax Reitz 
7119c4218e9SMax Reitz     QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
7129c4218e9SMax Reitz         AioContext *ctx = bdrv_get_aio_context(bs);
7139c4218e9SMax Reitz 
7149c4218e9SMax Reitz         aio_context_acquire(ctx);
7159c4218e9SMax Reitz         bdrv_unref(bs);
7169c4218e9SMax Reitz         aio_context_release(ctx);
7179c4218e9SMax Reitz     }
7189c4218e9SMax Reitz }
7199c4218e9SMax Reitz 
7205abbf0eeSKevin Wolf static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
7215abbf0eeSKevin Wolf                             Error **errp)
72257975222SKevin Wolf {
72357975222SKevin Wolf     const char *value;
72457975222SKevin Wolf 
72557975222SKevin Wolf     value = qemu_opt_get(opts, from);
72657975222SKevin Wolf     if (value) {
7275abbf0eeSKevin Wolf         if (qemu_opt_find(opts, to)) {
7285abbf0eeSKevin Wolf             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
7295abbf0eeSKevin Wolf                        "same time", to, from);
7305abbf0eeSKevin Wolf             return;
7315abbf0eeSKevin Wolf         }
73220d6cd47SJun Li     }
73320d6cd47SJun Li 
73420d6cd47SJun Li     /* rename all items in opts */
73520d6cd47SJun Li     while ((value = qemu_opt_get(opts, from))) {
736f43e47dbSMarkus Armbruster         qemu_opt_set(opts, to, value, &error_abort);
73757975222SKevin Wolf         qemu_opt_unset(opts, from);
73857975222SKevin Wolf     }
73957975222SKevin Wolf }
74057975222SKevin Wolf 
74133cb7dc8SKevin Wolf QemuOptsList qemu_legacy_drive_opts = {
74233cb7dc8SKevin Wolf     .name = "drive",
74333cb7dc8SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
74433cb7dc8SKevin Wolf     .desc = {
74533cb7dc8SKevin Wolf         {
74687a899c5SKevin Wolf             .name = "bus",
74787a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
74887a899c5SKevin Wolf             .help = "bus number",
74987a899c5SKevin Wolf         },{
75087a899c5SKevin Wolf             .name = "unit",
75187a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
75287a899c5SKevin Wolf             .help = "unit number (i.e. lun for scsi)",
75387a899c5SKevin Wolf         },{
75487a899c5SKevin Wolf             .name = "index",
75587a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
75687a899c5SKevin Wolf             .help = "index number",
75787a899c5SKevin Wolf         },{
75833cb7dc8SKevin Wolf             .name = "media",
75933cb7dc8SKevin Wolf             .type = QEMU_OPT_STRING,
76033cb7dc8SKevin Wolf             .help = "media type (disk, cdrom)",
761593d464bSKevin Wolf         },{
762593d464bSKevin Wolf             .name = "if",
763593d464bSKevin Wolf             .type = QEMU_OPT_STRING,
764593d464bSKevin Wolf             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
765b41a7338SKevin Wolf         },{
766b41a7338SKevin Wolf             .name = "cyls",
767b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
768b41a7338SKevin Wolf             .help = "number of cylinders (ide disk geometry)",
769b41a7338SKevin Wolf         },{
770b41a7338SKevin Wolf             .name = "heads",
771b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
772b41a7338SKevin Wolf             .help = "number of heads (ide disk geometry)",
773b41a7338SKevin Wolf         },{
774b41a7338SKevin Wolf             .name = "secs",
775b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
776b41a7338SKevin Wolf             .help = "number of sectors (ide disk geometry)",
777b41a7338SKevin Wolf         },{
778b41a7338SKevin Wolf             .name = "trans",
779b41a7338SKevin Wolf             .type = QEMU_OPT_STRING,
780b41a7338SKevin Wolf             .help = "chs translation (auto, lba, none)",
78126929298SKevin Wolf         },{
78226929298SKevin Wolf             .name = "boot",
78326929298SKevin Wolf             .type = QEMU_OPT_BOOL,
78426929298SKevin Wolf             .help = "(deprecated, ignored)",
785394c7d4dSKevin Wolf         },{
786394c7d4dSKevin Wolf             .name = "addr",
787394c7d4dSKevin Wolf             .type = QEMU_OPT_STRING,
788394c7d4dSKevin Wolf             .help = "pci address (virtio only)",
789d095b465SMax Reitz         },{
790bcf83158SKevin Wolf             .name = "serial",
791bcf83158SKevin Wolf             .type = QEMU_OPT_STRING,
792bcf83158SKevin Wolf             .help = "disk serial number",
793bcf83158SKevin Wolf         },{
794d095b465SMax Reitz             .name = "file",
795d095b465SMax Reitz             .type = QEMU_OPT_STRING,
796d095b465SMax Reitz             .help = "file name",
79733cb7dc8SKevin Wolf         },
7980ebd24e0SKevin Wolf 
7990ebd24e0SKevin Wolf         /* Options that are passed on, but have special semantics with -drive */
8000ebd24e0SKevin Wolf         {
8010ebd24e0SKevin Wolf             .name = "read-only",
8020ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
8030ebd24e0SKevin Wolf             .help = "open drive file as read-only",
8040ebd24e0SKevin Wolf         },{
805ee13ed1cSKevin Wolf             .name = "rerror",
806ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
807ee13ed1cSKevin Wolf             .help = "read error action",
808ee13ed1cSKevin Wolf         },{
809ee13ed1cSKevin Wolf             .name = "werror",
810ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
811ee13ed1cSKevin Wolf             .help = "write error action",
812ee13ed1cSKevin Wolf         },{
8130ebd24e0SKevin Wolf             .name = "copy-on-read",
8140ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
8150ebd24e0SKevin Wolf             .help = "copy read data from backing file into image file",
8160ebd24e0SKevin Wolf         },
8170ebd24e0SKevin Wolf 
81833cb7dc8SKevin Wolf         { /* end of list */ }
81933cb7dc8SKevin Wolf     },
82033cb7dc8SKevin Wolf };
82133cb7dc8SKevin Wolf 
82260e19e06SMarkus Armbruster DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
82357975222SKevin Wolf {
82429c4e2b5SKevin Wolf     const char *value;
82518e46a03SMarkus Armbruster     BlockBackend *blk;
82633cb7dc8SKevin Wolf     DriveInfo *dinfo = NULL;
827f298d071SKevin Wolf     QDict *bs_opts;
82833cb7dc8SKevin Wolf     QemuOpts *legacy_opts;
82933cb7dc8SKevin Wolf     DriveMediaType media = MEDIA_DISK;
830593d464bSKevin Wolf     BlockInterfaceType type;
831b41a7338SKevin Wolf     int cyls, heads, secs, translation;
83287a899c5SKevin Wolf     int max_devs, bus_id, unit_id, index;
833394c7d4dSKevin Wolf     const char *devaddr;
834ee13ed1cSKevin Wolf     const char *werror, *rerror;
835a7fdbcf0SFam Zheng     bool read_only = false;
836a7fdbcf0SFam Zheng     bool copy_on_read;
837bcf83158SKevin Wolf     const char *serial;
838d095b465SMax Reitz     const char *filename;
83933cb7dc8SKevin Wolf     Error *local_err = NULL;
840247147fbSKevin Wolf     int i;
84129c4e2b5SKevin Wolf 
84257975222SKevin Wolf     /* Change legacy command line options into QMP ones */
843247147fbSKevin Wolf     static const struct {
844247147fbSKevin Wolf         const char *from;
845247147fbSKevin Wolf         const char *to;
846247147fbSKevin Wolf     } opt_renames[] = {
847247147fbSKevin Wolf         { "iops",           "throttling.iops-total" },
848247147fbSKevin Wolf         { "iops_rd",        "throttling.iops-read" },
849247147fbSKevin Wolf         { "iops_wr",        "throttling.iops-write" },
85057975222SKevin Wolf 
851247147fbSKevin Wolf         { "bps",            "throttling.bps-total" },
852247147fbSKevin Wolf         { "bps_rd",         "throttling.bps-read" },
853247147fbSKevin Wolf         { "bps_wr",         "throttling.bps-write" },
85457975222SKevin Wolf 
855247147fbSKevin Wolf         { "iops_max",       "throttling.iops-total-max" },
856247147fbSKevin Wolf         { "iops_rd_max",    "throttling.iops-read-max" },
857247147fbSKevin Wolf         { "iops_wr_max",    "throttling.iops-write-max" },
8583e9fab69SBenoît Canet 
859247147fbSKevin Wolf         { "bps_max",        "throttling.bps-total-max" },
860247147fbSKevin Wolf         { "bps_rd_max",     "throttling.bps-read-max" },
861247147fbSKevin Wolf         { "bps_wr_max",     "throttling.bps-write-max" },
8623e9fab69SBenoît Canet 
863247147fbSKevin Wolf         { "iops_size",      "throttling.iops-size" },
8642024c1dfSBenoît Canet 
86576f4afb4SAlberto Garcia         { "group",          "throttling.group" },
86676f4afb4SAlberto Garcia 
867247147fbSKevin Wolf         { "readonly",       "read-only" },
868247147fbSKevin Wolf     };
869247147fbSKevin Wolf 
870247147fbSKevin Wolf     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
8715abbf0eeSKevin Wolf         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
8725abbf0eeSKevin Wolf                         &local_err);
8735abbf0eeSKevin Wolf         if (local_err) {
874565f65d2SMarkus Armbruster             error_report_err(local_err);
8755abbf0eeSKevin Wolf             return NULL;
8765abbf0eeSKevin Wolf         }
877247147fbSKevin Wolf     }
8780f227a94SKevin Wolf 
87929c4e2b5SKevin Wolf     value = qemu_opt_get(all_opts, "cache");
88029c4e2b5SKevin Wolf     if (value) {
88129c4e2b5SKevin Wolf         int flags = 0;
88229c4e2b5SKevin Wolf 
88329c4e2b5SKevin Wolf         if (bdrv_parse_cache_flags(value, &flags) != 0) {
88429c4e2b5SKevin Wolf             error_report("invalid cache option");
88529c4e2b5SKevin Wolf             return NULL;
88629c4e2b5SKevin Wolf         }
88729c4e2b5SKevin Wolf 
88829c4e2b5SKevin Wolf         /* Specific options take precedence */
88954861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
89054861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
891cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_CACHE_WB), &error_abort);
89229c4e2b5SKevin Wolf         }
89354861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
89454861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
895cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NOCACHE), &error_abort);
89629c4e2b5SKevin Wolf         }
89754861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
89854861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
899cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
90029c4e2b5SKevin Wolf         }
90129c4e2b5SKevin Wolf         qemu_opt_unset(all_opts, "cache");
90229c4e2b5SKevin Wolf     }
90329c4e2b5SKevin Wolf 
904f298d071SKevin Wolf     /* Get a QDict for processing the options */
905f298d071SKevin Wolf     bs_opts = qdict_new();
906f298d071SKevin Wolf     qemu_opts_to_qdict(all_opts, bs_opts);
907f298d071SKevin Wolf 
90887ea75d5SPeter Crosthwaite     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
90987ea75d5SPeter Crosthwaite                                    &error_abort);
91033cb7dc8SKevin Wolf     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
91184d18f06SMarkus Armbruster     if (local_err) {
912565f65d2SMarkus Armbruster         error_report_err(local_err);
91333cb7dc8SKevin Wolf         goto fail;
91433cb7dc8SKevin Wolf     }
91533cb7dc8SKevin Wolf 
91626929298SKevin Wolf     /* Deprecated option boot=[on|off] */
91726929298SKevin Wolf     if (qemu_opt_get(legacy_opts, "boot") != NULL) {
91826929298SKevin Wolf         fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
91926929298SKevin Wolf                 "ignored. Future versions will reject this parameter. Please "
92026929298SKevin Wolf                 "update your scripts.\n");
92126929298SKevin Wolf     }
92226929298SKevin Wolf 
92333cb7dc8SKevin Wolf     /* Media type */
92433cb7dc8SKevin Wolf     value = qemu_opt_get(legacy_opts, "media");
92533cb7dc8SKevin Wolf     if (value) {
92633cb7dc8SKevin Wolf         if (!strcmp(value, "disk")) {
92733cb7dc8SKevin Wolf             media = MEDIA_DISK;
92833cb7dc8SKevin Wolf         } else if (!strcmp(value, "cdrom")) {
92933cb7dc8SKevin Wolf             media = MEDIA_CDROM;
930a7fdbcf0SFam Zheng             read_only = true;
93133cb7dc8SKevin Wolf         } else {
93233cb7dc8SKevin Wolf             error_report("'%s' invalid media", value);
93333cb7dc8SKevin Wolf             goto fail;
93433cb7dc8SKevin Wolf         }
93533cb7dc8SKevin Wolf     }
93633cb7dc8SKevin Wolf 
9370ebd24e0SKevin Wolf     /* copy-on-read is disabled with a warning for read-only devices */
938a7fdbcf0SFam Zheng     read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
9390ebd24e0SKevin Wolf     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
9400ebd24e0SKevin Wolf 
9410ebd24e0SKevin Wolf     if (read_only && copy_on_read) {
9420ebd24e0SKevin Wolf         error_report("warning: disabling copy-on-read on read-only drive");
9430ebd24e0SKevin Wolf         copy_on_read = false;
9440ebd24e0SKevin Wolf     }
9450ebd24e0SKevin Wolf 
9460ebd24e0SKevin Wolf     qdict_put(bs_opts, "read-only",
9470ebd24e0SKevin Wolf               qstring_from_str(read_only ? "on" : "off"));
9480ebd24e0SKevin Wolf     qdict_put(bs_opts, "copy-on-read",
9490ebd24e0SKevin Wolf               qstring_from_str(copy_on_read ? "on" :"off"));
9500ebd24e0SKevin Wolf 
951593d464bSKevin Wolf     /* Controller type */
952593d464bSKevin Wolf     value = qemu_opt_get(legacy_opts, "if");
953593d464bSKevin Wolf     if (value) {
954593d464bSKevin Wolf         for (type = 0;
955593d464bSKevin Wolf              type < IF_COUNT && strcmp(value, if_name[type]);
956593d464bSKevin Wolf              type++) {
957593d464bSKevin Wolf         }
958593d464bSKevin Wolf         if (type == IF_COUNT) {
959593d464bSKevin Wolf             error_report("unsupported bus type '%s'", value);
960593d464bSKevin Wolf             goto fail;
961593d464bSKevin Wolf         }
962593d464bSKevin Wolf     } else {
963593d464bSKevin Wolf         type = block_default_type;
964593d464bSKevin Wolf     }
965593d464bSKevin Wolf 
966b41a7338SKevin Wolf     /* Geometry */
967b41a7338SKevin Wolf     cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
968b41a7338SKevin Wolf     heads = qemu_opt_get_number(legacy_opts, "heads", 0);
969b41a7338SKevin Wolf     secs  = qemu_opt_get_number(legacy_opts, "secs", 0);
970b41a7338SKevin Wolf 
971b41a7338SKevin Wolf     if (cyls || heads || secs) {
972b41a7338SKevin Wolf         if (cyls < 1) {
973b41a7338SKevin Wolf             error_report("invalid physical cyls number");
974b41a7338SKevin Wolf             goto fail;
975b41a7338SKevin Wolf         }
976b41a7338SKevin Wolf         if (heads < 1) {
977b41a7338SKevin Wolf             error_report("invalid physical heads number");
978b41a7338SKevin Wolf             goto fail;
979b41a7338SKevin Wolf         }
980b41a7338SKevin Wolf         if (secs < 1) {
981b41a7338SKevin Wolf             error_report("invalid physical secs number");
982b41a7338SKevin Wolf             goto fail;
983b41a7338SKevin Wolf         }
984b41a7338SKevin Wolf     }
985b41a7338SKevin Wolf 
986b41a7338SKevin Wolf     translation = BIOS_ATA_TRANSLATION_AUTO;
987b41a7338SKevin Wolf     value = qemu_opt_get(legacy_opts, "trans");
988b41a7338SKevin Wolf     if (value != NULL) {
989b41a7338SKevin Wolf         if (!cyls) {
990b41a7338SKevin Wolf             error_report("'%s' trans must be used with cyls, heads and secs",
991b41a7338SKevin Wolf                          value);
992b41a7338SKevin Wolf             goto fail;
993b41a7338SKevin Wolf         }
994b41a7338SKevin Wolf         if (!strcmp(value, "none")) {
995b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_NONE;
996b41a7338SKevin Wolf         } else if (!strcmp(value, "lba")) {
997b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_LBA;
998f31c41ffSPaolo Bonzini         } else if (!strcmp(value, "large")) {
999f31c41ffSPaolo Bonzini             translation = BIOS_ATA_TRANSLATION_LARGE;
1000f31c41ffSPaolo Bonzini         } else if (!strcmp(value, "rechs")) {
1001f31c41ffSPaolo Bonzini             translation = BIOS_ATA_TRANSLATION_RECHS;
1002b41a7338SKevin Wolf         } else if (!strcmp(value, "auto")) {
1003b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_AUTO;
1004b41a7338SKevin Wolf         } else {
1005b41a7338SKevin Wolf             error_report("'%s' invalid translation type", value);
1006b41a7338SKevin Wolf             goto fail;
1007b41a7338SKevin Wolf         }
1008b41a7338SKevin Wolf     }
1009b41a7338SKevin Wolf 
1010b41a7338SKevin Wolf     if (media == MEDIA_CDROM) {
1011b41a7338SKevin Wolf         if (cyls || secs || heads) {
1012b41a7338SKevin Wolf             error_report("CHS can't be set with media=cdrom");
1013b41a7338SKevin Wolf             goto fail;
1014b41a7338SKevin Wolf         }
1015b41a7338SKevin Wolf     }
1016b41a7338SKevin Wolf 
101787a899c5SKevin Wolf     /* Device address specified by bus/unit or index.
101887a899c5SKevin Wolf      * If none was specified, try to find the first free one. */
101987a899c5SKevin Wolf     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
102087a899c5SKevin Wolf     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
102187a899c5SKevin Wolf     index   = qemu_opt_get_number(legacy_opts, "index", -1);
102287a899c5SKevin Wolf 
102387a899c5SKevin Wolf     max_devs = if_max_devs[type];
102487a899c5SKevin Wolf 
102587a899c5SKevin Wolf     if (index != -1) {
102687a899c5SKevin Wolf         if (bus_id != 0 || unit_id != -1) {
102787a899c5SKevin Wolf             error_report("index cannot be used with bus and unit");
102887a899c5SKevin Wolf             goto fail;
102987a899c5SKevin Wolf         }
103087a899c5SKevin Wolf         bus_id = drive_index_to_bus_id(type, index);
103187a899c5SKevin Wolf         unit_id = drive_index_to_unit_id(type, index);
103287a899c5SKevin Wolf     }
103387a899c5SKevin Wolf 
103487a899c5SKevin Wolf     if (unit_id == -1) {
103587a899c5SKevin Wolf        unit_id = 0;
103687a899c5SKevin Wolf        while (drive_get(type, bus_id, unit_id) != NULL) {
103787a899c5SKevin Wolf            unit_id++;
103887a899c5SKevin Wolf            if (max_devs && unit_id >= max_devs) {
103987a899c5SKevin Wolf                unit_id -= max_devs;
104087a899c5SKevin Wolf                bus_id++;
104187a899c5SKevin Wolf            }
104287a899c5SKevin Wolf        }
104387a899c5SKevin Wolf     }
104487a899c5SKevin Wolf 
104587a899c5SKevin Wolf     if (max_devs && unit_id >= max_devs) {
104687a899c5SKevin Wolf         error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
104787a899c5SKevin Wolf         goto fail;
104887a899c5SKevin Wolf     }
104987a899c5SKevin Wolf 
105087a899c5SKevin Wolf     if (drive_get(type, bus_id, unit_id) != NULL) {
105187a899c5SKevin Wolf         error_report("drive with bus=%d, unit=%d (index=%d) exists",
105287a899c5SKevin Wolf                      bus_id, unit_id, index);
105387a899c5SKevin Wolf         goto fail;
105487a899c5SKevin Wolf     }
105587a899c5SKevin Wolf 
1056bcf83158SKevin Wolf     /* Serial number */
1057bcf83158SKevin Wolf     serial = qemu_opt_get(legacy_opts, "serial");
1058bcf83158SKevin Wolf 
105987a899c5SKevin Wolf     /* no id supplied -> create one */
106087a899c5SKevin Wolf     if (qemu_opts_id(all_opts) == NULL) {
106187a899c5SKevin Wolf         char *new_id;
106287a899c5SKevin Wolf         const char *mediastr = "";
106387a899c5SKevin Wolf         if (type == IF_IDE || type == IF_SCSI) {
106487a899c5SKevin Wolf             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
106587a899c5SKevin Wolf         }
106687a899c5SKevin Wolf         if (max_devs) {
106787a899c5SKevin Wolf             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
106887a899c5SKevin Wolf                                      mediastr, unit_id);
106987a899c5SKevin Wolf         } else {
107087a899c5SKevin Wolf             new_id = g_strdup_printf("%s%s%i", if_name[type],
107187a899c5SKevin Wolf                                      mediastr, unit_id);
107287a899c5SKevin Wolf         }
107387a899c5SKevin Wolf         qdict_put(bs_opts, "id", qstring_from_str(new_id));
107487a899c5SKevin Wolf         g_free(new_id);
107587a899c5SKevin Wolf     }
107687a899c5SKevin Wolf 
1077394c7d4dSKevin Wolf     /* Add virtio block device */
1078394c7d4dSKevin Wolf     devaddr = qemu_opt_get(legacy_opts, "addr");
1079394c7d4dSKevin Wolf     if (devaddr && type != IF_VIRTIO) {
1080394c7d4dSKevin Wolf         error_report("addr is not supported by this bus type");
1081394c7d4dSKevin Wolf         goto fail;
1082394c7d4dSKevin Wolf     }
1083394c7d4dSKevin Wolf 
1084394c7d4dSKevin Wolf     if (type == IF_VIRTIO) {
1085394c7d4dSKevin Wolf         QemuOpts *devopts;
108687ea75d5SPeter Crosthwaite         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
108787ea75d5SPeter Crosthwaite                                    &error_abort);
1088394c7d4dSKevin Wolf         if (arch_type == QEMU_ARCH_S390X) {
10891f68f1d3SAlexander Graf             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1090394c7d4dSKevin Wolf         } else {
1091f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1092394c7d4dSKevin Wolf         }
1093f43e47dbSMarkus Armbruster         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1094f43e47dbSMarkus Armbruster                      &error_abort);
1095394c7d4dSKevin Wolf         if (devaddr) {
1096f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1097394c7d4dSKevin Wolf         }
1098394c7d4dSKevin Wolf     }
1099394c7d4dSKevin Wolf 
1100d095b465SMax Reitz     filename = qemu_opt_get(legacy_opts, "file");
1101d095b465SMax Reitz 
1102ee13ed1cSKevin Wolf     /* Check werror/rerror compatibility with if=... */
1103ee13ed1cSKevin Wolf     werror = qemu_opt_get(legacy_opts, "werror");
1104ee13ed1cSKevin Wolf     if (werror != NULL) {
1105ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1106ee13ed1cSKevin Wolf             type != IF_NONE) {
1107ee13ed1cSKevin Wolf             error_report("werror is not supported by this bus type");
1108ee13ed1cSKevin Wolf             goto fail;
1109ee13ed1cSKevin Wolf         }
1110ee13ed1cSKevin Wolf         qdict_put(bs_opts, "werror", qstring_from_str(werror));
1111ee13ed1cSKevin Wolf     }
1112ee13ed1cSKevin Wolf 
1113ee13ed1cSKevin Wolf     rerror = qemu_opt_get(legacy_opts, "rerror");
1114ee13ed1cSKevin Wolf     if (rerror != NULL) {
1115ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1116ee13ed1cSKevin Wolf             type != IF_NONE) {
1117ee13ed1cSKevin Wolf             error_report("rerror is not supported by this bus type");
1118ee13ed1cSKevin Wolf             goto fail;
1119ee13ed1cSKevin Wolf         }
1120ee13ed1cSKevin Wolf         qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1121ee13ed1cSKevin Wolf     }
1122ee13ed1cSKevin Wolf 
11232d246f01SKevin Wolf     /* Actual block device init: Functionality shared with blockdev-add */
112418e46a03SMarkus Armbruster     blk = blockdev_init(filename, bs_opts, &local_err);
11253cb0e25cSMarkus Armbruster     bs_opts = NULL;
112618e46a03SMarkus Armbruster     if (!blk) {
112784d18f06SMarkus Armbruster         if (local_err) {
1128565f65d2SMarkus Armbruster             error_report_err(local_err);
1129b681072dSKevin Wolf         }
11302d246f01SKevin Wolf         goto fail;
1131b681072dSKevin Wolf     } else {
113284d18f06SMarkus Armbruster         assert(!local_err);
11332d246f01SKevin Wolf     }
11342d246f01SKevin Wolf 
113526f8b3a8SMarkus Armbruster     /* Create legacy DriveInfo */
113626f8b3a8SMarkus Armbruster     dinfo = g_malloc0(sizeof(*dinfo));
1137f298d071SKevin Wolf     dinfo->opts = all_opts;
11382d246f01SKevin Wolf 
1139b41a7338SKevin Wolf     dinfo->cyls = cyls;
1140b41a7338SKevin Wolf     dinfo->heads = heads;
1141b41a7338SKevin Wolf     dinfo->secs = secs;
1142b41a7338SKevin Wolf     dinfo->trans = translation;
1143b41a7338SKevin Wolf 
1144ee13ed1cSKevin Wolf     dinfo->type = type;
114587a899c5SKevin Wolf     dinfo->bus = bus_id;
114687a899c5SKevin Wolf     dinfo->unit = unit_id;
1147394c7d4dSKevin Wolf     dinfo->devaddr = devaddr;
1148bcf83158SKevin Wolf     dinfo->serial = g_strdup(serial);
1149bcf83158SKevin Wolf 
115026f8b3a8SMarkus Armbruster     blk_set_legacy_dinfo(blk, dinfo);
115126f8b3a8SMarkus Armbruster 
1152e34ef046SKevin Wolf     switch(type) {
1153e34ef046SKevin Wolf     case IF_IDE:
1154e34ef046SKevin Wolf     case IF_SCSI:
1155e34ef046SKevin Wolf     case IF_XEN:
1156e34ef046SKevin Wolf     case IF_NONE:
1157e34ef046SKevin Wolf         dinfo->media_cd = media == MEDIA_CDROM;
1158e34ef046SKevin Wolf         break;
1159e34ef046SKevin Wolf     default:
1160e34ef046SKevin Wolf         break;
1161e34ef046SKevin Wolf     }
1162e34ef046SKevin Wolf 
11632d246f01SKevin Wolf fail:
116433cb7dc8SKevin Wolf     qemu_opts_del(legacy_opts);
11653cb0e25cSMarkus Armbruster     QDECREF(bs_opts);
11662d246f01SKevin Wolf     return dinfo;
116757975222SKevin Wolf }
116857975222SKevin Wolf 
11693e5a50d6SMarkus Armbruster void hmp_commit(Monitor *mon, const QDict *qdict)
1170666daa68SMarkus Armbruster {
1171666daa68SMarkus Armbruster     const char *device = qdict_get_str(qdict, "device");
1172a0e8544cSFam Zheng     BlockBackend *blk;
11732d3735d3SStefan Hajnoczi     int ret;
11742d3735d3SStefan Hajnoczi 
1175e8877497SStefan Hajnoczi     if (!strcmp(device, "all")) {
1176e8877497SStefan Hajnoczi         ret = bdrv_commit_all();
1177e8877497SStefan Hajnoczi     } else {
117884aa0140SStefan Hajnoczi         BlockDriverState *bs;
117984aa0140SStefan Hajnoczi         AioContext *aio_context;
118084aa0140SStefan Hajnoczi 
1181a0e8544cSFam Zheng         blk = blk_by_name(device);
1182a0e8544cSFam Zheng         if (!blk) {
118358513bdeSJeff Cody             monitor_printf(mon, "Device '%s' not found\n", device);
1184ac59eb95SMarkus Armbruster             return;
11856ab4b5abSMarkus Armbruster         }
11865433c24fSMax Reitz         if (!blk_is_available(blk)) {
11875433c24fSMax Reitz             monitor_printf(mon, "Device '%s' has no medium\n", device);
11885433c24fSMax Reitz             return;
11895433c24fSMax Reitz         }
119084aa0140SStefan Hajnoczi 
119184aa0140SStefan Hajnoczi         bs = blk_bs(blk);
119284aa0140SStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
119384aa0140SStefan Hajnoczi         aio_context_acquire(aio_context);
119484aa0140SStefan Hajnoczi 
119584aa0140SStefan Hajnoczi         ret = bdrv_commit(bs);
119684aa0140SStefan Hajnoczi 
119784aa0140SStefan Hajnoczi         aio_context_release(aio_context);
11982d3735d3SStefan Hajnoczi     }
119958513bdeSJeff Cody     if (ret < 0) {
120058513bdeSJeff Cody         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
120158513bdeSJeff Cody                        strerror(-ret));
1202666daa68SMarkus Armbruster     }
1203666daa68SMarkus Armbruster }
1204666daa68SMarkus Armbruster 
120510f75907SEric Blake static void blockdev_do_action(TransactionAction *action, Error **errp)
12066cc2a415SPaolo Bonzini {
1207c8a83e85SKevin Wolf     TransactionActionList list;
12086cc2a415SPaolo Bonzini 
120910f75907SEric Blake     list.value = action;
12106cc2a415SPaolo Bonzini     list.next = NULL;
121194d16a64SJohn Snow     qmp_transaction(&list, false, NULL, errp);
12126cc2a415SPaolo Bonzini }
12136cc2a415SPaolo Bonzini 
12140901f67eSBenoît Canet void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
12150901f67eSBenoît Canet                                 bool has_node_name, const char *node_name,
12160901f67eSBenoît Canet                                 const char *snapshot_file,
12170901f67eSBenoît Canet                                 bool has_snapshot_node_name,
12180901f67eSBenoît Canet                                 const char *snapshot_node_name,
12196106e249SLuiz Capitulino                                 bool has_format, const char *format,
12200901f67eSBenoît Canet                                 bool has_mode, NewImageMode mode, Error **errp)
1221f8882568SJes Sorensen {
1222a911e6aeSAlberto Garcia     BlockdevSnapshotSync snapshot = {
12230901f67eSBenoît Canet         .has_device = has_device,
12246cc2a415SPaolo Bonzini         .device = (char *) device,
12250901f67eSBenoît Canet         .has_node_name = has_node_name,
12260901f67eSBenoît Canet         .node_name = (char *) node_name,
12276cc2a415SPaolo Bonzini         .snapshot_file = (char *) snapshot_file,
12280901f67eSBenoît Canet         .has_snapshot_node_name = has_snapshot_node_name,
12290901f67eSBenoît Canet         .snapshot_node_name = (char *) snapshot_node_name,
12306cc2a415SPaolo Bonzini         .has_format = has_format,
12316cc2a415SPaolo Bonzini         .format = (char *) format,
12326cc2a415SPaolo Bonzini         .has_mode = has_mode,
12336cc2a415SPaolo Bonzini         .mode = mode,
12346cc2a415SPaolo Bonzini     };
123510f75907SEric Blake     TransactionAction action = {
123610f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
123710f75907SEric Blake         .u.blockdev_snapshot_sync = &snapshot,
123810f75907SEric Blake     };
123910f75907SEric Blake     blockdev_do_action(&action, errp);
1240f8882568SJes Sorensen }
1241f8882568SJes Sorensen 
124243de7e2dSAlberto Garcia void qmp_blockdev_snapshot(const char *node, const char *overlay,
124343de7e2dSAlberto Garcia                            Error **errp)
124443de7e2dSAlberto Garcia {
124543de7e2dSAlberto Garcia     BlockdevSnapshot snapshot_data = {
124643de7e2dSAlberto Garcia         .node = (char *) node,
124743de7e2dSAlberto Garcia         .overlay = (char *) overlay
124843de7e2dSAlberto Garcia     };
124910f75907SEric Blake     TransactionAction action = {
125010f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
125110f75907SEric Blake         .u.blockdev_snapshot = &snapshot_data,
125210f75907SEric Blake     };
125310f75907SEric Blake     blockdev_do_action(&action, errp);
125443de7e2dSAlberto Garcia }
125543de7e2dSAlberto Garcia 
1256f323bc9eSWenchao Xia void qmp_blockdev_snapshot_internal_sync(const char *device,
1257f323bc9eSWenchao Xia                                          const char *name,
1258f323bc9eSWenchao Xia                                          Error **errp)
1259f323bc9eSWenchao Xia {
1260f323bc9eSWenchao Xia     BlockdevSnapshotInternal snapshot = {
1261f323bc9eSWenchao Xia         .device = (char *) device,
1262f323bc9eSWenchao Xia         .name = (char *) name
1263f323bc9eSWenchao Xia     };
126410f75907SEric Blake     TransactionAction action = {
126510f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
126610f75907SEric Blake         .u.blockdev_snapshot_internal_sync = &snapshot,
126710f75907SEric Blake     };
126810f75907SEric Blake     blockdev_do_action(&action, errp);
1269f323bc9eSWenchao Xia }
1270f323bc9eSWenchao Xia 
127144e3e053SWenchao Xia SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
127244e3e053SWenchao Xia                                                          bool has_id,
127344e3e053SWenchao Xia                                                          const char *id,
127444e3e053SWenchao Xia                                                          bool has_name,
127544e3e053SWenchao Xia                                                          const char *name,
127644e3e053SWenchao Xia                                                          Error **errp)
127744e3e053SWenchao Xia {
1278a0e8544cSFam Zheng     BlockDriverState *bs;
1279a0e8544cSFam Zheng     BlockBackend *blk;
12804ef3982aSStefan Hajnoczi     AioContext *aio_context;
128144e3e053SWenchao Xia     QEMUSnapshotInfo sn;
128244e3e053SWenchao Xia     Error *local_err = NULL;
128344e3e053SWenchao Xia     SnapshotInfo *info = NULL;
128444e3e053SWenchao Xia     int ret;
128544e3e053SWenchao Xia 
1286a0e8544cSFam Zheng     blk = blk_by_name(device);
1287a0e8544cSFam Zheng     if (!blk) {
128875158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
128975158ebbSMarkus Armbruster                   "Device '%s' not found", device);
129044e3e053SWenchao Xia         return NULL;
129144e3e053SWenchao Xia     }
12925433c24fSMax Reitz 
12935433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
12945433c24fSMax Reitz     aio_context_acquire(aio_context);
129544e3e053SWenchao Xia 
129644e3e053SWenchao Xia     if (!has_id) {
129744e3e053SWenchao Xia         id = NULL;
129844e3e053SWenchao Xia     }
129944e3e053SWenchao Xia 
130044e3e053SWenchao Xia     if (!has_name) {
130144e3e053SWenchao Xia         name = NULL;
130244e3e053SWenchao Xia     }
130344e3e053SWenchao Xia 
130444e3e053SWenchao Xia     if (!id && !name) {
130544e3e053SWenchao Xia         error_setg(errp, "Name or id must be provided");
13065433c24fSMax Reitz         goto out_aio_context;
130744e3e053SWenchao Xia     }
130844e3e053SWenchao Xia 
13095433c24fSMax Reitz     if (!blk_is_available(blk)) {
13105433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
13115433c24fSMax Reitz         goto out_aio_context;
13125433c24fSMax Reitz     }
13135433c24fSMax Reitz     bs = blk_bs(blk);
13144ef3982aSStefan Hajnoczi 
13150b928854SStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
13160b928854SStefan Hajnoczi         goto out_aio_context;
13170b928854SStefan Hajnoczi     }
13180b928854SStefan Hajnoczi 
131944e3e053SWenchao Xia     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
132084d18f06SMarkus Armbruster     if (local_err) {
132144e3e053SWenchao Xia         error_propagate(errp, local_err);
13224ef3982aSStefan Hajnoczi         goto out_aio_context;
132344e3e053SWenchao Xia     }
132444e3e053SWenchao Xia     if (!ret) {
132544e3e053SWenchao Xia         error_setg(errp,
132644e3e053SWenchao Xia                    "Snapshot with id '%s' and name '%s' does not exist on "
132744e3e053SWenchao Xia                    "device '%s'",
132844e3e053SWenchao Xia                    STR_OR_NULL(id), STR_OR_NULL(name), device);
13294ef3982aSStefan Hajnoczi         goto out_aio_context;
133044e3e053SWenchao Xia     }
133144e3e053SWenchao Xia 
133244e3e053SWenchao Xia     bdrv_snapshot_delete(bs, id, name, &local_err);
133384d18f06SMarkus Armbruster     if (local_err) {
133444e3e053SWenchao Xia         error_propagate(errp, local_err);
13354ef3982aSStefan Hajnoczi         goto out_aio_context;
133644e3e053SWenchao Xia     }
133744e3e053SWenchao Xia 
13384ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
13394ef3982aSStefan Hajnoczi 
13405839e53bSMarkus Armbruster     info = g_new0(SnapshotInfo, 1);
134144e3e053SWenchao Xia     info->id = g_strdup(sn.id_str);
134244e3e053SWenchao Xia     info->name = g_strdup(sn.name);
134344e3e053SWenchao Xia     info->date_nsec = sn.date_nsec;
134444e3e053SWenchao Xia     info->date_sec = sn.date_sec;
134544e3e053SWenchao Xia     info->vm_state_size = sn.vm_state_size;
134644e3e053SWenchao Xia     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
134744e3e053SWenchao Xia     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
134844e3e053SWenchao Xia 
134944e3e053SWenchao Xia     return info;
13504ef3982aSStefan Hajnoczi 
13514ef3982aSStefan Hajnoczi out_aio_context:
13524ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
13534ef3982aSStefan Hajnoczi     return NULL;
135444e3e053SWenchao Xia }
13558802d1fdSJeff Cody 
1356341ebc2fSJohn Snow /**
1357341ebc2fSJohn Snow  * block_dirty_bitmap_lookup:
1358341ebc2fSJohn Snow  * Return a dirty bitmap (if present), after validating
1359341ebc2fSJohn Snow  * the node reference and bitmap names.
1360341ebc2fSJohn Snow  *
1361341ebc2fSJohn Snow  * @node: The name of the BDS node to search for bitmaps
1362341ebc2fSJohn Snow  * @name: The name of the bitmap to search for
1363341ebc2fSJohn Snow  * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1364341ebc2fSJohn Snow  * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1365341ebc2fSJohn Snow  * @errp: Output pointer for error information. Can be NULL.
1366341ebc2fSJohn Snow  *
1367341ebc2fSJohn Snow  * @return: A bitmap object on success, or NULL on failure.
1368341ebc2fSJohn Snow  */
1369341ebc2fSJohn Snow static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1370341ebc2fSJohn Snow                                                   const char *name,
1371341ebc2fSJohn Snow                                                   BlockDriverState **pbs,
1372341ebc2fSJohn Snow                                                   AioContext **paio,
1373341ebc2fSJohn Snow                                                   Error **errp)
1374341ebc2fSJohn Snow {
1375341ebc2fSJohn Snow     BlockDriverState *bs;
1376341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
1377341ebc2fSJohn Snow     AioContext *aio_context;
1378341ebc2fSJohn Snow 
1379341ebc2fSJohn Snow     if (!node) {
1380341ebc2fSJohn Snow         error_setg(errp, "Node cannot be NULL");
1381341ebc2fSJohn Snow         return NULL;
1382341ebc2fSJohn Snow     }
1383341ebc2fSJohn Snow     if (!name) {
1384341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be NULL");
1385341ebc2fSJohn Snow         return NULL;
1386341ebc2fSJohn Snow     }
1387341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, NULL);
1388341ebc2fSJohn Snow     if (!bs) {
1389341ebc2fSJohn Snow         error_setg(errp, "Node '%s' not found", node);
1390341ebc2fSJohn Snow         return NULL;
1391341ebc2fSJohn Snow     }
1392341ebc2fSJohn Snow 
1393341ebc2fSJohn Snow     aio_context = bdrv_get_aio_context(bs);
1394341ebc2fSJohn Snow     aio_context_acquire(aio_context);
1395341ebc2fSJohn Snow 
1396341ebc2fSJohn Snow     bitmap = bdrv_find_dirty_bitmap(bs, name);
1397341ebc2fSJohn Snow     if (!bitmap) {
1398341ebc2fSJohn Snow         error_setg(errp, "Dirty bitmap '%s' not found", name);
1399341ebc2fSJohn Snow         goto fail;
1400341ebc2fSJohn Snow     }
1401341ebc2fSJohn Snow 
1402341ebc2fSJohn Snow     if (pbs) {
1403341ebc2fSJohn Snow         *pbs = bs;
1404341ebc2fSJohn Snow     }
1405341ebc2fSJohn Snow     if (paio) {
1406341ebc2fSJohn Snow         *paio = aio_context;
1407341ebc2fSJohn Snow     } else {
1408341ebc2fSJohn Snow         aio_context_release(aio_context);
1409341ebc2fSJohn Snow     }
1410341ebc2fSJohn Snow 
1411341ebc2fSJohn Snow     return bitmap;
1412341ebc2fSJohn Snow 
1413341ebc2fSJohn Snow  fail:
1414341ebc2fSJohn Snow     aio_context_release(aio_context);
1415341ebc2fSJohn Snow     return NULL;
1416341ebc2fSJohn Snow }
1417341ebc2fSJohn Snow 
1418b756b9ceSStefan Hajnoczi /* New and old BlockDriverState structs for atomic group operations */
1419ba0c86a3SWenchao Xia 
142050f43f0fSJohn Snow typedef struct BlkActionState BlkActionState;
1421ba0c86a3SWenchao Xia 
142250f43f0fSJohn Snow /**
142350f43f0fSJohn Snow  * BlkActionOps:
142450f43f0fSJohn Snow  * Table of operations that define an Action.
142550f43f0fSJohn Snow  *
142650f43f0fSJohn Snow  * @instance_size: Size of state struct, in bytes.
142750f43f0fSJohn Snow  * @prepare: Prepare the work, must NOT be NULL.
142850f43f0fSJohn Snow  * @commit: Commit the changes, can be NULL.
142950f43f0fSJohn Snow  * @abort: Abort the changes on fail, can be NULL.
143050f43f0fSJohn Snow  * @clean: Clean up resources after all transaction actions have called
143150f43f0fSJohn Snow  *         commit() or abort(). Can be NULL.
143250f43f0fSJohn Snow  *
143350f43f0fSJohn Snow  * Only prepare() may fail. In a single transaction, only one of commit() or
143450f43f0fSJohn Snow  * abort() will be called. clean() will always be called if it is present.
1435ba0c86a3SWenchao Xia  */
143650f43f0fSJohn Snow typedef struct BlkActionOps {
143750f43f0fSJohn Snow     size_t instance_size;
143850f43f0fSJohn Snow     void (*prepare)(BlkActionState *common, Error **errp);
143950f43f0fSJohn Snow     void (*commit)(BlkActionState *common);
144050f43f0fSJohn Snow     void (*abort)(BlkActionState *common);
144150f43f0fSJohn Snow     void (*clean)(BlkActionState *common);
144250f43f0fSJohn Snow } BlkActionOps;
144350f43f0fSJohn Snow 
144450f43f0fSJohn Snow /**
144550f43f0fSJohn Snow  * BlkActionState:
144650f43f0fSJohn Snow  * Describes one Action's state within a Transaction.
144750f43f0fSJohn Snow  *
144850f43f0fSJohn Snow  * @action: QAPI-defined enum identifying which Action to perform.
144950f43f0fSJohn Snow  * @ops: Table of ActionOps this Action can perform.
145094d16a64SJohn Snow  * @block_job_txn: Transaction which this action belongs to.
145150f43f0fSJohn Snow  * @entry: List membership for all Actions in this Transaction.
145250f43f0fSJohn Snow  *
145350f43f0fSJohn Snow  * This structure must be arranged as first member in a subclassed type,
145450f43f0fSJohn Snow  * assuming that the compiler will also arrange it to the same offsets as the
145550f43f0fSJohn Snow  * base class.
145650f43f0fSJohn Snow  */
145750f43f0fSJohn Snow struct BlkActionState {
1458c8a83e85SKevin Wolf     TransactionAction *action;
145950f43f0fSJohn Snow     const BlkActionOps *ops;
146094d16a64SJohn Snow     BlockJobTxn *block_job_txn;
146194d16a64SJohn Snow     TransactionProperties *txn_props;
146250f43f0fSJohn Snow     QSIMPLEQ_ENTRY(BlkActionState) entry;
1463ba0c86a3SWenchao Xia };
1464ba0c86a3SWenchao Xia 
1465bbe86010SWenchao Xia /* internal snapshot private data */
1466bbe86010SWenchao Xia typedef struct InternalSnapshotState {
146750f43f0fSJohn Snow     BlkActionState common;
1468bbe86010SWenchao Xia     BlockDriverState *bs;
14695d6e96efSStefan Hajnoczi     AioContext *aio_context;
1470bbe86010SWenchao Xia     QEMUSnapshotInfo sn;
1471507306ccSFam Zheng     bool created;
1472bbe86010SWenchao Xia } InternalSnapshotState;
1473bbe86010SWenchao Xia 
147494d16a64SJohn Snow 
147594d16a64SJohn Snow static int action_check_completion_mode(BlkActionState *s, Error **errp)
147694d16a64SJohn Snow {
147794d16a64SJohn Snow     if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
147894d16a64SJohn Snow         error_setg(errp,
147994d16a64SJohn Snow                    "Action '%s' does not support Transaction property "
148094d16a64SJohn Snow                    "completion-mode = %s",
148194d16a64SJohn Snow                    TransactionActionKind_lookup[s->action->type],
148294d16a64SJohn Snow                    ActionCompletionMode_lookup[s->txn_props->completion_mode]);
148394d16a64SJohn Snow         return -1;
148494d16a64SJohn Snow     }
148594d16a64SJohn Snow     return 0;
148694d16a64SJohn Snow }
148794d16a64SJohn Snow 
148850f43f0fSJohn Snow static void internal_snapshot_prepare(BlkActionState *common,
1489bbe86010SWenchao Xia                                       Error **errp)
1490bbe86010SWenchao Xia {
1491f70edf99SMarkus Armbruster     Error *local_err = NULL;
1492bbe86010SWenchao Xia     const char *device;
1493bbe86010SWenchao Xia     const char *name;
1494a0e8544cSFam Zheng     BlockBackend *blk;
1495bbe86010SWenchao Xia     BlockDriverState *bs;
1496bbe86010SWenchao Xia     QEMUSnapshotInfo old_sn, *sn;
1497bbe86010SWenchao Xia     bool ret;
1498bbe86010SWenchao Xia     qemu_timeval tv;
1499bbe86010SWenchao Xia     BlockdevSnapshotInternal *internal;
1500bbe86010SWenchao Xia     InternalSnapshotState *state;
1501bbe86010SWenchao Xia     int ret1;
1502bbe86010SWenchao Xia 
15036a8f9661SEric Blake     g_assert(common->action->type ==
1504bbe86010SWenchao Xia              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
15056a8f9661SEric Blake     internal = common->action->u.blockdev_snapshot_internal_sync;
1506bbe86010SWenchao Xia     state = DO_UPCAST(InternalSnapshotState, common, common);
1507bbe86010SWenchao Xia 
1508bbe86010SWenchao Xia     /* 1. parse input */
1509bbe86010SWenchao Xia     device = internal->device;
1510bbe86010SWenchao Xia     name = internal->name;
1511bbe86010SWenchao Xia 
1512bbe86010SWenchao Xia     /* 2. check for validation */
151394d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
151494d16a64SJohn Snow         return;
151594d16a64SJohn Snow     }
151694d16a64SJohn Snow 
1517a0e8544cSFam Zheng     blk = blk_by_name(device);
1518a0e8544cSFam Zheng     if (!blk) {
151975158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
152075158ebbSMarkus Armbruster                   "Device '%s' not found", device);
1521bbe86010SWenchao Xia         return;
1522bbe86010SWenchao Xia     }
1523bbe86010SWenchao Xia 
15245d6e96efSStefan Hajnoczi     /* AioContext is released in .clean() */
15255433c24fSMax Reitz     state->aio_context = blk_get_aio_context(blk);
15265d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
15275d6e96efSStefan Hajnoczi 
15285433c24fSMax Reitz     if (!blk_is_available(blk)) {
1529c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1530bbe86010SWenchao Xia         return;
1531bbe86010SWenchao Xia     }
15325433c24fSMax Reitz     bs = blk_bs(blk);
1533bbe86010SWenchao Xia 
1534507306ccSFam Zheng     state->bs = bs;
1535507306ccSFam Zheng     bdrv_drained_begin(bs);
1536507306ccSFam Zheng 
15373dc7ca3cSStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
15383dc7ca3cSStefan Hajnoczi         return;
15393dc7ca3cSStefan Hajnoczi     }
15403dc7ca3cSStefan Hajnoczi 
1541bbe86010SWenchao Xia     if (bdrv_is_read_only(bs)) {
154281e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
1543bbe86010SWenchao Xia         return;
1544bbe86010SWenchao Xia     }
1545bbe86010SWenchao Xia 
1546bbe86010SWenchao Xia     if (!bdrv_can_snapshot(bs)) {
154781e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by device '%s' "
154881e5f78aSAlberto Garcia                    "does not support internal snapshots",
154981e5f78aSAlberto Garcia                    bs->drv->format_name, device);
1550bbe86010SWenchao Xia         return;
1551bbe86010SWenchao Xia     }
1552bbe86010SWenchao Xia 
1553bbe86010SWenchao Xia     if (!strlen(name)) {
1554bbe86010SWenchao Xia         error_setg(errp, "Name is empty");
1555bbe86010SWenchao Xia         return;
1556bbe86010SWenchao Xia     }
1557bbe86010SWenchao Xia 
1558bbe86010SWenchao Xia     /* check whether a snapshot with name exist */
1559f70edf99SMarkus Armbruster     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1560f70edf99SMarkus Armbruster                                             &local_err);
1561f70edf99SMarkus Armbruster     if (local_err) {
1562f70edf99SMarkus Armbruster         error_propagate(errp, local_err);
1563bbe86010SWenchao Xia         return;
1564bbe86010SWenchao Xia     } else if (ret) {
1565bbe86010SWenchao Xia         error_setg(errp,
1566bbe86010SWenchao Xia                    "Snapshot with name '%s' already exists on device '%s'",
1567bbe86010SWenchao Xia                    name, device);
1568bbe86010SWenchao Xia         return;
1569bbe86010SWenchao Xia     }
1570bbe86010SWenchao Xia 
1571bbe86010SWenchao Xia     /* 3. take the snapshot */
1572bbe86010SWenchao Xia     sn = &state->sn;
1573bbe86010SWenchao Xia     pstrcpy(sn->name, sizeof(sn->name), name);
1574bbe86010SWenchao Xia     qemu_gettimeofday(&tv);
1575bbe86010SWenchao Xia     sn->date_sec = tv.tv_sec;
1576bbe86010SWenchao Xia     sn->date_nsec = tv.tv_usec * 1000;
1577bbe86010SWenchao Xia     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1578bbe86010SWenchao Xia 
1579bbe86010SWenchao Xia     ret1 = bdrv_snapshot_create(bs, sn);
1580bbe86010SWenchao Xia     if (ret1 < 0) {
1581bbe86010SWenchao Xia         error_setg_errno(errp, -ret1,
1582bbe86010SWenchao Xia                          "Failed to create snapshot '%s' on device '%s'",
1583bbe86010SWenchao Xia                          name, device);
1584bbe86010SWenchao Xia         return;
1585bbe86010SWenchao Xia     }
1586bbe86010SWenchao Xia 
1587bbe86010SWenchao Xia     /* 4. succeed, mark a snapshot is created */
1588507306ccSFam Zheng     state->created = true;
1589bbe86010SWenchao Xia }
1590bbe86010SWenchao Xia 
159150f43f0fSJohn Snow static void internal_snapshot_abort(BlkActionState *common)
1592bbe86010SWenchao Xia {
1593bbe86010SWenchao Xia     InternalSnapshotState *state =
1594bbe86010SWenchao Xia                              DO_UPCAST(InternalSnapshotState, common, common);
1595bbe86010SWenchao Xia     BlockDriverState *bs = state->bs;
1596bbe86010SWenchao Xia     QEMUSnapshotInfo *sn = &state->sn;
1597bbe86010SWenchao Xia     Error *local_error = NULL;
1598bbe86010SWenchao Xia 
1599507306ccSFam Zheng     if (!state->created) {
1600bbe86010SWenchao Xia         return;
1601bbe86010SWenchao Xia     }
1602bbe86010SWenchao Xia 
1603bbe86010SWenchao Xia     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1604c29b77f9SMarkus Armbruster         error_reportf_err(local_error,
1605c29b77f9SMarkus Armbruster                           "Failed to delete snapshot with id '%s' and "
1606c29b77f9SMarkus Armbruster                           "name '%s' on device '%s' in abort: ",
1607c29b77f9SMarkus Armbruster                           sn->id_str, sn->name,
1608c29b77f9SMarkus Armbruster                           bdrv_get_device_name(bs));
1609bbe86010SWenchao Xia     }
1610bbe86010SWenchao Xia }
1611bbe86010SWenchao Xia 
161250f43f0fSJohn Snow static void internal_snapshot_clean(BlkActionState *common)
16135d6e96efSStefan Hajnoczi {
16145d6e96efSStefan Hajnoczi     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
16155d6e96efSStefan Hajnoczi                                              common, common);
16165d6e96efSStefan Hajnoczi 
16175d6e96efSStefan Hajnoczi     if (state->aio_context) {
1618507306ccSFam Zheng         if (state->bs) {
1619507306ccSFam Zheng             bdrv_drained_end(state->bs);
1620507306ccSFam Zheng         }
16215d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
16225d6e96efSStefan Hajnoczi     }
16235d6e96efSStefan Hajnoczi }
16245d6e96efSStefan Hajnoczi 
1625ba0c86a3SWenchao Xia /* external snapshot private data */
1626ba5d6ab6SStefan Hajnoczi typedef struct ExternalSnapshotState {
162750f43f0fSJohn Snow     BlkActionState common;
16288802d1fdSJeff Cody     BlockDriverState *old_bs;
16298802d1fdSJeff Cody     BlockDriverState *new_bs;
16305d6e96efSStefan Hajnoczi     AioContext *aio_context;
1631ba5d6ab6SStefan Hajnoczi } ExternalSnapshotState;
16328802d1fdSJeff Cody 
163350f43f0fSJohn Snow static void external_snapshot_prepare(BlkActionState *common,
16349b9877eeSWenchao Xia                                       Error **errp)
16359b9877eeSWenchao Xia {
163643de7e2dSAlberto Garcia     int flags = 0, ret;
163743de7e2dSAlberto Garcia     QDict *options = NULL;
16389b9877eeSWenchao Xia     Error *local_err = NULL;
163943de7e2dSAlberto Garcia     /* Device and node name of the image to generate the snapshot from */
1640e2a31e87SWenchao Xia     const char *device;
16410901f67eSBenoît Canet     const char *node_name;
164243de7e2dSAlberto Garcia     /* Reference to the new image (for 'blockdev-snapshot') */
164343de7e2dSAlberto Garcia     const char *snapshot_ref;
164443de7e2dSAlberto Garcia     /* File name of the new image (for 'blockdev-snapshot-sync') */
1645e2a31e87SWenchao Xia     const char *new_image_file;
1646ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1647ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1648c8a83e85SKevin Wolf     TransactionAction *action = common->action;
16499b9877eeSWenchao Xia 
165043de7e2dSAlberto Garcia     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
165143de7e2dSAlberto Garcia      * purpose but a different set of parameters */
165243de7e2dSAlberto Garcia     switch (action->type) {
165343de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
165443de7e2dSAlberto Garcia         {
165543de7e2dSAlberto Garcia             BlockdevSnapshot *s = action->u.blockdev_snapshot;
165643de7e2dSAlberto Garcia             device = s->node;
165743de7e2dSAlberto Garcia             node_name = s->node;
165843de7e2dSAlberto Garcia             new_image_file = NULL;
165943de7e2dSAlberto Garcia             snapshot_ref = s->overlay;
1660e2a31e87SWenchao Xia         }
166143de7e2dSAlberto Garcia         break;
166243de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
166343de7e2dSAlberto Garcia         {
166443de7e2dSAlberto Garcia             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
166543de7e2dSAlberto Garcia             device = s->has_device ? s->device : NULL;
166643de7e2dSAlberto Garcia             node_name = s->has_node_name ? s->node_name : NULL;
166743de7e2dSAlberto Garcia             new_image_file = s->snapshot_file;
166843de7e2dSAlberto Garcia             snapshot_ref = NULL;
166943de7e2dSAlberto Garcia         }
167043de7e2dSAlberto Garcia         break;
167143de7e2dSAlberto Garcia     default:
167243de7e2dSAlberto Garcia         g_assert_not_reached();
1673e2a31e87SWenchao Xia     }
1674e2a31e87SWenchao Xia 
1675e2a31e87SWenchao Xia     /* start processing */
167694d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
167794d16a64SJohn Snow         return;
167894d16a64SJohn Snow     }
167994d16a64SJohn Snow 
168043de7e2dSAlberto Garcia     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
168143de7e2dSAlberto Garcia     if (!state->old_bs) {
16829b9877eeSWenchao Xia         return;
16839b9877eeSWenchao Xia     }
16849b9877eeSWenchao Xia 
16855d6e96efSStefan Hajnoczi     /* Acquire AioContext now so any threads operating on old_bs stop */
16865d6e96efSStefan Hajnoczi     state->aio_context = bdrv_get_aio_context(state->old_bs);
16875d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
1688da763e83SFam Zheng     bdrv_drained_begin(state->old_bs);
16895d6e96efSStefan Hajnoczi 
1690ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_inserted(state->old_bs)) {
1691c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
16929b9877eeSWenchao Xia         return;
16939b9877eeSWenchao Xia     }
16949b9877eeSWenchao Xia 
16953718d8abSFam Zheng     if (bdrv_op_is_blocked(state->old_bs,
16963718d8abSFam Zheng                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
16979b9877eeSWenchao Xia         return;
16989b9877eeSWenchao Xia     }
16999b9877eeSWenchao Xia 
1700ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_read_only(state->old_bs)) {
1701ba5d6ab6SStefan Hajnoczi         if (bdrv_flush(state->old_bs)) {
1702c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_IO_ERROR);
17039b9877eeSWenchao Xia             return;
17049b9877eeSWenchao Xia         }
17059b9877eeSWenchao Xia     }
17069b9877eeSWenchao Xia 
1707212a5a8fSBenoît Canet     if (!bdrv_is_first_non_filter(state->old_bs)) {
1708c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1709f6186f49SBenoît Canet         return;
1710f6186f49SBenoît Canet     }
1711f6186f49SBenoît Canet 
171243de7e2dSAlberto Garcia     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
171343de7e2dSAlberto Garcia         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
171443de7e2dSAlberto Garcia         const char *format = s->has_format ? s->format : "qcow2";
171543de7e2dSAlberto Garcia         enum NewImageMode mode;
171643de7e2dSAlberto Garcia         const char *snapshot_node_name =
171743de7e2dSAlberto Garcia             s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
171843de7e2dSAlberto Garcia 
171943de7e2dSAlberto Garcia         if (node_name && !snapshot_node_name) {
172043de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name missing");
172143de7e2dSAlberto Garcia             return;
172243de7e2dSAlberto Garcia         }
172343de7e2dSAlberto Garcia 
172443de7e2dSAlberto Garcia         if (snapshot_node_name &&
172543de7e2dSAlberto Garcia             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
172643de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name already in use");
172743de7e2dSAlberto Garcia             return;
172843de7e2dSAlberto Garcia         }
172943de7e2dSAlberto Garcia 
1730ba5d6ab6SStefan Hajnoczi         flags = state->old_bs->open_flags;
17319b9877eeSWenchao Xia 
17329b9877eeSWenchao Xia         /* create new image w/backing file */
173343de7e2dSAlberto Garcia         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
17349b9877eeSWenchao Xia         if (mode != NEW_IMAGE_MODE_EXISTING) {
1735*f86b8b58SKevin Wolf             int64_t size = bdrv_getlength(state->old_bs);
1736*f86b8b58SKevin Wolf             if (size < 0) {
1737*f86b8b58SKevin Wolf                 error_setg_errno(errp, -size, "bdrv_getlength failed");
1738*f86b8b58SKevin Wolf                 return;
1739*f86b8b58SKevin Wolf             }
17409b9877eeSWenchao Xia             bdrv_img_create(new_image_file, format,
1741ba5d6ab6SStefan Hajnoczi                             state->old_bs->filename,
1742ba5d6ab6SStefan Hajnoczi                             state->old_bs->drv->format_name,
1743*f86b8b58SKevin Wolf                             NULL, size, flags, &local_err, false);
174484d18f06SMarkus Armbruster             if (local_err) {
17459b9877eeSWenchao Xia                 error_propagate(errp, local_err);
17469b9877eeSWenchao Xia                 return;
17479b9877eeSWenchao Xia             }
17489b9877eeSWenchao Xia         }
17499b9877eeSWenchao Xia 
17500901f67eSBenoît Canet         options = qdict_new();
175143de7e2dSAlberto Garcia         if (s->has_snapshot_node_name) {
17520901f67eSBenoît Canet             qdict_put(options, "node-name",
17530901f67eSBenoît Canet                       qstring_from_str(snapshot_node_name));
17540901f67eSBenoît Canet         }
1755e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
17560901f67eSBenoît Canet 
175743de7e2dSAlberto Garcia         flags |= BDRV_O_NO_BACKING;
175843de7e2dSAlberto Garcia     }
175943de7e2dSAlberto Garcia 
1760f67503e5SMax Reitz     assert(state->new_bs == NULL);
176143de7e2dSAlberto Garcia     ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
176243de7e2dSAlberto Garcia                     flags, errp);
1763f67503e5SMax Reitz     /* We will manually add the backing_hd field to the bs later */
17649b9877eeSWenchao Xia     if (ret != 0) {
176543de7e2dSAlberto Garcia         return;
176643de7e2dSAlberto Garcia     }
176743de7e2dSAlberto Garcia 
176843de7e2dSAlberto Garcia     if (state->new_bs->blk != NULL) {
176943de7e2dSAlberto Garcia         error_setg(errp, "The snapshot is already in use by %s",
177043de7e2dSAlberto Garcia                    blk_name(state->new_bs->blk));
177143de7e2dSAlberto Garcia         return;
177243de7e2dSAlberto Garcia     }
177343de7e2dSAlberto Garcia 
177443de7e2dSAlberto Garcia     if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
177543de7e2dSAlberto Garcia                            errp)) {
177643de7e2dSAlberto Garcia         return;
177743de7e2dSAlberto Garcia     }
177843de7e2dSAlberto Garcia 
177943de7e2dSAlberto Garcia     if (state->new_bs->backing != NULL) {
178043de7e2dSAlberto Garcia         error_setg(errp, "The snapshot already has a backing image");
178108b24cfeSAlberto Garcia         return;
178208b24cfeSAlberto Garcia     }
178308b24cfeSAlberto Garcia 
178408b24cfeSAlberto Garcia     if (!state->new_bs->drv->supports_backing) {
178508b24cfeSAlberto Garcia         error_setg(errp, "The snapshot does not support backing images");
17869b9877eeSWenchao Xia     }
17879b9877eeSWenchao Xia }
17889b9877eeSWenchao Xia 
178950f43f0fSJohn Snow static void external_snapshot_commit(BlkActionState *common)
17903b0047e8SWenchao Xia {
1791ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1792ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1793ba0c86a3SWenchao Xia 
17945d6e96efSStefan Hajnoczi     bdrv_set_aio_context(state->new_bs, state->aio_context);
17955d6e96efSStefan Hajnoczi 
1796ba5d6ab6SStefan Hajnoczi     /* This removes our old bs and adds the new bs */
1797ba5d6ab6SStefan Hajnoczi     bdrv_append(state->new_bs, state->old_bs);
17983b0047e8SWenchao Xia     /* We don't need (or want) to use the transactional
17993b0047e8SWenchao Xia      * bdrv_reopen_multiple() across all the entries at once, because we
18003b0047e8SWenchao Xia      * don't want to abort all of them if one of them fails the reopen */
1801dd62f1caSKevin Wolf     bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
18023b0047e8SWenchao Xia                 NULL);
18033b0047e8SWenchao Xia }
18043b0047e8SWenchao Xia 
180550f43f0fSJohn Snow static void external_snapshot_abort(BlkActionState *common)
180696b86bf7SWenchao Xia {
1807ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1808ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1809ba5d6ab6SStefan Hajnoczi     if (state->new_bs) {
18104f6fd349SFam Zheng         bdrv_unref(state->new_bs);
181196b86bf7SWenchao Xia     }
1812da763e83SFam Zheng }
1813da763e83SFam Zheng 
181450f43f0fSJohn Snow static void external_snapshot_clean(BlkActionState *common)
1815da763e83SFam Zheng {
1816da763e83SFam Zheng     ExternalSnapshotState *state =
1817da763e83SFam Zheng                              DO_UPCAST(ExternalSnapshotState, common, common);
18185d6e96efSStefan Hajnoczi     if (state->aio_context) {
1819da763e83SFam Zheng         bdrv_drained_end(state->old_bs);
18205d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
18215d6e96efSStefan Hajnoczi     }
182296b86bf7SWenchao Xia }
182396b86bf7SWenchao Xia 
18243037f364SStefan Hajnoczi typedef struct DriveBackupState {
182550f43f0fSJohn Snow     BlkActionState common;
18263037f364SStefan Hajnoczi     BlockDriverState *bs;
18275d6e96efSStefan Hajnoczi     AioContext *aio_context;
18283037f364SStefan Hajnoczi     BlockJob *job;
18293037f364SStefan Hajnoczi } DriveBackupState;
18303037f364SStefan Hajnoczi 
183178f51fdeSJohn Snow static void do_drive_backup(const char *device, const char *target,
183278f51fdeSJohn Snow                             bool has_format, const char *format,
183378f51fdeSJohn Snow                             enum MirrorSyncMode sync,
183478f51fdeSJohn Snow                             bool has_mode, enum NewImageMode mode,
183578f51fdeSJohn Snow                             bool has_speed, int64_t speed,
183678f51fdeSJohn Snow                             bool has_bitmap, const char *bitmap,
183778f51fdeSJohn Snow                             bool has_on_source_error,
183878f51fdeSJohn Snow                             BlockdevOnError on_source_error,
183978f51fdeSJohn Snow                             bool has_on_target_error,
184078f51fdeSJohn Snow                             BlockdevOnError on_target_error,
184178f51fdeSJohn Snow                             BlockJobTxn *txn, Error **errp);
184278f51fdeSJohn Snow 
184350f43f0fSJohn Snow static void drive_backup_prepare(BlkActionState *common, Error **errp)
18443037f364SStefan Hajnoczi {
18453037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1846a0e8544cSFam Zheng     BlockBackend *blk;
18473037f364SStefan Hajnoczi     DriveBackup *backup;
18483037f364SStefan Hajnoczi     Error *local_err = NULL;
18493037f364SStefan Hajnoczi 
18506a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
18516a8f9661SEric Blake     backup = common->action->u.drive_backup;
18523037f364SStefan Hajnoczi 
1853a0e8544cSFam Zheng     blk = blk_by_name(backup->device);
1854a0e8544cSFam Zheng     if (!blk) {
185575158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
185675158ebbSMarkus Armbruster                   "Device '%s' not found", backup->device);
18575d6e96efSStefan Hajnoczi         return;
18585d6e96efSStefan Hajnoczi     }
18595d6e96efSStefan Hajnoczi 
18601fdd4b7bSFam Zheng     if (!blk_is_available(blk)) {
18611fdd4b7bSFam Zheng         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
18621fdd4b7bSFam Zheng         return;
18631fdd4b7bSFam Zheng     }
18641fdd4b7bSFam Zheng 
18655d6e96efSStefan Hajnoczi     /* AioContext is released in .clean() */
18665433c24fSMax Reitz     state->aio_context = blk_get_aio_context(blk);
18675d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
18681fdd4b7bSFam Zheng     bdrv_drained_begin(blk_bs(blk));
18691fdd4b7bSFam Zheng     state->bs = blk_bs(blk);
18705d6e96efSStefan Hajnoczi 
187178f51fdeSJohn Snow     do_drive_backup(backup->device, backup->target,
18723037f364SStefan Hajnoczi                     backup->has_format, backup->format,
1873b53169eaSStefan Hajnoczi                     backup->sync,
18743037f364SStefan Hajnoczi                     backup->has_mode, backup->mode,
18753037f364SStefan Hajnoczi                     backup->has_speed, backup->speed,
1876d58d8453SJohn Snow                     backup->has_bitmap, backup->bitmap,
18773037f364SStefan Hajnoczi                     backup->has_on_source_error, backup->on_source_error,
18783037f364SStefan Hajnoczi                     backup->has_on_target_error, backup->on_target_error,
187994d16a64SJohn Snow                     common->block_job_txn, &local_err);
188084d18f06SMarkus Armbruster     if (local_err) {
18813037f364SStefan Hajnoczi         error_propagate(errp, local_err);
18823037f364SStefan Hajnoczi         return;
18833037f364SStefan Hajnoczi     }
18843037f364SStefan Hajnoczi 
18853037f364SStefan Hajnoczi     state->job = state->bs->job;
18863037f364SStefan Hajnoczi }
18873037f364SStefan Hajnoczi 
188850f43f0fSJohn Snow static void drive_backup_abort(BlkActionState *common)
18893037f364SStefan Hajnoczi {
18903037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
18913037f364SStefan Hajnoczi     BlockDriverState *bs = state->bs;
18923037f364SStefan Hajnoczi 
18933037f364SStefan Hajnoczi     /* Only cancel if it's the job we started */
18943037f364SStefan Hajnoczi     if (bs && bs->job && bs->job == state->job) {
18953037f364SStefan Hajnoczi         block_job_cancel_sync(bs->job);
18963037f364SStefan Hajnoczi     }
18973037f364SStefan Hajnoczi }
18983037f364SStefan Hajnoczi 
189950f43f0fSJohn Snow static void drive_backup_clean(BlkActionState *common)
19005d6e96efSStefan Hajnoczi {
19015d6e96efSStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
19025d6e96efSStefan Hajnoczi 
19035d6e96efSStefan Hajnoczi     if (state->aio_context) {
19041fdd4b7bSFam Zheng         bdrv_drained_end(state->bs);
19055d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
19065d6e96efSStefan Hajnoczi     }
19075d6e96efSStefan Hajnoczi }
19085d6e96efSStefan Hajnoczi 
1909bd8baecdSFam Zheng typedef struct BlockdevBackupState {
191050f43f0fSJohn Snow     BlkActionState common;
1911bd8baecdSFam Zheng     BlockDriverState *bs;
1912bd8baecdSFam Zheng     BlockJob *job;
1913bd8baecdSFam Zheng     AioContext *aio_context;
1914bd8baecdSFam Zheng } BlockdevBackupState;
1915bd8baecdSFam Zheng 
191678f51fdeSJohn Snow static void do_blockdev_backup(const char *device, const char *target,
191778f51fdeSJohn Snow                                enum MirrorSyncMode sync,
191878f51fdeSJohn Snow                                bool has_speed, int64_t speed,
191978f51fdeSJohn Snow                                bool has_on_source_error,
192078f51fdeSJohn Snow                                BlockdevOnError on_source_error,
192178f51fdeSJohn Snow                                bool has_on_target_error,
192278f51fdeSJohn Snow                                BlockdevOnError on_target_error,
192378f51fdeSJohn Snow                                BlockJobTxn *txn, Error **errp);
192478f51fdeSJohn Snow 
192550f43f0fSJohn Snow static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1926bd8baecdSFam Zheng {
1927bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1928bd8baecdSFam Zheng     BlockdevBackup *backup;
19295433c24fSMax Reitz     BlockBackend *blk, *target;
1930bd8baecdSFam Zheng     Error *local_err = NULL;
1931bd8baecdSFam Zheng 
19326a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
19336a8f9661SEric Blake     backup = common->action->u.blockdev_backup;
1934bd8baecdSFam Zheng 
1935a0e8544cSFam Zheng     blk = blk_by_name(backup->device);
1936a0e8544cSFam Zheng     if (!blk) {
19375b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", backup->device);
1938bd8baecdSFam Zheng         return;
1939bd8baecdSFam Zheng     }
1940bd8baecdSFam Zheng 
1941ff52bf36SFam Zheng     if (!blk_is_available(blk)) {
1942ff52bf36SFam Zheng         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1943ff52bf36SFam Zheng         return;
1944ff52bf36SFam Zheng     }
1945ff52bf36SFam Zheng 
19465433c24fSMax Reitz     target = blk_by_name(backup->target);
19475433c24fSMax Reitz     if (!target) {
19485b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", backup->target);
1949bd8baecdSFam Zheng         return;
1950bd8baecdSFam Zheng     }
1951bd8baecdSFam Zheng 
1952bd8baecdSFam Zheng     /* AioContext is released in .clean() */
19535433c24fSMax Reitz     state->aio_context = blk_get_aio_context(blk);
19545433c24fSMax Reitz     if (state->aio_context != blk_get_aio_context(target)) {
1955bd8baecdSFam Zheng         state->aio_context = NULL;
1956bd8baecdSFam Zheng         error_setg(errp, "Backup between two IO threads is not implemented");
1957bd8baecdSFam Zheng         return;
1958bd8baecdSFam Zheng     }
1959bd8baecdSFam Zheng     aio_context_acquire(state->aio_context);
1960ff52bf36SFam Zheng     state->bs = blk_bs(blk);
1961ff52bf36SFam Zheng     bdrv_drained_begin(state->bs);
1962bd8baecdSFam Zheng 
196378f51fdeSJohn Snow     do_blockdev_backup(backup->device, backup->target,
1964bd8baecdSFam Zheng                        backup->sync,
1965bd8baecdSFam Zheng                        backup->has_speed, backup->speed,
1966bd8baecdSFam Zheng                        backup->has_on_source_error, backup->on_source_error,
1967bd8baecdSFam Zheng                        backup->has_on_target_error, backup->on_target_error,
196894d16a64SJohn Snow                        common->block_job_txn, &local_err);
1969bd8baecdSFam Zheng     if (local_err) {
1970bd8baecdSFam Zheng         error_propagate(errp, local_err);
1971bd8baecdSFam Zheng         return;
1972bd8baecdSFam Zheng     }
1973bd8baecdSFam Zheng 
1974bd8baecdSFam Zheng     state->job = state->bs->job;
1975bd8baecdSFam Zheng }
1976bd8baecdSFam Zheng 
197750f43f0fSJohn Snow static void blockdev_backup_abort(BlkActionState *common)
1978bd8baecdSFam Zheng {
1979bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1980bd8baecdSFam Zheng     BlockDriverState *bs = state->bs;
1981bd8baecdSFam Zheng 
1982bd8baecdSFam Zheng     /* Only cancel if it's the job we started */
1983bd8baecdSFam Zheng     if (bs && bs->job && bs->job == state->job) {
1984bd8baecdSFam Zheng         block_job_cancel_sync(bs->job);
1985bd8baecdSFam Zheng     }
1986bd8baecdSFam Zheng }
1987bd8baecdSFam Zheng 
198850f43f0fSJohn Snow static void blockdev_backup_clean(BlkActionState *common)
1989bd8baecdSFam Zheng {
1990bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1991bd8baecdSFam Zheng 
1992bd8baecdSFam Zheng     if (state->aio_context) {
1993ff52bf36SFam Zheng         bdrv_drained_end(state->bs);
1994bd8baecdSFam Zheng         aio_context_release(state->aio_context);
1995bd8baecdSFam Zheng     }
1996bd8baecdSFam Zheng }
1997bd8baecdSFam Zheng 
1998df9a681dSFam Zheng typedef struct BlockDirtyBitmapState {
199950f43f0fSJohn Snow     BlkActionState common;
2000df9a681dSFam Zheng     BdrvDirtyBitmap *bitmap;
2001df9a681dSFam Zheng     BlockDriverState *bs;
2002df9a681dSFam Zheng     AioContext *aio_context;
2003df9a681dSFam Zheng     HBitmap *backup;
2004df9a681dSFam Zheng     bool prepared;
2005df9a681dSFam Zheng } BlockDirtyBitmapState;
2006df9a681dSFam Zheng 
200750f43f0fSJohn Snow static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2008df9a681dSFam Zheng                                            Error **errp)
2009df9a681dSFam Zheng {
2010df9a681dSFam Zheng     Error *local_err = NULL;
2011df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
2012df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2013df9a681dSFam Zheng                                              common, common);
2014df9a681dSFam Zheng 
201594d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
201694d16a64SJohn Snow         return;
201794d16a64SJohn Snow     }
201894d16a64SJohn Snow 
201950f43f0fSJohn Snow     action = common->action->u.block_dirty_bitmap_add;
2020df9a681dSFam Zheng     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2021df9a681dSFam Zheng     qmp_block_dirty_bitmap_add(action->node, action->name,
2022df9a681dSFam Zheng                                action->has_granularity, action->granularity,
2023df9a681dSFam Zheng                                &local_err);
2024df9a681dSFam Zheng 
2025df9a681dSFam Zheng     if (!local_err) {
2026df9a681dSFam Zheng         state->prepared = true;
2027df9a681dSFam Zheng     } else {
2028df9a681dSFam Zheng         error_propagate(errp, local_err);
2029df9a681dSFam Zheng     }
2030df9a681dSFam Zheng }
2031df9a681dSFam Zheng 
203250f43f0fSJohn Snow static void block_dirty_bitmap_add_abort(BlkActionState *common)
2033df9a681dSFam Zheng {
2034df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
2035df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2036df9a681dSFam Zheng                                              common, common);
2037df9a681dSFam Zheng 
203850f43f0fSJohn Snow     action = common->action->u.block_dirty_bitmap_add;
2039df9a681dSFam Zheng     /* Should not be able to fail: IF the bitmap was added via .prepare(),
2040df9a681dSFam Zheng      * then the node reference and bitmap name must have been valid.
2041df9a681dSFam Zheng      */
2042df9a681dSFam Zheng     if (state->prepared) {
2043df9a681dSFam Zheng         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2044df9a681dSFam Zheng     }
2045df9a681dSFam Zheng }
2046df9a681dSFam Zheng 
204750f43f0fSJohn Snow static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2048df9a681dSFam Zheng                                              Error **errp)
2049df9a681dSFam Zheng {
2050df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2051df9a681dSFam Zheng                                              common, common);
2052df9a681dSFam Zheng     BlockDirtyBitmap *action;
2053df9a681dSFam Zheng 
205494d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
205594d16a64SJohn Snow         return;
205694d16a64SJohn Snow     }
205794d16a64SJohn Snow 
205850f43f0fSJohn Snow     action = common->action->u.block_dirty_bitmap_clear;
2059df9a681dSFam Zheng     state->bitmap = block_dirty_bitmap_lookup(action->node,
2060df9a681dSFam Zheng                                               action->name,
2061df9a681dSFam Zheng                                               &state->bs,
2062df9a681dSFam Zheng                                               &state->aio_context,
2063df9a681dSFam Zheng                                               errp);
2064df9a681dSFam Zheng     if (!state->bitmap) {
2065df9a681dSFam Zheng         return;
2066df9a681dSFam Zheng     }
2067df9a681dSFam Zheng 
2068df9a681dSFam Zheng     if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2069df9a681dSFam Zheng         error_setg(errp, "Cannot modify a frozen bitmap");
2070df9a681dSFam Zheng         return;
2071df9a681dSFam Zheng     } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2072df9a681dSFam Zheng         error_setg(errp, "Cannot clear a disabled bitmap");
2073df9a681dSFam Zheng         return;
2074df9a681dSFam Zheng     }
2075df9a681dSFam Zheng 
2076df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2077df9a681dSFam Zheng     /* AioContext is released in .clean() */
2078df9a681dSFam Zheng }
2079df9a681dSFam Zheng 
208050f43f0fSJohn Snow static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2081df9a681dSFam Zheng {
2082df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2083df9a681dSFam Zheng                                              common, common);
2084df9a681dSFam Zheng 
2085df9a681dSFam Zheng     bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2086df9a681dSFam Zheng }
2087df9a681dSFam Zheng 
208850f43f0fSJohn Snow static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2089df9a681dSFam Zheng {
2090df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2091df9a681dSFam Zheng                                              common, common);
2092df9a681dSFam Zheng 
2093df9a681dSFam Zheng     hbitmap_free(state->backup);
2094df9a681dSFam Zheng }
2095df9a681dSFam Zheng 
209650f43f0fSJohn Snow static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2097df9a681dSFam Zheng {
2098df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2099df9a681dSFam Zheng                                              common, common);
2100df9a681dSFam Zheng 
2101df9a681dSFam Zheng     if (state->aio_context) {
2102df9a681dSFam Zheng         aio_context_release(state->aio_context);
2103df9a681dSFam Zheng     }
2104df9a681dSFam Zheng }
2105df9a681dSFam Zheng 
210650f43f0fSJohn Snow static void abort_prepare(BlkActionState *common, Error **errp)
210778b18b78SStefan Hajnoczi {
210878b18b78SStefan Hajnoczi     error_setg(errp, "Transaction aborted using Abort action");
210978b18b78SStefan Hajnoczi }
211078b18b78SStefan Hajnoczi 
211150f43f0fSJohn Snow static void abort_commit(BlkActionState *common)
211278b18b78SStefan Hajnoczi {
2113dfc6f865SStefan Weil     g_assert_not_reached(); /* this action never succeeds */
211478b18b78SStefan Hajnoczi }
211578b18b78SStefan Hajnoczi 
211650f43f0fSJohn Snow static const BlkActionOps actions[] = {
211743de7e2dSAlberto Garcia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
211843de7e2dSAlberto Garcia         .instance_size = sizeof(ExternalSnapshotState),
211943de7e2dSAlberto Garcia         .prepare  = external_snapshot_prepare,
212043de7e2dSAlberto Garcia         .commit   = external_snapshot_commit,
212143de7e2dSAlberto Garcia         .abort = external_snapshot_abort,
21224ad6f3dbSAlberto Garcia         .clean = external_snapshot_clean,
212343de7e2dSAlberto Garcia     },
2124c8a83e85SKevin Wolf     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2125ba5d6ab6SStefan Hajnoczi         .instance_size = sizeof(ExternalSnapshotState),
2126ba0c86a3SWenchao Xia         .prepare  = external_snapshot_prepare,
2127ba0c86a3SWenchao Xia         .commit   = external_snapshot_commit,
2128ba0c86a3SWenchao Xia         .abort = external_snapshot_abort,
2129da763e83SFam Zheng         .clean = external_snapshot_clean,
2130ba0c86a3SWenchao Xia     },
21313037f364SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
21323037f364SStefan Hajnoczi         .instance_size = sizeof(DriveBackupState),
21333037f364SStefan Hajnoczi         .prepare = drive_backup_prepare,
21343037f364SStefan Hajnoczi         .abort = drive_backup_abort,
21355d6e96efSStefan Hajnoczi         .clean = drive_backup_clean,
21363037f364SStefan Hajnoczi     },
2137bd8baecdSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2138bd8baecdSFam Zheng         .instance_size = sizeof(BlockdevBackupState),
2139bd8baecdSFam Zheng         .prepare = blockdev_backup_prepare,
2140bd8baecdSFam Zheng         .abort = blockdev_backup_abort,
2141bd8baecdSFam Zheng         .clean = blockdev_backup_clean,
2142bd8baecdSFam Zheng     },
214378b18b78SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_ABORT] = {
214450f43f0fSJohn Snow         .instance_size = sizeof(BlkActionState),
214578b18b78SStefan Hajnoczi         .prepare = abort_prepare,
214678b18b78SStefan Hajnoczi         .commit = abort_commit,
214778b18b78SStefan Hajnoczi     },
2148bbe86010SWenchao Xia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2149bbe86010SWenchao Xia         .instance_size = sizeof(InternalSnapshotState),
2150bbe86010SWenchao Xia         .prepare  = internal_snapshot_prepare,
2151bbe86010SWenchao Xia         .abort = internal_snapshot_abort,
21525d6e96efSStefan Hajnoczi         .clean = internal_snapshot_clean,
2153bbe86010SWenchao Xia     },
2154df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2155df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2156df9a681dSFam Zheng         .prepare = block_dirty_bitmap_add_prepare,
2157df9a681dSFam Zheng         .abort = block_dirty_bitmap_add_abort,
2158df9a681dSFam Zheng     },
2159df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2160df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2161df9a681dSFam Zheng         .prepare = block_dirty_bitmap_clear_prepare,
2162df9a681dSFam Zheng         .commit = block_dirty_bitmap_clear_commit,
2163df9a681dSFam Zheng         .abort = block_dirty_bitmap_clear_abort,
2164df9a681dSFam Zheng         .clean = block_dirty_bitmap_clear_clean,
2165df9a681dSFam Zheng     }
2166ba0c86a3SWenchao Xia };
2167ba0c86a3SWenchao Xia 
216894d16a64SJohn Snow /**
216994d16a64SJohn Snow  * Allocate a TransactionProperties structure if necessary, and fill
217094d16a64SJohn Snow  * that structure with desired defaults if they are unset.
217194d16a64SJohn Snow  */
217294d16a64SJohn Snow static TransactionProperties *get_transaction_properties(
217394d16a64SJohn Snow     TransactionProperties *props)
217494d16a64SJohn Snow {
217594d16a64SJohn Snow     if (!props) {
217694d16a64SJohn Snow         props = g_new0(TransactionProperties, 1);
217794d16a64SJohn Snow     }
217894d16a64SJohn Snow 
217994d16a64SJohn Snow     if (!props->has_completion_mode) {
218094d16a64SJohn Snow         props->has_completion_mode = true;
218194d16a64SJohn Snow         props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
218294d16a64SJohn Snow     }
218394d16a64SJohn Snow 
218494d16a64SJohn Snow     return props;
218594d16a64SJohn Snow }
218694d16a64SJohn Snow 
21878802d1fdSJeff Cody /*
2188b756b9ceSStefan Hajnoczi  * 'Atomic' group operations.  The operations are performed as a set, and if
2189b756b9ceSStefan Hajnoczi  * any fail then we roll back all operations in the group.
21908802d1fdSJeff Cody  */
219194d16a64SJohn Snow void qmp_transaction(TransactionActionList *dev_list,
219294d16a64SJohn Snow                      bool has_props,
219394d16a64SJohn Snow                      struct TransactionProperties *props,
219494d16a64SJohn Snow                      Error **errp)
21958802d1fdSJeff Cody {
2196c8a83e85SKevin Wolf     TransactionActionList *dev_entry = dev_list;
219794d16a64SJohn Snow     BlockJobTxn *block_job_txn = NULL;
219850f43f0fSJohn Snow     BlkActionState *state, *next;
219943e17041SLuiz Capitulino     Error *local_err = NULL;
22008802d1fdSJeff Cody 
220150f43f0fSJohn Snow     QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
22028802d1fdSJeff Cody     QSIMPLEQ_INIT(&snap_bdrv_states);
22038802d1fdSJeff Cody 
220494d16a64SJohn Snow     /* Does this transaction get canceled as a group on failure?
220594d16a64SJohn Snow      * If not, we don't really need to make a BlockJobTxn.
220694d16a64SJohn Snow      */
220794d16a64SJohn Snow     props = get_transaction_properties(props);
220894d16a64SJohn Snow     if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
220994d16a64SJohn Snow         block_job_txn = block_job_txn_new();
221094d16a64SJohn Snow     }
221194d16a64SJohn Snow 
2212b756b9ceSStefan Hajnoczi     /* drain all i/o before any operations */
22138802d1fdSJeff Cody     bdrv_drain_all();
22148802d1fdSJeff Cody 
2215b756b9ceSStefan Hajnoczi     /* We don't do anything in this loop that commits us to the operations */
22168802d1fdSJeff Cody     while (NULL != dev_entry) {
2217c8a83e85SKevin Wolf         TransactionAction *dev_info = NULL;
221850f43f0fSJohn Snow         const BlkActionOps *ops;
221952e7c241SPaolo Bonzini 
22208802d1fdSJeff Cody         dev_info = dev_entry->value;
22218802d1fdSJeff Cody         dev_entry = dev_entry->next;
22228802d1fdSJeff Cody 
22236a8f9661SEric Blake         assert(dev_info->type < ARRAY_SIZE(actions));
2224ba0c86a3SWenchao Xia 
22256a8f9661SEric Blake         ops = &actions[dev_info->type];
2226aa3fe714SMax Reitz         assert(ops->instance_size > 0);
2227aa3fe714SMax Reitz 
2228ba5d6ab6SStefan Hajnoczi         state = g_malloc0(ops->instance_size);
2229ba5d6ab6SStefan Hajnoczi         state->ops = ops;
2230ba5d6ab6SStefan Hajnoczi         state->action = dev_info;
223194d16a64SJohn Snow         state->block_job_txn = block_job_txn;
223294d16a64SJohn Snow         state->txn_props = props;
2233ba5d6ab6SStefan Hajnoczi         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
22348802d1fdSJeff Cody 
2235ba5d6ab6SStefan Hajnoczi         state->ops->prepare(state, &local_err);
223684d18f06SMarkus Armbruster         if (local_err) {
22379b9877eeSWenchao Xia             error_propagate(errp, local_err);
22389b9877eeSWenchao Xia             goto delete_and_fail;
22399b9877eeSWenchao Xia         }
224052e7c241SPaolo Bonzini     }
22418802d1fdSJeff Cody 
2242ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2243f9ea81e8SStefan Hajnoczi         if (state->ops->commit) {
2244ba5d6ab6SStefan Hajnoczi             state->ops->commit(state);
22458802d1fdSJeff Cody         }
2246f9ea81e8SStefan Hajnoczi     }
22478802d1fdSJeff Cody 
22488802d1fdSJeff Cody     /* success */
22498802d1fdSJeff Cody     goto exit;
22508802d1fdSJeff Cody 
22518802d1fdSJeff Cody delete_and_fail:
2252b756b9ceSStefan Hajnoczi     /* failure, and it is all-or-none; roll back all operations */
2253ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2254ba5d6ab6SStefan Hajnoczi         if (state->ops->abort) {
2255ba5d6ab6SStefan Hajnoczi             state->ops->abort(state);
2256ba0c86a3SWenchao Xia         }
22578802d1fdSJeff Cody     }
22588802d1fdSJeff Cody exit:
2259ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2260ba5d6ab6SStefan Hajnoczi         if (state->ops->clean) {
2261ba5d6ab6SStefan Hajnoczi             state->ops->clean(state);
2262ba0c86a3SWenchao Xia         }
2263ba5d6ab6SStefan Hajnoczi         g_free(state);
22648802d1fdSJeff Cody     }
226594d16a64SJohn Snow     if (!has_props) {
226694d16a64SJohn Snow         qapi_free_TransactionProperties(props);
226794d16a64SJohn Snow     }
226894d16a64SJohn Snow     block_job_txn_unref(block_job_txn);
22698802d1fdSJeff Cody }
22708802d1fdSJeff Cody 
2271c245b6a3SLuiz Capitulino void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2272666daa68SMarkus Armbruster {
227338f54bd1SMax Reitz     Error *local_err = NULL;
2274666daa68SMarkus Armbruster 
227538f54bd1SMax Reitz     qmp_blockdev_open_tray(device, has_force, force, &local_err);
227638f54bd1SMax Reitz     if (local_err) {
227738f54bd1SMax Reitz         error_propagate(errp, local_err);
2278c245b6a3SLuiz Capitulino         return;
2279666daa68SMarkus Armbruster     }
228092d48558SLuiz Capitulino 
22816e0abc25SMax Reitz     qmp_x_blockdev_remove_medium(device, errp);
2282666daa68SMarkus Armbruster }
2283666daa68SMarkus Armbruster 
228412d3ba82SBenoît Canet void qmp_block_passwd(bool has_device, const char *device,
228512d3ba82SBenoît Canet                       bool has_node_name, const char *node_name,
228612d3ba82SBenoît Canet                       const char *password, Error **errp)
2287666daa68SMarkus Armbruster {
228812d3ba82SBenoît Canet     Error *local_err = NULL;
2289666daa68SMarkus Armbruster     BlockDriverState *bs;
2290e3442099SStefan Hajnoczi     AioContext *aio_context;
2291666daa68SMarkus Armbruster 
229212d3ba82SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
229312d3ba82SBenoît Canet                         has_node_name ? node_name : NULL,
229412d3ba82SBenoît Canet                         &local_err);
229584d18f06SMarkus Armbruster     if (local_err) {
229612d3ba82SBenoît Canet         error_propagate(errp, local_err);
2297a4dea8a9SLuiz Capitulino         return;
2298666daa68SMarkus Armbruster     }
2299666daa68SMarkus Armbruster 
2300e3442099SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
2301e3442099SStefan Hajnoczi     aio_context_acquire(aio_context);
2302e3442099SStefan Hajnoczi 
23034d2855a3SMarkus Armbruster     bdrv_add_key(bs, password, errp);
2304666daa68SMarkus Armbruster 
2305e3442099SStefan Hajnoczi     aio_context_release(aio_context);
2306e3442099SStefan Hajnoczi }
2307e3442099SStefan Hajnoczi 
23087d8a9f71SMax Reitz void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
23097d8a9f71SMax Reitz                             Error **errp)
23107d8a9f71SMax Reitz {
23117d8a9f71SMax Reitz     BlockBackend *blk;
23127d8a9f71SMax Reitz     bool locked;
23137d8a9f71SMax Reitz 
23147d8a9f71SMax Reitz     if (!has_force) {
23157d8a9f71SMax Reitz         force = false;
23167d8a9f71SMax Reitz     }
23177d8a9f71SMax Reitz 
23187d8a9f71SMax Reitz     blk = blk_by_name(device);
23197d8a9f71SMax Reitz     if (!blk) {
23207d8a9f71SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
23217d8a9f71SMax Reitz                   "Device '%s' not found", device);
23227d8a9f71SMax Reitz         return;
23237d8a9f71SMax Reitz     }
23247d8a9f71SMax Reitz 
23257d8a9f71SMax Reitz     if (!blk_dev_has_removable_media(blk)) {
23267d8a9f71SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
23277d8a9f71SMax Reitz         return;
23287d8a9f71SMax Reitz     }
23297d8a9f71SMax Reitz 
233012c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
233112c7ec87SMax Reitz         /* Ignore this command on tray-less devices */
233212c7ec87SMax Reitz         return;
233312c7ec87SMax Reitz     }
233412c7ec87SMax Reitz 
23357d8a9f71SMax Reitz     if (blk_dev_is_tray_open(blk)) {
23367d8a9f71SMax Reitz         return;
23377d8a9f71SMax Reitz     }
23387d8a9f71SMax Reitz 
23397d8a9f71SMax Reitz     locked = blk_dev_is_medium_locked(blk);
23407d8a9f71SMax Reitz     if (locked) {
23417d8a9f71SMax Reitz         blk_dev_eject_request(blk, force);
23427d8a9f71SMax Reitz     }
23437d8a9f71SMax Reitz 
23447d8a9f71SMax Reitz     if (!locked || force) {
23457d8a9f71SMax Reitz         blk_dev_change_media_cb(blk, false);
23467d8a9f71SMax Reitz     }
23477d8a9f71SMax Reitz }
23487d8a9f71SMax Reitz 
2349abaaf59dSMax Reitz void qmp_blockdev_close_tray(const char *device, Error **errp)
2350abaaf59dSMax Reitz {
2351abaaf59dSMax Reitz     BlockBackend *blk;
2352abaaf59dSMax Reitz 
2353abaaf59dSMax Reitz     blk = blk_by_name(device);
2354abaaf59dSMax Reitz     if (!blk) {
2355abaaf59dSMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2356abaaf59dSMax Reitz                   "Device '%s' not found", device);
2357abaaf59dSMax Reitz         return;
2358abaaf59dSMax Reitz     }
2359abaaf59dSMax Reitz 
2360abaaf59dSMax Reitz     if (!blk_dev_has_removable_media(blk)) {
2361abaaf59dSMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
2362abaaf59dSMax Reitz         return;
2363abaaf59dSMax Reitz     }
2364abaaf59dSMax Reitz 
236512c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
236612c7ec87SMax Reitz         /* Ignore this command on tray-less devices */
236712c7ec87SMax Reitz         return;
236812c7ec87SMax Reitz     }
236912c7ec87SMax Reitz 
2370abaaf59dSMax Reitz     if (!blk_dev_is_tray_open(blk)) {
2371abaaf59dSMax Reitz         return;
2372abaaf59dSMax Reitz     }
2373abaaf59dSMax Reitz 
2374abaaf59dSMax Reitz     blk_dev_change_media_cb(blk, true);
2375abaaf59dSMax Reitz }
2376abaaf59dSMax Reitz 
23776e0abc25SMax Reitz void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
23782814f672SMax Reitz {
23792814f672SMax Reitz     BlockBackend *blk;
23802814f672SMax Reitz     BlockDriverState *bs;
23812814f672SMax Reitz     AioContext *aio_context;
23822814f672SMax Reitz     bool has_device;
23832814f672SMax Reitz 
23842814f672SMax Reitz     blk = blk_by_name(device);
23852814f672SMax Reitz     if (!blk) {
23862814f672SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
23872814f672SMax Reitz                   "Device '%s' not found", device);
23882814f672SMax Reitz         return;
23892814f672SMax Reitz     }
23902814f672SMax Reitz 
23912814f672SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
23922814f672SMax Reitz     has_device = blk_get_attached_dev(blk);
23932814f672SMax Reitz 
23942814f672SMax Reitz     if (has_device && !blk_dev_has_removable_media(blk)) {
23952814f672SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
23962814f672SMax Reitz         return;
23972814f672SMax Reitz     }
23982814f672SMax Reitz 
239912c7ec87SMax Reitz     if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
24002814f672SMax Reitz         error_setg(errp, "Tray of device '%s' is not open", device);
24012814f672SMax Reitz         return;
24022814f672SMax Reitz     }
24032814f672SMax Reitz 
24042814f672SMax Reitz     bs = blk_bs(blk);
24052814f672SMax Reitz     if (!bs) {
24062814f672SMax Reitz         return;
24072814f672SMax Reitz     }
24082814f672SMax Reitz 
24092814f672SMax Reitz     aio_context = bdrv_get_aio_context(bs);
24102814f672SMax Reitz     aio_context_acquire(aio_context);
24112814f672SMax Reitz 
24122814f672SMax Reitz     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
24132814f672SMax Reitz         goto out;
24142814f672SMax Reitz     }
24152814f672SMax Reitz 
24162814f672SMax Reitz     /* This follows the convention established by bdrv_make_anon() */
24172814f672SMax Reitz     if (bs->device_list.tqe_prev) {
2418f8aa905aSJeff Cody         bdrv_device_remove(bs);
24192814f672SMax Reitz     }
24202814f672SMax Reitz 
24212814f672SMax Reitz     blk_remove_bs(blk);
24222814f672SMax Reitz 
242312c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
242412c7ec87SMax Reitz         /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
242512c7ec87SMax Reitz          * called at all); therefore, the medium needs to be ejected here.
242612c7ec87SMax Reitz          * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
242712c7ec87SMax Reitz          * value passed here (i.e. false). */
242812c7ec87SMax Reitz         blk_dev_change_media_cb(blk, false);
242912c7ec87SMax Reitz     }
243012c7ec87SMax Reitz 
24312814f672SMax Reitz out:
24322814f672SMax Reitz     aio_context_release(aio_context);
24332814f672SMax Reitz }
24342814f672SMax Reitz 
2435d1299882SMax Reitz static void qmp_blockdev_insert_anon_medium(const char *device,
2436d1299882SMax Reitz                                             BlockDriverState *bs, Error **errp)
2437d1299882SMax Reitz {
2438d1299882SMax Reitz     BlockBackend *blk;
2439d1299882SMax Reitz     bool has_device;
2440d1299882SMax Reitz 
2441d1299882SMax Reitz     blk = blk_by_name(device);
2442d1299882SMax Reitz     if (!blk) {
2443d1299882SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2444d1299882SMax Reitz                   "Device '%s' not found", device);
2445d1299882SMax Reitz         return;
2446d1299882SMax Reitz     }
2447d1299882SMax Reitz 
2448d1299882SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
2449d1299882SMax Reitz     has_device = blk_get_attached_dev(blk);
2450d1299882SMax Reitz 
2451d1299882SMax Reitz     if (has_device && !blk_dev_has_removable_media(blk)) {
2452d1299882SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
2453d1299882SMax Reitz         return;
2454d1299882SMax Reitz     }
2455d1299882SMax Reitz 
245612c7ec87SMax Reitz     if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2457d1299882SMax Reitz         error_setg(errp, "Tray of device '%s' is not open", device);
2458d1299882SMax Reitz         return;
2459d1299882SMax Reitz     }
2460d1299882SMax Reitz 
2461d1299882SMax Reitz     if (blk_bs(blk)) {
2462d1299882SMax Reitz         error_setg(errp, "There already is a medium in device '%s'", device);
2463d1299882SMax Reitz         return;
2464d1299882SMax Reitz     }
2465d1299882SMax Reitz 
2466d1299882SMax Reitz     blk_insert_bs(blk, bs);
2467d1299882SMax Reitz 
2468d1299882SMax Reitz     QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
246912c7ec87SMax Reitz 
247012c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
247112c7ec87SMax Reitz         /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
247212c7ec87SMax Reitz          * called at all); therefore, the medium needs to be pushed into the
247312c7ec87SMax Reitz          * slot here.
247412c7ec87SMax Reitz          * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
247512c7ec87SMax Reitz          * value passed here (i.e. true). */
247612c7ec87SMax Reitz         blk_dev_change_media_cb(blk, true);
247712c7ec87SMax Reitz     }
2478d1299882SMax Reitz }
2479d1299882SMax Reitz 
24806e0abc25SMax Reitz void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2481d1299882SMax Reitz                                   Error **errp)
2482d1299882SMax Reitz {
2483d1299882SMax Reitz     BlockDriverState *bs;
2484d1299882SMax Reitz 
2485d1299882SMax Reitz     bs = bdrv_find_node(node_name);
2486d1299882SMax Reitz     if (!bs) {
2487d1299882SMax Reitz         error_setg(errp, "Node '%s' not found", node_name);
2488d1299882SMax Reitz         return;
2489d1299882SMax Reitz     }
2490d1299882SMax Reitz 
2491d1299882SMax Reitz     if (bs->blk) {
2492d1299882SMax Reitz         error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2493d1299882SMax Reitz                    blk_name(bs->blk));
2494d1299882SMax Reitz         return;
2495d1299882SMax Reitz     }
2496d1299882SMax Reitz 
2497d1299882SMax Reitz     qmp_blockdev_insert_anon_medium(device, bs, errp);
2498d1299882SMax Reitz }
2499d1299882SMax Reitz 
250024fb4133SMax Reitz void qmp_blockdev_change_medium(const char *device, const char *filename,
250124fb4133SMax Reitz                                 bool has_format, const char *format,
250239ff43d9SMax Reitz                                 bool has_read_only,
250339ff43d9SMax Reitz                                 BlockdevChangeReadOnlyMode read_only,
250424fb4133SMax Reitz                                 Error **errp)
2505de2c6c05SMax Reitz {
2506de2c6c05SMax Reitz     BlockBackend *blk;
2507de2c6c05SMax Reitz     BlockDriverState *medium_bs = NULL;
2508de2c6c05SMax Reitz     int bdrv_flags, ret;
2509de2c6c05SMax Reitz     QDict *options = NULL;
2510de2c6c05SMax Reitz     Error *err = NULL;
2511de2c6c05SMax Reitz 
2512de2c6c05SMax Reitz     blk = blk_by_name(device);
2513de2c6c05SMax Reitz     if (!blk) {
2514de2c6c05SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2515de2c6c05SMax Reitz                   "Device '%s' not found", device);
2516de2c6c05SMax Reitz         goto fail;
2517de2c6c05SMax Reitz     }
2518de2c6c05SMax Reitz 
2519de2c6c05SMax Reitz     if (blk_bs(blk)) {
2520de2c6c05SMax Reitz         blk_update_root_state(blk);
2521de2c6c05SMax Reitz     }
2522de2c6c05SMax Reitz 
2523de2c6c05SMax Reitz     bdrv_flags = blk_get_open_flags_from_root_state(blk);
2524156abc2fSAlyssa Milburn     bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2525156abc2fSAlyssa Milburn         BDRV_O_PROTOCOL);
2526de2c6c05SMax Reitz 
252739ff43d9SMax Reitz     if (!has_read_only) {
252839ff43d9SMax Reitz         read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
252939ff43d9SMax Reitz     }
253039ff43d9SMax Reitz 
253139ff43d9SMax Reitz     switch (read_only) {
253239ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
253339ff43d9SMax Reitz         break;
253439ff43d9SMax Reitz 
253539ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
253639ff43d9SMax Reitz         bdrv_flags &= ~BDRV_O_RDWR;
253739ff43d9SMax Reitz         break;
253839ff43d9SMax Reitz 
253939ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
254039ff43d9SMax Reitz         bdrv_flags |= BDRV_O_RDWR;
254139ff43d9SMax Reitz         break;
254239ff43d9SMax Reitz 
254339ff43d9SMax Reitz     default:
254439ff43d9SMax Reitz         abort();
254539ff43d9SMax Reitz     }
254639ff43d9SMax Reitz 
254724fb4133SMax Reitz     if (has_format) {
2548de2c6c05SMax Reitz         options = qdict_new();
2549de2c6c05SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
2550de2c6c05SMax Reitz     }
2551de2c6c05SMax Reitz 
2552de2c6c05SMax Reitz     assert(!medium_bs);
2553de2c6c05SMax Reitz     ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2554de2c6c05SMax Reitz     if (ret < 0) {
2555de2c6c05SMax Reitz         goto fail;
2556de2c6c05SMax Reitz     }
2557de2c6c05SMax Reitz 
2558de2c6c05SMax Reitz     blk_apply_root_state(blk, medium_bs);
2559de2c6c05SMax Reitz 
2560de2c6c05SMax Reitz     bdrv_add_key(medium_bs, NULL, &err);
2561de2c6c05SMax Reitz     if (err) {
2562de2c6c05SMax Reitz         error_propagate(errp, err);
2563de2c6c05SMax Reitz         goto fail;
2564de2c6c05SMax Reitz     }
2565de2c6c05SMax Reitz 
2566de2c6c05SMax Reitz     qmp_blockdev_open_tray(device, false, false, &err);
2567de2c6c05SMax Reitz     if (err) {
2568de2c6c05SMax Reitz         error_propagate(errp, err);
2569de2c6c05SMax Reitz         goto fail;
2570de2c6c05SMax Reitz     }
2571de2c6c05SMax Reitz 
25726e0abc25SMax Reitz     qmp_x_blockdev_remove_medium(device, &err);
2573de2c6c05SMax Reitz     if (err) {
2574de2c6c05SMax Reitz         error_propagate(errp, err);
2575de2c6c05SMax Reitz         goto fail;
2576de2c6c05SMax Reitz     }
2577de2c6c05SMax Reitz 
2578de2c6c05SMax Reitz     qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2579de2c6c05SMax Reitz     if (err) {
2580de2c6c05SMax Reitz         error_propagate(errp, err);
2581de2c6c05SMax Reitz         goto fail;
2582de2c6c05SMax Reitz     }
2583de2c6c05SMax Reitz 
2584de2c6c05SMax Reitz     qmp_blockdev_close_tray(device, errp);
2585de2c6c05SMax Reitz 
2586de2c6c05SMax Reitz fail:
2587de2c6c05SMax Reitz     /* If the medium has been inserted, the device has its own reference, so
2588de2c6c05SMax Reitz      * ours must be relinquished; and if it has not been inserted successfully,
2589de2c6c05SMax Reitz      * the reference must be relinquished anyway */
2590de2c6c05SMax Reitz     bdrv_unref(medium_bs);
2591de2c6c05SMax Reitz }
2592de2c6c05SMax Reitz 
2593727f005eSZhi Yong Wu /* throttling disk I/O limits */
259480047da5SLuiz Capitulino void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
25953e9fab69SBenoît Canet                                int64_t bps_wr,
25963e9fab69SBenoît Canet                                int64_t iops,
25973e9fab69SBenoît Canet                                int64_t iops_rd,
25983e9fab69SBenoît Canet                                int64_t iops_wr,
25993e9fab69SBenoît Canet                                bool has_bps_max,
26003e9fab69SBenoît Canet                                int64_t bps_max,
26013e9fab69SBenoît Canet                                bool has_bps_rd_max,
26023e9fab69SBenoît Canet                                int64_t bps_rd_max,
26033e9fab69SBenoît Canet                                bool has_bps_wr_max,
26043e9fab69SBenoît Canet                                int64_t bps_wr_max,
26053e9fab69SBenoît Canet                                bool has_iops_max,
26063e9fab69SBenoît Canet                                int64_t iops_max,
26073e9fab69SBenoît Canet                                bool has_iops_rd_max,
26083e9fab69SBenoît Canet                                int64_t iops_rd_max,
26093e9fab69SBenoît Canet                                bool has_iops_wr_max,
26102024c1dfSBenoît Canet                                int64_t iops_wr_max,
2611dce13204SAlberto Garcia                                bool has_bps_max_length,
2612dce13204SAlberto Garcia                                int64_t bps_max_length,
2613dce13204SAlberto Garcia                                bool has_bps_rd_max_length,
2614dce13204SAlberto Garcia                                int64_t bps_rd_max_length,
2615dce13204SAlberto Garcia                                bool has_bps_wr_max_length,
2616dce13204SAlberto Garcia                                int64_t bps_wr_max_length,
2617dce13204SAlberto Garcia                                bool has_iops_max_length,
2618dce13204SAlberto Garcia                                int64_t iops_max_length,
2619dce13204SAlberto Garcia                                bool has_iops_rd_max_length,
2620dce13204SAlberto Garcia                                int64_t iops_rd_max_length,
2621dce13204SAlberto Garcia                                bool has_iops_wr_max_length,
2622dce13204SAlberto Garcia                                int64_t iops_wr_max_length,
26232024c1dfSBenoît Canet                                bool has_iops_size,
262476f4afb4SAlberto Garcia                                int64_t iops_size,
262576f4afb4SAlberto Garcia                                bool has_group,
262676f4afb4SAlberto Garcia                                const char *group, Error **errp)
2627727f005eSZhi Yong Wu {
2628cc0681c4SBenoît Canet     ThrottleConfig cfg;
2629727f005eSZhi Yong Wu     BlockDriverState *bs;
2630a0e8544cSFam Zheng     BlockBackend *blk;
2631b15446fdSStefan Hajnoczi     AioContext *aio_context;
2632727f005eSZhi Yong Wu 
2633a0e8544cSFam Zheng     blk = blk_by_name(device);
2634a0e8544cSFam Zheng     if (!blk) {
263575158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
263675158ebbSMarkus Armbruster                   "Device '%s' not found", device);
263780047da5SLuiz Capitulino         return;
2638727f005eSZhi Yong Wu     }
26395433c24fSMax Reitz 
26405433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
26415433c24fSMax Reitz     aio_context_acquire(aio_context);
26425433c24fSMax Reitz 
2643a0e8544cSFam Zheng     bs = blk_bs(blk);
26445433c24fSMax Reitz     if (!bs) {
26455433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
26465433c24fSMax Reitz         goto out;
26475433c24fSMax Reitz     }
2648727f005eSZhi Yong Wu 
26491588ab5dSAlberto Garcia     throttle_config_init(&cfg);
2650cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2651cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;
2652cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2653727f005eSZhi Yong Wu 
2654cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2655cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;
2656cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2657cc0681c4SBenoît Canet 
26583e9fab69SBenoît Canet     if (has_bps_max) {
26593e9fab69SBenoît Canet         cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
26603e9fab69SBenoît Canet     }
26613e9fab69SBenoît Canet     if (has_bps_rd_max) {
26623e9fab69SBenoît Canet         cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
26633e9fab69SBenoît Canet     }
26643e9fab69SBenoît Canet     if (has_bps_wr_max) {
26653e9fab69SBenoît Canet         cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
26663e9fab69SBenoît Canet     }
26673e9fab69SBenoît Canet     if (has_iops_max) {
26683e9fab69SBenoît Canet         cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
26693e9fab69SBenoît Canet     }
26703e9fab69SBenoît Canet     if (has_iops_rd_max) {
26713e9fab69SBenoît Canet         cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
26723e9fab69SBenoît Canet     }
26733e9fab69SBenoît Canet     if (has_iops_wr_max) {
26743e9fab69SBenoît Canet         cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
26753e9fab69SBenoît Canet     }
2676cc0681c4SBenoît Canet 
2677dce13204SAlberto Garcia     if (has_bps_max_length) {
2678dce13204SAlberto Garcia         cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = bps_max_length;
2679dce13204SAlberto Garcia     }
2680dce13204SAlberto Garcia     if (has_bps_rd_max_length) {
2681dce13204SAlberto Garcia         cfg.buckets[THROTTLE_BPS_READ].burst_length = bps_rd_max_length;
2682dce13204SAlberto Garcia     }
2683dce13204SAlberto Garcia     if (has_bps_wr_max_length) {
2684dce13204SAlberto Garcia         cfg.buckets[THROTTLE_BPS_WRITE].burst_length = bps_wr_max_length;
2685dce13204SAlberto Garcia     }
2686dce13204SAlberto Garcia     if (has_iops_max_length) {
2687dce13204SAlberto Garcia         cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = iops_max_length;
2688dce13204SAlberto Garcia     }
2689dce13204SAlberto Garcia     if (has_iops_rd_max_length) {
2690dce13204SAlberto Garcia         cfg.buckets[THROTTLE_OPS_READ].burst_length = iops_rd_max_length;
2691dce13204SAlberto Garcia     }
2692dce13204SAlberto Garcia     if (has_iops_wr_max_length) {
2693dce13204SAlberto Garcia         cfg.buckets[THROTTLE_OPS_WRITE].burst_length = iops_wr_max_length;
2694dce13204SAlberto Garcia     }
2695dce13204SAlberto Garcia 
26962024c1dfSBenoît Canet     if (has_iops_size) {
26972024c1dfSBenoît Canet         cfg.op_size = iops_size;
26982024c1dfSBenoît Canet     }
2699cc0681c4SBenoît Canet 
2700d5851089SAlberto Garcia     if (!throttle_is_valid(&cfg, errp)) {
27015433c24fSMax Reitz         goto out;
2702727f005eSZhi Yong Wu     }
2703727f005eSZhi Yong Wu 
270476f4afb4SAlberto Garcia     if (throttle_enabled(&cfg)) {
270576f4afb4SAlberto Garcia         /* Enable I/O limits if they're not enabled yet, otherwise
270676f4afb4SAlberto Garcia          * just update the throttling group. */
2707a0d64a61SAlberto Garcia         if (!bs->throttle_state) {
270876f4afb4SAlberto Garcia             bdrv_io_limits_enable(bs, has_group ? group : device);
270976f4afb4SAlberto Garcia         } else if (has_group) {
271076f4afb4SAlberto Garcia             bdrv_io_limits_update_group(bs, group);
2711727f005eSZhi Yong Wu         }
271276f4afb4SAlberto Garcia         /* Set the new throttling configuration */
2713cc0681c4SBenoît Canet         bdrv_set_io_limits(bs, &cfg);
2714a0d64a61SAlberto Garcia     } else if (bs->throttle_state) {
271576f4afb4SAlberto Garcia         /* If all throttling settings are set to 0, disable I/O limits */
271676f4afb4SAlberto Garcia         bdrv_io_limits_disable(bs);
2717727f005eSZhi Yong Wu     }
2718b15446fdSStefan Hajnoczi 
27195433c24fSMax Reitz out:
2720b15446fdSStefan Hajnoczi     aio_context_release(aio_context);
2721727f005eSZhi Yong Wu }
2722727f005eSZhi Yong Wu 
2723341ebc2fSJohn Snow void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2724341ebc2fSJohn Snow                                 bool has_granularity, uint32_t granularity,
2725341ebc2fSJohn Snow                                 Error **errp)
2726341ebc2fSJohn Snow {
2727341ebc2fSJohn Snow     AioContext *aio_context;
2728341ebc2fSJohn Snow     BlockDriverState *bs;
2729341ebc2fSJohn Snow 
2730341ebc2fSJohn Snow     if (!name || name[0] == '\0') {
2731341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be empty");
2732341ebc2fSJohn Snow         return;
2733341ebc2fSJohn Snow     }
2734341ebc2fSJohn Snow 
2735341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, errp);
2736341ebc2fSJohn Snow     if (!bs) {
2737341ebc2fSJohn Snow         return;
2738341ebc2fSJohn Snow     }
2739341ebc2fSJohn Snow 
2740341ebc2fSJohn Snow     aio_context = bdrv_get_aio_context(bs);
2741341ebc2fSJohn Snow     aio_context_acquire(aio_context);
2742341ebc2fSJohn Snow 
2743341ebc2fSJohn Snow     if (has_granularity) {
2744341ebc2fSJohn Snow         if (granularity < 512 || !is_power_of_2(granularity)) {
2745341ebc2fSJohn Snow             error_setg(errp, "Granularity must be power of 2 "
2746341ebc2fSJohn Snow                              "and at least 512");
2747341ebc2fSJohn Snow             goto out;
2748341ebc2fSJohn Snow         }
2749341ebc2fSJohn Snow     } else {
2750341ebc2fSJohn Snow         /* Default to cluster size, if available: */
2751341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(bs);
2752341ebc2fSJohn Snow     }
2753341ebc2fSJohn Snow 
2754341ebc2fSJohn Snow     bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2755341ebc2fSJohn Snow 
2756341ebc2fSJohn Snow  out:
2757341ebc2fSJohn Snow     aio_context_release(aio_context);
2758341ebc2fSJohn Snow }
2759341ebc2fSJohn Snow 
2760341ebc2fSJohn Snow void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2761341ebc2fSJohn Snow                                    Error **errp)
2762341ebc2fSJohn Snow {
2763341ebc2fSJohn Snow     AioContext *aio_context;
2764341ebc2fSJohn Snow     BlockDriverState *bs;
2765341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
2766341ebc2fSJohn Snow 
2767341ebc2fSJohn Snow     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2768341ebc2fSJohn Snow     if (!bitmap || !bs) {
2769341ebc2fSJohn Snow         return;
2770341ebc2fSJohn Snow     }
2771341ebc2fSJohn Snow 
27729bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
27739bd2b08fSJohn Snow         error_setg(errp,
27749bd2b08fSJohn Snow                    "Bitmap '%s' is currently frozen and cannot be removed",
27759bd2b08fSJohn Snow                    name);
27769bd2b08fSJohn Snow         goto out;
27779bd2b08fSJohn Snow     }
277820dca810SJohn Snow     bdrv_dirty_bitmap_make_anon(bitmap);
2779341ebc2fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
2780341ebc2fSJohn Snow 
27819bd2b08fSJohn Snow  out:
2782341ebc2fSJohn Snow     aio_context_release(aio_context);
2783341ebc2fSJohn Snow }
2784341ebc2fSJohn Snow 
2785e74e6b78SJohn Snow /**
2786e74e6b78SJohn Snow  * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2787e74e6b78SJohn Snow  * immediately after a full backup operation.
2788e74e6b78SJohn Snow  */
2789e74e6b78SJohn Snow void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2790e74e6b78SJohn Snow                                   Error **errp)
2791e74e6b78SJohn Snow {
2792e74e6b78SJohn Snow     AioContext *aio_context;
2793e74e6b78SJohn Snow     BdrvDirtyBitmap *bitmap;
2794e74e6b78SJohn Snow     BlockDriverState *bs;
2795e74e6b78SJohn Snow 
2796e74e6b78SJohn Snow     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2797e74e6b78SJohn Snow     if (!bitmap || !bs) {
2798e74e6b78SJohn Snow         return;
2799e74e6b78SJohn Snow     }
2800e74e6b78SJohn Snow 
2801e74e6b78SJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2802e74e6b78SJohn Snow         error_setg(errp,
2803e74e6b78SJohn Snow                    "Bitmap '%s' is currently frozen and cannot be modified",
2804e74e6b78SJohn Snow                    name);
2805e74e6b78SJohn Snow         goto out;
2806e74e6b78SJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2807e74e6b78SJohn Snow         error_setg(errp,
2808e74e6b78SJohn Snow                    "Bitmap '%s' is currently disabled and cannot be cleared",
2809e74e6b78SJohn Snow                    name);
2810e74e6b78SJohn Snow         goto out;
2811e74e6b78SJohn Snow     }
2812e74e6b78SJohn Snow 
2813df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(bitmap, NULL);
2814e74e6b78SJohn Snow 
2815e74e6b78SJohn Snow  out:
2816e74e6b78SJohn Snow     aio_context_release(aio_context);
2817e74e6b78SJohn Snow }
2818e74e6b78SJohn Snow 
2819072ebe6bSMarkus Armbruster void hmp_drive_del(Monitor *mon, const QDict *qdict)
28209063f814SRyan Harper {
28219063f814SRyan Harper     const char *id = qdict_get_str(qdict, "id");
28227e7d56d9SMarkus Armbruster     BlockBackend *blk;
28239063f814SRyan Harper     BlockDriverState *bs;
28248ad4202bSStefan Hajnoczi     AioContext *aio_context;
28253718d8abSFam Zheng     Error *local_err = NULL;
28269063f814SRyan Harper 
28277e7d56d9SMarkus Armbruster     blk = blk_by_name(id);
28287e7d56d9SMarkus Armbruster     if (!blk) {
2829b1422f20SMarkus Armbruster         error_report("Device '%s' not found", id);
2830072ebe6bSMarkus Armbruster         return;
28319063f814SRyan Harper     }
28328ad4202bSStefan Hajnoczi 
283326f8b3a8SMarkus Armbruster     if (!blk_legacy_dinfo(blk)) {
283448f364ddSMarkus Armbruster         error_report("Deleting device added with blockdev-add"
283548f364ddSMarkus Armbruster                      " is not supported");
2836072ebe6bSMarkus Armbruster         return;
283748f364ddSMarkus Armbruster     }
283848f364ddSMarkus Armbruster 
28395433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
28408ad4202bSStefan Hajnoczi     aio_context_acquire(aio_context);
28418ad4202bSStefan Hajnoczi 
28425433c24fSMax Reitz     bs = blk_bs(blk);
28435433c24fSMax Reitz     if (bs) {
28443718d8abSFam Zheng         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2845565f65d2SMarkus Armbruster             error_report_err(local_err);
28468ad4202bSStefan Hajnoczi             aio_context_release(aio_context);
2847072ebe6bSMarkus Armbruster             return;
28488591675fSMarcelo Tosatti         }
28499063f814SRyan Harper 
2850938abd43SMax Reitz         blk_remove_bs(blk);
28515433c24fSMax Reitz     }
28529063f814SRyan Harper 
2853fa879d62SMarkus Armbruster     /* if we have a device attached to this BlockDriverState
2854d22b2f41SRyan Harper      * then we need to make the drive anonymous until the device
2855d22b2f41SRyan Harper      * can be removed.  If this is a drive with no device backing
2856d22b2f41SRyan Harper      * then we can just get rid of the block driver state right here.
2857d22b2f41SRyan Harper      */
2858a7f53e26SMarkus Armbruster     if (blk_get_attached_dev(blk)) {
28593e5a50d6SMarkus Armbruster         blk_hide_on_behalf_of_hmp_drive_del(blk);
2860293c51a6SStefan Hajnoczi         /* Further I/O must not pause the guest */
2861373340b2SMax Reitz         blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2862293c51a6SStefan Hajnoczi                          BLOCKDEV_ON_ERROR_REPORT);
2863d22b2f41SRyan Harper     } else {
2864b9fe8a7aSMarkus Armbruster         blk_unref(blk);
2865d22b2f41SRyan Harper     }
28669063f814SRyan Harper 
28678ad4202bSStefan Hajnoczi     aio_context_release(aio_context);
28689063f814SRyan Harper }
28696d4a2b3aSChristoph Hellwig 
28703b1dbd11SBenoît Canet void qmp_block_resize(bool has_device, const char *device,
28713b1dbd11SBenoît Canet                       bool has_node_name, const char *node_name,
28723b1dbd11SBenoît Canet                       int64_t size, Error **errp)
28736d4a2b3aSChristoph Hellwig {
28743b1dbd11SBenoît Canet     Error *local_err = NULL;
28756d4a2b3aSChristoph Hellwig     BlockDriverState *bs;
2876927e0e76SStefan Hajnoczi     AioContext *aio_context;
28778732901eSKevin Wolf     int ret;
28786d4a2b3aSChristoph Hellwig 
28793b1dbd11SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
28803b1dbd11SBenoît Canet                         has_node_name ? node_name : NULL,
28813b1dbd11SBenoît Canet                         &local_err);
288284d18f06SMarkus Armbruster     if (local_err) {
28833b1dbd11SBenoît Canet         error_propagate(errp, local_err);
28843b1dbd11SBenoît Canet         return;
28853b1dbd11SBenoît Canet     }
28863b1dbd11SBenoît Canet 
2887927e0e76SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
2888927e0e76SStefan Hajnoczi     aio_context_acquire(aio_context);
2889927e0e76SStefan Hajnoczi 
28903b1dbd11SBenoît Canet     if (!bdrv_is_first_non_filter(bs)) {
2891c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2892927e0e76SStefan Hajnoczi         goto out;
28936d4a2b3aSChristoph Hellwig     }
28946d4a2b3aSChristoph Hellwig 
28956d4a2b3aSChristoph Hellwig     if (size < 0) {
2896c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2897927e0e76SStefan Hajnoczi         goto out;
28986d4a2b3aSChristoph Hellwig     }
28996d4a2b3aSChristoph Hellwig 
29009c75e168SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2901c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2902927e0e76SStefan Hajnoczi         goto out;
29039c75e168SJeff Cody     }
29049c75e168SJeff Cody 
290592b7a08dSPeter Lieven     /* complete all in-flight operations before resizing the device */
290692b7a08dSPeter Lieven     bdrv_drain_all();
290792b7a08dSPeter Lieven 
29088732901eSKevin Wolf     ret = bdrv_truncate(bs, size);
29098732901eSKevin Wolf     switch (ret) {
2910939a1cc3SStefan Hajnoczi     case 0:
2911939a1cc3SStefan Hajnoczi         break;
2912939a1cc3SStefan Hajnoczi     case -ENOMEDIUM:
2913c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2914939a1cc3SStefan Hajnoczi         break;
2915939a1cc3SStefan Hajnoczi     case -ENOTSUP:
2916c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_UNSUPPORTED);
2917939a1cc3SStefan Hajnoczi         break;
2918939a1cc3SStefan Hajnoczi     case -EACCES:
291981e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
2920939a1cc3SStefan Hajnoczi         break;
2921939a1cc3SStefan Hajnoczi     case -EBUSY:
2922c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2923939a1cc3SStefan Hajnoczi         break;
2924939a1cc3SStefan Hajnoczi     default:
29258732901eSKevin Wolf         error_setg_errno(errp, -ret, "Could not resize");
2926939a1cc3SStefan Hajnoczi         break;
29276d4a2b3aSChristoph Hellwig     }
2928927e0e76SStefan Hajnoczi 
2929927e0e76SStefan Hajnoczi out:
2930927e0e76SStefan Hajnoczi     aio_context_release(aio_context);
29316d4a2b3aSChristoph Hellwig }
293212bd451fSStefan Hajnoczi 
29339abf2dbaSJeff Cody static void block_job_cb(void *opaque, int ret)
293412bd451fSStefan Hajnoczi {
2935723c5d93SStefan Hajnoczi     /* Note that this function may be executed from another AioContext besides
2936723c5d93SStefan Hajnoczi      * the QEMU main loop.  If you need to access anything that assumes the
2937723c5d93SStefan Hajnoczi      * QEMU global mutex, use a BH or introduce a mutex.
2938723c5d93SStefan Hajnoczi      */
2939723c5d93SStefan Hajnoczi 
294012bd451fSStefan Hajnoczi     BlockDriverState *bs = opaque;
2941bcada37bSWenchao Xia     const char *msg = NULL;
294212bd451fSStefan Hajnoczi 
29439abf2dbaSJeff Cody     trace_block_job_cb(bs, bs->job, ret);
294412bd451fSStefan Hajnoczi 
294512bd451fSStefan Hajnoczi     assert(bs->job);
2946bcada37bSWenchao Xia 
294712bd451fSStefan Hajnoczi     if (ret < 0) {
2948bcada37bSWenchao Xia         msg = strerror(-ret);
294912bd451fSStefan Hajnoczi     }
295012bd451fSStefan Hajnoczi 
2951370521a1SStefan Hajnoczi     if (block_job_is_cancelled(bs->job)) {
2952bcada37bSWenchao Xia         block_job_event_cancelled(bs->job);
2953370521a1SStefan Hajnoczi     } else {
2954bcada37bSWenchao Xia         block_job_event_completed(bs->job, msg);
2955370521a1SStefan Hajnoczi     }
295612bd451fSStefan Hajnoczi }
295712bd451fSStefan Hajnoczi 
295813d8cc51SJeff Cody void qmp_block_stream(const char *device,
295913d8cc51SJeff Cody                       bool has_base, const char *base,
296013d8cc51SJeff Cody                       bool has_backing_file, const char *backing_file,
296113d8cc51SJeff Cody                       bool has_speed, int64_t speed,
29621d809098SPaolo Bonzini                       bool has_on_error, BlockdevOnError on_error,
29631d809098SPaolo Bonzini                       Error **errp)
296412bd451fSStefan Hajnoczi {
2965a0e8544cSFam Zheng     BlockBackend *blk;
296612bd451fSStefan Hajnoczi     BlockDriverState *bs;
2967c8c3080fSMarcelo Tosatti     BlockDriverState *base_bs = NULL;
2968f3e69bebSStefan Hajnoczi     AioContext *aio_context;
2969fd7f8c65SStefan Hajnoczi     Error *local_err = NULL;
297013d8cc51SJeff Cody     const char *base_name = NULL;
297112bd451fSStefan Hajnoczi 
29721d809098SPaolo Bonzini     if (!has_on_error) {
29731d809098SPaolo Bonzini         on_error = BLOCKDEV_ON_ERROR_REPORT;
29741d809098SPaolo Bonzini     }
29751d809098SPaolo Bonzini 
2976a0e8544cSFam Zheng     blk = blk_by_name(device);
2977a0e8544cSFam Zheng     if (!blk) {
297875158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
297975158ebbSMarkus Armbruster                   "Device '%s' not found", device);
298012bd451fSStefan Hajnoczi         return;
298112bd451fSStefan Hajnoczi     }
298212bd451fSStefan Hajnoczi 
29835433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
2984f3e69bebSStefan Hajnoczi     aio_context_acquire(aio_context);
2985f3e69bebSStefan Hajnoczi 
29865433c24fSMax Reitz     if (!blk_is_available(blk)) {
29875433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
29885433c24fSMax Reitz         goto out;
29895433c24fSMax Reitz     }
29905433c24fSMax Reitz     bs = blk_bs(blk);
29915433c24fSMax Reitz 
2992628ff683SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2993f3e69bebSStefan Hajnoczi         goto out;
2994628ff683SFam Zheng     }
2995628ff683SFam Zheng 
299613d8cc51SJeff Cody     if (has_base) {
2997c8c3080fSMarcelo Tosatti         base_bs = bdrv_find_backing_image(bs, base);
2998c8c3080fSMarcelo Tosatti         if (base_bs == NULL) {
2999c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_BASE_NOT_FOUND, base);
3000f3e69bebSStefan Hajnoczi             goto out;
300112bd451fSStefan Hajnoczi         }
3002f3e69bebSStefan Hajnoczi         assert(bdrv_get_aio_context(base_bs) == aio_context);
300313d8cc51SJeff Cody         base_name = base;
3004c8c3080fSMarcelo Tosatti     }
300512bd451fSStefan Hajnoczi 
300613d8cc51SJeff Cody     /* if we are streaming the entire chain, the result will have no backing
300713d8cc51SJeff Cody      * file, and specifying one is therefore an error */
300813d8cc51SJeff Cody     if (base_bs == NULL && has_backing_file) {
300913d8cc51SJeff Cody         error_setg(errp, "backing file specified, but streaming the "
301013d8cc51SJeff Cody                          "entire chain");
3011f3e69bebSStefan Hajnoczi         goto out;
301213d8cc51SJeff Cody     }
301313d8cc51SJeff Cody 
301413d8cc51SJeff Cody     /* backing_file string overrides base bs filename */
301513d8cc51SJeff Cody     base_name = has_backing_file ? backing_file : base_name;
301613d8cc51SJeff Cody 
301713d8cc51SJeff Cody     stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
30181d809098SPaolo Bonzini                  on_error, block_job_cb, bs, &local_err);
301984d18f06SMarkus Armbruster     if (local_err) {
3020fd7f8c65SStefan Hajnoczi         error_propagate(errp, local_err);
3021f3e69bebSStefan Hajnoczi         goto out;
302212bd451fSStefan Hajnoczi     }
302312bd451fSStefan Hajnoczi 
302412bd451fSStefan Hajnoczi     trace_qmp_block_stream(bs, bs->job);
3025f3e69bebSStefan Hajnoczi 
3026f3e69bebSStefan Hajnoczi out:
3027f3e69bebSStefan Hajnoczi     aio_context_release(aio_context);
302812bd451fSStefan Hajnoczi }
30292d47c6e9SStefan Hajnoczi 
3030ed61fc10SJeff Cody void qmp_block_commit(const char *device,
30317676e2c5SJeff Cody                       bool has_base, const char *base,
30327676e2c5SJeff Cody                       bool has_top, const char *top,
303354e26900SJeff Cody                       bool has_backing_file, const char *backing_file,
3034ed61fc10SJeff Cody                       bool has_speed, int64_t speed,
3035ed61fc10SJeff Cody                       Error **errp)
3036ed61fc10SJeff Cody {
3037a0e8544cSFam Zheng     BlockBackend *blk;
3038ed61fc10SJeff Cody     BlockDriverState *bs;
3039ed61fc10SJeff Cody     BlockDriverState *base_bs, *top_bs;
30409e85cd5cSStefan Hajnoczi     AioContext *aio_context;
3041ed61fc10SJeff Cody     Error *local_err = NULL;
3042ed61fc10SJeff Cody     /* This will be part of the QMP command, if/when the
3043ed61fc10SJeff Cody      * BlockdevOnError change for blkmirror makes it in
3044ed61fc10SJeff Cody      */
304592aa5c6dSPaolo Bonzini     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3046ed61fc10SJeff Cody 
304754504663SMax Reitz     if (!has_speed) {
304854504663SMax Reitz         speed = 0;
304954504663SMax Reitz     }
305054504663SMax Reitz 
30517676e2c5SJeff Cody     /* Important Note:
30527676e2c5SJeff Cody      *  libvirt relies on the DeviceNotFound error class in order to probe for
30537676e2c5SJeff Cody      *  live commit feature versions; for this to work, we must make sure to
30547676e2c5SJeff Cody      *  perform the device lookup before any generic errors that may occur in a
30557676e2c5SJeff Cody      *  scenario in which all optional arguments are omitted. */
3056a0e8544cSFam Zheng     blk = blk_by_name(device);
3057a0e8544cSFam Zheng     if (!blk) {
305875158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
305975158ebbSMarkus Armbruster                   "Device '%s' not found", device);
3060ed61fc10SJeff Cody         return;
3061ed61fc10SJeff Cody     }
3062ed61fc10SJeff Cody 
30635433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
30649e85cd5cSStefan Hajnoczi     aio_context_acquire(aio_context);
30659e85cd5cSStefan Hajnoczi 
30665433c24fSMax Reitz     if (!blk_is_available(blk)) {
30675433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
30685433c24fSMax Reitz         goto out;
30695433c24fSMax Reitz     }
30705433c24fSMax Reitz     bs = blk_bs(blk);
30715433c24fSMax Reitz 
3072bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
30739e85cd5cSStefan Hajnoczi         goto out;
3074628ff683SFam Zheng     }
3075628ff683SFam Zheng 
3076ed61fc10SJeff Cody     /* default top_bs is the active layer */
3077ed61fc10SJeff Cody     top_bs = bs;
3078ed61fc10SJeff Cody 
30797676e2c5SJeff Cody     if (has_top && top) {
3080ed61fc10SJeff Cody         if (strcmp(bs->filename, top) != 0) {
3081ed61fc10SJeff Cody             top_bs = bdrv_find_backing_image(bs, top);
3082ed61fc10SJeff Cody         }
3083ed61fc10SJeff Cody     }
3084ed61fc10SJeff Cody 
3085ed61fc10SJeff Cody     if (top_bs == NULL) {
3086ed61fc10SJeff Cody         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
30879e85cd5cSStefan Hajnoczi         goto out;
3088ed61fc10SJeff Cody     }
3089ed61fc10SJeff Cody 
30909e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(top_bs) == aio_context);
30919e85cd5cSStefan Hajnoczi 
3092d5208c45SJeff Cody     if (has_base && base) {
3093d5208c45SJeff Cody         base_bs = bdrv_find_backing_image(top_bs, base);
3094d5208c45SJeff Cody     } else {
3095d5208c45SJeff Cody         base_bs = bdrv_find_base(top_bs);
3096d5208c45SJeff Cody     }
3097d5208c45SJeff Cody 
3098d5208c45SJeff Cody     if (base_bs == NULL) {
3099c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
31009e85cd5cSStefan Hajnoczi         goto out;
3101d5208c45SJeff Cody     }
3102d5208c45SJeff Cody 
31039e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(base_bs) == aio_context);
31049e85cd5cSStefan Hajnoczi 
3105bb00021dSFam Zheng     if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3106bb00021dSFam Zheng         goto out;
3107bb00021dSFam Zheng     }
3108bb00021dSFam Zheng 
31097676e2c5SJeff Cody     /* Do not allow attempts to commit an image into itself */
31107676e2c5SJeff Cody     if (top_bs == base_bs) {
31117676e2c5SJeff Cody         error_setg(errp, "cannot commit an image into itself");
31129e85cd5cSStefan Hajnoczi         goto out;
31137676e2c5SJeff Cody     }
31147676e2c5SJeff Cody 
311520a63d2cSFam Zheng     if (top_bs == bs) {
311654e26900SJeff Cody         if (has_backing_file) {
311754e26900SJeff Cody             error_setg(errp, "'backing-file' specified,"
311854e26900SJeff Cody                              " but 'top' is the active layer");
31199e85cd5cSStefan Hajnoczi             goto out;
312054e26900SJeff Cody         }
312120a63d2cSFam Zheng         commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
312220a63d2cSFam Zheng                             bs, &local_err);
312320a63d2cSFam Zheng     } else {
3124ed61fc10SJeff Cody         commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
312554e26900SJeff Cody                      has_backing_file ? backing_file : NULL, &local_err);
312620a63d2cSFam Zheng     }
3127ed61fc10SJeff Cody     if (local_err != NULL) {
3128ed61fc10SJeff Cody         error_propagate(errp, local_err);
31299e85cd5cSStefan Hajnoczi         goto out;
3130ed61fc10SJeff Cody     }
31319e85cd5cSStefan Hajnoczi 
31329e85cd5cSStefan Hajnoczi out:
31339e85cd5cSStefan Hajnoczi     aio_context_release(aio_context);
3134ed61fc10SJeff Cody }
3135ed61fc10SJeff Cody 
313678f51fdeSJohn Snow static void do_drive_backup(const char *device, const char *target,
313799a9addfSStefan Hajnoczi                             bool has_format, const char *format,
3138b53169eaSStefan Hajnoczi                             enum MirrorSyncMode sync,
313999a9addfSStefan Hajnoczi                             bool has_mode, enum NewImageMode mode,
314099a9addfSStefan Hajnoczi                             bool has_speed, int64_t speed,
3141d58d8453SJohn Snow                             bool has_bitmap, const char *bitmap,
314278f51fdeSJohn Snow                             bool has_on_source_error,
314378f51fdeSJohn Snow                             BlockdevOnError on_source_error,
314478f51fdeSJohn Snow                             bool has_on_target_error,
314578f51fdeSJohn Snow                             BlockdevOnError on_target_error,
314678f51fdeSJohn Snow                             BlockJobTxn *txn, Error **errp)
314799a9addfSStefan Hajnoczi {
3148a0e8544cSFam Zheng     BlockBackend *blk;
314999a9addfSStefan Hajnoczi     BlockDriverState *bs;
315099a9addfSStefan Hajnoczi     BlockDriverState *target_bs;
3151fc5d3f84SIan Main     BlockDriverState *source = NULL;
3152d58d8453SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
3153761731b1SStefan Hajnoczi     AioContext *aio_context;
3154e6641719SMax Reitz     QDict *options = NULL;
315599a9addfSStefan Hajnoczi     Error *local_err = NULL;
315699a9addfSStefan Hajnoczi     int flags;
315799a9addfSStefan Hajnoczi     int64_t size;
315899a9addfSStefan Hajnoczi     int ret;
315999a9addfSStefan Hajnoczi 
316099a9addfSStefan Hajnoczi     if (!has_speed) {
316199a9addfSStefan Hajnoczi         speed = 0;
316299a9addfSStefan Hajnoczi     }
316399a9addfSStefan Hajnoczi     if (!has_on_source_error) {
316499a9addfSStefan Hajnoczi         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
316599a9addfSStefan Hajnoczi     }
316699a9addfSStefan Hajnoczi     if (!has_on_target_error) {
316799a9addfSStefan Hajnoczi         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
316899a9addfSStefan Hajnoczi     }
316999a9addfSStefan Hajnoczi     if (!has_mode) {
317099a9addfSStefan Hajnoczi         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
317199a9addfSStefan Hajnoczi     }
317299a9addfSStefan Hajnoczi 
3173a0e8544cSFam Zheng     blk = blk_by_name(device);
3174a0e8544cSFam Zheng     if (!blk) {
317575158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
317675158ebbSMarkus Armbruster                   "Device '%s' not found", device);
317799a9addfSStefan Hajnoczi         return;
317899a9addfSStefan Hajnoczi     }
317999a9addfSStefan Hajnoczi 
31805433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3181761731b1SStefan Hajnoczi     aio_context_acquire(aio_context);
3182761731b1SStefan Hajnoczi 
3183c29c1dd3SFam Zheng     /* Although backup_run has this check too, we need to use bs->drv below, so
3184c29c1dd3SFam Zheng      * do an early check redundantly. */
31855433c24fSMax Reitz     if (!blk_is_available(blk)) {
3186c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3187761731b1SStefan Hajnoczi         goto out;
318899a9addfSStefan Hajnoczi     }
31895433c24fSMax Reitz     bs = blk_bs(blk);
319099a9addfSStefan Hajnoczi 
319199a9addfSStefan Hajnoczi     if (!has_format) {
319299a9addfSStefan Hajnoczi         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
319399a9addfSStefan Hajnoczi     }
319499a9addfSStefan Hajnoczi 
3195c29c1dd3SFam Zheng     /* Early check to avoid creating target */
31963718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3197761731b1SStefan Hajnoczi         goto out;
319899a9addfSStefan Hajnoczi     }
319999a9addfSStefan Hajnoczi 
320099a9addfSStefan Hajnoczi     flags = bs->open_flags | BDRV_O_RDWR;
320199a9addfSStefan Hajnoczi 
3202fc5d3f84SIan Main     /* See if we have a backing HD we can use to create our new image
3203fc5d3f84SIan Main      * on top of. */
3204fc5d3f84SIan Main     if (sync == MIRROR_SYNC_MODE_TOP) {
3205760e0063SKevin Wolf         source = backing_bs(bs);
3206fc5d3f84SIan Main         if (!source) {
3207fc5d3f84SIan Main             sync = MIRROR_SYNC_MODE_FULL;
3208fc5d3f84SIan Main         }
3209fc5d3f84SIan Main     }
3210fc5d3f84SIan Main     if (sync == MIRROR_SYNC_MODE_NONE) {
3211fc5d3f84SIan Main         source = bs;
3212fc5d3f84SIan Main     }
3213fc5d3f84SIan Main 
321499a9addfSStefan Hajnoczi     size = bdrv_getlength(bs);
321599a9addfSStefan Hajnoczi     if (size < 0) {
321699a9addfSStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
3217761731b1SStefan Hajnoczi         goto out;
321899a9addfSStefan Hajnoczi     }
321999a9addfSStefan Hajnoczi 
322099a9addfSStefan Hajnoczi     if (mode != NEW_IMAGE_MODE_EXISTING) {
3221e6641719SMax Reitz         assert(format);
3222fc5d3f84SIan Main         if (source) {
3223fc5d3f84SIan Main             bdrv_img_create(target, format, source->filename,
3224fc5d3f84SIan Main                             source->drv->format_name, NULL,
3225fc5d3f84SIan Main                             size, flags, &local_err, false);
3226fc5d3f84SIan Main         } else {
3227fc5d3f84SIan Main             bdrv_img_create(target, format, NULL, NULL, NULL,
3228fc5d3f84SIan Main                             size, flags, &local_err, false);
3229fc5d3f84SIan Main         }
323099a9addfSStefan Hajnoczi     }
323199a9addfSStefan Hajnoczi 
323284d18f06SMarkus Armbruster     if (local_err) {
323399a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3234761731b1SStefan Hajnoczi         goto out;
323599a9addfSStefan Hajnoczi     }
323699a9addfSStefan Hajnoczi 
3237e6641719SMax Reitz     if (format) {
3238e6641719SMax Reitz         options = qdict_new();
3239e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
3240e6641719SMax Reitz     }
3241e6641719SMax Reitz 
3242f67503e5SMax Reitz     target_bs = NULL;
32436ebf9aa2SMax Reitz     ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
324499a9addfSStefan Hajnoczi     if (ret < 0) {
324534b5d2c6SMax Reitz         error_propagate(errp, local_err);
3246761731b1SStefan Hajnoczi         goto out;
324799a9addfSStefan Hajnoczi     }
324899a9addfSStefan Hajnoczi 
3249761731b1SStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
3250761731b1SStefan Hajnoczi 
3251d58d8453SJohn Snow     if (has_bitmap) {
3252d58d8453SJohn Snow         bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3253d58d8453SJohn Snow         if (!bmap) {
3254d58d8453SJohn Snow             error_setg(errp, "Bitmap '%s' could not be found", bitmap);
32550702d3d8SMax Reitz             bdrv_unref(target_bs);
3256d58d8453SJohn Snow             goto out;
3257d58d8453SJohn Snow         }
3258d58d8453SJohn Snow     }
3259d58d8453SJohn Snow 
3260d58d8453SJohn Snow     backup_start(bs, target_bs, speed, sync, bmap,
3261d58d8453SJohn Snow                  on_source_error, on_target_error,
326278f51fdeSJohn Snow                  block_job_cb, bs, txn, &local_err);
326399a9addfSStefan Hajnoczi     if (local_err != NULL) {
32644f6fd349SFam Zheng         bdrv_unref(target_bs);
326599a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3266761731b1SStefan Hajnoczi         goto out;
326799a9addfSStefan Hajnoczi     }
3268761731b1SStefan Hajnoczi 
3269761731b1SStefan Hajnoczi out:
3270761731b1SStefan Hajnoczi     aio_context_release(aio_context);
327199a9addfSStefan Hajnoczi }
327299a9addfSStefan Hajnoczi 
327378f51fdeSJohn Snow void qmp_drive_backup(const char *device, const char *target,
327478f51fdeSJohn Snow                       bool has_format, const char *format,
327578f51fdeSJohn Snow                       enum MirrorSyncMode sync,
327678f51fdeSJohn Snow                       bool has_mode, enum NewImageMode mode,
327778f51fdeSJohn Snow                       bool has_speed, int64_t speed,
327878f51fdeSJohn Snow                       bool has_bitmap, const char *bitmap,
327978f51fdeSJohn Snow                       bool has_on_source_error, BlockdevOnError on_source_error,
328078f51fdeSJohn Snow                       bool has_on_target_error, BlockdevOnError on_target_error,
328178f51fdeSJohn Snow                       Error **errp)
328278f51fdeSJohn Snow {
328378f51fdeSJohn Snow     return do_drive_backup(device, target, has_format, format, sync,
328478f51fdeSJohn Snow                            has_mode, mode, has_speed, speed,
328578f51fdeSJohn Snow                            has_bitmap, bitmap,
328678f51fdeSJohn Snow                            has_on_source_error, on_source_error,
328778f51fdeSJohn Snow                            has_on_target_error, on_target_error,
328878f51fdeSJohn Snow                            NULL, errp);
328978f51fdeSJohn Snow }
329078f51fdeSJohn Snow 
3291c13163fbSBenoît Canet BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3292c13163fbSBenoît Canet {
3293d5a8ee60SAlberto Garcia     return bdrv_named_nodes_list(errp);
3294c13163fbSBenoît Canet }
3295c13163fbSBenoît Canet 
329678f51fdeSJohn Snow void do_blockdev_backup(const char *device, const char *target,
3297c29c1dd3SFam Zheng                          enum MirrorSyncMode sync,
3298c29c1dd3SFam Zheng                          bool has_speed, int64_t speed,
3299c29c1dd3SFam Zheng                          bool has_on_source_error,
3300c29c1dd3SFam Zheng                          BlockdevOnError on_source_error,
3301c29c1dd3SFam Zheng                          bool has_on_target_error,
3302c29c1dd3SFam Zheng                          BlockdevOnError on_target_error,
330378f51fdeSJohn Snow                          BlockJobTxn *txn, Error **errp)
3304c29c1dd3SFam Zheng {
33055433c24fSMax Reitz     BlockBackend *blk, *target_blk;
3306c29c1dd3SFam Zheng     BlockDriverState *bs;
3307c29c1dd3SFam Zheng     BlockDriverState *target_bs;
3308c29c1dd3SFam Zheng     Error *local_err = NULL;
3309c29c1dd3SFam Zheng     AioContext *aio_context;
3310c29c1dd3SFam Zheng 
3311c29c1dd3SFam Zheng     if (!has_speed) {
3312c29c1dd3SFam Zheng         speed = 0;
3313c29c1dd3SFam Zheng     }
3314c29c1dd3SFam Zheng     if (!has_on_source_error) {
3315c29c1dd3SFam Zheng         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3316c29c1dd3SFam Zheng     }
3317c29c1dd3SFam Zheng     if (!has_on_target_error) {
3318c29c1dd3SFam Zheng         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3319c29c1dd3SFam Zheng     }
3320c29c1dd3SFam Zheng 
3321a0e8544cSFam Zheng     blk = blk_by_name(device);
3322a0e8544cSFam Zheng     if (!blk) {
33235b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", device);
3324c29c1dd3SFam Zheng         return;
3325c29c1dd3SFam Zheng     }
3326c29c1dd3SFam Zheng 
33275433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3328c29c1dd3SFam Zheng     aio_context_acquire(aio_context);
3329c29c1dd3SFam Zheng 
33305433c24fSMax Reitz     if (!blk_is_available(blk)) {
33315433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
33325433c24fSMax Reitz         goto out;
33335433c24fSMax Reitz     }
33345433c24fSMax Reitz     bs = blk_bs(blk);
33355433c24fSMax Reitz 
33365433c24fSMax Reitz     target_blk = blk_by_name(target);
33375433c24fSMax Reitz     if (!target_blk) {
33385b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", target);
3339c29c1dd3SFam Zheng         goto out;
3340c29c1dd3SFam Zheng     }
33415433c24fSMax Reitz 
33425433c24fSMax Reitz     if (!blk_is_available(target_blk)) {
33435433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", target);
33445433c24fSMax Reitz         goto out;
33455433c24fSMax Reitz     }
33465433c24fSMax Reitz     target_bs = blk_bs(target_blk);
3347c29c1dd3SFam Zheng 
3348c29c1dd3SFam Zheng     bdrv_ref(target_bs);
3349c29c1dd3SFam Zheng     bdrv_set_aio_context(target_bs, aio_context);
3350d58d8453SJohn Snow     backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
335178f51fdeSJohn Snow                  on_target_error, block_job_cb, bs, txn, &local_err);
3352c29c1dd3SFam Zheng     if (local_err != NULL) {
3353c29c1dd3SFam Zheng         bdrv_unref(target_bs);
3354c29c1dd3SFam Zheng         error_propagate(errp, local_err);
3355c29c1dd3SFam Zheng     }
3356c29c1dd3SFam Zheng out:
3357c29c1dd3SFam Zheng     aio_context_release(aio_context);
3358c29c1dd3SFam Zheng }
3359c29c1dd3SFam Zheng 
336078f51fdeSJohn Snow void qmp_blockdev_backup(const char *device, const char *target,
336178f51fdeSJohn Snow                          enum MirrorSyncMode sync,
336278f51fdeSJohn Snow                          bool has_speed, int64_t speed,
336378f51fdeSJohn Snow                          bool has_on_source_error,
336478f51fdeSJohn Snow                          BlockdevOnError on_source_error,
336578f51fdeSJohn Snow                          bool has_on_target_error,
336678f51fdeSJohn Snow                          BlockdevOnError on_target_error,
336778f51fdeSJohn Snow                          Error **errp)
336878f51fdeSJohn Snow {
336978f51fdeSJohn Snow     do_blockdev_backup(device, target, sync, has_speed, speed,
337078f51fdeSJohn Snow                        has_on_source_error, on_source_error,
337178f51fdeSJohn Snow                        has_on_target_error, on_target_error,
337278f51fdeSJohn Snow                        NULL, errp);
337378f51fdeSJohn Snow }
337478f51fdeSJohn Snow 
33754193cdd7SFam Zheng /* Parameter check and block job starting for drive mirroring.
33764193cdd7SFam Zheng  * Caller should hold @device and @target's aio context (must be the same).
33774193cdd7SFam Zheng  **/
33784193cdd7SFam Zheng static void blockdev_mirror_common(BlockDriverState *bs,
33794193cdd7SFam Zheng                                    BlockDriverState *target,
338009158f00SBenoît Canet                                    bool has_replaces, const char *replaces,
3381d9b902dbSPaolo Bonzini                                    enum MirrorSyncMode sync,
3382b952b558SPaolo Bonzini                                    bool has_speed, int64_t speed,
3383eee13dfeSPaolo Bonzini                                    bool has_granularity, uint32_t granularity,
338408e4ed6cSPaolo Bonzini                                    bool has_buf_size, int64_t buf_size,
33854193cdd7SFam Zheng                                    bool has_on_source_error,
33864193cdd7SFam Zheng                                    BlockdevOnError on_source_error,
33874193cdd7SFam Zheng                                    bool has_on_target_error,
33884193cdd7SFam Zheng                                    BlockdevOnError on_target_error,
33890fc9f8eaSFam Zheng                                    bool has_unmap, bool unmap,
3390b952b558SPaolo Bonzini                                    Error **errp)
3391d9b902dbSPaolo Bonzini {
3392d9b902dbSPaolo Bonzini 
3393d9b902dbSPaolo Bonzini     if (!has_speed) {
3394d9b902dbSPaolo Bonzini         speed = 0;
3395d9b902dbSPaolo Bonzini     }
3396b952b558SPaolo Bonzini     if (!has_on_source_error) {
3397b952b558SPaolo Bonzini         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3398b952b558SPaolo Bonzini     }
3399b952b558SPaolo Bonzini     if (!has_on_target_error) {
3400b952b558SPaolo Bonzini         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3401b952b558SPaolo Bonzini     }
3402eee13dfeSPaolo Bonzini     if (!has_granularity) {
3403eee13dfeSPaolo Bonzini         granularity = 0;
3404eee13dfeSPaolo Bonzini     }
340508e4ed6cSPaolo Bonzini     if (!has_buf_size) {
340648ac0a4dSWen Congyang         buf_size = 0;
340708e4ed6cSPaolo Bonzini     }
34080fc9f8eaSFam Zheng     if (!has_unmap) {
34090fc9f8eaSFam Zheng         unmap = true;
34100fc9f8eaSFam Zheng     }
341108e4ed6cSPaolo Bonzini 
3412eee13dfeSPaolo Bonzini     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3413c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
34143cbbe9fdSStefan Hajnoczi                    "a value in range [512B, 64MB]");
3415eee13dfeSPaolo Bonzini         return;
3416eee13dfeSPaolo Bonzini     }
3417eee13dfeSPaolo Bonzini     if (granularity & (granularity - 1)) {
3418c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3419c6bd8c70SMarkus Armbruster                    "power of 2");
3420eee13dfeSPaolo Bonzini         return;
3421eee13dfeSPaolo Bonzini     }
3422d9b902dbSPaolo Bonzini 
34234193cdd7SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
34244193cdd7SFam Zheng         return;
34254193cdd7SFam Zheng     }
3426e40e5027SFam Zheng     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3427e40e5027SFam Zheng         return;
3428e40e5027SFam Zheng     }
3429df92562eSFam Zheng     if (target->blk) {
3430df92562eSFam Zheng         error_setg(errp, "Cannot mirror to an attached block device");
3431df92562eSFam Zheng         return;
3432df92562eSFam Zheng     }
34334193cdd7SFam Zheng 
34344193cdd7SFam Zheng     if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
34354193cdd7SFam Zheng         sync = MIRROR_SYNC_MODE_FULL;
34364193cdd7SFam Zheng     }
34374193cdd7SFam Zheng 
34384193cdd7SFam Zheng     /* pass the node name to replace to mirror start since it's loose coupling
34394193cdd7SFam Zheng      * and will allow to check whether the node still exist at mirror completion
34404193cdd7SFam Zheng      */
34414193cdd7SFam Zheng     mirror_start(bs, target,
34424193cdd7SFam Zheng                  has_replaces ? replaces : NULL,
34434193cdd7SFam Zheng                  speed, granularity, buf_size, sync,
34444193cdd7SFam Zheng                  on_source_error, on_target_error, unmap,
34454193cdd7SFam Zheng                  block_job_cb, bs, errp);
34464193cdd7SFam Zheng }
34474193cdd7SFam Zheng 
34484193cdd7SFam Zheng void qmp_drive_mirror(const char *device, const char *target,
34494193cdd7SFam Zheng                       bool has_format, const char *format,
34504193cdd7SFam Zheng                       bool has_node_name, const char *node_name,
34514193cdd7SFam Zheng                       bool has_replaces, const char *replaces,
34524193cdd7SFam Zheng                       enum MirrorSyncMode sync,
34534193cdd7SFam Zheng                       bool has_mode, enum NewImageMode mode,
34544193cdd7SFam Zheng                       bool has_speed, int64_t speed,
34554193cdd7SFam Zheng                       bool has_granularity, uint32_t granularity,
34564193cdd7SFam Zheng                       bool has_buf_size, int64_t buf_size,
34574193cdd7SFam Zheng                       bool has_on_source_error, BlockdevOnError on_source_error,
34584193cdd7SFam Zheng                       bool has_on_target_error, BlockdevOnError on_target_error,
34594193cdd7SFam Zheng                       bool has_unmap, bool unmap,
34604193cdd7SFam Zheng                       Error **errp)
34614193cdd7SFam Zheng {
34624193cdd7SFam Zheng     BlockDriverState *bs;
34634193cdd7SFam Zheng     BlockBackend *blk;
34644193cdd7SFam Zheng     BlockDriverState *source, *target_bs;
34654193cdd7SFam Zheng     AioContext *aio_context;
34664193cdd7SFam Zheng     Error *local_err = NULL;
34674193cdd7SFam Zheng     QDict *options = NULL;
34684193cdd7SFam Zheng     int flags;
34694193cdd7SFam Zheng     int64_t size;
34704193cdd7SFam Zheng     int ret;
34714193cdd7SFam Zheng 
3472a0e8544cSFam Zheng     blk = blk_by_name(device);
3473a0e8544cSFam Zheng     if (!blk) {
347475158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
347575158ebbSMarkus Armbruster                   "Device '%s' not found", device);
3476d9b902dbSPaolo Bonzini         return;
3477d9b902dbSPaolo Bonzini     }
3478d9b902dbSPaolo Bonzini 
34795433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
34805a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
34815a7e7a0bSStefan Hajnoczi 
34825433c24fSMax Reitz     if (!blk_is_available(blk)) {
3483c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
34845a7e7a0bSStefan Hajnoczi         goto out;
3485d9b902dbSPaolo Bonzini     }
34865433c24fSMax Reitz     bs = blk_bs(blk);
34874193cdd7SFam Zheng     if (!has_mode) {
34884193cdd7SFam Zheng         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
34894193cdd7SFam Zheng     }
3490d9b902dbSPaolo Bonzini 
3491d9b902dbSPaolo Bonzini     if (!has_format) {
3492d9b902dbSPaolo Bonzini         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3493d9b902dbSPaolo Bonzini     }
3494d9b902dbSPaolo Bonzini 
3495d9b902dbSPaolo Bonzini     flags = bs->open_flags | BDRV_O_RDWR;
3496760e0063SKevin Wolf     source = backing_bs(bs);
3497d9b902dbSPaolo Bonzini     if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3498d9b902dbSPaolo Bonzini         sync = MIRROR_SYNC_MODE_FULL;
3499d9b902dbSPaolo Bonzini     }
3500117e0c82SMax Reitz     if (sync == MIRROR_SYNC_MODE_NONE) {
3501117e0c82SMax Reitz         source = bs;
3502117e0c82SMax Reitz     }
3503d9b902dbSPaolo Bonzini 
3504ac3c5d83SStefan Hajnoczi     size = bdrv_getlength(bs);
3505ac3c5d83SStefan Hajnoczi     if (size < 0) {
3506ac3c5d83SStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
35075a7e7a0bSStefan Hajnoczi         goto out;
3508ac3c5d83SStefan Hajnoczi     }
3509ac3c5d83SStefan Hajnoczi 
351009158f00SBenoît Canet     if (has_replaces) {
351109158f00SBenoît Canet         BlockDriverState *to_replace_bs;
35125a7e7a0bSStefan Hajnoczi         AioContext *replace_aio_context;
35135a7e7a0bSStefan Hajnoczi         int64_t replace_size;
351409158f00SBenoît Canet 
351509158f00SBenoît Canet         if (!has_node_name) {
351609158f00SBenoît Canet             error_setg(errp, "a node-name must be provided when replacing a"
351709158f00SBenoît Canet                              " named node of the graph");
35185a7e7a0bSStefan Hajnoczi             goto out;
351909158f00SBenoît Canet         }
352009158f00SBenoît Canet 
3521e12f3784SWen Congyang         to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
352209158f00SBenoît Canet 
352309158f00SBenoît Canet         if (!to_replace_bs) {
352409158f00SBenoît Canet             error_propagate(errp, local_err);
35255a7e7a0bSStefan Hajnoczi             goto out;
352609158f00SBenoît Canet         }
352709158f00SBenoît Canet 
35285a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
35295a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
35305a7e7a0bSStefan Hajnoczi         replace_size = bdrv_getlength(to_replace_bs);
35315a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
35325a7e7a0bSStefan Hajnoczi 
35335a7e7a0bSStefan Hajnoczi         if (size != replace_size) {
353409158f00SBenoît Canet             error_setg(errp, "cannot replace image with a mirror image of "
353509158f00SBenoît Canet                              "different size");
35365a7e7a0bSStefan Hajnoczi             goto out;
353709158f00SBenoît Canet         }
353809158f00SBenoît Canet     }
353909158f00SBenoît Canet 
354014526864SMax Reitz     if ((sync == MIRROR_SYNC_MODE_FULL || !source)
354114526864SMax Reitz         && mode != NEW_IMAGE_MODE_EXISTING)
354214526864SMax Reitz     {
3543d9b902dbSPaolo Bonzini         /* create new image w/o backing file */
3544e6641719SMax Reitz         assert(format);
3545cf8f2426SLuiz Capitulino         bdrv_img_create(target, format,
3546f382d43aSMiroslav Rezanina                         NULL, NULL, NULL, size, flags, &local_err, false);
3547d9b902dbSPaolo Bonzini     } else {
3548d9b902dbSPaolo Bonzini         switch (mode) {
3549d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_EXISTING:
3550d9b902dbSPaolo Bonzini             break;
3551d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3552d9b902dbSPaolo Bonzini             /* create new image with backing file */
3553cf8f2426SLuiz Capitulino             bdrv_img_create(target, format,
3554d9b902dbSPaolo Bonzini                             source->filename,
3555d9b902dbSPaolo Bonzini                             source->drv->format_name,
3556f382d43aSMiroslav Rezanina                             NULL, size, flags, &local_err, false);
3557d9b902dbSPaolo Bonzini             break;
3558d9b902dbSPaolo Bonzini         default:
3559d9b902dbSPaolo Bonzini             abort();
3560d9b902dbSPaolo Bonzini         }
3561d9b902dbSPaolo Bonzini     }
3562d9b902dbSPaolo Bonzini 
356384d18f06SMarkus Armbruster     if (local_err) {
3564cf8f2426SLuiz Capitulino         error_propagate(errp, local_err);
35655a7e7a0bSStefan Hajnoczi         goto out;
3566d9b902dbSPaolo Bonzini     }
3567d9b902dbSPaolo Bonzini 
35684c828dc6SBenoît Canet     options = qdict_new();
3569e6641719SMax Reitz     if (has_node_name) {
35704c828dc6SBenoît Canet         qdict_put(options, "node-name", qstring_from_str(node_name));
35714c828dc6SBenoît Canet     }
3572e6641719SMax Reitz     if (format) {
3573e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
3574e6641719SMax Reitz     }
35754c828dc6SBenoît Canet 
3576b812f671SPaolo Bonzini     /* Mirroring takes care of copy-on-write using the source's backing
3577b812f671SPaolo Bonzini      * file.
3578b812f671SPaolo Bonzini      */
3579f67503e5SMax Reitz     target_bs = NULL;
35804c828dc6SBenoît Canet     ret = bdrv_open(&target_bs, target, NULL, options,
35816ebf9aa2SMax Reitz                     flags | BDRV_O_NO_BACKING, &local_err);
3582d9b902dbSPaolo Bonzini     if (ret < 0) {
358334b5d2c6SMax Reitz         error_propagate(errp, local_err);
35845a7e7a0bSStefan Hajnoczi         goto out;
3585d9b902dbSPaolo Bonzini     }
3586d9b902dbSPaolo Bonzini 
35875a7e7a0bSStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
35885a7e7a0bSStefan Hajnoczi 
35894193cdd7SFam Zheng     blockdev_mirror_common(bs, target_bs,
35904193cdd7SFam Zheng                            has_replaces, replaces, sync,
35914193cdd7SFam Zheng                            has_speed, speed,
35924193cdd7SFam Zheng                            has_granularity, granularity,
35934193cdd7SFam Zheng                            has_buf_size, buf_size,
35944193cdd7SFam Zheng                            has_on_source_error, on_source_error,
35954193cdd7SFam Zheng                            has_on_target_error, on_target_error,
35964193cdd7SFam Zheng                            has_unmap, unmap,
35974193cdd7SFam Zheng                            &local_err);
35984193cdd7SFam Zheng     if (local_err) {
3599d9b902dbSPaolo Bonzini         error_propagate(errp, local_err);
36004193cdd7SFam Zheng         bdrv_unref(target_bs);
3601d9b902dbSPaolo Bonzini     }
36025a7e7a0bSStefan Hajnoczi out:
36035a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
3604d9b902dbSPaolo Bonzini }
3605d9b902dbSPaolo Bonzini 
3606df92562eSFam Zheng void qmp_blockdev_mirror(const char *device, const char *target,
3607df92562eSFam Zheng                          bool has_replaces, const char *replaces,
3608df92562eSFam Zheng                          MirrorSyncMode sync,
3609df92562eSFam Zheng                          bool has_speed, int64_t speed,
3610df92562eSFam Zheng                          bool has_granularity, uint32_t granularity,
3611df92562eSFam Zheng                          bool has_buf_size, int64_t buf_size,
3612df92562eSFam Zheng                          bool has_on_source_error,
3613df92562eSFam Zheng                          BlockdevOnError on_source_error,
3614df92562eSFam Zheng                          bool has_on_target_error,
3615df92562eSFam Zheng                          BlockdevOnError on_target_error,
3616df92562eSFam Zheng                          Error **errp)
3617df92562eSFam Zheng {
3618df92562eSFam Zheng     BlockDriverState *bs;
3619df92562eSFam Zheng     BlockBackend *blk;
3620df92562eSFam Zheng     BlockDriverState *target_bs;
3621df92562eSFam Zheng     AioContext *aio_context;
3622df92562eSFam Zheng     Error *local_err = NULL;
3623df92562eSFam Zheng 
3624df92562eSFam Zheng     blk = blk_by_name(device);
3625df92562eSFam Zheng     if (!blk) {
3626df92562eSFam Zheng         error_setg(errp, "Device '%s' not found", device);
3627df92562eSFam Zheng         return;
3628df92562eSFam Zheng     }
3629df92562eSFam Zheng     bs = blk_bs(blk);
3630df92562eSFam Zheng 
3631df92562eSFam Zheng     if (!bs) {
3632df92562eSFam Zheng         error_setg(errp, "Device '%s' has no media", device);
3633df92562eSFam Zheng         return;
3634df92562eSFam Zheng     }
3635df92562eSFam Zheng 
3636df92562eSFam Zheng     target_bs = bdrv_lookup_bs(target, target, errp);
3637df92562eSFam Zheng     if (!target_bs) {
3638df92562eSFam Zheng         return;
3639df92562eSFam Zheng     }
3640df92562eSFam Zheng 
3641df92562eSFam Zheng     aio_context = bdrv_get_aio_context(bs);
3642df92562eSFam Zheng     aio_context_acquire(aio_context);
3643df92562eSFam Zheng 
3644df92562eSFam Zheng     bdrv_ref(target_bs);
3645df92562eSFam Zheng     bdrv_set_aio_context(target_bs, aio_context);
3646df92562eSFam Zheng 
3647df92562eSFam Zheng     blockdev_mirror_common(bs, target_bs,
3648df92562eSFam Zheng                            has_replaces, replaces, sync,
3649df92562eSFam Zheng                            has_speed, speed,
3650df92562eSFam Zheng                            has_granularity, granularity,
3651df92562eSFam Zheng                            has_buf_size, buf_size,
3652df92562eSFam Zheng                            has_on_source_error, on_source_error,
3653df92562eSFam Zheng                            has_on_target_error, on_target_error,
3654df92562eSFam Zheng                            true, true,
3655df92562eSFam Zheng                            &local_err);
3656df92562eSFam Zheng     if (local_err) {
3657df92562eSFam Zheng         error_propagate(errp, local_err);
3658df92562eSFam Zheng         bdrv_unref(target_bs);
3659df92562eSFam Zheng     }
3660df92562eSFam Zheng 
3661df92562eSFam Zheng     aio_context_release(aio_context);
3662df92562eSFam Zheng }
3663df92562eSFam Zheng 
36643d948cdfSStefan Hajnoczi /* Get the block job for a given device name and acquire its AioContext */
366524d6bffeSMarkus Armbruster static BlockJob *find_block_job(const char *device, AioContext **aio_context,
366624d6bffeSMarkus Armbruster                                 Error **errp)
36672d47c6e9SStefan Hajnoczi {
3668a0e8544cSFam Zheng     BlockBackend *blk;
36692d47c6e9SStefan Hajnoczi     BlockDriverState *bs;
36702d47c6e9SStefan Hajnoczi 
36715433c24fSMax Reitz     *aio_context = NULL;
36725433c24fSMax Reitz 
3673a0e8544cSFam Zheng     blk = blk_by_name(device);
3674a0e8544cSFam Zheng     if (!blk) {
36753d948cdfSStefan Hajnoczi         goto notfound;
36762d47c6e9SStefan Hajnoczi     }
36773d948cdfSStefan Hajnoczi 
36785433c24fSMax Reitz     *aio_context = blk_get_aio_context(blk);
36793d948cdfSStefan Hajnoczi     aio_context_acquire(*aio_context);
36803d948cdfSStefan Hajnoczi 
36815433c24fSMax Reitz     if (!blk_is_available(blk)) {
36825433c24fSMax Reitz         goto notfound;
36835433c24fSMax Reitz     }
36845433c24fSMax Reitz     bs = blk_bs(blk);
36855433c24fSMax Reitz 
36863d948cdfSStefan Hajnoczi     if (!bs->job) {
36873d948cdfSStefan Hajnoczi         goto notfound;
36883d948cdfSStefan Hajnoczi     }
36893d948cdfSStefan Hajnoczi 
36902d47c6e9SStefan Hajnoczi     return bs->job;
36913d948cdfSStefan Hajnoczi 
36923d948cdfSStefan Hajnoczi notfound:
36932e3a0266SMarkus Armbruster     error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
36942e3a0266SMarkus Armbruster               "No active block job on device '%s'", device);
36955433c24fSMax Reitz     if (*aio_context) {
36965433c24fSMax Reitz         aio_context_release(*aio_context);
36973d948cdfSStefan Hajnoczi         *aio_context = NULL;
36985433c24fSMax Reitz     }
36993d948cdfSStefan Hajnoczi     return NULL;
37002d47c6e9SStefan Hajnoczi }
37012d47c6e9SStefan Hajnoczi 
3702882ec7ceSStefan Hajnoczi void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
37032d47c6e9SStefan Hajnoczi {
37043d948cdfSStefan Hajnoczi     AioContext *aio_context;
370524d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
37062d47c6e9SStefan Hajnoczi 
37072d47c6e9SStefan Hajnoczi     if (!job) {
37082d47c6e9SStefan Hajnoczi         return;
37092d47c6e9SStefan Hajnoczi     }
37102d47c6e9SStefan Hajnoczi 
3711882ec7ceSStefan Hajnoczi     block_job_set_speed(job, speed, errp);
37123d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
37132d47c6e9SStefan Hajnoczi }
3714370521a1SStefan Hajnoczi 
37156e37fb81SPaolo Bonzini void qmp_block_job_cancel(const char *device,
37166e37fb81SPaolo Bonzini                           bool has_force, bool force, Error **errp)
37176e37fb81SPaolo Bonzini {
37183d948cdfSStefan Hajnoczi     AioContext *aio_context;
371924d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
37206e37fb81SPaolo Bonzini 
37216e37fb81SPaolo Bonzini     if (!job) {
37226e37fb81SPaolo Bonzini         return;
37236e37fb81SPaolo Bonzini     }
37243d948cdfSStefan Hajnoczi 
37253d948cdfSStefan Hajnoczi     if (!has_force) {
37263d948cdfSStefan Hajnoczi         force = false;
37273d948cdfSStefan Hajnoczi     }
37283d948cdfSStefan Hajnoczi 
3729751ebd76SFam Zheng     if (job->user_paused && !force) {
3730f231b88dSCole Robinson         error_setg(errp, "The block job for device '%s' is currently paused",
3731f231b88dSCole Robinson                    device);
37323d948cdfSStefan Hajnoczi         goto out;
37336e37fb81SPaolo Bonzini     }
37346e37fb81SPaolo Bonzini 
37356e37fb81SPaolo Bonzini     trace_qmp_block_job_cancel(job);
37366e37fb81SPaolo Bonzini     block_job_cancel(job);
37373d948cdfSStefan Hajnoczi out:
37383d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
37396e37fb81SPaolo Bonzini }
37406e37fb81SPaolo Bonzini 
37416e37fb81SPaolo Bonzini void qmp_block_job_pause(const char *device, Error **errp)
3742370521a1SStefan Hajnoczi {
37433d948cdfSStefan Hajnoczi     AioContext *aio_context;
374424d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3745370521a1SStefan Hajnoczi 
3746751ebd76SFam Zheng     if (!job || job->user_paused) {
3747370521a1SStefan Hajnoczi         return;
3748370521a1SStefan Hajnoczi     }
37496e37fb81SPaolo Bonzini 
3750751ebd76SFam Zheng     job->user_paused = true;
37516e37fb81SPaolo Bonzini     trace_qmp_block_job_pause(job);
37526e37fb81SPaolo Bonzini     block_job_pause(job);
37533d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
37546e37fb81SPaolo Bonzini }
37556e37fb81SPaolo Bonzini 
37566e37fb81SPaolo Bonzini void qmp_block_job_resume(const char *device, Error **errp)
37576e37fb81SPaolo Bonzini {
37583d948cdfSStefan Hajnoczi     AioContext *aio_context;
375924d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
37606e37fb81SPaolo Bonzini 
3761751ebd76SFam Zheng     if (!job || !job->user_paused) {
37628acc72a4SPaolo Bonzini         return;
37638acc72a4SPaolo Bonzini     }
3764370521a1SStefan Hajnoczi 
3765751ebd76SFam Zheng     job->user_paused = false;
37666e37fb81SPaolo Bonzini     trace_qmp_block_job_resume(job);
37676e37fb81SPaolo Bonzini     block_job_resume(job);
37683d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3769370521a1SStefan Hajnoczi }
3770fb5458cdSStefan Hajnoczi 
3771aeae883bSPaolo Bonzini void qmp_block_job_complete(const char *device, Error **errp)
3772aeae883bSPaolo Bonzini {
37733d948cdfSStefan Hajnoczi     AioContext *aio_context;
377424d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3775aeae883bSPaolo Bonzini 
3776aeae883bSPaolo Bonzini     if (!job) {
3777aeae883bSPaolo Bonzini         return;
3778aeae883bSPaolo Bonzini     }
3779aeae883bSPaolo Bonzini 
3780aeae883bSPaolo Bonzini     trace_qmp_block_job_complete(job);
3781aeae883bSPaolo Bonzini     block_job_complete(job, errp);
37823d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3783aeae883bSPaolo Bonzini }
3784aeae883bSPaolo Bonzini 
3785fa40e656SJeff Cody void qmp_change_backing_file(const char *device,
3786fa40e656SJeff Cody                              const char *image_node_name,
3787fa40e656SJeff Cody                              const char *backing_file,
3788fa40e656SJeff Cody                              Error **errp)
3789fa40e656SJeff Cody {
3790a0e8544cSFam Zheng     BlockBackend *blk;
3791fa40e656SJeff Cody     BlockDriverState *bs = NULL;
3792729962f6SStefan Hajnoczi     AioContext *aio_context;
3793fa40e656SJeff Cody     BlockDriverState *image_bs = NULL;
3794fa40e656SJeff Cody     Error *local_err = NULL;
3795fa40e656SJeff Cody     bool ro;
3796fa40e656SJeff Cody     int open_flags;
3797fa40e656SJeff Cody     int ret;
3798fa40e656SJeff Cody 
3799a0e8544cSFam Zheng     blk = blk_by_name(device);
3800a0e8544cSFam Zheng     if (!blk) {
380175158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
380275158ebbSMarkus Armbruster                   "Device '%s' not found", device);
3803fa40e656SJeff Cody         return;
3804fa40e656SJeff Cody     }
3805fa40e656SJeff Cody 
38065433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3807729962f6SStefan Hajnoczi     aio_context_acquire(aio_context);
3808729962f6SStefan Hajnoczi 
38095433c24fSMax Reitz     if (!blk_is_available(blk)) {
38105433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
38115433c24fSMax Reitz         goto out;
38125433c24fSMax Reitz     }
38135433c24fSMax Reitz     bs = blk_bs(blk);
38145433c24fSMax Reitz 
3815fa40e656SJeff Cody     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3816fa40e656SJeff Cody     if (local_err) {
3817fa40e656SJeff Cody         error_propagate(errp, local_err);
3818729962f6SStefan Hajnoczi         goto out;
3819fa40e656SJeff Cody     }
3820fa40e656SJeff Cody 
3821fa40e656SJeff Cody     if (!image_bs) {
3822fa40e656SJeff Cody         error_setg(errp, "image file not found");
3823729962f6SStefan Hajnoczi         goto out;
3824fa40e656SJeff Cody     }
3825fa40e656SJeff Cody 
3826fa40e656SJeff Cody     if (bdrv_find_base(image_bs) == image_bs) {
3827fa40e656SJeff Cody         error_setg(errp, "not allowing backing file change on an image "
3828fa40e656SJeff Cody                          "without a backing file");
3829729962f6SStefan Hajnoczi         goto out;
3830fa40e656SJeff Cody     }
3831fa40e656SJeff Cody 
3832fa40e656SJeff Cody     /* even though we are not necessarily operating on bs, we need it to
3833fa40e656SJeff Cody      * determine if block ops are currently prohibited on the chain */
3834fa40e656SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3835729962f6SStefan Hajnoczi         goto out;
3836fa40e656SJeff Cody     }
3837fa40e656SJeff Cody 
3838fa40e656SJeff Cody     /* final sanity check */
3839fa40e656SJeff Cody     if (!bdrv_chain_contains(bs, image_bs)) {
3840fa40e656SJeff Cody         error_setg(errp, "'%s' and image file are not in the same chain",
3841fa40e656SJeff Cody                    device);
3842729962f6SStefan Hajnoczi         goto out;
3843fa40e656SJeff Cody     }
3844fa40e656SJeff Cody 
3845fa40e656SJeff Cody     /* if not r/w, reopen to make r/w */
3846fa40e656SJeff Cody     open_flags = image_bs->open_flags;
3847fa40e656SJeff Cody     ro = bdrv_is_read_only(image_bs);
3848fa40e656SJeff Cody 
3849fa40e656SJeff Cody     if (ro) {
3850fa40e656SJeff Cody         bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3851fa40e656SJeff Cody         if (local_err) {
3852fa40e656SJeff Cody             error_propagate(errp, local_err);
3853729962f6SStefan Hajnoczi             goto out;
3854fa40e656SJeff Cody         }
3855fa40e656SJeff Cody     }
3856fa40e656SJeff Cody 
3857fa40e656SJeff Cody     ret = bdrv_change_backing_file(image_bs, backing_file,
3858fa40e656SJeff Cody                                image_bs->drv ? image_bs->drv->format_name : "");
3859fa40e656SJeff Cody 
3860fa40e656SJeff Cody     if (ret < 0) {
3861fa40e656SJeff Cody         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3862fa40e656SJeff Cody                          backing_file);
3863fa40e656SJeff Cody         /* don't exit here, so we can try to restore open flags if
3864fa40e656SJeff Cody          * appropriate */
3865fa40e656SJeff Cody     }
3866fa40e656SJeff Cody 
3867fa40e656SJeff Cody     if (ro) {
3868fa40e656SJeff Cody         bdrv_reopen(image_bs, open_flags, &local_err);
3869fa40e656SJeff Cody         if (local_err) {
3870fa40e656SJeff Cody             error_propagate(errp, local_err); /* will preserve prior errp */
3871fa40e656SJeff Cody         }
3872fa40e656SJeff Cody     }
3873729962f6SStefan Hajnoczi 
3874729962f6SStefan Hajnoczi out:
3875729962f6SStefan Hajnoczi     aio_context_release(aio_context);
3876fa40e656SJeff Cody }
3877fa40e656SJeff Cody 
3878d26c9a15SKevin Wolf void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3879d26c9a15SKevin Wolf {
3880d26c9a15SKevin Wolf     QmpOutputVisitor *ov = qmp_output_visitor_new();
3881be4b67bcSMax Reitz     BlockDriverState *bs;
3882be4b67bcSMax Reitz     BlockBackend *blk = NULL;
3883d26c9a15SKevin Wolf     QObject *obj;
3884d26c9a15SKevin Wolf     QDict *qdict;
3885d26c9a15SKevin Wolf     Error *local_err = NULL;
3886d26c9a15SKevin Wolf 
388760e19e06SMarkus Armbruster     /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3888d26c9a15SKevin Wolf      * cache.direct=false instead of silently switching to aio=threads, except
388960e19e06SMarkus Armbruster      * when called from drive_new().
3890d26c9a15SKevin Wolf      *
3891d26c9a15SKevin Wolf      * For now, simply forbidding the combination for all drivers will do. */
3892d26c9a15SKevin Wolf     if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3893c6e0bd9bSKevin Wolf         bool direct = options->has_cache &&
3894c6e0bd9bSKevin Wolf                       options->cache->has_direct &&
3895c6e0bd9bSKevin Wolf                       options->cache->direct;
3896c6e0bd9bSKevin Wolf         if (!direct) {
3897d26c9a15SKevin Wolf             error_setg(errp, "aio=native requires cache.direct=true");
3898d26c9a15SKevin Wolf             goto fail;
3899d26c9a15SKevin Wolf         }
3900d26c9a15SKevin Wolf     }
3901d26c9a15SKevin Wolf 
390251e72bc1SEric Blake     visit_type_BlockdevOptions(qmp_output_get_visitor(ov), NULL, &options,
390351e72bc1SEric Blake                                &local_err);
390484d18f06SMarkus Armbruster     if (local_err) {
3905d26c9a15SKevin Wolf         error_propagate(errp, local_err);
3906d26c9a15SKevin Wolf         goto fail;
3907d26c9a15SKevin Wolf     }
3908d26c9a15SKevin Wolf 
3909d26c9a15SKevin Wolf     obj = qmp_output_get_qobject(ov);
3910d26c9a15SKevin Wolf     qdict = qobject_to_qdict(obj);
3911d26c9a15SKevin Wolf 
3912d26c9a15SKevin Wolf     qdict_flatten(qdict);
3913d26c9a15SKevin Wolf 
3914be4b67bcSMax Reitz     if (options->has_id) {
391518e46a03SMarkus Armbruster         blk = blockdev_init(NULL, qdict, &local_err);
391684d18f06SMarkus Armbruster         if (local_err) {
3917b681072dSKevin Wolf             error_propagate(errp, local_err);
3918d26c9a15SKevin Wolf             goto fail;
3919d26c9a15SKevin Wolf         }
3920d26c9a15SKevin Wolf 
3921be4b67bcSMax Reitz         bs = blk_bs(blk);
3922be4b67bcSMax Reitz     } else {
3923be4b67bcSMax Reitz         if (!qdict_get_try_str(qdict, "node-name")) {
3924be4b67bcSMax Reitz             error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3925be4b67bcSMax Reitz                        "the root node");
3926be4b67bcSMax Reitz             goto fail;
3927be4b67bcSMax Reitz         }
3928be4b67bcSMax Reitz 
3929bd745e23SMax Reitz         bs = bds_tree_init(qdict, errp);
3930bd745e23SMax Reitz         if (!bs) {
3931be4b67bcSMax Reitz             goto fail;
3932be4b67bcSMax Reitz         }
39339c4218e9SMax Reitz 
39349c4218e9SMax Reitz         QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3935be4b67bcSMax Reitz     }
3936be4b67bcSMax Reitz 
3937be4b67bcSMax Reitz     if (bs && bdrv_key_required(bs)) {
3938be4b67bcSMax Reitz         if (blk) {
393918e46a03SMarkus Armbruster             blk_unref(blk);
3940be4b67bcSMax Reitz         } else {
39419c4218e9SMax Reitz             QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3942be4b67bcSMax Reitz             bdrv_unref(bs);
3943be4b67bcSMax Reitz         }
39448ae8e904SKevin Wolf         error_setg(errp, "blockdev-add doesn't support encrypted devices");
39458ae8e904SKevin Wolf         goto fail;
39468ae8e904SKevin Wolf     }
39478ae8e904SKevin Wolf 
3948d26c9a15SKevin Wolf fail:
3949d26c9a15SKevin Wolf     qmp_output_visitor_cleanup(ov);
3950d26c9a15SKevin Wolf }
3951d26c9a15SKevin Wolf 
395281b936aeSAlberto Garcia void qmp_x_blockdev_del(bool has_id, const char *id,
395381b936aeSAlberto Garcia                         bool has_node_name, const char *node_name, Error **errp)
395481b936aeSAlberto Garcia {
395581b936aeSAlberto Garcia     AioContext *aio_context;
395681b936aeSAlberto Garcia     BlockBackend *blk;
395781b936aeSAlberto Garcia     BlockDriverState *bs;
395881b936aeSAlberto Garcia 
395981b936aeSAlberto Garcia     if (has_id && has_node_name) {
396081b936aeSAlberto Garcia         error_setg(errp, "Only one of id and node-name must be specified");
396181b936aeSAlberto Garcia         return;
396281b936aeSAlberto Garcia     } else if (!has_id && !has_node_name) {
396381b936aeSAlberto Garcia         error_setg(errp, "No block device specified");
396481b936aeSAlberto Garcia         return;
396581b936aeSAlberto Garcia     }
396681b936aeSAlberto Garcia 
396781b936aeSAlberto Garcia     if (has_id) {
396881b936aeSAlberto Garcia         blk = blk_by_name(id);
396981b936aeSAlberto Garcia         if (!blk) {
397081b936aeSAlberto Garcia             error_setg(errp, "Cannot find block backend %s", id);
397181b936aeSAlberto Garcia             return;
397281b936aeSAlberto Garcia         }
397381b936aeSAlberto Garcia         if (blk_get_refcnt(blk) > 1) {
397481b936aeSAlberto Garcia             error_setg(errp, "Block backend %s is in use", id);
397581b936aeSAlberto Garcia             return;
397681b936aeSAlberto Garcia         }
397781b936aeSAlberto Garcia         bs = blk_bs(blk);
397881b936aeSAlberto Garcia         aio_context = blk_get_aio_context(blk);
397981b936aeSAlberto Garcia     } else {
398081b936aeSAlberto Garcia         bs = bdrv_find_node(node_name);
398181b936aeSAlberto Garcia         if (!bs) {
398281b936aeSAlberto Garcia             error_setg(errp, "Cannot find node %s", node_name);
398381b936aeSAlberto Garcia             return;
398481b936aeSAlberto Garcia         }
398581b936aeSAlberto Garcia         blk = bs->blk;
398681b936aeSAlberto Garcia         if (blk) {
398781b936aeSAlberto Garcia             error_setg(errp, "Node %s is in use by %s",
398881b936aeSAlberto Garcia                        node_name, blk_name(blk));
398981b936aeSAlberto Garcia             return;
399081b936aeSAlberto Garcia         }
399181b936aeSAlberto Garcia         aio_context = bdrv_get_aio_context(bs);
399281b936aeSAlberto Garcia     }
399381b936aeSAlberto Garcia 
399481b936aeSAlberto Garcia     aio_context_acquire(aio_context);
399581b936aeSAlberto Garcia 
399681b936aeSAlberto Garcia     if (bs) {
399781b936aeSAlberto Garcia         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
399881b936aeSAlberto Garcia             goto out;
399981b936aeSAlberto Garcia         }
400081b936aeSAlberto Garcia 
40019c4218e9SMax Reitz         if (!blk && !bs->monitor_list.tqe_prev) {
40029c4218e9SMax Reitz             error_setg(errp, "Node %s is not owned by the monitor",
40039c4218e9SMax Reitz                        bs->node_name);
40049c4218e9SMax Reitz             goto out;
40059c4218e9SMax Reitz         }
40069c4218e9SMax Reitz 
40079c4218e9SMax Reitz         if (bs->refcnt > 1) {
400881b936aeSAlberto Garcia             error_setg(errp, "Block device %s is in use",
400981b936aeSAlberto Garcia                        bdrv_get_device_or_node_name(bs));
401081b936aeSAlberto Garcia             goto out;
401181b936aeSAlberto Garcia         }
401281b936aeSAlberto Garcia     }
401381b936aeSAlberto Garcia 
401481b936aeSAlberto Garcia     if (blk) {
401581b936aeSAlberto Garcia         blk_unref(blk);
401681b936aeSAlberto Garcia     } else {
40179c4218e9SMax Reitz         QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
401881b936aeSAlberto Garcia         bdrv_unref(bs);
401981b936aeSAlberto Garcia     }
402081b936aeSAlberto Garcia 
402181b936aeSAlberto Garcia out:
402281b936aeSAlberto Garcia     aio_context_release(aio_context);
402381b936aeSAlberto Garcia }
402481b936aeSAlberto Garcia 
4025fb5458cdSStefan Hajnoczi BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4026fb5458cdSStefan Hajnoczi {
4027fea68bb6SMarkus Armbruster     BlockJobInfoList *head = NULL, **p_next = &head;
4028fea68bb6SMarkus Armbruster     BlockDriverState *bs;
4029fea68bb6SMarkus Armbruster 
4030fea68bb6SMarkus Armbruster     for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
403169691e72SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
403269691e72SStefan Hajnoczi 
403369691e72SStefan Hajnoczi         aio_context_acquire(aio_context);
403469691e72SStefan Hajnoczi 
4035fea68bb6SMarkus Armbruster         if (bs->job) {
4036fea68bb6SMarkus Armbruster             BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4037fea68bb6SMarkus Armbruster             elem->value = block_job_query(bs->job);
4038fea68bb6SMarkus Armbruster             *p_next = elem;
4039fea68bb6SMarkus Armbruster             p_next = &elem->next;
4040fea68bb6SMarkus Armbruster         }
404169691e72SStefan Hajnoczi 
404269691e72SStefan Hajnoczi         aio_context_release(aio_context);
4043fea68bb6SMarkus Armbruster     }
4044fea68bb6SMarkus Armbruster 
4045fea68bb6SMarkus Armbruster     return head;
4046fb5458cdSStefan Hajnoczi }
40474d454574SPaolo Bonzini 
40480006383eSKevin Wolf QemuOptsList qemu_common_drive_opts = {
40494d454574SPaolo Bonzini     .name = "drive",
40500006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
40514d454574SPaolo Bonzini     .desc = {
40524d454574SPaolo Bonzini         {
40534d454574SPaolo Bonzini             .name = "snapshot",
40544d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
40554d454574SPaolo Bonzini             .help = "enable/disable snapshot mode",
40564d454574SPaolo Bonzini         },{
4057a9384affSPaolo Bonzini             .name = "discard",
4058a9384affSPaolo Bonzini             .type = QEMU_OPT_STRING,
4059a9384affSPaolo Bonzini             .help = "discard operation (ignore/off, unmap/on)",
4060a9384affSPaolo Bonzini         },{
40614d454574SPaolo Bonzini             .name = "aio",
40624d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
40634d454574SPaolo Bonzini             .help = "host AIO implementation (threads, native)",
40644d454574SPaolo Bonzini         },{
40654d454574SPaolo Bonzini             .name = "format",
40664d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
40674d454574SPaolo Bonzini             .help = "disk format (raw, qcow2, ...)",
40684d454574SPaolo Bonzini         },{
40694d454574SPaolo Bonzini             .name = "rerror",
40704d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
40714d454574SPaolo Bonzini             .help = "read error action",
40724d454574SPaolo Bonzini         },{
40734d454574SPaolo Bonzini             .name = "werror",
40744d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
40754d454574SPaolo Bonzini             .help = "write error action",
40764d454574SPaolo Bonzini         },{
40770f227a94SKevin Wolf             .name = "read-only",
40784d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
40794d454574SPaolo Bonzini             .help = "open drive file as read-only",
40804d454574SPaolo Bonzini         },{
408157975222SKevin Wolf             .name = "throttling.iops-total",
40824d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
40834d454574SPaolo Bonzini             .help = "limit total I/O operations per second",
40844d454574SPaolo Bonzini         },{
408557975222SKevin Wolf             .name = "throttling.iops-read",
40864d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
40874d454574SPaolo Bonzini             .help = "limit read operations per second",
40884d454574SPaolo Bonzini         },{
408957975222SKevin Wolf             .name = "throttling.iops-write",
40904d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
40914d454574SPaolo Bonzini             .help = "limit write operations per second",
40924d454574SPaolo Bonzini         },{
409357975222SKevin Wolf             .name = "throttling.bps-total",
40944d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
40954d454574SPaolo Bonzini             .help = "limit total bytes per second",
40964d454574SPaolo Bonzini         },{
409757975222SKevin Wolf             .name = "throttling.bps-read",
40984d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
40994d454574SPaolo Bonzini             .help = "limit read bytes per second",
41004d454574SPaolo Bonzini         },{
410157975222SKevin Wolf             .name = "throttling.bps-write",
41024d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
41034d454574SPaolo Bonzini             .help = "limit write bytes per second",
41044d454574SPaolo Bonzini         },{
41053e9fab69SBenoît Canet             .name = "throttling.iops-total-max",
41063e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41073e9fab69SBenoît Canet             .help = "I/O operations burst",
41083e9fab69SBenoît Canet         },{
41093e9fab69SBenoît Canet             .name = "throttling.iops-read-max",
41103e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41113e9fab69SBenoît Canet             .help = "I/O operations read burst",
41123e9fab69SBenoît Canet         },{
41133e9fab69SBenoît Canet             .name = "throttling.iops-write-max",
41143e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41153e9fab69SBenoît Canet             .help = "I/O operations write burst",
41163e9fab69SBenoît Canet         },{
41173e9fab69SBenoît Canet             .name = "throttling.bps-total-max",
41183e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41193e9fab69SBenoît Canet             .help = "total bytes burst",
41203e9fab69SBenoît Canet         },{
41213e9fab69SBenoît Canet             .name = "throttling.bps-read-max",
41223e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41233e9fab69SBenoît Canet             .help = "total bytes read burst",
41243e9fab69SBenoît Canet         },{
41253e9fab69SBenoît Canet             .name = "throttling.bps-write-max",
41263e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41273e9fab69SBenoît Canet             .help = "total bytes write burst",
41283e9fab69SBenoît Canet         },{
41298a0fc18dSAlberto Garcia             .name = "throttling.iops-total-max-length",
41308a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41318a0fc18dSAlberto Garcia             .help = "length of the iops-total-max burst period, in seconds",
41328a0fc18dSAlberto Garcia         },{
41338a0fc18dSAlberto Garcia             .name = "throttling.iops-read-max-length",
41348a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41358a0fc18dSAlberto Garcia             .help = "length of the iops-read-max burst period, in seconds",
41368a0fc18dSAlberto Garcia         },{
41378a0fc18dSAlberto Garcia             .name = "throttling.iops-write-max-length",
41388a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41398a0fc18dSAlberto Garcia             .help = "length of the iops-write-max burst period, in seconds",
41408a0fc18dSAlberto Garcia         },{
41418a0fc18dSAlberto Garcia             .name = "throttling.bps-total-max-length",
41428a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41438a0fc18dSAlberto Garcia             .help = "length of the bps-total-max burst period, in seconds",
41448a0fc18dSAlberto Garcia         },{
41458a0fc18dSAlberto Garcia             .name = "throttling.bps-read-max-length",
41468a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41478a0fc18dSAlberto Garcia             .help = "length of the bps-read-max burst period, in seconds",
41488a0fc18dSAlberto Garcia         },{
41498a0fc18dSAlberto Garcia             .name = "throttling.bps-write-max-length",
41508a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41518a0fc18dSAlberto Garcia             .help = "length of the bps-write-max burst period, in seconds",
41528a0fc18dSAlberto Garcia         },{
41532024c1dfSBenoît Canet             .name = "throttling.iops-size",
41542024c1dfSBenoît Canet             .type = QEMU_OPT_NUMBER,
41552024c1dfSBenoît Canet             .help = "when limiting by iops max size of an I/O in bytes",
41562024c1dfSBenoît Canet         },{
415776f4afb4SAlberto Garcia             .name = "throttling.group",
415876f4afb4SAlberto Garcia             .type = QEMU_OPT_STRING,
415976f4afb4SAlberto Garcia             .help = "name of the block throttling group",
416076f4afb4SAlberto Garcia         },{
41614d454574SPaolo Bonzini             .name = "copy-on-read",
41624d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
41634d454574SPaolo Bonzini             .help = "copy read data from backing file into image file",
4164465bee1dSPeter Lieven         },{
4165465bee1dSPeter Lieven             .name = "detect-zeroes",
4166465bee1dSPeter Lieven             .type = QEMU_OPT_STRING,
4167465bee1dSPeter Lieven             .help = "try to optimize zero writes (off, on, unmap)",
4168362e9299SAlberto Garcia         },{
4169362e9299SAlberto Garcia             .name = "stats-account-invalid",
4170362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4171362e9299SAlberto Garcia             .help = "whether to account for invalid I/O operations "
4172362e9299SAlberto Garcia                     "in the statistics",
4173362e9299SAlberto Garcia         },{
4174362e9299SAlberto Garcia             .name = "stats-account-failed",
4175362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4176362e9299SAlberto Garcia             .help = "whether to account for failed I/O operations "
4177362e9299SAlberto Garcia                     "in the statistics",
41784d454574SPaolo Bonzini         },
41794d454574SPaolo Bonzini         { /* end of list */ }
41804d454574SPaolo Bonzini     },
41814d454574SPaolo Bonzini };
41820006383eSKevin Wolf 
4183bd745e23SMax Reitz static QemuOptsList qemu_root_bds_opts = {
4184bd745e23SMax Reitz     .name = "root-bds",
4185bd745e23SMax Reitz     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4186bd745e23SMax Reitz     .desc = {
4187bd745e23SMax Reitz         {
4188bd745e23SMax Reitz             .name = "discard",
4189bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
4190bd745e23SMax Reitz             .help = "discard operation (ignore/off, unmap/on)",
4191bd745e23SMax Reitz         },{
4192bd745e23SMax Reitz             .name = "aio",
4193bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
4194bd745e23SMax Reitz             .help = "host AIO implementation (threads, native)",
4195bd745e23SMax Reitz         },{
4196bd745e23SMax Reitz             .name = "read-only",
4197bd745e23SMax Reitz             .type = QEMU_OPT_BOOL,
4198bd745e23SMax Reitz             .help = "open drive file as read-only",
4199bd745e23SMax Reitz         },{
4200bd745e23SMax Reitz             .name = "copy-on-read",
4201bd745e23SMax Reitz             .type = QEMU_OPT_BOOL,
4202bd745e23SMax Reitz             .help = "copy read data from backing file into image file",
4203bd745e23SMax Reitz         },{
4204bd745e23SMax Reitz             .name = "detect-zeroes",
4205bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
4206bd745e23SMax Reitz             .help = "try to optimize zero writes (off, on, unmap)",
4207bd745e23SMax Reitz         },
4208bd745e23SMax Reitz         { /* end of list */ }
4209bd745e23SMax Reitz     },
4210bd745e23SMax Reitz };
4211bd745e23SMax Reitz 
42120006383eSKevin Wolf QemuOptsList qemu_drive_opts = {
42130006383eSKevin Wolf     .name = "drive",
42140006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
42150006383eSKevin Wolf     .desc = {
4216492fdc6fSKevin Wolf         /*
4217492fdc6fSKevin Wolf          * no elements => accept any params
4218492fdc6fSKevin Wolf          * validation will happen later
4219492fdc6fSKevin Wolf          */
42200006383eSKevin Wolf         { /* end of list */ }
42210006383eSKevin Wolf     },
42220006383eSKevin Wolf };
4223