xref: /openbmc/qemu/blockdev.c (revision 5d3b4e99463642b226d1a37433d0e4b376162468)
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"
38609f45eaSMax Reitz #include "block/qdict.h"
3976f4afb4SAlberto Garcia #include "block/throttle-groups.h"
4083c9089eSPaolo Bonzini #include "monitor/monitor.h"
41d49b6836SMarkus Armbruster #include "qemu/error-report.h"
421de7afc9SPaolo Bonzini #include "qemu/option.h"
431de7afc9SPaolo Bonzini #include "qemu/config-file.h"
449af23989SMarkus Armbruster #include "qapi/qapi-commands-block.h"
459af23989SMarkus Armbruster #include "qapi/qapi-commands-transaction.h"
469af23989SMarkus Armbruster #include "qapi/qapi-visit-block-core.h"
47452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
4815280c36SMarkus Armbruster #include "qapi/qmp/qnum.h"
496b673957SMarkus Armbruster #include "qapi/qmp/qstring.h"
50e688df6bSMarkus Armbruster #include "qapi/error.h"
51cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
5247e6b297SMarkus Armbruster #include "qapi/qmp/qlist.h"
53b3db211fSDaniel P. Berrange #include "qapi/qobject-output-visitor.h"
549c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
55ca00bbb1SStefan Hajnoczi #include "sysemu/iothread.h"
56737e150eSPaolo Bonzini #include "block/block_int.h"
570ab8ed18SDaniel P. Berrange #include "block/trace.h"
589c17d615SPaolo Bonzini #include "sysemu/arch_init.h"
59c616f16eSThomas Huth #include "sysemu/qtest.h"
60f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
61f348b6d1SVeronia Bahaa #include "qemu/help_option.h"
62a2a7862cSPradeep Jagadeesh #include "qemu/throttle-options.h"
63666daa68SMarkus Armbruster 
649c4218e9SMax Reitz static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
659c4218e9SMax Reitz     QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
669c4218e9SMax Reitz 
67b33945cfSKevin Wolf static int do_open_tray(const char *blk_name, const char *qdev_id,
68b33945cfSKevin Wolf                         bool force, Error **errp);
6982fcf66eSMax Reitz static void blockdev_remove_medium(bool has_device, const char *device,
7082fcf66eSMax Reitz                                    bool has_id, const char *id, Error **errp);
7182fcf66eSMax Reitz static void blockdev_insert_medium(bool has_device, const char *device,
7282fcf66eSMax Reitz                                    bool has_id, const char *id,
7382fcf66eSMax Reitz                                    const char *node_name, Error **errp);
74bf18bee5SColin Lord 
751960966dSMarkus Armbruster static const char *const if_name[IF_COUNT] = {
761960966dSMarkus Armbruster     [IF_NONE] = "none",
771960966dSMarkus Armbruster     [IF_IDE] = "ide",
781960966dSMarkus Armbruster     [IF_SCSI] = "scsi",
791960966dSMarkus Armbruster     [IF_FLOPPY] = "floppy",
801960966dSMarkus Armbruster     [IF_PFLASH] = "pflash",
811960966dSMarkus Armbruster     [IF_MTD] = "mtd",
821960966dSMarkus Armbruster     [IF_SD] = "sd",
831960966dSMarkus Armbruster     [IF_VIRTIO] = "virtio",
841960966dSMarkus Armbruster     [IF_XEN] = "xen",
851960966dSMarkus Armbruster };
861960966dSMarkus Armbruster 
8721dff8cfSJohn Snow static int if_max_devs[IF_COUNT] = {
8827d6bf40SMarkus Armbruster     /*
8927d6bf40SMarkus Armbruster      * Do not change these numbers!  They govern how drive option
9027d6bf40SMarkus Armbruster      * index maps to unit and bus.  That mapping is ABI.
9127d6bf40SMarkus Armbruster      *
92547cb157SWei Jiangang      * All controllers used to implement if=T drives need to support
9327d6bf40SMarkus Armbruster      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
9427d6bf40SMarkus Armbruster      * Otherwise, some index values map to "impossible" bus, unit
9527d6bf40SMarkus Armbruster      * values.
9627d6bf40SMarkus Armbruster      *
9727d6bf40SMarkus Armbruster      * For instance, if you change [IF_SCSI] to 255, -drive
9827d6bf40SMarkus Armbruster      * if=scsi,index=12 no longer means bus=1,unit=5, but
9927d6bf40SMarkus Armbruster      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
10027d6bf40SMarkus Armbruster      * the drive can't be set up.  Regression.
10127d6bf40SMarkus Armbruster      */
10227d6bf40SMarkus Armbruster     [IF_IDE] = 2,
10327d6bf40SMarkus Armbruster     [IF_SCSI] = 7,
1041960966dSMarkus Armbruster };
1051960966dSMarkus Armbruster 
10621dff8cfSJohn Snow /**
10721dff8cfSJohn Snow  * Boards may call this to offer board-by-board overrides
10821dff8cfSJohn Snow  * of the default, global values.
10921dff8cfSJohn Snow  */
11021dff8cfSJohn Snow void override_max_devs(BlockInterfaceType type, int max_devs)
11121dff8cfSJohn Snow {
11218e46a03SMarkus Armbruster     BlockBackend *blk;
11321dff8cfSJohn Snow     DriveInfo *dinfo;
11421dff8cfSJohn Snow 
11521dff8cfSJohn Snow     if (max_devs <= 0) {
11621dff8cfSJohn Snow         return;
11721dff8cfSJohn Snow     }
11821dff8cfSJohn Snow 
11918e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
12018e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
12121dff8cfSJohn Snow         if (dinfo->type == type) {
12221dff8cfSJohn Snow             fprintf(stderr, "Cannot override units-per-bus property of"
12321dff8cfSJohn Snow                     " the %s interface, because a drive of that type has"
12421dff8cfSJohn Snow                     " already been added.\n", if_name[type]);
12521dff8cfSJohn Snow             g_assert_not_reached();
12621dff8cfSJohn Snow         }
12721dff8cfSJohn Snow     }
12821dff8cfSJohn Snow 
12921dff8cfSJohn Snow     if_max_devs[type] = max_devs;
13021dff8cfSJohn Snow }
13121dff8cfSJohn Snow 
13214bafc54SMarkus Armbruster /*
13314bafc54SMarkus Armbruster  * We automatically delete the drive when a device using it gets
13414bafc54SMarkus Armbruster  * unplugged.  Questionable feature, but we can't just drop it.
13514bafc54SMarkus Armbruster  * Device models call blockdev_mark_auto_del() to schedule the
13614bafc54SMarkus Armbruster  * automatic deletion, and generic qdev code calls blockdev_auto_del()
13714bafc54SMarkus Armbruster  * when deletion is actually safe.
13814bafc54SMarkus Armbruster  */
1394be74634SMarkus Armbruster void blockdev_mark_auto_del(BlockBackend *blk)
14014bafc54SMarkus Armbruster {
14118e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
1424be74634SMarkus Armbruster     BlockDriverState *bs = blk_bs(blk);
14391fddb0dSStefan Hajnoczi     AioContext *aio_context;
14414bafc54SMarkus Armbruster 
14526f8b3a8SMarkus Armbruster     if (!dinfo) {
1462d246f01SKevin Wolf         return;
1472d246f01SKevin Wolf     }
1482d246f01SKevin Wolf 
1495433c24fSMax Reitz     if (bs) {
15091fddb0dSStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
15191fddb0dSStefan Hajnoczi         aio_context_acquire(aio_context);
15291fddb0dSStefan Hajnoczi 
15312bde0eeSPaolo Bonzini         if (bs->job) {
1543d70ff53SKevin Wolf             job_cancel(&bs->job->job, false);
15512bde0eeSPaolo Bonzini         }
15691fddb0dSStefan Hajnoczi 
15791fddb0dSStefan Hajnoczi         aio_context_release(aio_context);
1585433c24fSMax Reitz     }
15991fddb0dSStefan Hajnoczi 
16014bafc54SMarkus Armbruster     dinfo->auto_del = 1;
16114bafc54SMarkus Armbruster }
16214bafc54SMarkus Armbruster 
1634be74634SMarkus Armbruster void blockdev_auto_del(BlockBackend *blk)
16414bafc54SMarkus Armbruster {
16518e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
16614bafc54SMarkus Armbruster 
1670fc0f1faSRyan Harper     if (dinfo && dinfo->auto_del) {
168efaa7c4eSMax Reitz         monitor_remove_blk(blk);
169b9fe8a7aSMarkus Armbruster         blk_unref(blk);
17014bafc54SMarkus Armbruster     }
17114bafc54SMarkus Armbruster }
17214bafc54SMarkus Armbruster 
173d8f94e1bSJohn Snow /**
174d8f94e1bSJohn Snow  * Returns the current mapping of how many units per bus
175d8f94e1bSJohn Snow  * a particular interface can support.
176d8f94e1bSJohn Snow  *
177d8f94e1bSJohn Snow  *  A positive integer indicates n units per bus.
178d8f94e1bSJohn Snow  *  0 implies the mapping has not been established.
179d8f94e1bSJohn Snow  * -1 indicates an invalid BlockInterfaceType was given.
180d8f94e1bSJohn Snow  */
181d8f94e1bSJohn Snow int drive_get_max_devs(BlockInterfaceType type)
182d8f94e1bSJohn Snow {
183d8f94e1bSJohn Snow     if (type >= IF_IDE && type < IF_COUNT) {
184d8f94e1bSJohn Snow         return if_max_devs[type];
185d8f94e1bSJohn Snow     }
186d8f94e1bSJohn Snow 
187d8f94e1bSJohn Snow     return -1;
188d8f94e1bSJohn Snow }
189d8f94e1bSJohn Snow 
190505a7fb1SMarkus Armbruster static int drive_index_to_bus_id(BlockInterfaceType type, int index)
191505a7fb1SMarkus Armbruster {
192505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
193505a7fb1SMarkus Armbruster     return max_devs ? index / max_devs : 0;
194505a7fb1SMarkus Armbruster }
195505a7fb1SMarkus Armbruster 
196505a7fb1SMarkus Armbruster static int drive_index_to_unit_id(BlockInterfaceType type, int index)
197505a7fb1SMarkus Armbruster {
198505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
199505a7fb1SMarkus Armbruster     return max_devs ? index % max_devs : index;
200505a7fb1SMarkus Armbruster }
201505a7fb1SMarkus Armbruster 
2022292ddaeSMarkus Armbruster QemuOpts *drive_def(const char *optstr)
2032292ddaeSMarkus Armbruster {
20470b94331SMarkus Armbruster     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
2052292ddaeSMarkus Armbruster }
2062292ddaeSMarkus Armbruster 
2072292ddaeSMarkus Armbruster QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
2085645b0f4SMarkus Armbruster                     const char *optstr)
209666daa68SMarkus Armbruster {
210666daa68SMarkus Armbruster     QemuOpts *opts;
211666daa68SMarkus Armbruster 
2122292ddaeSMarkus Armbruster     opts = drive_def(optstr);
213666daa68SMarkus Armbruster     if (!opts) {
214666daa68SMarkus Armbruster         return NULL;
215666daa68SMarkus Armbruster     }
2162292ddaeSMarkus Armbruster     if (type != IF_DEFAULT) {
217f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "if", if_name[type], &error_abort);
2182292ddaeSMarkus Armbruster     }
2192292ddaeSMarkus Armbruster     if (index >= 0) {
220a8b18f8fSMarkus Armbruster         qemu_opt_set_number(opts, "index", index, &error_abort);
2212292ddaeSMarkus Armbruster     }
222666daa68SMarkus Armbruster     if (file)
223f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "file", file, &error_abort);
224666daa68SMarkus Armbruster     return opts;
225666daa68SMarkus Armbruster }
226666daa68SMarkus Armbruster 
227666daa68SMarkus Armbruster DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
228666daa68SMarkus Armbruster {
22918e46a03SMarkus Armbruster     BlockBackend *blk;
230666daa68SMarkus Armbruster     DriveInfo *dinfo;
231666daa68SMarkus Armbruster 
23218e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
23318e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
23418e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type
23518e46a03SMarkus Armbruster             && dinfo->bus == bus && dinfo->unit == unit) {
236666daa68SMarkus Armbruster             return dinfo;
237666daa68SMarkus Armbruster         }
23818e46a03SMarkus Armbruster     }
239666daa68SMarkus Armbruster 
240666daa68SMarkus Armbruster     return NULL;
241666daa68SMarkus Armbruster }
242666daa68SMarkus Armbruster 
243720b8dc0SMarkus Armbruster void drive_check_orphaned(void)
244a66c9dc7SJohn Snow {
24518e46a03SMarkus Armbruster     BlockBackend *blk;
246a66c9dc7SJohn Snow     DriveInfo *dinfo;
247664cc623SMarkus Armbruster     Location loc;
248720b8dc0SMarkus Armbruster     bool orphans = false;
249a66c9dc7SJohn Snow 
25018e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
25118e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
252a7f53e26SMarkus Armbruster         if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
253a66c9dc7SJohn Snow             dinfo->type != IF_NONE) {
254664cc623SMarkus Armbruster             loc_push_none(&loc);
255664cc623SMarkus Armbruster             qemu_opts_loc_restore(dinfo->opts);
256720b8dc0SMarkus Armbruster             error_report("machine type does not support"
257664cc623SMarkus Armbruster                          " if=%s,bus=%d,unit=%d",
2585433c24fSMax Reitz                          if_name[dinfo->type], dinfo->bus, dinfo->unit);
259664cc623SMarkus Armbruster             loc_pop(&loc);
260720b8dc0SMarkus Armbruster             orphans = true;
261a66c9dc7SJohn Snow         }
262a66c9dc7SJohn Snow     }
263a66c9dc7SJohn Snow 
264720b8dc0SMarkus Armbruster     if (orphans) {
265720b8dc0SMarkus Armbruster         exit(1);
266720b8dc0SMarkus Armbruster     }
267a66c9dc7SJohn Snow }
268a66c9dc7SJohn Snow 
269f1bd51acSMarkus Armbruster DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
270f1bd51acSMarkus Armbruster {
271f1bd51acSMarkus Armbruster     return drive_get(type,
272f1bd51acSMarkus Armbruster                      drive_index_to_bus_id(type, index),
273f1bd51acSMarkus Armbruster                      drive_index_to_unit_id(type, index));
274f1bd51acSMarkus Armbruster }
275f1bd51acSMarkus Armbruster 
276666daa68SMarkus Armbruster int drive_get_max_bus(BlockInterfaceType type)
277666daa68SMarkus Armbruster {
278666daa68SMarkus Armbruster     int max_bus;
27918e46a03SMarkus Armbruster     BlockBackend *blk;
280666daa68SMarkus Armbruster     DriveInfo *dinfo;
281666daa68SMarkus Armbruster 
282666daa68SMarkus Armbruster     max_bus = -1;
28318e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
28418e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
28518e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
286666daa68SMarkus Armbruster             max_bus = dinfo->bus;
287666daa68SMarkus Armbruster         }
28818e46a03SMarkus Armbruster     }
289666daa68SMarkus Armbruster     return max_bus;
290666daa68SMarkus Armbruster }
291666daa68SMarkus Armbruster 
29213839974SMarkus Armbruster /* Get a block device.  This should only be used for single-drive devices
29313839974SMarkus Armbruster    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
29413839974SMarkus Armbruster    appropriate bus.  */
29513839974SMarkus Armbruster DriveInfo *drive_get_next(BlockInterfaceType type)
29613839974SMarkus Armbruster {
29713839974SMarkus Armbruster     static int next_block_unit[IF_COUNT];
29813839974SMarkus Armbruster 
29913839974SMarkus Armbruster     return drive_get(type, 0, next_block_unit[type]++);
30013839974SMarkus Armbruster }
30113839974SMarkus Armbruster 
302666daa68SMarkus Armbruster static void bdrv_format_print(void *opaque, const char *name)
303666daa68SMarkus Armbruster {
304807105a7SMarkus Armbruster     error_printf(" %s", name);
305666daa68SMarkus Armbruster }
306666daa68SMarkus Armbruster 
307aa398a5cSStefan Hajnoczi typedef struct {
308aa398a5cSStefan Hajnoczi     QEMUBH *bh;
309fa510ebfSFam Zheng     BlockDriverState *bs;
310fa510ebfSFam Zheng } BDRVPutRefBH;
311aa398a5cSStefan Hajnoczi 
312b681072dSKevin Wolf static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
313666daa68SMarkus Armbruster {
314666daa68SMarkus Armbruster     if (!strcmp(buf, "ignore")) {
31592aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_IGNORE;
316666daa68SMarkus Armbruster     } else if (!is_read && !strcmp(buf, "enospc")) {
31792aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_ENOSPC;
318666daa68SMarkus Armbruster     } else if (!strcmp(buf, "stop")) {
31992aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_STOP;
320666daa68SMarkus Armbruster     } else if (!strcmp(buf, "report")) {
32192aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_REPORT;
322666daa68SMarkus Armbruster     } else {
323b681072dSKevin Wolf         error_setg(errp, "'%s' invalid %s error action",
324666daa68SMarkus Armbruster                    buf, is_read ? "read" : "write");
325666daa68SMarkus Armbruster         return -1;
326666daa68SMarkus Armbruster     }
327666daa68SMarkus Armbruster }
328666daa68SMarkus Armbruster 
32940119effSAlberto Garcia static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
33040119effSAlberto Garcia                                   Error **errp)
33140119effSAlberto Garcia {
33240119effSAlberto Garcia     const QListEntry *entry;
33340119effSAlberto Garcia     for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
33440119effSAlberto Garcia         switch (qobject_type(entry->value)) {
33540119effSAlberto Garcia 
33640119effSAlberto Garcia         case QTYPE_QSTRING: {
33740119effSAlberto Garcia             unsigned long long length;
3387dc847ebSMax Reitz             const char *str = qstring_get_str(qobject_to(QString,
3397dc847ebSMax Reitz                                                          entry->value));
34040119effSAlberto Garcia             if (parse_uint_full(str, &length, 10) == 0 &&
34140119effSAlberto Garcia                 length > 0 && length <= UINT_MAX) {
34240119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
34340119effSAlberto Garcia             } else {
34440119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %s", str);
34540119effSAlberto Garcia                 return false;
34640119effSAlberto Garcia             }
34740119effSAlberto Garcia             break;
34840119effSAlberto Garcia         }
34940119effSAlberto Garcia 
35001b2ffceSMarc-André Lureau         case QTYPE_QNUM: {
3517dc847ebSMax Reitz             int64_t length = qnum_get_int(qobject_to(QNum, entry->value));
35201b2ffceSMarc-André Lureau 
35340119effSAlberto Garcia             if (length > 0 && length <= UINT_MAX) {
35440119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
35540119effSAlberto Garcia             } else {
35640119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %" PRId64, length);
35740119effSAlberto Garcia                 return false;
35840119effSAlberto Garcia             }
35940119effSAlberto Garcia             break;
36040119effSAlberto Garcia         }
36140119effSAlberto Garcia 
36240119effSAlberto Garcia         default:
36340119effSAlberto Garcia             error_setg(errp, "The specification of stats-intervals is invalid");
36440119effSAlberto Garcia             return false;
36540119effSAlberto Garcia         }
36640119effSAlberto Garcia     }
36740119effSAlberto Garcia     return true;
36840119effSAlberto Garcia }
36940119effSAlberto Garcia 
37033cb7dc8SKevin Wolf typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
37133cb7dc8SKevin Wolf 
372fbf8175eSMax Reitz /* All parameters but @opts are optional and may be set to NULL. */
373fbf8175eSMax Reitz static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
374fbf8175eSMax Reitz     const char **throttling_group, ThrottleConfig *throttle_cfg,
375fbf8175eSMax Reitz     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
376fbf8175eSMax Reitz {
377fbf8175eSMax Reitz     Error *local_error = NULL;
378fbf8175eSMax Reitz     const char *aio;
379fbf8175eSMax Reitz 
380fbf8175eSMax Reitz     if (bdrv_flags) {
381fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
382fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_COPY_ON_READ;
383fbf8175eSMax Reitz         }
384fbf8175eSMax Reitz 
385fbf8175eSMax Reitz         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
386fbf8175eSMax Reitz             if (!strcmp(aio, "native")) {
387fbf8175eSMax Reitz                 *bdrv_flags |= BDRV_O_NATIVE_AIO;
388fbf8175eSMax Reitz             } else if (!strcmp(aio, "threads")) {
389fbf8175eSMax Reitz                 /* this is the default */
390fbf8175eSMax Reitz             } else {
391fbf8175eSMax Reitz                error_setg(errp, "invalid aio option");
392fbf8175eSMax Reitz                return;
393fbf8175eSMax Reitz             }
394fbf8175eSMax Reitz         }
395fbf8175eSMax Reitz     }
396fbf8175eSMax Reitz 
397fbf8175eSMax Reitz     /* disk I/O throttling */
398fbf8175eSMax Reitz     if (throttling_group) {
399fbf8175eSMax Reitz         *throttling_group = qemu_opt_get(opts, "throttling.group");
400fbf8175eSMax Reitz     }
401fbf8175eSMax Reitz 
402fbf8175eSMax Reitz     if (throttle_cfg) {
4031588ab5dSAlberto Garcia         throttle_config_init(throttle_cfg);
404fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
405fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total", 0);
406fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
407fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read", 0);
408fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
409fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write", 0);
410fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
411fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total", 0);
412fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
413fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read", 0);
414fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
415fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write", 0);
416fbf8175eSMax Reitz 
417fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
418fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
419fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
420fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
421fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
422fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
423fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
424fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
425fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
426fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
427fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
428fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
429fbf8175eSMax Reitz 
4308a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
4318a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
4328a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length  =
4338a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
4348a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
4358a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
4368a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
4378a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
4388a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
4398a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
4408a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
4418a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
4428a0fc18dSAlberto Garcia 
443fbf8175eSMax Reitz         throttle_cfg->op_size =
444fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-size", 0);
445fbf8175eSMax Reitz 
446d5851089SAlberto Garcia         if (!throttle_is_valid(throttle_cfg, errp)) {
447fbf8175eSMax Reitz             return;
448fbf8175eSMax Reitz         }
449fbf8175eSMax Reitz     }
450fbf8175eSMax Reitz 
451fbf8175eSMax Reitz     if (detect_zeroes) {
452fbf8175eSMax Reitz         *detect_zeroes =
453f7abe0ecSMarc-André Lureau             qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
454fbf8175eSMax Reitz                             qemu_opt_get(opts, "detect-zeroes"),
455fbf8175eSMax Reitz                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
456fbf8175eSMax Reitz                             &local_error);
457fbf8175eSMax Reitz         if (local_error) {
458fbf8175eSMax Reitz             error_propagate(errp, local_error);
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         }
54346f5ac20SEric Blake         qdict_put_str(bs_opts, "driver", 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 
5746d0eb64dSKevin Wolf         blk = blk_new(0, BLK_PERM_ALL);
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 
580cb3e7f08SMarc-André Lureau         qobject_unref(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");
5939384a444SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_AUTO_READ_ONLY, "on");
59472e775c7SKevin Wolf         assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
59591a097e7SKevin Wolf 
59612d5ee3aSKevin Wolf         if (runstate_check(RUN_STATE_INMIGRATE)) {
59712d5ee3aSKevin Wolf             bdrv_flags |= BDRV_O_INACTIVE;
59812d5ee3aSKevin Wolf         }
59912d5ee3aSKevin Wolf 
600efaa7c4eSMax Reitz         blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
601e4342ce5SMax Reitz         if (!blk) {
602e4342ce5SMax Reitz             goto err_no_bs_opts;
603e4342ce5SMax Reitz         }
604e4342ce5SMax Reitz         bs = blk_bs(blk);
6050006383eSKevin Wolf 
606e4342ce5SMax Reitz         bs->detect_zeroes = detect_zeroes;
607e4342ce5SMax Reitz 
6089caa6f3dSPaolo Bonzini         block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
6092be5506fSAlberto Garcia 
61040119effSAlberto Garcia         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
6112be5506fSAlberto Garcia             blk_unref(blk);
6122be5506fSAlberto Garcia             blk = NULL;
6132be5506fSAlberto Garcia             goto err_no_bs_opts;
6142be5506fSAlberto Garcia         }
6152be5506fSAlberto Garcia     }
6165ec18f8cSMax Reitz 
6177ca7f0f6SKevin Wolf     /* disk I/O throttling */
6187ca7f0f6SKevin Wolf     if (throttle_enabled(&cfg)) {
6197ca7f0f6SKevin Wolf         if (!throttling_group) {
620ff356ee4SAlberto Garcia             throttling_group = id;
6217ca7f0f6SKevin Wolf         }
6227ca7f0f6SKevin Wolf         blk_io_limits_enable(blk, throttling_group);
6237ca7f0f6SKevin Wolf         blk_set_io_limits(blk, &cfg);
6247ca7f0f6SKevin Wolf     }
6257ca7f0f6SKevin Wolf 
626e4b24b49SKevin Wolf     blk_set_enable_write_cache(blk, !writethrough);
6275ec18f8cSMax Reitz     blk_set_on_error(blk, on_read_error, on_write_error);
6280006383eSKevin Wolf 
629ff356ee4SAlberto Garcia     if (!monitor_add_blk(blk, id, errp)) {
630efaa7c4eSMax Reitz         blk_unref(blk);
631efaa7c4eSMax Reitz         blk = NULL;
632efaa7c4eSMax Reitz         goto err_no_bs_opts;
633efaa7c4eSMax Reitz     }
634efaa7c4eSMax Reitz 
635e4342ce5SMax Reitz err_no_bs_opts:
6360006383eSKevin Wolf     qemu_opts_del(opts);
637cb3e7f08SMarc-André Lureau     qobject_unref(interval_dict);
638cb3e7f08SMarc-André Lureau     qobject_unref(interval_list);
63918e46a03SMarkus Armbruster     return blk;
640a9ae2bffSMarkus Armbruster 
641ec9c10d2SStefan Hajnoczi early_err:
642ec9c10d2SStefan Hajnoczi     qemu_opts_del(opts);
643cb3e7f08SMarc-André Lureau     qobject_unref(interval_dict);
644cb3e7f08SMarc-André Lureau     qobject_unref(interval_list);
6456376f952SMarkus Armbruster err_no_opts:
646cb3e7f08SMarc-André Lureau     qobject_unref(bs_opts);
647a9ae2bffSMarkus Armbruster     return NULL;
648666daa68SMarkus Armbruster }
649666daa68SMarkus Armbruster 
650bd745e23SMax Reitz /* Takes the ownership of bs_opts */
651bd745e23SMax Reitz static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
652bd745e23SMax Reitz {
653bd745e23SMax Reitz     int bdrv_flags = 0;
654bd745e23SMax Reitz 
655a81d6164SKevin Wolf     /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
656a81d6164SKevin Wolf      * with other callers) rather than what we want as the real defaults.
657a81d6164SKevin Wolf      * Apply the defaults here instead. */
658a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
659a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
660f87a0e29SAlberto Garcia     qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
661a81d6164SKevin Wolf 
66212d5ee3aSKevin Wolf     if (runstate_check(RUN_STATE_INMIGRATE)) {
66312d5ee3aSKevin Wolf         bdrv_flags |= BDRV_O_INACTIVE;
66412d5ee3aSKevin Wolf     }
66512d5ee3aSKevin Wolf 
66674e1ae7cSKevin Wolf     return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
667bd745e23SMax Reitz }
668bd745e23SMax Reitz 
6699c4218e9SMax Reitz void blockdev_close_all_bdrv_states(void)
6709c4218e9SMax Reitz {
6719c4218e9SMax Reitz     BlockDriverState *bs, *next_bs;
6729c4218e9SMax Reitz 
6739c4218e9SMax Reitz     QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
6749c4218e9SMax Reitz         AioContext *ctx = bdrv_get_aio_context(bs);
6759c4218e9SMax Reitz 
6769c4218e9SMax Reitz         aio_context_acquire(ctx);
6779c4218e9SMax Reitz         bdrv_unref(bs);
6789c4218e9SMax Reitz         aio_context_release(ctx);
6799c4218e9SMax Reitz     }
6809c4218e9SMax Reitz }
6819c4218e9SMax Reitz 
682262b4e8fSMax Reitz /* Iterates over the list of monitor-owned BlockDriverStates */
683262b4e8fSMax Reitz BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
684262b4e8fSMax Reitz {
685262b4e8fSMax Reitz     return bs ? QTAILQ_NEXT(bs, monitor_list)
686262b4e8fSMax Reitz               : QTAILQ_FIRST(&monitor_bdrv_states);
687262b4e8fSMax Reitz }
688262b4e8fSMax Reitz 
6895abbf0eeSKevin Wolf static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
6905abbf0eeSKevin Wolf                             Error **errp)
69157975222SKevin Wolf {
69257975222SKevin Wolf     const char *value;
69357975222SKevin Wolf 
69457975222SKevin Wolf     value = qemu_opt_get(opts, from);
69557975222SKevin Wolf     if (value) {
6965abbf0eeSKevin Wolf         if (qemu_opt_find(opts, to)) {
6975abbf0eeSKevin Wolf             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
6985abbf0eeSKevin Wolf                        "same time", to, from);
6995abbf0eeSKevin Wolf             return;
7005abbf0eeSKevin Wolf         }
70120d6cd47SJun Li     }
70220d6cd47SJun Li 
70320d6cd47SJun Li     /* rename all items in opts */
70420d6cd47SJun Li     while ((value = qemu_opt_get(opts, from))) {
705f43e47dbSMarkus Armbruster         qemu_opt_set(opts, to, value, &error_abort);
70657975222SKevin Wolf         qemu_opt_unset(opts, from);
70757975222SKevin Wolf     }
70857975222SKevin Wolf }
70957975222SKevin Wolf 
71033cb7dc8SKevin Wolf QemuOptsList qemu_legacy_drive_opts = {
71133cb7dc8SKevin Wolf     .name = "drive",
71233cb7dc8SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
71333cb7dc8SKevin Wolf     .desc = {
71433cb7dc8SKevin Wolf         {
71587a899c5SKevin Wolf             .name = "bus",
71687a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
71787a899c5SKevin Wolf             .help = "bus number",
71887a899c5SKevin Wolf         },{
71987a899c5SKevin Wolf             .name = "unit",
72087a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
72187a899c5SKevin Wolf             .help = "unit number (i.e. lun for scsi)",
72287a899c5SKevin Wolf         },{
72387a899c5SKevin Wolf             .name = "index",
72487a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
72587a899c5SKevin Wolf             .help = "index number",
72687a899c5SKevin Wolf         },{
72733cb7dc8SKevin Wolf             .name = "media",
72833cb7dc8SKevin Wolf             .type = QEMU_OPT_STRING,
72933cb7dc8SKevin Wolf             .help = "media type (disk, cdrom)",
730593d464bSKevin Wolf         },{
731593d464bSKevin Wolf             .name = "if",
732593d464bSKevin Wolf             .type = QEMU_OPT_STRING,
733593d464bSKevin Wolf             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
734b41a7338SKevin Wolf         },{
735d095b465SMax Reitz             .name = "file",
736d095b465SMax Reitz             .type = QEMU_OPT_STRING,
737d095b465SMax Reitz             .help = "file name",
73833cb7dc8SKevin Wolf         },
7390ebd24e0SKevin Wolf 
7400ebd24e0SKevin Wolf         /* Options that are passed on, but have special semantics with -drive */
7410ebd24e0SKevin Wolf         {
7424e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
7430ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
7440ebd24e0SKevin Wolf             .help = "open drive file as read-only",
7450ebd24e0SKevin Wolf         },{
746ee13ed1cSKevin Wolf             .name = "rerror",
747ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
748ee13ed1cSKevin Wolf             .help = "read error action",
749ee13ed1cSKevin Wolf         },{
750ee13ed1cSKevin Wolf             .name = "werror",
751ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
752ee13ed1cSKevin Wolf             .help = "write error action",
753ee13ed1cSKevin Wolf         },{
7540ebd24e0SKevin Wolf             .name = "copy-on-read",
7550ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
7560ebd24e0SKevin Wolf             .help = "copy read data from backing file into image file",
7570ebd24e0SKevin Wolf         },
7580ebd24e0SKevin Wolf 
75933cb7dc8SKevin Wolf         { /* end of list */ }
76033cb7dc8SKevin Wolf     },
76133cb7dc8SKevin Wolf };
76233cb7dc8SKevin Wolf 
763c4f26c9fSMarkus Armbruster DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
764c4f26c9fSMarkus Armbruster                      Error **errp)
76557975222SKevin Wolf {
76629c4e2b5SKevin Wolf     const char *value;
76718e46a03SMarkus Armbruster     BlockBackend *blk;
76833cb7dc8SKevin Wolf     DriveInfo *dinfo = NULL;
769f298d071SKevin Wolf     QDict *bs_opts;
77033cb7dc8SKevin Wolf     QemuOpts *legacy_opts;
77133cb7dc8SKevin Wolf     DriveMediaType media = MEDIA_DISK;
772593d464bSKevin Wolf     BlockInterfaceType type;
77387a899c5SKevin Wolf     int max_devs, bus_id, unit_id, index;
774ee13ed1cSKevin Wolf     const char *werror, *rerror;
775a7fdbcf0SFam Zheng     bool read_only = false;
776a7fdbcf0SFam Zheng     bool copy_on_read;
777d095b465SMax Reitz     const char *filename;
77833cb7dc8SKevin Wolf     Error *local_err = NULL;
779247147fbSKevin Wolf     int i;
78029c4e2b5SKevin Wolf 
78157975222SKevin Wolf     /* Change legacy command line options into QMP ones */
782247147fbSKevin Wolf     static const struct {
783247147fbSKevin Wolf         const char *from;
784247147fbSKevin Wolf         const char *to;
785247147fbSKevin Wolf     } opt_renames[] = {
786247147fbSKevin Wolf         { "iops",           "throttling.iops-total" },
787247147fbSKevin Wolf         { "iops_rd",        "throttling.iops-read" },
788247147fbSKevin Wolf         { "iops_wr",        "throttling.iops-write" },
78957975222SKevin Wolf 
790247147fbSKevin Wolf         { "bps",            "throttling.bps-total" },
791247147fbSKevin Wolf         { "bps_rd",         "throttling.bps-read" },
792247147fbSKevin Wolf         { "bps_wr",         "throttling.bps-write" },
79357975222SKevin Wolf 
794247147fbSKevin Wolf         { "iops_max",       "throttling.iops-total-max" },
795247147fbSKevin Wolf         { "iops_rd_max",    "throttling.iops-read-max" },
796247147fbSKevin Wolf         { "iops_wr_max",    "throttling.iops-write-max" },
7973e9fab69SBenoît Canet 
798247147fbSKevin Wolf         { "bps_max",        "throttling.bps-total-max" },
799247147fbSKevin Wolf         { "bps_rd_max",     "throttling.bps-read-max" },
800247147fbSKevin Wolf         { "bps_wr_max",     "throttling.bps-write-max" },
8013e9fab69SBenoît Canet 
802247147fbSKevin Wolf         { "iops_size",      "throttling.iops-size" },
8032024c1dfSBenoît Canet 
80476f4afb4SAlberto Garcia         { "group",          "throttling.group" },
80576f4afb4SAlberto Garcia 
8064e200cf8SAlberto Garcia         { "readonly",       BDRV_OPT_READ_ONLY },
807247147fbSKevin Wolf     };
808247147fbSKevin Wolf 
809247147fbSKevin Wolf     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
8105abbf0eeSKevin Wolf         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
8115abbf0eeSKevin Wolf                         &local_err);
8125abbf0eeSKevin Wolf         if (local_err) {
813c4f26c9fSMarkus Armbruster             error_propagate(errp, local_err);
8145abbf0eeSKevin Wolf             return NULL;
8155abbf0eeSKevin Wolf         }
816247147fbSKevin Wolf     }
8170f227a94SKevin Wolf 
81829c4e2b5SKevin Wolf     value = qemu_opt_get(all_opts, "cache");
81929c4e2b5SKevin Wolf     if (value) {
82029c4e2b5SKevin Wolf         int flags = 0;
82104feb4a5SKevin Wolf         bool writethrough;
82229c4e2b5SKevin Wolf 
82304feb4a5SKevin Wolf         if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
824c4f26c9fSMarkus Armbruster             error_setg(errp, "invalid cache option");
82529c4e2b5SKevin Wolf             return NULL;
82629c4e2b5SKevin Wolf         }
82729c4e2b5SKevin Wolf 
82829c4e2b5SKevin Wolf         /* Specific options take precedence */
82954861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
83054861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
83104feb4a5SKevin Wolf                               !writethrough, &error_abort);
83229c4e2b5SKevin Wolf         }
83354861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
83454861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
835cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NOCACHE), &error_abort);
83629c4e2b5SKevin Wolf         }
83754861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
83854861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
839cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
84029c4e2b5SKevin Wolf         }
84129c4e2b5SKevin Wolf         qemu_opt_unset(all_opts, "cache");
84229c4e2b5SKevin Wolf     }
84329c4e2b5SKevin Wolf 
844f298d071SKevin Wolf     /* Get a QDict for processing the options */
845f298d071SKevin Wolf     bs_opts = qdict_new();
846f298d071SKevin Wolf     qemu_opts_to_qdict(all_opts, bs_opts);
847f298d071SKevin Wolf 
84887ea75d5SPeter Crosthwaite     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
84987ea75d5SPeter Crosthwaite                                    &error_abort);
85033cb7dc8SKevin Wolf     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
85184d18f06SMarkus Armbruster     if (local_err) {
852c4f26c9fSMarkus Armbruster         error_propagate(errp, local_err);
85333cb7dc8SKevin Wolf         goto fail;
85433cb7dc8SKevin Wolf     }
85533cb7dc8SKevin Wolf 
85633cb7dc8SKevin Wolf     /* Media type */
85733cb7dc8SKevin Wolf     value = qemu_opt_get(legacy_opts, "media");
85833cb7dc8SKevin Wolf     if (value) {
85933cb7dc8SKevin Wolf         if (!strcmp(value, "disk")) {
86033cb7dc8SKevin Wolf             media = MEDIA_DISK;
86133cb7dc8SKevin Wolf         } else if (!strcmp(value, "cdrom")) {
86233cb7dc8SKevin Wolf             media = MEDIA_CDROM;
863a7fdbcf0SFam Zheng             read_only = true;
86433cb7dc8SKevin Wolf         } else {
865c4f26c9fSMarkus Armbruster             error_setg(errp, "'%s' invalid media", value);
86633cb7dc8SKevin Wolf             goto fail;
86733cb7dc8SKevin Wolf         }
86833cb7dc8SKevin Wolf     }
86933cb7dc8SKevin Wolf 
8700ebd24e0SKevin Wolf     /* copy-on-read is disabled with a warning for read-only devices */
8714e200cf8SAlberto Garcia     read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
8720ebd24e0SKevin Wolf     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
8730ebd24e0SKevin Wolf 
8740ebd24e0SKevin Wolf     if (read_only && copy_on_read) {
8753dc6f869SAlistair Francis         warn_report("disabling copy-on-read on read-only drive");
8760ebd24e0SKevin Wolf         copy_on_read = false;
8770ebd24e0SKevin Wolf     }
8780ebd24e0SKevin Wolf 
87946f5ac20SEric Blake     qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
88046f5ac20SEric Blake     qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
8810ebd24e0SKevin Wolf 
882593d464bSKevin Wolf     /* Controller type */
883593d464bSKevin Wolf     value = qemu_opt_get(legacy_opts, "if");
884593d464bSKevin Wolf     if (value) {
885593d464bSKevin Wolf         for (type = 0;
886593d464bSKevin Wolf              type < IF_COUNT && strcmp(value, if_name[type]);
887593d464bSKevin Wolf              type++) {
888593d464bSKevin Wolf         }
889593d464bSKevin Wolf         if (type == IF_COUNT) {
890c4f26c9fSMarkus Armbruster             error_setg(errp, "unsupported bus type '%s'", value);
891593d464bSKevin Wolf             goto fail;
892593d464bSKevin Wolf         }
893593d464bSKevin Wolf     } else {
894593d464bSKevin Wolf         type = block_default_type;
895593d464bSKevin Wolf     }
896593d464bSKevin Wolf 
89787a899c5SKevin Wolf     /* Device address specified by bus/unit or index.
89887a899c5SKevin Wolf      * If none was specified, try to find the first free one. */
89987a899c5SKevin Wolf     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
90087a899c5SKevin Wolf     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
90187a899c5SKevin Wolf     index   = qemu_opt_get_number(legacy_opts, "index", -1);
90287a899c5SKevin Wolf 
90387a899c5SKevin Wolf     max_devs = if_max_devs[type];
90487a899c5SKevin Wolf 
90587a899c5SKevin Wolf     if (index != -1) {
90687a899c5SKevin Wolf         if (bus_id != 0 || unit_id != -1) {
907c4f26c9fSMarkus Armbruster             error_setg(errp, "index cannot be used with bus and unit");
90887a899c5SKevin Wolf             goto fail;
90987a899c5SKevin Wolf         }
91087a899c5SKevin Wolf         bus_id = drive_index_to_bus_id(type, index);
91187a899c5SKevin Wolf         unit_id = drive_index_to_unit_id(type, index);
91287a899c5SKevin Wolf     }
91387a899c5SKevin Wolf 
91487a899c5SKevin Wolf     if (unit_id == -1) {
91587a899c5SKevin Wolf        unit_id = 0;
91687a899c5SKevin Wolf        while (drive_get(type, bus_id, unit_id) != NULL) {
91787a899c5SKevin Wolf            unit_id++;
91887a899c5SKevin Wolf            if (max_devs && unit_id >= max_devs) {
91987a899c5SKevin Wolf                unit_id -= max_devs;
92087a899c5SKevin Wolf                bus_id++;
92187a899c5SKevin Wolf            }
92287a899c5SKevin Wolf        }
92387a899c5SKevin Wolf     }
92487a899c5SKevin Wolf 
92587a899c5SKevin Wolf     if (max_devs && unit_id >= max_devs) {
926c4f26c9fSMarkus Armbruster         error_setg(errp, "unit %d too big (max is %d)", unit_id, max_devs - 1);
92787a899c5SKevin Wolf         goto fail;
92887a899c5SKevin Wolf     }
92987a899c5SKevin Wolf 
93087a899c5SKevin Wolf     if (drive_get(type, bus_id, unit_id) != NULL) {
931c4f26c9fSMarkus Armbruster         error_setg(errp, "drive with bus=%d, unit=%d (index=%d) exists",
93287a899c5SKevin Wolf                    bus_id, unit_id, index);
93387a899c5SKevin Wolf         goto fail;
93487a899c5SKevin Wolf     }
93587a899c5SKevin Wolf 
93687a899c5SKevin Wolf     /* no id supplied -> create one */
93787a899c5SKevin Wolf     if (qemu_opts_id(all_opts) == NULL) {
93887a899c5SKevin Wolf         char *new_id;
93987a899c5SKevin Wolf         const char *mediastr = "";
94087a899c5SKevin Wolf         if (type == IF_IDE || type == IF_SCSI) {
94187a899c5SKevin Wolf             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
94287a899c5SKevin Wolf         }
94387a899c5SKevin Wolf         if (max_devs) {
94487a899c5SKevin Wolf             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
94587a899c5SKevin Wolf                                      mediastr, unit_id);
94687a899c5SKevin Wolf         } else {
94787a899c5SKevin Wolf             new_id = g_strdup_printf("%s%s%i", if_name[type],
94887a899c5SKevin Wolf                                      mediastr, unit_id);
94987a899c5SKevin Wolf         }
95046f5ac20SEric Blake         qdict_put_str(bs_opts, "id", new_id);
95187a899c5SKevin Wolf         g_free(new_id);
95287a899c5SKevin Wolf     }
95387a899c5SKevin Wolf 
954394c7d4dSKevin Wolf     /* Add virtio block device */
955394c7d4dSKevin Wolf     if (type == IF_VIRTIO) {
956394c7d4dSKevin Wolf         QemuOpts *devopts;
95787ea75d5SPeter Crosthwaite         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
95887ea75d5SPeter Crosthwaite                                    &error_abort);
959394c7d4dSKevin Wolf         if (arch_type == QEMU_ARCH_S390X) {
9601f68f1d3SAlexander Graf             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
961394c7d4dSKevin Wolf         } else {
962f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
963394c7d4dSKevin Wolf         }
964f43e47dbSMarkus Armbruster         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
965f43e47dbSMarkus Armbruster                      &error_abort);
966394c7d4dSKevin Wolf     }
967394c7d4dSKevin Wolf 
968d095b465SMax Reitz     filename = qemu_opt_get(legacy_opts, "file");
969d095b465SMax Reitz 
970ee13ed1cSKevin Wolf     /* Check werror/rerror compatibility with if=... */
971ee13ed1cSKevin Wolf     werror = qemu_opt_get(legacy_opts, "werror");
972ee13ed1cSKevin Wolf     if (werror != NULL) {
973ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
974ee13ed1cSKevin Wolf             type != IF_NONE) {
975c4f26c9fSMarkus Armbruster             error_setg(errp, "werror is not supported by this bus type");
976ee13ed1cSKevin Wolf             goto fail;
977ee13ed1cSKevin Wolf         }
97846f5ac20SEric Blake         qdict_put_str(bs_opts, "werror", werror);
979ee13ed1cSKevin Wolf     }
980ee13ed1cSKevin Wolf 
981ee13ed1cSKevin Wolf     rerror = qemu_opt_get(legacy_opts, "rerror");
982ee13ed1cSKevin Wolf     if (rerror != NULL) {
983ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
984ee13ed1cSKevin Wolf             type != IF_NONE) {
985c4f26c9fSMarkus Armbruster             error_setg(errp, "rerror is not supported by this bus type");
986ee13ed1cSKevin Wolf             goto fail;
987ee13ed1cSKevin Wolf         }
98846f5ac20SEric Blake         qdict_put_str(bs_opts, "rerror", rerror);
989ee13ed1cSKevin Wolf     }
990ee13ed1cSKevin Wolf 
9912d246f01SKevin Wolf     /* Actual block device init: Functionality shared with blockdev-add */
99218e46a03SMarkus Armbruster     blk = blockdev_init(filename, bs_opts, &local_err);
9933cb0e25cSMarkus Armbruster     bs_opts = NULL;
99418e46a03SMarkus Armbruster     if (!blk) {
995c4f26c9fSMarkus Armbruster         error_propagate(errp, local_err);
9962d246f01SKevin Wolf         goto fail;
997b681072dSKevin Wolf     } else {
99884d18f06SMarkus Armbruster         assert(!local_err);
9992d246f01SKevin Wolf     }
10002d246f01SKevin Wolf 
100126f8b3a8SMarkus Armbruster     /* Create legacy DriveInfo */
100226f8b3a8SMarkus Armbruster     dinfo = g_malloc0(sizeof(*dinfo));
1003f298d071SKevin Wolf     dinfo->opts = all_opts;
10042d246f01SKevin Wolf 
1005ee13ed1cSKevin Wolf     dinfo->type = type;
100687a899c5SKevin Wolf     dinfo->bus = bus_id;
100787a899c5SKevin Wolf     dinfo->unit = unit_id;
1008bcf83158SKevin Wolf 
100926f8b3a8SMarkus Armbruster     blk_set_legacy_dinfo(blk, dinfo);
101026f8b3a8SMarkus Armbruster 
1011e34ef046SKevin Wolf     switch(type) {
1012e34ef046SKevin Wolf     case IF_IDE:
1013e34ef046SKevin Wolf     case IF_SCSI:
1014e34ef046SKevin Wolf     case IF_XEN:
1015e34ef046SKevin Wolf     case IF_NONE:
1016e34ef046SKevin Wolf         dinfo->media_cd = media == MEDIA_CDROM;
1017e34ef046SKevin Wolf         break;
1018e34ef046SKevin Wolf     default:
1019e34ef046SKevin Wolf         break;
1020e34ef046SKevin Wolf     }
1021e34ef046SKevin Wolf 
10222d246f01SKevin Wolf fail:
102333cb7dc8SKevin Wolf     qemu_opts_del(legacy_opts);
1024cb3e7f08SMarc-André Lureau     qobject_unref(bs_opts);
10252d246f01SKevin Wolf     return dinfo;
102657975222SKevin Wolf }
102757975222SKevin Wolf 
1028b6c1bae5SKevin Wolf static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1029b6c1bae5SKevin Wolf {
1030b6c1bae5SKevin Wolf     BlockDriverState *bs;
1031b6c1bae5SKevin Wolf 
1032b6c1bae5SKevin Wolf     bs = bdrv_lookup_bs(name, name, errp);
1033b6c1bae5SKevin Wolf     if (bs == NULL) {
1034b6c1bae5SKevin Wolf         return NULL;
1035b6c1bae5SKevin Wolf     }
1036b6c1bae5SKevin Wolf 
1037b6c1bae5SKevin Wolf     if (!bdrv_is_root_node(bs)) {
1038b6c1bae5SKevin Wolf         error_setg(errp, "Need a root block node");
1039b6c1bae5SKevin Wolf         return NULL;
1040b6c1bae5SKevin Wolf     }
1041b6c1bae5SKevin Wolf 
1042b6c1bae5SKevin Wolf     if (!bdrv_is_inserted(bs)) {
1043b6c1bae5SKevin Wolf         error_setg(errp, "Device has no medium");
1044b6c1bae5SKevin Wolf         return NULL;
1045b6c1bae5SKevin Wolf     }
1046b6c1bae5SKevin Wolf 
1047b6c1bae5SKevin Wolf     return bs;
1048b6c1bae5SKevin Wolf }
1049b6c1bae5SKevin Wolf 
1050b33945cfSKevin Wolf static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1051b33945cfSKevin Wolf                                  Error **errp)
1052b33945cfSKevin Wolf {
1053b33945cfSKevin Wolf     BlockBackend *blk;
1054b33945cfSKevin Wolf 
1055b33945cfSKevin Wolf     if (!blk_name == !qdev_id) {
1056b33945cfSKevin Wolf         error_setg(errp, "Need exactly one of 'device' and 'id'");
1057b33945cfSKevin Wolf         return NULL;
1058b33945cfSKevin Wolf     }
1059b33945cfSKevin Wolf 
1060b33945cfSKevin Wolf     if (qdev_id) {
1061b33945cfSKevin Wolf         blk = blk_by_qdev_id(qdev_id, errp);
1062b33945cfSKevin Wolf     } else {
1063b33945cfSKevin Wolf         blk = blk_by_name(blk_name);
1064b33945cfSKevin Wolf         if (blk == NULL) {
1065b33945cfSKevin Wolf             error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1066b33945cfSKevin Wolf                       "Device '%s' not found", blk_name);
1067b33945cfSKevin Wolf         }
1068b33945cfSKevin Wolf     }
1069b33945cfSKevin Wolf 
1070b33945cfSKevin Wolf     return blk;
1071b33945cfSKevin Wolf }
1072b33945cfSKevin Wolf 
10733e5a50d6SMarkus Armbruster void hmp_commit(Monitor *mon, const QDict *qdict)
1074666daa68SMarkus Armbruster {
1075666daa68SMarkus Armbruster     const char *device = qdict_get_str(qdict, "device");
1076a0e8544cSFam Zheng     BlockBackend *blk;
10772d3735d3SStefan Hajnoczi     int ret;
10782d3735d3SStefan Hajnoczi 
1079e8877497SStefan Hajnoczi     if (!strcmp(device, "all")) {
1080da31d594SMax Reitz         ret = blk_commit_all();
1081e8877497SStefan Hajnoczi     } else {
108284aa0140SStefan Hajnoczi         BlockDriverState *bs;
108384aa0140SStefan Hajnoczi         AioContext *aio_context;
108484aa0140SStefan Hajnoczi 
1085a0e8544cSFam Zheng         blk = blk_by_name(device);
1086a0e8544cSFam Zheng         if (!blk) {
108758513bdeSJeff Cody             monitor_printf(mon, "Device '%s' not found\n", device);
1088ac59eb95SMarkus Armbruster             return;
10896ab4b5abSMarkus Armbruster         }
10905433c24fSMax Reitz         if (!blk_is_available(blk)) {
10915433c24fSMax Reitz             monitor_printf(mon, "Device '%s' has no medium\n", device);
10925433c24fSMax Reitz             return;
10935433c24fSMax Reitz         }
109484aa0140SStefan Hajnoczi 
109584aa0140SStefan Hajnoczi         bs = blk_bs(blk);
109684aa0140SStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
109784aa0140SStefan Hajnoczi         aio_context_acquire(aio_context);
109884aa0140SStefan Hajnoczi 
109984aa0140SStefan Hajnoczi         ret = bdrv_commit(bs);
110084aa0140SStefan Hajnoczi 
110184aa0140SStefan Hajnoczi         aio_context_release(aio_context);
11022d3735d3SStefan Hajnoczi     }
110358513bdeSJeff Cody     if (ret < 0) {
110458513bdeSJeff Cody         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
110558513bdeSJeff Cody                        strerror(-ret));
1106666daa68SMarkus Armbruster     }
1107666daa68SMarkus Armbruster }
1108666daa68SMarkus Armbruster 
110910f75907SEric Blake static void blockdev_do_action(TransactionAction *action, Error **errp)
11106cc2a415SPaolo Bonzini {
1111c8a83e85SKevin Wolf     TransactionActionList list;
11126cc2a415SPaolo Bonzini 
111310f75907SEric Blake     list.value = action;
11146cc2a415SPaolo Bonzini     list.next = NULL;
111594d16a64SJohn Snow     qmp_transaction(&list, false, NULL, errp);
11166cc2a415SPaolo Bonzini }
11176cc2a415SPaolo Bonzini 
11180901f67eSBenoît Canet void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
11190901f67eSBenoît Canet                                 bool has_node_name, const char *node_name,
11200901f67eSBenoît Canet                                 const char *snapshot_file,
11210901f67eSBenoît Canet                                 bool has_snapshot_node_name,
11220901f67eSBenoît Canet                                 const char *snapshot_node_name,
11236106e249SLuiz Capitulino                                 bool has_format, const char *format,
11240901f67eSBenoît Canet                                 bool has_mode, NewImageMode mode, Error **errp)
1125f8882568SJes Sorensen {
1126a911e6aeSAlberto Garcia     BlockdevSnapshotSync snapshot = {
11270901f67eSBenoît Canet         .has_device = has_device,
11286cc2a415SPaolo Bonzini         .device = (char *) device,
11290901f67eSBenoît Canet         .has_node_name = has_node_name,
11300901f67eSBenoît Canet         .node_name = (char *) node_name,
11316cc2a415SPaolo Bonzini         .snapshot_file = (char *) snapshot_file,
11320901f67eSBenoît Canet         .has_snapshot_node_name = has_snapshot_node_name,
11330901f67eSBenoît Canet         .snapshot_node_name = (char *) snapshot_node_name,
11346cc2a415SPaolo Bonzini         .has_format = has_format,
11356cc2a415SPaolo Bonzini         .format = (char *) format,
11366cc2a415SPaolo Bonzini         .has_mode = has_mode,
11376cc2a415SPaolo Bonzini         .mode = mode,
11386cc2a415SPaolo Bonzini     };
113910f75907SEric Blake     TransactionAction action = {
114010f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
114132bafa8fSEric Blake         .u.blockdev_snapshot_sync.data = &snapshot,
114210f75907SEric Blake     };
114310f75907SEric Blake     blockdev_do_action(&action, errp);
1144f8882568SJes Sorensen }
1145f8882568SJes Sorensen 
114643de7e2dSAlberto Garcia void qmp_blockdev_snapshot(const char *node, const char *overlay,
114743de7e2dSAlberto Garcia                            Error **errp)
114843de7e2dSAlberto Garcia {
114943de7e2dSAlberto Garcia     BlockdevSnapshot snapshot_data = {
115043de7e2dSAlberto Garcia         .node = (char *) node,
115143de7e2dSAlberto Garcia         .overlay = (char *) overlay
115243de7e2dSAlberto Garcia     };
115310f75907SEric Blake     TransactionAction action = {
115410f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
115532bafa8fSEric Blake         .u.blockdev_snapshot.data = &snapshot_data,
115610f75907SEric Blake     };
115710f75907SEric Blake     blockdev_do_action(&action, errp);
115843de7e2dSAlberto Garcia }
115943de7e2dSAlberto Garcia 
1160f323bc9eSWenchao Xia void qmp_blockdev_snapshot_internal_sync(const char *device,
1161f323bc9eSWenchao Xia                                          const char *name,
1162f323bc9eSWenchao Xia                                          Error **errp)
1163f323bc9eSWenchao Xia {
1164f323bc9eSWenchao Xia     BlockdevSnapshotInternal snapshot = {
1165f323bc9eSWenchao Xia         .device = (char *) device,
1166f323bc9eSWenchao Xia         .name = (char *) name
1167f323bc9eSWenchao Xia     };
116810f75907SEric Blake     TransactionAction action = {
116910f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
117032bafa8fSEric Blake         .u.blockdev_snapshot_internal_sync.data = &snapshot,
117110f75907SEric Blake     };
117210f75907SEric Blake     blockdev_do_action(&action, errp);
1173f323bc9eSWenchao Xia }
1174f323bc9eSWenchao Xia 
117544e3e053SWenchao Xia SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
117644e3e053SWenchao Xia                                                          bool has_id,
117744e3e053SWenchao Xia                                                          const char *id,
117844e3e053SWenchao Xia                                                          bool has_name,
117944e3e053SWenchao Xia                                                          const char *name,
118044e3e053SWenchao Xia                                                          Error **errp)
118144e3e053SWenchao Xia {
1182a0e8544cSFam Zheng     BlockDriverState *bs;
11834ef3982aSStefan Hajnoczi     AioContext *aio_context;
118444e3e053SWenchao Xia     QEMUSnapshotInfo sn;
118544e3e053SWenchao Xia     Error *local_err = NULL;
118644e3e053SWenchao Xia     SnapshotInfo *info = NULL;
118744e3e053SWenchao Xia     int ret;
118844e3e053SWenchao Xia 
11892dfb4c03SKevin Wolf     bs = qmp_get_root_bs(device, errp);
11902dfb4c03SKevin Wolf     if (!bs) {
119144e3e053SWenchao Xia         return NULL;
119244e3e053SWenchao Xia     }
11932dfb4c03SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
11945433c24fSMax Reitz     aio_context_acquire(aio_context);
119544e3e053SWenchao Xia 
119644e3e053SWenchao Xia     if (!has_id) {
119744e3e053SWenchao Xia         id = NULL;
119844e3e053SWenchao Xia     }
119944e3e053SWenchao Xia 
120044e3e053SWenchao Xia     if (!has_name) {
120144e3e053SWenchao Xia         name = NULL;
120244e3e053SWenchao Xia     }
120344e3e053SWenchao Xia 
120444e3e053SWenchao Xia     if (!id && !name) {
120544e3e053SWenchao Xia         error_setg(errp, "Name or id must be provided");
12065433c24fSMax Reitz         goto out_aio_context;
120744e3e053SWenchao Xia     }
120844e3e053SWenchao Xia 
12090b928854SStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
12100b928854SStefan Hajnoczi         goto out_aio_context;
12110b928854SStefan Hajnoczi     }
12120b928854SStefan Hajnoczi 
121344e3e053SWenchao Xia     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
121484d18f06SMarkus Armbruster     if (local_err) {
121544e3e053SWenchao Xia         error_propagate(errp, local_err);
12164ef3982aSStefan Hajnoczi         goto out_aio_context;
121744e3e053SWenchao Xia     }
121844e3e053SWenchao Xia     if (!ret) {
121944e3e053SWenchao Xia         error_setg(errp,
122044e3e053SWenchao Xia                    "Snapshot with id '%s' and name '%s' does not exist on "
122144e3e053SWenchao Xia                    "device '%s'",
122244e3e053SWenchao Xia                    STR_OR_NULL(id), STR_OR_NULL(name), device);
12234ef3982aSStefan Hajnoczi         goto out_aio_context;
122444e3e053SWenchao Xia     }
122544e3e053SWenchao Xia 
122644e3e053SWenchao Xia     bdrv_snapshot_delete(bs, id, name, &local_err);
122784d18f06SMarkus Armbruster     if (local_err) {
122844e3e053SWenchao Xia         error_propagate(errp, local_err);
12294ef3982aSStefan Hajnoczi         goto out_aio_context;
123044e3e053SWenchao Xia     }
123144e3e053SWenchao Xia 
12324ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
12334ef3982aSStefan Hajnoczi 
12345839e53bSMarkus Armbruster     info = g_new0(SnapshotInfo, 1);
123544e3e053SWenchao Xia     info->id = g_strdup(sn.id_str);
123644e3e053SWenchao Xia     info->name = g_strdup(sn.name);
123744e3e053SWenchao Xia     info->date_nsec = sn.date_nsec;
123844e3e053SWenchao Xia     info->date_sec = sn.date_sec;
123944e3e053SWenchao Xia     info->vm_state_size = sn.vm_state_size;
124044e3e053SWenchao Xia     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
124144e3e053SWenchao Xia     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
124244e3e053SWenchao Xia 
124344e3e053SWenchao Xia     return info;
12444ef3982aSStefan Hajnoczi 
12454ef3982aSStefan Hajnoczi out_aio_context:
12464ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
12474ef3982aSStefan Hajnoczi     return NULL;
124844e3e053SWenchao Xia }
12498802d1fdSJeff Cody 
1250341ebc2fSJohn Snow /**
1251341ebc2fSJohn Snow  * block_dirty_bitmap_lookup:
1252341ebc2fSJohn Snow  * Return a dirty bitmap (if present), after validating
1253341ebc2fSJohn Snow  * the node reference and bitmap names.
1254341ebc2fSJohn Snow  *
1255341ebc2fSJohn Snow  * @node: The name of the BDS node to search for bitmaps
1256341ebc2fSJohn Snow  * @name: The name of the bitmap to search for
1257341ebc2fSJohn Snow  * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1258341ebc2fSJohn Snow  * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1259341ebc2fSJohn Snow  * @errp: Output pointer for error information. Can be NULL.
1260341ebc2fSJohn Snow  *
1261341ebc2fSJohn Snow  * @return: A bitmap object on success, or NULL on failure.
1262341ebc2fSJohn Snow  */
1263341ebc2fSJohn Snow static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1264341ebc2fSJohn Snow                                                   const char *name,
1265341ebc2fSJohn Snow                                                   BlockDriverState **pbs,
1266341ebc2fSJohn Snow                                                   Error **errp)
1267341ebc2fSJohn Snow {
1268341ebc2fSJohn Snow     BlockDriverState *bs;
1269341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
1270341ebc2fSJohn Snow 
1271341ebc2fSJohn Snow     if (!node) {
1272341ebc2fSJohn Snow         error_setg(errp, "Node cannot be NULL");
1273341ebc2fSJohn Snow         return NULL;
1274341ebc2fSJohn Snow     }
1275341ebc2fSJohn Snow     if (!name) {
1276341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be NULL");
1277341ebc2fSJohn Snow         return NULL;
1278341ebc2fSJohn Snow     }
1279341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, NULL);
1280341ebc2fSJohn Snow     if (!bs) {
1281341ebc2fSJohn Snow         error_setg(errp, "Node '%s' not found", node);
1282341ebc2fSJohn Snow         return NULL;
1283341ebc2fSJohn Snow     }
1284341ebc2fSJohn Snow 
1285341ebc2fSJohn Snow     bitmap = bdrv_find_dirty_bitmap(bs, name);
1286341ebc2fSJohn Snow     if (!bitmap) {
1287341ebc2fSJohn Snow         error_setg(errp, "Dirty bitmap '%s' not found", name);
12882119882cSPaolo Bonzini         return NULL;
1289341ebc2fSJohn Snow     }
1290341ebc2fSJohn Snow 
1291341ebc2fSJohn Snow     if (pbs) {
1292341ebc2fSJohn Snow         *pbs = bs;
1293341ebc2fSJohn Snow     }
1294341ebc2fSJohn Snow 
1295341ebc2fSJohn Snow     return bitmap;
1296341ebc2fSJohn Snow }
1297341ebc2fSJohn Snow 
1298b756b9ceSStefan Hajnoczi /* New and old BlockDriverState structs for atomic group operations */
1299ba0c86a3SWenchao Xia 
130050f43f0fSJohn Snow typedef struct BlkActionState BlkActionState;
1301ba0c86a3SWenchao Xia 
130250f43f0fSJohn Snow /**
130350f43f0fSJohn Snow  * BlkActionOps:
130450f43f0fSJohn Snow  * Table of operations that define an Action.
130550f43f0fSJohn Snow  *
130650f43f0fSJohn Snow  * @instance_size: Size of state struct, in bytes.
130750f43f0fSJohn Snow  * @prepare: Prepare the work, must NOT be NULL.
130850f43f0fSJohn Snow  * @commit: Commit the changes, can be NULL.
130950f43f0fSJohn Snow  * @abort: Abort the changes on fail, can be NULL.
131050f43f0fSJohn Snow  * @clean: Clean up resources after all transaction actions have called
131150f43f0fSJohn Snow  *         commit() or abort(). Can be NULL.
131250f43f0fSJohn Snow  *
131350f43f0fSJohn Snow  * Only prepare() may fail. In a single transaction, only one of commit() or
131450f43f0fSJohn Snow  * abort() will be called. clean() will always be called if it is present.
1315ba0c86a3SWenchao Xia  */
131650f43f0fSJohn Snow typedef struct BlkActionOps {
131750f43f0fSJohn Snow     size_t instance_size;
131850f43f0fSJohn Snow     void (*prepare)(BlkActionState *common, Error **errp);
131950f43f0fSJohn Snow     void (*commit)(BlkActionState *common);
132050f43f0fSJohn Snow     void (*abort)(BlkActionState *common);
132150f43f0fSJohn Snow     void (*clean)(BlkActionState *common);
132250f43f0fSJohn Snow } BlkActionOps;
132350f43f0fSJohn Snow 
132450f43f0fSJohn Snow /**
132550f43f0fSJohn Snow  * BlkActionState:
132650f43f0fSJohn Snow  * Describes one Action's state within a Transaction.
132750f43f0fSJohn Snow  *
132850f43f0fSJohn Snow  * @action: QAPI-defined enum identifying which Action to perform.
132950f43f0fSJohn Snow  * @ops: Table of ActionOps this Action can perform.
133094d16a64SJohn Snow  * @block_job_txn: Transaction which this action belongs to.
133150f43f0fSJohn Snow  * @entry: List membership for all Actions in this Transaction.
133250f43f0fSJohn Snow  *
133350f43f0fSJohn Snow  * This structure must be arranged as first member in a subclassed type,
133450f43f0fSJohn Snow  * assuming that the compiler will also arrange it to the same offsets as the
133550f43f0fSJohn Snow  * base class.
133650f43f0fSJohn Snow  */
133750f43f0fSJohn Snow struct BlkActionState {
1338c8a83e85SKevin Wolf     TransactionAction *action;
133950f43f0fSJohn Snow     const BlkActionOps *ops;
134062c9e416SKevin Wolf     JobTxn *block_job_txn;
134194d16a64SJohn Snow     TransactionProperties *txn_props;
1342f4de0f8cSJohn Snow     QTAILQ_ENTRY(BlkActionState) entry;
1343ba0c86a3SWenchao Xia };
1344ba0c86a3SWenchao Xia 
1345bbe86010SWenchao Xia /* internal snapshot private data */
1346bbe86010SWenchao Xia typedef struct InternalSnapshotState {
134750f43f0fSJohn Snow     BlkActionState common;
1348bbe86010SWenchao Xia     BlockDriverState *bs;
1349bbe86010SWenchao Xia     QEMUSnapshotInfo sn;
1350507306ccSFam Zheng     bool created;
1351bbe86010SWenchao Xia } InternalSnapshotState;
1352bbe86010SWenchao Xia 
135394d16a64SJohn Snow 
135494d16a64SJohn Snow static int action_check_completion_mode(BlkActionState *s, Error **errp)
135594d16a64SJohn Snow {
135694d16a64SJohn Snow     if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
135794d16a64SJohn Snow         error_setg(errp,
135894d16a64SJohn Snow                    "Action '%s' does not support Transaction property "
135994d16a64SJohn Snow                    "completion-mode = %s",
1360977c736fSMarkus Armbruster                    TransactionActionKind_str(s->action->type),
1361977c736fSMarkus Armbruster                    ActionCompletionMode_str(s->txn_props->completion_mode));
136294d16a64SJohn Snow         return -1;
136394d16a64SJohn Snow     }
136494d16a64SJohn Snow     return 0;
136594d16a64SJohn Snow }
136694d16a64SJohn Snow 
136750f43f0fSJohn Snow static void internal_snapshot_prepare(BlkActionState *common,
1368bbe86010SWenchao Xia                                       Error **errp)
1369bbe86010SWenchao Xia {
1370f70edf99SMarkus Armbruster     Error *local_err = NULL;
1371bbe86010SWenchao Xia     const char *device;
1372bbe86010SWenchao Xia     const char *name;
1373bbe86010SWenchao Xia     BlockDriverState *bs;
1374bbe86010SWenchao Xia     QEMUSnapshotInfo old_sn, *sn;
1375bbe86010SWenchao Xia     bool ret;
1376bbe86010SWenchao Xia     qemu_timeval tv;
1377bbe86010SWenchao Xia     BlockdevSnapshotInternal *internal;
1378bbe86010SWenchao Xia     InternalSnapshotState *state;
1379a36e458cSStefan Hajnoczi     AioContext *aio_context;
1380bbe86010SWenchao Xia     int ret1;
1381bbe86010SWenchao Xia 
13826a8f9661SEric Blake     g_assert(common->action->type ==
1383bbe86010SWenchao Xia              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
138432bafa8fSEric Blake     internal = common->action->u.blockdev_snapshot_internal_sync.data;
1385bbe86010SWenchao Xia     state = DO_UPCAST(InternalSnapshotState, common, common);
1386bbe86010SWenchao Xia 
1387bbe86010SWenchao Xia     /* 1. parse input */
1388bbe86010SWenchao Xia     device = internal->device;
1389bbe86010SWenchao Xia     name = internal->name;
1390bbe86010SWenchao Xia 
1391bbe86010SWenchao Xia     /* 2. check for validation */
139294d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
139394d16a64SJohn Snow         return;
139494d16a64SJohn Snow     }
139594d16a64SJohn Snow 
139675dfd402SKevin Wolf     bs = qmp_get_root_bs(device, errp);
139775dfd402SKevin Wolf     if (!bs) {
1398bbe86010SWenchao Xia         return;
1399bbe86010SWenchao Xia     }
1400bbe86010SWenchao Xia 
1401a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
1402a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
14035d6e96efSStefan Hajnoczi 
1404507306ccSFam Zheng     state->bs = bs;
1405a36e458cSStefan Hajnoczi 
1406a36e458cSStefan Hajnoczi     /* Paired with .clean() */
1407507306ccSFam Zheng     bdrv_drained_begin(bs);
1408507306ccSFam Zheng 
14093dc7ca3cSStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1410a36e458cSStefan Hajnoczi         goto out;
14113dc7ca3cSStefan Hajnoczi     }
14123dc7ca3cSStefan Hajnoczi 
1413bbe86010SWenchao Xia     if (bdrv_is_read_only(bs)) {
141481e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
1415a36e458cSStefan Hajnoczi         goto out;
1416bbe86010SWenchao Xia     }
1417bbe86010SWenchao Xia 
1418bbe86010SWenchao Xia     if (!bdrv_can_snapshot(bs)) {
141981e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by device '%s' "
142081e5f78aSAlberto Garcia                    "does not support internal snapshots",
142181e5f78aSAlberto Garcia                    bs->drv->format_name, device);
1422a36e458cSStefan Hajnoczi         goto out;
1423bbe86010SWenchao Xia     }
1424bbe86010SWenchao Xia 
1425bbe86010SWenchao Xia     if (!strlen(name)) {
1426bbe86010SWenchao Xia         error_setg(errp, "Name is empty");
1427a36e458cSStefan Hajnoczi         goto out;
1428bbe86010SWenchao Xia     }
1429bbe86010SWenchao Xia 
1430bbe86010SWenchao Xia     /* check whether a snapshot with name exist */
1431f70edf99SMarkus Armbruster     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1432f70edf99SMarkus Armbruster                                             &local_err);
1433f70edf99SMarkus Armbruster     if (local_err) {
1434f70edf99SMarkus Armbruster         error_propagate(errp, local_err);
1435a36e458cSStefan Hajnoczi         goto out;
1436bbe86010SWenchao Xia     } else if (ret) {
1437bbe86010SWenchao Xia         error_setg(errp,
1438bbe86010SWenchao Xia                    "Snapshot with name '%s' already exists on device '%s'",
1439bbe86010SWenchao Xia                    name, device);
1440a36e458cSStefan Hajnoczi         goto out;
1441bbe86010SWenchao Xia     }
1442bbe86010SWenchao Xia 
1443bbe86010SWenchao Xia     /* 3. take the snapshot */
1444bbe86010SWenchao Xia     sn = &state->sn;
1445bbe86010SWenchao Xia     pstrcpy(sn->name, sizeof(sn->name), name);
1446bbe86010SWenchao Xia     qemu_gettimeofday(&tv);
1447bbe86010SWenchao Xia     sn->date_sec = tv.tv_sec;
1448bbe86010SWenchao Xia     sn->date_nsec = tv.tv_usec * 1000;
1449bbe86010SWenchao Xia     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1450bbe86010SWenchao Xia 
1451bbe86010SWenchao Xia     ret1 = bdrv_snapshot_create(bs, sn);
1452bbe86010SWenchao Xia     if (ret1 < 0) {
1453bbe86010SWenchao Xia         error_setg_errno(errp, -ret1,
1454bbe86010SWenchao Xia                          "Failed to create snapshot '%s' on device '%s'",
1455bbe86010SWenchao Xia                          name, device);
1456a36e458cSStefan Hajnoczi         goto out;
1457bbe86010SWenchao Xia     }
1458bbe86010SWenchao Xia 
1459bbe86010SWenchao Xia     /* 4. succeed, mark a snapshot is created */
1460507306ccSFam Zheng     state->created = true;
1461a36e458cSStefan Hajnoczi 
1462a36e458cSStefan Hajnoczi out:
1463a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
1464bbe86010SWenchao Xia }
1465bbe86010SWenchao Xia 
146650f43f0fSJohn Snow static void internal_snapshot_abort(BlkActionState *common)
1467bbe86010SWenchao Xia {
1468bbe86010SWenchao Xia     InternalSnapshotState *state =
1469bbe86010SWenchao Xia                              DO_UPCAST(InternalSnapshotState, common, common);
1470bbe86010SWenchao Xia     BlockDriverState *bs = state->bs;
1471bbe86010SWenchao Xia     QEMUSnapshotInfo *sn = &state->sn;
1472a36e458cSStefan Hajnoczi     AioContext *aio_context;
1473bbe86010SWenchao Xia     Error *local_error = NULL;
1474bbe86010SWenchao Xia 
1475507306ccSFam Zheng     if (!state->created) {
1476bbe86010SWenchao Xia         return;
1477bbe86010SWenchao Xia     }
1478bbe86010SWenchao Xia 
1479a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1480a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
1481a36e458cSStefan Hajnoczi 
1482bbe86010SWenchao Xia     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1483c29b77f9SMarkus Armbruster         error_reportf_err(local_error,
1484c29b77f9SMarkus Armbruster                           "Failed to delete snapshot with id '%s' and "
1485c29b77f9SMarkus Armbruster                           "name '%s' on device '%s' in abort: ",
1486c29b77f9SMarkus Armbruster                           sn->id_str, sn->name,
1487c29b77f9SMarkus Armbruster                           bdrv_get_device_name(bs));
1488bbe86010SWenchao Xia     }
1489a36e458cSStefan Hajnoczi 
1490a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
1491bbe86010SWenchao Xia }
1492bbe86010SWenchao Xia 
149350f43f0fSJohn Snow static void internal_snapshot_clean(BlkActionState *common)
14945d6e96efSStefan Hajnoczi {
14955d6e96efSStefan Hajnoczi     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
14965d6e96efSStefan Hajnoczi                                              common, common);
1497a36e458cSStefan Hajnoczi     AioContext *aio_context;
14985d6e96efSStefan Hajnoczi 
1499a36e458cSStefan Hajnoczi     if (!state->bs) {
1500a36e458cSStefan Hajnoczi         return;
1501a36e458cSStefan Hajnoczi     }
1502a36e458cSStefan Hajnoczi 
1503a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1504a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
1505a36e458cSStefan Hajnoczi 
1506507306ccSFam Zheng     bdrv_drained_end(state->bs);
1507a36e458cSStefan Hajnoczi 
1508a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
15095d6e96efSStefan Hajnoczi }
15105d6e96efSStefan Hajnoczi 
1511ba0c86a3SWenchao Xia /* external snapshot private data */
1512ba5d6ab6SStefan Hajnoczi typedef struct ExternalSnapshotState {
151350f43f0fSJohn Snow     BlkActionState common;
15148802d1fdSJeff Cody     BlockDriverState *old_bs;
15158802d1fdSJeff Cody     BlockDriverState *new_bs;
1516067acf28SKevin Wolf     bool overlay_appended;
1517ba5d6ab6SStefan Hajnoczi } ExternalSnapshotState;
15188802d1fdSJeff Cody 
151950f43f0fSJohn Snow static void external_snapshot_prepare(BlkActionState *common,
15209b9877eeSWenchao Xia                                       Error **errp)
15219b9877eeSWenchao Xia {
15225b363937SMax Reitz     int flags = 0;
152343de7e2dSAlberto Garcia     QDict *options = NULL;
15249b9877eeSWenchao Xia     Error *local_err = NULL;
152543de7e2dSAlberto Garcia     /* Device and node name of the image to generate the snapshot from */
1526e2a31e87SWenchao Xia     const char *device;
15270901f67eSBenoît Canet     const char *node_name;
152843de7e2dSAlberto Garcia     /* Reference to the new image (for 'blockdev-snapshot') */
152943de7e2dSAlberto Garcia     const char *snapshot_ref;
153043de7e2dSAlberto Garcia     /* File name of the new image (for 'blockdev-snapshot-sync') */
1531e2a31e87SWenchao Xia     const char *new_image_file;
1532ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1533ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1534c8a83e85SKevin Wolf     TransactionAction *action = common->action;
15352d24b60bSStefan Hajnoczi     AioContext *aio_context;
15369b9877eeSWenchao Xia 
153743de7e2dSAlberto Garcia     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
153843de7e2dSAlberto Garcia      * purpose but a different set of parameters */
153943de7e2dSAlberto Garcia     switch (action->type) {
154043de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
154143de7e2dSAlberto Garcia         {
154232bafa8fSEric Blake             BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
154343de7e2dSAlberto Garcia             device = s->node;
154443de7e2dSAlberto Garcia             node_name = s->node;
154543de7e2dSAlberto Garcia             new_image_file = NULL;
154643de7e2dSAlberto Garcia             snapshot_ref = s->overlay;
1547e2a31e87SWenchao Xia         }
154843de7e2dSAlberto Garcia         break;
154943de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
155043de7e2dSAlberto Garcia         {
155132bafa8fSEric Blake             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
155243de7e2dSAlberto Garcia             device = s->has_device ? s->device : NULL;
155343de7e2dSAlberto Garcia             node_name = s->has_node_name ? s->node_name : NULL;
155443de7e2dSAlberto Garcia             new_image_file = s->snapshot_file;
155543de7e2dSAlberto Garcia             snapshot_ref = NULL;
155643de7e2dSAlberto Garcia         }
155743de7e2dSAlberto Garcia         break;
155843de7e2dSAlberto Garcia     default:
155943de7e2dSAlberto Garcia         g_assert_not_reached();
1560e2a31e87SWenchao Xia     }
1561e2a31e87SWenchao Xia 
1562e2a31e87SWenchao Xia     /* start processing */
156394d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
156494d16a64SJohn Snow         return;
156594d16a64SJohn Snow     }
156694d16a64SJohn Snow 
156743de7e2dSAlberto Garcia     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
156843de7e2dSAlberto Garcia     if (!state->old_bs) {
15699b9877eeSWenchao Xia         return;
15709b9877eeSWenchao Xia     }
15719b9877eeSWenchao Xia 
15722d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
15732d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
15742d24b60bSStefan Hajnoczi 
15752d24b60bSStefan Hajnoczi     /* Paired with .clean() */
1576da763e83SFam Zheng     bdrv_drained_begin(state->old_bs);
15775d6e96efSStefan Hajnoczi 
1578ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_inserted(state->old_bs)) {
1579c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
15802d24b60bSStefan Hajnoczi         goto out;
15819b9877eeSWenchao Xia     }
15829b9877eeSWenchao Xia 
15833718d8abSFam Zheng     if (bdrv_op_is_blocked(state->old_bs,
15843718d8abSFam Zheng                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
15852d24b60bSStefan Hajnoczi         goto out;
15869b9877eeSWenchao Xia     }
15879b9877eeSWenchao Xia 
1588ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_read_only(state->old_bs)) {
1589ba5d6ab6SStefan Hajnoczi         if (bdrv_flush(state->old_bs)) {
1590c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_IO_ERROR);
15912d24b60bSStefan Hajnoczi             goto out;
15929b9877eeSWenchao Xia         }
15939b9877eeSWenchao Xia     }
15949b9877eeSWenchao Xia 
1595212a5a8fSBenoît Canet     if (!bdrv_is_first_non_filter(state->old_bs)) {
1596c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
15972d24b60bSStefan Hajnoczi         goto out;
1598f6186f49SBenoît Canet     }
1599f6186f49SBenoît Canet 
160043de7e2dSAlberto Garcia     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
160132bafa8fSEric Blake         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
160243de7e2dSAlberto Garcia         const char *format = s->has_format ? s->format : "qcow2";
160343de7e2dSAlberto Garcia         enum NewImageMode mode;
160443de7e2dSAlberto Garcia         const char *snapshot_node_name =
160543de7e2dSAlberto Garcia             s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
160643de7e2dSAlberto Garcia 
160743de7e2dSAlberto Garcia         if (node_name && !snapshot_node_name) {
160843de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name missing");
16092d24b60bSStefan Hajnoczi             goto out;
161043de7e2dSAlberto Garcia         }
161143de7e2dSAlberto Garcia 
161243de7e2dSAlberto Garcia         if (snapshot_node_name &&
161343de7e2dSAlberto Garcia             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
161443de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name already in use");
16152d24b60bSStefan Hajnoczi             goto out;
161643de7e2dSAlberto Garcia         }
161743de7e2dSAlberto Garcia 
1618ba5d6ab6SStefan Hajnoczi         flags = state->old_bs->open_flags;
16192a32c6e8SJohn Snow         flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
16202a32c6e8SJohn Snow         flags |= BDRV_O_NO_BACKING;
16219b9877eeSWenchao Xia 
16229b9877eeSWenchao Xia         /* create new image w/backing file */
162343de7e2dSAlberto Garcia         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
16249b9877eeSWenchao Xia         if (mode != NEW_IMAGE_MODE_EXISTING) {
1625f86b8b58SKevin Wolf             int64_t size = bdrv_getlength(state->old_bs);
1626f86b8b58SKevin Wolf             if (size < 0) {
1627f86b8b58SKevin Wolf                 error_setg_errno(errp, -size, "bdrv_getlength failed");
16282d24b60bSStefan Hajnoczi                 goto out;
1629f86b8b58SKevin Wolf             }
16309b9877eeSWenchao Xia             bdrv_img_create(new_image_file, format,
1631ba5d6ab6SStefan Hajnoczi                             state->old_bs->filename,
1632ba5d6ab6SStefan Hajnoczi                             state->old_bs->drv->format_name,
16339217283dSFam Zheng                             NULL, size, flags, false, &local_err);
163484d18f06SMarkus Armbruster             if (local_err) {
16359b9877eeSWenchao Xia                 error_propagate(errp, local_err);
16362d24b60bSStefan Hajnoczi                 goto out;
16379b9877eeSWenchao Xia             }
16389b9877eeSWenchao Xia         }
16399b9877eeSWenchao Xia 
16400901f67eSBenoît Canet         options = qdict_new();
1641d52e1a0eSPeter Maydell         if (snapshot_node_name) {
164246f5ac20SEric Blake             qdict_put_str(options, "node-name", snapshot_node_name);
16430901f67eSBenoît Canet         }
164446f5ac20SEric Blake         qdict_put_str(options, "driver", format);
164543de7e2dSAlberto Garcia     }
164643de7e2dSAlberto Garcia 
16475b363937SMax Reitz     state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
16485b363937SMax Reitz                               errp);
1649f67503e5SMax Reitz     /* We will manually add the backing_hd field to the bs later */
16505b363937SMax Reitz     if (!state->new_bs) {
16512d24b60bSStefan Hajnoczi         goto out;
165243de7e2dSAlberto Garcia     }
165343de7e2dSAlberto Garcia 
16541f0c461bSKevin Wolf     if (bdrv_has_blk(state->new_bs)) {
1655e467da7bSKevin Wolf         error_setg(errp, "The snapshot is already in use");
16562d24b60bSStefan Hajnoczi         goto out;
165743de7e2dSAlberto Garcia     }
165843de7e2dSAlberto Garcia 
165943de7e2dSAlberto Garcia     if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
166043de7e2dSAlberto Garcia                            errp)) {
16612d24b60bSStefan Hajnoczi         goto out;
166243de7e2dSAlberto Garcia     }
166343de7e2dSAlberto Garcia 
166443de7e2dSAlberto Garcia     if (state->new_bs->backing != NULL) {
166543de7e2dSAlberto Garcia         error_setg(errp, "The snapshot already has a backing image");
16662d24b60bSStefan Hajnoczi         goto out;
166708b24cfeSAlberto Garcia     }
166808b24cfeSAlberto Garcia 
166908b24cfeSAlberto Garcia     if (!state->new_bs->drv->supports_backing) {
167008b24cfeSAlberto Garcia         error_setg(errp, "The snapshot does not support backing images");
16712d24b60bSStefan Hajnoczi         goto out;
1672b2c2832cSKevin Wolf     }
1673b2c2832cSKevin Wolf 
16742d24b60bSStefan Hajnoczi     bdrv_set_aio_context(state->new_bs, aio_context);
1675c26a5ab7SFam Zheng 
1676b2c2832cSKevin Wolf     /* This removes our old bs and adds the new bs. This is an operation that
1677b2c2832cSKevin Wolf      * can fail, so we need to do it in .prepare; undoing it for abort is
1678b2c2832cSKevin Wolf      * always possible. */
1679b2c2832cSKevin Wolf     bdrv_ref(state->new_bs);
1680b2c2832cSKevin Wolf     bdrv_append(state->new_bs, state->old_bs, &local_err);
1681b2c2832cSKevin Wolf     if (local_err) {
1682b2c2832cSKevin Wolf         error_propagate(errp, local_err);
16832d24b60bSStefan Hajnoczi         goto out;
16849b9877eeSWenchao Xia     }
1685067acf28SKevin Wolf     state->overlay_appended = true;
16862d24b60bSStefan Hajnoczi 
16872d24b60bSStefan Hajnoczi out:
16882d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
16899b9877eeSWenchao Xia }
16909b9877eeSWenchao Xia 
169150f43f0fSJohn Snow static void external_snapshot_commit(BlkActionState *common)
16923b0047e8SWenchao Xia {
1693ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1694ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
16952d24b60bSStefan Hajnoczi     AioContext *aio_context;
16962d24b60bSStefan Hajnoczi 
16972d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
16982d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
1699ba0c86a3SWenchao Xia 
17003b0047e8SWenchao Xia     /* We don't need (or want) to use the transactional
17013b0047e8SWenchao Xia      * bdrv_reopen_multiple() across all the entries at once, because we
17023b0047e8SWenchao Xia      * don't want to abort all of them if one of them fails the reopen */
1703d3faa13eSPaolo Bonzini     if (!atomic_read(&state->old_bs->copy_on_read)) {
17041b57774fSAlberto Garcia         bdrv_reopen_set_read_only(state->old_bs, true, NULL);
17053b0047e8SWenchao Xia     }
17062d24b60bSStefan Hajnoczi 
17072d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
17084c844983SKevin Wolf }
17093b0047e8SWenchao Xia 
171050f43f0fSJohn Snow static void external_snapshot_abort(BlkActionState *common)
171196b86bf7SWenchao Xia {
1712ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1713ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1714ba5d6ab6SStefan Hajnoczi     if (state->new_bs) {
1715067acf28SKevin Wolf         if (state->overlay_appended) {
17162d24b60bSStefan Hajnoczi             AioContext *aio_context;
17172d24b60bSStefan Hajnoczi 
17182d24b60bSStefan Hajnoczi             aio_context = bdrv_get_aio_context(state->old_bs);
17192d24b60bSStefan Hajnoczi             aio_context_acquire(aio_context);
17202d24b60bSStefan Hajnoczi 
1721719fc28cSJeff Cody             bdrv_ref(state->old_bs);   /* we can't let bdrv_set_backind_hd()
1722719fc28cSJeff Cody                                           close state->old_bs; we need it */
1723719fc28cSJeff Cody             bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
17245fe31c25SKevin Wolf             bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1725719fc28cSJeff Cody             bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
17262d24b60bSStefan Hajnoczi 
17272d24b60bSStefan Hajnoczi             aio_context_release(aio_context);
1728b2c2832cSKevin Wolf         }
172996b86bf7SWenchao Xia     }
1730da763e83SFam Zheng }
1731da763e83SFam Zheng 
173250f43f0fSJohn Snow static void external_snapshot_clean(BlkActionState *common)
1733da763e83SFam Zheng {
1734da763e83SFam Zheng     ExternalSnapshotState *state =
1735da763e83SFam Zheng                              DO_UPCAST(ExternalSnapshotState, common, common);
17362d24b60bSStefan Hajnoczi     AioContext *aio_context;
17372d24b60bSStefan Hajnoczi 
17382d24b60bSStefan Hajnoczi     if (!state->old_bs) {
17392d24b60bSStefan Hajnoczi         return;
17402d24b60bSStefan Hajnoczi     }
17412d24b60bSStefan Hajnoczi 
17422d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
17432d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
17442d24b60bSStefan Hajnoczi 
1745da763e83SFam Zheng     bdrv_drained_end(state->old_bs);
1746b2c2832cSKevin Wolf     bdrv_unref(state->new_bs);
17472d24b60bSStefan Hajnoczi 
17482d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
174996b86bf7SWenchao Xia }
175096b86bf7SWenchao Xia 
17513037f364SStefan Hajnoczi typedef struct DriveBackupState {
175250f43f0fSJohn Snow     BlkActionState common;
17533037f364SStefan Hajnoczi     BlockDriverState *bs;
17543037f364SStefan Hajnoczi     BlockJob *job;
17553037f364SStefan Hajnoczi } DriveBackupState;
17563037f364SStefan Hajnoczi 
175762c9e416SKevin Wolf static BlockJob *do_drive_backup(DriveBackup *backup, JobTxn *txn,
175881206a89SPavel Butsykin                             Error **errp);
175978f51fdeSJohn Snow 
176050f43f0fSJohn Snow static void drive_backup_prepare(BlkActionState *common, Error **errp)
17613037f364SStefan Hajnoczi {
17623037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1763b7e4fa22SKevin Wolf     BlockDriverState *bs;
17643037f364SStefan Hajnoczi     DriveBackup *backup;
176566d56054SStefan Hajnoczi     AioContext *aio_context;
17663037f364SStefan Hajnoczi     Error *local_err = NULL;
17673037f364SStefan Hajnoczi 
17686a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
176932bafa8fSEric Blake     backup = common->action->u.drive_backup.data;
17703037f364SStefan Hajnoczi 
1771b7e4fa22SKevin Wolf     bs = qmp_get_root_bs(backup->device, errp);
1772b7e4fa22SKevin Wolf     if (!bs) {
17731fdd4b7bSFam Zheng         return;
17741fdd4b7bSFam Zheng     }
17751fdd4b7bSFam Zheng 
177666d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
177766d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
177866d56054SStefan Hajnoczi 
177966d56054SStefan Hajnoczi     /* Paired with .clean() */
1780b7e4fa22SKevin Wolf     bdrv_drained_begin(bs);
178166d56054SStefan Hajnoczi 
1782b7e4fa22SKevin Wolf     state->bs = bs;
17835d6e96efSStefan Hajnoczi 
1784111049a4SJohn Snow     state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
178584d18f06SMarkus Armbruster     if (local_err) {
17863037f364SStefan Hajnoczi         error_propagate(errp, local_err);
178766d56054SStefan Hajnoczi         goto out;
17883037f364SStefan Hajnoczi     }
178966d56054SStefan Hajnoczi 
179066d56054SStefan Hajnoczi out:
179166d56054SStefan Hajnoczi     aio_context_release(aio_context);
1792111049a4SJohn Snow }
17933037f364SStefan Hajnoczi 
1794111049a4SJohn Snow static void drive_backup_commit(BlkActionState *common)
1795111049a4SJohn Snow {
1796111049a4SJohn Snow     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
179766d56054SStefan Hajnoczi     AioContext *aio_context;
179866d56054SStefan Hajnoczi 
179966d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
180066d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
180166d56054SStefan Hajnoczi 
1802111049a4SJohn Snow     assert(state->job);
1803da01ff7fSKevin Wolf     job_start(&state->job->job);
180466d56054SStefan Hajnoczi 
180566d56054SStefan Hajnoczi     aio_context_release(aio_context);
18063037f364SStefan Hajnoczi }
18073037f364SStefan Hajnoczi 
180850f43f0fSJohn Snow static void drive_backup_abort(BlkActionState *common)
18093037f364SStefan Hajnoczi {
18103037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
18113037f364SStefan Hajnoczi 
1812111049a4SJohn Snow     if (state->job) {
181366d56054SStefan Hajnoczi         AioContext *aio_context;
181466d56054SStefan Hajnoczi 
181566d56054SStefan Hajnoczi         aio_context = bdrv_get_aio_context(state->bs);
181666d56054SStefan Hajnoczi         aio_context_acquire(aio_context);
181766d56054SStefan Hajnoczi 
18183d70ff53SKevin Wolf         job_cancel_sync(&state->job->job);
181966d56054SStefan Hajnoczi 
182066d56054SStefan Hajnoczi         aio_context_release(aio_context);
18213037f364SStefan Hajnoczi     }
18223037f364SStefan Hajnoczi }
18233037f364SStefan Hajnoczi 
182450f43f0fSJohn Snow static void drive_backup_clean(BlkActionState *common)
18255d6e96efSStefan Hajnoczi {
18265d6e96efSStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
182766d56054SStefan Hajnoczi     AioContext *aio_context;
18285d6e96efSStefan Hajnoczi 
182966d56054SStefan Hajnoczi     if (!state->bs) {
183066d56054SStefan Hajnoczi         return;
18315d6e96efSStefan Hajnoczi     }
183266d56054SStefan Hajnoczi 
183366d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
183466d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
183566d56054SStefan Hajnoczi 
183666d56054SStefan Hajnoczi     bdrv_drained_end(state->bs);
183766d56054SStefan Hajnoczi 
183866d56054SStefan Hajnoczi     aio_context_release(aio_context);
18395d6e96efSStefan Hajnoczi }
18405d6e96efSStefan Hajnoczi 
1841bd8baecdSFam Zheng typedef struct BlockdevBackupState {
184250f43f0fSJohn Snow     BlkActionState common;
1843bd8baecdSFam Zheng     BlockDriverState *bs;
1844bd8baecdSFam Zheng     BlockJob *job;
1845bd8baecdSFam Zheng } BlockdevBackupState;
1846bd8baecdSFam Zheng 
184762c9e416SKevin Wolf static BlockJob *do_blockdev_backup(BlockdevBackup *backup, JobTxn *txn,
1848dc7a4a9eSPavel Butsykin                                     Error **errp);
184978f51fdeSJohn Snow 
185050f43f0fSJohn Snow static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1851bd8baecdSFam Zheng {
1852bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1853bd8baecdSFam Zheng     BlockdevBackup *backup;
1854cef34eebSKevin Wolf     BlockDriverState *bs, *target;
1855edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1856bd8baecdSFam Zheng     Error *local_err = NULL;
1857bd8baecdSFam Zheng 
18586a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
185932bafa8fSEric Blake     backup = common->action->u.blockdev_backup.data;
1860bd8baecdSFam Zheng 
1861930fe17fSVladimir Sementsov-Ogievskiy     bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1862cef34eebSKevin Wolf     if (!bs) {
1863ff52bf36SFam Zheng         return;
1864ff52bf36SFam Zheng     }
1865ff52bf36SFam Zheng 
186639d990acSKevin Wolf     target = bdrv_lookup_bs(backup->target, backup->target, errp);
18675433c24fSMax Reitz     if (!target) {
1868bd8baecdSFam Zheng         return;
1869bd8baecdSFam Zheng     }
1870bd8baecdSFam Zheng 
1871edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
1872edd5adeeSStefan Hajnoczi     if (aio_context != bdrv_get_aio_context(target)) {
1873bd8baecdSFam Zheng         error_setg(errp, "Backup between two IO threads is not implemented");
1874bd8baecdSFam Zheng         return;
1875bd8baecdSFam Zheng     }
1876edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1877cef34eebSKevin Wolf     state->bs = bs;
1878edd5adeeSStefan Hajnoczi 
1879edd5adeeSStefan Hajnoczi     /* Paired with .clean() */
1880ff52bf36SFam Zheng     bdrv_drained_begin(state->bs);
1881bd8baecdSFam Zheng 
1882111049a4SJohn Snow     state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
1883bd8baecdSFam Zheng     if (local_err) {
1884bd8baecdSFam Zheng         error_propagate(errp, local_err);
1885edd5adeeSStefan Hajnoczi         goto out;
1886bd8baecdSFam Zheng     }
1887edd5adeeSStefan Hajnoczi 
1888edd5adeeSStefan Hajnoczi out:
1889edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1890111049a4SJohn Snow }
1891bd8baecdSFam Zheng 
1892111049a4SJohn Snow static void blockdev_backup_commit(BlkActionState *common)
1893111049a4SJohn Snow {
1894111049a4SJohn Snow     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1895edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1896edd5adeeSStefan Hajnoczi 
1897edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1898edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1899edd5adeeSStefan Hajnoczi 
1900111049a4SJohn Snow     assert(state->job);
1901da01ff7fSKevin Wolf     job_start(&state->job->job);
1902edd5adeeSStefan Hajnoczi 
1903edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1904bd8baecdSFam Zheng }
1905bd8baecdSFam Zheng 
190650f43f0fSJohn Snow static void blockdev_backup_abort(BlkActionState *common)
1907bd8baecdSFam Zheng {
1908bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1909bd8baecdSFam Zheng 
1910111049a4SJohn Snow     if (state->job) {
1911edd5adeeSStefan Hajnoczi         AioContext *aio_context;
1912edd5adeeSStefan Hajnoczi 
1913edd5adeeSStefan Hajnoczi         aio_context = bdrv_get_aio_context(state->bs);
1914edd5adeeSStefan Hajnoczi         aio_context_acquire(aio_context);
1915edd5adeeSStefan Hajnoczi 
19163d70ff53SKevin Wolf         job_cancel_sync(&state->job->job);
1917edd5adeeSStefan Hajnoczi 
1918edd5adeeSStefan Hajnoczi         aio_context_release(aio_context);
1919bd8baecdSFam Zheng     }
1920bd8baecdSFam Zheng }
1921bd8baecdSFam Zheng 
192250f43f0fSJohn Snow static void blockdev_backup_clean(BlkActionState *common)
1923bd8baecdSFam Zheng {
1924bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1925edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1926bd8baecdSFam Zheng 
1927edd5adeeSStefan Hajnoczi     if (!state->bs) {
1928edd5adeeSStefan Hajnoczi         return;
1929bd8baecdSFam Zheng     }
1930edd5adeeSStefan Hajnoczi 
1931edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1932edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1933edd5adeeSStefan Hajnoczi 
1934edd5adeeSStefan Hajnoczi     bdrv_drained_end(state->bs);
1935edd5adeeSStefan Hajnoczi 
1936edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1937bd8baecdSFam Zheng }
1938bd8baecdSFam Zheng 
1939df9a681dSFam Zheng typedef struct BlockDirtyBitmapState {
194050f43f0fSJohn Snow     BlkActionState common;
1941df9a681dSFam Zheng     BdrvDirtyBitmap *bitmap;
1942df9a681dSFam Zheng     BlockDriverState *bs;
1943df9a681dSFam Zheng     HBitmap *backup;
1944df9a681dSFam Zheng     bool prepared;
1945c6490447SVladimir Sementsov-Ogievskiy     bool was_enabled;
1946df9a681dSFam Zheng } BlockDirtyBitmapState;
1947df9a681dSFam Zheng 
194850f43f0fSJohn Snow static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1949df9a681dSFam Zheng                                            Error **errp)
1950df9a681dSFam Zheng {
1951df9a681dSFam Zheng     Error *local_err = NULL;
1952df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
1953df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1954df9a681dSFam Zheng                                              common, common);
1955df9a681dSFam Zheng 
195694d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
195794d16a64SJohn Snow         return;
195894d16a64SJohn Snow     }
195994d16a64SJohn Snow 
196032bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
1961df9a681dSFam Zheng     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1962df9a681dSFam Zheng     qmp_block_dirty_bitmap_add(action->node, action->name,
1963df9a681dSFam Zheng                                action->has_granularity, action->granularity,
1964fd5ae4ccSVladimir Sementsov-Ogievskiy                                action->has_persistent, action->persistent,
1965eb738bb5SVladimir Sementsov-Ogievskiy                                action->has_autoload, action->autoload,
19660e2b7f09SJohn Snow                                action->has_disabled, action->disabled,
1967df9a681dSFam Zheng                                &local_err);
1968df9a681dSFam Zheng 
1969df9a681dSFam Zheng     if (!local_err) {
1970df9a681dSFam Zheng         state->prepared = true;
1971df9a681dSFam Zheng     } else {
1972df9a681dSFam Zheng         error_propagate(errp, local_err);
1973df9a681dSFam Zheng     }
1974df9a681dSFam Zheng }
1975df9a681dSFam Zheng 
197650f43f0fSJohn Snow static void block_dirty_bitmap_add_abort(BlkActionState *common)
1977df9a681dSFam Zheng {
1978df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
1979df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1980df9a681dSFam Zheng                                              common, common);
1981df9a681dSFam Zheng 
198232bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
1983df9a681dSFam Zheng     /* Should not be able to fail: IF the bitmap was added via .prepare(),
1984df9a681dSFam Zheng      * then the node reference and bitmap name must have been valid.
1985df9a681dSFam Zheng      */
1986df9a681dSFam Zheng     if (state->prepared) {
1987df9a681dSFam Zheng         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
1988df9a681dSFam Zheng     }
1989df9a681dSFam Zheng }
1990df9a681dSFam Zheng 
199150f43f0fSJohn Snow static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
1992df9a681dSFam Zheng                                              Error **errp)
1993df9a681dSFam Zheng {
1994df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1995df9a681dSFam Zheng                                              common, common);
1996df9a681dSFam Zheng     BlockDirtyBitmap *action;
1997df9a681dSFam Zheng 
199894d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
199994d16a64SJohn Snow         return;
200094d16a64SJohn Snow     }
200194d16a64SJohn Snow 
200232bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_clear.data;
2003df9a681dSFam Zheng     state->bitmap = block_dirty_bitmap_lookup(action->node,
2004df9a681dSFam Zheng                                               action->name,
2005df9a681dSFam Zheng                                               &state->bs,
2006df9a681dSFam Zheng                                               errp);
2007df9a681dSFam Zheng     if (!state->bitmap) {
2008df9a681dSFam Zheng         return;
2009df9a681dSFam Zheng     }
2010df9a681dSFam Zheng 
2011993edc0cSJohn Snow     if (bdrv_dirty_bitmap_user_locked(state->bitmap)) {
2012993edc0cSJohn Snow         error_setg(errp, "Cannot modify a bitmap in use by another operation");
20134f43e953SVladimir Sementsov-Ogievskiy         return;
2014d6883bc9SVladimir Sementsov-Ogievskiy     } else if (bdrv_dirty_bitmap_readonly(state->bitmap)) {
2015d6883bc9SVladimir Sementsov-Ogievskiy         error_setg(errp, "Cannot clear a readonly bitmap");
2016d6883bc9SVladimir Sementsov-Ogievskiy         return;
2017df9a681dSFam Zheng     }
2018df9a681dSFam Zheng 
2019df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2020df9a681dSFam Zheng }
2021df9a681dSFam Zheng 
20225c4cf8b2SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_restore(BlkActionState *common)
2023df9a681dSFam Zheng {
2024df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2025df9a681dSFam Zheng                                              common, common);
2026df9a681dSFam Zheng 
2027184dd9c4SJohn Snow     if (state->backup) {
202856bd6624SVladimir Sementsov-Ogievskiy         bdrv_restore_dirty_bitmap(state->bitmap, state->backup);
2029df9a681dSFam Zheng     }
2030184dd9c4SJohn Snow }
2031df9a681dSFam Zheng 
20325c4cf8b2SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_free_backup(BlkActionState *common)
2033df9a681dSFam Zheng {
2034df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2035df9a681dSFam Zheng                                              common, common);
2036df9a681dSFam Zheng 
2037df9a681dSFam Zheng     hbitmap_free(state->backup);
2038df9a681dSFam Zheng }
2039df9a681dSFam Zheng 
2040c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_enable_prepare(BlkActionState *common,
2041c6490447SVladimir Sementsov-Ogievskiy                                               Error **errp)
2042c6490447SVladimir Sementsov-Ogievskiy {
2043c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmap *action;
2044c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2045c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2046c6490447SVladimir Sementsov-Ogievskiy 
2047c6490447SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
2048c6490447SVladimir Sementsov-Ogievskiy         return;
2049c6490447SVladimir Sementsov-Ogievskiy     }
2050c6490447SVladimir Sementsov-Ogievskiy 
20510e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_enable.data;
2052c6490447SVladimir Sementsov-Ogievskiy     state->bitmap = block_dirty_bitmap_lookup(action->node,
2053c6490447SVladimir Sementsov-Ogievskiy                                               action->name,
2054c6490447SVladimir Sementsov-Ogievskiy                                               NULL,
2055c6490447SVladimir Sementsov-Ogievskiy                                               errp);
2056c6490447SVladimir Sementsov-Ogievskiy     if (!state->bitmap) {
2057c6490447SVladimir Sementsov-Ogievskiy         return;
2058c6490447SVladimir Sementsov-Ogievskiy     }
2059c6490447SVladimir Sementsov-Ogievskiy 
2060b053bb55SJohn Snow     if (bdrv_dirty_bitmap_user_locked(state->bitmap)) {
2061b053bb55SJohn Snow         error_setg(errp,
2062b053bb55SJohn Snow                    "Bitmap '%s' is currently in use by another operation"
2063b053bb55SJohn Snow                    " and cannot be enabled", action->name);
2064b053bb55SJohn Snow         return;
2065b053bb55SJohn Snow     }
2066b053bb55SJohn Snow 
2067c6490447SVladimir Sementsov-Ogievskiy     state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2068c6490447SVladimir Sementsov-Ogievskiy     bdrv_enable_dirty_bitmap(state->bitmap);
2069c6490447SVladimir Sementsov-Ogievskiy }
2070c6490447SVladimir Sementsov-Ogievskiy 
2071c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_enable_abort(BlkActionState *common)
2072c6490447SVladimir Sementsov-Ogievskiy {
2073c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2074c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2075c6490447SVladimir Sementsov-Ogievskiy 
2076c6490447SVladimir Sementsov-Ogievskiy     if (!state->was_enabled) {
2077c6490447SVladimir Sementsov-Ogievskiy         bdrv_disable_dirty_bitmap(state->bitmap);
2078c6490447SVladimir Sementsov-Ogievskiy     }
2079c6490447SVladimir Sementsov-Ogievskiy }
2080c6490447SVladimir Sementsov-Ogievskiy 
2081c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_disable_prepare(BlkActionState *common,
2082c6490447SVladimir Sementsov-Ogievskiy                                                Error **errp)
2083c6490447SVladimir Sementsov-Ogievskiy {
2084c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmap *action;
2085c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2086c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2087c6490447SVladimir Sementsov-Ogievskiy 
2088c6490447SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
2089c6490447SVladimir Sementsov-Ogievskiy         return;
2090c6490447SVladimir Sementsov-Ogievskiy     }
2091c6490447SVladimir Sementsov-Ogievskiy 
20920e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_disable.data;
2093c6490447SVladimir Sementsov-Ogievskiy     state->bitmap = block_dirty_bitmap_lookup(action->node,
2094c6490447SVladimir Sementsov-Ogievskiy                                               action->name,
2095c6490447SVladimir Sementsov-Ogievskiy                                               NULL,
2096c6490447SVladimir Sementsov-Ogievskiy                                               errp);
2097c6490447SVladimir Sementsov-Ogievskiy     if (!state->bitmap) {
2098c6490447SVladimir Sementsov-Ogievskiy         return;
2099c6490447SVladimir Sementsov-Ogievskiy     }
2100c6490447SVladimir Sementsov-Ogievskiy 
2101b053bb55SJohn Snow     if (bdrv_dirty_bitmap_user_locked(state->bitmap)) {
2102b053bb55SJohn Snow         error_setg(errp,
2103b053bb55SJohn Snow                    "Bitmap '%s' is currently in use by another operation"
2104b053bb55SJohn Snow                    " and cannot be disabled", action->name);
2105b053bb55SJohn Snow         return;
2106b053bb55SJohn Snow     }
2107b053bb55SJohn Snow 
2108c6490447SVladimir Sementsov-Ogievskiy     state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2109c6490447SVladimir Sementsov-Ogievskiy     bdrv_disable_dirty_bitmap(state->bitmap);
2110c6490447SVladimir Sementsov-Ogievskiy }
2111c6490447SVladimir Sementsov-Ogievskiy 
2112c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_disable_abort(BlkActionState *common)
2113c6490447SVladimir Sementsov-Ogievskiy {
2114c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2115c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2116c6490447SVladimir Sementsov-Ogievskiy 
2117c6490447SVladimir Sementsov-Ogievskiy     if (state->was_enabled) {
2118c6490447SVladimir Sementsov-Ogievskiy         bdrv_enable_dirty_bitmap(state->bitmap);
2119c6490447SVladimir Sementsov-Ogievskiy     }
2120c6490447SVladimir Sementsov-Ogievskiy }
2121c6490447SVladimir Sementsov-Ogievskiy 
2122360d4e4eSJohn Snow static BdrvDirtyBitmap *do_block_dirty_bitmap_merge(const char *node,
2123360d4e4eSJohn Snow                                                     const char *target,
2124360d4e4eSJohn Snow                                                     strList *bitmaps,
2125360d4e4eSJohn Snow                                                     HBitmap **backup,
2126360d4e4eSJohn Snow                                                     Error **errp);
2127360d4e4eSJohn Snow 
21286fd2e407SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_merge_prepare(BlkActionState *common,
21296fd2e407SVladimir Sementsov-Ogievskiy                                              Error **errp)
21306fd2e407SVladimir Sementsov-Ogievskiy {
21316fd2e407SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapMerge *action;
21326fd2e407SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
21336fd2e407SVladimir Sementsov-Ogievskiy                                              common, common);
21346fd2e407SVladimir Sementsov-Ogievskiy 
21356fd2e407SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
21366fd2e407SVladimir Sementsov-Ogievskiy         return;
21376fd2e407SVladimir Sementsov-Ogievskiy     }
21386fd2e407SVladimir Sementsov-Ogievskiy 
21390e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_merge.data;
2140360d4e4eSJohn Snow 
2141360d4e4eSJohn Snow     state->bitmap = do_block_dirty_bitmap_merge(action->node, action->target,
2142360d4e4eSJohn Snow                                                 action->bitmaps, &state->backup,
21436fd2e407SVladimir Sementsov-Ogievskiy                                                 errp);
21446fd2e407SVladimir Sementsov-Ogievskiy }
21456fd2e407SVladimir Sementsov-Ogievskiy 
214650f43f0fSJohn Snow static void abort_prepare(BlkActionState *common, Error **errp)
214778b18b78SStefan Hajnoczi {
214878b18b78SStefan Hajnoczi     error_setg(errp, "Transaction aborted using Abort action");
214978b18b78SStefan Hajnoczi }
215078b18b78SStefan Hajnoczi 
215150f43f0fSJohn Snow static void abort_commit(BlkActionState *common)
215278b18b78SStefan Hajnoczi {
2153dfc6f865SStefan Weil     g_assert_not_reached(); /* this action never succeeds */
215478b18b78SStefan Hajnoczi }
215578b18b78SStefan Hajnoczi 
215650f43f0fSJohn Snow static const BlkActionOps actions[] = {
215743de7e2dSAlberto Garcia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
215843de7e2dSAlberto Garcia         .instance_size = sizeof(ExternalSnapshotState),
215943de7e2dSAlberto Garcia         .prepare  = external_snapshot_prepare,
216043de7e2dSAlberto Garcia         .commit   = external_snapshot_commit,
216143de7e2dSAlberto Garcia         .abort = external_snapshot_abort,
21624ad6f3dbSAlberto Garcia         .clean = external_snapshot_clean,
216343de7e2dSAlberto Garcia     },
2164c8a83e85SKevin Wolf     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2165ba5d6ab6SStefan Hajnoczi         .instance_size = sizeof(ExternalSnapshotState),
2166ba0c86a3SWenchao Xia         .prepare  = external_snapshot_prepare,
2167ba0c86a3SWenchao Xia         .commit   = external_snapshot_commit,
2168ba0c86a3SWenchao Xia         .abort = external_snapshot_abort,
2169da763e83SFam Zheng         .clean = external_snapshot_clean,
2170ba0c86a3SWenchao Xia     },
21713037f364SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
21723037f364SStefan Hajnoczi         .instance_size = sizeof(DriveBackupState),
21733037f364SStefan Hajnoczi         .prepare = drive_backup_prepare,
2174111049a4SJohn Snow         .commit = drive_backup_commit,
21753037f364SStefan Hajnoczi         .abort = drive_backup_abort,
21765d6e96efSStefan Hajnoczi         .clean = drive_backup_clean,
21773037f364SStefan Hajnoczi     },
2178bd8baecdSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2179bd8baecdSFam Zheng         .instance_size = sizeof(BlockdevBackupState),
2180bd8baecdSFam Zheng         .prepare = blockdev_backup_prepare,
2181111049a4SJohn Snow         .commit = blockdev_backup_commit,
2182bd8baecdSFam Zheng         .abort = blockdev_backup_abort,
2183bd8baecdSFam Zheng         .clean = blockdev_backup_clean,
2184bd8baecdSFam Zheng     },
218578b18b78SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_ABORT] = {
218650f43f0fSJohn Snow         .instance_size = sizeof(BlkActionState),
218778b18b78SStefan Hajnoczi         .prepare = abort_prepare,
218878b18b78SStefan Hajnoczi         .commit = abort_commit,
218978b18b78SStefan Hajnoczi     },
2190bbe86010SWenchao Xia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2191bbe86010SWenchao Xia         .instance_size = sizeof(InternalSnapshotState),
2192bbe86010SWenchao Xia         .prepare  = internal_snapshot_prepare,
2193bbe86010SWenchao Xia         .abort = internal_snapshot_abort,
21945d6e96efSStefan Hajnoczi         .clean = internal_snapshot_clean,
2195bbe86010SWenchao Xia     },
2196df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2197df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2198df9a681dSFam Zheng         .prepare = block_dirty_bitmap_add_prepare,
2199df9a681dSFam Zheng         .abort = block_dirty_bitmap_add_abort,
2200df9a681dSFam Zheng     },
2201df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2202df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2203df9a681dSFam Zheng         .prepare = block_dirty_bitmap_clear_prepare,
22045c4cf8b2SVladimir Sementsov-Ogievskiy         .commit = block_dirty_bitmap_free_backup,
22055c4cf8b2SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_restore,
2206c6490447SVladimir Sementsov-Ogievskiy     },
22070e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ENABLE] = {
2208c6490447SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
2209c6490447SVladimir Sementsov-Ogievskiy         .prepare = block_dirty_bitmap_enable_prepare,
2210c6490447SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_enable_abort,
2211c6490447SVladimir Sementsov-Ogievskiy     },
22120e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_DISABLE] = {
2213c6490447SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
2214c6490447SVladimir Sementsov-Ogievskiy         .prepare = block_dirty_bitmap_disable_prepare,
2215c6490447SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_disable_abort,
221666da04ddSJohn Snow     },
22170e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_MERGE] = {
22186fd2e407SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
22196fd2e407SVladimir Sementsov-Ogievskiy         .prepare = block_dirty_bitmap_merge_prepare,
22206fd2e407SVladimir Sementsov-Ogievskiy         .commit = block_dirty_bitmap_free_backup,
22216fd2e407SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_restore,
22226fd2e407SVladimir Sementsov-Ogievskiy     },
222366da04ddSJohn Snow     /* Where are transactions for MIRROR, COMMIT and STREAM?
222466da04ddSJohn Snow      * Although these blockjobs use transaction callbacks like the backup job,
222566da04ddSJohn Snow      * these jobs do not necessarily adhere to transaction semantics.
222666da04ddSJohn Snow      * These jobs may not fully undo all of their actions on abort, nor do they
222766da04ddSJohn Snow      * necessarily work in transactions with more than one job in them.
222866da04ddSJohn Snow      */
2229ba0c86a3SWenchao Xia };
2230ba0c86a3SWenchao Xia 
223194d16a64SJohn Snow /**
223294d16a64SJohn Snow  * Allocate a TransactionProperties structure if necessary, and fill
223394d16a64SJohn Snow  * that structure with desired defaults if they are unset.
223494d16a64SJohn Snow  */
223594d16a64SJohn Snow static TransactionProperties *get_transaction_properties(
223694d16a64SJohn Snow     TransactionProperties *props)
223794d16a64SJohn Snow {
223894d16a64SJohn Snow     if (!props) {
223994d16a64SJohn Snow         props = g_new0(TransactionProperties, 1);
224094d16a64SJohn Snow     }
224194d16a64SJohn Snow 
224294d16a64SJohn Snow     if (!props->has_completion_mode) {
224394d16a64SJohn Snow         props->has_completion_mode = true;
224494d16a64SJohn Snow         props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
224594d16a64SJohn Snow     }
224694d16a64SJohn Snow 
224794d16a64SJohn Snow     return props;
224894d16a64SJohn Snow }
224994d16a64SJohn Snow 
22508802d1fdSJeff Cody /*
2251b756b9ceSStefan Hajnoczi  * 'Atomic' group operations.  The operations are performed as a set, and if
2252b756b9ceSStefan Hajnoczi  * any fail then we roll back all operations in the group.
22538802d1fdSJeff Cody  */
225494d16a64SJohn Snow void qmp_transaction(TransactionActionList *dev_list,
225594d16a64SJohn Snow                      bool has_props,
225694d16a64SJohn Snow                      struct TransactionProperties *props,
225794d16a64SJohn Snow                      Error **errp)
22588802d1fdSJeff Cody {
2259c8a83e85SKevin Wolf     TransactionActionList *dev_entry = dev_list;
226062c9e416SKevin Wolf     JobTxn *block_job_txn = NULL;
226150f43f0fSJohn Snow     BlkActionState *state, *next;
226243e17041SLuiz Capitulino     Error *local_err = NULL;
22638802d1fdSJeff Cody 
2264f4de0f8cSJohn Snow     QTAILQ_HEAD(, BlkActionState) snap_bdrv_states;
2265f4de0f8cSJohn Snow     QTAILQ_INIT(&snap_bdrv_states);
22668802d1fdSJeff Cody 
226794d16a64SJohn Snow     /* Does this transaction get canceled as a group on failure?
226862c9e416SKevin Wolf      * If not, we don't really need to make a JobTxn.
226994d16a64SJohn Snow      */
227094d16a64SJohn Snow     props = get_transaction_properties(props);
227194d16a64SJohn Snow     if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
22727eaa8fb5SKevin Wolf         block_job_txn = job_txn_new();
227394d16a64SJohn Snow     }
227494d16a64SJohn Snow 
2275b756b9ceSStefan Hajnoczi     /* drain all i/o before any operations */
22768802d1fdSJeff Cody     bdrv_drain_all();
22778802d1fdSJeff Cody 
2278b756b9ceSStefan Hajnoczi     /* We don't do anything in this loop that commits us to the operations */
22798802d1fdSJeff Cody     while (NULL != dev_entry) {
2280c8a83e85SKevin Wolf         TransactionAction *dev_info = NULL;
228150f43f0fSJohn Snow         const BlkActionOps *ops;
228252e7c241SPaolo Bonzini 
22838802d1fdSJeff Cody         dev_info = dev_entry->value;
22848802d1fdSJeff Cody         dev_entry = dev_entry->next;
22858802d1fdSJeff Cody 
22866a8f9661SEric Blake         assert(dev_info->type < ARRAY_SIZE(actions));
2287ba0c86a3SWenchao Xia 
22886a8f9661SEric Blake         ops = &actions[dev_info->type];
2289aa3fe714SMax Reitz         assert(ops->instance_size > 0);
2290aa3fe714SMax Reitz 
2291ba5d6ab6SStefan Hajnoczi         state = g_malloc0(ops->instance_size);
2292ba5d6ab6SStefan Hajnoczi         state->ops = ops;
2293ba5d6ab6SStefan Hajnoczi         state->action = dev_info;
229494d16a64SJohn Snow         state->block_job_txn = block_job_txn;
229594d16a64SJohn Snow         state->txn_props = props;
2296f4de0f8cSJohn Snow         QTAILQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
22978802d1fdSJeff Cody 
2298ba5d6ab6SStefan Hajnoczi         state->ops->prepare(state, &local_err);
229984d18f06SMarkus Armbruster         if (local_err) {
23009b9877eeSWenchao Xia             error_propagate(errp, local_err);
23019b9877eeSWenchao Xia             goto delete_and_fail;
23029b9877eeSWenchao Xia         }
230352e7c241SPaolo Bonzini     }
23048802d1fdSJeff Cody 
2305f4de0f8cSJohn Snow     QTAILQ_FOREACH(state, &snap_bdrv_states, entry) {
2306f9ea81e8SStefan Hajnoczi         if (state->ops->commit) {
2307ba5d6ab6SStefan Hajnoczi             state->ops->commit(state);
23088802d1fdSJeff Cody         }
2309f9ea81e8SStefan Hajnoczi     }
23108802d1fdSJeff Cody 
23118802d1fdSJeff Cody     /* success */
23128802d1fdSJeff Cody     goto exit;
23138802d1fdSJeff Cody 
23148802d1fdSJeff Cody delete_and_fail:
2315b756b9ceSStefan Hajnoczi     /* failure, and it is all-or-none; roll back all operations */
2316f4de0f8cSJohn Snow     QTAILQ_FOREACH_REVERSE(state, &snap_bdrv_states, entry) {
2317ba5d6ab6SStefan Hajnoczi         if (state->ops->abort) {
2318ba5d6ab6SStefan Hajnoczi             state->ops->abort(state);
2319ba0c86a3SWenchao Xia         }
23208802d1fdSJeff Cody     }
23218802d1fdSJeff Cody exit:
2322f4de0f8cSJohn Snow     QTAILQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2323ba5d6ab6SStefan Hajnoczi         if (state->ops->clean) {
2324ba5d6ab6SStefan Hajnoczi             state->ops->clean(state);
2325ba0c86a3SWenchao Xia         }
2326ba5d6ab6SStefan Hajnoczi         g_free(state);
23278802d1fdSJeff Cody     }
232894d16a64SJohn Snow     if (!has_props) {
232994d16a64SJohn Snow         qapi_free_TransactionProperties(props);
233094d16a64SJohn Snow     }
23317eaa8fb5SKevin Wolf     job_txn_unref(block_job_txn);
23328802d1fdSJeff Cody }
23338802d1fdSJeff Cody 
2334fbe2d816SKevin Wolf void qmp_eject(bool has_device, const char *device,
2335fbe2d816SKevin Wolf                bool has_id, const char *id,
2336fbe2d816SKevin Wolf                bool has_force, bool force, Error **errp)
2337666daa68SMarkus Armbruster {
233838f54bd1SMax Reitz     Error *local_err = NULL;
23393a3086b7SJohn Snow     int rc;
2340666daa68SMarkus Armbruster 
23413a3086b7SJohn Snow     if (!has_force) {
23423a3086b7SJohn Snow         force = false;
23433a3086b7SJohn Snow     }
23443a3086b7SJohn Snow 
2345fbe2d816SKevin Wolf     rc = do_open_tray(has_device ? device : NULL,
2346fbe2d816SKevin Wolf                       has_id ? id : NULL,
2347fbe2d816SKevin Wolf                       force, &local_err);
2348bf18bee5SColin Lord     if (rc && rc != -ENOSYS) {
234938f54bd1SMax Reitz         error_propagate(errp, local_err);
2350c245b6a3SLuiz Capitulino         return;
2351666daa68SMarkus Armbruster     }
2352bf18bee5SColin Lord     error_free(local_err);
23533a3086b7SJohn Snow 
235482fcf66eSMax Reitz     blockdev_remove_medium(has_device, device, has_id, id, errp);
2355666daa68SMarkus Armbruster }
2356666daa68SMarkus Armbruster 
235712d3ba82SBenoît Canet void qmp_block_passwd(bool has_device, const char *device,
235812d3ba82SBenoît Canet                       bool has_node_name, const char *node_name,
235912d3ba82SBenoît Canet                       const char *password, Error **errp)
2360666daa68SMarkus Armbruster {
2361c01c214bSDaniel P. Berrange     error_setg(errp,
2362c01c214bSDaniel P. Berrange                "Setting block passwords directly is no longer supported");
2363e3442099SStefan Hajnoczi }
2364e3442099SStefan Hajnoczi 
2365bf18bee5SColin Lord /*
2366bf18bee5SColin Lord  * Attempt to open the tray of @device.
2367bf18bee5SColin Lord  * If @force, ignore its tray lock.
2368bf18bee5SColin Lord  * Else, if the tray is locked, don't open it, but ask the guest to open it.
2369bf18bee5SColin Lord  * On error, store an error through @errp and return -errno.
2370bf18bee5SColin Lord  * If @device does not exist, return -ENODEV.
2371bf18bee5SColin Lord  * If it has no removable media, return -ENOTSUP.
2372bf18bee5SColin Lord  * If it has no tray, return -ENOSYS.
2373bf18bee5SColin Lord  * If the guest was asked to open the tray, return -EINPROGRESS.
2374bf18bee5SColin Lord  * Else, return 0.
23753a3086b7SJohn Snow  */
2376b33945cfSKevin Wolf static int do_open_tray(const char *blk_name, const char *qdev_id,
2377b33945cfSKevin Wolf                         bool force, Error **errp)
23787d8a9f71SMax Reitz {
23797d8a9f71SMax Reitz     BlockBackend *blk;
2380b33945cfSKevin Wolf     const char *device = qdev_id ?: blk_name;
23817d8a9f71SMax Reitz     bool locked;
23827d8a9f71SMax Reitz 
2383b33945cfSKevin Wolf     blk = qmp_get_blk(blk_name, qdev_id, errp);
23847d8a9f71SMax Reitz     if (!blk) {
23853a3086b7SJohn Snow         return -ENODEV;
23867d8a9f71SMax Reitz     }
23877d8a9f71SMax Reitz 
23887d8a9f71SMax Reitz     if (!blk_dev_has_removable_media(blk)) {
23897d8a9f71SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
23903a3086b7SJohn Snow         return -ENOTSUP;
23917d8a9f71SMax Reitz     }
23927d8a9f71SMax Reitz 
239312c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
2394bf18bee5SColin Lord         error_setg(errp, "Device '%s' does not have a tray", device);
2395bf18bee5SColin Lord         return -ENOSYS;
239612c7ec87SMax Reitz     }
239712c7ec87SMax Reitz 
23987d8a9f71SMax Reitz     if (blk_dev_is_tray_open(blk)) {
23993a3086b7SJohn Snow         return 0;
24007d8a9f71SMax Reitz     }
24017d8a9f71SMax Reitz 
24027d8a9f71SMax Reitz     locked = blk_dev_is_medium_locked(blk);
24037d8a9f71SMax Reitz     if (locked) {
24047d8a9f71SMax Reitz         blk_dev_eject_request(blk, force);
24057d8a9f71SMax Reitz     }
24067d8a9f71SMax Reitz 
24077d8a9f71SMax Reitz     if (!locked || force) {
240839829a01SKevin Wolf         blk_dev_change_media_cb(blk, false, &error_abort);
24097d8a9f71SMax Reitz     }
24103a3086b7SJohn Snow 
24113a3086b7SJohn Snow     if (locked && !force) {
2412bf18bee5SColin Lord         error_setg(errp, "Device '%s' is locked and force was not specified, "
2413bf18bee5SColin Lord                    "wait for tray to open and try again", device);
2414bf18bee5SColin Lord         return -EINPROGRESS;
24153a3086b7SJohn Snow     }
24163a3086b7SJohn Snow 
24173a3086b7SJohn Snow     return 0;
24183a3086b7SJohn Snow }
24193a3086b7SJohn Snow 
2420b33945cfSKevin Wolf void qmp_blockdev_open_tray(bool has_device, const char *device,
2421b33945cfSKevin Wolf                             bool has_id, const char *id,
2422b33945cfSKevin Wolf                             bool has_force, bool force,
24233a3086b7SJohn Snow                             Error **errp)
24243a3086b7SJohn Snow {
2425bf18bee5SColin Lord     Error *local_err = NULL;
2426bf18bee5SColin Lord     int rc;
2427bf18bee5SColin Lord 
24283a3086b7SJohn Snow     if (!has_force) {
24293a3086b7SJohn Snow         force = false;
24303a3086b7SJohn Snow     }
2431b33945cfSKevin Wolf     rc = do_open_tray(has_device ? device : NULL,
2432b33945cfSKevin Wolf                       has_id ? id : NULL,
2433b33945cfSKevin Wolf                       force, &local_err);
2434bf18bee5SColin Lord     if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2435bf18bee5SColin Lord         error_propagate(errp, local_err);
2436bf18bee5SColin Lord         return;
2437bf18bee5SColin Lord     }
2438bf18bee5SColin Lord     error_free(local_err);
24397d8a9f71SMax Reitz }
24407d8a9f71SMax Reitz 
2441b33945cfSKevin Wolf void qmp_blockdev_close_tray(bool has_device, const char *device,
2442b33945cfSKevin Wolf                              bool has_id, const char *id,
2443b33945cfSKevin Wolf                              Error **errp)
2444abaaf59dSMax Reitz {
2445abaaf59dSMax Reitz     BlockBackend *blk;
244639829a01SKevin Wolf     Error *local_err = NULL;
2447abaaf59dSMax Reitz 
2448b33945cfSKevin Wolf     device = has_device ? device : NULL;
2449b33945cfSKevin Wolf     id = has_id ? id : NULL;
2450b33945cfSKevin Wolf 
2451b33945cfSKevin Wolf     blk = qmp_get_blk(device, id, errp);
2452abaaf59dSMax Reitz     if (!blk) {
2453abaaf59dSMax Reitz         return;
2454abaaf59dSMax Reitz     }
2455abaaf59dSMax Reitz 
2456abaaf59dSMax Reitz     if (!blk_dev_has_removable_media(blk)) {
2457b33945cfSKevin Wolf         error_setg(errp, "Device '%s' is not removable", device ?: id);
2458abaaf59dSMax Reitz         return;
2459abaaf59dSMax Reitz     }
2460abaaf59dSMax Reitz 
246112c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
246212c7ec87SMax Reitz         /* Ignore this command on tray-less devices */
246312c7ec87SMax Reitz         return;
246412c7ec87SMax Reitz     }
246512c7ec87SMax Reitz 
2466abaaf59dSMax Reitz     if (!blk_dev_is_tray_open(blk)) {
2467abaaf59dSMax Reitz         return;
2468abaaf59dSMax Reitz     }
2469abaaf59dSMax Reitz 
247039829a01SKevin Wolf     blk_dev_change_media_cb(blk, true, &local_err);
247139829a01SKevin Wolf     if (local_err) {
247239829a01SKevin Wolf         error_propagate(errp, local_err);
247339829a01SKevin Wolf         return;
247439829a01SKevin Wolf     }
2475abaaf59dSMax Reitz }
2476abaaf59dSMax Reitz 
247782fcf66eSMax Reitz static void blockdev_remove_medium(bool has_device, const char *device,
247800949babSKevin Wolf                                    bool has_id, const char *id, Error **errp)
24792814f672SMax Reitz {
24802814f672SMax Reitz     BlockBackend *blk;
24812814f672SMax Reitz     BlockDriverState *bs;
24822814f672SMax Reitz     AioContext *aio_context;
248300949babSKevin Wolf     bool has_attached_device;
24842814f672SMax Reitz 
248500949babSKevin Wolf     device = has_device ? device : NULL;
248600949babSKevin Wolf     id = has_id ? id : NULL;
248700949babSKevin Wolf 
248800949babSKevin Wolf     blk = qmp_get_blk(device, id, errp);
24892814f672SMax Reitz     if (!blk) {
24902814f672SMax Reitz         return;
24912814f672SMax Reitz     }
24922814f672SMax Reitz 
24932814f672SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
249400949babSKevin Wolf     has_attached_device = blk_get_attached_dev(blk);
24952814f672SMax Reitz 
249600949babSKevin Wolf     if (has_attached_device && !blk_dev_has_removable_media(blk)) {
249700949babSKevin Wolf         error_setg(errp, "Device '%s' is not removable", device ?: id);
24982814f672SMax Reitz         return;
24992814f672SMax Reitz     }
25002814f672SMax Reitz 
250100949babSKevin Wolf     if (has_attached_device && blk_dev_has_tray(blk) &&
250200949babSKevin Wolf         !blk_dev_is_tray_open(blk))
250300949babSKevin Wolf     {
250400949babSKevin Wolf         error_setg(errp, "Tray of device '%s' is not open", device ?: id);
25052814f672SMax Reitz         return;
25062814f672SMax Reitz     }
25072814f672SMax Reitz 
25082814f672SMax Reitz     bs = blk_bs(blk);
25092814f672SMax Reitz     if (!bs) {
25102814f672SMax Reitz         return;
25112814f672SMax Reitz     }
25122814f672SMax Reitz 
25132814f672SMax Reitz     aio_context = bdrv_get_aio_context(bs);
25142814f672SMax Reitz     aio_context_acquire(aio_context);
25152814f672SMax Reitz 
25162814f672SMax Reitz     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
25172814f672SMax Reitz         goto out;
25182814f672SMax Reitz     }
25192814f672SMax Reitz 
25202814f672SMax Reitz     blk_remove_bs(blk);
25212814f672SMax Reitz 
252212c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
252312c7ec87SMax Reitz         /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
252412c7ec87SMax Reitz          * called at all); therefore, the medium needs to be ejected here.
252512c7ec87SMax Reitz          * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
252612c7ec87SMax Reitz          * value passed here (i.e. false). */
252739829a01SKevin Wolf         blk_dev_change_media_cb(blk, false, &error_abort);
252812c7ec87SMax Reitz     }
252912c7ec87SMax Reitz 
25302814f672SMax Reitz out:
25312814f672SMax Reitz     aio_context_release(aio_context);
25322814f672SMax Reitz }
25332814f672SMax Reitz 
253434ce1111SMax Reitz void qmp_blockdev_remove_medium(const char *id, Error **errp)
253582fcf66eSMax Reitz {
253682fcf66eSMax Reitz     blockdev_remove_medium(false, NULL, true, id, errp);
253782fcf66eSMax Reitz }
253882fcf66eSMax Reitz 
2539716df217SKevin Wolf static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2540d1299882SMax Reitz                                             BlockDriverState *bs, Error **errp)
2541d1299882SMax Reitz {
254239829a01SKevin Wolf     Error *local_err = NULL;
2543d1299882SMax Reitz     bool has_device;
2544d7086422SKevin Wolf     int ret;
2545d1299882SMax Reitz 
2546d1299882SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
2547d1299882SMax Reitz     has_device = blk_get_attached_dev(blk);
2548d1299882SMax Reitz 
2549d1299882SMax Reitz     if (has_device && !blk_dev_has_removable_media(blk)) {
2550716df217SKevin Wolf         error_setg(errp, "Device is not removable");
2551d1299882SMax Reitz         return;
2552d1299882SMax Reitz     }
2553d1299882SMax Reitz 
255412c7ec87SMax Reitz     if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2555716df217SKevin Wolf         error_setg(errp, "Tray of the device is not open");
2556d1299882SMax Reitz         return;
2557d1299882SMax Reitz     }
2558d1299882SMax Reitz 
2559d1299882SMax Reitz     if (blk_bs(blk)) {
2560716df217SKevin Wolf         error_setg(errp, "There already is a medium in the device");
2561d1299882SMax Reitz         return;
2562d1299882SMax Reitz     }
2563d1299882SMax Reitz 
2564d7086422SKevin Wolf     ret = blk_insert_bs(blk, bs, errp);
2565d7086422SKevin Wolf     if (ret < 0) {
2566d7086422SKevin Wolf         return;
2567d7086422SKevin Wolf     }
2568d1299882SMax Reitz 
256912c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
257012c7ec87SMax Reitz         /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
257112c7ec87SMax Reitz          * called at all); therefore, the medium needs to be pushed into the
257212c7ec87SMax Reitz          * slot here.
257312c7ec87SMax Reitz          * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
257412c7ec87SMax Reitz          * value passed here (i.e. true). */
257539829a01SKevin Wolf         blk_dev_change_media_cb(blk, true, &local_err);
257639829a01SKevin Wolf         if (local_err) {
257739829a01SKevin Wolf             error_propagate(errp, local_err);
257839829a01SKevin Wolf             blk_remove_bs(blk);
257939829a01SKevin Wolf             return;
258039829a01SKevin Wolf         }
258112c7ec87SMax Reitz     }
2582d1299882SMax Reitz }
2583d1299882SMax Reitz 
258482fcf66eSMax Reitz static void blockdev_insert_medium(bool has_device, const char *device,
2585716df217SKevin Wolf                                    bool has_id, const char *id,
2586716df217SKevin Wolf                                    const char *node_name, Error **errp)
2587d1299882SMax Reitz {
2588716df217SKevin Wolf     BlockBackend *blk;
2589d1299882SMax Reitz     BlockDriverState *bs;
2590d1299882SMax Reitz 
2591716df217SKevin Wolf     blk = qmp_get_blk(has_device ? device : NULL,
2592716df217SKevin Wolf                       has_id ? id : NULL,
2593716df217SKevin Wolf                       errp);
2594716df217SKevin Wolf     if (!blk) {
2595716df217SKevin Wolf         return;
2596716df217SKevin Wolf     }
2597716df217SKevin Wolf 
2598d1299882SMax Reitz     bs = bdrv_find_node(node_name);
2599d1299882SMax Reitz     if (!bs) {
2600d1299882SMax Reitz         error_setg(errp, "Node '%s' not found", node_name);
2601d1299882SMax Reitz         return;
2602d1299882SMax Reitz     }
2603d1299882SMax Reitz 
26041f0c461bSKevin Wolf     if (bdrv_has_blk(bs)) {
2605e467da7bSKevin Wolf         error_setg(errp, "Node '%s' is already in use", node_name);
2606d1299882SMax Reitz         return;
2607d1299882SMax Reitz     }
2608d1299882SMax Reitz 
2609716df217SKevin Wolf     qmp_blockdev_insert_anon_medium(blk, bs, errp);
2610d1299882SMax Reitz }
2611d1299882SMax Reitz 
261234ce1111SMax Reitz void qmp_blockdev_insert_medium(const char *id, const char *node_name,
261382fcf66eSMax Reitz                                 Error **errp)
261482fcf66eSMax Reitz {
261582fcf66eSMax Reitz     blockdev_insert_medium(false, NULL, true, id, node_name, errp);
261682fcf66eSMax Reitz }
261782fcf66eSMax Reitz 
261870e2cb3bSKevin Wolf void qmp_blockdev_change_medium(bool has_device, const char *device,
261970e2cb3bSKevin Wolf                                 bool has_id, const char *id,
262070e2cb3bSKevin Wolf                                 const char *filename,
262124fb4133SMax Reitz                                 bool has_format, const char *format,
262239ff43d9SMax Reitz                                 bool has_read_only,
262339ff43d9SMax Reitz                                 BlockdevChangeReadOnlyMode read_only,
262424fb4133SMax Reitz                                 Error **errp)
2625de2c6c05SMax Reitz {
2626de2c6c05SMax Reitz     BlockBackend *blk;
2627de2c6c05SMax Reitz     BlockDriverState *medium_bs = NULL;
26285b363937SMax Reitz     int bdrv_flags;
2629b85114f8SKevin Wolf     bool detect_zeroes;
263038a53d50SColin Lord     int rc;
2631de2c6c05SMax Reitz     QDict *options = NULL;
2632de2c6c05SMax Reitz     Error *err = NULL;
2633de2c6c05SMax Reitz 
263470e2cb3bSKevin Wolf     blk = qmp_get_blk(has_device ? device : NULL,
263570e2cb3bSKevin Wolf                       has_id ? id : NULL,
263670e2cb3bSKevin Wolf                       errp);
2637de2c6c05SMax Reitz     if (!blk) {
2638de2c6c05SMax Reitz         goto fail;
2639de2c6c05SMax Reitz     }
2640de2c6c05SMax Reitz 
2641de2c6c05SMax Reitz     if (blk_bs(blk)) {
2642de2c6c05SMax Reitz         blk_update_root_state(blk);
2643de2c6c05SMax Reitz     }
2644de2c6c05SMax Reitz 
2645de2c6c05SMax Reitz     bdrv_flags = blk_get_open_flags_from_root_state(blk);
2646156abc2fSAlyssa Milburn     bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2647e35bdc12SKevin Wolf         BDRV_O_PROTOCOL | BDRV_O_AUTO_RDONLY);
2648de2c6c05SMax Reitz 
264939ff43d9SMax Reitz     if (!has_read_only) {
265039ff43d9SMax Reitz         read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
265139ff43d9SMax Reitz     }
265239ff43d9SMax Reitz 
265339ff43d9SMax Reitz     switch (read_only) {
265439ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
265539ff43d9SMax Reitz         break;
265639ff43d9SMax Reitz 
265739ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
265839ff43d9SMax Reitz         bdrv_flags &= ~BDRV_O_RDWR;
265939ff43d9SMax Reitz         break;
266039ff43d9SMax Reitz 
266139ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
266239ff43d9SMax Reitz         bdrv_flags |= BDRV_O_RDWR;
266339ff43d9SMax Reitz         break;
266439ff43d9SMax Reitz 
266539ff43d9SMax Reitz     default:
266639ff43d9SMax Reitz         abort();
266739ff43d9SMax Reitz     }
266839ff43d9SMax Reitz 
2669de2c6c05SMax Reitz     options = qdict_new();
2670b85114f8SKevin Wolf     detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
267146f5ac20SEric Blake     qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2672b85114f8SKevin Wolf 
2673b85114f8SKevin Wolf     if (has_format) {
267446f5ac20SEric Blake         qdict_put_str(options, "driver", format);
2675de2c6c05SMax Reitz     }
2676de2c6c05SMax Reitz 
26775b363937SMax Reitz     medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
26785b363937SMax Reitz     if (!medium_bs) {
2679de2c6c05SMax Reitz         goto fail;
2680de2c6c05SMax Reitz     }
2681de2c6c05SMax Reitz 
268270e2cb3bSKevin Wolf     rc = do_open_tray(has_device ? device : NULL,
268370e2cb3bSKevin Wolf                       has_id ? id : NULL,
268470e2cb3bSKevin Wolf                       false, &err);
268538a53d50SColin Lord     if (rc && rc != -ENOSYS) {
2686de2c6c05SMax Reitz         error_propagate(errp, err);
2687de2c6c05SMax Reitz         goto fail;
2688de2c6c05SMax Reitz     }
268938a53d50SColin Lord     error_free(err);
269038a53d50SColin Lord     err = NULL;
2691de2c6c05SMax Reitz 
269282fcf66eSMax Reitz     blockdev_remove_medium(has_device, device, has_id, id, &err);
2693de2c6c05SMax Reitz     if (err) {
2694de2c6c05SMax Reitz         error_propagate(errp, err);
2695de2c6c05SMax Reitz         goto fail;
2696de2c6c05SMax Reitz     }
2697de2c6c05SMax Reitz 
2698716df217SKevin Wolf     qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2699de2c6c05SMax Reitz     if (err) {
2700de2c6c05SMax Reitz         error_propagate(errp, err);
2701de2c6c05SMax Reitz         goto fail;
2702de2c6c05SMax Reitz     }
2703de2c6c05SMax Reitz 
270470e2cb3bSKevin Wolf     qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2705de2c6c05SMax Reitz 
2706de2c6c05SMax Reitz fail:
2707de2c6c05SMax Reitz     /* If the medium has been inserted, the device has its own reference, so
2708de2c6c05SMax Reitz      * ours must be relinquished; and if it has not been inserted successfully,
2709de2c6c05SMax Reitz      * the reference must be relinquished anyway */
2710de2c6c05SMax Reitz     bdrv_unref(medium_bs);
2711de2c6c05SMax Reitz }
2712de2c6c05SMax Reitz 
2713727f005eSZhi Yong Wu /* throttling disk I/O limits */
27144dc9397bSEric Blake void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2715727f005eSZhi Yong Wu {
2716cc0681c4SBenoît Canet     ThrottleConfig cfg;
2717727f005eSZhi Yong Wu     BlockDriverState *bs;
2718a0e8544cSFam Zheng     BlockBackend *blk;
2719b15446fdSStefan Hajnoczi     AioContext *aio_context;
2720727f005eSZhi Yong Wu 
27217a9877a0SKevin Wolf     blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
27227a9877a0SKevin Wolf                       arg->has_id ? arg->id : NULL,
27237a9877a0SKevin Wolf                       errp);
2724a0e8544cSFam Zheng     if (!blk) {
272580047da5SLuiz Capitulino         return;
2726727f005eSZhi Yong Wu     }
27275433c24fSMax Reitz 
27285433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
27295433c24fSMax Reitz     aio_context_acquire(aio_context);
27305433c24fSMax Reitz 
2731a0e8544cSFam Zheng     bs = blk_bs(blk);
27325433c24fSMax Reitz     if (!bs) {
27337a9877a0SKevin Wolf         error_setg(errp, "Device has no medium");
27345433c24fSMax Reitz         goto out;
27355433c24fSMax Reitz     }
2736727f005eSZhi Yong Wu 
27371588ab5dSAlberto Garcia     throttle_config_init(&cfg);
27384dc9397bSEric Blake     cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
27394dc9397bSEric Blake     cfg.buckets[THROTTLE_BPS_READ].avg  = arg->bps_rd;
27404dc9397bSEric Blake     cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2741727f005eSZhi Yong Wu 
27424dc9397bSEric Blake     cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
27434dc9397bSEric Blake     cfg.buckets[THROTTLE_OPS_READ].avg  = arg->iops_rd;
27444dc9397bSEric Blake     cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2745cc0681c4SBenoît Canet 
27464dc9397bSEric Blake     if (arg->has_bps_max) {
27474dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
27483e9fab69SBenoît Canet     }
27494dc9397bSEric Blake     if (arg->has_bps_rd_max) {
27504dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
27513e9fab69SBenoît Canet     }
27524dc9397bSEric Blake     if (arg->has_bps_wr_max) {
27534dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
27543e9fab69SBenoît Canet     }
27554dc9397bSEric Blake     if (arg->has_iops_max) {
27564dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
27573e9fab69SBenoît Canet     }
27584dc9397bSEric Blake     if (arg->has_iops_rd_max) {
27594dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
27603e9fab69SBenoît Canet     }
27614dc9397bSEric Blake     if (arg->has_iops_wr_max) {
27624dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
27633e9fab69SBenoît Canet     }
2764cc0681c4SBenoît Canet 
27654dc9397bSEric Blake     if (arg->has_bps_max_length) {
27664dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2767dce13204SAlberto Garcia     }
27684dc9397bSEric Blake     if (arg->has_bps_rd_max_length) {
27694dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2770dce13204SAlberto Garcia     }
27714dc9397bSEric Blake     if (arg->has_bps_wr_max_length) {
27724dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2773dce13204SAlberto Garcia     }
27744dc9397bSEric Blake     if (arg->has_iops_max_length) {
27754dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2776dce13204SAlberto Garcia     }
27774dc9397bSEric Blake     if (arg->has_iops_rd_max_length) {
27784dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2779dce13204SAlberto Garcia     }
27804dc9397bSEric Blake     if (arg->has_iops_wr_max_length) {
27814dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2782dce13204SAlberto Garcia     }
2783dce13204SAlberto Garcia 
27844dc9397bSEric Blake     if (arg->has_iops_size) {
27854dc9397bSEric Blake         cfg.op_size = arg->iops_size;
27862024c1dfSBenoît Canet     }
2787cc0681c4SBenoît Canet 
2788d5851089SAlberto Garcia     if (!throttle_is_valid(&cfg, errp)) {
27895433c24fSMax Reitz         goto out;
2790727f005eSZhi Yong Wu     }
2791727f005eSZhi Yong Wu 
279276f4afb4SAlberto Garcia     if (throttle_enabled(&cfg)) {
279376f4afb4SAlberto Garcia         /* Enable I/O limits if they're not enabled yet, otherwise
279476f4afb4SAlberto Garcia          * just update the throttling group. */
2795022cdc9fSManos Pitsidianakis         if (!blk_get_public(blk)->throttle_group_member.throttle_state) {
27964dc9397bSEric Blake             blk_io_limits_enable(blk,
27977a9877a0SKevin Wolf                                  arg->has_group ? arg->group :
27987a9877a0SKevin Wolf                                  arg->has_device ? arg->device :
27997a9877a0SKevin Wolf                                  arg->id);
28004dc9397bSEric Blake         } else if (arg->has_group) {
28014dc9397bSEric Blake             blk_io_limits_update_group(blk, arg->group);
2802727f005eSZhi Yong Wu         }
280376f4afb4SAlberto Garcia         /* Set the new throttling configuration */
280497148076SKevin Wolf         blk_set_io_limits(blk, &cfg);
2805022cdc9fSManos Pitsidianakis     } else if (blk_get_public(blk)->throttle_group_member.throttle_state) {
280676f4afb4SAlberto Garcia         /* If all throttling settings are set to 0, disable I/O limits */
280797148076SKevin Wolf         blk_io_limits_disable(blk);
2808727f005eSZhi Yong Wu     }
2809b15446fdSStefan Hajnoczi 
28105433c24fSMax Reitz out:
2811b15446fdSStefan Hajnoczi     aio_context_release(aio_context);
2812727f005eSZhi Yong Wu }
2813727f005eSZhi Yong Wu 
2814341ebc2fSJohn Snow void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2815341ebc2fSJohn Snow                                 bool has_granularity, uint32_t granularity,
2816fd5ae4ccSVladimir Sementsov-Ogievskiy                                 bool has_persistent, bool persistent,
2817eb738bb5SVladimir Sementsov-Ogievskiy                                 bool has_autoload, bool autoload,
2818a6e2ca5fSVladimir Sementsov-Ogievskiy                                 bool has_disabled, bool disabled,
2819341ebc2fSJohn Snow                                 Error **errp)
2820341ebc2fSJohn Snow {
2821341ebc2fSJohn Snow     BlockDriverState *bs;
2822fd5ae4ccSVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
2823341ebc2fSJohn Snow 
2824341ebc2fSJohn Snow     if (!name || name[0] == '\0') {
2825341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be empty");
2826341ebc2fSJohn Snow         return;
2827341ebc2fSJohn Snow     }
2828341ebc2fSJohn Snow 
2829341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, errp);
2830341ebc2fSJohn Snow     if (!bs) {
2831341ebc2fSJohn Snow         return;
2832341ebc2fSJohn Snow     }
2833341ebc2fSJohn Snow 
2834341ebc2fSJohn Snow     if (has_granularity) {
2835341ebc2fSJohn Snow         if (granularity < 512 || !is_power_of_2(granularity)) {
2836341ebc2fSJohn Snow             error_setg(errp, "Granularity must be power of 2 "
2837341ebc2fSJohn Snow                              "and at least 512");
28382119882cSPaolo Bonzini             return;
2839341ebc2fSJohn Snow         }
2840341ebc2fSJohn Snow     } else {
2841341ebc2fSJohn Snow         /* Default to cluster size, if available: */
2842341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(bs);
2843341ebc2fSJohn Snow     }
2844341ebc2fSJohn Snow 
2845fd5ae4ccSVladimir Sementsov-Ogievskiy     if (!has_persistent) {
2846fd5ae4ccSVladimir Sementsov-Ogievskiy         persistent = false;
2847fd5ae4ccSVladimir Sementsov-Ogievskiy     }
2848eb738bb5SVladimir Sementsov-Ogievskiy 
28493e99da5eSVladimir Sementsov-Ogievskiy     if (has_autoload) {
28503e99da5eSVladimir Sementsov-Ogievskiy         warn_report("Autoload option is deprecated and its value is ignored");
2851eb738bb5SVladimir Sementsov-Ogievskiy     }
2852fd5ae4ccSVladimir Sementsov-Ogievskiy 
2853a6e2ca5fSVladimir Sementsov-Ogievskiy     if (!has_disabled) {
2854a6e2ca5fSVladimir Sementsov-Ogievskiy         disabled = false;
2855a6e2ca5fSVladimir Sementsov-Ogievskiy     }
2856a6e2ca5fSVladimir Sementsov-Ogievskiy 
2857fd5ae4ccSVladimir Sementsov-Ogievskiy     if (persistent &&
2858fd5ae4ccSVladimir Sementsov-Ogievskiy         !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
2859fd5ae4ccSVladimir Sementsov-Ogievskiy     {
2860fd5ae4ccSVladimir Sementsov-Ogievskiy         return;
2861fd5ae4ccSVladimir Sementsov-Ogievskiy     }
2862fd5ae4ccSVladimir Sementsov-Ogievskiy 
2863fd5ae4ccSVladimir Sementsov-Ogievskiy     bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2864eb738bb5SVladimir Sementsov-Ogievskiy     if (bitmap == NULL) {
2865eb738bb5SVladimir Sementsov-Ogievskiy         return;
2866fd5ae4ccSVladimir Sementsov-Ogievskiy     }
2867eb738bb5SVladimir Sementsov-Ogievskiy 
2868a6e2ca5fSVladimir Sementsov-Ogievskiy     if (disabled) {
2869a6e2ca5fSVladimir Sementsov-Ogievskiy         bdrv_disable_dirty_bitmap(bitmap);
2870a6e2ca5fSVladimir Sementsov-Ogievskiy     }
2871a6e2ca5fSVladimir Sementsov-Ogievskiy 
2872eb738bb5SVladimir Sementsov-Ogievskiy     bdrv_dirty_bitmap_set_persistance(bitmap, persistent);
2873341ebc2fSJohn Snow }
2874341ebc2fSJohn Snow 
2875341ebc2fSJohn Snow void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2876341ebc2fSJohn Snow                                    Error **errp)
2877341ebc2fSJohn Snow {
2878341ebc2fSJohn Snow     BlockDriverState *bs;
2879341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
28805c36c1afSVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
2881341ebc2fSJohn Snow 
28822119882cSPaolo Bonzini     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2883341ebc2fSJohn Snow     if (!bitmap || !bs) {
2884341ebc2fSJohn Snow         return;
2885341ebc2fSJohn Snow     }
2886341ebc2fSJohn Snow 
2887993edc0cSJohn Snow     if (bdrv_dirty_bitmap_user_locked(bitmap)) {
28889bd2b08fSJohn Snow         error_setg(errp,
2889993edc0cSJohn Snow                    "Bitmap '%s' is currently in use by another operation and"
2890993edc0cSJohn Snow                    " cannot be removed", name);
28914f43e953SVladimir Sementsov-Ogievskiy         return;
28929bd2b08fSJohn Snow     }
28935c36c1afSVladimir Sementsov-Ogievskiy 
28945c36c1afSVladimir Sementsov-Ogievskiy     if (bdrv_dirty_bitmap_get_persistance(bitmap)) {
28955c36c1afSVladimir Sementsov-Ogievskiy         bdrv_remove_persistent_dirty_bitmap(bs, name, &local_err);
28965c36c1afSVladimir Sementsov-Ogievskiy         if (local_err != NULL) {
28975c36c1afSVladimir Sementsov-Ogievskiy             error_propagate(errp, local_err);
28985c36c1afSVladimir Sementsov-Ogievskiy             return;
28995c36c1afSVladimir Sementsov-Ogievskiy         }
29005c36c1afSVladimir Sementsov-Ogievskiy     }
29015c36c1afSVladimir Sementsov-Ogievskiy 
2902341ebc2fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
2903341ebc2fSJohn Snow }
2904341ebc2fSJohn Snow 
2905e74e6b78SJohn Snow /**
2906e74e6b78SJohn Snow  * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2907e74e6b78SJohn Snow  * immediately after a full backup operation.
2908e74e6b78SJohn Snow  */
2909e74e6b78SJohn Snow void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2910e74e6b78SJohn Snow                                   Error **errp)
2911e74e6b78SJohn Snow {
2912e74e6b78SJohn Snow     BdrvDirtyBitmap *bitmap;
2913e74e6b78SJohn Snow     BlockDriverState *bs;
2914e74e6b78SJohn Snow 
29152119882cSPaolo Bonzini     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2916e74e6b78SJohn Snow     if (!bitmap || !bs) {
2917e74e6b78SJohn Snow         return;
2918e74e6b78SJohn Snow     }
2919e74e6b78SJohn Snow 
2920993edc0cSJohn Snow     if (bdrv_dirty_bitmap_user_locked(bitmap)) {
2921e74e6b78SJohn Snow         error_setg(errp,
2922993edc0cSJohn Snow                    "Bitmap '%s' is currently in use by another operation"
2923993edc0cSJohn Snow                    " and cannot be cleared", name);
29244f43e953SVladimir Sementsov-Ogievskiy         return;
2925d6883bc9SVladimir Sementsov-Ogievskiy     } else if (bdrv_dirty_bitmap_readonly(bitmap)) {
2926d6883bc9SVladimir Sementsov-Ogievskiy         error_setg(errp, "Bitmap '%s' is readonly and cannot be cleared", name);
2927d6883bc9SVladimir Sementsov-Ogievskiy         return;
2928e74e6b78SJohn Snow     }
2929e74e6b78SJohn Snow 
2930df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(bitmap, NULL);
2931e74e6b78SJohn Snow }
2932e74e6b78SJohn Snow 
29330e2b7f09SJohn Snow void qmp_block_dirty_bitmap_enable(const char *node, const char *name,
29345c5d2e50SVladimir Sementsov-Ogievskiy                                    Error **errp)
29355c5d2e50SVladimir Sementsov-Ogievskiy {
29365c5d2e50SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
29375c5d2e50SVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
29385c5d2e50SVladimir Sementsov-Ogievskiy 
29395c5d2e50SVladimir Sementsov-Ogievskiy     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
29405c5d2e50SVladimir Sementsov-Ogievskiy     if (!bitmap) {
29415c5d2e50SVladimir Sementsov-Ogievskiy         return;
29425c5d2e50SVladimir Sementsov-Ogievskiy     }
29435c5d2e50SVladimir Sementsov-Ogievskiy 
2944b053bb55SJohn Snow     if (bdrv_dirty_bitmap_user_locked(bitmap)) {
29455c5d2e50SVladimir Sementsov-Ogievskiy         error_setg(errp,
2946b053bb55SJohn Snow                    "Bitmap '%s' is currently in use by another operation"
2947b053bb55SJohn Snow                    " and cannot be enabled", name);
29485c5d2e50SVladimir Sementsov-Ogievskiy         return;
29495c5d2e50SVladimir Sementsov-Ogievskiy     }
29505c5d2e50SVladimir Sementsov-Ogievskiy 
29515c5d2e50SVladimir Sementsov-Ogievskiy     bdrv_enable_dirty_bitmap(bitmap);
29525c5d2e50SVladimir Sementsov-Ogievskiy }
29535c5d2e50SVladimir Sementsov-Ogievskiy 
29540e2b7f09SJohn Snow void qmp_block_dirty_bitmap_disable(const char *node, const char *name,
29555c5d2e50SVladimir Sementsov-Ogievskiy                                     Error **errp)
29565c5d2e50SVladimir Sementsov-Ogievskiy {
29575c5d2e50SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
29585c5d2e50SVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
29595c5d2e50SVladimir Sementsov-Ogievskiy 
29605c5d2e50SVladimir Sementsov-Ogievskiy     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
29615c5d2e50SVladimir Sementsov-Ogievskiy     if (!bitmap) {
29625c5d2e50SVladimir Sementsov-Ogievskiy         return;
29635c5d2e50SVladimir Sementsov-Ogievskiy     }
29645c5d2e50SVladimir Sementsov-Ogievskiy 
2965b053bb55SJohn Snow     if (bdrv_dirty_bitmap_user_locked(bitmap)) {
29665c5d2e50SVladimir Sementsov-Ogievskiy         error_setg(errp,
2967b053bb55SJohn Snow                    "Bitmap '%s' is currently in use by another operation"
2968b053bb55SJohn Snow                    " and cannot be disabled", name);
29695c5d2e50SVladimir Sementsov-Ogievskiy         return;
29705c5d2e50SVladimir Sementsov-Ogievskiy     }
29715c5d2e50SVladimir Sementsov-Ogievskiy 
29725c5d2e50SVladimir Sementsov-Ogievskiy     bdrv_disable_dirty_bitmap(bitmap);
29735c5d2e50SVladimir Sementsov-Ogievskiy }
29745c5d2e50SVladimir Sementsov-Ogievskiy 
2975360d4e4eSJohn Snow static BdrvDirtyBitmap *do_block_dirty_bitmap_merge(const char *node,
2976360d4e4eSJohn Snow                                                     const char *target,
2977360d4e4eSJohn Snow                                                     strList *bitmaps,
2978360d4e4eSJohn Snow                                                     HBitmap **backup,
2979360d4e4eSJohn Snow                                                     Error **errp)
2980b598e531SVladimir Sementsov-Ogievskiy {
2981b598e531SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
2982360d4e4eSJohn Snow     BdrvDirtyBitmap *dst, *src, *anon;
2983360d4e4eSJohn Snow     strList *lst;
2984360d4e4eSJohn Snow     Error *local_err = NULL;
2985b598e531SVladimir Sementsov-Ogievskiy 
2986360d4e4eSJohn Snow     dst = block_dirty_bitmap_lookup(node, target, &bs, errp);
2987b598e531SVladimir Sementsov-Ogievskiy     if (!dst) {
2988360d4e4eSJohn Snow         return NULL;
2989b598e531SVladimir Sementsov-Ogievskiy     }
2990b598e531SVladimir Sementsov-Ogievskiy 
2991360d4e4eSJohn Snow     anon = bdrv_create_dirty_bitmap(bs, bdrv_dirty_bitmap_granularity(dst),
2992360d4e4eSJohn Snow                                     NULL, errp);
2993360d4e4eSJohn Snow     if (!anon) {
2994360d4e4eSJohn Snow         return NULL;
2995360d4e4eSJohn Snow     }
2996360d4e4eSJohn Snow 
2997360d4e4eSJohn Snow     for (lst = bitmaps; lst; lst = lst->next) {
2998360d4e4eSJohn Snow         src = bdrv_find_dirty_bitmap(bs, lst->value);
2999b598e531SVladimir Sementsov-Ogievskiy         if (!src) {
3000360d4e4eSJohn Snow             error_setg(errp, "Dirty bitmap '%s' not found", lst->value);
3001360d4e4eSJohn Snow             dst = NULL;
3002360d4e4eSJohn Snow             goto out;
3003b598e531SVladimir Sementsov-Ogievskiy         }
3004b598e531SVladimir Sementsov-Ogievskiy 
3005360d4e4eSJohn Snow         bdrv_merge_dirty_bitmap(anon, src, NULL, &local_err);
3006360d4e4eSJohn Snow         if (local_err) {
3007360d4e4eSJohn Snow             error_propagate(errp, local_err);
3008360d4e4eSJohn Snow             dst = NULL;
3009360d4e4eSJohn Snow             goto out;
3010360d4e4eSJohn Snow         }
3011360d4e4eSJohn Snow     }
3012360d4e4eSJohn Snow 
3013360d4e4eSJohn Snow     /* Merge into dst; dst is unchanged on failure. */
3014360d4e4eSJohn Snow     bdrv_merge_dirty_bitmap(dst, anon, backup, errp);
3015360d4e4eSJohn Snow 
3016360d4e4eSJohn Snow  out:
3017360d4e4eSJohn Snow     bdrv_release_dirty_bitmap(bs, anon);
3018360d4e4eSJohn Snow     return dst;
3019360d4e4eSJohn Snow }
3020360d4e4eSJohn Snow 
30210e2b7f09SJohn Snow void qmp_block_dirty_bitmap_merge(const char *node, const char *target,
3022360d4e4eSJohn Snow                                   strList *bitmaps, Error **errp)
3023360d4e4eSJohn Snow {
3024360d4e4eSJohn Snow     do_block_dirty_bitmap_merge(node, target, bitmaps, NULL, errp);
3025b598e531SVladimir Sementsov-Ogievskiy }
3026b598e531SVladimir Sementsov-Ogievskiy 
3027a3b52535SVladimir Sementsov-Ogievskiy BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
3028a3b52535SVladimir Sementsov-Ogievskiy                                                               const char *name,
3029a3b52535SVladimir Sementsov-Ogievskiy                                                               Error **errp)
3030a3b52535SVladimir Sementsov-Ogievskiy {
3031a3b52535SVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
3032a3b52535SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
3033a3b52535SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapSha256 *ret = NULL;
3034a3b52535SVladimir Sementsov-Ogievskiy     char *sha256;
3035a3b52535SVladimir Sementsov-Ogievskiy 
3036a3b52535SVladimir Sementsov-Ogievskiy     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3037a3b52535SVladimir Sementsov-Ogievskiy     if (!bitmap || !bs) {
3038a3b52535SVladimir Sementsov-Ogievskiy         return NULL;
3039a3b52535SVladimir Sementsov-Ogievskiy     }
3040a3b52535SVladimir Sementsov-Ogievskiy 
3041a3b52535SVladimir Sementsov-Ogievskiy     sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
3042a3b52535SVladimir Sementsov-Ogievskiy     if (sha256 == NULL) {
3043a3b52535SVladimir Sementsov-Ogievskiy         return NULL;
3044a3b52535SVladimir Sementsov-Ogievskiy     }
3045a3b52535SVladimir Sementsov-Ogievskiy 
3046a3b52535SVladimir Sementsov-Ogievskiy     ret = g_new(BlockDirtyBitmapSha256, 1);
3047a3b52535SVladimir Sementsov-Ogievskiy     ret->sha256 = sha256;
3048a3b52535SVladimir Sementsov-Ogievskiy 
3049a3b52535SVladimir Sementsov-Ogievskiy     return ret;
3050a3b52535SVladimir Sementsov-Ogievskiy }
3051a3b52535SVladimir Sementsov-Ogievskiy 
3052072ebe6bSMarkus Armbruster void hmp_drive_del(Monitor *mon, const QDict *qdict)
30539063f814SRyan Harper {
30549063f814SRyan Harper     const char *id = qdict_get_str(qdict, "id");
30557e7d56d9SMarkus Armbruster     BlockBackend *blk;
30569063f814SRyan Harper     BlockDriverState *bs;
30578ad4202bSStefan Hajnoczi     AioContext *aio_context;
30583718d8abSFam Zheng     Error *local_err = NULL;
30599063f814SRyan Harper 
30602073d410SKevin Wolf     bs = bdrv_find_node(id);
30612073d410SKevin Wolf     if (bs) {
306279b7a77eSMarkus Armbruster         qmp_blockdev_del(id, &local_err);
30632073d410SKevin Wolf         if (local_err) {
30642073d410SKevin Wolf             error_report_err(local_err);
30652073d410SKevin Wolf         }
30662073d410SKevin Wolf         return;
30672073d410SKevin Wolf     }
30682073d410SKevin Wolf 
30697e7d56d9SMarkus Armbruster     blk = blk_by_name(id);
30707e7d56d9SMarkus Armbruster     if (!blk) {
3071b1422f20SMarkus Armbruster         error_report("Device '%s' not found", id);
3072072ebe6bSMarkus Armbruster         return;
30739063f814SRyan Harper     }
30748ad4202bSStefan Hajnoczi 
307526f8b3a8SMarkus Armbruster     if (!blk_legacy_dinfo(blk)) {
307648f364ddSMarkus Armbruster         error_report("Deleting device added with blockdev-add"
307748f364ddSMarkus Armbruster                      " is not supported");
3078072ebe6bSMarkus Armbruster         return;
307948f364ddSMarkus Armbruster     }
308048f364ddSMarkus Armbruster 
30815433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
30828ad4202bSStefan Hajnoczi     aio_context_acquire(aio_context);
30838ad4202bSStefan Hajnoczi 
30845433c24fSMax Reitz     bs = blk_bs(blk);
30855433c24fSMax Reitz     if (bs) {
30863718d8abSFam Zheng         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
3087565f65d2SMarkus Armbruster             error_report_err(local_err);
30888ad4202bSStefan Hajnoczi             aio_context_release(aio_context);
3089072ebe6bSMarkus Armbruster             return;
30908591675fSMarcelo Tosatti         }
30919063f814SRyan Harper 
3092938abd43SMax Reitz         blk_remove_bs(blk);
30935433c24fSMax Reitz     }
30949063f814SRyan Harper 
30957c735873SMax Reitz     /* Make the BlockBackend and the attached BlockDriverState anonymous */
3096efaa7c4eSMax Reitz     monitor_remove_blk(blk);
3097efaa7c4eSMax Reitz 
30987c735873SMax Reitz     /* If this BlockBackend has a device attached to it, its refcount will be
30997c735873SMax Reitz      * decremented when the device is removed; otherwise we have to do so here.
3100d22b2f41SRyan Harper      */
3101a7f53e26SMarkus Armbruster     if (blk_get_attached_dev(blk)) {
3102293c51a6SStefan Hajnoczi         /* Further I/O must not pause the guest */
3103373340b2SMax Reitz         blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
3104293c51a6SStefan Hajnoczi                          BLOCKDEV_ON_ERROR_REPORT);
3105d22b2f41SRyan Harper     } else {
3106b9fe8a7aSMarkus Armbruster         blk_unref(blk);
3107d22b2f41SRyan Harper     }
31089063f814SRyan Harper 
31098ad4202bSStefan Hajnoczi     aio_context_release(aio_context);
31109063f814SRyan Harper }
31116d4a2b3aSChristoph Hellwig 
31123b1dbd11SBenoît Canet void qmp_block_resize(bool has_device, const char *device,
31133b1dbd11SBenoît Canet                       bool has_node_name, const char *node_name,
31143b1dbd11SBenoît Canet                       int64_t size, Error **errp)
31156d4a2b3aSChristoph Hellwig {
31163b1dbd11SBenoît Canet     Error *local_err = NULL;
31177dad9ee6SKevin Wolf     BlockBackend *blk = NULL;
31186d4a2b3aSChristoph Hellwig     BlockDriverState *bs;
3119927e0e76SStefan Hajnoczi     AioContext *aio_context;
31208732901eSKevin Wolf     int ret;
31216d4a2b3aSChristoph Hellwig 
31223b1dbd11SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
31233b1dbd11SBenoît Canet                         has_node_name ? node_name : NULL,
31243b1dbd11SBenoît Canet                         &local_err);
312584d18f06SMarkus Armbruster     if (local_err) {
31263b1dbd11SBenoît Canet         error_propagate(errp, local_err);
31273b1dbd11SBenoît Canet         return;
31283b1dbd11SBenoît Canet     }
31293b1dbd11SBenoît Canet 
3130927e0e76SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
3131927e0e76SStefan Hajnoczi     aio_context_acquire(aio_context);
3132927e0e76SStefan Hajnoczi 
31333b1dbd11SBenoît Canet     if (!bdrv_is_first_non_filter(bs)) {
3134c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "resize");
3135927e0e76SStefan Hajnoczi         goto out;
31366d4a2b3aSChristoph Hellwig     }
31376d4a2b3aSChristoph Hellwig 
31386d4a2b3aSChristoph Hellwig     if (size < 0) {
3139c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
3140927e0e76SStefan Hajnoczi         goto out;
31416d4a2b3aSChristoph Hellwig     }
31426d4a2b3aSChristoph Hellwig 
31439c75e168SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
3144c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
3145927e0e76SStefan Hajnoczi         goto out;
31469c75e168SJeff Cody     }
31479c75e168SJeff Cody 
31486d0eb64dSKevin Wolf     blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
3149d7086422SKevin Wolf     ret = blk_insert_bs(blk, bs, errp);
3150d7086422SKevin Wolf     if (ret < 0) {
3151d7086422SKevin Wolf         goto out;
3152d7086422SKevin Wolf     }
31537dad9ee6SKevin Wolf 
3154698bdfa0SJohn Snow     bdrv_drained_begin(bs);
31553a691c50SMax Reitz     ret = blk_truncate(blk, size, PREALLOC_MODE_OFF, errp);
3156698bdfa0SJohn Snow     bdrv_drained_end(bs);
3157927e0e76SStefan Hajnoczi 
3158927e0e76SStefan Hajnoczi out:
31597dad9ee6SKevin Wolf     blk_unref(blk);
3160927e0e76SStefan Hajnoczi     aio_context_release(aio_context);
31616d4a2b3aSChristoph Hellwig }
316212bd451fSStefan Hajnoczi 
31632323322eSAlberto Garcia void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
316413d8cc51SJeff Cody                       bool has_base, const char *base,
3165312fe09cSAlberto Garcia                       bool has_base_node, const char *base_node,
316613d8cc51SJeff Cody                       bool has_backing_file, const char *backing_file,
316713d8cc51SJeff Cody                       bool has_speed, int64_t speed,
31681d809098SPaolo Bonzini                       bool has_on_error, BlockdevOnError on_error,
3169241ca1abSJohn Snow                       bool has_auto_finalize, bool auto_finalize,
3170241ca1abSJohn Snow                       bool has_auto_dismiss, bool auto_dismiss,
31711d809098SPaolo Bonzini                       Error **errp)
317212bd451fSStefan Hajnoczi {
3173554b6147SAlberto Garcia     BlockDriverState *bs, *iter;
3174c8c3080fSMarcelo Tosatti     BlockDriverState *base_bs = NULL;
3175f3e69bebSStefan Hajnoczi     AioContext *aio_context;
3176fd7f8c65SStefan Hajnoczi     Error *local_err = NULL;
317713d8cc51SJeff Cody     const char *base_name = NULL;
3178cf6320dfSJohn Snow     int job_flags = JOB_DEFAULT;
317912bd451fSStefan Hajnoczi 
31801d809098SPaolo Bonzini     if (!has_on_error) {
31811d809098SPaolo Bonzini         on_error = BLOCKDEV_ON_ERROR_REPORT;
31821d809098SPaolo Bonzini     }
31831d809098SPaolo Bonzini 
3184554b6147SAlberto Garcia     bs = bdrv_lookup_bs(device, device, errp);
3185b6c1bae5SKevin Wolf     if (!bs) {
318612bd451fSStefan Hajnoczi         return;
318712bd451fSStefan Hajnoczi     }
318812bd451fSStefan Hajnoczi 
3189b6c1bae5SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3190f3e69bebSStefan Hajnoczi     aio_context_acquire(aio_context);
3191f3e69bebSStefan Hajnoczi 
3192312fe09cSAlberto Garcia     if (has_base && has_base_node) {
3193312fe09cSAlberto Garcia         error_setg(errp, "'base' and 'base-node' cannot be specified "
3194312fe09cSAlberto Garcia                    "at the same time");
3195312fe09cSAlberto Garcia         goto out;
3196312fe09cSAlberto Garcia     }
3197312fe09cSAlberto Garcia 
319813d8cc51SJeff Cody     if (has_base) {
3199c8c3080fSMarcelo Tosatti         base_bs = bdrv_find_backing_image(bs, base);
3200c8c3080fSMarcelo Tosatti         if (base_bs == NULL) {
3201c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_BASE_NOT_FOUND, base);
3202f3e69bebSStefan Hajnoczi             goto out;
320312bd451fSStefan Hajnoczi         }
3204f3e69bebSStefan Hajnoczi         assert(bdrv_get_aio_context(base_bs) == aio_context);
320513d8cc51SJeff Cody         base_name = base;
3206c8c3080fSMarcelo Tosatti     }
320712bd451fSStefan Hajnoczi 
3208312fe09cSAlberto Garcia     if (has_base_node) {
3209312fe09cSAlberto Garcia         base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3210312fe09cSAlberto Garcia         if (!base_bs) {
3211312fe09cSAlberto Garcia             goto out;
3212312fe09cSAlberto Garcia         }
3213312fe09cSAlberto Garcia         if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3214312fe09cSAlberto Garcia             error_setg(errp, "Node '%s' is not a backing image of '%s'",
3215312fe09cSAlberto Garcia                        base_node, device);
3216312fe09cSAlberto Garcia             goto out;
3217312fe09cSAlberto Garcia         }
3218312fe09cSAlberto Garcia         assert(bdrv_get_aio_context(base_bs) == aio_context);
3219312fe09cSAlberto Garcia         base_name = base_bs->filename;
3220312fe09cSAlberto Garcia     }
3221312fe09cSAlberto Garcia 
3222554b6147SAlberto Garcia     /* Check for op blockers in the whole chain between bs and base */
3223554b6147SAlberto Garcia     for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3224554b6147SAlberto Garcia         if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3225554b6147SAlberto Garcia             goto out;
3226554b6147SAlberto Garcia         }
3227554b6147SAlberto Garcia     }
3228554b6147SAlberto Garcia 
322913d8cc51SJeff Cody     /* if we are streaming the entire chain, the result will have no backing
323013d8cc51SJeff Cody      * file, and specifying one is therefore an error */
323113d8cc51SJeff Cody     if (base_bs == NULL && has_backing_file) {
323213d8cc51SJeff Cody         error_setg(errp, "backing file specified, but streaming the "
323313d8cc51SJeff Cody                          "entire chain");
3234f3e69bebSStefan Hajnoczi         goto out;
323513d8cc51SJeff Cody     }
323613d8cc51SJeff Cody 
323713d8cc51SJeff Cody     /* backing_file string overrides base bs filename */
323813d8cc51SJeff Cody     base_name = has_backing_file ? backing_file : base_name;
323913d8cc51SJeff Cody 
3240241ca1abSJohn Snow     if (has_auto_finalize && !auto_finalize) {
3241241ca1abSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
3242241ca1abSJohn Snow     }
3243241ca1abSJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
3244241ca1abSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
3245241ca1abSJohn Snow     }
3246241ca1abSJohn Snow 
32472323322eSAlberto Garcia     stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3248cf6320dfSJohn Snow                  job_flags, has_speed ? speed : 0, on_error, &local_err);
324984d18f06SMarkus Armbruster     if (local_err) {
3250fd7f8c65SStefan Hajnoczi         error_propagate(errp, local_err);
3251f3e69bebSStefan Hajnoczi         goto out;
325212bd451fSStefan Hajnoczi     }
325312bd451fSStefan Hajnoczi 
325412bd451fSStefan Hajnoczi     trace_qmp_block_stream(bs, bs->job);
3255f3e69bebSStefan Hajnoczi 
3256f3e69bebSStefan Hajnoczi out:
3257f3e69bebSStefan Hajnoczi     aio_context_release(aio_context);
325812bd451fSStefan Hajnoczi }
32592d47c6e9SStefan Hajnoczi 
3260fd62c609SAlberto Garcia void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
32613c605f40SKevin Wolf                       bool has_base_node, const char *base_node,
32627676e2c5SJeff Cody                       bool has_base, const char *base,
32633c605f40SKevin Wolf                       bool has_top_node, const char *top_node,
32647676e2c5SJeff Cody                       bool has_top, const char *top,
326554e26900SJeff Cody                       bool has_backing_file, const char *backing_file,
3266ed61fc10SJeff Cody                       bool has_speed, int64_t speed,
32670db832f4SKevin Wolf                       bool has_filter_node_name, const char *filter_node_name,
326896fbf534SJohn Snow                       bool has_auto_finalize, bool auto_finalize,
326996fbf534SJohn Snow                       bool has_auto_dismiss, bool auto_dismiss,
3270ed61fc10SJeff Cody                       Error **errp)
3271ed61fc10SJeff Cody {
3272ed61fc10SJeff Cody     BlockDriverState *bs;
3273058223a6SAlberto Garcia     BlockDriverState *iter;
3274ed61fc10SJeff Cody     BlockDriverState *base_bs, *top_bs;
32759e85cd5cSStefan Hajnoczi     AioContext *aio_context;
3276ed61fc10SJeff Cody     Error *local_err = NULL;
3277ed61fc10SJeff Cody     /* This will be part of the QMP command, if/when the
3278ed61fc10SJeff Cody      * BlockdevOnError change for blkmirror makes it in
3279ed61fc10SJeff Cody      */
328092aa5c6dSPaolo Bonzini     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
32815360782dSJohn Snow     int job_flags = JOB_DEFAULT;
3282ed61fc10SJeff Cody 
328354504663SMax Reitz     if (!has_speed) {
328454504663SMax Reitz         speed = 0;
328554504663SMax Reitz     }
32860db832f4SKevin Wolf     if (!has_filter_node_name) {
32870db832f4SKevin Wolf         filter_node_name = NULL;
32880db832f4SKevin Wolf     }
328996fbf534SJohn Snow     if (has_auto_finalize && !auto_finalize) {
329096fbf534SJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
329196fbf534SJohn Snow     }
329296fbf534SJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
329396fbf534SJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
329496fbf534SJohn Snow     }
329554504663SMax Reitz 
32967676e2c5SJeff Cody     /* Important Note:
32977676e2c5SJeff Cody      *  libvirt relies on the DeviceNotFound error class in order to probe for
32987676e2c5SJeff Cody      *  live commit feature versions; for this to work, we must make sure to
32997676e2c5SJeff Cody      *  perform the device lookup before any generic errors that may occur in a
33007676e2c5SJeff Cody      *  scenario in which all optional arguments are omitted. */
33011d13b167SKevin Wolf     bs = qmp_get_root_bs(device, &local_err);
33021d13b167SKevin Wolf     if (!bs) {
33031d13b167SKevin Wolf         bs = bdrv_lookup_bs(device, device, NULL);
33041d13b167SKevin Wolf         if (!bs) {
33051d13b167SKevin Wolf             error_free(local_err);
330675158ebbSMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
330775158ebbSMarkus Armbruster                       "Device '%s' not found", device);
33081d13b167SKevin Wolf         } else {
33091d13b167SKevin Wolf             error_propagate(errp, local_err);
33101d13b167SKevin Wolf         }
3311ed61fc10SJeff Cody         return;
3312ed61fc10SJeff Cody     }
3313ed61fc10SJeff Cody 
33141d13b167SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
33159e85cd5cSStefan Hajnoczi     aio_context_acquire(aio_context);
33169e85cd5cSStefan Hajnoczi 
3317bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
33189e85cd5cSStefan Hajnoczi         goto out;
3319628ff683SFam Zheng     }
3320628ff683SFam Zheng 
3321ed61fc10SJeff Cody     /* default top_bs is the active layer */
3322ed61fc10SJeff Cody     top_bs = bs;
3323ed61fc10SJeff Cody 
33243c605f40SKevin Wolf     if (has_top_node && has_top) {
33253c605f40SKevin Wolf         error_setg(errp, "'top-node' and 'top' are mutually exclusive");
33263c605f40SKevin Wolf         goto out;
33273c605f40SKevin Wolf     } else if (has_top_node) {
33283c605f40SKevin Wolf         top_bs = bdrv_lookup_bs(NULL, top_node, errp);
33293c605f40SKevin Wolf         if (top_bs == NULL) {
33303c605f40SKevin Wolf             goto out;
33313c605f40SKevin Wolf         }
33323c605f40SKevin Wolf         if (!bdrv_chain_contains(bs, top_bs)) {
33333c605f40SKevin Wolf             error_setg(errp, "'%s' is not in this backing file chain",
33343c605f40SKevin Wolf                        top_node);
33353c605f40SKevin Wolf             goto out;
33363c605f40SKevin Wolf         }
33373c605f40SKevin Wolf     } else if (has_top && top) {
3338ed61fc10SJeff Cody         if (strcmp(bs->filename, top) != 0) {
3339ed61fc10SJeff Cody             top_bs = bdrv_find_backing_image(bs, top);
3340ed61fc10SJeff Cody         }
3341ed61fc10SJeff Cody     }
3342ed61fc10SJeff Cody 
3343ed61fc10SJeff Cody     if (top_bs == NULL) {
3344ed61fc10SJeff Cody         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
33459e85cd5cSStefan Hajnoczi         goto out;
3346ed61fc10SJeff Cody     }
3347ed61fc10SJeff Cody 
33489e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(top_bs) == aio_context);
33499e85cd5cSStefan Hajnoczi 
33503c605f40SKevin Wolf     if (has_base_node && has_base) {
33513c605f40SKevin Wolf         error_setg(errp, "'base-node' and 'base' are mutually exclusive");
33523c605f40SKevin Wolf         goto out;
33533c605f40SKevin Wolf     } else if (has_base_node) {
33543c605f40SKevin Wolf         base_bs = bdrv_lookup_bs(NULL, base_node, errp);
33553c605f40SKevin Wolf         if (base_bs == NULL) {
33563c605f40SKevin Wolf             goto out;
33573c605f40SKevin Wolf         }
33583c605f40SKevin Wolf         if (!bdrv_chain_contains(top_bs, base_bs)) {
33593c605f40SKevin Wolf             error_setg(errp, "'%s' is not in this backing file chain",
33603c605f40SKevin Wolf                        base_node);
33613c605f40SKevin Wolf             goto out;
33623c605f40SKevin Wolf         }
33633c605f40SKevin Wolf     } else if (has_base && base) {
3364d5208c45SJeff Cody         base_bs = bdrv_find_backing_image(top_bs, base);
3365d5208c45SJeff Cody     } else {
3366d5208c45SJeff Cody         base_bs = bdrv_find_base(top_bs);
3367d5208c45SJeff Cody     }
3368d5208c45SJeff Cody 
3369d5208c45SJeff Cody     if (base_bs == NULL) {
3370c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
33719e85cd5cSStefan Hajnoczi         goto out;
3372d5208c45SJeff Cody     }
3373d5208c45SJeff Cody 
33749e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(base_bs) == aio_context);
33759e85cd5cSStefan Hajnoczi 
3376058223a6SAlberto Garcia     for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3377058223a6SAlberto Garcia         if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3378bb00021dSFam Zheng             goto out;
3379bb00021dSFam Zheng         }
3380058223a6SAlberto Garcia     }
3381bb00021dSFam Zheng 
33827676e2c5SJeff Cody     /* Do not allow attempts to commit an image into itself */
33837676e2c5SJeff Cody     if (top_bs == base_bs) {
33847676e2c5SJeff Cody         error_setg(errp, "cannot commit an image into itself");
33859e85cd5cSStefan Hajnoczi         goto out;
33867676e2c5SJeff Cody     }
33877676e2c5SJeff Cody 
338820a63d2cSFam Zheng     if (top_bs == bs) {
338954e26900SJeff Cody         if (has_backing_file) {
339054e26900SJeff Cody             error_setg(errp, "'backing-file' specified,"
339154e26900SJeff Cody                              " but 'top' is the active layer");
33929e85cd5cSStefan Hajnoczi             goto out;
339354e26900SJeff Cody         }
339447970dfbSJohn Snow         commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
33955360782dSJohn Snow                             job_flags, speed, on_error,
339678bbd910SFam Zheng                             filter_node_name, NULL, NULL, false, &local_err);
339720a63d2cSFam Zheng     } else {
3398058223a6SAlberto Garcia         BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3399058223a6SAlberto Garcia         if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3400058223a6SAlberto Garcia             goto out;
3401058223a6SAlberto Garcia         }
34025360782dSJohn Snow         commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, job_flags,
34035360782dSJohn Snow                      speed, on_error, has_backing_file ? backing_file : NULL,
34040db832f4SKevin Wolf                      filter_node_name, &local_err);
340520a63d2cSFam Zheng     }
3406ed61fc10SJeff Cody     if (local_err != NULL) {
3407ed61fc10SJeff Cody         error_propagate(errp, local_err);
34089e85cd5cSStefan Hajnoczi         goto out;
3409ed61fc10SJeff Cody     }
34109e85cd5cSStefan Hajnoczi 
34119e85cd5cSStefan Hajnoczi out:
34129e85cd5cSStefan Hajnoczi     aio_context_release(aio_context);
3413ed61fc10SJeff Cody }
3414ed61fc10SJeff Cody 
341562c9e416SKevin Wolf static BlockJob *do_drive_backup(DriveBackup *backup, JobTxn *txn,
3416111049a4SJohn Snow                                  Error **errp)
341799a9addfSStefan Hajnoczi {
341899a9addfSStefan Hajnoczi     BlockDriverState *bs;
341999a9addfSStefan Hajnoczi     BlockDriverState *target_bs;
3420fc5d3f84SIan Main     BlockDriverState *source = NULL;
3421111049a4SJohn Snow     BlockJob *job = NULL;
3422d58d8453SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
3423761731b1SStefan Hajnoczi     AioContext *aio_context;
3424e6641719SMax Reitz     QDict *options = NULL;
342599a9addfSStefan Hajnoczi     Error *local_err = NULL;
3426bb02b65cSKevin Wolf     int flags, job_flags = JOB_DEFAULT;
342799a9addfSStefan Hajnoczi     int64_t size;
3428fc0932fdSFam Zheng     bool set_backing_hd = false;
342999a9addfSStefan Hajnoczi 
343081206a89SPavel Butsykin     if (!backup->has_speed) {
343181206a89SPavel Butsykin         backup->speed = 0;
343299a9addfSStefan Hajnoczi     }
343381206a89SPavel Butsykin     if (!backup->has_on_source_error) {
343481206a89SPavel Butsykin         backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
343599a9addfSStefan Hajnoczi     }
343681206a89SPavel Butsykin     if (!backup->has_on_target_error) {
343781206a89SPavel Butsykin         backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
343899a9addfSStefan Hajnoczi     }
343981206a89SPavel Butsykin     if (!backup->has_mode) {
344081206a89SPavel Butsykin         backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
344181206a89SPavel Butsykin     }
344281206a89SPavel Butsykin     if (!backup->has_job_id) {
344381206a89SPavel Butsykin         backup->job_id = NULL;
344499a9addfSStefan Hajnoczi     }
3445b40dacdcSJohn Snow     if (!backup->has_auto_finalize) {
3446b40dacdcSJohn Snow         backup->auto_finalize = true;
3447b40dacdcSJohn Snow     }
3448b40dacdcSJohn Snow     if (!backup->has_auto_dismiss) {
3449b40dacdcSJohn Snow         backup->auto_dismiss = true;
3450b40dacdcSJohn Snow     }
345113b9414bSPavel Butsykin     if (!backup->has_compress) {
345213b9414bSPavel Butsykin         backup->compress = false;
345313b9414bSPavel Butsykin     }
345499a9addfSStefan Hajnoczi 
345581206a89SPavel Butsykin     bs = qmp_get_root_bs(backup->device, errp);
3456b7e4fa22SKevin Wolf     if (!bs) {
3457111049a4SJohn Snow         return NULL;
345899a9addfSStefan Hajnoczi     }
345999a9addfSStefan Hajnoczi 
3460b7e4fa22SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3461761731b1SStefan Hajnoczi     aio_context_acquire(aio_context);
3462761731b1SStefan Hajnoczi 
346381206a89SPavel Butsykin     if (!backup->has_format) {
346481206a89SPavel Butsykin         backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
346581206a89SPavel Butsykin                          NULL : (char*) bs->drv->format_name;
346699a9addfSStefan Hajnoczi     }
346799a9addfSStefan Hajnoczi 
3468c29c1dd3SFam Zheng     /* Early check to avoid creating target */
34693718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3470761731b1SStefan Hajnoczi         goto out;
347199a9addfSStefan Hajnoczi     }
347299a9addfSStefan Hajnoczi 
347361de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
347499a9addfSStefan Hajnoczi 
3475fc5d3f84SIan Main     /* See if we have a backing HD we can use to create our new image
3476fc5d3f84SIan Main      * on top of. */
347781206a89SPavel Butsykin     if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3478760e0063SKevin Wolf         source = backing_bs(bs);
3479fc5d3f84SIan Main         if (!source) {
348081206a89SPavel Butsykin             backup->sync = MIRROR_SYNC_MODE_FULL;
3481fc5d3f84SIan Main         }
3482fc5d3f84SIan Main     }
348381206a89SPavel Butsykin     if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3484fc5d3f84SIan Main         source = bs;
3485fc0932fdSFam Zheng         flags |= BDRV_O_NO_BACKING;
3486fc0932fdSFam Zheng         set_backing_hd = true;
3487fc5d3f84SIan Main     }
3488fc5d3f84SIan Main 
348999a9addfSStefan Hajnoczi     size = bdrv_getlength(bs);
349099a9addfSStefan Hajnoczi     if (size < 0) {
349199a9addfSStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
3492761731b1SStefan Hajnoczi         goto out;
349399a9addfSStefan Hajnoczi     }
349499a9addfSStefan Hajnoczi 
349581206a89SPavel Butsykin     if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
349681206a89SPavel Butsykin         assert(backup->format);
3497fc5d3f84SIan Main         if (source) {
349881206a89SPavel Butsykin             bdrv_img_create(backup->target, backup->format, source->filename,
3499fc5d3f84SIan Main                             source->drv->format_name, NULL,
35009217283dSFam Zheng                             size, flags, false, &local_err);
3501fc5d3f84SIan Main         } else {
350281206a89SPavel Butsykin             bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
35039217283dSFam Zheng                             size, flags, false, &local_err);
3504fc5d3f84SIan Main         }
350599a9addfSStefan Hajnoczi     }
350699a9addfSStefan Hajnoczi 
350784d18f06SMarkus Armbruster     if (local_err) {
350899a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3509761731b1SStefan Hajnoczi         goto out;
351099a9addfSStefan Hajnoczi     }
351199a9addfSStefan Hajnoczi 
351281206a89SPavel Butsykin     if (backup->format) {
3513fc0932fdSFam Zheng         if (!options) {
3514e6641719SMax Reitz             options = qdict_new();
3515fc0932fdSFam Zheng         }
351646f5ac20SEric Blake         qdict_put_str(options, "driver", backup->format);
3517e6641719SMax Reitz     }
3518e6641719SMax Reitz 
351981206a89SPavel Butsykin     target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
35205b363937SMax Reitz     if (!target_bs) {
3521761731b1SStefan Hajnoczi         goto out;
352299a9addfSStefan Hajnoczi     }
352399a9addfSStefan Hajnoczi 
3524761731b1SStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
3525761731b1SStefan Hajnoczi 
3526fc0932fdSFam Zheng     if (set_backing_hd) {
3527fc0932fdSFam Zheng         bdrv_set_backing_hd(target_bs, source, &local_err);
3528fc0932fdSFam Zheng         if (local_err) {
3529fc0932fdSFam Zheng             bdrv_unref(target_bs);
3530fc0932fdSFam Zheng             goto out;
3531fc0932fdSFam Zheng         }
3532fc0932fdSFam Zheng     }
3533fc0932fdSFam Zheng 
353481206a89SPavel Butsykin     if (backup->has_bitmap) {
353581206a89SPavel Butsykin         bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3536d58d8453SJohn Snow         if (!bmap) {
353781206a89SPavel Butsykin             error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
35380702d3d8SMax Reitz             bdrv_unref(target_bs);
3539d58d8453SJohn Snow             goto out;
3540d58d8453SJohn Snow         }
3541b27a6b8bSJohn Snow         if (bdrv_dirty_bitmap_user_locked(bmap)) {
35424f43e953SVladimir Sementsov-Ogievskiy             error_setg(errp,
3543b27a6b8bSJohn Snow                        "Bitmap '%s' is currently in use by another operation"
3544b27a6b8bSJohn Snow                        " and cannot be used for backup", backup->bitmap);
35454f43e953SVladimir Sementsov-Ogievskiy             goto out;
35464f43e953SVladimir Sementsov-Ogievskiy         }
3547d58d8453SJohn Snow     }
3548b40dacdcSJohn Snow     if (!backup->auto_finalize) {
3549bb02b65cSKevin Wolf         job_flags |= JOB_MANUAL_FINALIZE;
3550b40dacdcSJohn Snow     }
3551b40dacdcSJohn Snow     if (!backup->auto_dismiss) {
3552bb02b65cSKevin Wolf         job_flags |= JOB_MANUAL_DISMISS;
3553b40dacdcSJohn Snow     }
3554d58d8453SJohn Snow 
3555111049a4SJohn Snow     job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3556111049a4SJohn Snow                             backup->sync, bmap, backup->compress,
3557111049a4SJohn Snow                             backup->on_source_error, backup->on_target_error,
3558b40dacdcSJohn Snow                             job_flags, NULL, NULL, txn, &local_err);
35594f6fd349SFam Zheng     bdrv_unref(target_bs);
35605c438bc6SKevin Wolf     if (local_err != NULL) {
356199a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3562761731b1SStefan Hajnoczi         goto out;
356399a9addfSStefan Hajnoczi     }
3564761731b1SStefan Hajnoczi 
3565761731b1SStefan Hajnoczi out:
3566761731b1SStefan Hajnoczi     aio_context_release(aio_context);
3567111049a4SJohn Snow     return job;
356899a9addfSStefan Hajnoczi }
356999a9addfSStefan Hajnoczi 
357081206a89SPavel Butsykin void qmp_drive_backup(DriveBackup *arg, Error **errp)
357178f51fdeSJohn Snow {
3572111049a4SJohn Snow 
3573111049a4SJohn Snow     BlockJob *job;
3574111049a4SJohn Snow     job = do_drive_backup(arg, NULL, errp);
3575111049a4SJohn Snow     if (job) {
3576da01ff7fSKevin Wolf         job_start(&job->job);
3577111049a4SJohn Snow     }
357878f51fdeSJohn Snow }
357978f51fdeSJohn Snow 
3580c13163fbSBenoît Canet BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3581c13163fbSBenoît Canet {
3582d5a8ee60SAlberto Garcia     return bdrv_named_nodes_list(errp);
3583c13163fbSBenoît Canet }
3584c13163fbSBenoît Canet 
3585*5d3b4e99SVladimir Sementsov-Ogievskiy XDbgBlockGraph *qmp_x_debug_query_block_graph(Error **errp)
3586*5d3b4e99SVladimir Sementsov-Ogievskiy {
3587*5d3b4e99SVladimir Sementsov-Ogievskiy     return bdrv_get_xdbg_block_graph(errp);
3588*5d3b4e99SVladimir Sementsov-Ogievskiy }
3589*5d3b4e99SVladimir Sementsov-Ogievskiy 
359062c9e416SKevin Wolf BlockJob *do_blockdev_backup(BlockdevBackup *backup, JobTxn *txn,
3591111049a4SJohn Snow                              Error **errp)
3592c29c1dd3SFam Zheng {
3593c29c1dd3SFam Zheng     BlockDriverState *bs;
3594c29c1dd3SFam Zheng     BlockDriverState *target_bs;
3595c29c1dd3SFam Zheng     Error *local_err = NULL;
3596945c1ee0SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
3597c29c1dd3SFam Zheng     AioContext *aio_context;
3598111049a4SJohn Snow     BlockJob *job = NULL;
3599bb02b65cSKevin Wolf     int job_flags = JOB_DEFAULT;
3600c29c1dd3SFam Zheng 
3601dc7a4a9eSPavel Butsykin     if (!backup->has_speed) {
3602dc7a4a9eSPavel Butsykin         backup->speed = 0;
3603c29c1dd3SFam Zheng     }
3604dc7a4a9eSPavel Butsykin     if (!backup->has_on_source_error) {
3605dc7a4a9eSPavel Butsykin         backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3606c29c1dd3SFam Zheng     }
3607dc7a4a9eSPavel Butsykin     if (!backup->has_on_target_error) {
3608dc7a4a9eSPavel Butsykin         backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3609dc7a4a9eSPavel Butsykin     }
3610dc7a4a9eSPavel Butsykin     if (!backup->has_job_id) {
3611dc7a4a9eSPavel Butsykin         backup->job_id = NULL;
3612c29c1dd3SFam Zheng     }
3613b40dacdcSJohn Snow     if (!backup->has_auto_finalize) {
3614b40dacdcSJohn Snow         backup->auto_finalize = true;
3615b40dacdcSJohn Snow     }
3616b40dacdcSJohn Snow     if (!backup->has_auto_dismiss) {
3617b40dacdcSJohn Snow         backup->auto_dismiss = true;
3618b40dacdcSJohn Snow     }
36193b7b1236SPavel Butsykin     if (!backup->has_compress) {
36203b7b1236SPavel Butsykin         backup->compress = false;
36213b7b1236SPavel Butsykin     }
3622c29c1dd3SFam Zheng 
3623930fe17fSVladimir Sementsov-Ogievskiy     bs = bdrv_lookup_bs(backup->device, backup->device, errp);
3624cef34eebSKevin Wolf     if (!bs) {
3625111049a4SJohn Snow         return NULL;
3626c29c1dd3SFam Zheng     }
3627c29c1dd3SFam Zheng 
3628cef34eebSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3629c29c1dd3SFam Zheng     aio_context_acquire(aio_context);
3630c29c1dd3SFam Zheng 
3631dc7a4a9eSPavel Butsykin     target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
36320d978913SFam Zheng     if (!target_bs) {
3633c29c1dd3SFam Zheng         goto out;
3634c29c1dd3SFam Zheng     }
36355433c24fSMax Reitz 
3636efd75567SFam Zheng     if (bdrv_get_aio_context(target_bs) != aio_context) {
3637efd75567SFam Zheng         if (!bdrv_has_blk(target_bs)) {
3638efd75567SFam Zheng             /* The target BDS is not attached, we can safely move it to another
3639efd75567SFam Zheng              * AioContext. */
3640c29c1dd3SFam Zheng             bdrv_set_aio_context(target_bs, aio_context);
3641efd75567SFam Zheng         } else {
3642efd75567SFam Zheng             error_setg(errp, "Target is attached to a different thread from "
3643efd75567SFam Zheng                              "source.");
3644efd75567SFam Zheng             goto out;
3645efd75567SFam Zheng         }
3646efd75567SFam Zheng     }
3647945c1ee0SJohn Snow 
3648945c1ee0SJohn Snow     if (backup->has_bitmap) {
3649945c1ee0SJohn Snow         bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3650945c1ee0SJohn Snow         if (!bmap) {
3651945c1ee0SJohn Snow             error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3652945c1ee0SJohn Snow             goto out;
3653945c1ee0SJohn Snow         }
3654b27a6b8bSJohn Snow         if (bdrv_dirty_bitmap_user_locked(bmap)) {
3655945c1ee0SJohn Snow             error_setg(errp,
3656b27a6b8bSJohn Snow                        "Bitmap '%s' is currently in use by another operation"
3657b27a6b8bSJohn Snow                        " and cannot be used for backup", backup->bitmap);
3658945c1ee0SJohn Snow             goto out;
3659945c1ee0SJohn Snow         }
3660945c1ee0SJohn Snow     }
3661945c1ee0SJohn Snow 
3662b40dacdcSJohn Snow     if (!backup->auto_finalize) {
3663bb02b65cSKevin Wolf         job_flags |= JOB_MANUAL_FINALIZE;
3664b40dacdcSJohn Snow     }
3665b40dacdcSJohn Snow     if (!backup->auto_dismiss) {
3666bb02b65cSKevin Wolf         job_flags |= JOB_MANUAL_DISMISS;
3667b40dacdcSJohn Snow     }
3668111049a4SJohn Snow     job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3669945c1ee0SJohn Snow                             backup->sync, bmap, backup->compress,
3670111049a4SJohn Snow                             backup->on_source_error, backup->on_target_error,
3671b40dacdcSJohn Snow                             job_flags, NULL, NULL, txn, &local_err);
3672c29c1dd3SFam Zheng     if (local_err != NULL) {
3673c29c1dd3SFam Zheng         error_propagate(errp, local_err);
3674c29c1dd3SFam Zheng     }
3675c29c1dd3SFam Zheng out:
3676c29c1dd3SFam Zheng     aio_context_release(aio_context);
3677111049a4SJohn Snow     return job;
3678c29c1dd3SFam Zheng }
3679c29c1dd3SFam Zheng 
3680dc7a4a9eSPavel Butsykin void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
368178f51fdeSJohn Snow {
3682111049a4SJohn Snow     BlockJob *job;
3683111049a4SJohn Snow     job = do_blockdev_backup(arg, NULL, errp);
3684111049a4SJohn Snow     if (job) {
3685da01ff7fSKevin Wolf         job_start(&job->job);
3686111049a4SJohn Snow     }
368778f51fdeSJohn Snow }
368878f51fdeSJohn Snow 
36894193cdd7SFam Zheng /* Parameter check and block job starting for drive mirroring.
36904193cdd7SFam Zheng  * Caller should hold @device and @target's aio context (must be the same).
36914193cdd7SFam Zheng  **/
369271aa9867SAlberto Garcia static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
36934193cdd7SFam Zheng                                    BlockDriverState *target,
369409158f00SBenoît Canet                                    bool has_replaces, const char *replaces,
3695d9b902dbSPaolo Bonzini                                    enum MirrorSyncMode sync,
3696274fcceeSMax Reitz                                    BlockMirrorBackingMode backing_mode,
3697b952b558SPaolo Bonzini                                    bool has_speed, int64_t speed,
3698eee13dfeSPaolo Bonzini                                    bool has_granularity, uint32_t granularity,
369908e4ed6cSPaolo Bonzini                                    bool has_buf_size, int64_t buf_size,
37004193cdd7SFam Zheng                                    bool has_on_source_error,
37014193cdd7SFam Zheng                                    BlockdevOnError on_source_error,
37024193cdd7SFam Zheng                                    bool has_on_target_error,
37034193cdd7SFam Zheng                                    BlockdevOnError on_target_error,
37040fc9f8eaSFam Zheng                                    bool has_unmap, bool unmap,
37056cdbceb1SKevin Wolf                                    bool has_filter_node_name,
37066cdbceb1SKevin Wolf                                    const char *filter_node_name,
3707481debaaSMax Reitz                                    bool has_copy_mode, MirrorCopyMode copy_mode,
3708a6b58adeSJohn Snow                                    bool has_auto_finalize, bool auto_finalize,
3709a6b58adeSJohn Snow                                    bool has_auto_dismiss, bool auto_dismiss,
3710b952b558SPaolo Bonzini                                    Error **errp)
3711d9b902dbSPaolo Bonzini {
3712a1999b33SJohn Snow     int job_flags = JOB_DEFAULT;
3713d9b902dbSPaolo Bonzini 
3714d9b902dbSPaolo Bonzini     if (!has_speed) {
3715d9b902dbSPaolo Bonzini         speed = 0;
3716d9b902dbSPaolo Bonzini     }
3717b952b558SPaolo Bonzini     if (!has_on_source_error) {
3718b952b558SPaolo Bonzini         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3719b952b558SPaolo Bonzini     }
3720b952b558SPaolo Bonzini     if (!has_on_target_error) {
3721b952b558SPaolo Bonzini         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3722b952b558SPaolo Bonzini     }
3723eee13dfeSPaolo Bonzini     if (!has_granularity) {
3724eee13dfeSPaolo Bonzini         granularity = 0;
3725eee13dfeSPaolo Bonzini     }
372608e4ed6cSPaolo Bonzini     if (!has_buf_size) {
372748ac0a4dSWen Congyang         buf_size = 0;
372808e4ed6cSPaolo Bonzini     }
37290fc9f8eaSFam Zheng     if (!has_unmap) {
37300fc9f8eaSFam Zheng         unmap = true;
37310fc9f8eaSFam Zheng     }
37326cdbceb1SKevin Wolf     if (!has_filter_node_name) {
37336cdbceb1SKevin Wolf         filter_node_name = NULL;
37346cdbceb1SKevin Wolf     }
3735481debaaSMax Reitz     if (!has_copy_mode) {
3736481debaaSMax Reitz         copy_mode = MIRROR_COPY_MODE_BACKGROUND;
3737481debaaSMax Reitz     }
3738a6b58adeSJohn Snow     if (has_auto_finalize && !auto_finalize) {
3739a6b58adeSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
3740a6b58adeSJohn Snow     }
3741a6b58adeSJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
3742a6b58adeSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
3743a6b58adeSJohn Snow     }
374408e4ed6cSPaolo Bonzini 
3745eee13dfeSPaolo Bonzini     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3746c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
37473cbbe9fdSStefan Hajnoczi                    "a value in range [512B, 64MB]");
3748eee13dfeSPaolo Bonzini         return;
3749eee13dfeSPaolo Bonzini     }
3750eee13dfeSPaolo Bonzini     if (granularity & (granularity - 1)) {
3751c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3752c6bd8c70SMarkus Armbruster                    "power of 2");
3753eee13dfeSPaolo Bonzini         return;
3754eee13dfeSPaolo Bonzini     }
3755d9b902dbSPaolo Bonzini 
37564193cdd7SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
37574193cdd7SFam Zheng         return;
37584193cdd7SFam Zheng     }
3759e40e5027SFam Zheng     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3760e40e5027SFam Zheng         return;
3761e40e5027SFam Zheng     }
37624193cdd7SFam Zheng 
37634193cdd7SFam Zheng     if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
37644193cdd7SFam Zheng         sync = MIRROR_SYNC_MODE_FULL;
37654193cdd7SFam Zheng     }
37664193cdd7SFam Zheng 
37674193cdd7SFam Zheng     /* pass the node name to replace to mirror start since it's loose coupling
37684193cdd7SFam Zheng      * and will allow to check whether the node still exist at mirror completion
37694193cdd7SFam Zheng      */
377071aa9867SAlberto Garcia     mirror_start(job_id, bs, target,
3771a1999b33SJohn Snow                  has_replaces ? replaces : NULL, job_flags,
3772274fcceeSMax Reitz                  speed, granularity, buf_size, sync, backing_mode,
37736cdbceb1SKevin Wolf                  on_source_error, on_target_error, unmap, filter_node_name,
3774481debaaSMax Reitz                  copy_mode, errp);
37754193cdd7SFam Zheng }
37764193cdd7SFam Zheng 
3777faecd40aSEric Blake void qmp_drive_mirror(DriveMirror *arg, Error **errp)
37784193cdd7SFam Zheng {
37794193cdd7SFam Zheng     BlockDriverState *bs;
37804193cdd7SFam Zheng     BlockDriverState *source, *target_bs;
37814193cdd7SFam Zheng     AioContext *aio_context;
3782274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode;
37834193cdd7SFam Zheng     Error *local_err = NULL;
37844193cdd7SFam Zheng     QDict *options = NULL;
37854193cdd7SFam Zheng     int flags;
37864193cdd7SFam Zheng     int64_t size;
3787faecd40aSEric Blake     const char *format = arg->format;
37884193cdd7SFam Zheng 
37890524e93aSKevin Wolf     bs = qmp_get_root_bs(arg->device, errp);
37900524e93aSKevin Wolf     if (!bs) {
3791d9b902dbSPaolo Bonzini         return;
3792d9b902dbSPaolo Bonzini     }
3793d9b902dbSPaolo Bonzini 
3794cb2af917SPaolo Bonzini     /* Early check to avoid creating target */
3795cb2af917SPaolo Bonzini     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3796cb2af917SPaolo Bonzini         return;
3797cb2af917SPaolo Bonzini     }
3798cb2af917SPaolo Bonzini 
37990524e93aSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
38005a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
38015a7e7a0bSStefan Hajnoczi 
3802faecd40aSEric Blake     if (!arg->has_mode) {
3803faecd40aSEric Blake         arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
38044193cdd7SFam Zheng     }
3805d9b902dbSPaolo Bonzini 
3806faecd40aSEric Blake     if (!arg->has_format) {
3807faecd40aSEric Blake         format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3808faecd40aSEric Blake                   ? NULL : bs->drv->format_name);
3809d9b902dbSPaolo Bonzini     }
3810d9b902dbSPaolo Bonzini 
381161de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
3812760e0063SKevin Wolf     source = backing_bs(bs);
3813faecd40aSEric Blake     if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3814faecd40aSEric Blake         arg->sync = MIRROR_SYNC_MODE_FULL;
3815d9b902dbSPaolo Bonzini     }
3816faecd40aSEric Blake     if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3817117e0c82SMax Reitz         source = bs;
3818117e0c82SMax Reitz     }
3819d9b902dbSPaolo Bonzini 
3820ac3c5d83SStefan Hajnoczi     size = bdrv_getlength(bs);
3821ac3c5d83SStefan Hajnoczi     if (size < 0) {
3822ac3c5d83SStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
38235a7e7a0bSStefan Hajnoczi         goto out;
3824ac3c5d83SStefan Hajnoczi     }
3825ac3c5d83SStefan Hajnoczi 
3826faecd40aSEric Blake     if (arg->has_replaces) {
382709158f00SBenoît Canet         BlockDriverState *to_replace_bs;
38285a7e7a0bSStefan Hajnoczi         AioContext *replace_aio_context;
38295a7e7a0bSStefan Hajnoczi         int64_t replace_size;
383009158f00SBenoît Canet 
3831faecd40aSEric Blake         if (!arg->has_node_name) {
383209158f00SBenoît Canet             error_setg(errp, "a node-name must be provided when replacing a"
383309158f00SBenoît Canet                              " named node of the graph");
38345a7e7a0bSStefan Hajnoczi             goto out;
383509158f00SBenoît Canet         }
383609158f00SBenoît Canet 
3837faecd40aSEric Blake         to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
383809158f00SBenoît Canet 
383909158f00SBenoît Canet         if (!to_replace_bs) {
384009158f00SBenoît Canet             error_propagate(errp, local_err);
38415a7e7a0bSStefan Hajnoczi             goto out;
384209158f00SBenoît Canet         }
384309158f00SBenoît Canet 
38445a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
38455a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
38465a7e7a0bSStefan Hajnoczi         replace_size = bdrv_getlength(to_replace_bs);
38475a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
38485a7e7a0bSStefan Hajnoczi 
38495a7e7a0bSStefan Hajnoczi         if (size != replace_size) {
385009158f00SBenoît Canet             error_setg(errp, "cannot replace image with a mirror image of "
385109158f00SBenoît Canet                              "different size");
38525a7e7a0bSStefan Hajnoczi             goto out;
385309158f00SBenoît Canet         }
385409158f00SBenoît Canet     }
385509158f00SBenoît Canet 
3856faecd40aSEric Blake     if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3857274fcceeSMax Reitz         backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3858274fcceeSMax Reitz     } else {
3859274fcceeSMax Reitz         backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3860274fcceeSMax Reitz     }
3861274fcceeSMax Reitz 
38622a32c6e8SJohn Snow     /* Don't open backing image in create() */
38632a32c6e8SJohn Snow     flags |= BDRV_O_NO_BACKING;
38642a32c6e8SJohn Snow 
3865faecd40aSEric Blake     if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3866faecd40aSEric Blake         && arg->mode != NEW_IMAGE_MODE_EXISTING)
386714526864SMax Reitz     {
3868d9b902dbSPaolo Bonzini         /* create new image w/o backing file */
3869e6641719SMax Reitz         assert(format);
3870faecd40aSEric Blake         bdrv_img_create(arg->target, format,
38719217283dSFam Zheng                         NULL, NULL, NULL, size, flags, false, &local_err);
3872d9b902dbSPaolo Bonzini     } else {
3873faecd40aSEric Blake         switch (arg->mode) {
3874d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_EXISTING:
3875d9b902dbSPaolo Bonzini             break;
3876d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3877d9b902dbSPaolo Bonzini             /* create new image with backing file */
3878faecd40aSEric Blake             bdrv_img_create(arg->target, format,
3879d9b902dbSPaolo Bonzini                             source->filename,
3880d9b902dbSPaolo Bonzini                             source->drv->format_name,
38819217283dSFam Zheng                             NULL, size, flags, false, &local_err);
3882d9b902dbSPaolo Bonzini             break;
3883d9b902dbSPaolo Bonzini         default:
3884d9b902dbSPaolo Bonzini             abort();
3885d9b902dbSPaolo Bonzini         }
3886d9b902dbSPaolo Bonzini     }
3887d9b902dbSPaolo Bonzini 
388884d18f06SMarkus Armbruster     if (local_err) {
3889cf8f2426SLuiz Capitulino         error_propagate(errp, local_err);
38905a7e7a0bSStefan Hajnoczi         goto out;
3891d9b902dbSPaolo Bonzini     }
3892d9b902dbSPaolo Bonzini 
38934c828dc6SBenoît Canet     options = qdict_new();
3894faecd40aSEric Blake     if (arg->has_node_name) {
389546f5ac20SEric Blake         qdict_put_str(options, "node-name", arg->node_name);
38964c828dc6SBenoît Canet     }
3897e6641719SMax Reitz     if (format) {
389846f5ac20SEric Blake         qdict_put_str(options, "driver", format);
3899e6641719SMax Reitz     }
39004c828dc6SBenoît Canet 
3901b812f671SPaolo Bonzini     /* Mirroring takes care of copy-on-write using the source's backing
3902b812f671SPaolo Bonzini      * file.
3903b812f671SPaolo Bonzini      */
39042a32c6e8SJohn Snow     target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
39055b363937SMax Reitz     if (!target_bs) {
39065a7e7a0bSStefan Hajnoczi         goto out;
3907d9b902dbSPaolo Bonzini     }
3908d9b902dbSPaolo Bonzini 
39095a7e7a0bSStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
39105a7e7a0bSStefan Hajnoczi 
3911faecd40aSEric Blake     blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3912faecd40aSEric Blake                            arg->has_replaces, arg->replaces, arg->sync,
3913faecd40aSEric Blake                            backing_mode, arg->has_speed, arg->speed,
3914faecd40aSEric Blake                            arg->has_granularity, arg->granularity,
3915faecd40aSEric Blake                            arg->has_buf_size, arg->buf_size,
3916faecd40aSEric Blake                            arg->has_on_source_error, arg->on_source_error,
3917faecd40aSEric Blake                            arg->has_on_target_error, arg->on_target_error,
3918faecd40aSEric Blake                            arg->has_unmap, arg->unmap,
39196cdbceb1SKevin Wolf                            false, NULL,
3920481debaaSMax Reitz                            arg->has_copy_mode, arg->copy_mode,
3921a6b58adeSJohn Snow                            arg->has_auto_finalize, arg->auto_finalize,
3922a6b58adeSJohn Snow                            arg->has_auto_dismiss, arg->auto_dismiss,
39234193cdd7SFam Zheng                            &local_err);
3924e253f4b8SKevin Wolf     bdrv_unref(target_bs);
3925d9b902dbSPaolo Bonzini     error_propagate(errp, local_err);
39265a7e7a0bSStefan Hajnoczi out:
39275a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
3928d9b902dbSPaolo Bonzini }
3929d9b902dbSPaolo Bonzini 
393071aa9867SAlberto Garcia void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
393171aa9867SAlberto Garcia                          const char *device, const char *target,
3932df92562eSFam Zheng                          bool has_replaces, const char *replaces,
3933df92562eSFam Zheng                          MirrorSyncMode sync,
3934df92562eSFam Zheng                          bool has_speed, int64_t speed,
3935df92562eSFam Zheng                          bool has_granularity, uint32_t granularity,
3936df92562eSFam Zheng                          bool has_buf_size, int64_t buf_size,
3937df92562eSFam Zheng                          bool has_on_source_error,
3938df92562eSFam Zheng                          BlockdevOnError on_source_error,
3939df92562eSFam Zheng                          bool has_on_target_error,
3940df92562eSFam Zheng                          BlockdevOnError on_target_error,
39416cdbceb1SKevin Wolf                          bool has_filter_node_name,
39426cdbceb1SKevin Wolf                          const char *filter_node_name,
3943481debaaSMax Reitz                          bool has_copy_mode, MirrorCopyMode copy_mode,
3944a6b58adeSJohn Snow                          bool has_auto_finalize, bool auto_finalize,
3945a6b58adeSJohn Snow                          bool has_auto_dismiss, bool auto_dismiss,
3946df92562eSFam Zheng                          Error **errp)
3947df92562eSFam Zheng {
3948df92562eSFam Zheng     BlockDriverState *bs;
3949df92562eSFam Zheng     BlockDriverState *target_bs;
3950df92562eSFam Zheng     AioContext *aio_context;
3951274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3952df92562eSFam Zheng     Error *local_err = NULL;
3953df92562eSFam Zheng 
395407eec652SKevin Wolf     bs = qmp_get_root_bs(device, errp);
3955df92562eSFam Zheng     if (!bs) {
3956df92562eSFam Zheng         return;
3957df92562eSFam Zheng     }
3958df92562eSFam Zheng 
3959df92562eSFam Zheng     target_bs = bdrv_lookup_bs(target, target, errp);
3960df92562eSFam Zheng     if (!target_bs) {
3961df92562eSFam Zheng         return;
3962df92562eSFam Zheng     }
3963df92562eSFam Zheng 
3964df92562eSFam Zheng     aio_context = bdrv_get_aio_context(bs);
3965df92562eSFam Zheng     aio_context_acquire(aio_context);
3966df92562eSFam Zheng 
3967df92562eSFam Zheng     bdrv_set_aio_context(target_bs, aio_context);
3968df92562eSFam Zheng 
396971aa9867SAlberto Garcia     blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3970274fcceeSMax Reitz                            has_replaces, replaces, sync, backing_mode,
3971df92562eSFam Zheng                            has_speed, speed,
3972df92562eSFam Zheng                            has_granularity, granularity,
3973df92562eSFam Zheng                            has_buf_size, buf_size,
3974df92562eSFam Zheng                            has_on_source_error, on_source_error,
3975df92562eSFam Zheng                            has_on_target_error, on_target_error,
3976df92562eSFam Zheng                            true, true,
39776cdbceb1SKevin Wolf                            has_filter_node_name, filter_node_name,
3978481debaaSMax Reitz                            has_copy_mode, copy_mode,
3979a6b58adeSJohn Snow                            has_auto_finalize, auto_finalize,
3980a6b58adeSJohn Snow                            has_auto_dismiss, auto_dismiss,
3981df92562eSFam Zheng                            &local_err);
3982df92562eSFam Zheng     error_propagate(errp, local_err);
3983df92562eSFam Zheng 
3984df92562eSFam Zheng     aio_context_release(aio_context);
3985df92562eSFam Zheng }
3986df92562eSFam Zheng 
39873ddf3efeSAlberto Garcia /* Get a block job using its ID and acquire its AioContext */
39883ddf3efeSAlberto Garcia static BlockJob *find_block_job(const char *id, AioContext **aio_context,
398924d6bffeSMarkus Armbruster                                 Error **errp)
39902d47c6e9SStefan Hajnoczi {
39913ddf3efeSAlberto Garcia     BlockJob *job;
39923ddf3efeSAlberto Garcia 
39933ddf3efeSAlberto Garcia     assert(id != NULL);
39942d47c6e9SStefan Hajnoczi 
39955433c24fSMax Reitz     *aio_context = NULL;
39965433c24fSMax Reitz 
39973ddf3efeSAlberto Garcia     job = block_job_get(id);
39983ddf3efeSAlberto Garcia 
39993ddf3efeSAlberto Garcia     if (!job) {
40003ddf3efeSAlberto Garcia         error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
40013ddf3efeSAlberto Garcia                   "Block job '%s' not found", id);
40023ddf3efeSAlberto Garcia         return NULL;
40032d47c6e9SStefan Hajnoczi     }
40043d948cdfSStefan Hajnoczi 
40053ddf3efeSAlberto Garcia     *aio_context = blk_get_aio_context(job->blk);
40063d948cdfSStefan Hajnoczi     aio_context_acquire(*aio_context);
40073d948cdfSStefan Hajnoczi 
40083ddf3efeSAlberto Garcia     return job;
40092d47c6e9SStefan Hajnoczi }
40102d47c6e9SStefan Hajnoczi 
4011882ec7ceSStefan Hajnoczi void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
40122d47c6e9SStefan Hajnoczi {
40133d948cdfSStefan Hajnoczi     AioContext *aio_context;
401424d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
40152d47c6e9SStefan Hajnoczi 
40162d47c6e9SStefan Hajnoczi     if (!job) {
40172d47c6e9SStefan Hajnoczi         return;
40182d47c6e9SStefan Hajnoczi     }
40192d47c6e9SStefan Hajnoczi 
4020882ec7ceSStefan Hajnoczi     block_job_set_speed(job, speed, errp);
40213d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
40222d47c6e9SStefan Hajnoczi }
4023370521a1SStefan Hajnoczi 
40246e37fb81SPaolo Bonzini void qmp_block_job_cancel(const char *device,
40256e37fb81SPaolo Bonzini                           bool has_force, bool force, Error **errp)
40266e37fb81SPaolo Bonzini {
40273d948cdfSStefan Hajnoczi     AioContext *aio_context;
402824d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
40296e37fb81SPaolo Bonzini 
40306e37fb81SPaolo Bonzini     if (!job) {
40316e37fb81SPaolo Bonzini         return;
40326e37fb81SPaolo Bonzini     }
40333d948cdfSStefan Hajnoczi 
40343d948cdfSStefan Hajnoczi     if (!has_force) {
40353d948cdfSStefan Hajnoczi         force = false;
40363d948cdfSStefan Hajnoczi     }
40373d948cdfSStefan Hajnoczi 
4038b15de828SKevin Wolf     if (job_user_paused(&job->job) && !force) {
4039f231b88dSCole Robinson         error_setg(errp, "The block job for device '%s' is currently paused",
4040f231b88dSCole Robinson                    device);
40413d948cdfSStefan Hajnoczi         goto out;
40426e37fb81SPaolo Bonzini     }
40436e37fb81SPaolo Bonzini 
40446e37fb81SPaolo Bonzini     trace_qmp_block_job_cancel(job);
40453d70ff53SKevin Wolf     job_user_cancel(&job->job, force, errp);
40463d948cdfSStefan Hajnoczi out:
40473d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
40486e37fb81SPaolo Bonzini }
40496e37fb81SPaolo Bonzini 
40506e37fb81SPaolo Bonzini void qmp_block_job_pause(const char *device, Error **errp)
4051370521a1SStefan Hajnoczi {
40523d948cdfSStefan Hajnoczi     AioContext *aio_context;
405324d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
4054370521a1SStefan Hajnoczi 
40550ec4dfb8SJohn Snow     if (!job) {
4056370521a1SStefan Hajnoczi         return;
4057370521a1SStefan Hajnoczi     }
40586e37fb81SPaolo Bonzini 
40596e37fb81SPaolo Bonzini     trace_qmp_block_job_pause(job);
4060b15de828SKevin Wolf     job_user_pause(&job->job, errp);
40613d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
40626e37fb81SPaolo Bonzini }
40636e37fb81SPaolo Bonzini 
40646e37fb81SPaolo Bonzini void qmp_block_job_resume(const char *device, Error **errp)
40656e37fb81SPaolo Bonzini {
40663d948cdfSStefan Hajnoczi     AioContext *aio_context;
406724d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
40686e37fb81SPaolo Bonzini 
40690ec4dfb8SJohn Snow     if (!job) {
40708acc72a4SPaolo Bonzini         return;
40718acc72a4SPaolo Bonzini     }
4072370521a1SStefan Hajnoczi 
40736e37fb81SPaolo Bonzini     trace_qmp_block_job_resume(job);
4074b15de828SKevin Wolf     job_user_resume(&job->job, errp);
40753d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
4076370521a1SStefan Hajnoczi }
4077fb5458cdSStefan Hajnoczi 
4078aeae883bSPaolo Bonzini void qmp_block_job_complete(const char *device, Error **errp)
4079aeae883bSPaolo Bonzini {
40803d948cdfSStefan Hajnoczi     AioContext *aio_context;
408124d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
4082aeae883bSPaolo Bonzini 
4083aeae883bSPaolo Bonzini     if (!job) {
4084aeae883bSPaolo Bonzini         return;
4085aeae883bSPaolo Bonzini     }
4086aeae883bSPaolo Bonzini 
4087aeae883bSPaolo Bonzini     trace_qmp_block_job_complete(job);
40883453d972SKevin Wolf     job_complete(&job->job, errp);
40893d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
4090aeae883bSPaolo Bonzini }
4091aeae883bSPaolo Bonzini 
409211b61fbcSJohn Snow void qmp_block_job_finalize(const char *id, Error **errp)
409311b61fbcSJohn Snow {
409411b61fbcSJohn Snow     AioContext *aio_context;
409511b61fbcSJohn Snow     BlockJob *job = find_block_job(id, &aio_context, errp);
409611b61fbcSJohn Snow 
409711b61fbcSJohn Snow     if (!job) {
409811b61fbcSJohn Snow         return;
409911b61fbcSJohn Snow     }
410011b61fbcSJohn Snow 
410111b61fbcSJohn Snow     trace_qmp_block_job_finalize(job);
41027eaa8fb5SKevin Wolf     job_finalize(&job->job, errp);
410311b61fbcSJohn Snow     aio_context_release(aio_context);
410411b61fbcSJohn Snow }
410511b61fbcSJohn Snow 
410675f71059SJohn Snow void qmp_block_job_dismiss(const char *id, Error **errp)
410775f71059SJohn Snow {
410875f71059SJohn Snow     AioContext *aio_context;
41095f9a6a08SKevin Wolf     BlockJob *bjob = find_block_job(id, &aio_context, errp);
41105f9a6a08SKevin Wolf     Job *job;
411175f71059SJohn Snow 
41125f9a6a08SKevin Wolf     if (!bjob) {
411375f71059SJohn Snow         return;
411475f71059SJohn Snow     }
411575f71059SJohn Snow 
41165f9a6a08SKevin Wolf     trace_qmp_block_job_dismiss(bjob);
41175f9a6a08SKevin Wolf     job = &bjob->job;
41185f9a6a08SKevin Wolf     job_dismiss(&job, errp);
411975f71059SJohn Snow     aio_context_release(aio_context);
412075f71059SJohn Snow }
412175f71059SJohn Snow 
4122fa40e656SJeff Cody void qmp_change_backing_file(const char *device,
4123fa40e656SJeff Cody                              const char *image_node_name,
4124fa40e656SJeff Cody                              const char *backing_file,
4125fa40e656SJeff Cody                              Error **errp)
4126fa40e656SJeff Cody {
4127fa40e656SJeff Cody     BlockDriverState *bs = NULL;
4128729962f6SStefan Hajnoczi     AioContext *aio_context;
4129fa40e656SJeff Cody     BlockDriverState *image_bs = NULL;
4130fa40e656SJeff Cody     Error *local_err = NULL;
4131fa40e656SJeff Cody     bool ro;
4132fa40e656SJeff Cody     int ret;
4133fa40e656SJeff Cody 
41347b5dca3fSKevin Wolf     bs = qmp_get_root_bs(device, errp);
41357b5dca3fSKevin Wolf     if (!bs) {
4136fa40e656SJeff Cody         return;
4137fa40e656SJeff Cody     }
4138fa40e656SJeff Cody 
41397b5dca3fSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
4140729962f6SStefan Hajnoczi     aio_context_acquire(aio_context);
4141729962f6SStefan Hajnoczi 
4142fa40e656SJeff Cody     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
4143fa40e656SJeff Cody     if (local_err) {
4144fa40e656SJeff Cody         error_propagate(errp, local_err);
4145729962f6SStefan Hajnoczi         goto out;
4146fa40e656SJeff Cody     }
4147fa40e656SJeff Cody 
4148fa40e656SJeff Cody     if (!image_bs) {
4149fa40e656SJeff Cody         error_setg(errp, "image file not found");
4150729962f6SStefan Hajnoczi         goto out;
4151fa40e656SJeff Cody     }
4152fa40e656SJeff Cody 
4153fa40e656SJeff Cody     if (bdrv_find_base(image_bs) == image_bs) {
4154fa40e656SJeff Cody         error_setg(errp, "not allowing backing file change on an image "
4155fa40e656SJeff Cody                          "without a backing file");
4156729962f6SStefan Hajnoczi         goto out;
4157fa40e656SJeff Cody     }
4158fa40e656SJeff Cody 
4159fa40e656SJeff Cody     /* even though we are not necessarily operating on bs, we need it to
4160fa40e656SJeff Cody      * determine if block ops are currently prohibited on the chain */
4161fa40e656SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
4162729962f6SStefan Hajnoczi         goto out;
4163fa40e656SJeff Cody     }
4164fa40e656SJeff Cody 
4165fa40e656SJeff Cody     /* final sanity check */
4166fa40e656SJeff Cody     if (!bdrv_chain_contains(bs, image_bs)) {
4167fa40e656SJeff Cody         error_setg(errp, "'%s' and image file are not in the same chain",
4168fa40e656SJeff Cody                    device);
4169729962f6SStefan Hajnoczi         goto out;
4170fa40e656SJeff Cody     }
4171fa40e656SJeff Cody 
4172fa40e656SJeff Cody     /* if not r/w, reopen to make r/w */
4173fa40e656SJeff Cody     ro = bdrv_is_read_only(image_bs);
4174fa40e656SJeff Cody 
4175fa40e656SJeff Cody     if (ro) {
4176051a60f6SAlberto Garcia         if (bdrv_reopen_set_read_only(image_bs, false, errp) != 0) {
4177729962f6SStefan Hajnoczi             goto out;
4178fa40e656SJeff Cody         }
4179fa40e656SJeff Cody     }
4180fa40e656SJeff Cody 
4181fa40e656SJeff Cody     ret = bdrv_change_backing_file(image_bs, backing_file,
4182fa40e656SJeff Cody                                image_bs->drv ? image_bs->drv->format_name : "");
4183fa40e656SJeff Cody 
4184fa40e656SJeff Cody     if (ret < 0) {
4185fa40e656SJeff Cody         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
4186fa40e656SJeff Cody                          backing_file);
4187fa40e656SJeff Cody         /* don't exit here, so we can try to restore open flags if
4188fa40e656SJeff Cody          * appropriate */
4189fa40e656SJeff Cody     }
4190fa40e656SJeff Cody 
4191fa40e656SJeff Cody     if (ro) {
4192051a60f6SAlberto Garcia         bdrv_reopen_set_read_only(image_bs, true, &local_err);
4193621ff94dSEduardo Habkost         error_propagate(errp, local_err);
4194fa40e656SJeff Cody     }
4195729962f6SStefan Hajnoczi 
4196729962f6SStefan Hajnoczi out:
4197729962f6SStefan Hajnoczi     aio_context_release(aio_context);
4198fa40e656SJeff Cody }
4199fa40e656SJeff Cody 
4200abb21ac3SKevin Wolf void hmp_drive_add_node(Monitor *mon, const char *optstr)
4201abb21ac3SKevin Wolf {
4202abb21ac3SKevin Wolf     QemuOpts *opts;
4203abb21ac3SKevin Wolf     QDict *qdict;
4204abb21ac3SKevin Wolf     Error *local_err = NULL;
4205abb21ac3SKevin Wolf 
4206abb21ac3SKevin Wolf     opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
4207abb21ac3SKevin Wolf     if (!opts) {
4208abb21ac3SKevin Wolf         return;
4209abb21ac3SKevin Wolf     }
4210abb21ac3SKevin Wolf 
4211abb21ac3SKevin Wolf     qdict = qemu_opts_to_qdict(opts, NULL);
4212abb21ac3SKevin Wolf 
4213abb21ac3SKevin Wolf     if (!qdict_get_try_str(qdict, "node-name")) {
4214cb3e7f08SMarc-André Lureau         qobject_unref(qdict);
4215abb21ac3SKevin Wolf         error_report("'node-name' needs to be specified");
4216abb21ac3SKevin Wolf         goto out;
4217abb21ac3SKevin Wolf     }
4218abb21ac3SKevin Wolf 
4219abb21ac3SKevin Wolf     BlockDriverState *bs = bds_tree_init(qdict, &local_err);
4220abb21ac3SKevin Wolf     if (!bs) {
4221abb21ac3SKevin Wolf         error_report_err(local_err);
4222abb21ac3SKevin Wolf         goto out;
4223abb21ac3SKevin Wolf     }
4224abb21ac3SKevin Wolf 
4225abb21ac3SKevin Wolf     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4226abb21ac3SKevin Wolf 
4227abb21ac3SKevin Wolf out:
4228abb21ac3SKevin Wolf     qemu_opts_del(opts);
4229abb21ac3SKevin Wolf }
4230abb21ac3SKevin Wolf 
4231d26c9a15SKevin Wolf void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
4232d26c9a15SKevin Wolf {
4233be4b67bcSMax Reitz     BlockDriverState *bs;
4234d26c9a15SKevin Wolf     QObject *obj;
42357d5e199aSDaniel P. Berrange     Visitor *v = qobject_output_visitor_new(&obj);
4236d26c9a15SKevin Wolf     QDict *qdict;
4237d26c9a15SKevin Wolf     Error *local_err = NULL;
4238d26c9a15SKevin Wolf 
42393b098d56SEric Blake     visit_type_BlockdevOptions(v, NULL, &options, &local_err);
424084d18f06SMarkus Armbruster     if (local_err) {
4241d26c9a15SKevin Wolf         error_propagate(errp, local_err);
4242d26c9a15SKevin Wolf         goto fail;
4243d26c9a15SKevin Wolf     }
4244d26c9a15SKevin Wolf 
42453b098d56SEric Blake     visit_complete(v, &obj);
42467dc847ebSMax Reitz     qdict = qobject_to(QDict, obj);
4247d26c9a15SKevin Wolf 
4248d26c9a15SKevin Wolf     qdict_flatten(qdict);
4249d26c9a15SKevin Wolf 
4250be4b67bcSMax Reitz     if (!qdict_get_try_str(qdict, "node-name")) {
42519ec8873eSKevin Wolf         error_setg(errp, "'node-name' must be specified for the root node");
4252be4b67bcSMax Reitz         goto fail;
4253be4b67bcSMax Reitz     }
4254be4b67bcSMax Reitz 
4255bd745e23SMax Reitz     bs = bds_tree_init(qdict, errp);
4256bd745e23SMax Reitz     if (!bs) {
4257be4b67bcSMax Reitz         goto fail;
4258be4b67bcSMax Reitz     }
42599c4218e9SMax Reitz 
42609c4218e9SMax Reitz     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4261be4b67bcSMax Reitz 
4262d26c9a15SKevin Wolf fail:
42633b098d56SEric Blake     visit_free(v);
4264d26c9a15SKevin Wolf }
4265d26c9a15SKevin Wolf 
426679b7a77eSMarkus Armbruster void qmp_blockdev_del(const char *node_name, Error **errp)
426781b936aeSAlberto Garcia {
426881b936aeSAlberto Garcia     AioContext *aio_context;
426981b936aeSAlberto Garcia     BlockDriverState *bs;
427081b936aeSAlberto Garcia 
427181b936aeSAlberto Garcia     bs = bdrv_find_node(node_name);
427281b936aeSAlberto Garcia     if (!bs) {
427381b936aeSAlberto Garcia         error_setg(errp, "Cannot find node %s", node_name);
427481b936aeSAlberto Garcia         return;
427581b936aeSAlberto Garcia     }
42761f0c461bSKevin Wolf     if (bdrv_has_blk(bs)) {
4277e467da7bSKevin Wolf         error_setg(errp, "Node %s is in use", node_name);
427881b936aeSAlberto Garcia         return;
427981b936aeSAlberto Garcia     }
428081b936aeSAlberto Garcia     aio_context = bdrv_get_aio_context(bs);
428181b936aeSAlberto Garcia     aio_context_acquire(aio_context);
428281b936aeSAlberto Garcia 
428381b936aeSAlberto Garcia     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
428481b936aeSAlberto Garcia         goto out;
428581b936aeSAlberto Garcia     }
428681b936aeSAlberto Garcia 
428770537ed5SPaolo Bonzini     if (!QTAILQ_IN_USE(bs, monitor_list)) {
42889c4218e9SMax Reitz         error_setg(errp, "Node %s is not owned by the monitor",
42899c4218e9SMax Reitz                    bs->node_name);
42909c4218e9SMax Reitz         goto out;
42919c4218e9SMax Reitz     }
42929c4218e9SMax Reitz 
42939c4218e9SMax Reitz     if (bs->refcnt > 1) {
429481b936aeSAlberto Garcia         error_setg(errp, "Block device %s is in use",
429581b936aeSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
429681b936aeSAlberto Garcia         goto out;
429781b936aeSAlberto Garcia     }
429881b936aeSAlberto Garcia 
42999c4218e9SMax Reitz     QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
430081b936aeSAlberto Garcia     bdrv_unref(bs);
430181b936aeSAlberto Garcia 
430281b936aeSAlberto Garcia out:
430381b936aeSAlberto Garcia     aio_context_release(aio_context);
430481b936aeSAlberto Garcia }
430581b936aeSAlberto Garcia 
43067f821597SWen Congyang static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
43077f821597SWen Congyang                                   const char *child_name)
43087f821597SWen Congyang {
43097f821597SWen Congyang     BdrvChild *child;
43107f821597SWen Congyang 
43117f821597SWen Congyang     QLIST_FOREACH(child, &parent_bs->children, next) {
43127f821597SWen Congyang         if (strcmp(child->name, child_name) == 0) {
43137f821597SWen Congyang             return child;
43147f821597SWen Congyang         }
43157f821597SWen Congyang     }
43167f821597SWen Congyang 
43177f821597SWen Congyang     return NULL;
43187f821597SWen Congyang }
43197f821597SWen Congyang 
43207f821597SWen Congyang void qmp_x_blockdev_change(const char *parent, bool has_child,
43217f821597SWen Congyang                            const char *child, bool has_node,
43227f821597SWen Congyang                            const char *node, Error **errp)
43237f821597SWen Congyang {
43247f821597SWen Congyang     BlockDriverState *parent_bs, *new_bs = NULL;
43257f821597SWen Congyang     BdrvChild *p_child;
43267f821597SWen Congyang 
43277f821597SWen Congyang     parent_bs = bdrv_lookup_bs(parent, parent, errp);
43287f821597SWen Congyang     if (!parent_bs) {
43297f821597SWen Congyang         return;
43307f821597SWen Congyang     }
43317f821597SWen Congyang 
43327f821597SWen Congyang     if (has_child == has_node) {
43337f821597SWen Congyang         if (has_child) {
43347f821597SWen Congyang             error_setg(errp, "The parameters child and node are in conflict");
43357f821597SWen Congyang         } else {
43367f821597SWen Congyang             error_setg(errp, "Either child or node must be specified");
43377f821597SWen Congyang         }
43387f821597SWen Congyang         return;
43397f821597SWen Congyang     }
43407f821597SWen Congyang 
43417f821597SWen Congyang     if (has_child) {
43427f821597SWen Congyang         p_child = bdrv_find_child(parent_bs, child);
43437f821597SWen Congyang         if (!p_child) {
43447f821597SWen Congyang             error_setg(errp, "Node '%s' does not have child '%s'",
43457f821597SWen Congyang                        parent, child);
43467f821597SWen Congyang             return;
43477f821597SWen Congyang         }
43487f821597SWen Congyang         bdrv_del_child(parent_bs, p_child, errp);
43497f821597SWen Congyang     }
43507f821597SWen Congyang 
43517f821597SWen Congyang     if (has_node) {
43527f821597SWen Congyang         new_bs = bdrv_find_node(node);
43537f821597SWen Congyang         if (!new_bs) {
43547f821597SWen Congyang             error_setg(errp, "Node '%s' not found", node);
43557f821597SWen Congyang             return;
43567f821597SWen Congyang         }
43577f821597SWen Congyang         bdrv_add_child(parent_bs, new_bs, errp);
43587f821597SWen Congyang     }
43597f821597SWen Congyang }
43607f821597SWen Congyang 
4361fb5458cdSStefan Hajnoczi BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4362fb5458cdSStefan Hajnoczi {
4363fea68bb6SMarkus Armbruster     BlockJobInfoList *head = NULL, **p_next = &head;
4364f0f55dedSAlberto Garcia     BlockJob *job;
4365fea68bb6SMarkus Armbruster 
4366f0f55dedSAlberto Garcia     for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4367559b935fSJohn Snow         BlockJobInfoList *elem;
4368559b935fSJohn Snow         AioContext *aio_context;
436969691e72SStefan Hajnoczi 
4370559b935fSJohn Snow         if (block_job_is_internal(job)) {
4371559b935fSJohn Snow             continue;
4372559b935fSJohn Snow         }
4373559b935fSJohn Snow         elem = g_new0(BlockJobInfoList, 1);
4374559b935fSJohn Snow         aio_context = blk_get_aio_context(job->blk);
437569691e72SStefan Hajnoczi         aio_context_acquire(aio_context);
4376559b935fSJohn Snow         elem->value = block_job_query(job, errp);
4377f0f55dedSAlberto Garcia         aio_context_release(aio_context);
4378559b935fSJohn Snow         if (!elem->value) {
4379559b935fSJohn Snow             g_free(elem);
4380559b935fSJohn Snow             qapi_free_BlockJobInfoList(head);
4381559b935fSJohn Snow             return NULL;
4382559b935fSJohn Snow         }
4383fea68bb6SMarkus Armbruster         *p_next = elem;
4384fea68bb6SMarkus Armbruster         p_next = &elem->next;
4385fea68bb6SMarkus Armbruster     }
438669691e72SStefan Hajnoczi 
4387fea68bb6SMarkus Armbruster     return head;
4388fb5458cdSStefan Hajnoczi }
43894d454574SPaolo Bonzini 
4390ca00bbb1SStefan Hajnoczi void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
4391882e9b89SStefan Hajnoczi                                  bool has_force, bool force, Error **errp)
4392ca00bbb1SStefan Hajnoczi {
4393ca00bbb1SStefan Hajnoczi     AioContext *old_context;
4394ca00bbb1SStefan Hajnoczi     AioContext *new_context;
4395ca00bbb1SStefan Hajnoczi     BlockDriverState *bs;
4396ca00bbb1SStefan Hajnoczi 
4397ca00bbb1SStefan Hajnoczi     bs = bdrv_find_node(node_name);
4398ca00bbb1SStefan Hajnoczi     if (!bs) {
4399ca00bbb1SStefan Hajnoczi         error_setg(errp, "Cannot find node %s", node_name);
4400ca00bbb1SStefan Hajnoczi         return;
4401ca00bbb1SStefan Hajnoczi     }
4402ca00bbb1SStefan Hajnoczi 
4403882e9b89SStefan Hajnoczi     /* Protects against accidents. */
4404882e9b89SStefan Hajnoczi     if (!(has_force && force) && bdrv_has_blk(bs)) {
4405882e9b89SStefan Hajnoczi         error_setg(errp, "Node %s is associated with a BlockBackend and could "
4406882e9b89SStefan Hajnoczi                          "be in use (use force=true to override this check)",
4407882e9b89SStefan Hajnoczi                          node_name);
4408ca00bbb1SStefan Hajnoczi         return;
4409ca00bbb1SStefan Hajnoczi     }
4410ca00bbb1SStefan Hajnoczi 
4411ca00bbb1SStefan Hajnoczi     if (iothread->type == QTYPE_QSTRING) {
4412ca00bbb1SStefan Hajnoczi         IOThread *obj = iothread_by_id(iothread->u.s);
4413ca00bbb1SStefan Hajnoczi         if (!obj) {
4414ca00bbb1SStefan Hajnoczi             error_setg(errp, "Cannot find iothread %s", iothread->u.s);
4415ca00bbb1SStefan Hajnoczi             return;
4416ca00bbb1SStefan Hajnoczi         }
4417ca00bbb1SStefan Hajnoczi 
4418ca00bbb1SStefan Hajnoczi         new_context = iothread_get_aio_context(obj);
4419ca00bbb1SStefan Hajnoczi     } else {
4420ca00bbb1SStefan Hajnoczi         new_context = qemu_get_aio_context();
4421ca00bbb1SStefan Hajnoczi     }
4422ca00bbb1SStefan Hajnoczi 
4423ca00bbb1SStefan Hajnoczi     old_context = bdrv_get_aio_context(bs);
4424ca00bbb1SStefan Hajnoczi     aio_context_acquire(old_context);
4425ca00bbb1SStefan Hajnoczi 
4426ca00bbb1SStefan Hajnoczi     bdrv_set_aio_context(bs, new_context);
4427ca00bbb1SStefan Hajnoczi 
4428ca00bbb1SStefan Hajnoczi     aio_context_release(old_context);
4429ca00bbb1SStefan Hajnoczi }
4430ca00bbb1SStefan Hajnoczi 
44317e5c776dSVladimir Sementsov-Ogievskiy void qmp_x_block_latency_histogram_set(
44327e5c776dSVladimir Sementsov-Ogievskiy     const char *device,
44337e5c776dSVladimir Sementsov-Ogievskiy     bool has_boundaries, uint64List *boundaries,
44347e5c776dSVladimir Sementsov-Ogievskiy     bool has_boundaries_read, uint64List *boundaries_read,
44357e5c776dSVladimir Sementsov-Ogievskiy     bool has_boundaries_write, uint64List *boundaries_write,
44367e5c776dSVladimir Sementsov-Ogievskiy     bool has_boundaries_flush, uint64List *boundaries_flush,
44377e5c776dSVladimir Sementsov-Ogievskiy     Error **errp)
44387e5c776dSVladimir Sementsov-Ogievskiy {
44397e5c776dSVladimir Sementsov-Ogievskiy     BlockBackend *blk = blk_by_name(device);
44407e5c776dSVladimir Sementsov-Ogievskiy     BlockAcctStats *stats;
444163d5341fSzhenwei pi     int ret;
44427e5c776dSVladimir Sementsov-Ogievskiy 
44437e5c776dSVladimir Sementsov-Ogievskiy     if (!blk) {
44447e5c776dSVladimir Sementsov-Ogievskiy         error_setg(errp, "Device '%s' not found", device);
44457e5c776dSVladimir Sementsov-Ogievskiy         return;
44467e5c776dSVladimir Sementsov-Ogievskiy     }
44477e5c776dSVladimir Sementsov-Ogievskiy     stats = blk_get_stats(blk);
44487e5c776dSVladimir Sementsov-Ogievskiy 
44497e5c776dSVladimir Sementsov-Ogievskiy     if (!has_boundaries && !has_boundaries_read && !has_boundaries_write &&
44507e5c776dSVladimir Sementsov-Ogievskiy         !has_boundaries_flush)
44517e5c776dSVladimir Sementsov-Ogievskiy     {
44527e5c776dSVladimir Sementsov-Ogievskiy         block_latency_histograms_clear(stats);
44537e5c776dSVladimir Sementsov-Ogievskiy         return;
44547e5c776dSVladimir Sementsov-Ogievskiy     }
44557e5c776dSVladimir Sementsov-Ogievskiy 
44567e5c776dSVladimir Sementsov-Ogievskiy     if (has_boundaries || has_boundaries_read) {
445763d5341fSzhenwei pi         ret = block_latency_histogram_set(
44587e5c776dSVladimir Sementsov-Ogievskiy             stats, BLOCK_ACCT_READ,
44597e5c776dSVladimir Sementsov-Ogievskiy             has_boundaries_read ? boundaries_read : boundaries);
446063d5341fSzhenwei pi         if (ret) {
446163d5341fSzhenwei pi             error_setg(errp, "Device '%s' set read boundaries fail", device);
446263d5341fSzhenwei pi             return;
446363d5341fSzhenwei pi         }
44647e5c776dSVladimir Sementsov-Ogievskiy     }
44657e5c776dSVladimir Sementsov-Ogievskiy 
44667e5c776dSVladimir Sementsov-Ogievskiy     if (has_boundaries || has_boundaries_write) {
446763d5341fSzhenwei pi         ret = block_latency_histogram_set(
44687e5c776dSVladimir Sementsov-Ogievskiy             stats, BLOCK_ACCT_WRITE,
44697e5c776dSVladimir Sementsov-Ogievskiy             has_boundaries_write ? boundaries_write : boundaries);
447063d5341fSzhenwei pi         if (ret) {
447163d5341fSzhenwei pi             error_setg(errp, "Device '%s' set write boundaries fail", device);
447263d5341fSzhenwei pi             return;
447363d5341fSzhenwei pi         }
44747e5c776dSVladimir Sementsov-Ogievskiy     }
44757e5c776dSVladimir Sementsov-Ogievskiy 
44767e5c776dSVladimir Sementsov-Ogievskiy     if (has_boundaries || has_boundaries_flush) {
447763d5341fSzhenwei pi         ret = block_latency_histogram_set(
44787e5c776dSVladimir Sementsov-Ogievskiy             stats, BLOCK_ACCT_FLUSH,
44797e5c776dSVladimir Sementsov-Ogievskiy             has_boundaries_flush ? boundaries_flush : boundaries);
448063d5341fSzhenwei pi         if (ret) {
448163d5341fSzhenwei pi             error_setg(errp, "Device '%s' set flush boundaries fail", device);
448263d5341fSzhenwei pi             return;
448363d5341fSzhenwei pi         }
44847e5c776dSVladimir Sementsov-Ogievskiy     }
44857e5c776dSVladimir Sementsov-Ogievskiy }
44867e5c776dSVladimir Sementsov-Ogievskiy 
44870006383eSKevin Wolf QemuOptsList qemu_common_drive_opts = {
44884d454574SPaolo Bonzini     .name = "drive",
44890006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
44904d454574SPaolo Bonzini     .desc = {
44914d454574SPaolo Bonzini         {
44924d454574SPaolo Bonzini             .name = "snapshot",
44934d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
44944d454574SPaolo Bonzini             .help = "enable/disable snapshot mode",
44954d454574SPaolo Bonzini         },{
44964d454574SPaolo Bonzini             .name = "aio",
44974d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
44984d454574SPaolo Bonzini             .help = "host AIO implementation (threads, native)",
44994d454574SPaolo Bonzini         },{
4500e4b24b49SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
4501e4b24b49SKevin Wolf             .type = QEMU_OPT_BOOL,
4502e4b24b49SKevin Wolf             .help = "Enable writeback mode",
4503e4b24b49SKevin Wolf         },{
45044d454574SPaolo Bonzini             .name = "format",
45054d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
45064d454574SPaolo Bonzini             .help = "disk format (raw, qcow2, ...)",
45074d454574SPaolo Bonzini         },{
45084d454574SPaolo Bonzini             .name = "rerror",
45094d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
45104d454574SPaolo Bonzini             .help = "read error action",
45114d454574SPaolo Bonzini         },{
45124d454574SPaolo Bonzini             .name = "werror",
45134d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
45144d454574SPaolo Bonzini             .help = "write error action",
45154d454574SPaolo Bonzini         },{
45164e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
45174d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
45184d454574SPaolo Bonzini             .help = "open drive file as read-only",
4519a2a7862cSPradeep Jagadeesh         },
4520a2a7862cSPradeep Jagadeesh 
4521a2a7862cSPradeep Jagadeesh         THROTTLE_OPTS,
4522a2a7862cSPradeep Jagadeesh 
4523a2a7862cSPradeep Jagadeesh         {
452476f4afb4SAlberto Garcia             .name = "throttling.group",
452576f4afb4SAlberto Garcia             .type = QEMU_OPT_STRING,
452676f4afb4SAlberto Garcia             .help = "name of the block throttling group",
452776f4afb4SAlberto Garcia         },{
45284d454574SPaolo Bonzini             .name = "copy-on-read",
45294d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
45304d454574SPaolo Bonzini             .help = "copy read data from backing file into image file",
4531465bee1dSPeter Lieven         },{
4532465bee1dSPeter Lieven             .name = "detect-zeroes",
4533465bee1dSPeter Lieven             .type = QEMU_OPT_STRING,
4534465bee1dSPeter Lieven             .help = "try to optimize zero writes (off, on, unmap)",
4535362e9299SAlberto Garcia         },{
4536362e9299SAlberto Garcia             .name = "stats-account-invalid",
4537362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4538362e9299SAlberto Garcia             .help = "whether to account for invalid I/O operations "
4539362e9299SAlberto Garcia                     "in the statistics",
4540362e9299SAlberto Garcia         },{
4541362e9299SAlberto Garcia             .name = "stats-account-failed",
4542362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4543362e9299SAlberto Garcia             .help = "whether to account for failed I/O operations "
4544362e9299SAlberto Garcia                     "in the statistics",
45454d454574SPaolo Bonzini         },
45464d454574SPaolo Bonzini         { /* end of list */ }
45474d454574SPaolo Bonzini     },
45484d454574SPaolo Bonzini };
45490006383eSKevin Wolf 
45500006383eSKevin Wolf QemuOptsList qemu_drive_opts = {
45510006383eSKevin Wolf     .name = "drive",
45520006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
45530006383eSKevin Wolf     .desc = {
4554492fdc6fSKevin Wolf         /*
4555492fdc6fSKevin Wolf          * no elements => accept any params
4556492fdc6fSKevin Wolf          * validation will happen later
4557492fdc6fSKevin Wolf          */
45580006383eSKevin Wolf         { /* end of list */ }
45590006383eSKevin Wolf     },
45600006383eSKevin Wolf };
4561