xref: /openbmc/qemu/blockdev.c (revision 00949babe90c528df1ffb79439d632c7bd4f6c42)
1666daa68SMarkus Armbruster /*
2666daa68SMarkus Armbruster  * QEMU host block devices
3666daa68SMarkus Armbruster  *
4666daa68SMarkus Armbruster  * Copyright (c) 2003-2008 Fabrice Bellard
5666daa68SMarkus Armbruster  *
6666daa68SMarkus Armbruster  * This work is licensed under the terms of the GNU GPL, version 2 or
7666daa68SMarkus Armbruster  * later.  See the COPYING file in the top-level directory.
83618a094SMarkus Armbruster  *
93618a094SMarkus Armbruster  * This file incorporates work covered by the following copyright and
103618a094SMarkus Armbruster  * permission notice:
113618a094SMarkus Armbruster  *
123618a094SMarkus Armbruster  * Copyright (c) 2003-2008 Fabrice Bellard
133618a094SMarkus Armbruster  *
143618a094SMarkus Armbruster  * Permission is hereby granted, free of charge, to any person obtaining a copy
153618a094SMarkus Armbruster  * of this software and associated documentation files (the "Software"), to deal
163618a094SMarkus Armbruster  * in the Software without restriction, including without limitation the rights
173618a094SMarkus Armbruster  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
183618a094SMarkus Armbruster  * copies of the Software, and to permit persons to whom the Software is
193618a094SMarkus Armbruster  * furnished to do so, subject to the following conditions:
203618a094SMarkus Armbruster  *
213618a094SMarkus Armbruster  * The above copyright notice and this permission notice shall be included in
223618a094SMarkus Armbruster  * all copies or substantial portions of the Software.
233618a094SMarkus Armbruster  *
243618a094SMarkus Armbruster  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
253618a094SMarkus Armbruster  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
263618a094SMarkus Armbruster  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
273618a094SMarkus Armbruster  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
283618a094SMarkus Armbruster  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
293618a094SMarkus Armbruster  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
303618a094SMarkus Armbruster  * THE SOFTWARE.
31666daa68SMarkus Armbruster  */
32666daa68SMarkus Armbruster 
33d38ea87aSPeter Maydell #include "qemu/osdep.h"
3426f54e9aSMarkus Armbruster #include "sysemu/block-backend.h"
359c17d615SPaolo Bonzini #include "sysemu/blockdev.h"
360d09e41aSPaolo Bonzini #include "hw/block/block.h"
37737e150eSPaolo Bonzini #include "block/blockjob.h"
3876f4afb4SAlberto Garcia #include "block/throttle-groups.h"
3983c9089eSPaolo Bonzini #include "monitor/monitor.h"
40d49b6836SMarkus Armbruster #include "qemu/error-report.h"
411de7afc9SPaolo Bonzini #include "qemu/option.h"
421de7afc9SPaolo Bonzini #include "qemu/config-file.h"
437b1b5d19SPaolo Bonzini #include "qapi/qmp/types.h"
44d26c9a15SKevin Wolf #include "qapi-visit.h"
45cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
46d26c9a15SKevin Wolf #include "qapi/qmp-output-visitor.h"
479e7dac7cSPeter Lieven #include "qapi/util.h"
489c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
49737e150eSPaolo Bonzini #include "block/block_int.h"
50a4dea8a9SLuiz Capitulino #include "qmp-commands.h"
5112bd451fSStefan Hajnoczi #include "trace.h"
529c17d615SPaolo Bonzini #include "sysemu/arch_init.h"
53f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
54f348b6d1SVeronia Bahaa #include "qemu/help_option.h"
55666daa68SMarkus Armbruster 
569c4218e9SMax Reitz static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
579c4218e9SMax Reitz     QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
589c4218e9SMax Reitz 
59b33945cfSKevin Wolf static int do_open_tray(const char *blk_name, const char *qdev_id,
60b33945cfSKevin Wolf                         bool force, Error **errp);
61bf18bee5SColin Lord 
621960966dSMarkus Armbruster static const char *const if_name[IF_COUNT] = {
631960966dSMarkus Armbruster     [IF_NONE] = "none",
641960966dSMarkus Armbruster     [IF_IDE] = "ide",
651960966dSMarkus Armbruster     [IF_SCSI] = "scsi",
661960966dSMarkus Armbruster     [IF_FLOPPY] = "floppy",
671960966dSMarkus Armbruster     [IF_PFLASH] = "pflash",
681960966dSMarkus Armbruster     [IF_MTD] = "mtd",
691960966dSMarkus Armbruster     [IF_SD] = "sd",
701960966dSMarkus Armbruster     [IF_VIRTIO] = "virtio",
711960966dSMarkus Armbruster     [IF_XEN] = "xen",
721960966dSMarkus Armbruster };
731960966dSMarkus Armbruster 
7421dff8cfSJohn Snow static int if_max_devs[IF_COUNT] = {
7527d6bf40SMarkus Armbruster     /*
7627d6bf40SMarkus Armbruster      * Do not change these numbers!  They govern how drive option
7727d6bf40SMarkus Armbruster      * index maps to unit and bus.  That mapping is ABI.
7827d6bf40SMarkus Armbruster      *
79547cb157SWei Jiangang      * All controllers used to implement if=T drives need to support
8027d6bf40SMarkus Armbruster      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
8127d6bf40SMarkus Armbruster      * Otherwise, some index values map to "impossible" bus, unit
8227d6bf40SMarkus Armbruster      * values.
8327d6bf40SMarkus Armbruster      *
8427d6bf40SMarkus Armbruster      * For instance, if you change [IF_SCSI] to 255, -drive
8527d6bf40SMarkus Armbruster      * if=scsi,index=12 no longer means bus=1,unit=5, but
8627d6bf40SMarkus Armbruster      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
8727d6bf40SMarkus Armbruster      * the drive can't be set up.  Regression.
8827d6bf40SMarkus Armbruster      */
8927d6bf40SMarkus Armbruster     [IF_IDE] = 2,
9027d6bf40SMarkus Armbruster     [IF_SCSI] = 7,
911960966dSMarkus Armbruster };
921960966dSMarkus Armbruster 
9321dff8cfSJohn Snow /**
9421dff8cfSJohn Snow  * Boards may call this to offer board-by-board overrides
9521dff8cfSJohn Snow  * of the default, global values.
9621dff8cfSJohn Snow  */
9721dff8cfSJohn Snow void override_max_devs(BlockInterfaceType type, int max_devs)
9821dff8cfSJohn Snow {
9918e46a03SMarkus Armbruster     BlockBackend *blk;
10021dff8cfSJohn Snow     DriveInfo *dinfo;
10121dff8cfSJohn Snow 
10221dff8cfSJohn Snow     if (max_devs <= 0) {
10321dff8cfSJohn Snow         return;
10421dff8cfSJohn Snow     }
10521dff8cfSJohn Snow 
10618e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
10718e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
10821dff8cfSJohn Snow         if (dinfo->type == type) {
10921dff8cfSJohn Snow             fprintf(stderr, "Cannot override units-per-bus property of"
11021dff8cfSJohn Snow                     " the %s interface, because a drive of that type has"
11121dff8cfSJohn Snow                     " already been added.\n", if_name[type]);
11221dff8cfSJohn Snow             g_assert_not_reached();
11321dff8cfSJohn Snow         }
11421dff8cfSJohn Snow     }
11521dff8cfSJohn Snow 
11621dff8cfSJohn Snow     if_max_devs[type] = max_devs;
11721dff8cfSJohn Snow }
11821dff8cfSJohn Snow 
11914bafc54SMarkus Armbruster /*
12014bafc54SMarkus Armbruster  * We automatically delete the drive when a device using it gets
12114bafc54SMarkus Armbruster  * unplugged.  Questionable feature, but we can't just drop it.
12214bafc54SMarkus Armbruster  * Device models call blockdev_mark_auto_del() to schedule the
12314bafc54SMarkus Armbruster  * automatic deletion, and generic qdev code calls blockdev_auto_del()
12414bafc54SMarkus Armbruster  * when deletion is actually safe.
12514bafc54SMarkus Armbruster  */
1264be74634SMarkus Armbruster void blockdev_mark_auto_del(BlockBackend *blk)
12714bafc54SMarkus Armbruster {
12818e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
1294be74634SMarkus Armbruster     BlockDriverState *bs = blk_bs(blk);
13091fddb0dSStefan Hajnoczi     AioContext *aio_context;
13114bafc54SMarkus Armbruster 
13226f8b3a8SMarkus Armbruster     if (!dinfo) {
1332d246f01SKevin Wolf         return;
1342d246f01SKevin Wolf     }
1352d246f01SKevin Wolf 
1365433c24fSMax Reitz     if (bs) {
13791fddb0dSStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
13891fddb0dSStefan Hajnoczi         aio_context_acquire(aio_context);
13991fddb0dSStefan Hajnoczi 
14012bde0eeSPaolo Bonzini         if (bs->job) {
14112bde0eeSPaolo Bonzini             block_job_cancel(bs->job);
14212bde0eeSPaolo Bonzini         }
14391fddb0dSStefan Hajnoczi 
14491fddb0dSStefan Hajnoczi         aio_context_release(aio_context);
1455433c24fSMax Reitz     }
14691fddb0dSStefan Hajnoczi 
14714bafc54SMarkus Armbruster     dinfo->auto_del = 1;
14814bafc54SMarkus Armbruster }
14914bafc54SMarkus Armbruster 
1504be74634SMarkus Armbruster void blockdev_auto_del(BlockBackend *blk)
15114bafc54SMarkus Armbruster {
15218e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
15314bafc54SMarkus Armbruster 
1540fc0f1faSRyan Harper     if (dinfo && dinfo->auto_del) {
155efaa7c4eSMax Reitz         monitor_remove_blk(blk);
156b9fe8a7aSMarkus Armbruster         blk_unref(blk);
15714bafc54SMarkus Armbruster     }
15814bafc54SMarkus Armbruster }
15914bafc54SMarkus Armbruster 
160d8f94e1bSJohn Snow /**
161d8f94e1bSJohn Snow  * Returns the current mapping of how many units per bus
162d8f94e1bSJohn Snow  * a particular interface can support.
163d8f94e1bSJohn Snow  *
164d8f94e1bSJohn Snow  *  A positive integer indicates n units per bus.
165d8f94e1bSJohn Snow  *  0 implies the mapping has not been established.
166d8f94e1bSJohn Snow  * -1 indicates an invalid BlockInterfaceType was given.
167d8f94e1bSJohn Snow  */
168d8f94e1bSJohn Snow int drive_get_max_devs(BlockInterfaceType type)
169d8f94e1bSJohn Snow {
170d8f94e1bSJohn Snow     if (type >= IF_IDE && type < IF_COUNT) {
171d8f94e1bSJohn Snow         return if_max_devs[type];
172d8f94e1bSJohn Snow     }
173d8f94e1bSJohn Snow 
174d8f94e1bSJohn Snow     return -1;
175d8f94e1bSJohn Snow }
176d8f94e1bSJohn Snow 
177505a7fb1SMarkus Armbruster static int drive_index_to_bus_id(BlockInterfaceType type, int index)
178505a7fb1SMarkus Armbruster {
179505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
180505a7fb1SMarkus Armbruster     return max_devs ? index / max_devs : 0;
181505a7fb1SMarkus Armbruster }
182505a7fb1SMarkus Armbruster 
183505a7fb1SMarkus Armbruster static int drive_index_to_unit_id(BlockInterfaceType type, int index)
184505a7fb1SMarkus Armbruster {
185505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
186505a7fb1SMarkus Armbruster     return max_devs ? index % max_devs : index;
187505a7fb1SMarkus Armbruster }
188505a7fb1SMarkus Armbruster 
1892292ddaeSMarkus Armbruster QemuOpts *drive_def(const char *optstr)
1902292ddaeSMarkus Armbruster {
19170b94331SMarkus Armbruster     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
1922292ddaeSMarkus Armbruster }
1932292ddaeSMarkus Armbruster 
1942292ddaeSMarkus Armbruster QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
1955645b0f4SMarkus Armbruster                     const char *optstr)
196666daa68SMarkus Armbruster {
197666daa68SMarkus Armbruster     QemuOpts *opts;
198666daa68SMarkus Armbruster 
1992292ddaeSMarkus Armbruster     opts = drive_def(optstr);
200666daa68SMarkus Armbruster     if (!opts) {
201666daa68SMarkus Armbruster         return NULL;
202666daa68SMarkus Armbruster     }
2032292ddaeSMarkus Armbruster     if (type != IF_DEFAULT) {
204f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "if", if_name[type], &error_abort);
2052292ddaeSMarkus Armbruster     }
2062292ddaeSMarkus Armbruster     if (index >= 0) {
207a8b18f8fSMarkus Armbruster         qemu_opt_set_number(opts, "index", index, &error_abort);
2082292ddaeSMarkus Armbruster     }
209666daa68SMarkus Armbruster     if (file)
210f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "file", file, &error_abort);
211666daa68SMarkus Armbruster     return opts;
212666daa68SMarkus Armbruster }
213666daa68SMarkus Armbruster 
214666daa68SMarkus Armbruster DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
215666daa68SMarkus Armbruster {
21618e46a03SMarkus Armbruster     BlockBackend *blk;
217666daa68SMarkus Armbruster     DriveInfo *dinfo;
218666daa68SMarkus Armbruster 
21918e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
22018e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
22118e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type
22218e46a03SMarkus Armbruster             && dinfo->bus == bus && dinfo->unit == unit) {
223666daa68SMarkus Armbruster             return dinfo;
224666daa68SMarkus Armbruster         }
22518e46a03SMarkus Armbruster     }
226666daa68SMarkus Armbruster 
227666daa68SMarkus Armbruster     return NULL;
228666daa68SMarkus Armbruster }
229666daa68SMarkus Armbruster 
230a66c9dc7SJohn Snow bool drive_check_orphaned(void)
231a66c9dc7SJohn Snow {
23218e46a03SMarkus Armbruster     BlockBackend *blk;
233a66c9dc7SJohn Snow     DriveInfo *dinfo;
234a66c9dc7SJohn Snow     bool rs = false;
235a66c9dc7SJohn Snow 
23618e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
23718e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
238a66c9dc7SJohn Snow         /* If dinfo->bdrv->dev is NULL, it has no device attached. */
239a66c9dc7SJohn Snow         /* Unless this is a default drive, this may be an oversight. */
240a7f53e26SMarkus Armbruster         if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
241a66c9dc7SJohn Snow             dinfo->type != IF_NONE) {
242a66c9dc7SJohn Snow             fprintf(stderr, "Warning: Orphaned drive without device: "
243a66c9dc7SJohn Snow                     "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
2445433c24fSMax Reitz                     blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
2455433c24fSMax Reitz                     if_name[dinfo->type], dinfo->bus, dinfo->unit);
246a66c9dc7SJohn Snow             rs = true;
247a66c9dc7SJohn Snow         }
248a66c9dc7SJohn Snow     }
249a66c9dc7SJohn Snow 
250a66c9dc7SJohn Snow     return rs;
251a66c9dc7SJohn Snow }
252a66c9dc7SJohn Snow 
253f1bd51acSMarkus Armbruster DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
254f1bd51acSMarkus Armbruster {
255f1bd51acSMarkus Armbruster     return drive_get(type,
256f1bd51acSMarkus Armbruster                      drive_index_to_bus_id(type, index),
257f1bd51acSMarkus Armbruster                      drive_index_to_unit_id(type, index));
258f1bd51acSMarkus Armbruster }
259f1bd51acSMarkus Armbruster 
260666daa68SMarkus Armbruster int drive_get_max_bus(BlockInterfaceType type)
261666daa68SMarkus Armbruster {
262666daa68SMarkus Armbruster     int max_bus;
26318e46a03SMarkus Armbruster     BlockBackend *blk;
264666daa68SMarkus Armbruster     DriveInfo *dinfo;
265666daa68SMarkus Armbruster 
266666daa68SMarkus Armbruster     max_bus = -1;
26718e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
26818e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
26918e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
270666daa68SMarkus Armbruster             max_bus = dinfo->bus;
271666daa68SMarkus Armbruster         }
27218e46a03SMarkus Armbruster     }
273666daa68SMarkus Armbruster     return max_bus;
274666daa68SMarkus Armbruster }
275666daa68SMarkus Armbruster 
27613839974SMarkus Armbruster /* Get a block device.  This should only be used for single-drive devices
27713839974SMarkus Armbruster    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
27813839974SMarkus Armbruster    appropriate bus.  */
27913839974SMarkus Armbruster DriveInfo *drive_get_next(BlockInterfaceType type)
28013839974SMarkus Armbruster {
28113839974SMarkus Armbruster     static int next_block_unit[IF_COUNT];
28213839974SMarkus Armbruster 
28313839974SMarkus Armbruster     return drive_get(type, 0, next_block_unit[type]++);
28413839974SMarkus Armbruster }
28513839974SMarkus Armbruster 
286666daa68SMarkus Armbruster static void bdrv_format_print(void *opaque, const char *name)
287666daa68SMarkus Armbruster {
288807105a7SMarkus Armbruster     error_printf(" %s", name);
289666daa68SMarkus Armbruster }
290666daa68SMarkus Armbruster 
291aa398a5cSStefan Hajnoczi typedef struct {
292aa398a5cSStefan Hajnoczi     QEMUBH *bh;
293fa510ebfSFam Zheng     BlockDriverState *bs;
294fa510ebfSFam Zheng } BDRVPutRefBH;
295aa398a5cSStefan Hajnoczi 
296b681072dSKevin Wolf static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
297666daa68SMarkus Armbruster {
298666daa68SMarkus Armbruster     if (!strcmp(buf, "ignore")) {
29992aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_IGNORE;
300666daa68SMarkus Armbruster     } else if (!is_read && !strcmp(buf, "enospc")) {
30192aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_ENOSPC;
302666daa68SMarkus Armbruster     } else if (!strcmp(buf, "stop")) {
30392aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_STOP;
304666daa68SMarkus Armbruster     } else if (!strcmp(buf, "report")) {
30592aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_REPORT;
306666daa68SMarkus Armbruster     } else {
307b681072dSKevin Wolf         error_setg(errp, "'%s' invalid %s error action",
308666daa68SMarkus Armbruster                    buf, is_read ? "read" : "write");
309666daa68SMarkus Armbruster         return -1;
310666daa68SMarkus Armbruster     }
311666daa68SMarkus Armbruster }
312666daa68SMarkus Armbruster 
31340119effSAlberto Garcia static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
31440119effSAlberto Garcia                                   Error **errp)
31540119effSAlberto Garcia {
31640119effSAlberto Garcia     const QListEntry *entry;
31740119effSAlberto Garcia     for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
31840119effSAlberto Garcia         switch (qobject_type(entry->value)) {
31940119effSAlberto Garcia 
32040119effSAlberto Garcia         case QTYPE_QSTRING: {
32140119effSAlberto Garcia             unsigned long long length;
32240119effSAlberto Garcia             const char *str = qstring_get_str(qobject_to_qstring(entry->value));
32340119effSAlberto Garcia             if (parse_uint_full(str, &length, 10) == 0 &&
32440119effSAlberto Garcia                 length > 0 && length <= UINT_MAX) {
32540119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
32640119effSAlberto Garcia             } else {
32740119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %s", str);
32840119effSAlberto Garcia                 return false;
32940119effSAlberto Garcia             }
33040119effSAlberto Garcia             break;
33140119effSAlberto Garcia         }
33240119effSAlberto Garcia 
33340119effSAlberto Garcia         case QTYPE_QINT: {
33440119effSAlberto Garcia             int64_t length = qint_get_int(qobject_to_qint(entry->value));
33540119effSAlberto Garcia             if (length > 0 && length <= UINT_MAX) {
33640119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
33740119effSAlberto Garcia             } else {
33840119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %" PRId64, length);
33940119effSAlberto Garcia                 return false;
34040119effSAlberto Garcia             }
34140119effSAlberto Garcia             break;
34240119effSAlberto Garcia         }
34340119effSAlberto Garcia 
34440119effSAlberto Garcia         default:
34540119effSAlberto Garcia             error_setg(errp, "The specification of stats-intervals is invalid");
34640119effSAlberto Garcia             return false;
34740119effSAlberto Garcia         }
34840119effSAlberto Garcia     }
34940119effSAlberto Garcia     return true;
35040119effSAlberto Garcia }
35140119effSAlberto Garcia 
35233cb7dc8SKevin Wolf typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
35333cb7dc8SKevin Wolf 
354fbf8175eSMax Reitz /* All parameters but @opts are optional and may be set to NULL. */
355fbf8175eSMax Reitz static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
356fbf8175eSMax Reitz     const char **throttling_group, ThrottleConfig *throttle_cfg,
357fbf8175eSMax Reitz     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
358fbf8175eSMax Reitz {
359fbf8175eSMax Reitz     const char *discard;
360fbf8175eSMax Reitz     Error *local_error = NULL;
361fbf8175eSMax Reitz     const char *aio;
362fbf8175eSMax Reitz 
363fbf8175eSMax Reitz     if (bdrv_flags) {
364fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
365fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_COPY_ON_READ;
366fbf8175eSMax Reitz         }
367fbf8175eSMax Reitz 
368fbf8175eSMax Reitz         if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
369fbf8175eSMax Reitz             if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
370fbf8175eSMax Reitz                 error_setg(errp, "Invalid discard option");
371fbf8175eSMax Reitz                 return;
372fbf8175eSMax Reitz             }
373fbf8175eSMax Reitz         }
374fbf8175eSMax Reitz 
375fbf8175eSMax Reitz         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
376fbf8175eSMax Reitz             if (!strcmp(aio, "native")) {
377fbf8175eSMax Reitz                 *bdrv_flags |= BDRV_O_NATIVE_AIO;
378fbf8175eSMax Reitz             } else if (!strcmp(aio, "threads")) {
379fbf8175eSMax Reitz                 /* this is the default */
380fbf8175eSMax Reitz             } else {
381fbf8175eSMax Reitz                error_setg(errp, "invalid aio option");
382fbf8175eSMax Reitz                return;
383fbf8175eSMax Reitz             }
384fbf8175eSMax Reitz         }
385fbf8175eSMax Reitz     }
386fbf8175eSMax Reitz 
387fbf8175eSMax Reitz     /* disk I/O throttling */
388fbf8175eSMax Reitz     if (throttling_group) {
389fbf8175eSMax Reitz         *throttling_group = qemu_opt_get(opts, "throttling.group");
390fbf8175eSMax Reitz     }
391fbf8175eSMax Reitz 
392fbf8175eSMax Reitz     if (throttle_cfg) {
3931588ab5dSAlberto Garcia         throttle_config_init(throttle_cfg);
394fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
395fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total", 0);
396fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
397fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read", 0);
398fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
399fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write", 0);
400fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
401fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total", 0);
402fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
403fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read", 0);
404fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
405fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write", 0);
406fbf8175eSMax Reitz 
407fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
408fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
409fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
410fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
411fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
412fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
413fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
414fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
415fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
416fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
417fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
418fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
419fbf8175eSMax Reitz 
4208a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
4218a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
4228a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length  =
4238a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
4248a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
4258a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
4268a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
4278a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
4288a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
4298a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
4308a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
4318a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
4328a0fc18dSAlberto Garcia 
433fbf8175eSMax Reitz         throttle_cfg->op_size =
434fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-size", 0);
435fbf8175eSMax Reitz 
436d5851089SAlberto Garcia         if (!throttle_is_valid(throttle_cfg, errp)) {
437fbf8175eSMax Reitz             return;
438fbf8175eSMax Reitz         }
439fbf8175eSMax Reitz     }
440fbf8175eSMax Reitz 
441fbf8175eSMax Reitz     if (detect_zeroes) {
442fbf8175eSMax Reitz         *detect_zeroes =
443fbf8175eSMax Reitz             qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
444fbf8175eSMax Reitz                             qemu_opt_get(opts, "detect-zeroes"),
4457fb1cf16SEric Blake                             BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
446fbf8175eSMax Reitz                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
447fbf8175eSMax Reitz                             &local_error);
448fbf8175eSMax Reitz         if (local_error) {
449fbf8175eSMax Reitz             error_propagate(errp, local_error);
450fbf8175eSMax Reitz             return;
451fbf8175eSMax Reitz         }
452fbf8175eSMax Reitz 
453fbf8175eSMax Reitz         if (bdrv_flags &&
454fbf8175eSMax Reitz             *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
455fbf8175eSMax Reitz             !(*bdrv_flags & BDRV_O_UNMAP))
456fbf8175eSMax Reitz         {
457fbf8175eSMax Reitz             error_setg(errp, "setting detect-zeroes to unmap is not allowed "
458fbf8175eSMax Reitz                              "without setting discard operation to unmap");
459fbf8175eSMax Reitz             return;
460fbf8175eSMax Reitz         }
461fbf8175eSMax Reitz     }
462fbf8175eSMax Reitz }
463fbf8175eSMax Reitz 
464f298d071SKevin Wolf /* Takes the ownership of bs_opts */
46518e46a03SMarkus Armbruster static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
466b681072dSKevin Wolf                                    Error **errp)
467666daa68SMarkus Armbruster {
468666daa68SMarkus Armbruster     const char *buf;
469666daa68SMarkus Armbruster     int bdrv_flags = 0;
470666daa68SMarkus Armbruster     int on_read_error, on_write_error;
471362e9299SAlberto Garcia     bool account_invalid, account_failed;
472f87a0e29SAlberto Garcia     bool writethrough, read_only;
47326f54e9aSMarkus Armbruster     BlockBackend *blk;
474a0f1eab1SMarkus Armbruster     BlockDriverState *bs;
475cc0681c4SBenoît Canet     ThrottleConfig cfg;
476666daa68SMarkus Armbruster     int snapshot = 0;
477c546194fSStefan Hajnoczi     Error *error = NULL;
4780006383eSKevin Wolf     QemuOpts *opts;
47940119effSAlberto Garcia     QDict *interval_dict = NULL;
48040119effSAlberto Garcia     QList *interval_list = NULL;
4810006383eSKevin Wolf     const char *id;
482fbf8175eSMax Reitz     BlockdevDetectZeroesOptions detect_zeroes =
483fbf8175eSMax Reitz         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
484fbf8175eSMax Reitz     const char *throttling_group = NULL;
485666daa68SMarkus Armbruster 
486f298d071SKevin Wolf     /* Check common options by copying from bs_opts to opts, all other options
487f298d071SKevin Wolf      * stay in bs_opts for processing by bdrv_open(). */
488f298d071SKevin Wolf     id = qdict_get_try_str(bs_opts, "id");
4890006383eSKevin Wolf     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
49084d18f06SMarkus Armbruster     if (error) {
491b681072dSKevin Wolf         error_propagate(errp, error);
4926376f952SMarkus Armbruster         goto err_no_opts;
4930006383eSKevin Wolf     }
4940006383eSKevin Wolf 
4950006383eSKevin Wolf     qemu_opts_absorb_qdict(opts, bs_opts, &error);
49684d18f06SMarkus Armbruster     if (error) {
497b681072dSKevin Wolf         error_propagate(errp, error);
498ec9c10d2SStefan Hajnoczi         goto early_err;
4990006383eSKevin Wolf     }
5000006383eSKevin Wolf 
5010006383eSKevin Wolf     if (id) {
5020006383eSKevin Wolf         qdict_del(bs_opts, "id");
5030006383eSKevin Wolf     }
5040006383eSKevin Wolf 
505666daa68SMarkus Armbruster     /* extract parameters */
506666daa68SMarkus Armbruster     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
507666daa68SMarkus Armbruster 
508362e9299SAlberto Garcia     account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
509362e9299SAlberto Garcia     account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
510362e9299SAlberto Garcia 
511e4b24b49SKevin Wolf     writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
512e4b24b49SKevin Wolf 
513ff356ee4SAlberto Garcia     id = qemu_opts_id(opts);
514ff356ee4SAlberto Garcia 
51540119effSAlberto Garcia     qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
51640119effSAlberto Garcia     qdict_array_split(interval_dict, &interval_list);
51740119effSAlberto Garcia 
51840119effSAlberto Garcia     if (qdict_size(interval_dict) != 0) {
51940119effSAlberto Garcia         error_setg(errp, "Invalid option stats-intervals.%s",
52040119effSAlberto Garcia                    qdict_first(interval_dict)->key);
52140119effSAlberto Garcia         goto early_err;
52240119effSAlberto Garcia     }
5232be5506fSAlberto Garcia 
524fbf8175eSMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
525fbf8175eSMax Reitz                                     &detect_zeroes, &error);
526fbf8175eSMax Reitz     if (error) {
527fbf8175eSMax Reitz         error_propagate(errp, error);
528ec9c10d2SStefan Hajnoczi         goto early_err;
529a9384affSPaolo Bonzini     }
530666daa68SMarkus Armbruster 
531666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
532c8057f95SPeter Maydell         if (is_help_option(buf)) {
533807105a7SMarkus Armbruster             error_printf("Supported formats:");
534666daa68SMarkus Armbruster             bdrv_iterate_format(bdrv_format_print, NULL);
535807105a7SMarkus Armbruster             error_printf("\n");
536ec9c10d2SStefan Hajnoczi             goto early_err;
537666daa68SMarkus Armbruster         }
53874fe54f2SKevin Wolf 
539e4342ce5SMax Reitz         if (qdict_haskey(bs_opts, "driver")) {
540e4342ce5SMax Reitz             error_setg(errp, "Cannot specify both 'driver' and 'format'");
541ec9c10d2SStefan Hajnoczi             goto early_err;
5426db5f5d6SMike Qiu         }
543e4342ce5SMax Reitz         qdict_put(bs_opts, "driver", qstring_from_str(buf));
544666daa68SMarkus Armbruster     }
545666daa68SMarkus Armbruster 
54692aa5c6dSPaolo Bonzini     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
547666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
548b681072dSKevin Wolf         on_write_error = parse_block_error_action(buf, 0, &error);
54984d18f06SMarkus Armbruster         if (error) {
550b681072dSKevin Wolf             error_propagate(errp, error);
551ec9c10d2SStefan Hajnoczi             goto early_err;
552666daa68SMarkus Armbruster         }
553666daa68SMarkus Armbruster     }
554666daa68SMarkus Armbruster 
55592aa5c6dSPaolo Bonzini     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
556666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
557b681072dSKevin Wolf         on_read_error = parse_block_error_action(buf, 1, &error);
55884d18f06SMarkus Armbruster         if (error) {
559b681072dSKevin Wolf             error_propagate(errp, error);
560ec9c10d2SStefan Hajnoczi             goto early_err;
561666daa68SMarkus Armbruster         }
562666daa68SMarkus Armbruster     }
563666daa68SMarkus Armbruster 
564666daa68SMarkus Armbruster     if (snapshot) {
56591a097e7SKevin Wolf         bdrv_flags |= BDRV_O_SNAPSHOT;
566666daa68SMarkus Armbruster     }
567666daa68SMarkus Armbruster 
568f87a0e29SAlberto Garcia     read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
569f87a0e29SAlberto Garcia 
5705ec18f8cSMax Reitz     /* init */
57139c4ae94SKevin Wolf     if ((!file || !*file) && !qdict_size(bs_opts)) {
5725ec18f8cSMax Reitz         BlockBackendRootState *blk_rs;
5735ec18f8cSMax Reitz 
574109525adSMax Reitz         blk = blk_new();
5755ec18f8cSMax Reitz         blk_rs = blk_get_root_state(blk);
5765ec18f8cSMax Reitz         blk_rs->open_flags    = bdrv_flags;
577f87a0e29SAlberto Garcia         blk_rs->read_only     = read_only;
5785ec18f8cSMax Reitz         blk_rs->detect_zeroes = detect_zeroes;
5795ec18f8cSMax Reitz 
5805ec18f8cSMax Reitz         QDECREF(bs_opts);
5815ec18f8cSMax Reitz     } else {
5825ec18f8cSMax Reitz         if (file && !*file) {
5835ec18f8cSMax Reitz             file = NULL;
5845ec18f8cSMax Reitz         }
5855ec18f8cSMax Reitz 
58691a097e7SKevin Wolf         /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
58791a097e7SKevin Wolf          * with other callers) rather than what we want as the real defaults.
58891a097e7SKevin Wolf          * Apply the defaults here instead. */
58991a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
59091a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
591f87a0e29SAlberto Garcia         qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
592f87a0e29SAlberto Garcia                               read_only ? "on" : "off");
59372e775c7SKevin Wolf         assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
59491a097e7SKevin Wolf 
59512d5ee3aSKevin Wolf         if (runstate_check(RUN_STATE_INMIGRATE)) {
59612d5ee3aSKevin Wolf             bdrv_flags |= BDRV_O_INACTIVE;
59712d5ee3aSKevin Wolf         }
59812d5ee3aSKevin Wolf 
599efaa7c4eSMax Reitz         blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
600e4342ce5SMax Reitz         if (!blk) {
601e4342ce5SMax Reitz             goto err_no_bs_opts;
602e4342ce5SMax Reitz         }
603e4342ce5SMax Reitz         bs = blk_bs(blk);
6040006383eSKevin Wolf 
605e4342ce5SMax Reitz         bs->detect_zeroes = detect_zeroes;
606e4342ce5SMax Reitz 
607a0f1eab1SMarkus Armbruster         if (bdrv_key_required(bs)) {
608666daa68SMarkus Armbruster             autostart = 0;
609a0f1eab1SMarkus Armbruster         }
610362e9299SAlberto Garcia 
611362e9299SAlberto Garcia         block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
6122be5506fSAlberto Garcia 
61340119effSAlberto Garcia         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
6142be5506fSAlberto Garcia             blk_unref(blk);
6152be5506fSAlberto Garcia             blk = NULL;
6162be5506fSAlberto Garcia             goto err_no_bs_opts;
6172be5506fSAlberto Garcia         }
6182be5506fSAlberto Garcia     }
6195ec18f8cSMax Reitz 
6207ca7f0f6SKevin Wolf     /* disk I/O throttling */
6217ca7f0f6SKevin Wolf     if (throttle_enabled(&cfg)) {
6227ca7f0f6SKevin Wolf         if (!throttling_group) {
623ff356ee4SAlberto Garcia             throttling_group = id;
6247ca7f0f6SKevin Wolf         }
6257ca7f0f6SKevin Wolf         blk_io_limits_enable(blk, throttling_group);
6267ca7f0f6SKevin Wolf         blk_set_io_limits(blk, &cfg);
6277ca7f0f6SKevin Wolf     }
6287ca7f0f6SKevin Wolf 
629e4b24b49SKevin Wolf     blk_set_enable_write_cache(blk, !writethrough);
6305ec18f8cSMax Reitz     blk_set_on_error(blk, on_read_error, on_write_error);
6310006383eSKevin Wolf 
632ff356ee4SAlberto Garcia     if (!monitor_add_blk(blk, id, errp)) {
633efaa7c4eSMax Reitz         blk_unref(blk);
634efaa7c4eSMax Reitz         blk = NULL;
635efaa7c4eSMax Reitz         goto err_no_bs_opts;
636efaa7c4eSMax Reitz     }
637efaa7c4eSMax Reitz 
638e4342ce5SMax Reitz err_no_bs_opts:
6390006383eSKevin Wolf     qemu_opts_del(opts);
64040119effSAlberto Garcia     QDECREF(interval_dict);
64140119effSAlberto Garcia     QDECREF(interval_list);
64218e46a03SMarkus Armbruster     return blk;
643a9ae2bffSMarkus Armbruster 
644ec9c10d2SStefan Hajnoczi early_err:
645ec9c10d2SStefan Hajnoczi     qemu_opts_del(opts);
64640119effSAlberto Garcia     QDECREF(interval_dict);
64740119effSAlberto Garcia     QDECREF(interval_list);
6486376f952SMarkus Armbruster err_no_opts:
6496376f952SMarkus Armbruster     QDECREF(bs_opts);
650a9ae2bffSMarkus Armbruster     return NULL;
651666daa68SMarkus Armbruster }
652666daa68SMarkus Armbruster 
653bd745e23SMax Reitz static QemuOptsList qemu_root_bds_opts;
654bd745e23SMax Reitz 
655bd745e23SMax Reitz /* Takes the ownership of bs_opts */
656bd745e23SMax Reitz static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
657bd745e23SMax Reitz {
658bd745e23SMax Reitz     BlockDriverState *bs;
659bd745e23SMax Reitz     QemuOpts *opts;
660bd745e23SMax Reitz     Error *local_error = NULL;
661bd745e23SMax Reitz     BlockdevDetectZeroesOptions detect_zeroes;
662bd745e23SMax Reitz     int bdrv_flags = 0;
663bd745e23SMax Reitz 
664bd745e23SMax Reitz     opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
665bd745e23SMax Reitz     if (!opts) {
666bd745e23SMax Reitz         goto fail;
667bd745e23SMax Reitz     }
668bd745e23SMax Reitz 
669bd745e23SMax Reitz     qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
670bd745e23SMax Reitz     if (local_error) {
671bd745e23SMax Reitz         error_propagate(errp, local_error);
672bd745e23SMax Reitz         goto fail;
673bd745e23SMax Reitz     }
674bd745e23SMax Reitz 
675bd745e23SMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
676bd745e23SMax Reitz                                     &detect_zeroes, &local_error);
677bd745e23SMax Reitz     if (local_error) {
678bd745e23SMax Reitz         error_propagate(errp, local_error);
679bd745e23SMax Reitz         goto fail;
680bd745e23SMax Reitz     }
681bd745e23SMax Reitz 
682a81d6164SKevin Wolf     /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
683a81d6164SKevin Wolf      * with other callers) rather than what we want as the real defaults.
684a81d6164SKevin Wolf      * Apply the defaults here instead. */
685a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
686a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
687f87a0e29SAlberto Garcia     qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
688a81d6164SKevin Wolf 
68912d5ee3aSKevin Wolf     if (runstate_check(RUN_STATE_INMIGRATE)) {
69012d5ee3aSKevin Wolf         bdrv_flags |= BDRV_O_INACTIVE;
69112d5ee3aSKevin Wolf     }
69212d5ee3aSKevin Wolf 
6935b363937SMax Reitz     bs = bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
6945b363937SMax Reitz     if (!bs) {
695bd745e23SMax Reitz         goto fail_no_bs_opts;
696bd745e23SMax Reitz     }
697bd745e23SMax Reitz 
698bd745e23SMax Reitz     bs->detect_zeroes = detect_zeroes;
699bd745e23SMax Reitz 
700bd745e23SMax Reitz fail_no_bs_opts:
701bd745e23SMax Reitz     qemu_opts_del(opts);
702bd745e23SMax Reitz     return bs;
703bd745e23SMax Reitz 
704bd745e23SMax Reitz fail:
705bd745e23SMax Reitz     qemu_opts_del(opts);
706bd745e23SMax Reitz     QDECREF(bs_opts);
707bd745e23SMax Reitz     return NULL;
708bd745e23SMax Reitz }
709bd745e23SMax Reitz 
7109c4218e9SMax Reitz void blockdev_close_all_bdrv_states(void)
7119c4218e9SMax Reitz {
7129c4218e9SMax Reitz     BlockDriverState *bs, *next_bs;
7139c4218e9SMax Reitz 
7149c4218e9SMax Reitz     QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
7159c4218e9SMax Reitz         AioContext *ctx = bdrv_get_aio_context(bs);
7169c4218e9SMax Reitz 
7179c4218e9SMax Reitz         aio_context_acquire(ctx);
7189c4218e9SMax Reitz         bdrv_unref(bs);
7199c4218e9SMax Reitz         aio_context_release(ctx);
7209c4218e9SMax Reitz     }
7219c4218e9SMax Reitz }
7229c4218e9SMax Reitz 
723262b4e8fSMax Reitz /* Iterates over the list of monitor-owned BlockDriverStates */
724262b4e8fSMax Reitz BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
725262b4e8fSMax Reitz {
726262b4e8fSMax Reitz     return bs ? QTAILQ_NEXT(bs, monitor_list)
727262b4e8fSMax Reitz               : QTAILQ_FIRST(&monitor_bdrv_states);
728262b4e8fSMax Reitz }
729262b4e8fSMax Reitz 
7305abbf0eeSKevin Wolf static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
7315abbf0eeSKevin Wolf                             Error **errp)
73257975222SKevin Wolf {
73357975222SKevin Wolf     const char *value;
73457975222SKevin Wolf 
73557975222SKevin Wolf     value = qemu_opt_get(opts, from);
73657975222SKevin Wolf     if (value) {
7375abbf0eeSKevin Wolf         if (qemu_opt_find(opts, to)) {
7385abbf0eeSKevin Wolf             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
7395abbf0eeSKevin Wolf                        "same time", to, from);
7405abbf0eeSKevin Wolf             return;
7415abbf0eeSKevin Wolf         }
74220d6cd47SJun Li     }
74320d6cd47SJun Li 
74420d6cd47SJun Li     /* rename all items in opts */
74520d6cd47SJun Li     while ((value = qemu_opt_get(opts, from))) {
746f43e47dbSMarkus Armbruster         qemu_opt_set(opts, to, value, &error_abort);
74757975222SKevin Wolf         qemu_opt_unset(opts, from);
74857975222SKevin Wolf     }
74957975222SKevin Wolf }
75057975222SKevin Wolf 
75133cb7dc8SKevin Wolf QemuOptsList qemu_legacy_drive_opts = {
75233cb7dc8SKevin Wolf     .name = "drive",
75333cb7dc8SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
75433cb7dc8SKevin Wolf     .desc = {
75533cb7dc8SKevin Wolf         {
75687a899c5SKevin Wolf             .name = "bus",
75787a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
75887a899c5SKevin Wolf             .help = "bus number",
75987a899c5SKevin Wolf         },{
76087a899c5SKevin Wolf             .name = "unit",
76187a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
76287a899c5SKevin Wolf             .help = "unit number (i.e. lun for scsi)",
76387a899c5SKevin Wolf         },{
76487a899c5SKevin Wolf             .name = "index",
76587a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
76687a899c5SKevin Wolf             .help = "index number",
76787a899c5SKevin Wolf         },{
76833cb7dc8SKevin Wolf             .name = "media",
76933cb7dc8SKevin Wolf             .type = QEMU_OPT_STRING,
77033cb7dc8SKevin Wolf             .help = "media type (disk, cdrom)",
771593d464bSKevin Wolf         },{
772593d464bSKevin Wolf             .name = "if",
773593d464bSKevin Wolf             .type = QEMU_OPT_STRING,
774593d464bSKevin Wolf             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
775b41a7338SKevin Wolf         },{
776b41a7338SKevin Wolf             .name = "cyls",
777b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
778b41a7338SKevin Wolf             .help = "number of cylinders (ide disk geometry)",
779b41a7338SKevin Wolf         },{
780b41a7338SKevin Wolf             .name = "heads",
781b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
782b41a7338SKevin Wolf             .help = "number of heads (ide disk geometry)",
783b41a7338SKevin Wolf         },{
784b41a7338SKevin Wolf             .name = "secs",
785b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
786b41a7338SKevin Wolf             .help = "number of sectors (ide disk geometry)",
787b41a7338SKevin Wolf         },{
788b41a7338SKevin Wolf             .name = "trans",
789b41a7338SKevin Wolf             .type = QEMU_OPT_STRING,
790b41a7338SKevin Wolf             .help = "chs translation (auto, lba, none)",
79126929298SKevin Wolf         },{
79226929298SKevin Wolf             .name = "boot",
79326929298SKevin Wolf             .type = QEMU_OPT_BOOL,
79426929298SKevin Wolf             .help = "(deprecated, ignored)",
795394c7d4dSKevin Wolf         },{
796394c7d4dSKevin Wolf             .name = "addr",
797394c7d4dSKevin Wolf             .type = QEMU_OPT_STRING,
798394c7d4dSKevin Wolf             .help = "pci address (virtio only)",
799d095b465SMax Reitz         },{
800bcf83158SKevin Wolf             .name = "serial",
801bcf83158SKevin Wolf             .type = QEMU_OPT_STRING,
802bcf83158SKevin Wolf             .help = "disk serial number",
803bcf83158SKevin Wolf         },{
804d095b465SMax Reitz             .name = "file",
805d095b465SMax Reitz             .type = QEMU_OPT_STRING,
806d095b465SMax Reitz             .help = "file name",
80733cb7dc8SKevin Wolf         },
8080ebd24e0SKevin Wolf 
8090ebd24e0SKevin Wolf         /* Options that are passed on, but have special semantics with -drive */
8100ebd24e0SKevin Wolf         {
8114e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
8120ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
8130ebd24e0SKevin Wolf             .help = "open drive file as read-only",
8140ebd24e0SKevin Wolf         },{
815ee13ed1cSKevin Wolf             .name = "rerror",
816ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
817ee13ed1cSKevin Wolf             .help = "read error action",
818ee13ed1cSKevin Wolf         },{
819ee13ed1cSKevin Wolf             .name = "werror",
820ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
821ee13ed1cSKevin Wolf             .help = "write error action",
822ee13ed1cSKevin Wolf         },{
8230ebd24e0SKevin Wolf             .name = "copy-on-read",
8240ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
8250ebd24e0SKevin Wolf             .help = "copy read data from backing file into image file",
8260ebd24e0SKevin Wolf         },
8270ebd24e0SKevin Wolf 
82833cb7dc8SKevin Wolf         { /* end of list */ }
82933cb7dc8SKevin Wolf     },
83033cb7dc8SKevin Wolf };
83133cb7dc8SKevin Wolf 
83260e19e06SMarkus Armbruster DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
83357975222SKevin Wolf {
83429c4e2b5SKevin Wolf     const char *value;
83518e46a03SMarkus Armbruster     BlockBackend *blk;
83633cb7dc8SKevin Wolf     DriveInfo *dinfo = NULL;
837f298d071SKevin Wolf     QDict *bs_opts;
83833cb7dc8SKevin Wolf     QemuOpts *legacy_opts;
83933cb7dc8SKevin Wolf     DriveMediaType media = MEDIA_DISK;
840593d464bSKevin Wolf     BlockInterfaceType type;
841b41a7338SKevin Wolf     int cyls, heads, secs, translation;
84287a899c5SKevin Wolf     int max_devs, bus_id, unit_id, index;
843394c7d4dSKevin Wolf     const char *devaddr;
844ee13ed1cSKevin Wolf     const char *werror, *rerror;
845a7fdbcf0SFam Zheng     bool read_only = false;
846a7fdbcf0SFam Zheng     bool copy_on_read;
847bcf83158SKevin Wolf     const char *serial;
848d095b465SMax Reitz     const char *filename;
84933cb7dc8SKevin Wolf     Error *local_err = NULL;
850247147fbSKevin Wolf     int i;
85129c4e2b5SKevin Wolf 
85257975222SKevin Wolf     /* Change legacy command line options into QMP ones */
853247147fbSKevin Wolf     static const struct {
854247147fbSKevin Wolf         const char *from;
855247147fbSKevin Wolf         const char *to;
856247147fbSKevin Wolf     } opt_renames[] = {
857247147fbSKevin Wolf         { "iops",           "throttling.iops-total" },
858247147fbSKevin Wolf         { "iops_rd",        "throttling.iops-read" },
859247147fbSKevin Wolf         { "iops_wr",        "throttling.iops-write" },
86057975222SKevin Wolf 
861247147fbSKevin Wolf         { "bps",            "throttling.bps-total" },
862247147fbSKevin Wolf         { "bps_rd",         "throttling.bps-read" },
863247147fbSKevin Wolf         { "bps_wr",         "throttling.bps-write" },
86457975222SKevin Wolf 
865247147fbSKevin Wolf         { "iops_max",       "throttling.iops-total-max" },
866247147fbSKevin Wolf         { "iops_rd_max",    "throttling.iops-read-max" },
867247147fbSKevin Wolf         { "iops_wr_max",    "throttling.iops-write-max" },
8683e9fab69SBenoît Canet 
869247147fbSKevin Wolf         { "bps_max",        "throttling.bps-total-max" },
870247147fbSKevin Wolf         { "bps_rd_max",     "throttling.bps-read-max" },
871247147fbSKevin Wolf         { "bps_wr_max",     "throttling.bps-write-max" },
8723e9fab69SBenoît Canet 
873247147fbSKevin Wolf         { "iops_size",      "throttling.iops-size" },
8742024c1dfSBenoît Canet 
87576f4afb4SAlberto Garcia         { "group",          "throttling.group" },
87676f4afb4SAlberto Garcia 
8774e200cf8SAlberto Garcia         { "readonly",       BDRV_OPT_READ_ONLY },
878247147fbSKevin Wolf     };
879247147fbSKevin Wolf 
880247147fbSKevin Wolf     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
8815abbf0eeSKevin Wolf         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
8825abbf0eeSKevin Wolf                         &local_err);
8835abbf0eeSKevin Wolf         if (local_err) {
884565f65d2SMarkus Armbruster             error_report_err(local_err);
8855abbf0eeSKevin Wolf             return NULL;
8865abbf0eeSKevin Wolf         }
887247147fbSKevin Wolf     }
8880f227a94SKevin Wolf 
88929c4e2b5SKevin Wolf     value = qemu_opt_get(all_opts, "cache");
89029c4e2b5SKevin Wolf     if (value) {
89129c4e2b5SKevin Wolf         int flags = 0;
89204feb4a5SKevin Wolf         bool writethrough;
89329c4e2b5SKevin Wolf 
89404feb4a5SKevin Wolf         if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
89529c4e2b5SKevin Wolf             error_report("invalid cache option");
89629c4e2b5SKevin Wolf             return NULL;
89729c4e2b5SKevin Wolf         }
89829c4e2b5SKevin Wolf 
89929c4e2b5SKevin Wolf         /* Specific options take precedence */
90054861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
90154861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
90204feb4a5SKevin Wolf                               !writethrough, &error_abort);
90329c4e2b5SKevin Wolf         }
90454861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
90554861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
906cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NOCACHE), &error_abort);
90729c4e2b5SKevin Wolf         }
90854861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
90954861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
910cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
91129c4e2b5SKevin Wolf         }
91229c4e2b5SKevin Wolf         qemu_opt_unset(all_opts, "cache");
91329c4e2b5SKevin Wolf     }
91429c4e2b5SKevin Wolf 
915f298d071SKevin Wolf     /* Get a QDict for processing the options */
916f298d071SKevin Wolf     bs_opts = qdict_new();
917f298d071SKevin Wolf     qemu_opts_to_qdict(all_opts, bs_opts);
918f298d071SKevin Wolf 
91987ea75d5SPeter Crosthwaite     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
92087ea75d5SPeter Crosthwaite                                    &error_abort);
92133cb7dc8SKevin Wolf     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
92284d18f06SMarkus Armbruster     if (local_err) {
923565f65d2SMarkus Armbruster         error_report_err(local_err);
92433cb7dc8SKevin Wolf         goto fail;
92533cb7dc8SKevin Wolf     }
92633cb7dc8SKevin Wolf 
92726929298SKevin Wolf     /* Deprecated option boot=[on|off] */
92826929298SKevin Wolf     if (qemu_opt_get(legacy_opts, "boot") != NULL) {
92926929298SKevin Wolf         fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
93026929298SKevin Wolf                 "ignored. Future versions will reject this parameter. Please "
93126929298SKevin Wolf                 "update your scripts.\n");
93226929298SKevin Wolf     }
93326929298SKevin Wolf 
93433cb7dc8SKevin Wolf     /* Media type */
93533cb7dc8SKevin Wolf     value = qemu_opt_get(legacy_opts, "media");
93633cb7dc8SKevin Wolf     if (value) {
93733cb7dc8SKevin Wolf         if (!strcmp(value, "disk")) {
93833cb7dc8SKevin Wolf             media = MEDIA_DISK;
93933cb7dc8SKevin Wolf         } else if (!strcmp(value, "cdrom")) {
94033cb7dc8SKevin Wolf             media = MEDIA_CDROM;
941a7fdbcf0SFam Zheng             read_only = true;
94233cb7dc8SKevin Wolf         } else {
94333cb7dc8SKevin Wolf             error_report("'%s' invalid media", value);
94433cb7dc8SKevin Wolf             goto fail;
94533cb7dc8SKevin Wolf         }
94633cb7dc8SKevin Wolf     }
94733cb7dc8SKevin Wolf 
9480ebd24e0SKevin Wolf     /* copy-on-read is disabled with a warning for read-only devices */
9494e200cf8SAlberto Garcia     read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
9500ebd24e0SKevin Wolf     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
9510ebd24e0SKevin Wolf 
9520ebd24e0SKevin Wolf     if (read_only && copy_on_read) {
9530ebd24e0SKevin Wolf         error_report("warning: disabling copy-on-read on read-only drive");
9540ebd24e0SKevin Wolf         copy_on_read = false;
9550ebd24e0SKevin Wolf     }
9560ebd24e0SKevin Wolf 
9574e200cf8SAlberto Garcia     qdict_put(bs_opts, BDRV_OPT_READ_ONLY,
9580ebd24e0SKevin Wolf               qstring_from_str(read_only ? "on" : "off"));
9590ebd24e0SKevin Wolf     qdict_put(bs_opts, "copy-on-read",
9600ebd24e0SKevin Wolf               qstring_from_str(copy_on_read ? "on" :"off"));
9610ebd24e0SKevin Wolf 
962593d464bSKevin Wolf     /* Controller type */
963593d464bSKevin Wolf     value = qemu_opt_get(legacy_opts, "if");
964593d464bSKevin Wolf     if (value) {
965593d464bSKevin Wolf         for (type = 0;
966593d464bSKevin Wolf              type < IF_COUNT && strcmp(value, if_name[type]);
967593d464bSKevin Wolf              type++) {
968593d464bSKevin Wolf         }
969593d464bSKevin Wolf         if (type == IF_COUNT) {
970593d464bSKevin Wolf             error_report("unsupported bus type '%s'", value);
971593d464bSKevin Wolf             goto fail;
972593d464bSKevin Wolf         }
973593d464bSKevin Wolf     } else {
974593d464bSKevin Wolf         type = block_default_type;
975593d464bSKevin Wolf     }
976593d464bSKevin Wolf 
977b41a7338SKevin Wolf     /* Geometry */
978b41a7338SKevin Wolf     cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
979b41a7338SKevin Wolf     heads = qemu_opt_get_number(legacy_opts, "heads", 0);
980b41a7338SKevin Wolf     secs  = qemu_opt_get_number(legacy_opts, "secs", 0);
981b41a7338SKevin Wolf 
982b41a7338SKevin Wolf     if (cyls || heads || secs) {
983b41a7338SKevin Wolf         if (cyls < 1) {
984b41a7338SKevin Wolf             error_report("invalid physical cyls number");
985b41a7338SKevin Wolf             goto fail;
986b41a7338SKevin Wolf         }
987b41a7338SKevin Wolf         if (heads < 1) {
988b41a7338SKevin Wolf             error_report("invalid physical heads number");
989b41a7338SKevin Wolf             goto fail;
990b41a7338SKevin Wolf         }
991b41a7338SKevin Wolf         if (secs < 1) {
992b41a7338SKevin Wolf             error_report("invalid physical secs number");
993b41a7338SKevin Wolf             goto fail;
994b41a7338SKevin Wolf         }
995b41a7338SKevin Wolf     }
996b41a7338SKevin Wolf 
997b41a7338SKevin Wolf     translation = BIOS_ATA_TRANSLATION_AUTO;
998b41a7338SKevin Wolf     value = qemu_opt_get(legacy_opts, "trans");
999b41a7338SKevin Wolf     if (value != NULL) {
1000b41a7338SKevin Wolf         if (!cyls) {
1001b41a7338SKevin Wolf             error_report("'%s' trans must be used with cyls, heads and secs",
1002b41a7338SKevin Wolf                          value);
1003b41a7338SKevin Wolf             goto fail;
1004b41a7338SKevin Wolf         }
1005b41a7338SKevin Wolf         if (!strcmp(value, "none")) {
1006b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_NONE;
1007b41a7338SKevin Wolf         } else if (!strcmp(value, "lba")) {
1008b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_LBA;
1009f31c41ffSPaolo Bonzini         } else if (!strcmp(value, "large")) {
1010f31c41ffSPaolo Bonzini             translation = BIOS_ATA_TRANSLATION_LARGE;
1011f31c41ffSPaolo Bonzini         } else if (!strcmp(value, "rechs")) {
1012f31c41ffSPaolo Bonzini             translation = BIOS_ATA_TRANSLATION_RECHS;
1013b41a7338SKevin Wolf         } else if (!strcmp(value, "auto")) {
1014b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_AUTO;
1015b41a7338SKevin Wolf         } else {
1016b41a7338SKevin Wolf             error_report("'%s' invalid translation type", value);
1017b41a7338SKevin Wolf             goto fail;
1018b41a7338SKevin Wolf         }
1019b41a7338SKevin Wolf     }
1020b41a7338SKevin Wolf 
1021b41a7338SKevin Wolf     if (media == MEDIA_CDROM) {
1022b41a7338SKevin Wolf         if (cyls || secs || heads) {
1023b41a7338SKevin Wolf             error_report("CHS can't be set with media=cdrom");
1024b41a7338SKevin Wolf             goto fail;
1025b41a7338SKevin Wolf         }
1026b41a7338SKevin Wolf     }
1027b41a7338SKevin Wolf 
102887a899c5SKevin Wolf     /* Device address specified by bus/unit or index.
102987a899c5SKevin Wolf      * If none was specified, try to find the first free one. */
103087a899c5SKevin Wolf     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
103187a899c5SKevin Wolf     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
103287a899c5SKevin Wolf     index   = qemu_opt_get_number(legacy_opts, "index", -1);
103387a899c5SKevin Wolf 
103487a899c5SKevin Wolf     max_devs = if_max_devs[type];
103587a899c5SKevin Wolf 
103687a899c5SKevin Wolf     if (index != -1) {
103787a899c5SKevin Wolf         if (bus_id != 0 || unit_id != -1) {
103887a899c5SKevin Wolf             error_report("index cannot be used with bus and unit");
103987a899c5SKevin Wolf             goto fail;
104087a899c5SKevin Wolf         }
104187a899c5SKevin Wolf         bus_id = drive_index_to_bus_id(type, index);
104287a899c5SKevin Wolf         unit_id = drive_index_to_unit_id(type, index);
104387a899c5SKevin Wolf     }
104487a899c5SKevin Wolf 
104587a899c5SKevin Wolf     if (unit_id == -1) {
104687a899c5SKevin Wolf        unit_id = 0;
104787a899c5SKevin Wolf        while (drive_get(type, bus_id, unit_id) != NULL) {
104887a899c5SKevin Wolf            unit_id++;
104987a899c5SKevin Wolf            if (max_devs && unit_id >= max_devs) {
105087a899c5SKevin Wolf                unit_id -= max_devs;
105187a899c5SKevin Wolf                bus_id++;
105287a899c5SKevin Wolf            }
105387a899c5SKevin Wolf        }
105487a899c5SKevin Wolf     }
105587a899c5SKevin Wolf 
105687a899c5SKevin Wolf     if (max_devs && unit_id >= max_devs) {
105787a899c5SKevin Wolf         error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
105887a899c5SKevin Wolf         goto fail;
105987a899c5SKevin Wolf     }
106087a899c5SKevin Wolf 
106187a899c5SKevin Wolf     if (drive_get(type, bus_id, unit_id) != NULL) {
106287a899c5SKevin Wolf         error_report("drive with bus=%d, unit=%d (index=%d) exists",
106387a899c5SKevin Wolf                      bus_id, unit_id, index);
106487a899c5SKevin Wolf         goto fail;
106587a899c5SKevin Wolf     }
106687a899c5SKevin Wolf 
1067bcf83158SKevin Wolf     /* Serial number */
1068bcf83158SKevin Wolf     serial = qemu_opt_get(legacy_opts, "serial");
1069bcf83158SKevin Wolf 
107087a899c5SKevin Wolf     /* no id supplied -> create one */
107187a899c5SKevin Wolf     if (qemu_opts_id(all_opts) == NULL) {
107287a899c5SKevin Wolf         char *new_id;
107387a899c5SKevin Wolf         const char *mediastr = "";
107487a899c5SKevin Wolf         if (type == IF_IDE || type == IF_SCSI) {
107587a899c5SKevin Wolf             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
107687a899c5SKevin Wolf         }
107787a899c5SKevin Wolf         if (max_devs) {
107887a899c5SKevin Wolf             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
107987a899c5SKevin Wolf                                      mediastr, unit_id);
108087a899c5SKevin Wolf         } else {
108187a899c5SKevin Wolf             new_id = g_strdup_printf("%s%s%i", if_name[type],
108287a899c5SKevin Wolf                                      mediastr, unit_id);
108387a899c5SKevin Wolf         }
108487a899c5SKevin Wolf         qdict_put(bs_opts, "id", qstring_from_str(new_id));
108587a899c5SKevin Wolf         g_free(new_id);
108687a899c5SKevin Wolf     }
108787a899c5SKevin Wolf 
1088394c7d4dSKevin Wolf     /* Add virtio block device */
1089394c7d4dSKevin Wolf     devaddr = qemu_opt_get(legacy_opts, "addr");
1090394c7d4dSKevin Wolf     if (devaddr && type != IF_VIRTIO) {
1091394c7d4dSKevin Wolf         error_report("addr is not supported by this bus type");
1092394c7d4dSKevin Wolf         goto fail;
1093394c7d4dSKevin Wolf     }
1094394c7d4dSKevin Wolf 
1095394c7d4dSKevin Wolf     if (type == IF_VIRTIO) {
1096394c7d4dSKevin Wolf         QemuOpts *devopts;
109787ea75d5SPeter Crosthwaite         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
109887ea75d5SPeter Crosthwaite                                    &error_abort);
1099394c7d4dSKevin Wolf         if (arch_type == QEMU_ARCH_S390X) {
11001f68f1d3SAlexander Graf             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1101394c7d4dSKevin Wolf         } else {
1102f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1103394c7d4dSKevin Wolf         }
1104f43e47dbSMarkus Armbruster         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1105f43e47dbSMarkus Armbruster                      &error_abort);
1106394c7d4dSKevin Wolf         if (devaddr) {
1107f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1108394c7d4dSKevin Wolf         }
1109394c7d4dSKevin Wolf     }
1110394c7d4dSKevin Wolf 
1111d095b465SMax Reitz     filename = qemu_opt_get(legacy_opts, "file");
1112d095b465SMax Reitz 
1113ee13ed1cSKevin Wolf     /* Check werror/rerror compatibility with if=... */
1114ee13ed1cSKevin Wolf     werror = qemu_opt_get(legacy_opts, "werror");
1115ee13ed1cSKevin Wolf     if (werror != NULL) {
1116ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1117ee13ed1cSKevin Wolf             type != IF_NONE) {
1118ee13ed1cSKevin Wolf             error_report("werror is not supported by this bus type");
1119ee13ed1cSKevin Wolf             goto fail;
1120ee13ed1cSKevin Wolf         }
1121ee13ed1cSKevin Wolf         qdict_put(bs_opts, "werror", qstring_from_str(werror));
1122ee13ed1cSKevin Wolf     }
1123ee13ed1cSKevin Wolf 
1124ee13ed1cSKevin Wolf     rerror = qemu_opt_get(legacy_opts, "rerror");
1125ee13ed1cSKevin Wolf     if (rerror != NULL) {
1126ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1127ee13ed1cSKevin Wolf             type != IF_NONE) {
1128ee13ed1cSKevin Wolf             error_report("rerror is not supported by this bus type");
1129ee13ed1cSKevin Wolf             goto fail;
1130ee13ed1cSKevin Wolf         }
1131ee13ed1cSKevin Wolf         qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1132ee13ed1cSKevin Wolf     }
1133ee13ed1cSKevin Wolf 
11342d246f01SKevin Wolf     /* Actual block device init: Functionality shared with blockdev-add */
113518e46a03SMarkus Armbruster     blk = blockdev_init(filename, bs_opts, &local_err);
11363cb0e25cSMarkus Armbruster     bs_opts = NULL;
113718e46a03SMarkus Armbruster     if (!blk) {
113884d18f06SMarkus Armbruster         if (local_err) {
1139565f65d2SMarkus Armbruster             error_report_err(local_err);
1140b681072dSKevin Wolf         }
11412d246f01SKevin Wolf         goto fail;
1142b681072dSKevin Wolf     } else {
114384d18f06SMarkus Armbruster         assert(!local_err);
11442d246f01SKevin Wolf     }
11452d246f01SKevin Wolf 
114626f8b3a8SMarkus Armbruster     /* Create legacy DriveInfo */
114726f8b3a8SMarkus Armbruster     dinfo = g_malloc0(sizeof(*dinfo));
1148f298d071SKevin Wolf     dinfo->opts = all_opts;
11492d246f01SKevin Wolf 
1150b41a7338SKevin Wolf     dinfo->cyls = cyls;
1151b41a7338SKevin Wolf     dinfo->heads = heads;
1152b41a7338SKevin Wolf     dinfo->secs = secs;
1153b41a7338SKevin Wolf     dinfo->trans = translation;
1154b41a7338SKevin Wolf 
1155ee13ed1cSKevin Wolf     dinfo->type = type;
115687a899c5SKevin Wolf     dinfo->bus = bus_id;
115787a899c5SKevin Wolf     dinfo->unit = unit_id;
1158394c7d4dSKevin Wolf     dinfo->devaddr = devaddr;
1159bcf83158SKevin Wolf     dinfo->serial = g_strdup(serial);
1160bcf83158SKevin Wolf 
116126f8b3a8SMarkus Armbruster     blk_set_legacy_dinfo(blk, dinfo);
116226f8b3a8SMarkus Armbruster 
1163e34ef046SKevin Wolf     switch(type) {
1164e34ef046SKevin Wolf     case IF_IDE:
1165e34ef046SKevin Wolf     case IF_SCSI:
1166e34ef046SKevin Wolf     case IF_XEN:
1167e34ef046SKevin Wolf     case IF_NONE:
1168e34ef046SKevin Wolf         dinfo->media_cd = media == MEDIA_CDROM;
1169e34ef046SKevin Wolf         break;
1170e34ef046SKevin Wolf     default:
1171e34ef046SKevin Wolf         break;
1172e34ef046SKevin Wolf     }
1173e34ef046SKevin Wolf 
11742d246f01SKevin Wolf fail:
117533cb7dc8SKevin Wolf     qemu_opts_del(legacy_opts);
11763cb0e25cSMarkus Armbruster     QDECREF(bs_opts);
11772d246f01SKevin Wolf     return dinfo;
117857975222SKevin Wolf }
117957975222SKevin Wolf 
1180b6c1bae5SKevin Wolf static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1181b6c1bae5SKevin Wolf {
1182b6c1bae5SKevin Wolf     BlockDriverState *bs;
1183b6c1bae5SKevin Wolf 
1184b6c1bae5SKevin Wolf     bs = bdrv_lookup_bs(name, name, errp);
1185b6c1bae5SKevin Wolf     if (bs == NULL) {
1186b6c1bae5SKevin Wolf         return NULL;
1187b6c1bae5SKevin Wolf     }
1188b6c1bae5SKevin Wolf 
1189b6c1bae5SKevin Wolf     if (!bdrv_is_root_node(bs)) {
1190b6c1bae5SKevin Wolf         error_setg(errp, "Need a root block node");
1191b6c1bae5SKevin Wolf         return NULL;
1192b6c1bae5SKevin Wolf     }
1193b6c1bae5SKevin Wolf 
1194b6c1bae5SKevin Wolf     if (!bdrv_is_inserted(bs)) {
1195b6c1bae5SKevin Wolf         error_setg(errp, "Device has no medium");
1196b6c1bae5SKevin Wolf         return NULL;
1197b6c1bae5SKevin Wolf     }
1198b6c1bae5SKevin Wolf 
1199b6c1bae5SKevin Wolf     return bs;
1200b6c1bae5SKevin Wolf }
1201b6c1bae5SKevin Wolf 
1202b33945cfSKevin Wolf static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1203b33945cfSKevin Wolf                                  Error **errp)
1204b33945cfSKevin Wolf {
1205b33945cfSKevin Wolf     BlockBackend *blk;
1206b33945cfSKevin Wolf 
1207b33945cfSKevin Wolf     if (!blk_name == !qdev_id) {
1208b33945cfSKevin Wolf         error_setg(errp, "Need exactly one of 'device' and 'id'");
1209b33945cfSKevin Wolf         return NULL;
1210b33945cfSKevin Wolf     }
1211b33945cfSKevin Wolf 
1212b33945cfSKevin Wolf     if (qdev_id) {
1213b33945cfSKevin Wolf         blk = blk_by_qdev_id(qdev_id, errp);
1214b33945cfSKevin Wolf     } else {
1215b33945cfSKevin Wolf         blk = blk_by_name(blk_name);
1216b33945cfSKevin Wolf         if (blk == NULL) {
1217b33945cfSKevin Wolf             error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1218b33945cfSKevin Wolf                       "Device '%s' not found", blk_name);
1219b33945cfSKevin Wolf         }
1220b33945cfSKevin Wolf     }
1221b33945cfSKevin Wolf 
1222b33945cfSKevin Wolf     return blk;
1223b33945cfSKevin Wolf }
1224b33945cfSKevin Wolf 
12253e5a50d6SMarkus Armbruster void hmp_commit(Monitor *mon, const QDict *qdict)
1226666daa68SMarkus Armbruster {
1227666daa68SMarkus Armbruster     const char *device = qdict_get_str(qdict, "device");
1228a0e8544cSFam Zheng     BlockBackend *blk;
12292d3735d3SStefan Hajnoczi     int ret;
12302d3735d3SStefan Hajnoczi 
1231e8877497SStefan Hajnoczi     if (!strcmp(device, "all")) {
1232da31d594SMax Reitz         ret = blk_commit_all();
1233e8877497SStefan Hajnoczi     } else {
123484aa0140SStefan Hajnoczi         BlockDriverState *bs;
123584aa0140SStefan Hajnoczi         AioContext *aio_context;
123684aa0140SStefan Hajnoczi 
1237a0e8544cSFam Zheng         blk = blk_by_name(device);
1238a0e8544cSFam Zheng         if (!blk) {
123958513bdeSJeff Cody             monitor_printf(mon, "Device '%s' not found\n", device);
1240ac59eb95SMarkus Armbruster             return;
12416ab4b5abSMarkus Armbruster         }
12425433c24fSMax Reitz         if (!blk_is_available(blk)) {
12435433c24fSMax Reitz             monitor_printf(mon, "Device '%s' has no medium\n", device);
12445433c24fSMax Reitz             return;
12455433c24fSMax Reitz         }
124684aa0140SStefan Hajnoczi 
124784aa0140SStefan Hajnoczi         bs = blk_bs(blk);
124884aa0140SStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
124984aa0140SStefan Hajnoczi         aio_context_acquire(aio_context);
125084aa0140SStefan Hajnoczi 
125184aa0140SStefan Hajnoczi         ret = bdrv_commit(bs);
125284aa0140SStefan Hajnoczi 
125384aa0140SStefan Hajnoczi         aio_context_release(aio_context);
12542d3735d3SStefan Hajnoczi     }
125558513bdeSJeff Cody     if (ret < 0) {
125658513bdeSJeff Cody         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
125758513bdeSJeff Cody                        strerror(-ret));
1258666daa68SMarkus Armbruster     }
1259666daa68SMarkus Armbruster }
1260666daa68SMarkus Armbruster 
126110f75907SEric Blake static void blockdev_do_action(TransactionAction *action, Error **errp)
12626cc2a415SPaolo Bonzini {
1263c8a83e85SKevin Wolf     TransactionActionList list;
12646cc2a415SPaolo Bonzini 
126510f75907SEric Blake     list.value = action;
12666cc2a415SPaolo Bonzini     list.next = NULL;
126794d16a64SJohn Snow     qmp_transaction(&list, false, NULL, errp);
12686cc2a415SPaolo Bonzini }
12696cc2a415SPaolo Bonzini 
12700901f67eSBenoît Canet void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
12710901f67eSBenoît Canet                                 bool has_node_name, const char *node_name,
12720901f67eSBenoît Canet                                 const char *snapshot_file,
12730901f67eSBenoît Canet                                 bool has_snapshot_node_name,
12740901f67eSBenoît Canet                                 const char *snapshot_node_name,
12756106e249SLuiz Capitulino                                 bool has_format, const char *format,
12760901f67eSBenoît Canet                                 bool has_mode, NewImageMode mode, Error **errp)
1277f8882568SJes Sorensen {
1278a911e6aeSAlberto Garcia     BlockdevSnapshotSync snapshot = {
12790901f67eSBenoît Canet         .has_device = has_device,
12806cc2a415SPaolo Bonzini         .device = (char *) device,
12810901f67eSBenoît Canet         .has_node_name = has_node_name,
12820901f67eSBenoît Canet         .node_name = (char *) node_name,
12836cc2a415SPaolo Bonzini         .snapshot_file = (char *) snapshot_file,
12840901f67eSBenoît Canet         .has_snapshot_node_name = has_snapshot_node_name,
12850901f67eSBenoît Canet         .snapshot_node_name = (char *) snapshot_node_name,
12866cc2a415SPaolo Bonzini         .has_format = has_format,
12876cc2a415SPaolo Bonzini         .format = (char *) format,
12886cc2a415SPaolo Bonzini         .has_mode = has_mode,
12896cc2a415SPaolo Bonzini         .mode = mode,
12906cc2a415SPaolo Bonzini     };
129110f75907SEric Blake     TransactionAction action = {
129210f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
129332bafa8fSEric Blake         .u.blockdev_snapshot_sync.data = &snapshot,
129410f75907SEric Blake     };
129510f75907SEric Blake     blockdev_do_action(&action, errp);
1296f8882568SJes Sorensen }
1297f8882568SJes Sorensen 
129843de7e2dSAlberto Garcia void qmp_blockdev_snapshot(const char *node, const char *overlay,
129943de7e2dSAlberto Garcia                            Error **errp)
130043de7e2dSAlberto Garcia {
130143de7e2dSAlberto Garcia     BlockdevSnapshot snapshot_data = {
130243de7e2dSAlberto Garcia         .node = (char *) node,
130343de7e2dSAlberto Garcia         .overlay = (char *) overlay
130443de7e2dSAlberto Garcia     };
130510f75907SEric Blake     TransactionAction action = {
130610f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
130732bafa8fSEric Blake         .u.blockdev_snapshot.data = &snapshot_data,
130810f75907SEric Blake     };
130910f75907SEric Blake     blockdev_do_action(&action, errp);
131043de7e2dSAlberto Garcia }
131143de7e2dSAlberto Garcia 
1312f323bc9eSWenchao Xia void qmp_blockdev_snapshot_internal_sync(const char *device,
1313f323bc9eSWenchao Xia                                          const char *name,
1314f323bc9eSWenchao Xia                                          Error **errp)
1315f323bc9eSWenchao Xia {
1316f323bc9eSWenchao Xia     BlockdevSnapshotInternal snapshot = {
1317f323bc9eSWenchao Xia         .device = (char *) device,
1318f323bc9eSWenchao Xia         .name = (char *) name
1319f323bc9eSWenchao Xia     };
132010f75907SEric Blake     TransactionAction action = {
132110f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
132232bafa8fSEric Blake         .u.blockdev_snapshot_internal_sync.data = &snapshot,
132310f75907SEric Blake     };
132410f75907SEric Blake     blockdev_do_action(&action, errp);
1325f323bc9eSWenchao Xia }
1326f323bc9eSWenchao Xia 
132744e3e053SWenchao Xia SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
132844e3e053SWenchao Xia                                                          bool has_id,
132944e3e053SWenchao Xia                                                          const char *id,
133044e3e053SWenchao Xia                                                          bool has_name,
133144e3e053SWenchao Xia                                                          const char *name,
133244e3e053SWenchao Xia                                                          Error **errp)
133344e3e053SWenchao Xia {
1334a0e8544cSFam Zheng     BlockDriverState *bs;
13354ef3982aSStefan Hajnoczi     AioContext *aio_context;
133644e3e053SWenchao Xia     QEMUSnapshotInfo sn;
133744e3e053SWenchao Xia     Error *local_err = NULL;
133844e3e053SWenchao Xia     SnapshotInfo *info = NULL;
133944e3e053SWenchao Xia     int ret;
134044e3e053SWenchao Xia 
13412dfb4c03SKevin Wolf     bs = qmp_get_root_bs(device, errp);
13422dfb4c03SKevin Wolf     if (!bs) {
134344e3e053SWenchao Xia         return NULL;
134444e3e053SWenchao Xia     }
13452dfb4c03SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
13465433c24fSMax Reitz     aio_context_acquire(aio_context);
134744e3e053SWenchao Xia 
134844e3e053SWenchao Xia     if (!has_id) {
134944e3e053SWenchao Xia         id = NULL;
135044e3e053SWenchao Xia     }
135144e3e053SWenchao Xia 
135244e3e053SWenchao Xia     if (!has_name) {
135344e3e053SWenchao Xia         name = NULL;
135444e3e053SWenchao Xia     }
135544e3e053SWenchao Xia 
135644e3e053SWenchao Xia     if (!id && !name) {
135744e3e053SWenchao Xia         error_setg(errp, "Name or id must be provided");
13585433c24fSMax Reitz         goto out_aio_context;
135944e3e053SWenchao Xia     }
136044e3e053SWenchao Xia 
13610b928854SStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
13620b928854SStefan Hajnoczi         goto out_aio_context;
13630b928854SStefan Hajnoczi     }
13640b928854SStefan Hajnoczi 
136544e3e053SWenchao Xia     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
136684d18f06SMarkus Armbruster     if (local_err) {
136744e3e053SWenchao Xia         error_propagate(errp, local_err);
13684ef3982aSStefan Hajnoczi         goto out_aio_context;
136944e3e053SWenchao Xia     }
137044e3e053SWenchao Xia     if (!ret) {
137144e3e053SWenchao Xia         error_setg(errp,
137244e3e053SWenchao Xia                    "Snapshot with id '%s' and name '%s' does not exist on "
137344e3e053SWenchao Xia                    "device '%s'",
137444e3e053SWenchao Xia                    STR_OR_NULL(id), STR_OR_NULL(name), device);
13754ef3982aSStefan Hajnoczi         goto out_aio_context;
137644e3e053SWenchao Xia     }
137744e3e053SWenchao Xia 
137844e3e053SWenchao Xia     bdrv_snapshot_delete(bs, id, name, &local_err);
137984d18f06SMarkus Armbruster     if (local_err) {
138044e3e053SWenchao Xia         error_propagate(errp, local_err);
13814ef3982aSStefan Hajnoczi         goto out_aio_context;
138244e3e053SWenchao Xia     }
138344e3e053SWenchao Xia 
13844ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
13854ef3982aSStefan Hajnoczi 
13865839e53bSMarkus Armbruster     info = g_new0(SnapshotInfo, 1);
138744e3e053SWenchao Xia     info->id = g_strdup(sn.id_str);
138844e3e053SWenchao Xia     info->name = g_strdup(sn.name);
138944e3e053SWenchao Xia     info->date_nsec = sn.date_nsec;
139044e3e053SWenchao Xia     info->date_sec = sn.date_sec;
139144e3e053SWenchao Xia     info->vm_state_size = sn.vm_state_size;
139244e3e053SWenchao Xia     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
139344e3e053SWenchao Xia     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
139444e3e053SWenchao Xia 
139544e3e053SWenchao Xia     return info;
13964ef3982aSStefan Hajnoczi 
13974ef3982aSStefan Hajnoczi out_aio_context:
13984ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
13994ef3982aSStefan Hajnoczi     return NULL;
140044e3e053SWenchao Xia }
14018802d1fdSJeff Cody 
1402341ebc2fSJohn Snow /**
1403341ebc2fSJohn Snow  * block_dirty_bitmap_lookup:
1404341ebc2fSJohn Snow  * Return a dirty bitmap (if present), after validating
1405341ebc2fSJohn Snow  * the node reference and bitmap names.
1406341ebc2fSJohn Snow  *
1407341ebc2fSJohn Snow  * @node: The name of the BDS node to search for bitmaps
1408341ebc2fSJohn Snow  * @name: The name of the bitmap to search for
1409341ebc2fSJohn Snow  * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1410341ebc2fSJohn Snow  * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1411341ebc2fSJohn Snow  * @errp: Output pointer for error information. Can be NULL.
1412341ebc2fSJohn Snow  *
1413341ebc2fSJohn Snow  * @return: A bitmap object on success, or NULL on failure.
1414341ebc2fSJohn Snow  */
1415341ebc2fSJohn Snow static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1416341ebc2fSJohn Snow                                                   const char *name,
1417341ebc2fSJohn Snow                                                   BlockDriverState **pbs,
1418341ebc2fSJohn Snow                                                   AioContext **paio,
1419341ebc2fSJohn Snow                                                   Error **errp)
1420341ebc2fSJohn Snow {
1421341ebc2fSJohn Snow     BlockDriverState *bs;
1422341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
1423341ebc2fSJohn Snow     AioContext *aio_context;
1424341ebc2fSJohn Snow 
1425341ebc2fSJohn Snow     if (!node) {
1426341ebc2fSJohn Snow         error_setg(errp, "Node cannot be NULL");
1427341ebc2fSJohn Snow         return NULL;
1428341ebc2fSJohn Snow     }
1429341ebc2fSJohn Snow     if (!name) {
1430341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be NULL");
1431341ebc2fSJohn Snow         return NULL;
1432341ebc2fSJohn Snow     }
1433341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, NULL);
1434341ebc2fSJohn Snow     if (!bs) {
1435341ebc2fSJohn Snow         error_setg(errp, "Node '%s' not found", node);
1436341ebc2fSJohn Snow         return NULL;
1437341ebc2fSJohn Snow     }
1438341ebc2fSJohn Snow 
1439341ebc2fSJohn Snow     aio_context = bdrv_get_aio_context(bs);
1440341ebc2fSJohn Snow     aio_context_acquire(aio_context);
1441341ebc2fSJohn Snow 
1442341ebc2fSJohn Snow     bitmap = bdrv_find_dirty_bitmap(bs, name);
1443341ebc2fSJohn Snow     if (!bitmap) {
1444341ebc2fSJohn Snow         error_setg(errp, "Dirty bitmap '%s' not found", name);
1445341ebc2fSJohn Snow         goto fail;
1446341ebc2fSJohn Snow     }
1447341ebc2fSJohn Snow 
1448341ebc2fSJohn Snow     if (pbs) {
1449341ebc2fSJohn Snow         *pbs = bs;
1450341ebc2fSJohn Snow     }
1451341ebc2fSJohn Snow     if (paio) {
1452341ebc2fSJohn Snow         *paio = aio_context;
1453341ebc2fSJohn Snow     } else {
1454341ebc2fSJohn Snow         aio_context_release(aio_context);
1455341ebc2fSJohn Snow     }
1456341ebc2fSJohn Snow 
1457341ebc2fSJohn Snow     return bitmap;
1458341ebc2fSJohn Snow 
1459341ebc2fSJohn Snow  fail:
1460341ebc2fSJohn Snow     aio_context_release(aio_context);
1461341ebc2fSJohn Snow     return NULL;
1462341ebc2fSJohn Snow }
1463341ebc2fSJohn Snow 
1464b756b9ceSStefan Hajnoczi /* New and old BlockDriverState structs for atomic group operations */
1465ba0c86a3SWenchao Xia 
146650f43f0fSJohn Snow typedef struct BlkActionState BlkActionState;
1467ba0c86a3SWenchao Xia 
146850f43f0fSJohn Snow /**
146950f43f0fSJohn Snow  * BlkActionOps:
147050f43f0fSJohn Snow  * Table of operations that define an Action.
147150f43f0fSJohn Snow  *
147250f43f0fSJohn Snow  * @instance_size: Size of state struct, in bytes.
147350f43f0fSJohn Snow  * @prepare: Prepare the work, must NOT be NULL.
147450f43f0fSJohn Snow  * @commit: Commit the changes, can be NULL.
147550f43f0fSJohn Snow  * @abort: Abort the changes on fail, can be NULL.
147650f43f0fSJohn Snow  * @clean: Clean up resources after all transaction actions have called
147750f43f0fSJohn Snow  *         commit() or abort(). Can be NULL.
147850f43f0fSJohn Snow  *
147950f43f0fSJohn Snow  * Only prepare() may fail. In a single transaction, only one of commit() or
148050f43f0fSJohn Snow  * abort() will be called. clean() will always be called if it is present.
1481ba0c86a3SWenchao Xia  */
148250f43f0fSJohn Snow typedef struct BlkActionOps {
148350f43f0fSJohn Snow     size_t instance_size;
148450f43f0fSJohn Snow     void (*prepare)(BlkActionState *common, Error **errp);
148550f43f0fSJohn Snow     void (*commit)(BlkActionState *common);
148650f43f0fSJohn Snow     void (*abort)(BlkActionState *common);
148750f43f0fSJohn Snow     void (*clean)(BlkActionState *common);
148850f43f0fSJohn Snow } BlkActionOps;
148950f43f0fSJohn Snow 
149050f43f0fSJohn Snow /**
149150f43f0fSJohn Snow  * BlkActionState:
149250f43f0fSJohn Snow  * Describes one Action's state within a Transaction.
149350f43f0fSJohn Snow  *
149450f43f0fSJohn Snow  * @action: QAPI-defined enum identifying which Action to perform.
149550f43f0fSJohn Snow  * @ops: Table of ActionOps this Action can perform.
149694d16a64SJohn Snow  * @block_job_txn: Transaction which this action belongs to.
149750f43f0fSJohn Snow  * @entry: List membership for all Actions in this Transaction.
149850f43f0fSJohn Snow  *
149950f43f0fSJohn Snow  * This structure must be arranged as first member in a subclassed type,
150050f43f0fSJohn Snow  * assuming that the compiler will also arrange it to the same offsets as the
150150f43f0fSJohn Snow  * base class.
150250f43f0fSJohn Snow  */
150350f43f0fSJohn Snow struct BlkActionState {
1504c8a83e85SKevin Wolf     TransactionAction *action;
150550f43f0fSJohn Snow     const BlkActionOps *ops;
150694d16a64SJohn Snow     BlockJobTxn *block_job_txn;
150794d16a64SJohn Snow     TransactionProperties *txn_props;
150850f43f0fSJohn Snow     QSIMPLEQ_ENTRY(BlkActionState) entry;
1509ba0c86a3SWenchao Xia };
1510ba0c86a3SWenchao Xia 
1511bbe86010SWenchao Xia /* internal snapshot private data */
1512bbe86010SWenchao Xia typedef struct InternalSnapshotState {
151350f43f0fSJohn Snow     BlkActionState common;
1514bbe86010SWenchao Xia     BlockDriverState *bs;
15155d6e96efSStefan Hajnoczi     AioContext *aio_context;
1516bbe86010SWenchao Xia     QEMUSnapshotInfo sn;
1517507306ccSFam Zheng     bool created;
1518bbe86010SWenchao Xia } InternalSnapshotState;
1519bbe86010SWenchao Xia 
152094d16a64SJohn Snow 
152194d16a64SJohn Snow static int action_check_completion_mode(BlkActionState *s, Error **errp)
152294d16a64SJohn Snow {
152394d16a64SJohn Snow     if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
152494d16a64SJohn Snow         error_setg(errp,
152594d16a64SJohn Snow                    "Action '%s' does not support Transaction property "
152694d16a64SJohn Snow                    "completion-mode = %s",
152794d16a64SJohn Snow                    TransactionActionKind_lookup[s->action->type],
152894d16a64SJohn Snow                    ActionCompletionMode_lookup[s->txn_props->completion_mode]);
152994d16a64SJohn Snow         return -1;
153094d16a64SJohn Snow     }
153194d16a64SJohn Snow     return 0;
153294d16a64SJohn Snow }
153394d16a64SJohn Snow 
153450f43f0fSJohn Snow static void internal_snapshot_prepare(BlkActionState *common,
1535bbe86010SWenchao Xia                                       Error **errp)
1536bbe86010SWenchao Xia {
1537f70edf99SMarkus Armbruster     Error *local_err = NULL;
1538bbe86010SWenchao Xia     const char *device;
1539bbe86010SWenchao Xia     const char *name;
1540bbe86010SWenchao Xia     BlockDriverState *bs;
1541bbe86010SWenchao Xia     QEMUSnapshotInfo old_sn, *sn;
1542bbe86010SWenchao Xia     bool ret;
1543bbe86010SWenchao Xia     qemu_timeval tv;
1544bbe86010SWenchao Xia     BlockdevSnapshotInternal *internal;
1545bbe86010SWenchao Xia     InternalSnapshotState *state;
1546bbe86010SWenchao Xia     int ret1;
1547bbe86010SWenchao Xia 
15486a8f9661SEric Blake     g_assert(common->action->type ==
1549bbe86010SWenchao Xia              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
155032bafa8fSEric Blake     internal = common->action->u.blockdev_snapshot_internal_sync.data;
1551bbe86010SWenchao Xia     state = DO_UPCAST(InternalSnapshotState, common, common);
1552bbe86010SWenchao Xia 
1553bbe86010SWenchao Xia     /* 1. parse input */
1554bbe86010SWenchao Xia     device = internal->device;
1555bbe86010SWenchao Xia     name = internal->name;
1556bbe86010SWenchao Xia 
1557bbe86010SWenchao Xia     /* 2. check for validation */
155894d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
155994d16a64SJohn Snow         return;
156094d16a64SJohn Snow     }
156194d16a64SJohn Snow 
156275dfd402SKevin Wolf     bs = qmp_get_root_bs(device, errp);
156375dfd402SKevin Wolf     if (!bs) {
1564bbe86010SWenchao Xia         return;
1565bbe86010SWenchao Xia     }
1566bbe86010SWenchao Xia 
15675d6e96efSStefan Hajnoczi     /* AioContext is released in .clean() */
156875dfd402SKevin Wolf     state->aio_context = bdrv_get_aio_context(bs);
15695d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
15705d6e96efSStefan Hajnoczi 
1571507306ccSFam Zheng     state->bs = bs;
1572507306ccSFam Zheng     bdrv_drained_begin(bs);
1573507306ccSFam Zheng 
15743dc7ca3cSStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
15753dc7ca3cSStefan Hajnoczi         return;
15763dc7ca3cSStefan Hajnoczi     }
15773dc7ca3cSStefan Hajnoczi 
1578bbe86010SWenchao Xia     if (bdrv_is_read_only(bs)) {
157981e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
1580bbe86010SWenchao Xia         return;
1581bbe86010SWenchao Xia     }
1582bbe86010SWenchao Xia 
1583bbe86010SWenchao Xia     if (!bdrv_can_snapshot(bs)) {
158481e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by device '%s' "
158581e5f78aSAlberto Garcia                    "does not support internal snapshots",
158681e5f78aSAlberto Garcia                    bs->drv->format_name, device);
1587bbe86010SWenchao Xia         return;
1588bbe86010SWenchao Xia     }
1589bbe86010SWenchao Xia 
1590bbe86010SWenchao Xia     if (!strlen(name)) {
1591bbe86010SWenchao Xia         error_setg(errp, "Name is empty");
1592bbe86010SWenchao Xia         return;
1593bbe86010SWenchao Xia     }
1594bbe86010SWenchao Xia 
1595bbe86010SWenchao Xia     /* check whether a snapshot with name exist */
1596f70edf99SMarkus Armbruster     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1597f70edf99SMarkus Armbruster                                             &local_err);
1598f70edf99SMarkus Armbruster     if (local_err) {
1599f70edf99SMarkus Armbruster         error_propagate(errp, local_err);
1600bbe86010SWenchao Xia         return;
1601bbe86010SWenchao Xia     } else if (ret) {
1602bbe86010SWenchao Xia         error_setg(errp,
1603bbe86010SWenchao Xia                    "Snapshot with name '%s' already exists on device '%s'",
1604bbe86010SWenchao Xia                    name, device);
1605bbe86010SWenchao Xia         return;
1606bbe86010SWenchao Xia     }
1607bbe86010SWenchao Xia 
1608bbe86010SWenchao Xia     /* 3. take the snapshot */
1609bbe86010SWenchao Xia     sn = &state->sn;
1610bbe86010SWenchao Xia     pstrcpy(sn->name, sizeof(sn->name), name);
1611bbe86010SWenchao Xia     qemu_gettimeofday(&tv);
1612bbe86010SWenchao Xia     sn->date_sec = tv.tv_sec;
1613bbe86010SWenchao Xia     sn->date_nsec = tv.tv_usec * 1000;
1614bbe86010SWenchao Xia     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1615bbe86010SWenchao Xia 
1616bbe86010SWenchao Xia     ret1 = bdrv_snapshot_create(bs, sn);
1617bbe86010SWenchao Xia     if (ret1 < 0) {
1618bbe86010SWenchao Xia         error_setg_errno(errp, -ret1,
1619bbe86010SWenchao Xia                          "Failed to create snapshot '%s' on device '%s'",
1620bbe86010SWenchao Xia                          name, device);
1621bbe86010SWenchao Xia         return;
1622bbe86010SWenchao Xia     }
1623bbe86010SWenchao Xia 
1624bbe86010SWenchao Xia     /* 4. succeed, mark a snapshot is created */
1625507306ccSFam Zheng     state->created = true;
1626bbe86010SWenchao Xia }
1627bbe86010SWenchao Xia 
162850f43f0fSJohn Snow static void internal_snapshot_abort(BlkActionState *common)
1629bbe86010SWenchao Xia {
1630bbe86010SWenchao Xia     InternalSnapshotState *state =
1631bbe86010SWenchao Xia                              DO_UPCAST(InternalSnapshotState, common, common);
1632bbe86010SWenchao Xia     BlockDriverState *bs = state->bs;
1633bbe86010SWenchao Xia     QEMUSnapshotInfo *sn = &state->sn;
1634bbe86010SWenchao Xia     Error *local_error = NULL;
1635bbe86010SWenchao Xia 
1636507306ccSFam Zheng     if (!state->created) {
1637bbe86010SWenchao Xia         return;
1638bbe86010SWenchao Xia     }
1639bbe86010SWenchao Xia 
1640bbe86010SWenchao Xia     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1641c29b77f9SMarkus Armbruster         error_reportf_err(local_error,
1642c29b77f9SMarkus Armbruster                           "Failed to delete snapshot with id '%s' and "
1643c29b77f9SMarkus Armbruster                           "name '%s' on device '%s' in abort: ",
1644c29b77f9SMarkus Armbruster                           sn->id_str, sn->name,
1645c29b77f9SMarkus Armbruster                           bdrv_get_device_name(bs));
1646bbe86010SWenchao Xia     }
1647bbe86010SWenchao Xia }
1648bbe86010SWenchao Xia 
164950f43f0fSJohn Snow static void internal_snapshot_clean(BlkActionState *common)
16505d6e96efSStefan Hajnoczi {
16515d6e96efSStefan Hajnoczi     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
16525d6e96efSStefan Hajnoczi                                              common, common);
16535d6e96efSStefan Hajnoczi 
16545d6e96efSStefan Hajnoczi     if (state->aio_context) {
1655507306ccSFam Zheng         if (state->bs) {
1656507306ccSFam Zheng             bdrv_drained_end(state->bs);
1657507306ccSFam Zheng         }
16585d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
16595d6e96efSStefan Hajnoczi     }
16605d6e96efSStefan Hajnoczi }
16615d6e96efSStefan Hajnoczi 
1662ba0c86a3SWenchao Xia /* external snapshot private data */
1663ba5d6ab6SStefan Hajnoczi typedef struct ExternalSnapshotState {
166450f43f0fSJohn Snow     BlkActionState common;
16658802d1fdSJeff Cody     BlockDriverState *old_bs;
16668802d1fdSJeff Cody     BlockDriverState *new_bs;
16675d6e96efSStefan Hajnoczi     AioContext *aio_context;
1668ba5d6ab6SStefan Hajnoczi } ExternalSnapshotState;
16698802d1fdSJeff Cody 
167050f43f0fSJohn Snow static void external_snapshot_prepare(BlkActionState *common,
16719b9877eeSWenchao Xia                                       Error **errp)
16729b9877eeSWenchao Xia {
16735b363937SMax Reitz     int flags = 0;
167443de7e2dSAlberto Garcia     QDict *options = NULL;
16759b9877eeSWenchao Xia     Error *local_err = NULL;
167643de7e2dSAlberto Garcia     /* Device and node name of the image to generate the snapshot from */
1677e2a31e87SWenchao Xia     const char *device;
16780901f67eSBenoît Canet     const char *node_name;
167943de7e2dSAlberto Garcia     /* Reference to the new image (for 'blockdev-snapshot') */
168043de7e2dSAlberto Garcia     const char *snapshot_ref;
168143de7e2dSAlberto Garcia     /* File name of the new image (for 'blockdev-snapshot-sync') */
1682e2a31e87SWenchao Xia     const char *new_image_file;
1683ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1684ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1685c8a83e85SKevin Wolf     TransactionAction *action = common->action;
16869b9877eeSWenchao Xia 
168743de7e2dSAlberto Garcia     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
168843de7e2dSAlberto Garcia      * purpose but a different set of parameters */
168943de7e2dSAlberto Garcia     switch (action->type) {
169043de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
169143de7e2dSAlberto Garcia         {
169232bafa8fSEric Blake             BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
169343de7e2dSAlberto Garcia             device = s->node;
169443de7e2dSAlberto Garcia             node_name = s->node;
169543de7e2dSAlberto Garcia             new_image_file = NULL;
169643de7e2dSAlberto Garcia             snapshot_ref = s->overlay;
1697e2a31e87SWenchao Xia         }
169843de7e2dSAlberto Garcia         break;
169943de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
170043de7e2dSAlberto Garcia         {
170132bafa8fSEric Blake             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
170243de7e2dSAlberto Garcia             device = s->has_device ? s->device : NULL;
170343de7e2dSAlberto Garcia             node_name = s->has_node_name ? s->node_name : NULL;
170443de7e2dSAlberto Garcia             new_image_file = s->snapshot_file;
170543de7e2dSAlberto Garcia             snapshot_ref = NULL;
170643de7e2dSAlberto Garcia         }
170743de7e2dSAlberto Garcia         break;
170843de7e2dSAlberto Garcia     default:
170943de7e2dSAlberto Garcia         g_assert_not_reached();
1710e2a31e87SWenchao Xia     }
1711e2a31e87SWenchao Xia 
1712e2a31e87SWenchao Xia     /* start processing */
171394d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
171494d16a64SJohn Snow         return;
171594d16a64SJohn Snow     }
171694d16a64SJohn Snow 
171743de7e2dSAlberto Garcia     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
171843de7e2dSAlberto Garcia     if (!state->old_bs) {
17199b9877eeSWenchao Xia         return;
17209b9877eeSWenchao Xia     }
17219b9877eeSWenchao Xia 
17225d6e96efSStefan Hajnoczi     /* Acquire AioContext now so any threads operating on old_bs stop */
17235d6e96efSStefan Hajnoczi     state->aio_context = bdrv_get_aio_context(state->old_bs);
17245d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
1725da763e83SFam Zheng     bdrv_drained_begin(state->old_bs);
17265d6e96efSStefan Hajnoczi 
1727ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_inserted(state->old_bs)) {
1728c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
17299b9877eeSWenchao Xia         return;
17309b9877eeSWenchao Xia     }
17319b9877eeSWenchao Xia 
17323718d8abSFam Zheng     if (bdrv_op_is_blocked(state->old_bs,
17333718d8abSFam Zheng                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
17349b9877eeSWenchao Xia         return;
17359b9877eeSWenchao Xia     }
17369b9877eeSWenchao Xia 
1737ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_read_only(state->old_bs)) {
1738ba5d6ab6SStefan Hajnoczi         if (bdrv_flush(state->old_bs)) {
1739c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_IO_ERROR);
17409b9877eeSWenchao Xia             return;
17419b9877eeSWenchao Xia         }
17429b9877eeSWenchao Xia     }
17439b9877eeSWenchao Xia 
1744212a5a8fSBenoît Canet     if (!bdrv_is_first_non_filter(state->old_bs)) {
1745c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1746f6186f49SBenoît Canet         return;
1747f6186f49SBenoît Canet     }
1748f6186f49SBenoît Canet 
174943de7e2dSAlberto Garcia     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
175032bafa8fSEric Blake         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
175143de7e2dSAlberto Garcia         const char *format = s->has_format ? s->format : "qcow2";
175243de7e2dSAlberto Garcia         enum NewImageMode mode;
175343de7e2dSAlberto Garcia         const char *snapshot_node_name =
175443de7e2dSAlberto Garcia             s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
175543de7e2dSAlberto Garcia 
175643de7e2dSAlberto Garcia         if (node_name && !snapshot_node_name) {
175743de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name missing");
175843de7e2dSAlberto Garcia             return;
175943de7e2dSAlberto Garcia         }
176043de7e2dSAlberto Garcia 
176143de7e2dSAlberto Garcia         if (snapshot_node_name &&
176243de7e2dSAlberto Garcia             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
176343de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name already in use");
176443de7e2dSAlberto Garcia             return;
176543de7e2dSAlberto Garcia         }
176643de7e2dSAlberto Garcia 
1767ba5d6ab6SStefan Hajnoczi         flags = state->old_bs->open_flags;
17684c844983SKevin Wolf         flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
17699b9877eeSWenchao Xia 
17709b9877eeSWenchao Xia         /* create new image w/backing file */
177143de7e2dSAlberto Garcia         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
17729b9877eeSWenchao Xia         if (mode != NEW_IMAGE_MODE_EXISTING) {
1773f86b8b58SKevin Wolf             int64_t size = bdrv_getlength(state->old_bs);
1774f86b8b58SKevin Wolf             if (size < 0) {
1775f86b8b58SKevin Wolf                 error_setg_errno(errp, -size, "bdrv_getlength failed");
1776f86b8b58SKevin Wolf                 return;
1777f86b8b58SKevin Wolf             }
17789b9877eeSWenchao Xia             bdrv_img_create(new_image_file, format,
1779ba5d6ab6SStefan Hajnoczi                             state->old_bs->filename,
1780ba5d6ab6SStefan Hajnoczi                             state->old_bs->drv->format_name,
1781f86b8b58SKevin Wolf                             NULL, size, flags, &local_err, false);
178284d18f06SMarkus Armbruster             if (local_err) {
17839b9877eeSWenchao Xia                 error_propagate(errp, local_err);
17849b9877eeSWenchao Xia                 return;
17859b9877eeSWenchao Xia             }
17869b9877eeSWenchao Xia         }
17879b9877eeSWenchao Xia 
17880901f67eSBenoît Canet         options = qdict_new();
178943de7e2dSAlberto Garcia         if (s->has_snapshot_node_name) {
17900901f67eSBenoît Canet             qdict_put(options, "node-name",
17910901f67eSBenoît Canet                       qstring_from_str(snapshot_node_name));
17920901f67eSBenoît Canet         }
1793e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
17940901f67eSBenoît Canet 
179543de7e2dSAlberto Garcia         flags |= BDRV_O_NO_BACKING;
179643de7e2dSAlberto Garcia     }
179743de7e2dSAlberto Garcia 
17985b363937SMax Reitz     state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
17995b363937SMax Reitz                               errp);
1800f67503e5SMax Reitz     /* We will manually add the backing_hd field to the bs later */
18015b363937SMax Reitz     if (!state->new_bs) {
180243de7e2dSAlberto Garcia         return;
180343de7e2dSAlberto Garcia     }
180443de7e2dSAlberto Garcia 
18051f0c461bSKevin Wolf     if (bdrv_has_blk(state->new_bs)) {
180643de7e2dSAlberto Garcia         error_setg(errp, "The snapshot is already in use by %s",
18071f0c461bSKevin Wolf                    bdrv_get_parent_name(state->new_bs));
180843de7e2dSAlberto Garcia         return;
180943de7e2dSAlberto Garcia     }
181043de7e2dSAlberto Garcia 
181143de7e2dSAlberto Garcia     if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
181243de7e2dSAlberto Garcia                            errp)) {
181343de7e2dSAlberto Garcia         return;
181443de7e2dSAlberto Garcia     }
181543de7e2dSAlberto Garcia 
181643de7e2dSAlberto Garcia     if (state->new_bs->backing != NULL) {
181743de7e2dSAlberto Garcia         error_setg(errp, "The snapshot already has a backing image");
181808b24cfeSAlberto Garcia         return;
181908b24cfeSAlberto Garcia     }
182008b24cfeSAlberto Garcia 
182108b24cfeSAlberto Garcia     if (!state->new_bs->drv->supports_backing) {
182208b24cfeSAlberto Garcia         error_setg(errp, "The snapshot does not support backing images");
18239b9877eeSWenchao Xia     }
18249b9877eeSWenchao Xia }
18259b9877eeSWenchao Xia 
182650f43f0fSJohn Snow static void external_snapshot_commit(BlkActionState *common)
18273b0047e8SWenchao Xia {
1828ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1829ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1830ba0c86a3SWenchao Xia 
18315d6e96efSStefan Hajnoczi     bdrv_set_aio_context(state->new_bs, state->aio_context);
18325d6e96efSStefan Hajnoczi 
1833ba5d6ab6SStefan Hajnoczi     /* This removes our old bs and adds the new bs */
1834ba5d6ab6SStefan Hajnoczi     bdrv_append(state->new_bs, state->old_bs);
18353b0047e8SWenchao Xia     /* We don't need (or want) to use the transactional
18363b0047e8SWenchao Xia      * bdrv_reopen_multiple() across all the entries at once, because we
18373b0047e8SWenchao Xia      * don't want to abort all of them if one of them fails the reopen */
18384c844983SKevin Wolf     if (!state->old_bs->copy_on_read) {
1839dd62f1caSKevin Wolf         bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
18403b0047e8SWenchao Xia                     NULL);
18413b0047e8SWenchao Xia     }
18424c844983SKevin Wolf }
18433b0047e8SWenchao Xia 
184450f43f0fSJohn Snow static void external_snapshot_abort(BlkActionState *common)
184596b86bf7SWenchao Xia {
1846ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1847ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1848ba5d6ab6SStefan Hajnoczi     if (state->new_bs) {
18494f6fd349SFam Zheng         bdrv_unref(state->new_bs);
185096b86bf7SWenchao Xia     }
1851da763e83SFam Zheng }
1852da763e83SFam Zheng 
185350f43f0fSJohn Snow static void external_snapshot_clean(BlkActionState *common)
1854da763e83SFam Zheng {
1855da763e83SFam Zheng     ExternalSnapshotState *state =
1856da763e83SFam Zheng                              DO_UPCAST(ExternalSnapshotState, common, common);
18575d6e96efSStefan Hajnoczi     if (state->aio_context) {
1858da763e83SFam Zheng         bdrv_drained_end(state->old_bs);
18595d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
18605d6e96efSStefan Hajnoczi     }
186196b86bf7SWenchao Xia }
186296b86bf7SWenchao Xia 
18633037f364SStefan Hajnoczi typedef struct DriveBackupState {
186450f43f0fSJohn Snow     BlkActionState common;
18653037f364SStefan Hajnoczi     BlockDriverState *bs;
18665d6e96efSStefan Hajnoczi     AioContext *aio_context;
18673037f364SStefan Hajnoczi     BlockJob *job;
18683037f364SStefan Hajnoczi } DriveBackupState;
18693037f364SStefan Hajnoczi 
187081206a89SPavel Butsykin static void do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
187181206a89SPavel Butsykin                             Error **errp);
187278f51fdeSJohn Snow 
187350f43f0fSJohn Snow static void drive_backup_prepare(BlkActionState *common, Error **errp)
18743037f364SStefan Hajnoczi {
18753037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1876b7e4fa22SKevin Wolf     BlockDriverState *bs;
18773037f364SStefan Hajnoczi     DriveBackup *backup;
18783037f364SStefan Hajnoczi     Error *local_err = NULL;
18793037f364SStefan Hajnoczi 
18806a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
188132bafa8fSEric Blake     backup = common->action->u.drive_backup.data;
18823037f364SStefan Hajnoczi 
1883b7e4fa22SKevin Wolf     bs = qmp_get_root_bs(backup->device, errp);
1884b7e4fa22SKevin Wolf     if (!bs) {
18851fdd4b7bSFam Zheng         return;
18861fdd4b7bSFam Zheng     }
18871fdd4b7bSFam Zheng 
18885d6e96efSStefan Hajnoczi     /* AioContext is released in .clean() */
1889b7e4fa22SKevin Wolf     state->aio_context = bdrv_get_aio_context(bs);
18905d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
1891b7e4fa22SKevin Wolf     bdrv_drained_begin(bs);
1892b7e4fa22SKevin Wolf     state->bs = bs;
18935d6e96efSStefan Hajnoczi 
189481206a89SPavel Butsykin     do_drive_backup(backup, common->block_job_txn, &local_err);
189584d18f06SMarkus Armbruster     if (local_err) {
18963037f364SStefan Hajnoczi         error_propagate(errp, local_err);
18973037f364SStefan Hajnoczi         return;
18983037f364SStefan Hajnoczi     }
18993037f364SStefan Hajnoczi 
19003037f364SStefan Hajnoczi     state->job = state->bs->job;
19013037f364SStefan Hajnoczi }
19023037f364SStefan Hajnoczi 
190350f43f0fSJohn Snow static void drive_backup_abort(BlkActionState *common)
19043037f364SStefan Hajnoczi {
19053037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
19063037f364SStefan Hajnoczi     BlockDriverState *bs = state->bs;
19073037f364SStefan Hajnoczi 
19083037f364SStefan Hajnoczi     /* Only cancel if it's the job we started */
19093037f364SStefan Hajnoczi     if (bs && bs->job && bs->job == state->job) {
19103037f364SStefan Hajnoczi         block_job_cancel_sync(bs->job);
19113037f364SStefan Hajnoczi     }
19123037f364SStefan Hajnoczi }
19133037f364SStefan Hajnoczi 
191450f43f0fSJohn Snow static void drive_backup_clean(BlkActionState *common)
19155d6e96efSStefan Hajnoczi {
19165d6e96efSStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
19175d6e96efSStefan Hajnoczi 
19185d6e96efSStefan Hajnoczi     if (state->aio_context) {
19191fdd4b7bSFam Zheng         bdrv_drained_end(state->bs);
19205d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
19215d6e96efSStefan Hajnoczi     }
19225d6e96efSStefan Hajnoczi }
19235d6e96efSStefan Hajnoczi 
1924bd8baecdSFam Zheng typedef struct BlockdevBackupState {
192550f43f0fSJohn Snow     BlkActionState common;
1926bd8baecdSFam Zheng     BlockDriverState *bs;
1927bd8baecdSFam Zheng     BlockJob *job;
1928bd8baecdSFam Zheng     AioContext *aio_context;
1929bd8baecdSFam Zheng } BlockdevBackupState;
1930bd8baecdSFam Zheng 
1931dc7a4a9eSPavel Butsykin static void do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
1932dc7a4a9eSPavel Butsykin                                Error **errp);
193378f51fdeSJohn Snow 
193450f43f0fSJohn Snow static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1935bd8baecdSFam Zheng {
1936bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1937bd8baecdSFam Zheng     BlockdevBackup *backup;
1938cef34eebSKevin Wolf     BlockDriverState *bs, *target;
1939bd8baecdSFam Zheng     Error *local_err = NULL;
1940bd8baecdSFam Zheng 
19416a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
194232bafa8fSEric Blake     backup = common->action->u.blockdev_backup.data;
1943bd8baecdSFam Zheng 
1944cef34eebSKevin Wolf     bs = qmp_get_root_bs(backup->device, errp);
1945cef34eebSKevin Wolf     if (!bs) {
1946ff52bf36SFam Zheng         return;
1947ff52bf36SFam Zheng     }
1948ff52bf36SFam Zheng 
194939d990acSKevin Wolf     target = bdrv_lookup_bs(backup->target, backup->target, errp);
19505433c24fSMax Reitz     if (!target) {
1951bd8baecdSFam Zheng         return;
1952bd8baecdSFam Zheng     }
1953bd8baecdSFam Zheng 
1954bd8baecdSFam Zheng     /* AioContext is released in .clean() */
1955cef34eebSKevin Wolf     state->aio_context = bdrv_get_aio_context(bs);
195639d990acSKevin Wolf     if (state->aio_context != bdrv_get_aio_context(target)) {
1957bd8baecdSFam Zheng         state->aio_context = NULL;
1958bd8baecdSFam Zheng         error_setg(errp, "Backup between two IO threads is not implemented");
1959bd8baecdSFam Zheng         return;
1960bd8baecdSFam Zheng     }
1961bd8baecdSFam Zheng     aio_context_acquire(state->aio_context);
1962cef34eebSKevin Wolf     state->bs = bs;
1963ff52bf36SFam Zheng     bdrv_drained_begin(state->bs);
1964bd8baecdSFam Zheng 
1965dc7a4a9eSPavel Butsykin     do_blockdev_backup(backup, common->block_job_txn, &local_err);
1966bd8baecdSFam Zheng     if (local_err) {
1967bd8baecdSFam Zheng         error_propagate(errp, local_err);
1968bd8baecdSFam Zheng         return;
1969bd8baecdSFam Zheng     }
1970bd8baecdSFam Zheng 
1971bd8baecdSFam Zheng     state->job = state->bs->job;
1972bd8baecdSFam Zheng }
1973bd8baecdSFam Zheng 
197450f43f0fSJohn Snow static void blockdev_backup_abort(BlkActionState *common)
1975bd8baecdSFam Zheng {
1976bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1977bd8baecdSFam Zheng     BlockDriverState *bs = state->bs;
1978bd8baecdSFam Zheng 
1979bd8baecdSFam Zheng     /* Only cancel if it's the job we started */
1980bd8baecdSFam Zheng     if (bs && bs->job && bs->job == state->job) {
1981bd8baecdSFam Zheng         block_job_cancel_sync(bs->job);
1982bd8baecdSFam Zheng     }
1983bd8baecdSFam Zheng }
1984bd8baecdSFam Zheng 
198550f43f0fSJohn Snow static void blockdev_backup_clean(BlkActionState *common)
1986bd8baecdSFam Zheng {
1987bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1988bd8baecdSFam Zheng 
1989bd8baecdSFam Zheng     if (state->aio_context) {
1990ff52bf36SFam Zheng         bdrv_drained_end(state->bs);
1991bd8baecdSFam Zheng         aio_context_release(state->aio_context);
1992bd8baecdSFam Zheng     }
1993bd8baecdSFam Zheng }
1994bd8baecdSFam Zheng 
1995df9a681dSFam Zheng typedef struct BlockDirtyBitmapState {
199650f43f0fSJohn Snow     BlkActionState common;
1997df9a681dSFam Zheng     BdrvDirtyBitmap *bitmap;
1998df9a681dSFam Zheng     BlockDriverState *bs;
1999df9a681dSFam Zheng     AioContext *aio_context;
2000df9a681dSFam Zheng     HBitmap *backup;
2001df9a681dSFam Zheng     bool prepared;
2002df9a681dSFam Zheng } BlockDirtyBitmapState;
2003df9a681dSFam Zheng 
200450f43f0fSJohn Snow static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2005df9a681dSFam Zheng                                            Error **errp)
2006df9a681dSFam Zheng {
2007df9a681dSFam Zheng     Error *local_err = NULL;
2008df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
2009df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2010df9a681dSFam Zheng                                              common, common);
2011df9a681dSFam Zheng 
201294d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
201394d16a64SJohn Snow         return;
201494d16a64SJohn Snow     }
201594d16a64SJohn Snow 
201632bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
2017df9a681dSFam Zheng     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2018df9a681dSFam Zheng     qmp_block_dirty_bitmap_add(action->node, action->name,
2019df9a681dSFam Zheng                                action->has_granularity, action->granularity,
2020df9a681dSFam Zheng                                &local_err);
2021df9a681dSFam Zheng 
2022df9a681dSFam Zheng     if (!local_err) {
2023df9a681dSFam Zheng         state->prepared = true;
2024df9a681dSFam Zheng     } else {
2025df9a681dSFam Zheng         error_propagate(errp, local_err);
2026df9a681dSFam Zheng     }
2027df9a681dSFam Zheng }
2028df9a681dSFam Zheng 
202950f43f0fSJohn Snow static void block_dirty_bitmap_add_abort(BlkActionState *common)
2030df9a681dSFam Zheng {
2031df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
2032df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2033df9a681dSFam Zheng                                              common, common);
2034df9a681dSFam Zheng 
203532bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
2036df9a681dSFam Zheng     /* Should not be able to fail: IF the bitmap was added via .prepare(),
2037df9a681dSFam Zheng      * then the node reference and bitmap name must have been valid.
2038df9a681dSFam Zheng      */
2039df9a681dSFam Zheng     if (state->prepared) {
2040df9a681dSFam Zheng         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2041df9a681dSFam Zheng     }
2042df9a681dSFam Zheng }
2043df9a681dSFam Zheng 
204450f43f0fSJohn Snow static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2045df9a681dSFam Zheng                                              Error **errp)
2046df9a681dSFam Zheng {
2047df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2048df9a681dSFam Zheng                                              common, common);
2049df9a681dSFam Zheng     BlockDirtyBitmap *action;
2050df9a681dSFam Zheng 
205194d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
205294d16a64SJohn Snow         return;
205394d16a64SJohn Snow     }
205494d16a64SJohn Snow 
205532bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_clear.data;
2056df9a681dSFam Zheng     state->bitmap = block_dirty_bitmap_lookup(action->node,
2057df9a681dSFam Zheng                                               action->name,
2058df9a681dSFam Zheng                                               &state->bs,
2059df9a681dSFam Zheng                                               &state->aio_context,
2060df9a681dSFam Zheng                                               errp);
2061df9a681dSFam Zheng     if (!state->bitmap) {
2062df9a681dSFam Zheng         return;
2063df9a681dSFam Zheng     }
2064df9a681dSFam Zheng 
2065df9a681dSFam Zheng     if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2066df9a681dSFam Zheng         error_setg(errp, "Cannot modify a frozen bitmap");
2067df9a681dSFam Zheng         return;
2068df9a681dSFam Zheng     } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2069df9a681dSFam Zheng         error_setg(errp, "Cannot clear a disabled bitmap");
2070df9a681dSFam Zheng         return;
2071df9a681dSFam Zheng     }
2072df9a681dSFam Zheng 
2073df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2074df9a681dSFam Zheng     /* AioContext is released in .clean() */
2075df9a681dSFam Zheng }
2076df9a681dSFam Zheng 
207750f43f0fSJohn Snow static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2078df9a681dSFam Zheng {
2079df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2080df9a681dSFam Zheng                                              common, common);
2081df9a681dSFam Zheng 
2082df9a681dSFam Zheng     bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2083df9a681dSFam Zheng }
2084df9a681dSFam Zheng 
208550f43f0fSJohn Snow static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2086df9a681dSFam Zheng {
2087df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2088df9a681dSFam Zheng                                              common, common);
2089df9a681dSFam Zheng 
2090df9a681dSFam Zheng     hbitmap_free(state->backup);
2091df9a681dSFam Zheng }
2092df9a681dSFam Zheng 
209350f43f0fSJohn Snow static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2094df9a681dSFam Zheng {
2095df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2096df9a681dSFam Zheng                                              common, common);
2097df9a681dSFam Zheng 
2098df9a681dSFam Zheng     if (state->aio_context) {
2099df9a681dSFam Zheng         aio_context_release(state->aio_context);
2100df9a681dSFam Zheng     }
2101df9a681dSFam Zheng }
2102df9a681dSFam Zheng 
210350f43f0fSJohn Snow static void abort_prepare(BlkActionState *common, Error **errp)
210478b18b78SStefan Hajnoczi {
210578b18b78SStefan Hajnoczi     error_setg(errp, "Transaction aborted using Abort action");
210678b18b78SStefan Hajnoczi }
210778b18b78SStefan Hajnoczi 
210850f43f0fSJohn Snow static void abort_commit(BlkActionState *common)
210978b18b78SStefan Hajnoczi {
2110dfc6f865SStefan Weil     g_assert_not_reached(); /* this action never succeeds */
211178b18b78SStefan Hajnoczi }
211278b18b78SStefan Hajnoczi 
211350f43f0fSJohn Snow static const BlkActionOps actions[] = {
211443de7e2dSAlberto Garcia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
211543de7e2dSAlberto Garcia         .instance_size = sizeof(ExternalSnapshotState),
211643de7e2dSAlberto Garcia         .prepare  = external_snapshot_prepare,
211743de7e2dSAlberto Garcia         .commit   = external_snapshot_commit,
211843de7e2dSAlberto Garcia         .abort = external_snapshot_abort,
21194ad6f3dbSAlberto Garcia         .clean = external_snapshot_clean,
212043de7e2dSAlberto Garcia     },
2121c8a83e85SKevin Wolf     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2122ba5d6ab6SStefan Hajnoczi         .instance_size = sizeof(ExternalSnapshotState),
2123ba0c86a3SWenchao Xia         .prepare  = external_snapshot_prepare,
2124ba0c86a3SWenchao Xia         .commit   = external_snapshot_commit,
2125ba0c86a3SWenchao Xia         .abort = external_snapshot_abort,
2126da763e83SFam Zheng         .clean = external_snapshot_clean,
2127ba0c86a3SWenchao Xia     },
21283037f364SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
21293037f364SStefan Hajnoczi         .instance_size = sizeof(DriveBackupState),
21303037f364SStefan Hajnoczi         .prepare = drive_backup_prepare,
21313037f364SStefan Hajnoczi         .abort = drive_backup_abort,
21325d6e96efSStefan Hajnoczi         .clean = drive_backup_clean,
21333037f364SStefan Hajnoczi     },
2134bd8baecdSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2135bd8baecdSFam Zheng         .instance_size = sizeof(BlockdevBackupState),
2136bd8baecdSFam Zheng         .prepare = blockdev_backup_prepare,
2137bd8baecdSFam Zheng         .abort = blockdev_backup_abort,
2138bd8baecdSFam Zheng         .clean = blockdev_backup_clean,
2139bd8baecdSFam Zheng     },
214078b18b78SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_ABORT] = {
214150f43f0fSJohn Snow         .instance_size = sizeof(BlkActionState),
214278b18b78SStefan Hajnoczi         .prepare = abort_prepare,
214378b18b78SStefan Hajnoczi         .commit = abort_commit,
214478b18b78SStefan Hajnoczi     },
2145bbe86010SWenchao Xia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2146bbe86010SWenchao Xia         .instance_size = sizeof(InternalSnapshotState),
2147bbe86010SWenchao Xia         .prepare  = internal_snapshot_prepare,
2148bbe86010SWenchao Xia         .abort = internal_snapshot_abort,
21495d6e96efSStefan Hajnoczi         .clean = internal_snapshot_clean,
2150bbe86010SWenchao Xia     },
2151df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2152df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2153df9a681dSFam Zheng         .prepare = block_dirty_bitmap_add_prepare,
2154df9a681dSFam Zheng         .abort = block_dirty_bitmap_add_abort,
2155df9a681dSFam Zheng     },
2156df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2157df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2158df9a681dSFam Zheng         .prepare = block_dirty_bitmap_clear_prepare,
2159df9a681dSFam Zheng         .commit = block_dirty_bitmap_clear_commit,
2160df9a681dSFam Zheng         .abort = block_dirty_bitmap_clear_abort,
2161df9a681dSFam Zheng         .clean = block_dirty_bitmap_clear_clean,
2162df9a681dSFam Zheng     }
2163ba0c86a3SWenchao Xia };
2164ba0c86a3SWenchao Xia 
216594d16a64SJohn Snow /**
216694d16a64SJohn Snow  * Allocate a TransactionProperties structure if necessary, and fill
216794d16a64SJohn Snow  * that structure with desired defaults if they are unset.
216894d16a64SJohn Snow  */
216994d16a64SJohn Snow static TransactionProperties *get_transaction_properties(
217094d16a64SJohn Snow     TransactionProperties *props)
217194d16a64SJohn Snow {
217294d16a64SJohn Snow     if (!props) {
217394d16a64SJohn Snow         props = g_new0(TransactionProperties, 1);
217494d16a64SJohn Snow     }
217594d16a64SJohn Snow 
217694d16a64SJohn Snow     if (!props->has_completion_mode) {
217794d16a64SJohn Snow         props->has_completion_mode = true;
217894d16a64SJohn Snow         props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
217994d16a64SJohn Snow     }
218094d16a64SJohn Snow 
218194d16a64SJohn Snow     return props;
218294d16a64SJohn Snow }
218394d16a64SJohn Snow 
21848802d1fdSJeff Cody /*
2185b756b9ceSStefan Hajnoczi  * 'Atomic' group operations.  The operations are performed as a set, and if
2186b756b9ceSStefan Hajnoczi  * any fail then we roll back all operations in the group.
21878802d1fdSJeff Cody  */
218894d16a64SJohn Snow void qmp_transaction(TransactionActionList *dev_list,
218994d16a64SJohn Snow                      bool has_props,
219094d16a64SJohn Snow                      struct TransactionProperties *props,
219194d16a64SJohn Snow                      Error **errp)
21928802d1fdSJeff Cody {
2193c8a83e85SKevin Wolf     TransactionActionList *dev_entry = dev_list;
219494d16a64SJohn Snow     BlockJobTxn *block_job_txn = NULL;
219550f43f0fSJohn Snow     BlkActionState *state, *next;
219643e17041SLuiz Capitulino     Error *local_err = NULL;
21978802d1fdSJeff Cody 
219850f43f0fSJohn Snow     QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
21998802d1fdSJeff Cody     QSIMPLEQ_INIT(&snap_bdrv_states);
22008802d1fdSJeff Cody 
220194d16a64SJohn Snow     /* Does this transaction get canceled as a group on failure?
220294d16a64SJohn Snow      * If not, we don't really need to make a BlockJobTxn.
220394d16a64SJohn Snow      */
220494d16a64SJohn Snow     props = get_transaction_properties(props);
220594d16a64SJohn Snow     if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
220694d16a64SJohn Snow         block_job_txn = block_job_txn_new();
220794d16a64SJohn Snow     }
220894d16a64SJohn Snow 
2209b756b9ceSStefan Hajnoczi     /* drain all i/o before any operations */
22108802d1fdSJeff Cody     bdrv_drain_all();
22118802d1fdSJeff Cody 
2212b756b9ceSStefan Hajnoczi     /* We don't do anything in this loop that commits us to the operations */
22138802d1fdSJeff Cody     while (NULL != dev_entry) {
2214c8a83e85SKevin Wolf         TransactionAction *dev_info = NULL;
221550f43f0fSJohn Snow         const BlkActionOps *ops;
221652e7c241SPaolo Bonzini 
22178802d1fdSJeff Cody         dev_info = dev_entry->value;
22188802d1fdSJeff Cody         dev_entry = dev_entry->next;
22198802d1fdSJeff Cody 
22206a8f9661SEric Blake         assert(dev_info->type < ARRAY_SIZE(actions));
2221ba0c86a3SWenchao Xia 
22226a8f9661SEric Blake         ops = &actions[dev_info->type];
2223aa3fe714SMax Reitz         assert(ops->instance_size > 0);
2224aa3fe714SMax Reitz 
2225ba5d6ab6SStefan Hajnoczi         state = g_malloc0(ops->instance_size);
2226ba5d6ab6SStefan Hajnoczi         state->ops = ops;
2227ba5d6ab6SStefan Hajnoczi         state->action = dev_info;
222894d16a64SJohn Snow         state->block_job_txn = block_job_txn;
222994d16a64SJohn Snow         state->txn_props = props;
2230ba5d6ab6SStefan Hajnoczi         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
22318802d1fdSJeff Cody 
2232ba5d6ab6SStefan Hajnoczi         state->ops->prepare(state, &local_err);
223384d18f06SMarkus Armbruster         if (local_err) {
22349b9877eeSWenchao Xia             error_propagate(errp, local_err);
22359b9877eeSWenchao Xia             goto delete_and_fail;
22369b9877eeSWenchao Xia         }
223752e7c241SPaolo Bonzini     }
22388802d1fdSJeff Cody 
2239ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2240f9ea81e8SStefan Hajnoczi         if (state->ops->commit) {
2241ba5d6ab6SStefan Hajnoczi             state->ops->commit(state);
22428802d1fdSJeff Cody         }
2243f9ea81e8SStefan Hajnoczi     }
22448802d1fdSJeff Cody 
22458802d1fdSJeff Cody     /* success */
22468802d1fdSJeff Cody     goto exit;
22478802d1fdSJeff Cody 
22488802d1fdSJeff Cody delete_and_fail:
2249b756b9ceSStefan Hajnoczi     /* failure, and it is all-or-none; roll back all operations */
2250ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2251ba5d6ab6SStefan Hajnoczi         if (state->ops->abort) {
2252ba5d6ab6SStefan Hajnoczi             state->ops->abort(state);
2253ba0c86a3SWenchao Xia         }
22548802d1fdSJeff Cody     }
22558802d1fdSJeff Cody exit:
2256ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2257ba5d6ab6SStefan Hajnoczi         if (state->ops->clean) {
2258ba5d6ab6SStefan Hajnoczi             state->ops->clean(state);
2259ba0c86a3SWenchao Xia         }
2260ba5d6ab6SStefan Hajnoczi         g_free(state);
22618802d1fdSJeff Cody     }
226294d16a64SJohn Snow     if (!has_props) {
226394d16a64SJohn Snow         qapi_free_TransactionProperties(props);
226494d16a64SJohn Snow     }
226594d16a64SJohn Snow     block_job_txn_unref(block_job_txn);
22668802d1fdSJeff Cody }
22678802d1fdSJeff Cody 
2268c245b6a3SLuiz Capitulino void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2269666daa68SMarkus Armbruster {
227038f54bd1SMax Reitz     Error *local_err = NULL;
22713a3086b7SJohn Snow     int rc;
2272666daa68SMarkus Armbruster 
22733a3086b7SJohn Snow     if (!has_force) {
22743a3086b7SJohn Snow         force = false;
22753a3086b7SJohn Snow     }
22763a3086b7SJohn Snow 
2277b33945cfSKevin Wolf     rc = do_open_tray(device, NULL, force, &local_err);
2278bf18bee5SColin Lord     if (rc && rc != -ENOSYS) {
227938f54bd1SMax Reitz         error_propagate(errp, local_err);
2280c245b6a3SLuiz Capitulino         return;
2281666daa68SMarkus Armbruster     }
2282bf18bee5SColin Lord     error_free(local_err);
22833a3086b7SJohn Snow 
2284*00949babSKevin Wolf     qmp_x_blockdev_remove_medium(true, device, false, NULL, errp);
2285666daa68SMarkus Armbruster }
2286666daa68SMarkus Armbruster 
228712d3ba82SBenoît Canet void qmp_block_passwd(bool has_device, const char *device,
228812d3ba82SBenoît Canet                       bool has_node_name, const char *node_name,
228912d3ba82SBenoît Canet                       const char *password, Error **errp)
2290666daa68SMarkus Armbruster {
229112d3ba82SBenoît Canet     Error *local_err = NULL;
2292666daa68SMarkus Armbruster     BlockDriverState *bs;
2293e3442099SStefan Hajnoczi     AioContext *aio_context;
2294666daa68SMarkus Armbruster 
229512d3ba82SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
229612d3ba82SBenoît Canet                         has_node_name ? node_name : NULL,
229712d3ba82SBenoît Canet                         &local_err);
229884d18f06SMarkus Armbruster     if (local_err) {
229912d3ba82SBenoît Canet         error_propagate(errp, local_err);
2300a4dea8a9SLuiz Capitulino         return;
2301666daa68SMarkus Armbruster     }
2302666daa68SMarkus Armbruster 
2303e3442099SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
2304e3442099SStefan Hajnoczi     aio_context_acquire(aio_context);
2305e3442099SStefan Hajnoczi 
23064d2855a3SMarkus Armbruster     bdrv_add_key(bs, password, errp);
2307666daa68SMarkus Armbruster 
2308e3442099SStefan Hajnoczi     aio_context_release(aio_context);
2309e3442099SStefan Hajnoczi }
2310e3442099SStefan Hajnoczi 
2311bf18bee5SColin Lord /*
2312bf18bee5SColin Lord  * Attempt to open the tray of @device.
2313bf18bee5SColin Lord  * If @force, ignore its tray lock.
2314bf18bee5SColin Lord  * Else, if the tray is locked, don't open it, but ask the guest to open it.
2315bf18bee5SColin Lord  * On error, store an error through @errp and return -errno.
2316bf18bee5SColin Lord  * If @device does not exist, return -ENODEV.
2317bf18bee5SColin Lord  * If it has no removable media, return -ENOTSUP.
2318bf18bee5SColin Lord  * If it has no tray, return -ENOSYS.
2319bf18bee5SColin Lord  * If the guest was asked to open the tray, return -EINPROGRESS.
2320bf18bee5SColin Lord  * Else, return 0.
23213a3086b7SJohn Snow  */
2322b33945cfSKevin Wolf static int do_open_tray(const char *blk_name, const char *qdev_id,
2323b33945cfSKevin Wolf                         bool force, Error **errp)
23247d8a9f71SMax Reitz {
23257d8a9f71SMax Reitz     BlockBackend *blk;
2326b33945cfSKevin Wolf     const char *device = qdev_id ?: blk_name;
23277d8a9f71SMax Reitz     bool locked;
23287d8a9f71SMax Reitz 
2329b33945cfSKevin Wolf     blk = qmp_get_blk(blk_name, qdev_id, errp);
23307d8a9f71SMax Reitz     if (!blk) {
23313a3086b7SJohn Snow         return -ENODEV;
23327d8a9f71SMax Reitz     }
23337d8a9f71SMax Reitz 
23347d8a9f71SMax Reitz     if (!blk_dev_has_removable_media(blk)) {
23357d8a9f71SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
23363a3086b7SJohn Snow         return -ENOTSUP;
23377d8a9f71SMax Reitz     }
23387d8a9f71SMax Reitz 
233912c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
2340bf18bee5SColin Lord         error_setg(errp, "Device '%s' does not have a tray", device);
2341bf18bee5SColin Lord         return -ENOSYS;
234212c7ec87SMax Reitz     }
234312c7ec87SMax Reitz 
23447d8a9f71SMax Reitz     if (blk_dev_is_tray_open(blk)) {
23453a3086b7SJohn Snow         return 0;
23467d8a9f71SMax Reitz     }
23477d8a9f71SMax Reitz 
23487d8a9f71SMax Reitz     locked = blk_dev_is_medium_locked(blk);
23497d8a9f71SMax Reitz     if (locked) {
23507d8a9f71SMax Reitz         blk_dev_eject_request(blk, force);
23517d8a9f71SMax Reitz     }
23527d8a9f71SMax Reitz 
23537d8a9f71SMax Reitz     if (!locked || force) {
23547d8a9f71SMax Reitz         blk_dev_change_media_cb(blk, false);
23557d8a9f71SMax Reitz     }
23563a3086b7SJohn Snow 
23573a3086b7SJohn Snow     if (locked && !force) {
2358bf18bee5SColin Lord         error_setg(errp, "Device '%s' is locked and force was not specified, "
2359bf18bee5SColin Lord                    "wait for tray to open and try again", device);
2360bf18bee5SColin Lord         return -EINPROGRESS;
23613a3086b7SJohn Snow     }
23623a3086b7SJohn Snow 
23633a3086b7SJohn Snow     return 0;
23643a3086b7SJohn Snow }
23653a3086b7SJohn Snow 
2366b33945cfSKevin Wolf void qmp_blockdev_open_tray(bool has_device, const char *device,
2367b33945cfSKevin Wolf                             bool has_id, const char *id,
2368b33945cfSKevin Wolf                             bool has_force, bool force,
23693a3086b7SJohn Snow                             Error **errp)
23703a3086b7SJohn Snow {
2371bf18bee5SColin Lord     Error *local_err = NULL;
2372bf18bee5SColin Lord     int rc;
2373bf18bee5SColin Lord 
23743a3086b7SJohn Snow     if (!has_force) {
23753a3086b7SJohn Snow         force = false;
23763a3086b7SJohn Snow     }
2377b33945cfSKevin Wolf     rc = do_open_tray(has_device ? device : NULL,
2378b33945cfSKevin Wolf                       has_id ? id : NULL,
2379b33945cfSKevin Wolf                       force, &local_err);
2380bf18bee5SColin Lord     if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2381bf18bee5SColin Lord         error_propagate(errp, local_err);
2382bf18bee5SColin Lord         return;
2383bf18bee5SColin Lord     }
2384bf18bee5SColin Lord     error_free(local_err);
23857d8a9f71SMax Reitz }
23867d8a9f71SMax Reitz 
2387b33945cfSKevin Wolf void qmp_blockdev_close_tray(bool has_device, const char *device,
2388b33945cfSKevin Wolf                              bool has_id, const char *id,
2389b33945cfSKevin Wolf                              Error **errp)
2390abaaf59dSMax Reitz {
2391abaaf59dSMax Reitz     BlockBackend *blk;
2392abaaf59dSMax Reitz 
2393b33945cfSKevin Wolf     device = has_device ? device : NULL;
2394b33945cfSKevin Wolf     id = has_id ? id : NULL;
2395b33945cfSKevin Wolf 
2396b33945cfSKevin Wolf     blk = qmp_get_blk(device, id, errp);
2397abaaf59dSMax Reitz     if (!blk) {
2398abaaf59dSMax Reitz         return;
2399abaaf59dSMax Reitz     }
2400abaaf59dSMax Reitz 
2401abaaf59dSMax Reitz     if (!blk_dev_has_removable_media(blk)) {
2402b33945cfSKevin Wolf         error_setg(errp, "Device '%s' is not removable", device ?: id);
2403abaaf59dSMax Reitz         return;
2404abaaf59dSMax Reitz     }
2405abaaf59dSMax Reitz 
240612c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
240712c7ec87SMax Reitz         /* Ignore this command on tray-less devices */
240812c7ec87SMax Reitz         return;
240912c7ec87SMax Reitz     }
241012c7ec87SMax Reitz 
2411abaaf59dSMax Reitz     if (!blk_dev_is_tray_open(blk)) {
2412abaaf59dSMax Reitz         return;
2413abaaf59dSMax Reitz     }
2414abaaf59dSMax Reitz 
2415abaaf59dSMax Reitz     blk_dev_change_media_cb(blk, true);
2416abaaf59dSMax Reitz }
2417abaaf59dSMax Reitz 
2418*00949babSKevin Wolf void qmp_x_blockdev_remove_medium(bool has_device, const char *device,
2419*00949babSKevin Wolf                                   bool has_id, const char *id, Error **errp)
24202814f672SMax Reitz {
24212814f672SMax Reitz     BlockBackend *blk;
24222814f672SMax Reitz     BlockDriverState *bs;
24232814f672SMax Reitz     AioContext *aio_context;
2424*00949babSKevin Wolf     bool has_attached_device;
24252814f672SMax Reitz 
2426*00949babSKevin Wolf     device = has_device ? device : NULL;
2427*00949babSKevin Wolf     id = has_id ? id : NULL;
2428*00949babSKevin Wolf 
2429*00949babSKevin Wolf     blk = qmp_get_blk(device, id, errp);
24302814f672SMax Reitz     if (!blk) {
24312814f672SMax Reitz         return;
24322814f672SMax Reitz     }
24332814f672SMax Reitz 
24342814f672SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
2435*00949babSKevin Wolf     has_attached_device = blk_get_attached_dev(blk);
24362814f672SMax Reitz 
2437*00949babSKevin Wolf     if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2438*00949babSKevin Wolf         error_setg(errp, "Device '%s' is not removable", device ?: id);
24392814f672SMax Reitz         return;
24402814f672SMax Reitz     }
24412814f672SMax Reitz 
2442*00949babSKevin Wolf     if (has_attached_device && blk_dev_has_tray(blk) &&
2443*00949babSKevin Wolf         !blk_dev_is_tray_open(blk))
2444*00949babSKevin Wolf     {
2445*00949babSKevin Wolf         error_setg(errp, "Tray of device '%s' is not open", device ?: id);
24462814f672SMax Reitz         return;
24472814f672SMax Reitz     }
24482814f672SMax Reitz 
24492814f672SMax Reitz     bs = blk_bs(blk);
24502814f672SMax Reitz     if (!bs) {
24512814f672SMax Reitz         return;
24522814f672SMax Reitz     }
24532814f672SMax Reitz 
24542814f672SMax Reitz     aio_context = bdrv_get_aio_context(bs);
24552814f672SMax Reitz     aio_context_acquire(aio_context);
24562814f672SMax Reitz 
24572814f672SMax Reitz     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
24582814f672SMax Reitz         goto out;
24592814f672SMax Reitz     }
24602814f672SMax Reitz 
24612814f672SMax Reitz     blk_remove_bs(blk);
24622814f672SMax Reitz 
246312c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
246412c7ec87SMax Reitz         /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
246512c7ec87SMax Reitz          * called at all); therefore, the medium needs to be ejected here.
246612c7ec87SMax Reitz          * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
246712c7ec87SMax Reitz          * value passed here (i.e. false). */
246812c7ec87SMax Reitz         blk_dev_change_media_cb(blk, false);
246912c7ec87SMax Reitz     }
247012c7ec87SMax Reitz 
24712814f672SMax Reitz out:
24722814f672SMax Reitz     aio_context_release(aio_context);
24732814f672SMax Reitz }
24742814f672SMax Reitz 
2475716df217SKevin Wolf static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2476d1299882SMax Reitz                                             BlockDriverState *bs, Error **errp)
2477d1299882SMax Reitz {
2478d1299882SMax Reitz     bool has_device;
2479d1299882SMax Reitz 
2480d1299882SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
2481d1299882SMax Reitz     has_device = blk_get_attached_dev(blk);
2482d1299882SMax Reitz 
2483d1299882SMax Reitz     if (has_device && !blk_dev_has_removable_media(blk)) {
2484716df217SKevin Wolf         error_setg(errp, "Device is not removable");
2485d1299882SMax Reitz         return;
2486d1299882SMax Reitz     }
2487d1299882SMax Reitz 
248812c7ec87SMax Reitz     if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2489716df217SKevin Wolf         error_setg(errp, "Tray of the device is not open");
2490d1299882SMax Reitz         return;
2491d1299882SMax Reitz     }
2492d1299882SMax Reitz 
2493d1299882SMax Reitz     if (blk_bs(blk)) {
2494716df217SKevin Wolf         error_setg(errp, "There already is a medium in the device");
2495d1299882SMax Reitz         return;
2496d1299882SMax Reitz     }
2497d1299882SMax Reitz 
2498d1299882SMax Reitz     blk_insert_bs(blk, bs);
2499d1299882SMax Reitz 
250012c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
250112c7ec87SMax Reitz         /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
250212c7ec87SMax Reitz          * called at all); therefore, the medium needs to be pushed into the
250312c7ec87SMax Reitz          * slot here.
250412c7ec87SMax Reitz          * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
250512c7ec87SMax Reitz          * value passed here (i.e. true). */
250612c7ec87SMax Reitz         blk_dev_change_media_cb(blk, true);
250712c7ec87SMax Reitz     }
2508d1299882SMax Reitz }
2509d1299882SMax Reitz 
2510716df217SKevin Wolf void qmp_x_blockdev_insert_medium(bool has_device, const char *device,
2511716df217SKevin Wolf                                   bool has_id, const char *id,
2512716df217SKevin Wolf                                   const char *node_name, Error **errp)
2513d1299882SMax Reitz {
2514716df217SKevin Wolf     BlockBackend *blk;
2515d1299882SMax Reitz     BlockDriverState *bs;
2516d1299882SMax Reitz 
2517716df217SKevin Wolf     blk = qmp_get_blk(has_device ? device : NULL,
2518716df217SKevin Wolf                       has_id ? id : NULL,
2519716df217SKevin Wolf                       errp);
2520716df217SKevin Wolf     if (!blk) {
2521716df217SKevin Wolf         return;
2522716df217SKevin Wolf     }
2523716df217SKevin Wolf 
2524d1299882SMax Reitz     bs = bdrv_find_node(node_name);
2525d1299882SMax Reitz     if (!bs) {
2526d1299882SMax Reitz         error_setg(errp, "Node '%s' not found", node_name);
2527d1299882SMax Reitz         return;
2528d1299882SMax Reitz     }
2529d1299882SMax Reitz 
25301f0c461bSKevin Wolf     if (bdrv_has_blk(bs)) {
2531d1299882SMax Reitz         error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
25321f0c461bSKevin Wolf                    bdrv_get_parent_name(bs));
2533d1299882SMax Reitz         return;
2534d1299882SMax Reitz     }
2535d1299882SMax Reitz 
2536716df217SKevin Wolf     qmp_blockdev_insert_anon_medium(blk, bs, errp);
2537d1299882SMax Reitz }
2538d1299882SMax Reitz 
253924fb4133SMax Reitz void qmp_blockdev_change_medium(const char *device, const char *filename,
254024fb4133SMax Reitz                                 bool has_format, const char *format,
254139ff43d9SMax Reitz                                 bool has_read_only,
254239ff43d9SMax Reitz                                 BlockdevChangeReadOnlyMode read_only,
254324fb4133SMax Reitz                                 Error **errp)
2544de2c6c05SMax Reitz {
2545de2c6c05SMax Reitz     BlockBackend *blk;
2546de2c6c05SMax Reitz     BlockDriverState *medium_bs = NULL;
25475b363937SMax Reitz     int bdrv_flags;
254838a53d50SColin Lord     int rc;
2549de2c6c05SMax Reitz     QDict *options = NULL;
2550de2c6c05SMax Reitz     Error *err = NULL;
2551de2c6c05SMax Reitz 
2552de2c6c05SMax Reitz     blk = blk_by_name(device);
2553de2c6c05SMax Reitz     if (!blk) {
2554de2c6c05SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2555de2c6c05SMax Reitz                   "Device '%s' not found", device);
2556de2c6c05SMax Reitz         goto fail;
2557de2c6c05SMax Reitz     }
2558de2c6c05SMax Reitz 
2559de2c6c05SMax Reitz     if (blk_bs(blk)) {
2560de2c6c05SMax Reitz         blk_update_root_state(blk);
2561de2c6c05SMax Reitz     }
2562de2c6c05SMax Reitz 
2563de2c6c05SMax Reitz     bdrv_flags = blk_get_open_flags_from_root_state(blk);
2564156abc2fSAlyssa Milburn     bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2565156abc2fSAlyssa Milburn         BDRV_O_PROTOCOL);
2566de2c6c05SMax Reitz 
256739ff43d9SMax Reitz     if (!has_read_only) {
256839ff43d9SMax Reitz         read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
256939ff43d9SMax Reitz     }
257039ff43d9SMax Reitz 
257139ff43d9SMax Reitz     switch (read_only) {
257239ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
257339ff43d9SMax Reitz         break;
257439ff43d9SMax Reitz 
257539ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
257639ff43d9SMax Reitz         bdrv_flags &= ~BDRV_O_RDWR;
257739ff43d9SMax Reitz         break;
257839ff43d9SMax Reitz 
257939ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
258039ff43d9SMax Reitz         bdrv_flags |= BDRV_O_RDWR;
258139ff43d9SMax Reitz         break;
258239ff43d9SMax Reitz 
258339ff43d9SMax Reitz     default:
258439ff43d9SMax Reitz         abort();
258539ff43d9SMax Reitz     }
258639ff43d9SMax Reitz 
258724fb4133SMax Reitz     if (has_format) {
2588de2c6c05SMax Reitz         options = qdict_new();
2589de2c6c05SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
2590de2c6c05SMax Reitz     }
2591de2c6c05SMax Reitz 
25925b363937SMax Reitz     medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
25935b363937SMax Reitz     if (!medium_bs) {
2594de2c6c05SMax Reitz         goto fail;
2595de2c6c05SMax Reitz     }
2596de2c6c05SMax Reitz 
2597de2c6c05SMax Reitz     bdrv_add_key(medium_bs, NULL, &err);
2598de2c6c05SMax Reitz     if (err) {
2599de2c6c05SMax Reitz         error_propagate(errp, err);
2600de2c6c05SMax Reitz         goto fail;
2601de2c6c05SMax Reitz     }
2602de2c6c05SMax Reitz 
2603b33945cfSKevin Wolf     rc = do_open_tray(device, NULL, false, &err);
260438a53d50SColin Lord     if (rc && rc != -ENOSYS) {
2605de2c6c05SMax Reitz         error_propagate(errp, err);
2606de2c6c05SMax Reitz         goto fail;
2607de2c6c05SMax Reitz     }
260838a53d50SColin Lord     error_free(err);
260938a53d50SColin Lord     err = NULL;
2610de2c6c05SMax Reitz 
2611*00949babSKevin Wolf     qmp_x_blockdev_remove_medium(true, device, false, NULL, errp);
2612de2c6c05SMax Reitz     if (err) {
2613de2c6c05SMax Reitz         error_propagate(errp, err);
2614de2c6c05SMax Reitz         goto fail;
2615de2c6c05SMax Reitz     }
2616de2c6c05SMax Reitz 
2617716df217SKevin Wolf     qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2618de2c6c05SMax Reitz     if (err) {
2619de2c6c05SMax Reitz         error_propagate(errp, err);
2620de2c6c05SMax Reitz         goto fail;
2621de2c6c05SMax Reitz     }
2622de2c6c05SMax Reitz 
2623a5614993SKevin Wolf     blk_apply_root_state(blk, medium_bs);
2624a5614993SKevin Wolf 
2625b33945cfSKevin Wolf     qmp_blockdev_close_tray(true, device, false, NULL, errp);
2626de2c6c05SMax Reitz 
2627de2c6c05SMax Reitz fail:
2628de2c6c05SMax Reitz     /* If the medium has been inserted, the device has its own reference, so
2629de2c6c05SMax Reitz      * ours must be relinquished; and if it has not been inserted successfully,
2630de2c6c05SMax Reitz      * the reference must be relinquished anyway */
2631de2c6c05SMax Reitz     bdrv_unref(medium_bs);
2632de2c6c05SMax Reitz }
2633de2c6c05SMax Reitz 
2634727f005eSZhi Yong Wu /* throttling disk I/O limits */
26354dc9397bSEric Blake void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2636727f005eSZhi Yong Wu {
2637cc0681c4SBenoît Canet     ThrottleConfig cfg;
2638727f005eSZhi Yong Wu     BlockDriverState *bs;
2639a0e8544cSFam Zheng     BlockBackend *blk;
2640b15446fdSStefan Hajnoczi     AioContext *aio_context;
2641727f005eSZhi Yong Wu 
26424dc9397bSEric Blake     blk = blk_by_name(arg->device);
2643a0e8544cSFam Zheng     if (!blk) {
264475158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
26454dc9397bSEric Blake                   "Device '%s' not found", arg->device);
264680047da5SLuiz Capitulino         return;
2647727f005eSZhi Yong Wu     }
26485433c24fSMax Reitz 
26495433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
26505433c24fSMax Reitz     aio_context_acquire(aio_context);
26515433c24fSMax Reitz 
2652a0e8544cSFam Zheng     bs = blk_bs(blk);
26535433c24fSMax Reitz     if (!bs) {
26544dc9397bSEric Blake         error_setg(errp, "Device '%s' has no medium", arg->device);
26555433c24fSMax Reitz         goto out;
26565433c24fSMax Reitz     }
2657727f005eSZhi Yong Wu 
26581588ab5dSAlberto Garcia     throttle_config_init(&cfg);
26594dc9397bSEric Blake     cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
26604dc9397bSEric Blake     cfg.buckets[THROTTLE_BPS_READ].avg  = arg->bps_rd;
26614dc9397bSEric Blake     cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2662727f005eSZhi Yong Wu 
26634dc9397bSEric Blake     cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
26644dc9397bSEric Blake     cfg.buckets[THROTTLE_OPS_READ].avg  = arg->iops_rd;
26654dc9397bSEric Blake     cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2666cc0681c4SBenoît Canet 
26674dc9397bSEric Blake     if (arg->has_bps_max) {
26684dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
26693e9fab69SBenoît Canet     }
26704dc9397bSEric Blake     if (arg->has_bps_rd_max) {
26714dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
26723e9fab69SBenoît Canet     }
26734dc9397bSEric Blake     if (arg->has_bps_wr_max) {
26744dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
26753e9fab69SBenoît Canet     }
26764dc9397bSEric Blake     if (arg->has_iops_max) {
26774dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
26783e9fab69SBenoît Canet     }
26794dc9397bSEric Blake     if (arg->has_iops_rd_max) {
26804dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
26813e9fab69SBenoît Canet     }
26824dc9397bSEric Blake     if (arg->has_iops_wr_max) {
26834dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
26843e9fab69SBenoît Canet     }
2685cc0681c4SBenoît Canet 
26864dc9397bSEric Blake     if (arg->has_bps_max_length) {
26874dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2688dce13204SAlberto Garcia     }
26894dc9397bSEric Blake     if (arg->has_bps_rd_max_length) {
26904dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2691dce13204SAlberto Garcia     }
26924dc9397bSEric Blake     if (arg->has_bps_wr_max_length) {
26934dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2694dce13204SAlberto Garcia     }
26954dc9397bSEric Blake     if (arg->has_iops_max_length) {
26964dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2697dce13204SAlberto Garcia     }
26984dc9397bSEric Blake     if (arg->has_iops_rd_max_length) {
26994dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2700dce13204SAlberto Garcia     }
27014dc9397bSEric Blake     if (arg->has_iops_wr_max_length) {
27024dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2703dce13204SAlberto Garcia     }
2704dce13204SAlberto Garcia 
27054dc9397bSEric Blake     if (arg->has_iops_size) {
27064dc9397bSEric Blake         cfg.op_size = arg->iops_size;
27072024c1dfSBenoît Canet     }
2708cc0681c4SBenoît Canet 
2709d5851089SAlberto Garcia     if (!throttle_is_valid(&cfg, errp)) {
27105433c24fSMax Reitz         goto out;
2711727f005eSZhi Yong Wu     }
2712727f005eSZhi Yong Wu 
271376f4afb4SAlberto Garcia     if (throttle_enabled(&cfg)) {
271476f4afb4SAlberto Garcia         /* Enable I/O limits if they're not enabled yet, otherwise
271576f4afb4SAlberto Garcia          * just update the throttling group. */
271697148076SKevin Wolf         if (!blk_get_public(blk)->throttle_state) {
27174dc9397bSEric Blake             blk_io_limits_enable(blk,
27184dc9397bSEric Blake                                  arg->has_group ? arg->group : arg->device);
27194dc9397bSEric Blake         } else if (arg->has_group) {
27204dc9397bSEric Blake             blk_io_limits_update_group(blk, arg->group);
2721727f005eSZhi Yong Wu         }
272276f4afb4SAlberto Garcia         /* Set the new throttling configuration */
272397148076SKevin Wolf         blk_set_io_limits(blk, &cfg);
272497148076SKevin Wolf     } else if (blk_get_public(blk)->throttle_state) {
272576f4afb4SAlberto Garcia         /* If all throttling settings are set to 0, disable I/O limits */
272697148076SKevin Wolf         blk_io_limits_disable(blk);
2727727f005eSZhi Yong Wu     }
2728b15446fdSStefan Hajnoczi 
27295433c24fSMax Reitz out:
2730b15446fdSStefan Hajnoczi     aio_context_release(aio_context);
2731727f005eSZhi Yong Wu }
2732727f005eSZhi Yong Wu 
2733341ebc2fSJohn Snow void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2734341ebc2fSJohn Snow                                 bool has_granularity, uint32_t granularity,
2735341ebc2fSJohn Snow                                 Error **errp)
2736341ebc2fSJohn Snow {
2737341ebc2fSJohn Snow     AioContext *aio_context;
2738341ebc2fSJohn Snow     BlockDriverState *bs;
2739341ebc2fSJohn Snow 
2740341ebc2fSJohn Snow     if (!name || name[0] == '\0') {
2741341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be empty");
2742341ebc2fSJohn Snow         return;
2743341ebc2fSJohn Snow     }
2744341ebc2fSJohn Snow 
2745341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, errp);
2746341ebc2fSJohn Snow     if (!bs) {
2747341ebc2fSJohn Snow         return;
2748341ebc2fSJohn Snow     }
2749341ebc2fSJohn Snow 
2750341ebc2fSJohn Snow     aio_context = bdrv_get_aio_context(bs);
2751341ebc2fSJohn Snow     aio_context_acquire(aio_context);
2752341ebc2fSJohn Snow 
2753341ebc2fSJohn Snow     if (has_granularity) {
2754341ebc2fSJohn Snow         if (granularity < 512 || !is_power_of_2(granularity)) {
2755341ebc2fSJohn Snow             error_setg(errp, "Granularity must be power of 2 "
2756341ebc2fSJohn Snow                              "and at least 512");
2757341ebc2fSJohn Snow             goto out;
2758341ebc2fSJohn Snow         }
2759341ebc2fSJohn Snow     } else {
2760341ebc2fSJohn Snow         /* Default to cluster size, if available: */
2761341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(bs);
2762341ebc2fSJohn Snow     }
2763341ebc2fSJohn Snow 
2764341ebc2fSJohn Snow     bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2765341ebc2fSJohn Snow 
2766341ebc2fSJohn Snow  out:
2767341ebc2fSJohn Snow     aio_context_release(aio_context);
2768341ebc2fSJohn Snow }
2769341ebc2fSJohn Snow 
2770341ebc2fSJohn Snow void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2771341ebc2fSJohn Snow                                    Error **errp)
2772341ebc2fSJohn Snow {
2773341ebc2fSJohn Snow     AioContext *aio_context;
2774341ebc2fSJohn Snow     BlockDriverState *bs;
2775341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
2776341ebc2fSJohn Snow 
2777341ebc2fSJohn Snow     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2778341ebc2fSJohn Snow     if (!bitmap || !bs) {
2779341ebc2fSJohn Snow         return;
2780341ebc2fSJohn Snow     }
2781341ebc2fSJohn Snow 
27829bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
27839bd2b08fSJohn Snow         error_setg(errp,
27849bd2b08fSJohn Snow                    "Bitmap '%s' is currently frozen and cannot be removed",
27859bd2b08fSJohn Snow                    name);
27869bd2b08fSJohn Snow         goto out;
27879bd2b08fSJohn Snow     }
278820dca810SJohn Snow     bdrv_dirty_bitmap_make_anon(bitmap);
2789341ebc2fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
2790341ebc2fSJohn Snow 
27919bd2b08fSJohn Snow  out:
2792341ebc2fSJohn Snow     aio_context_release(aio_context);
2793341ebc2fSJohn Snow }
2794341ebc2fSJohn Snow 
2795e74e6b78SJohn Snow /**
2796e74e6b78SJohn Snow  * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2797e74e6b78SJohn Snow  * immediately after a full backup operation.
2798e74e6b78SJohn Snow  */
2799e74e6b78SJohn Snow void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2800e74e6b78SJohn Snow                                   Error **errp)
2801e74e6b78SJohn Snow {
2802e74e6b78SJohn Snow     AioContext *aio_context;
2803e74e6b78SJohn Snow     BdrvDirtyBitmap *bitmap;
2804e74e6b78SJohn Snow     BlockDriverState *bs;
2805e74e6b78SJohn Snow 
2806e74e6b78SJohn Snow     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2807e74e6b78SJohn Snow     if (!bitmap || !bs) {
2808e74e6b78SJohn Snow         return;
2809e74e6b78SJohn Snow     }
2810e74e6b78SJohn Snow 
2811e74e6b78SJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2812e74e6b78SJohn Snow         error_setg(errp,
2813e74e6b78SJohn Snow                    "Bitmap '%s' is currently frozen and cannot be modified",
2814e74e6b78SJohn Snow                    name);
2815e74e6b78SJohn Snow         goto out;
2816e74e6b78SJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2817e74e6b78SJohn Snow         error_setg(errp,
2818e74e6b78SJohn Snow                    "Bitmap '%s' is currently disabled and cannot be cleared",
2819e74e6b78SJohn Snow                    name);
2820e74e6b78SJohn Snow         goto out;
2821e74e6b78SJohn Snow     }
2822e74e6b78SJohn Snow 
2823df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(bitmap, NULL);
2824e74e6b78SJohn Snow 
2825e74e6b78SJohn Snow  out:
2826e74e6b78SJohn Snow     aio_context_release(aio_context);
2827e74e6b78SJohn Snow }
2828e74e6b78SJohn Snow 
2829072ebe6bSMarkus Armbruster void hmp_drive_del(Monitor *mon, const QDict *qdict)
28309063f814SRyan Harper {
28319063f814SRyan Harper     const char *id = qdict_get_str(qdict, "id");
28327e7d56d9SMarkus Armbruster     BlockBackend *blk;
28339063f814SRyan Harper     BlockDriverState *bs;
28348ad4202bSStefan Hajnoczi     AioContext *aio_context;
28353718d8abSFam Zheng     Error *local_err = NULL;
28369063f814SRyan Harper 
28372073d410SKevin Wolf     bs = bdrv_find_node(id);
28382073d410SKevin Wolf     if (bs) {
28392073d410SKevin Wolf         qmp_x_blockdev_del(false, NULL, true, id, &local_err);
28402073d410SKevin Wolf         if (local_err) {
28412073d410SKevin Wolf             error_report_err(local_err);
28422073d410SKevin Wolf         }
28432073d410SKevin Wolf         return;
28442073d410SKevin Wolf     }
28452073d410SKevin Wolf 
28467e7d56d9SMarkus Armbruster     blk = blk_by_name(id);
28477e7d56d9SMarkus Armbruster     if (!blk) {
2848b1422f20SMarkus Armbruster         error_report("Device '%s' not found", id);
2849072ebe6bSMarkus Armbruster         return;
28509063f814SRyan Harper     }
28518ad4202bSStefan Hajnoczi 
285226f8b3a8SMarkus Armbruster     if (!blk_legacy_dinfo(blk)) {
285348f364ddSMarkus Armbruster         error_report("Deleting device added with blockdev-add"
285448f364ddSMarkus Armbruster                      " is not supported");
2855072ebe6bSMarkus Armbruster         return;
285648f364ddSMarkus Armbruster     }
285748f364ddSMarkus Armbruster 
28585433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
28598ad4202bSStefan Hajnoczi     aio_context_acquire(aio_context);
28608ad4202bSStefan Hajnoczi 
28615433c24fSMax Reitz     bs = blk_bs(blk);
28625433c24fSMax Reitz     if (bs) {
28633718d8abSFam Zheng         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2864565f65d2SMarkus Armbruster             error_report_err(local_err);
28658ad4202bSStefan Hajnoczi             aio_context_release(aio_context);
2866072ebe6bSMarkus Armbruster             return;
28678591675fSMarcelo Tosatti         }
28689063f814SRyan Harper 
2869938abd43SMax Reitz         blk_remove_bs(blk);
28705433c24fSMax Reitz     }
28719063f814SRyan Harper 
28727c735873SMax Reitz     /* Make the BlockBackend and the attached BlockDriverState anonymous */
2873efaa7c4eSMax Reitz     monitor_remove_blk(blk);
2874efaa7c4eSMax Reitz 
28757c735873SMax Reitz     /* If this BlockBackend has a device attached to it, its refcount will be
28767c735873SMax Reitz      * decremented when the device is removed; otherwise we have to do so here.
2877d22b2f41SRyan Harper      */
2878a7f53e26SMarkus Armbruster     if (blk_get_attached_dev(blk)) {
2879293c51a6SStefan Hajnoczi         /* Further I/O must not pause the guest */
2880373340b2SMax Reitz         blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2881293c51a6SStefan Hajnoczi                          BLOCKDEV_ON_ERROR_REPORT);
2882d22b2f41SRyan Harper     } else {
2883b9fe8a7aSMarkus Armbruster         blk_unref(blk);
2884d22b2f41SRyan Harper     }
28859063f814SRyan Harper 
28868ad4202bSStefan Hajnoczi     aio_context_release(aio_context);
28879063f814SRyan Harper }
28886d4a2b3aSChristoph Hellwig 
28893b1dbd11SBenoît Canet void qmp_block_resize(bool has_device, const char *device,
28903b1dbd11SBenoît Canet                       bool has_node_name, const char *node_name,
28913b1dbd11SBenoît Canet                       int64_t size, Error **errp)
28926d4a2b3aSChristoph Hellwig {
28933b1dbd11SBenoît Canet     Error *local_err = NULL;
28946d4a2b3aSChristoph Hellwig     BlockDriverState *bs;
2895927e0e76SStefan Hajnoczi     AioContext *aio_context;
28968732901eSKevin Wolf     int ret;
28976d4a2b3aSChristoph Hellwig 
28983b1dbd11SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
28993b1dbd11SBenoît Canet                         has_node_name ? node_name : NULL,
29003b1dbd11SBenoît Canet                         &local_err);
290184d18f06SMarkus Armbruster     if (local_err) {
29023b1dbd11SBenoît Canet         error_propagate(errp, local_err);
29033b1dbd11SBenoît Canet         return;
29043b1dbd11SBenoît Canet     }
29053b1dbd11SBenoît Canet 
2906927e0e76SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
2907927e0e76SStefan Hajnoczi     aio_context_acquire(aio_context);
2908927e0e76SStefan Hajnoczi 
29093b1dbd11SBenoît Canet     if (!bdrv_is_first_non_filter(bs)) {
2910c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2911927e0e76SStefan Hajnoczi         goto out;
29126d4a2b3aSChristoph Hellwig     }
29136d4a2b3aSChristoph Hellwig 
29146d4a2b3aSChristoph Hellwig     if (size < 0) {
2915c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2916927e0e76SStefan Hajnoczi         goto out;
29176d4a2b3aSChristoph Hellwig     }
29186d4a2b3aSChristoph Hellwig 
29199c75e168SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2920c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2921927e0e76SStefan Hajnoczi         goto out;
29229c75e168SJeff Cody     }
29239c75e168SJeff Cody 
292492b7a08dSPeter Lieven     /* complete all in-flight operations before resizing the device */
292592b7a08dSPeter Lieven     bdrv_drain_all();
292692b7a08dSPeter Lieven 
29278732901eSKevin Wolf     ret = bdrv_truncate(bs, size);
29288732901eSKevin Wolf     switch (ret) {
2929939a1cc3SStefan Hajnoczi     case 0:
2930939a1cc3SStefan Hajnoczi         break;
2931939a1cc3SStefan Hajnoczi     case -ENOMEDIUM:
2932c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2933939a1cc3SStefan Hajnoczi         break;
2934939a1cc3SStefan Hajnoczi     case -ENOTSUP:
2935c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_UNSUPPORTED);
2936939a1cc3SStefan Hajnoczi         break;
2937939a1cc3SStefan Hajnoczi     case -EACCES:
293881e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
2939939a1cc3SStefan Hajnoczi         break;
2940939a1cc3SStefan Hajnoczi     case -EBUSY:
2941c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2942939a1cc3SStefan Hajnoczi         break;
2943939a1cc3SStefan Hajnoczi     default:
29448732901eSKevin Wolf         error_setg_errno(errp, -ret, "Could not resize");
2945939a1cc3SStefan Hajnoczi         break;
29466d4a2b3aSChristoph Hellwig     }
2947927e0e76SStefan Hajnoczi 
2948927e0e76SStefan Hajnoczi out:
2949927e0e76SStefan Hajnoczi     aio_context_release(aio_context);
29506d4a2b3aSChristoph Hellwig }
295112bd451fSStefan Hajnoczi 
29529abf2dbaSJeff Cody static void block_job_cb(void *opaque, int ret)
295312bd451fSStefan Hajnoczi {
2954723c5d93SStefan Hajnoczi     /* Note that this function may be executed from another AioContext besides
2955723c5d93SStefan Hajnoczi      * the QEMU main loop.  If you need to access anything that assumes the
2956723c5d93SStefan Hajnoczi      * QEMU global mutex, use a BH or introduce a mutex.
2957723c5d93SStefan Hajnoczi      */
2958723c5d93SStefan Hajnoczi 
295912bd451fSStefan Hajnoczi     BlockDriverState *bs = opaque;
2960bcada37bSWenchao Xia     const char *msg = NULL;
296112bd451fSStefan Hajnoczi 
29629abf2dbaSJeff Cody     trace_block_job_cb(bs, bs->job, ret);
296312bd451fSStefan Hajnoczi 
296412bd451fSStefan Hajnoczi     assert(bs->job);
2965bcada37bSWenchao Xia 
296612bd451fSStefan Hajnoczi     if (ret < 0) {
2967bcada37bSWenchao Xia         msg = strerror(-ret);
296812bd451fSStefan Hajnoczi     }
296912bd451fSStefan Hajnoczi 
2970370521a1SStefan Hajnoczi     if (block_job_is_cancelled(bs->job)) {
2971bcada37bSWenchao Xia         block_job_event_cancelled(bs->job);
2972370521a1SStefan Hajnoczi     } else {
2973bcada37bSWenchao Xia         block_job_event_completed(bs->job, msg);
2974370521a1SStefan Hajnoczi     }
297512bd451fSStefan Hajnoczi }
297612bd451fSStefan Hajnoczi 
29772323322eSAlberto Garcia void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
297813d8cc51SJeff Cody                       bool has_base, const char *base,
297913d8cc51SJeff Cody                       bool has_backing_file, const char *backing_file,
298013d8cc51SJeff Cody                       bool has_speed, int64_t speed,
29811d809098SPaolo Bonzini                       bool has_on_error, BlockdevOnError on_error,
29821d809098SPaolo Bonzini                       Error **errp)
298312bd451fSStefan Hajnoczi {
298412bd451fSStefan Hajnoczi     BlockDriverState *bs;
2985c8c3080fSMarcelo Tosatti     BlockDriverState *base_bs = NULL;
2986f3e69bebSStefan Hajnoczi     AioContext *aio_context;
2987fd7f8c65SStefan Hajnoczi     Error *local_err = NULL;
298813d8cc51SJeff Cody     const char *base_name = NULL;
298912bd451fSStefan Hajnoczi 
29901d809098SPaolo Bonzini     if (!has_on_error) {
29911d809098SPaolo Bonzini         on_error = BLOCKDEV_ON_ERROR_REPORT;
29921d809098SPaolo Bonzini     }
29931d809098SPaolo Bonzini 
2994b6c1bae5SKevin Wolf     bs = qmp_get_root_bs(device, errp);
2995b6c1bae5SKevin Wolf     if (!bs) {
299612bd451fSStefan Hajnoczi         return;
299712bd451fSStefan Hajnoczi     }
299812bd451fSStefan Hajnoczi 
2999b6c1bae5SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3000f3e69bebSStefan Hajnoczi     aio_context_acquire(aio_context);
3001f3e69bebSStefan Hajnoczi 
3002628ff683SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
3003f3e69bebSStefan Hajnoczi         goto out;
3004628ff683SFam Zheng     }
3005628ff683SFam Zheng 
300613d8cc51SJeff Cody     if (has_base) {
3007c8c3080fSMarcelo Tosatti         base_bs = bdrv_find_backing_image(bs, base);
3008c8c3080fSMarcelo Tosatti         if (base_bs == NULL) {
3009c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_BASE_NOT_FOUND, base);
3010f3e69bebSStefan Hajnoczi             goto out;
301112bd451fSStefan Hajnoczi         }
3012f3e69bebSStefan Hajnoczi         assert(bdrv_get_aio_context(base_bs) == aio_context);
301313d8cc51SJeff Cody         base_name = base;
3014c8c3080fSMarcelo Tosatti     }
301512bd451fSStefan Hajnoczi 
301613d8cc51SJeff Cody     /* if we are streaming the entire chain, the result will have no backing
301713d8cc51SJeff Cody      * file, and specifying one is therefore an error */
301813d8cc51SJeff Cody     if (base_bs == NULL && has_backing_file) {
301913d8cc51SJeff Cody         error_setg(errp, "backing file specified, but streaming the "
302013d8cc51SJeff Cody                          "entire chain");
3021f3e69bebSStefan Hajnoczi         goto out;
302213d8cc51SJeff Cody     }
302313d8cc51SJeff Cody 
302413d8cc51SJeff Cody     /* backing_file string overrides base bs filename */
302513d8cc51SJeff Cody     base_name = has_backing_file ? backing_file : base_name;
302613d8cc51SJeff Cody 
30272323322eSAlberto Garcia     stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
30282323322eSAlberto Garcia                  has_speed ? speed : 0, on_error, block_job_cb, bs, &local_err);
302984d18f06SMarkus Armbruster     if (local_err) {
3030fd7f8c65SStefan Hajnoczi         error_propagate(errp, local_err);
3031f3e69bebSStefan Hajnoczi         goto out;
303212bd451fSStefan Hajnoczi     }
303312bd451fSStefan Hajnoczi 
303412bd451fSStefan Hajnoczi     trace_qmp_block_stream(bs, bs->job);
3035f3e69bebSStefan Hajnoczi 
3036f3e69bebSStefan Hajnoczi out:
3037f3e69bebSStefan Hajnoczi     aio_context_release(aio_context);
303812bd451fSStefan Hajnoczi }
30392d47c6e9SStefan Hajnoczi 
3040fd62c609SAlberto Garcia void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
30417676e2c5SJeff Cody                       bool has_base, const char *base,
30427676e2c5SJeff Cody                       bool has_top, const char *top,
304354e26900SJeff Cody                       bool has_backing_file, const char *backing_file,
3044ed61fc10SJeff Cody                       bool has_speed, int64_t speed,
3045ed61fc10SJeff Cody                       Error **errp)
3046ed61fc10SJeff Cody {
3047ed61fc10SJeff Cody     BlockDriverState *bs;
3048ed61fc10SJeff Cody     BlockDriverState *base_bs, *top_bs;
30499e85cd5cSStefan Hajnoczi     AioContext *aio_context;
3050ed61fc10SJeff Cody     Error *local_err = NULL;
3051ed61fc10SJeff Cody     /* This will be part of the QMP command, if/when the
3052ed61fc10SJeff Cody      * BlockdevOnError change for blkmirror makes it in
3053ed61fc10SJeff Cody      */
305492aa5c6dSPaolo Bonzini     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3055ed61fc10SJeff Cody 
305654504663SMax Reitz     if (!has_speed) {
305754504663SMax Reitz         speed = 0;
305854504663SMax Reitz     }
305954504663SMax Reitz 
30607676e2c5SJeff Cody     /* Important Note:
30617676e2c5SJeff Cody      *  libvirt relies on the DeviceNotFound error class in order to probe for
30627676e2c5SJeff Cody      *  live commit feature versions; for this to work, we must make sure to
30637676e2c5SJeff Cody      *  perform the device lookup before any generic errors that may occur in a
30647676e2c5SJeff Cody      *  scenario in which all optional arguments are omitted. */
30651d13b167SKevin Wolf     bs = qmp_get_root_bs(device, &local_err);
30661d13b167SKevin Wolf     if (!bs) {
30671d13b167SKevin Wolf         bs = bdrv_lookup_bs(device, device, NULL);
30681d13b167SKevin Wolf         if (!bs) {
30691d13b167SKevin Wolf             error_free(local_err);
307075158ebbSMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
307175158ebbSMarkus Armbruster                       "Device '%s' not found", device);
30721d13b167SKevin Wolf         } else {
30731d13b167SKevin Wolf             error_propagate(errp, local_err);
30741d13b167SKevin Wolf         }
3075ed61fc10SJeff Cody         return;
3076ed61fc10SJeff Cody     }
3077ed61fc10SJeff Cody 
30781d13b167SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
30799e85cd5cSStefan Hajnoczi     aio_context_acquire(aio_context);
30809e85cd5cSStefan Hajnoczi 
3081bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
30829e85cd5cSStefan Hajnoczi         goto out;
3083628ff683SFam Zheng     }
3084628ff683SFam Zheng 
3085ed61fc10SJeff Cody     /* default top_bs is the active layer */
3086ed61fc10SJeff Cody     top_bs = bs;
3087ed61fc10SJeff Cody 
30887676e2c5SJeff Cody     if (has_top && top) {
3089ed61fc10SJeff Cody         if (strcmp(bs->filename, top) != 0) {
3090ed61fc10SJeff Cody             top_bs = bdrv_find_backing_image(bs, top);
3091ed61fc10SJeff Cody         }
3092ed61fc10SJeff Cody     }
3093ed61fc10SJeff Cody 
3094ed61fc10SJeff Cody     if (top_bs == NULL) {
3095ed61fc10SJeff Cody         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
30969e85cd5cSStefan Hajnoczi         goto out;
3097ed61fc10SJeff Cody     }
3098ed61fc10SJeff Cody 
30999e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(top_bs) == aio_context);
31009e85cd5cSStefan Hajnoczi 
3101d5208c45SJeff Cody     if (has_base && base) {
3102d5208c45SJeff Cody         base_bs = bdrv_find_backing_image(top_bs, base);
3103d5208c45SJeff Cody     } else {
3104d5208c45SJeff Cody         base_bs = bdrv_find_base(top_bs);
3105d5208c45SJeff Cody     }
3106d5208c45SJeff Cody 
3107d5208c45SJeff Cody     if (base_bs == NULL) {
3108c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
31099e85cd5cSStefan Hajnoczi         goto out;
3110d5208c45SJeff Cody     }
3111d5208c45SJeff Cody 
31129e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(base_bs) == aio_context);
31139e85cd5cSStefan Hajnoczi 
3114bb00021dSFam Zheng     if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3115bb00021dSFam Zheng         goto out;
3116bb00021dSFam Zheng     }
3117bb00021dSFam Zheng 
31187676e2c5SJeff Cody     /* Do not allow attempts to commit an image into itself */
31197676e2c5SJeff Cody     if (top_bs == base_bs) {
31207676e2c5SJeff Cody         error_setg(errp, "cannot commit an image into itself");
31219e85cd5cSStefan Hajnoczi         goto out;
31227676e2c5SJeff Cody     }
31237676e2c5SJeff Cody 
312420a63d2cSFam Zheng     if (top_bs == bs) {
312554e26900SJeff Cody         if (has_backing_file) {
312654e26900SJeff Cody             error_setg(errp, "'backing-file' specified,"
312754e26900SJeff Cody                              " but 'top' is the active layer");
31289e85cd5cSStefan Hajnoczi             goto out;
312954e26900SJeff Cody         }
3130fd62c609SAlberto Garcia         commit_active_start(has_job_id ? job_id : NULL, bs, base_bs, speed,
3131b49f7eadSWen Congyang                             on_error, block_job_cb, bs, &local_err, false);
313220a63d2cSFam Zheng     } else {
3133fd62c609SAlberto Garcia         commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3134fd62c609SAlberto Garcia                      on_error, block_job_cb, bs,
313554e26900SJeff Cody                      has_backing_file ? backing_file : NULL, &local_err);
313620a63d2cSFam Zheng     }
3137ed61fc10SJeff Cody     if (local_err != NULL) {
3138ed61fc10SJeff Cody         error_propagate(errp, local_err);
31399e85cd5cSStefan Hajnoczi         goto out;
3140ed61fc10SJeff Cody     }
31419e85cd5cSStefan Hajnoczi 
31429e85cd5cSStefan Hajnoczi out:
31439e85cd5cSStefan Hajnoczi     aio_context_release(aio_context);
3144ed61fc10SJeff Cody }
3145ed61fc10SJeff Cody 
314681206a89SPavel Butsykin static void do_drive_backup(DriveBackup *backup, BlockJobTxn *txn, Error **errp)
314799a9addfSStefan Hajnoczi {
314899a9addfSStefan Hajnoczi     BlockDriverState *bs;
314999a9addfSStefan Hajnoczi     BlockDriverState *target_bs;
3150fc5d3f84SIan Main     BlockDriverState *source = NULL;
3151d58d8453SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
3152761731b1SStefan Hajnoczi     AioContext *aio_context;
3153e6641719SMax Reitz     QDict *options = NULL;
315499a9addfSStefan Hajnoczi     Error *local_err = NULL;
315599a9addfSStefan Hajnoczi     int flags;
315699a9addfSStefan Hajnoczi     int64_t size;
315799a9addfSStefan Hajnoczi 
315881206a89SPavel Butsykin     if (!backup->has_speed) {
315981206a89SPavel Butsykin         backup->speed = 0;
316099a9addfSStefan Hajnoczi     }
316181206a89SPavel Butsykin     if (!backup->has_on_source_error) {
316281206a89SPavel Butsykin         backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
316399a9addfSStefan Hajnoczi     }
316481206a89SPavel Butsykin     if (!backup->has_on_target_error) {
316581206a89SPavel Butsykin         backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
316699a9addfSStefan Hajnoczi     }
316781206a89SPavel Butsykin     if (!backup->has_mode) {
316881206a89SPavel Butsykin         backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
316981206a89SPavel Butsykin     }
317081206a89SPavel Butsykin     if (!backup->has_job_id) {
317181206a89SPavel Butsykin         backup->job_id = NULL;
317299a9addfSStefan Hajnoczi     }
317313b9414bSPavel Butsykin     if (!backup->has_compress) {
317413b9414bSPavel Butsykin         backup->compress = false;
317513b9414bSPavel Butsykin     }
317699a9addfSStefan Hajnoczi 
317781206a89SPavel Butsykin     bs = qmp_get_root_bs(backup->device, errp);
3178b7e4fa22SKevin Wolf     if (!bs) {
317999a9addfSStefan Hajnoczi         return;
318099a9addfSStefan Hajnoczi     }
318199a9addfSStefan Hajnoczi 
3182b7e4fa22SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3183761731b1SStefan Hajnoczi     aio_context_acquire(aio_context);
3184761731b1SStefan Hajnoczi 
318581206a89SPavel Butsykin     if (!backup->has_format) {
318681206a89SPavel Butsykin         backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
318781206a89SPavel Butsykin                          NULL : (char*) bs->drv->format_name;
318899a9addfSStefan Hajnoczi     }
318999a9addfSStefan Hajnoczi 
3190c29c1dd3SFam Zheng     /* Early check to avoid creating target */
31913718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3192761731b1SStefan Hajnoczi         goto out;
319399a9addfSStefan Hajnoczi     }
319499a9addfSStefan Hajnoczi 
319561de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
319699a9addfSStefan Hajnoczi 
3197fc5d3f84SIan Main     /* See if we have a backing HD we can use to create our new image
3198fc5d3f84SIan Main      * on top of. */
319981206a89SPavel Butsykin     if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3200760e0063SKevin Wolf         source = backing_bs(bs);
3201fc5d3f84SIan Main         if (!source) {
320281206a89SPavel Butsykin             backup->sync = MIRROR_SYNC_MODE_FULL;
3203fc5d3f84SIan Main         }
3204fc5d3f84SIan Main     }
320581206a89SPavel Butsykin     if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3206fc5d3f84SIan Main         source = bs;
3207fc5d3f84SIan Main     }
3208fc5d3f84SIan Main 
320999a9addfSStefan Hajnoczi     size = bdrv_getlength(bs);
321099a9addfSStefan Hajnoczi     if (size < 0) {
321199a9addfSStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
3212761731b1SStefan Hajnoczi         goto out;
321399a9addfSStefan Hajnoczi     }
321499a9addfSStefan Hajnoczi 
321581206a89SPavel Butsykin     if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
321681206a89SPavel Butsykin         assert(backup->format);
3217fc5d3f84SIan Main         if (source) {
321881206a89SPavel Butsykin             bdrv_img_create(backup->target, backup->format, source->filename,
3219fc5d3f84SIan Main                             source->drv->format_name, NULL,
3220fc5d3f84SIan Main                             size, flags, &local_err, false);
3221fc5d3f84SIan Main         } else {
322281206a89SPavel Butsykin             bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
3223fc5d3f84SIan Main                             size, flags, &local_err, false);
3224fc5d3f84SIan Main         }
322599a9addfSStefan Hajnoczi     }
322699a9addfSStefan Hajnoczi 
322784d18f06SMarkus Armbruster     if (local_err) {
322899a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3229761731b1SStefan Hajnoczi         goto out;
323099a9addfSStefan Hajnoczi     }
323199a9addfSStefan Hajnoczi 
323281206a89SPavel Butsykin     if (backup->format) {
3233e6641719SMax Reitz         options = qdict_new();
323481206a89SPavel Butsykin         qdict_put(options, "driver", qstring_from_str(backup->format));
3235e6641719SMax Reitz     }
3236e6641719SMax Reitz 
323781206a89SPavel Butsykin     target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
32385b363937SMax Reitz     if (!target_bs) {
3239761731b1SStefan Hajnoczi         goto out;
324099a9addfSStefan Hajnoczi     }
324199a9addfSStefan Hajnoczi 
3242761731b1SStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
3243761731b1SStefan Hajnoczi 
324481206a89SPavel Butsykin     if (backup->has_bitmap) {
324581206a89SPavel Butsykin         bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3246d58d8453SJohn Snow         if (!bmap) {
324781206a89SPavel Butsykin             error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
32480702d3d8SMax Reitz             bdrv_unref(target_bs);
3249d58d8453SJohn Snow             goto out;
3250d58d8453SJohn Snow         }
3251d58d8453SJohn Snow     }
3252d58d8453SJohn Snow 
325381206a89SPavel Butsykin     backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,
325413b9414bSPavel Butsykin                  bmap, backup->compress, backup->on_source_error,
325513b9414bSPavel Butsykin                  backup->on_target_error, block_job_cb, bs, txn, &local_err);
32564f6fd349SFam Zheng     bdrv_unref(target_bs);
32575c438bc6SKevin Wolf     if (local_err != NULL) {
325899a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3259761731b1SStefan Hajnoczi         goto out;
326099a9addfSStefan Hajnoczi     }
3261761731b1SStefan Hajnoczi 
3262761731b1SStefan Hajnoczi out:
3263761731b1SStefan Hajnoczi     aio_context_release(aio_context);
326499a9addfSStefan Hajnoczi }
326599a9addfSStefan Hajnoczi 
326681206a89SPavel Butsykin void qmp_drive_backup(DriveBackup *arg, Error **errp)
326778f51fdeSJohn Snow {
326881206a89SPavel Butsykin     return do_drive_backup(arg, NULL, errp);
326978f51fdeSJohn Snow }
327078f51fdeSJohn Snow 
3271c13163fbSBenoît Canet BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3272c13163fbSBenoît Canet {
3273d5a8ee60SAlberto Garcia     return bdrv_named_nodes_list(errp);
3274c13163fbSBenoît Canet }
3275c13163fbSBenoît Canet 
3276dc7a4a9eSPavel Butsykin void do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn, Error **errp)
3277c29c1dd3SFam Zheng {
3278c29c1dd3SFam Zheng     BlockDriverState *bs;
3279c29c1dd3SFam Zheng     BlockDriverState *target_bs;
3280c29c1dd3SFam Zheng     Error *local_err = NULL;
3281c29c1dd3SFam Zheng     AioContext *aio_context;
3282c29c1dd3SFam Zheng 
3283dc7a4a9eSPavel Butsykin     if (!backup->has_speed) {
3284dc7a4a9eSPavel Butsykin         backup->speed = 0;
3285c29c1dd3SFam Zheng     }
3286dc7a4a9eSPavel Butsykin     if (!backup->has_on_source_error) {
3287dc7a4a9eSPavel Butsykin         backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3288c29c1dd3SFam Zheng     }
3289dc7a4a9eSPavel Butsykin     if (!backup->has_on_target_error) {
3290dc7a4a9eSPavel Butsykin         backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3291dc7a4a9eSPavel Butsykin     }
3292dc7a4a9eSPavel Butsykin     if (!backup->has_job_id) {
3293dc7a4a9eSPavel Butsykin         backup->job_id = NULL;
3294c29c1dd3SFam Zheng     }
32953b7b1236SPavel Butsykin     if (!backup->has_compress) {
32963b7b1236SPavel Butsykin         backup->compress = false;
32973b7b1236SPavel Butsykin     }
3298c29c1dd3SFam Zheng 
3299dc7a4a9eSPavel Butsykin     bs = qmp_get_root_bs(backup->device, errp);
3300cef34eebSKevin Wolf     if (!bs) {
3301c29c1dd3SFam Zheng         return;
3302c29c1dd3SFam Zheng     }
3303c29c1dd3SFam Zheng 
3304cef34eebSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3305c29c1dd3SFam Zheng     aio_context_acquire(aio_context);
3306c29c1dd3SFam Zheng 
3307dc7a4a9eSPavel Butsykin     target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
33080d978913SFam Zheng     if (!target_bs) {
3309c29c1dd3SFam Zheng         goto out;
3310c29c1dd3SFam Zheng     }
33115433c24fSMax Reitz 
3312efd75567SFam Zheng     if (bdrv_get_aio_context(target_bs) != aio_context) {
3313efd75567SFam Zheng         if (!bdrv_has_blk(target_bs)) {
3314efd75567SFam Zheng             /* The target BDS is not attached, we can safely move it to another
3315efd75567SFam Zheng              * AioContext. */
3316c29c1dd3SFam Zheng             bdrv_set_aio_context(target_bs, aio_context);
3317efd75567SFam Zheng         } else {
3318efd75567SFam Zheng             error_setg(errp, "Target is attached to a different thread from "
3319efd75567SFam Zheng                              "source.");
3320efd75567SFam Zheng             goto out;
3321efd75567SFam Zheng         }
3322efd75567SFam Zheng     }
3323dc7a4a9eSPavel Butsykin     backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,
33243b7b1236SPavel Butsykin                  NULL, backup->compress, backup->on_source_error,
33253b7b1236SPavel Butsykin                  backup->on_target_error, block_job_cb, bs, txn, &local_err);
3326c29c1dd3SFam Zheng     if (local_err != NULL) {
3327c29c1dd3SFam Zheng         error_propagate(errp, local_err);
3328c29c1dd3SFam Zheng     }
3329c29c1dd3SFam Zheng out:
3330c29c1dd3SFam Zheng     aio_context_release(aio_context);
3331c29c1dd3SFam Zheng }
3332c29c1dd3SFam Zheng 
3333dc7a4a9eSPavel Butsykin void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
333478f51fdeSJohn Snow {
3335dc7a4a9eSPavel Butsykin     do_blockdev_backup(arg, NULL, errp);
333678f51fdeSJohn Snow }
333778f51fdeSJohn Snow 
33384193cdd7SFam Zheng /* Parameter check and block job starting for drive mirroring.
33394193cdd7SFam Zheng  * Caller should hold @device and @target's aio context (must be the same).
33404193cdd7SFam Zheng  **/
334171aa9867SAlberto Garcia static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
33424193cdd7SFam Zheng                                    BlockDriverState *target,
334309158f00SBenoît Canet                                    bool has_replaces, const char *replaces,
3344d9b902dbSPaolo Bonzini                                    enum MirrorSyncMode sync,
3345274fcceeSMax Reitz                                    BlockMirrorBackingMode backing_mode,
3346b952b558SPaolo Bonzini                                    bool has_speed, int64_t speed,
3347eee13dfeSPaolo Bonzini                                    bool has_granularity, uint32_t granularity,
334808e4ed6cSPaolo Bonzini                                    bool has_buf_size, int64_t buf_size,
33494193cdd7SFam Zheng                                    bool has_on_source_error,
33504193cdd7SFam Zheng                                    BlockdevOnError on_source_error,
33514193cdd7SFam Zheng                                    bool has_on_target_error,
33524193cdd7SFam Zheng                                    BlockdevOnError on_target_error,
33530fc9f8eaSFam Zheng                                    bool has_unmap, bool unmap,
3354b952b558SPaolo Bonzini                                    Error **errp)
3355d9b902dbSPaolo Bonzini {
3356d9b902dbSPaolo Bonzini 
3357d9b902dbSPaolo Bonzini     if (!has_speed) {
3358d9b902dbSPaolo Bonzini         speed = 0;
3359d9b902dbSPaolo Bonzini     }
3360b952b558SPaolo Bonzini     if (!has_on_source_error) {
3361b952b558SPaolo Bonzini         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3362b952b558SPaolo Bonzini     }
3363b952b558SPaolo Bonzini     if (!has_on_target_error) {
3364b952b558SPaolo Bonzini         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3365b952b558SPaolo Bonzini     }
3366eee13dfeSPaolo Bonzini     if (!has_granularity) {
3367eee13dfeSPaolo Bonzini         granularity = 0;
3368eee13dfeSPaolo Bonzini     }
336908e4ed6cSPaolo Bonzini     if (!has_buf_size) {
337048ac0a4dSWen Congyang         buf_size = 0;
337108e4ed6cSPaolo Bonzini     }
33720fc9f8eaSFam Zheng     if (!has_unmap) {
33730fc9f8eaSFam Zheng         unmap = true;
33740fc9f8eaSFam Zheng     }
337508e4ed6cSPaolo Bonzini 
3376eee13dfeSPaolo Bonzini     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3377c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
33783cbbe9fdSStefan Hajnoczi                    "a value in range [512B, 64MB]");
3379eee13dfeSPaolo Bonzini         return;
3380eee13dfeSPaolo Bonzini     }
3381eee13dfeSPaolo Bonzini     if (granularity & (granularity - 1)) {
3382c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3383c6bd8c70SMarkus Armbruster                    "power of 2");
3384eee13dfeSPaolo Bonzini         return;
3385eee13dfeSPaolo Bonzini     }
3386d9b902dbSPaolo Bonzini 
33874193cdd7SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
33884193cdd7SFam Zheng         return;
33894193cdd7SFam Zheng     }
3390e40e5027SFam Zheng     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3391e40e5027SFam Zheng         return;
3392e40e5027SFam Zheng     }
33934193cdd7SFam Zheng 
33944193cdd7SFam Zheng     if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
33954193cdd7SFam Zheng         sync = MIRROR_SYNC_MODE_FULL;
33964193cdd7SFam Zheng     }
33974193cdd7SFam Zheng 
33984193cdd7SFam Zheng     /* pass the node name to replace to mirror start since it's loose coupling
33994193cdd7SFam Zheng      * and will allow to check whether the node still exist at mirror completion
34004193cdd7SFam Zheng      */
340171aa9867SAlberto Garcia     mirror_start(job_id, bs, target,
34024193cdd7SFam Zheng                  has_replaces ? replaces : NULL,
3403274fcceeSMax Reitz                  speed, granularity, buf_size, sync, backing_mode,
34044193cdd7SFam Zheng                  on_source_error, on_target_error, unmap,
34054193cdd7SFam Zheng                  block_job_cb, bs, errp);
34064193cdd7SFam Zheng }
34074193cdd7SFam Zheng 
3408faecd40aSEric Blake void qmp_drive_mirror(DriveMirror *arg, Error **errp)
34094193cdd7SFam Zheng {
34104193cdd7SFam Zheng     BlockDriverState *bs;
34114193cdd7SFam Zheng     BlockDriverState *source, *target_bs;
34124193cdd7SFam Zheng     AioContext *aio_context;
3413274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode;
34144193cdd7SFam Zheng     Error *local_err = NULL;
34154193cdd7SFam Zheng     QDict *options = NULL;
34164193cdd7SFam Zheng     int flags;
34174193cdd7SFam Zheng     int64_t size;
3418faecd40aSEric Blake     const char *format = arg->format;
34194193cdd7SFam Zheng 
34200524e93aSKevin Wolf     bs = qmp_get_root_bs(arg->device, errp);
34210524e93aSKevin Wolf     if (!bs) {
3422d9b902dbSPaolo Bonzini         return;
3423d9b902dbSPaolo Bonzini     }
3424d9b902dbSPaolo Bonzini 
34250524e93aSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
34265a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
34275a7e7a0bSStefan Hajnoczi 
3428faecd40aSEric Blake     if (!arg->has_mode) {
3429faecd40aSEric Blake         arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
34304193cdd7SFam Zheng     }
3431d9b902dbSPaolo Bonzini 
3432faecd40aSEric Blake     if (!arg->has_format) {
3433faecd40aSEric Blake         format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3434faecd40aSEric Blake                   ? NULL : bs->drv->format_name);
3435d9b902dbSPaolo Bonzini     }
3436d9b902dbSPaolo Bonzini 
343761de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
3438760e0063SKevin Wolf     source = backing_bs(bs);
3439faecd40aSEric Blake     if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3440faecd40aSEric Blake         arg->sync = MIRROR_SYNC_MODE_FULL;
3441d9b902dbSPaolo Bonzini     }
3442faecd40aSEric Blake     if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3443117e0c82SMax Reitz         source = bs;
3444117e0c82SMax Reitz     }
3445d9b902dbSPaolo Bonzini 
3446ac3c5d83SStefan Hajnoczi     size = bdrv_getlength(bs);
3447ac3c5d83SStefan Hajnoczi     if (size < 0) {
3448ac3c5d83SStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
34495a7e7a0bSStefan Hajnoczi         goto out;
3450ac3c5d83SStefan Hajnoczi     }
3451ac3c5d83SStefan Hajnoczi 
3452faecd40aSEric Blake     if (arg->has_replaces) {
345309158f00SBenoît Canet         BlockDriverState *to_replace_bs;
34545a7e7a0bSStefan Hajnoczi         AioContext *replace_aio_context;
34555a7e7a0bSStefan Hajnoczi         int64_t replace_size;
345609158f00SBenoît Canet 
3457faecd40aSEric Blake         if (!arg->has_node_name) {
345809158f00SBenoît Canet             error_setg(errp, "a node-name must be provided when replacing a"
345909158f00SBenoît Canet                              " named node of the graph");
34605a7e7a0bSStefan Hajnoczi             goto out;
346109158f00SBenoît Canet         }
346209158f00SBenoît Canet 
3463faecd40aSEric Blake         to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
346409158f00SBenoît Canet 
346509158f00SBenoît Canet         if (!to_replace_bs) {
346609158f00SBenoît Canet             error_propagate(errp, local_err);
34675a7e7a0bSStefan Hajnoczi             goto out;
346809158f00SBenoît Canet         }
346909158f00SBenoît Canet 
34705a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
34715a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
34725a7e7a0bSStefan Hajnoczi         replace_size = bdrv_getlength(to_replace_bs);
34735a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
34745a7e7a0bSStefan Hajnoczi 
34755a7e7a0bSStefan Hajnoczi         if (size != replace_size) {
347609158f00SBenoît Canet             error_setg(errp, "cannot replace image with a mirror image of "
347709158f00SBenoît Canet                              "different size");
34785a7e7a0bSStefan Hajnoczi             goto out;
347909158f00SBenoît Canet         }
348009158f00SBenoît Canet     }
348109158f00SBenoît Canet 
3482faecd40aSEric Blake     if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3483274fcceeSMax Reitz         backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3484274fcceeSMax Reitz     } else {
3485274fcceeSMax Reitz         backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3486274fcceeSMax Reitz     }
3487274fcceeSMax Reitz 
3488faecd40aSEric Blake     if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3489faecd40aSEric Blake         && arg->mode != NEW_IMAGE_MODE_EXISTING)
349014526864SMax Reitz     {
3491d9b902dbSPaolo Bonzini         /* create new image w/o backing file */
3492e6641719SMax Reitz         assert(format);
3493faecd40aSEric Blake         bdrv_img_create(arg->target, format,
3494f382d43aSMiroslav Rezanina                         NULL, NULL, NULL, size, flags, &local_err, false);
3495d9b902dbSPaolo Bonzini     } else {
3496faecd40aSEric Blake         switch (arg->mode) {
3497d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_EXISTING:
3498d9b902dbSPaolo Bonzini             break;
3499d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3500d9b902dbSPaolo Bonzini             /* create new image with backing file */
3501faecd40aSEric Blake             bdrv_img_create(arg->target, format,
3502d9b902dbSPaolo Bonzini                             source->filename,
3503d9b902dbSPaolo Bonzini                             source->drv->format_name,
3504f382d43aSMiroslav Rezanina                             NULL, size, flags, &local_err, false);
3505d9b902dbSPaolo Bonzini             break;
3506d9b902dbSPaolo Bonzini         default:
3507d9b902dbSPaolo Bonzini             abort();
3508d9b902dbSPaolo Bonzini         }
3509d9b902dbSPaolo Bonzini     }
3510d9b902dbSPaolo Bonzini 
351184d18f06SMarkus Armbruster     if (local_err) {
3512cf8f2426SLuiz Capitulino         error_propagate(errp, local_err);
35135a7e7a0bSStefan Hajnoczi         goto out;
3514d9b902dbSPaolo Bonzini     }
3515d9b902dbSPaolo Bonzini 
35164c828dc6SBenoît Canet     options = qdict_new();
3517faecd40aSEric Blake     if (arg->has_node_name) {
3518faecd40aSEric Blake         qdict_put(options, "node-name", qstring_from_str(arg->node_name));
35194c828dc6SBenoît Canet     }
3520e6641719SMax Reitz     if (format) {
3521e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
3522e6641719SMax Reitz     }
35234c828dc6SBenoît Canet 
3524b812f671SPaolo Bonzini     /* Mirroring takes care of copy-on-write using the source's backing
3525b812f671SPaolo Bonzini      * file.
3526b812f671SPaolo Bonzini      */
3527faecd40aSEric Blake     target_bs = bdrv_open(arg->target, NULL, options,
3528faecd40aSEric Blake                           flags | BDRV_O_NO_BACKING, errp);
35295b363937SMax Reitz     if (!target_bs) {
35305a7e7a0bSStefan Hajnoczi         goto out;
3531d9b902dbSPaolo Bonzini     }
3532d9b902dbSPaolo Bonzini 
35335a7e7a0bSStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
35345a7e7a0bSStefan Hajnoczi 
3535faecd40aSEric Blake     blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3536faecd40aSEric Blake                            arg->has_replaces, arg->replaces, arg->sync,
3537faecd40aSEric Blake                            backing_mode, arg->has_speed, arg->speed,
3538faecd40aSEric Blake                            arg->has_granularity, arg->granularity,
3539faecd40aSEric Blake                            arg->has_buf_size, arg->buf_size,
3540faecd40aSEric Blake                            arg->has_on_source_error, arg->on_source_error,
3541faecd40aSEric Blake                            arg->has_on_target_error, arg->on_target_error,
3542faecd40aSEric Blake                            arg->has_unmap, arg->unmap,
35434193cdd7SFam Zheng                            &local_err);
3544e253f4b8SKevin Wolf     bdrv_unref(target_bs);
3545d9b902dbSPaolo Bonzini     error_propagate(errp, local_err);
35465a7e7a0bSStefan Hajnoczi out:
35475a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
3548d9b902dbSPaolo Bonzini }
3549d9b902dbSPaolo Bonzini 
355071aa9867SAlberto Garcia void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
355171aa9867SAlberto Garcia                          const char *device, const char *target,
3552df92562eSFam Zheng                          bool has_replaces, const char *replaces,
3553df92562eSFam Zheng                          MirrorSyncMode sync,
3554df92562eSFam Zheng                          bool has_speed, int64_t speed,
3555df92562eSFam Zheng                          bool has_granularity, uint32_t granularity,
3556df92562eSFam Zheng                          bool has_buf_size, int64_t buf_size,
3557df92562eSFam Zheng                          bool has_on_source_error,
3558df92562eSFam Zheng                          BlockdevOnError on_source_error,
3559df92562eSFam Zheng                          bool has_on_target_error,
3560df92562eSFam Zheng                          BlockdevOnError on_target_error,
3561df92562eSFam Zheng                          Error **errp)
3562df92562eSFam Zheng {
3563df92562eSFam Zheng     BlockDriverState *bs;
3564df92562eSFam Zheng     BlockDriverState *target_bs;
3565df92562eSFam Zheng     AioContext *aio_context;
3566274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3567df92562eSFam Zheng     Error *local_err = NULL;
3568df92562eSFam Zheng 
356907eec652SKevin Wolf     bs = qmp_get_root_bs(device, errp);
3570df92562eSFam Zheng     if (!bs) {
3571df92562eSFam Zheng         return;
3572df92562eSFam Zheng     }
3573df92562eSFam Zheng 
3574df92562eSFam Zheng     target_bs = bdrv_lookup_bs(target, target, errp);
3575df92562eSFam Zheng     if (!target_bs) {
3576df92562eSFam Zheng         return;
3577df92562eSFam Zheng     }
3578df92562eSFam Zheng 
3579df92562eSFam Zheng     aio_context = bdrv_get_aio_context(bs);
3580df92562eSFam Zheng     aio_context_acquire(aio_context);
3581df92562eSFam Zheng 
3582df92562eSFam Zheng     bdrv_set_aio_context(target_bs, aio_context);
3583df92562eSFam Zheng 
358471aa9867SAlberto Garcia     blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3585274fcceeSMax Reitz                            has_replaces, replaces, sync, backing_mode,
3586df92562eSFam Zheng                            has_speed, speed,
3587df92562eSFam Zheng                            has_granularity, granularity,
3588df92562eSFam Zheng                            has_buf_size, buf_size,
3589df92562eSFam Zheng                            has_on_source_error, on_source_error,
3590df92562eSFam Zheng                            has_on_target_error, on_target_error,
3591df92562eSFam Zheng                            true, true,
3592df92562eSFam Zheng                            &local_err);
3593df92562eSFam Zheng     error_propagate(errp, local_err);
3594df92562eSFam Zheng 
3595df92562eSFam Zheng     aio_context_release(aio_context);
3596df92562eSFam Zheng }
3597df92562eSFam Zheng 
35983ddf3efeSAlberto Garcia /* Get a block job using its ID and acquire its AioContext */
35993ddf3efeSAlberto Garcia static BlockJob *find_block_job(const char *id, AioContext **aio_context,
360024d6bffeSMarkus Armbruster                                 Error **errp)
36012d47c6e9SStefan Hajnoczi {
36023ddf3efeSAlberto Garcia     BlockJob *job;
36033ddf3efeSAlberto Garcia 
36043ddf3efeSAlberto Garcia     assert(id != NULL);
36052d47c6e9SStefan Hajnoczi 
36065433c24fSMax Reitz     *aio_context = NULL;
36075433c24fSMax Reitz 
36083ddf3efeSAlberto Garcia     job = block_job_get(id);
36093ddf3efeSAlberto Garcia 
36103ddf3efeSAlberto Garcia     if (!job) {
36113ddf3efeSAlberto Garcia         error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
36123ddf3efeSAlberto Garcia                   "Block job '%s' not found", id);
36133ddf3efeSAlberto Garcia         return NULL;
36142d47c6e9SStefan Hajnoczi     }
36153d948cdfSStefan Hajnoczi 
36163ddf3efeSAlberto Garcia     *aio_context = blk_get_aio_context(job->blk);
36173d948cdfSStefan Hajnoczi     aio_context_acquire(*aio_context);
36183d948cdfSStefan Hajnoczi 
36193ddf3efeSAlberto Garcia     return job;
36202d47c6e9SStefan Hajnoczi }
36212d47c6e9SStefan Hajnoczi 
3622882ec7ceSStefan Hajnoczi void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
36232d47c6e9SStefan Hajnoczi {
36243d948cdfSStefan Hajnoczi     AioContext *aio_context;
362524d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
36262d47c6e9SStefan Hajnoczi 
36272d47c6e9SStefan Hajnoczi     if (!job) {
36282d47c6e9SStefan Hajnoczi         return;
36292d47c6e9SStefan Hajnoczi     }
36302d47c6e9SStefan Hajnoczi 
3631882ec7ceSStefan Hajnoczi     block_job_set_speed(job, speed, errp);
36323d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
36332d47c6e9SStefan Hajnoczi }
3634370521a1SStefan Hajnoczi 
36356e37fb81SPaolo Bonzini void qmp_block_job_cancel(const char *device,
36366e37fb81SPaolo Bonzini                           bool has_force, bool force, Error **errp)
36376e37fb81SPaolo Bonzini {
36383d948cdfSStefan Hajnoczi     AioContext *aio_context;
363924d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
36406e37fb81SPaolo Bonzini 
36416e37fb81SPaolo Bonzini     if (!job) {
36426e37fb81SPaolo Bonzini         return;
36436e37fb81SPaolo Bonzini     }
36443d948cdfSStefan Hajnoczi 
36453d948cdfSStefan Hajnoczi     if (!has_force) {
36463d948cdfSStefan Hajnoczi         force = false;
36473d948cdfSStefan Hajnoczi     }
36483d948cdfSStefan Hajnoczi 
3649751ebd76SFam Zheng     if (job->user_paused && !force) {
3650f231b88dSCole Robinson         error_setg(errp, "The block job for device '%s' is currently paused",
3651f231b88dSCole Robinson                    device);
36523d948cdfSStefan Hajnoczi         goto out;
36536e37fb81SPaolo Bonzini     }
36546e37fb81SPaolo Bonzini 
36556e37fb81SPaolo Bonzini     trace_qmp_block_job_cancel(job);
36566e37fb81SPaolo Bonzini     block_job_cancel(job);
36573d948cdfSStefan Hajnoczi out:
36583d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
36596e37fb81SPaolo Bonzini }
36606e37fb81SPaolo Bonzini 
36616e37fb81SPaolo Bonzini void qmp_block_job_pause(const char *device, Error **errp)
3662370521a1SStefan Hajnoczi {
36633d948cdfSStefan Hajnoczi     AioContext *aio_context;
366424d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3665370521a1SStefan Hajnoczi 
3666751ebd76SFam Zheng     if (!job || job->user_paused) {
3667370521a1SStefan Hajnoczi         return;
3668370521a1SStefan Hajnoczi     }
36696e37fb81SPaolo Bonzini 
3670751ebd76SFam Zheng     job->user_paused = true;
36716e37fb81SPaolo Bonzini     trace_qmp_block_job_pause(job);
36726e37fb81SPaolo Bonzini     block_job_pause(job);
36733d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
36746e37fb81SPaolo Bonzini }
36756e37fb81SPaolo Bonzini 
36766e37fb81SPaolo Bonzini void qmp_block_job_resume(const char *device, Error **errp)
36776e37fb81SPaolo Bonzini {
36783d948cdfSStefan Hajnoczi     AioContext *aio_context;
367924d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
36806e37fb81SPaolo Bonzini 
3681751ebd76SFam Zheng     if (!job || !job->user_paused) {
36828acc72a4SPaolo Bonzini         return;
36838acc72a4SPaolo Bonzini     }
3684370521a1SStefan Hajnoczi 
3685751ebd76SFam Zheng     job->user_paused = false;
36866e37fb81SPaolo Bonzini     trace_qmp_block_job_resume(job);
368717bd51f9SStefan Hajnoczi     block_job_iostatus_reset(job);
36886e37fb81SPaolo Bonzini     block_job_resume(job);
36893d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3690370521a1SStefan Hajnoczi }
3691fb5458cdSStefan Hajnoczi 
3692aeae883bSPaolo Bonzini void qmp_block_job_complete(const char *device, Error **errp)
3693aeae883bSPaolo Bonzini {
36943d948cdfSStefan Hajnoczi     AioContext *aio_context;
369524d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3696aeae883bSPaolo Bonzini 
3697aeae883bSPaolo Bonzini     if (!job) {
3698aeae883bSPaolo Bonzini         return;
3699aeae883bSPaolo Bonzini     }
3700aeae883bSPaolo Bonzini 
3701aeae883bSPaolo Bonzini     trace_qmp_block_job_complete(job);
3702aeae883bSPaolo Bonzini     block_job_complete(job, errp);
37033d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3704aeae883bSPaolo Bonzini }
3705aeae883bSPaolo Bonzini 
3706fa40e656SJeff Cody void qmp_change_backing_file(const char *device,
3707fa40e656SJeff Cody                              const char *image_node_name,
3708fa40e656SJeff Cody                              const char *backing_file,
3709fa40e656SJeff Cody                              Error **errp)
3710fa40e656SJeff Cody {
3711fa40e656SJeff Cody     BlockDriverState *bs = NULL;
3712729962f6SStefan Hajnoczi     AioContext *aio_context;
3713fa40e656SJeff Cody     BlockDriverState *image_bs = NULL;
3714fa40e656SJeff Cody     Error *local_err = NULL;
3715fa40e656SJeff Cody     bool ro;
3716fa40e656SJeff Cody     int open_flags;
3717fa40e656SJeff Cody     int ret;
3718fa40e656SJeff Cody 
37197b5dca3fSKevin Wolf     bs = qmp_get_root_bs(device, errp);
37207b5dca3fSKevin Wolf     if (!bs) {
3721fa40e656SJeff Cody         return;
3722fa40e656SJeff Cody     }
3723fa40e656SJeff Cody 
37247b5dca3fSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3725729962f6SStefan Hajnoczi     aio_context_acquire(aio_context);
3726729962f6SStefan Hajnoczi 
3727fa40e656SJeff Cody     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3728fa40e656SJeff Cody     if (local_err) {
3729fa40e656SJeff Cody         error_propagate(errp, local_err);
3730729962f6SStefan Hajnoczi         goto out;
3731fa40e656SJeff Cody     }
3732fa40e656SJeff Cody 
3733fa40e656SJeff Cody     if (!image_bs) {
3734fa40e656SJeff Cody         error_setg(errp, "image file not found");
3735729962f6SStefan Hajnoczi         goto out;
3736fa40e656SJeff Cody     }
3737fa40e656SJeff Cody 
3738fa40e656SJeff Cody     if (bdrv_find_base(image_bs) == image_bs) {
3739fa40e656SJeff Cody         error_setg(errp, "not allowing backing file change on an image "
3740fa40e656SJeff Cody                          "without a backing file");
3741729962f6SStefan Hajnoczi         goto out;
3742fa40e656SJeff Cody     }
3743fa40e656SJeff Cody 
3744fa40e656SJeff Cody     /* even though we are not necessarily operating on bs, we need it to
3745fa40e656SJeff Cody      * determine if block ops are currently prohibited on the chain */
3746fa40e656SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3747729962f6SStefan Hajnoczi         goto out;
3748fa40e656SJeff Cody     }
3749fa40e656SJeff Cody 
3750fa40e656SJeff Cody     /* final sanity check */
3751fa40e656SJeff Cody     if (!bdrv_chain_contains(bs, image_bs)) {
3752fa40e656SJeff Cody         error_setg(errp, "'%s' and image file are not in the same chain",
3753fa40e656SJeff Cody                    device);
3754729962f6SStefan Hajnoczi         goto out;
3755fa40e656SJeff Cody     }
3756fa40e656SJeff Cody 
3757fa40e656SJeff Cody     /* if not r/w, reopen to make r/w */
3758fa40e656SJeff Cody     open_flags = image_bs->open_flags;
3759fa40e656SJeff Cody     ro = bdrv_is_read_only(image_bs);
3760fa40e656SJeff Cody 
3761fa40e656SJeff Cody     if (ro) {
3762fa40e656SJeff Cody         bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3763fa40e656SJeff Cody         if (local_err) {
3764fa40e656SJeff Cody             error_propagate(errp, local_err);
3765729962f6SStefan Hajnoczi             goto out;
3766fa40e656SJeff Cody         }
3767fa40e656SJeff Cody     }
3768fa40e656SJeff Cody 
3769fa40e656SJeff Cody     ret = bdrv_change_backing_file(image_bs, backing_file,
3770fa40e656SJeff Cody                                image_bs->drv ? image_bs->drv->format_name : "");
3771fa40e656SJeff Cody 
3772fa40e656SJeff Cody     if (ret < 0) {
3773fa40e656SJeff Cody         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3774fa40e656SJeff Cody                          backing_file);
3775fa40e656SJeff Cody         /* don't exit here, so we can try to restore open flags if
3776fa40e656SJeff Cody          * appropriate */
3777fa40e656SJeff Cody     }
3778fa40e656SJeff Cody 
3779fa40e656SJeff Cody     if (ro) {
3780fa40e656SJeff Cody         bdrv_reopen(image_bs, open_flags, &local_err);
3781621ff94dSEduardo Habkost         error_propagate(errp, local_err);
3782fa40e656SJeff Cody     }
3783729962f6SStefan Hajnoczi 
3784729962f6SStefan Hajnoczi out:
3785729962f6SStefan Hajnoczi     aio_context_release(aio_context);
3786fa40e656SJeff Cody }
3787fa40e656SJeff Cody 
3788abb21ac3SKevin Wolf void hmp_drive_add_node(Monitor *mon, const char *optstr)
3789abb21ac3SKevin Wolf {
3790abb21ac3SKevin Wolf     QemuOpts *opts;
3791abb21ac3SKevin Wolf     QDict *qdict;
3792abb21ac3SKevin Wolf     Error *local_err = NULL;
3793abb21ac3SKevin Wolf 
3794abb21ac3SKevin Wolf     opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3795abb21ac3SKevin Wolf     if (!opts) {
3796abb21ac3SKevin Wolf         return;
3797abb21ac3SKevin Wolf     }
3798abb21ac3SKevin Wolf 
3799abb21ac3SKevin Wolf     qdict = qemu_opts_to_qdict(opts, NULL);
3800abb21ac3SKevin Wolf 
3801abb21ac3SKevin Wolf     if (!qdict_get_try_str(qdict, "node-name")) {
3802f8746fb8SKevin Wolf         QDECREF(qdict);
3803abb21ac3SKevin Wolf         error_report("'node-name' needs to be specified");
3804abb21ac3SKevin Wolf         goto out;
3805abb21ac3SKevin Wolf     }
3806abb21ac3SKevin Wolf 
3807abb21ac3SKevin Wolf     BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3808abb21ac3SKevin Wolf     if (!bs) {
3809abb21ac3SKevin Wolf         error_report_err(local_err);
3810abb21ac3SKevin Wolf         goto out;
3811abb21ac3SKevin Wolf     }
3812abb21ac3SKevin Wolf 
3813abb21ac3SKevin Wolf     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3814abb21ac3SKevin Wolf 
3815abb21ac3SKevin Wolf out:
3816abb21ac3SKevin Wolf     qemu_opts_del(opts);
3817abb21ac3SKevin Wolf }
3818abb21ac3SKevin Wolf 
3819d26c9a15SKevin Wolf void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3820d26c9a15SKevin Wolf {
3821be4b67bcSMax Reitz     BlockDriverState *bs;
3822be4b67bcSMax Reitz     BlockBackend *blk = NULL;
3823d26c9a15SKevin Wolf     QObject *obj;
38243b098d56SEric Blake     Visitor *v = qmp_output_visitor_new(&obj);
3825d26c9a15SKevin Wolf     QDict *qdict;
3826d26c9a15SKevin Wolf     Error *local_err = NULL;
3827d26c9a15SKevin Wolf 
382860e19e06SMarkus Armbruster     /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3829d26c9a15SKevin Wolf      * cache.direct=false instead of silently switching to aio=threads, except
383060e19e06SMarkus Armbruster      * when called from drive_new().
3831d26c9a15SKevin Wolf      *
3832d26c9a15SKevin Wolf      * For now, simply forbidding the combination for all drivers will do. */
3833d26c9a15SKevin Wolf     if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3834c6e0bd9bSKevin Wolf         bool direct = options->has_cache &&
3835c6e0bd9bSKevin Wolf                       options->cache->has_direct &&
3836c6e0bd9bSKevin Wolf                       options->cache->direct;
3837c6e0bd9bSKevin Wolf         if (!direct) {
3838d26c9a15SKevin Wolf             error_setg(errp, "aio=native requires cache.direct=true");
3839d26c9a15SKevin Wolf             goto fail;
3840d26c9a15SKevin Wolf         }
3841d26c9a15SKevin Wolf     }
3842d26c9a15SKevin Wolf 
38433b098d56SEric Blake     visit_type_BlockdevOptions(v, NULL, &options, &local_err);
384484d18f06SMarkus Armbruster     if (local_err) {
3845d26c9a15SKevin Wolf         error_propagate(errp, local_err);
3846d26c9a15SKevin Wolf         goto fail;
3847d26c9a15SKevin Wolf     }
3848d26c9a15SKevin Wolf 
38493b098d56SEric Blake     visit_complete(v, &obj);
3850d26c9a15SKevin Wolf     qdict = qobject_to_qdict(obj);
3851d26c9a15SKevin Wolf 
3852d26c9a15SKevin Wolf     qdict_flatten(qdict);
3853d26c9a15SKevin Wolf 
3854be4b67bcSMax Reitz     if (options->has_id) {
385518e46a03SMarkus Armbruster         blk = blockdev_init(NULL, qdict, &local_err);
385684d18f06SMarkus Armbruster         if (local_err) {
3857b681072dSKevin Wolf             error_propagate(errp, local_err);
3858d26c9a15SKevin Wolf             goto fail;
3859d26c9a15SKevin Wolf         }
3860d26c9a15SKevin Wolf 
3861be4b67bcSMax Reitz         bs = blk_bs(blk);
3862be4b67bcSMax Reitz     } else {
3863be4b67bcSMax Reitz         if (!qdict_get_try_str(qdict, "node-name")) {
3864be4b67bcSMax Reitz             error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3865be4b67bcSMax Reitz                        "the root node");
3866be4b67bcSMax Reitz             goto fail;
3867be4b67bcSMax Reitz         }
3868be4b67bcSMax Reitz 
3869bd745e23SMax Reitz         bs = bds_tree_init(qdict, errp);
3870bd745e23SMax Reitz         if (!bs) {
3871be4b67bcSMax Reitz             goto fail;
3872be4b67bcSMax Reitz         }
38739c4218e9SMax Reitz 
38749c4218e9SMax Reitz         QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3875be4b67bcSMax Reitz     }
3876be4b67bcSMax Reitz 
3877be4b67bcSMax Reitz     if (bs && bdrv_key_required(bs)) {
3878be4b67bcSMax Reitz         if (blk) {
3879efaa7c4eSMax Reitz             monitor_remove_blk(blk);
388018e46a03SMarkus Armbruster             blk_unref(blk);
3881be4b67bcSMax Reitz         } else {
38829c4218e9SMax Reitz             QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
3883be4b67bcSMax Reitz             bdrv_unref(bs);
3884be4b67bcSMax Reitz         }
38858ae8e904SKevin Wolf         error_setg(errp, "blockdev-add doesn't support encrypted devices");
38868ae8e904SKevin Wolf         goto fail;
38878ae8e904SKevin Wolf     }
38888ae8e904SKevin Wolf 
3889d26c9a15SKevin Wolf fail:
38903b098d56SEric Blake     visit_free(v);
3891d26c9a15SKevin Wolf }
3892d26c9a15SKevin Wolf 
389381b936aeSAlberto Garcia void qmp_x_blockdev_del(bool has_id, const char *id,
389481b936aeSAlberto Garcia                         bool has_node_name, const char *node_name, Error **errp)
389581b936aeSAlberto Garcia {
389681b936aeSAlberto Garcia     AioContext *aio_context;
389781b936aeSAlberto Garcia     BlockBackend *blk;
389881b936aeSAlberto Garcia     BlockDriverState *bs;
389981b936aeSAlberto Garcia 
390081b936aeSAlberto Garcia     if (has_id && has_node_name) {
390181b936aeSAlberto Garcia         error_setg(errp, "Only one of id and node-name must be specified");
390281b936aeSAlberto Garcia         return;
390381b936aeSAlberto Garcia     } else if (!has_id && !has_node_name) {
390481b936aeSAlberto Garcia         error_setg(errp, "No block device specified");
390581b936aeSAlberto Garcia         return;
390681b936aeSAlberto Garcia     }
390781b936aeSAlberto Garcia 
390881b936aeSAlberto Garcia     if (has_id) {
3909efaa7c4eSMax Reitz         /* blk_by_name() never returns a BB that is not owned by the monitor */
391081b936aeSAlberto Garcia         blk = blk_by_name(id);
391181b936aeSAlberto Garcia         if (!blk) {
391281b936aeSAlberto Garcia             error_setg(errp, "Cannot find block backend %s", id);
391381b936aeSAlberto Garcia             return;
391481b936aeSAlberto Garcia         }
39155cf87fd6SPaolo Bonzini         if (blk_legacy_dinfo(blk)) {
39165cf87fd6SPaolo Bonzini             error_setg(errp, "Deleting block backend added with drive-add"
39175cf87fd6SPaolo Bonzini                        " is not supported");
39185cf87fd6SPaolo Bonzini             return;
39195cf87fd6SPaolo Bonzini         }
392081b936aeSAlberto Garcia         if (blk_get_refcnt(blk) > 1) {
392181b936aeSAlberto Garcia             error_setg(errp, "Block backend %s is in use", id);
392281b936aeSAlberto Garcia             return;
392381b936aeSAlberto Garcia         }
392481b936aeSAlberto Garcia         bs = blk_bs(blk);
392581b936aeSAlberto Garcia         aio_context = blk_get_aio_context(blk);
392681b936aeSAlberto Garcia     } else {
39271f0c461bSKevin Wolf         blk = NULL;
392881b936aeSAlberto Garcia         bs = bdrv_find_node(node_name);
392981b936aeSAlberto Garcia         if (!bs) {
393081b936aeSAlberto Garcia             error_setg(errp, "Cannot find node %s", node_name);
393181b936aeSAlberto Garcia             return;
393281b936aeSAlberto Garcia         }
39331f0c461bSKevin Wolf         if (bdrv_has_blk(bs)) {
393481b936aeSAlberto Garcia             error_setg(errp, "Node %s is in use by %s",
39351f0c461bSKevin Wolf                        node_name, bdrv_get_parent_name(bs));
393681b936aeSAlberto Garcia             return;
393781b936aeSAlberto Garcia         }
393881b936aeSAlberto Garcia         aio_context = bdrv_get_aio_context(bs);
393981b936aeSAlberto Garcia     }
394081b936aeSAlberto Garcia 
394181b936aeSAlberto Garcia     aio_context_acquire(aio_context);
394281b936aeSAlberto Garcia 
394381b936aeSAlberto Garcia     if (bs) {
394481b936aeSAlberto Garcia         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
394581b936aeSAlberto Garcia             goto out;
394681b936aeSAlberto Garcia         }
394781b936aeSAlberto Garcia 
39483b8c1761SIgor Mammedov         if (!blk && !QTAILQ_IN_USE(bs, monitor_list)) {
39499c4218e9SMax Reitz             error_setg(errp, "Node %s is not owned by the monitor",
39509c4218e9SMax Reitz                        bs->node_name);
39519c4218e9SMax Reitz             goto out;
39529c4218e9SMax Reitz         }
39539c4218e9SMax Reitz 
39549c4218e9SMax Reitz         if (bs->refcnt > 1) {
395581b936aeSAlberto Garcia             error_setg(errp, "Block device %s is in use",
395681b936aeSAlberto Garcia                        bdrv_get_device_or_node_name(bs));
395781b936aeSAlberto Garcia             goto out;
395881b936aeSAlberto Garcia         }
395981b936aeSAlberto Garcia     }
396081b936aeSAlberto Garcia 
396181b936aeSAlberto Garcia     if (blk) {
3962efaa7c4eSMax Reitz         monitor_remove_blk(blk);
396381b936aeSAlberto Garcia         blk_unref(blk);
396481b936aeSAlberto Garcia     } else {
39659c4218e9SMax Reitz         QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
396681b936aeSAlberto Garcia         bdrv_unref(bs);
396781b936aeSAlberto Garcia     }
396881b936aeSAlberto Garcia 
396981b936aeSAlberto Garcia out:
397081b936aeSAlberto Garcia     aio_context_release(aio_context);
397181b936aeSAlberto Garcia }
397281b936aeSAlberto Garcia 
39737f821597SWen Congyang static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
39747f821597SWen Congyang                                   const char *child_name)
39757f821597SWen Congyang {
39767f821597SWen Congyang     BdrvChild *child;
39777f821597SWen Congyang 
39787f821597SWen Congyang     QLIST_FOREACH(child, &parent_bs->children, next) {
39797f821597SWen Congyang         if (strcmp(child->name, child_name) == 0) {
39807f821597SWen Congyang             return child;
39817f821597SWen Congyang         }
39827f821597SWen Congyang     }
39837f821597SWen Congyang 
39847f821597SWen Congyang     return NULL;
39857f821597SWen Congyang }
39867f821597SWen Congyang 
39877f821597SWen Congyang void qmp_x_blockdev_change(const char *parent, bool has_child,
39887f821597SWen Congyang                            const char *child, bool has_node,
39897f821597SWen Congyang                            const char *node, Error **errp)
39907f821597SWen Congyang {
39917f821597SWen Congyang     BlockDriverState *parent_bs, *new_bs = NULL;
39927f821597SWen Congyang     BdrvChild *p_child;
39937f821597SWen Congyang 
39947f821597SWen Congyang     parent_bs = bdrv_lookup_bs(parent, parent, errp);
39957f821597SWen Congyang     if (!parent_bs) {
39967f821597SWen Congyang         return;
39977f821597SWen Congyang     }
39987f821597SWen Congyang 
39997f821597SWen Congyang     if (has_child == has_node) {
40007f821597SWen Congyang         if (has_child) {
40017f821597SWen Congyang             error_setg(errp, "The parameters child and node are in conflict");
40027f821597SWen Congyang         } else {
40037f821597SWen Congyang             error_setg(errp, "Either child or node must be specified");
40047f821597SWen Congyang         }
40057f821597SWen Congyang         return;
40067f821597SWen Congyang     }
40077f821597SWen Congyang 
40087f821597SWen Congyang     if (has_child) {
40097f821597SWen Congyang         p_child = bdrv_find_child(parent_bs, child);
40107f821597SWen Congyang         if (!p_child) {
40117f821597SWen Congyang             error_setg(errp, "Node '%s' does not have child '%s'",
40127f821597SWen Congyang                        parent, child);
40137f821597SWen Congyang             return;
40147f821597SWen Congyang         }
40157f821597SWen Congyang         bdrv_del_child(parent_bs, p_child, errp);
40167f821597SWen Congyang     }
40177f821597SWen Congyang 
40187f821597SWen Congyang     if (has_node) {
40197f821597SWen Congyang         new_bs = bdrv_find_node(node);
40207f821597SWen Congyang         if (!new_bs) {
40217f821597SWen Congyang             error_setg(errp, "Node '%s' not found", node);
40227f821597SWen Congyang             return;
40237f821597SWen Congyang         }
40247f821597SWen Congyang         bdrv_add_child(parent_bs, new_bs, errp);
40257f821597SWen Congyang     }
40267f821597SWen Congyang }
40277f821597SWen Congyang 
4028fb5458cdSStefan Hajnoczi BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4029fb5458cdSStefan Hajnoczi {
4030fea68bb6SMarkus Armbruster     BlockJobInfoList *head = NULL, **p_next = &head;
4031f0f55dedSAlberto Garcia     BlockJob *job;
4032fea68bb6SMarkus Armbruster 
4033f0f55dedSAlberto Garcia     for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4034f0f55dedSAlberto Garcia         BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4035f0f55dedSAlberto Garcia         AioContext *aio_context = blk_get_aio_context(job->blk);
403669691e72SStefan Hajnoczi 
403769691e72SStefan Hajnoczi         aio_context_acquire(aio_context);
4038f0f55dedSAlberto Garcia         elem->value = block_job_query(job);
4039f0f55dedSAlberto Garcia         aio_context_release(aio_context);
404069691e72SStefan Hajnoczi 
4041fea68bb6SMarkus Armbruster         *p_next = elem;
4042fea68bb6SMarkus Armbruster         p_next = &elem->next;
4043fea68bb6SMarkus Armbruster     }
404469691e72SStefan Hajnoczi 
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         },{
4065e4b24b49SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
4066e4b24b49SKevin Wolf             .type = QEMU_OPT_BOOL,
4067e4b24b49SKevin Wolf             .help = "Enable writeback mode",
4068e4b24b49SKevin Wolf         },{
40694d454574SPaolo Bonzini             .name = "format",
40704d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
40714d454574SPaolo Bonzini             .help = "disk format (raw, qcow2, ...)",
40724d454574SPaolo Bonzini         },{
40734d454574SPaolo Bonzini             .name = "rerror",
40744d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
40754d454574SPaolo Bonzini             .help = "read error action",
40764d454574SPaolo Bonzini         },{
40774d454574SPaolo Bonzini             .name = "werror",
40784d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
40794d454574SPaolo Bonzini             .help = "write error action",
40804d454574SPaolo Bonzini         },{
40814e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
40824d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
40834d454574SPaolo Bonzini             .help = "open drive file as read-only",
40844d454574SPaolo Bonzini         },{
408557975222SKevin Wolf             .name = "throttling.iops-total",
40864d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
40874d454574SPaolo Bonzini             .help = "limit total I/O operations per second",
40884d454574SPaolo Bonzini         },{
408957975222SKevin Wolf             .name = "throttling.iops-read",
40904d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
40914d454574SPaolo Bonzini             .help = "limit read operations per second",
40924d454574SPaolo Bonzini         },{
409357975222SKevin Wolf             .name = "throttling.iops-write",
40944d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
40954d454574SPaolo Bonzini             .help = "limit write operations per second",
40964d454574SPaolo Bonzini         },{
409757975222SKevin Wolf             .name = "throttling.bps-total",
40984d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
40994d454574SPaolo Bonzini             .help = "limit total bytes per second",
41004d454574SPaolo Bonzini         },{
410157975222SKevin Wolf             .name = "throttling.bps-read",
41024d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
41034d454574SPaolo Bonzini             .help = "limit read bytes per second",
41044d454574SPaolo Bonzini         },{
410557975222SKevin Wolf             .name = "throttling.bps-write",
41064d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
41074d454574SPaolo Bonzini             .help = "limit write bytes per second",
41084d454574SPaolo Bonzini         },{
41093e9fab69SBenoît Canet             .name = "throttling.iops-total-max",
41103e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41113e9fab69SBenoît Canet             .help = "I/O operations burst",
41123e9fab69SBenoît Canet         },{
41133e9fab69SBenoît Canet             .name = "throttling.iops-read-max",
41143e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41153e9fab69SBenoît Canet             .help = "I/O operations read burst",
41163e9fab69SBenoît Canet         },{
41173e9fab69SBenoît Canet             .name = "throttling.iops-write-max",
41183e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41193e9fab69SBenoît Canet             .help = "I/O operations write burst",
41203e9fab69SBenoît Canet         },{
41213e9fab69SBenoît Canet             .name = "throttling.bps-total-max",
41223e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41233e9fab69SBenoît Canet             .help = "total bytes burst",
41243e9fab69SBenoît Canet         },{
41253e9fab69SBenoît Canet             .name = "throttling.bps-read-max",
41263e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41273e9fab69SBenoît Canet             .help = "total bytes read burst",
41283e9fab69SBenoît Canet         },{
41293e9fab69SBenoît Canet             .name = "throttling.bps-write-max",
41303e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
41313e9fab69SBenoît Canet             .help = "total bytes write burst",
41323e9fab69SBenoît Canet         },{
41338a0fc18dSAlberto Garcia             .name = "throttling.iops-total-max-length",
41348a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41358a0fc18dSAlberto Garcia             .help = "length of the iops-total-max burst period, in seconds",
41368a0fc18dSAlberto Garcia         },{
41378a0fc18dSAlberto Garcia             .name = "throttling.iops-read-max-length",
41388a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41398a0fc18dSAlberto Garcia             .help = "length of the iops-read-max burst period, in seconds",
41408a0fc18dSAlberto Garcia         },{
41418a0fc18dSAlberto Garcia             .name = "throttling.iops-write-max-length",
41428a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41438a0fc18dSAlberto Garcia             .help = "length of the iops-write-max burst period, in seconds",
41448a0fc18dSAlberto Garcia         },{
41458a0fc18dSAlberto Garcia             .name = "throttling.bps-total-max-length",
41468a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41478a0fc18dSAlberto Garcia             .help = "length of the bps-total-max burst period, in seconds",
41488a0fc18dSAlberto Garcia         },{
41498a0fc18dSAlberto Garcia             .name = "throttling.bps-read-max-length",
41508a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41518a0fc18dSAlberto Garcia             .help = "length of the bps-read-max burst period, in seconds",
41528a0fc18dSAlberto Garcia         },{
41538a0fc18dSAlberto Garcia             .name = "throttling.bps-write-max-length",
41548a0fc18dSAlberto Garcia             .type = QEMU_OPT_NUMBER,
41558a0fc18dSAlberto Garcia             .help = "length of the bps-write-max burst period, in seconds",
41568a0fc18dSAlberto Garcia         },{
41572024c1dfSBenoît Canet             .name = "throttling.iops-size",
41582024c1dfSBenoît Canet             .type = QEMU_OPT_NUMBER,
41592024c1dfSBenoît Canet             .help = "when limiting by iops max size of an I/O in bytes",
41602024c1dfSBenoît Canet         },{
416176f4afb4SAlberto Garcia             .name = "throttling.group",
416276f4afb4SAlberto Garcia             .type = QEMU_OPT_STRING,
416376f4afb4SAlberto Garcia             .help = "name of the block throttling group",
416476f4afb4SAlberto Garcia         },{
41654d454574SPaolo Bonzini             .name = "copy-on-read",
41664d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
41674d454574SPaolo Bonzini             .help = "copy read data from backing file into image file",
4168465bee1dSPeter Lieven         },{
4169465bee1dSPeter Lieven             .name = "detect-zeroes",
4170465bee1dSPeter Lieven             .type = QEMU_OPT_STRING,
4171465bee1dSPeter Lieven             .help = "try to optimize zero writes (off, on, unmap)",
4172362e9299SAlberto Garcia         },{
4173362e9299SAlberto Garcia             .name = "stats-account-invalid",
4174362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4175362e9299SAlberto Garcia             .help = "whether to account for invalid I/O operations "
4176362e9299SAlberto Garcia                     "in the statistics",
4177362e9299SAlberto Garcia         },{
4178362e9299SAlberto Garcia             .name = "stats-account-failed",
4179362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4180362e9299SAlberto Garcia             .help = "whether to account for failed I/O operations "
4181362e9299SAlberto Garcia                     "in the statistics",
41824d454574SPaolo Bonzini         },
41834d454574SPaolo Bonzini         { /* end of list */ }
41844d454574SPaolo Bonzini     },
41854d454574SPaolo Bonzini };
41860006383eSKevin Wolf 
4187bd745e23SMax Reitz static QemuOptsList qemu_root_bds_opts = {
4188bd745e23SMax Reitz     .name = "root-bds",
418923f7fcb2SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
4190bd745e23SMax Reitz     .desc = {
4191bd745e23SMax Reitz         {
4192bd745e23SMax Reitz             .name = "discard",
4193bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
4194bd745e23SMax Reitz             .help = "discard operation (ignore/off, unmap/on)",
4195bd745e23SMax Reitz         },{
4196bd745e23SMax Reitz             .name = "aio",
4197bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
4198bd745e23SMax Reitz             .help = "host AIO implementation (threads, native)",
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