xref: /openbmc/qemu/blockdev.c (revision eff0829b0710d60c1846eb99baeb47b2478a414a)
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"
43cdcd4361SMarkus Armbruster #include "qemu/qemu-print.h"
441de7afc9SPaolo Bonzini #include "qemu/config-file.h"
459af23989SMarkus Armbruster #include "qapi/qapi-commands-block.h"
469af23989SMarkus Armbruster #include "qapi/qapi-commands-transaction.h"
479af23989SMarkus Armbruster #include "qapi/qapi-visit-block-core.h"
48452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
4915280c36SMarkus Armbruster #include "qapi/qmp/qnum.h"
506b673957SMarkus Armbruster #include "qapi/qmp/qstring.h"
51e688df6bSMarkus Armbruster #include "qapi/error.h"
52cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
5347e6b297SMarkus Armbruster #include "qapi/qmp/qlist.h"
54b3db211fSDaniel P. Berrange #include "qapi/qobject-output-visitor.h"
559c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
56ca00bbb1SStefan Hajnoczi #include "sysemu/iothread.h"
57737e150eSPaolo Bonzini #include "block/block_int.h"
580ab8ed18SDaniel P. Berrange #include "block/trace.h"
599c17d615SPaolo Bonzini #include "sysemu/arch_init.h"
60c616f16eSThomas Huth #include "sysemu/qtest.h"
61f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
62f348b6d1SVeronia Bahaa #include "qemu/help_option.h"
63a2a7862cSPradeep Jagadeesh #include "qemu/throttle-options.h"
64666daa68SMarkus Armbruster 
659c4218e9SMax Reitz static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
669c4218e9SMax Reitz     QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
679c4218e9SMax Reitz 
68b33945cfSKevin Wolf static int do_open_tray(const char *blk_name, const char *qdev_id,
69b33945cfSKevin Wolf                         bool force, Error **errp);
7082fcf66eSMax Reitz static void blockdev_remove_medium(bool has_device, const char *device,
7182fcf66eSMax Reitz                                    bool has_id, const char *id, Error **errp);
7282fcf66eSMax Reitz static void blockdev_insert_medium(bool has_device, const char *device,
7382fcf66eSMax Reitz                                    bool has_id, const char *id,
7482fcf66eSMax Reitz                                    const char *node_name, Error **errp);
75bf18bee5SColin Lord 
761960966dSMarkus Armbruster static const char *const if_name[IF_COUNT] = {
771960966dSMarkus Armbruster     [IF_NONE] = "none",
781960966dSMarkus Armbruster     [IF_IDE] = "ide",
791960966dSMarkus Armbruster     [IF_SCSI] = "scsi",
801960966dSMarkus Armbruster     [IF_FLOPPY] = "floppy",
811960966dSMarkus Armbruster     [IF_PFLASH] = "pflash",
821960966dSMarkus Armbruster     [IF_MTD] = "mtd",
831960966dSMarkus Armbruster     [IF_SD] = "sd",
841960966dSMarkus Armbruster     [IF_VIRTIO] = "virtio",
851960966dSMarkus Armbruster     [IF_XEN] = "xen",
861960966dSMarkus Armbruster };
871960966dSMarkus Armbruster 
8821dff8cfSJohn Snow static int if_max_devs[IF_COUNT] = {
8927d6bf40SMarkus Armbruster     /*
9027d6bf40SMarkus Armbruster      * Do not change these numbers!  They govern how drive option
9127d6bf40SMarkus Armbruster      * index maps to unit and bus.  That mapping is ABI.
9227d6bf40SMarkus Armbruster      *
93547cb157SWei Jiangang      * All controllers used to implement if=T drives need to support
9427d6bf40SMarkus Armbruster      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
9527d6bf40SMarkus Armbruster      * Otherwise, some index values map to "impossible" bus, unit
9627d6bf40SMarkus Armbruster      * values.
9727d6bf40SMarkus Armbruster      *
9827d6bf40SMarkus Armbruster      * For instance, if you change [IF_SCSI] to 255, -drive
9927d6bf40SMarkus Armbruster      * if=scsi,index=12 no longer means bus=1,unit=5, but
10027d6bf40SMarkus Armbruster      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
10127d6bf40SMarkus Armbruster      * the drive can't be set up.  Regression.
10227d6bf40SMarkus Armbruster      */
10327d6bf40SMarkus Armbruster     [IF_IDE] = 2,
10427d6bf40SMarkus Armbruster     [IF_SCSI] = 7,
1051960966dSMarkus Armbruster };
1061960966dSMarkus Armbruster 
10721dff8cfSJohn Snow /**
10821dff8cfSJohn Snow  * Boards may call this to offer board-by-board overrides
10921dff8cfSJohn Snow  * of the default, global values.
11021dff8cfSJohn Snow  */
11121dff8cfSJohn Snow void override_max_devs(BlockInterfaceType type, int max_devs)
11221dff8cfSJohn Snow {
11318e46a03SMarkus Armbruster     BlockBackend *blk;
11421dff8cfSJohn Snow     DriveInfo *dinfo;
11521dff8cfSJohn Snow 
11621dff8cfSJohn Snow     if (max_devs <= 0) {
11721dff8cfSJohn Snow         return;
11821dff8cfSJohn Snow     }
11921dff8cfSJohn Snow 
12018e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
12118e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
12221dff8cfSJohn Snow         if (dinfo->type == type) {
12321dff8cfSJohn Snow             fprintf(stderr, "Cannot override units-per-bus property of"
12421dff8cfSJohn Snow                     " the %s interface, because a drive of that type has"
12521dff8cfSJohn Snow                     " already been added.\n", if_name[type]);
12621dff8cfSJohn Snow             g_assert_not_reached();
12721dff8cfSJohn Snow         }
12821dff8cfSJohn Snow     }
12921dff8cfSJohn Snow 
13021dff8cfSJohn Snow     if_max_devs[type] = max_devs;
13121dff8cfSJohn Snow }
13221dff8cfSJohn Snow 
13314bafc54SMarkus Armbruster /*
13414bafc54SMarkus Armbruster  * We automatically delete the drive when a device using it gets
13514bafc54SMarkus Armbruster  * unplugged.  Questionable feature, but we can't just drop it.
13614bafc54SMarkus Armbruster  * Device models call blockdev_mark_auto_del() to schedule the
13714bafc54SMarkus Armbruster  * automatic deletion, and generic qdev code calls blockdev_auto_del()
13814bafc54SMarkus Armbruster  * when deletion is actually safe.
13914bafc54SMarkus Armbruster  */
1404be74634SMarkus Armbruster void blockdev_mark_auto_del(BlockBackend *blk)
14114bafc54SMarkus Armbruster {
14218e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
1434be74634SMarkus Armbruster     BlockDriverState *bs = blk_bs(blk);
14491fddb0dSStefan Hajnoczi     AioContext *aio_context;
14514bafc54SMarkus Armbruster 
14626f8b3a8SMarkus Armbruster     if (!dinfo) {
1472d246f01SKevin Wolf         return;
1482d246f01SKevin Wolf     }
1492d246f01SKevin Wolf 
1505433c24fSMax Reitz     if (bs) {
15191fddb0dSStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
15291fddb0dSStefan Hajnoczi         aio_context_acquire(aio_context);
15391fddb0dSStefan Hajnoczi 
15412bde0eeSPaolo Bonzini         if (bs->job) {
1553d70ff53SKevin Wolf             job_cancel(&bs->job->job, false);
15612bde0eeSPaolo Bonzini         }
15791fddb0dSStefan Hajnoczi 
15891fddb0dSStefan Hajnoczi         aio_context_release(aio_context);
1595433c24fSMax Reitz     }
16091fddb0dSStefan Hajnoczi 
16114bafc54SMarkus Armbruster     dinfo->auto_del = 1;
16214bafc54SMarkus Armbruster }
16314bafc54SMarkus Armbruster 
1644be74634SMarkus Armbruster void blockdev_auto_del(BlockBackend *blk)
16514bafc54SMarkus Armbruster {
16618e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
16714bafc54SMarkus Armbruster 
1680fc0f1faSRyan Harper     if (dinfo && dinfo->auto_del) {
169efaa7c4eSMax Reitz         monitor_remove_blk(blk);
170b9fe8a7aSMarkus Armbruster         blk_unref(blk);
17114bafc54SMarkus Armbruster     }
17214bafc54SMarkus Armbruster }
17314bafc54SMarkus Armbruster 
174d8f94e1bSJohn Snow /**
175d8f94e1bSJohn Snow  * Returns the current mapping of how many units per bus
176d8f94e1bSJohn Snow  * a particular interface can support.
177d8f94e1bSJohn Snow  *
178d8f94e1bSJohn Snow  *  A positive integer indicates n units per bus.
179d8f94e1bSJohn Snow  *  0 implies the mapping has not been established.
180d8f94e1bSJohn Snow  * -1 indicates an invalid BlockInterfaceType was given.
181d8f94e1bSJohn Snow  */
182d8f94e1bSJohn Snow int drive_get_max_devs(BlockInterfaceType type)
183d8f94e1bSJohn Snow {
184d8f94e1bSJohn Snow     if (type >= IF_IDE && type < IF_COUNT) {
185d8f94e1bSJohn Snow         return if_max_devs[type];
186d8f94e1bSJohn Snow     }
187d8f94e1bSJohn Snow 
188d8f94e1bSJohn Snow     return -1;
189d8f94e1bSJohn Snow }
190d8f94e1bSJohn Snow 
191505a7fb1SMarkus Armbruster static int drive_index_to_bus_id(BlockInterfaceType type, int index)
192505a7fb1SMarkus Armbruster {
193505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
194505a7fb1SMarkus Armbruster     return max_devs ? index / max_devs : 0;
195505a7fb1SMarkus Armbruster }
196505a7fb1SMarkus Armbruster 
197505a7fb1SMarkus Armbruster static int drive_index_to_unit_id(BlockInterfaceType type, int index)
198505a7fb1SMarkus Armbruster {
199505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
200505a7fb1SMarkus Armbruster     return max_devs ? index % max_devs : index;
201505a7fb1SMarkus Armbruster }
202505a7fb1SMarkus Armbruster 
2032292ddaeSMarkus Armbruster QemuOpts *drive_def(const char *optstr)
2042292ddaeSMarkus Armbruster {
20570b94331SMarkus Armbruster     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
2062292ddaeSMarkus Armbruster }
2072292ddaeSMarkus Armbruster 
2082292ddaeSMarkus Armbruster QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
2095645b0f4SMarkus Armbruster                     const char *optstr)
210666daa68SMarkus Armbruster {
211666daa68SMarkus Armbruster     QemuOpts *opts;
212666daa68SMarkus Armbruster 
2132292ddaeSMarkus Armbruster     opts = drive_def(optstr);
214666daa68SMarkus Armbruster     if (!opts) {
215666daa68SMarkus Armbruster         return NULL;
216666daa68SMarkus Armbruster     }
2172292ddaeSMarkus Armbruster     if (type != IF_DEFAULT) {
218f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "if", if_name[type], &error_abort);
2192292ddaeSMarkus Armbruster     }
2202292ddaeSMarkus Armbruster     if (index >= 0) {
221a8b18f8fSMarkus Armbruster         qemu_opt_set_number(opts, "index", index, &error_abort);
2222292ddaeSMarkus Armbruster     }
223666daa68SMarkus Armbruster     if (file)
224f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "file", file, &error_abort);
225666daa68SMarkus Armbruster     return opts;
226666daa68SMarkus Armbruster }
227666daa68SMarkus Armbruster 
228666daa68SMarkus Armbruster DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
229666daa68SMarkus Armbruster {
23018e46a03SMarkus Armbruster     BlockBackend *blk;
231666daa68SMarkus Armbruster     DriveInfo *dinfo;
232666daa68SMarkus Armbruster 
23318e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
23418e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
23518e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type
23618e46a03SMarkus Armbruster             && dinfo->bus == bus && dinfo->unit == unit) {
237666daa68SMarkus Armbruster             return dinfo;
238666daa68SMarkus Armbruster         }
23918e46a03SMarkus Armbruster     }
240666daa68SMarkus Armbruster 
241666daa68SMarkus Armbruster     return NULL;
242666daa68SMarkus Armbruster }
243666daa68SMarkus Armbruster 
244720b8dc0SMarkus Armbruster void drive_check_orphaned(void)
245a66c9dc7SJohn Snow {
24618e46a03SMarkus Armbruster     BlockBackend *blk;
247a66c9dc7SJohn Snow     DriveInfo *dinfo;
248664cc623SMarkus Armbruster     Location loc;
249720b8dc0SMarkus Armbruster     bool orphans = false;
250a66c9dc7SJohn Snow 
25118e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
25218e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
253a7f53e26SMarkus Armbruster         if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
254a66c9dc7SJohn Snow             dinfo->type != IF_NONE) {
255664cc623SMarkus Armbruster             loc_push_none(&loc);
256664cc623SMarkus Armbruster             qemu_opts_loc_restore(dinfo->opts);
257720b8dc0SMarkus Armbruster             error_report("machine type does not support"
258664cc623SMarkus Armbruster                          " if=%s,bus=%d,unit=%d",
2595433c24fSMax Reitz                          if_name[dinfo->type], dinfo->bus, dinfo->unit);
260664cc623SMarkus Armbruster             loc_pop(&loc);
261720b8dc0SMarkus Armbruster             orphans = true;
262a66c9dc7SJohn Snow         }
263a66c9dc7SJohn Snow     }
264a66c9dc7SJohn Snow 
265720b8dc0SMarkus Armbruster     if (orphans) {
266720b8dc0SMarkus Armbruster         exit(1);
267720b8dc0SMarkus Armbruster     }
268a66c9dc7SJohn Snow }
269a66c9dc7SJohn Snow 
270f1bd51acSMarkus Armbruster DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
271f1bd51acSMarkus Armbruster {
272f1bd51acSMarkus Armbruster     return drive_get(type,
273f1bd51acSMarkus Armbruster                      drive_index_to_bus_id(type, index),
274f1bd51acSMarkus Armbruster                      drive_index_to_unit_id(type, index));
275f1bd51acSMarkus Armbruster }
276f1bd51acSMarkus Armbruster 
277666daa68SMarkus Armbruster int drive_get_max_bus(BlockInterfaceType type)
278666daa68SMarkus Armbruster {
279666daa68SMarkus Armbruster     int max_bus;
28018e46a03SMarkus Armbruster     BlockBackend *blk;
281666daa68SMarkus Armbruster     DriveInfo *dinfo;
282666daa68SMarkus Armbruster 
283666daa68SMarkus Armbruster     max_bus = -1;
28418e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
28518e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
28618e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
287666daa68SMarkus Armbruster             max_bus = dinfo->bus;
288666daa68SMarkus Armbruster         }
28918e46a03SMarkus Armbruster     }
290666daa68SMarkus Armbruster     return max_bus;
291666daa68SMarkus Armbruster }
292666daa68SMarkus Armbruster 
29313839974SMarkus Armbruster /* Get a block device.  This should only be used for single-drive devices
29413839974SMarkus Armbruster    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
29513839974SMarkus Armbruster    appropriate bus.  */
29613839974SMarkus Armbruster DriveInfo *drive_get_next(BlockInterfaceType type)
29713839974SMarkus Armbruster {
29813839974SMarkus Armbruster     static int next_block_unit[IF_COUNT];
29913839974SMarkus Armbruster 
30013839974SMarkus Armbruster     return drive_get(type, 0, next_block_unit[type]++);
30113839974SMarkus Armbruster }
30213839974SMarkus Armbruster 
303666daa68SMarkus Armbruster static void bdrv_format_print(void *opaque, const char *name)
304666daa68SMarkus Armbruster {
305cdcd4361SMarkus Armbruster     qemu_printf(" %s", name);
306666daa68SMarkus Armbruster }
307666daa68SMarkus Armbruster 
308aa398a5cSStefan Hajnoczi typedef struct {
309aa398a5cSStefan Hajnoczi     QEMUBH *bh;
310fa510ebfSFam Zheng     BlockDriverState *bs;
311fa510ebfSFam Zheng } BDRVPutRefBH;
312aa398a5cSStefan Hajnoczi 
313b681072dSKevin Wolf static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
314666daa68SMarkus Armbruster {
315666daa68SMarkus Armbruster     if (!strcmp(buf, "ignore")) {
31692aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_IGNORE;
317666daa68SMarkus Armbruster     } else if (!is_read && !strcmp(buf, "enospc")) {
31892aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_ENOSPC;
319666daa68SMarkus Armbruster     } else if (!strcmp(buf, "stop")) {
32092aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_STOP;
321666daa68SMarkus Armbruster     } else if (!strcmp(buf, "report")) {
32292aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_REPORT;
323666daa68SMarkus Armbruster     } else {
324b681072dSKevin Wolf         error_setg(errp, "'%s' invalid %s error action",
325666daa68SMarkus Armbruster                    buf, is_read ? "read" : "write");
326666daa68SMarkus Armbruster         return -1;
327666daa68SMarkus Armbruster     }
328666daa68SMarkus Armbruster }
329666daa68SMarkus Armbruster 
33040119effSAlberto Garcia static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
33140119effSAlberto Garcia                                   Error **errp)
33240119effSAlberto Garcia {
33340119effSAlberto Garcia     const QListEntry *entry;
33440119effSAlberto Garcia     for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
33540119effSAlberto Garcia         switch (qobject_type(entry->value)) {
33640119effSAlberto Garcia 
33740119effSAlberto Garcia         case QTYPE_QSTRING: {
33840119effSAlberto Garcia             unsigned long long length;
3397dc847ebSMax Reitz             const char *str = qstring_get_str(qobject_to(QString,
3407dc847ebSMax Reitz                                                          entry->value));
34140119effSAlberto Garcia             if (parse_uint_full(str, &length, 10) == 0 &&
34240119effSAlberto Garcia                 length > 0 && length <= UINT_MAX) {
34340119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
34440119effSAlberto Garcia             } else {
34540119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %s", str);
34640119effSAlberto Garcia                 return false;
34740119effSAlberto Garcia             }
34840119effSAlberto Garcia             break;
34940119effSAlberto Garcia         }
35040119effSAlberto Garcia 
35101b2ffceSMarc-André Lureau         case QTYPE_QNUM: {
3527dc847ebSMax Reitz             int64_t length = qnum_get_int(qobject_to(QNum, entry->value));
35301b2ffceSMarc-André Lureau 
35440119effSAlberto Garcia             if (length > 0 && length <= UINT_MAX) {
35540119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
35640119effSAlberto Garcia             } else {
35740119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %" PRId64, length);
35840119effSAlberto Garcia                 return false;
35940119effSAlberto Garcia             }
36040119effSAlberto Garcia             break;
36140119effSAlberto Garcia         }
36240119effSAlberto Garcia 
36340119effSAlberto Garcia         default:
36440119effSAlberto Garcia             error_setg(errp, "The specification of stats-intervals is invalid");
36540119effSAlberto Garcia             return false;
36640119effSAlberto Garcia         }
36740119effSAlberto Garcia     }
36840119effSAlberto Garcia     return true;
36940119effSAlberto Garcia }
37040119effSAlberto Garcia 
37133cb7dc8SKevin Wolf typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
37233cb7dc8SKevin Wolf 
373fbf8175eSMax Reitz /* All parameters but @opts are optional and may be set to NULL. */
374fbf8175eSMax Reitz static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
375fbf8175eSMax Reitz     const char **throttling_group, ThrottleConfig *throttle_cfg,
376fbf8175eSMax Reitz     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
377fbf8175eSMax Reitz {
378fbf8175eSMax Reitz     Error *local_error = NULL;
379fbf8175eSMax Reitz     const char *aio;
380fbf8175eSMax Reitz 
381fbf8175eSMax Reitz     if (bdrv_flags) {
382fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
383fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_COPY_ON_READ;
384fbf8175eSMax Reitz         }
385fbf8175eSMax Reitz 
386fbf8175eSMax Reitz         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
387fbf8175eSMax Reitz             if (!strcmp(aio, "native")) {
388fbf8175eSMax Reitz                 *bdrv_flags |= BDRV_O_NATIVE_AIO;
389fbf8175eSMax Reitz             } else if (!strcmp(aio, "threads")) {
390fbf8175eSMax Reitz                 /* this is the default */
391fbf8175eSMax Reitz             } else {
392fbf8175eSMax Reitz                error_setg(errp, "invalid aio option");
393fbf8175eSMax Reitz                return;
394fbf8175eSMax Reitz             }
395fbf8175eSMax Reitz         }
396fbf8175eSMax Reitz     }
397fbf8175eSMax Reitz 
398fbf8175eSMax Reitz     /* disk I/O throttling */
399fbf8175eSMax Reitz     if (throttling_group) {
400fbf8175eSMax Reitz         *throttling_group = qemu_opt_get(opts, "throttling.group");
401fbf8175eSMax Reitz     }
402fbf8175eSMax Reitz 
403fbf8175eSMax Reitz     if (throttle_cfg) {
4041588ab5dSAlberto Garcia         throttle_config_init(throttle_cfg);
405fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
406fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total", 0);
407fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
408fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read", 0);
409fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
410fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write", 0);
411fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
412fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total", 0);
413fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
414fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read", 0);
415fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
416fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write", 0);
417fbf8175eSMax Reitz 
418fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
419fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
420fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
421fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
422fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
423fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
424fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
425fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
426fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
427fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
428fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
429fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
430fbf8175eSMax Reitz 
4318a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
4328a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
4338a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length  =
4348a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
4358a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
4368a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
4378a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
4388a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
4398a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
4408a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
4418a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
4428a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
4438a0fc18dSAlberto Garcia 
444fbf8175eSMax Reitz         throttle_cfg->op_size =
445fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-size", 0);
446fbf8175eSMax Reitz 
447d5851089SAlberto Garcia         if (!throttle_is_valid(throttle_cfg, errp)) {
448fbf8175eSMax Reitz             return;
449fbf8175eSMax Reitz         }
450fbf8175eSMax Reitz     }
451fbf8175eSMax Reitz 
452fbf8175eSMax Reitz     if (detect_zeroes) {
453fbf8175eSMax Reitz         *detect_zeroes =
454f7abe0ecSMarc-André Lureau             qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
455fbf8175eSMax Reitz                             qemu_opt_get(opts, "detect-zeroes"),
456fbf8175eSMax Reitz                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
457fbf8175eSMax Reitz                             &local_error);
458fbf8175eSMax Reitz         if (local_error) {
459fbf8175eSMax Reitz             error_propagate(errp, local_error);
460fbf8175eSMax Reitz             return;
461fbf8175eSMax Reitz         }
462fbf8175eSMax Reitz     }
463fbf8175eSMax Reitz }
464fbf8175eSMax Reitz 
465f298d071SKevin Wolf /* Takes the ownership of bs_opts */
46618e46a03SMarkus Armbruster static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
467b681072dSKevin Wolf                                    Error **errp)
468666daa68SMarkus Armbruster {
469666daa68SMarkus Armbruster     const char *buf;
470666daa68SMarkus Armbruster     int bdrv_flags = 0;
471666daa68SMarkus Armbruster     int on_read_error, on_write_error;
472362e9299SAlberto Garcia     bool account_invalid, account_failed;
473f87a0e29SAlberto Garcia     bool writethrough, read_only;
47426f54e9aSMarkus Armbruster     BlockBackend *blk;
475a0f1eab1SMarkus Armbruster     BlockDriverState *bs;
476cc0681c4SBenoît Canet     ThrottleConfig cfg;
477666daa68SMarkus Armbruster     int snapshot = 0;
478c546194fSStefan Hajnoczi     Error *error = NULL;
4790006383eSKevin Wolf     QemuOpts *opts;
48040119effSAlberto Garcia     QDict *interval_dict = NULL;
48140119effSAlberto Garcia     QList *interval_list = NULL;
4820006383eSKevin Wolf     const char *id;
483fbf8175eSMax Reitz     BlockdevDetectZeroesOptions detect_zeroes =
484fbf8175eSMax Reitz         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
485fbf8175eSMax Reitz     const char *throttling_group = NULL;
486666daa68SMarkus Armbruster 
487f298d071SKevin Wolf     /* Check common options by copying from bs_opts to opts, all other options
488f298d071SKevin Wolf      * stay in bs_opts for processing by bdrv_open(). */
489f298d071SKevin Wolf     id = qdict_get_try_str(bs_opts, "id");
4900006383eSKevin Wolf     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
49184d18f06SMarkus Armbruster     if (error) {
492b681072dSKevin Wolf         error_propagate(errp, error);
4936376f952SMarkus Armbruster         goto err_no_opts;
4940006383eSKevin Wolf     }
4950006383eSKevin Wolf 
4960006383eSKevin Wolf     qemu_opts_absorb_qdict(opts, bs_opts, &error);
49784d18f06SMarkus Armbruster     if (error) {
498b681072dSKevin Wolf         error_propagate(errp, error);
499ec9c10d2SStefan Hajnoczi         goto early_err;
5000006383eSKevin Wolf     }
5010006383eSKevin Wolf 
5020006383eSKevin Wolf     if (id) {
5030006383eSKevin Wolf         qdict_del(bs_opts, "id");
5040006383eSKevin Wolf     }
5050006383eSKevin Wolf 
506666daa68SMarkus Armbruster     /* extract parameters */
507666daa68SMarkus Armbruster     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
508666daa68SMarkus Armbruster 
509362e9299SAlberto Garcia     account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
510362e9299SAlberto Garcia     account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
511362e9299SAlberto Garcia 
512e4b24b49SKevin Wolf     writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
513e4b24b49SKevin Wolf 
514ff356ee4SAlberto Garcia     id = qemu_opts_id(opts);
515ff356ee4SAlberto Garcia 
51640119effSAlberto Garcia     qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
51740119effSAlberto Garcia     qdict_array_split(interval_dict, &interval_list);
51840119effSAlberto Garcia 
51940119effSAlberto Garcia     if (qdict_size(interval_dict) != 0) {
52040119effSAlberto Garcia         error_setg(errp, "Invalid option stats-intervals.%s",
52140119effSAlberto Garcia                    qdict_first(interval_dict)->key);
52240119effSAlberto Garcia         goto early_err;
52340119effSAlberto Garcia     }
5242be5506fSAlberto Garcia 
525fbf8175eSMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
526fbf8175eSMax Reitz                                     &detect_zeroes, &error);
527fbf8175eSMax Reitz     if (error) {
528fbf8175eSMax Reitz         error_propagate(errp, error);
529ec9c10d2SStefan Hajnoczi         goto early_err;
530a9384affSPaolo Bonzini     }
531666daa68SMarkus Armbruster 
532666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
533c8057f95SPeter Maydell         if (is_help_option(buf)) {
534cdcd4361SMarkus Armbruster             qemu_printf("Supported formats:");
5359ac404c5SAndrey Shinkevich             bdrv_iterate_format(bdrv_format_print, NULL, false);
536cdcd4361SMarkus Armbruster             qemu_printf("\nSupported formats (read-only):");
5379ac404c5SAndrey Shinkevich             bdrv_iterate_format(bdrv_format_print, NULL, true);
538cdcd4361SMarkus Armbruster             qemu_printf("\n");
539ec9c10d2SStefan Hajnoczi             goto early_err;
540666daa68SMarkus Armbruster         }
54174fe54f2SKevin Wolf 
542e4342ce5SMax Reitz         if (qdict_haskey(bs_opts, "driver")) {
543e4342ce5SMax Reitz             error_setg(errp, "Cannot specify both 'driver' and 'format'");
544ec9c10d2SStefan Hajnoczi             goto early_err;
5456db5f5d6SMike Qiu         }
54646f5ac20SEric Blake         qdict_put_str(bs_opts, "driver", buf);
547666daa68SMarkus Armbruster     }
548666daa68SMarkus Armbruster 
54992aa5c6dSPaolo Bonzini     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
550666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
551b681072dSKevin Wolf         on_write_error = parse_block_error_action(buf, 0, &error);
55284d18f06SMarkus Armbruster         if (error) {
553b681072dSKevin Wolf             error_propagate(errp, error);
554ec9c10d2SStefan Hajnoczi             goto early_err;
555666daa68SMarkus Armbruster         }
556666daa68SMarkus Armbruster     }
557666daa68SMarkus Armbruster 
55892aa5c6dSPaolo Bonzini     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
559666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
560b681072dSKevin Wolf         on_read_error = parse_block_error_action(buf, 1, &error);
56184d18f06SMarkus Armbruster         if (error) {
562b681072dSKevin Wolf             error_propagate(errp, error);
563ec9c10d2SStefan Hajnoczi             goto early_err;
564666daa68SMarkus Armbruster         }
565666daa68SMarkus Armbruster     }
566666daa68SMarkus Armbruster 
567666daa68SMarkus Armbruster     if (snapshot) {
56891a097e7SKevin Wolf         bdrv_flags |= BDRV_O_SNAPSHOT;
569666daa68SMarkus Armbruster     }
570666daa68SMarkus Armbruster 
571f87a0e29SAlberto Garcia     read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
572f87a0e29SAlberto Garcia 
5735ec18f8cSMax Reitz     /* init */
57439c4ae94SKevin Wolf     if ((!file || !*file) && !qdict_size(bs_opts)) {
5755ec18f8cSMax Reitz         BlockBackendRootState *blk_rs;
5765ec18f8cSMax Reitz 
5776d0eb64dSKevin Wolf         blk = blk_new(0, BLK_PERM_ALL);
5785ec18f8cSMax Reitz         blk_rs = blk_get_root_state(blk);
5795ec18f8cSMax Reitz         blk_rs->open_flags    = bdrv_flags;
580f87a0e29SAlberto Garcia         blk_rs->read_only     = read_only;
5815ec18f8cSMax Reitz         blk_rs->detect_zeroes = detect_zeroes;
5825ec18f8cSMax Reitz 
583cb3e7f08SMarc-André Lureau         qobject_unref(bs_opts);
5845ec18f8cSMax Reitz     } else {
5855ec18f8cSMax Reitz         if (file && !*file) {
5865ec18f8cSMax Reitz             file = NULL;
5875ec18f8cSMax Reitz         }
5885ec18f8cSMax Reitz 
58991a097e7SKevin Wolf         /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
59091a097e7SKevin Wolf          * with other callers) rather than what we want as the real defaults.
59191a097e7SKevin Wolf          * Apply the defaults here instead. */
59291a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
59391a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
594f87a0e29SAlberto Garcia         qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
595f87a0e29SAlberto Garcia                               read_only ? "on" : "off");
5969384a444SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_AUTO_READ_ONLY, "on");
59772e775c7SKevin Wolf         assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
59891a097e7SKevin Wolf 
59912d5ee3aSKevin Wolf         if (runstate_check(RUN_STATE_INMIGRATE)) {
60012d5ee3aSKevin Wolf             bdrv_flags |= BDRV_O_INACTIVE;
60112d5ee3aSKevin Wolf         }
60212d5ee3aSKevin Wolf 
603efaa7c4eSMax Reitz         blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
604e4342ce5SMax Reitz         if (!blk) {
605e4342ce5SMax Reitz             goto err_no_bs_opts;
606e4342ce5SMax Reitz         }
607e4342ce5SMax Reitz         bs = blk_bs(blk);
6080006383eSKevin Wolf 
609e4342ce5SMax Reitz         bs->detect_zeroes = detect_zeroes;
610e4342ce5SMax Reitz 
6119caa6f3dSPaolo Bonzini         block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
6122be5506fSAlberto Garcia 
61340119effSAlberto Garcia         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
6142be5506fSAlberto Garcia             blk_unref(blk);
6152be5506fSAlberto Garcia             blk = NULL;
6162be5506fSAlberto Garcia             goto err_no_bs_opts;
6172be5506fSAlberto Garcia         }
6182be5506fSAlberto Garcia     }
6195ec18f8cSMax Reitz 
6207ca7f0f6SKevin Wolf     /* disk I/O throttling */
6217ca7f0f6SKevin Wolf     if (throttle_enabled(&cfg)) {
6227ca7f0f6SKevin Wolf         if (!throttling_group) {
623ff356ee4SAlberto Garcia             throttling_group = id;
6247ca7f0f6SKevin Wolf         }
6257ca7f0f6SKevin Wolf         blk_io_limits_enable(blk, throttling_group);
6267ca7f0f6SKevin Wolf         blk_set_io_limits(blk, &cfg);
6277ca7f0f6SKevin Wolf     }
6287ca7f0f6SKevin Wolf 
629e4b24b49SKevin Wolf     blk_set_enable_write_cache(blk, !writethrough);
6305ec18f8cSMax Reitz     blk_set_on_error(blk, on_read_error, on_write_error);
6310006383eSKevin Wolf 
632ff356ee4SAlberto Garcia     if (!monitor_add_blk(blk, id, errp)) {
633efaa7c4eSMax Reitz         blk_unref(blk);
634efaa7c4eSMax Reitz         blk = NULL;
635efaa7c4eSMax Reitz         goto err_no_bs_opts;
636efaa7c4eSMax Reitz     }
637efaa7c4eSMax Reitz 
638e4342ce5SMax Reitz err_no_bs_opts:
6390006383eSKevin Wolf     qemu_opts_del(opts);
640cb3e7f08SMarc-André Lureau     qobject_unref(interval_dict);
641cb3e7f08SMarc-André Lureau     qobject_unref(interval_list);
64218e46a03SMarkus Armbruster     return blk;
643a9ae2bffSMarkus Armbruster 
644ec9c10d2SStefan Hajnoczi early_err:
645ec9c10d2SStefan Hajnoczi     qemu_opts_del(opts);
646cb3e7f08SMarc-André Lureau     qobject_unref(interval_dict);
647cb3e7f08SMarc-André Lureau     qobject_unref(interval_list);
6486376f952SMarkus Armbruster err_no_opts:
649cb3e7f08SMarc-André Lureau     qobject_unref(bs_opts);
650a9ae2bffSMarkus Armbruster     return NULL;
651666daa68SMarkus Armbruster }
652666daa68SMarkus Armbruster 
653bd745e23SMax Reitz /* Takes the ownership of bs_opts */
654bd745e23SMax Reitz static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
655bd745e23SMax Reitz {
656bd745e23SMax Reitz     int bdrv_flags = 0;
657bd745e23SMax Reitz 
658a81d6164SKevin Wolf     /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
659a81d6164SKevin Wolf      * with other callers) rather than what we want as the real defaults.
660a81d6164SKevin Wolf      * Apply the defaults here instead. */
661a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
662a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
663f87a0e29SAlberto Garcia     qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
664a81d6164SKevin Wolf 
66512d5ee3aSKevin Wolf     if (runstate_check(RUN_STATE_INMIGRATE)) {
66612d5ee3aSKevin Wolf         bdrv_flags |= BDRV_O_INACTIVE;
66712d5ee3aSKevin Wolf     }
66812d5ee3aSKevin Wolf 
66974e1ae7cSKevin Wolf     return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
670bd745e23SMax Reitz }
671bd745e23SMax Reitz 
6729c4218e9SMax Reitz void blockdev_close_all_bdrv_states(void)
6739c4218e9SMax Reitz {
6749c4218e9SMax Reitz     BlockDriverState *bs, *next_bs;
6759c4218e9SMax Reitz 
6769c4218e9SMax Reitz     QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
6779c4218e9SMax Reitz         AioContext *ctx = bdrv_get_aio_context(bs);
6789c4218e9SMax Reitz 
6799c4218e9SMax Reitz         aio_context_acquire(ctx);
6809c4218e9SMax Reitz         bdrv_unref(bs);
6819c4218e9SMax Reitz         aio_context_release(ctx);
6829c4218e9SMax Reitz     }
6839c4218e9SMax Reitz }
6849c4218e9SMax Reitz 
685262b4e8fSMax Reitz /* Iterates over the list of monitor-owned BlockDriverStates */
686262b4e8fSMax Reitz BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
687262b4e8fSMax Reitz {
688262b4e8fSMax Reitz     return bs ? QTAILQ_NEXT(bs, monitor_list)
689262b4e8fSMax Reitz               : QTAILQ_FIRST(&monitor_bdrv_states);
690262b4e8fSMax Reitz }
691262b4e8fSMax Reitz 
6925abbf0eeSKevin Wolf static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
6935abbf0eeSKevin Wolf                             Error **errp)
69457975222SKevin Wolf {
69557975222SKevin Wolf     const char *value;
69657975222SKevin Wolf 
69757975222SKevin Wolf     value = qemu_opt_get(opts, from);
69857975222SKevin Wolf     if (value) {
6995abbf0eeSKevin Wolf         if (qemu_opt_find(opts, to)) {
7005abbf0eeSKevin Wolf             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
7015abbf0eeSKevin Wolf                        "same time", to, from);
7025abbf0eeSKevin Wolf             return;
7035abbf0eeSKevin Wolf         }
70420d6cd47SJun Li     }
70520d6cd47SJun Li 
70620d6cd47SJun Li     /* rename all items in opts */
70720d6cd47SJun Li     while ((value = qemu_opt_get(opts, from))) {
708f43e47dbSMarkus Armbruster         qemu_opt_set(opts, to, value, &error_abort);
70957975222SKevin Wolf         qemu_opt_unset(opts, from);
71057975222SKevin Wolf     }
71157975222SKevin Wolf }
71257975222SKevin Wolf 
71333cb7dc8SKevin Wolf QemuOptsList qemu_legacy_drive_opts = {
71433cb7dc8SKevin Wolf     .name = "drive",
71533cb7dc8SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
71633cb7dc8SKevin Wolf     .desc = {
71733cb7dc8SKevin Wolf         {
71887a899c5SKevin Wolf             .name = "bus",
71987a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
72087a899c5SKevin Wolf             .help = "bus number",
72187a899c5SKevin Wolf         },{
72287a899c5SKevin Wolf             .name = "unit",
72387a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
72487a899c5SKevin Wolf             .help = "unit number (i.e. lun for scsi)",
72587a899c5SKevin Wolf         },{
72687a899c5SKevin Wolf             .name = "index",
72787a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
72887a899c5SKevin Wolf             .help = "index number",
72987a899c5SKevin Wolf         },{
73033cb7dc8SKevin Wolf             .name = "media",
73133cb7dc8SKevin Wolf             .type = QEMU_OPT_STRING,
73233cb7dc8SKevin Wolf             .help = "media type (disk, cdrom)",
733593d464bSKevin Wolf         },{
734593d464bSKevin Wolf             .name = "if",
735593d464bSKevin Wolf             .type = QEMU_OPT_STRING,
736593d464bSKevin Wolf             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
737b41a7338SKevin Wolf         },{
738d095b465SMax Reitz             .name = "file",
739d095b465SMax Reitz             .type = QEMU_OPT_STRING,
740d095b465SMax Reitz             .help = "file name",
74133cb7dc8SKevin Wolf         },
7420ebd24e0SKevin Wolf 
7430ebd24e0SKevin Wolf         /* Options that are passed on, but have special semantics with -drive */
7440ebd24e0SKevin Wolf         {
7454e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
7460ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
7470ebd24e0SKevin Wolf             .help = "open drive file as read-only",
7480ebd24e0SKevin Wolf         },{
749ee13ed1cSKevin Wolf             .name = "rerror",
750ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
751ee13ed1cSKevin Wolf             .help = "read error action",
752ee13ed1cSKevin Wolf         },{
753ee13ed1cSKevin Wolf             .name = "werror",
754ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
755ee13ed1cSKevin Wolf             .help = "write error action",
756ee13ed1cSKevin Wolf         },{
7570ebd24e0SKevin Wolf             .name = "copy-on-read",
7580ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
7590ebd24e0SKevin Wolf             .help = "copy read data from backing file into image file",
7600ebd24e0SKevin Wolf         },
7610ebd24e0SKevin Wolf 
76233cb7dc8SKevin Wolf         { /* end of list */ }
76333cb7dc8SKevin Wolf     },
76433cb7dc8SKevin Wolf };
76533cb7dc8SKevin Wolf 
766c4f26c9fSMarkus Armbruster DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
767c4f26c9fSMarkus Armbruster                      Error **errp)
76857975222SKevin Wolf {
76929c4e2b5SKevin Wolf     const char *value;
77018e46a03SMarkus Armbruster     BlockBackend *blk;
77133cb7dc8SKevin Wolf     DriveInfo *dinfo = NULL;
772f298d071SKevin Wolf     QDict *bs_opts;
77333cb7dc8SKevin Wolf     QemuOpts *legacy_opts;
77433cb7dc8SKevin Wolf     DriveMediaType media = MEDIA_DISK;
775593d464bSKevin Wolf     BlockInterfaceType type;
77687a899c5SKevin Wolf     int max_devs, bus_id, unit_id, index;
777ee13ed1cSKevin Wolf     const char *werror, *rerror;
778a7fdbcf0SFam Zheng     bool read_only = false;
779a7fdbcf0SFam Zheng     bool copy_on_read;
780d095b465SMax Reitz     const char *filename;
78133cb7dc8SKevin Wolf     Error *local_err = NULL;
782247147fbSKevin Wolf     int i;
78329c4e2b5SKevin Wolf 
78457975222SKevin Wolf     /* Change legacy command line options into QMP ones */
785247147fbSKevin Wolf     static const struct {
786247147fbSKevin Wolf         const char *from;
787247147fbSKevin Wolf         const char *to;
788247147fbSKevin Wolf     } opt_renames[] = {
789247147fbSKevin Wolf         { "iops",           "throttling.iops-total" },
790247147fbSKevin Wolf         { "iops_rd",        "throttling.iops-read" },
791247147fbSKevin Wolf         { "iops_wr",        "throttling.iops-write" },
79257975222SKevin Wolf 
793247147fbSKevin Wolf         { "bps",            "throttling.bps-total" },
794247147fbSKevin Wolf         { "bps_rd",         "throttling.bps-read" },
795247147fbSKevin Wolf         { "bps_wr",         "throttling.bps-write" },
79657975222SKevin Wolf 
797247147fbSKevin Wolf         { "iops_max",       "throttling.iops-total-max" },
798247147fbSKevin Wolf         { "iops_rd_max",    "throttling.iops-read-max" },
799247147fbSKevin Wolf         { "iops_wr_max",    "throttling.iops-write-max" },
8003e9fab69SBenoît Canet 
801247147fbSKevin Wolf         { "bps_max",        "throttling.bps-total-max" },
802247147fbSKevin Wolf         { "bps_rd_max",     "throttling.bps-read-max" },
803247147fbSKevin Wolf         { "bps_wr_max",     "throttling.bps-write-max" },
8043e9fab69SBenoît Canet 
805247147fbSKevin Wolf         { "iops_size",      "throttling.iops-size" },
8062024c1dfSBenoît Canet 
80776f4afb4SAlberto Garcia         { "group",          "throttling.group" },
80876f4afb4SAlberto Garcia 
8094e200cf8SAlberto Garcia         { "readonly",       BDRV_OPT_READ_ONLY },
810247147fbSKevin Wolf     };
811247147fbSKevin Wolf 
812247147fbSKevin Wolf     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
8135abbf0eeSKevin Wolf         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
8145abbf0eeSKevin Wolf                         &local_err);
8155abbf0eeSKevin Wolf         if (local_err) {
816c4f26c9fSMarkus Armbruster             error_propagate(errp, local_err);
8175abbf0eeSKevin Wolf             return NULL;
8185abbf0eeSKevin Wolf         }
819247147fbSKevin Wolf     }
8200f227a94SKevin Wolf 
82129c4e2b5SKevin Wolf     value = qemu_opt_get(all_opts, "cache");
82229c4e2b5SKevin Wolf     if (value) {
82329c4e2b5SKevin Wolf         int flags = 0;
82404feb4a5SKevin Wolf         bool writethrough;
82529c4e2b5SKevin Wolf 
82604feb4a5SKevin Wolf         if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
827c4f26c9fSMarkus Armbruster             error_setg(errp, "invalid cache option");
82829c4e2b5SKevin Wolf             return NULL;
82929c4e2b5SKevin Wolf         }
83029c4e2b5SKevin Wolf 
83129c4e2b5SKevin Wolf         /* Specific options take precedence */
83254861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
83354861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
83404feb4a5SKevin Wolf                               !writethrough, &error_abort);
83529c4e2b5SKevin Wolf         }
83654861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
83754861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
838cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NOCACHE), &error_abort);
83929c4e2b5SKevin Wolf         }
84054861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
84154861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
842cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
84329c4e2b5SKevin Wolf         }
84429c4e2b5SKevin Wolf         qemu_opt_unset(all_opts, "cache");
84529c4e2b5SKevin Wolf     }
84629c4e2b5SKevin Wolf 
847f298d071SKevin Wolf     /* Get a QDict for processing the options */
848f298d071SKevin Wolf     bs_opts = qdict_new();
849f298d071SKevin Wolf     qemu_opts_to_qdict(all_opts, bs_opts);
850f298d071SKevin Wolf 
85187ea75d5SPeter Crosthwaite     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
85287ea75d5SPeter Crosthwaite                                    &error_abort);
85333cb7dc8SKevin Wolf     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
85484d18f06SMarkus Armbruster     if (local_err) {
855c4f26c9fSMarkus Armbruster         error_propagate(errp, local_err);
85633cb7dc8SKevin Wolf         goto fail;
85733cb7dc8SKevin Wolf     }
85833cb7dc8SKevin Wolf 
85933cb7dc8SKevin Wolf     /* Media type */
86033cb7dc8SKevin Wolf     value = qemu_opt_get(legacy_opts, "media");
86133cb7dc8SKevin Wolf     if (value) {
86233cb7dc8SKevin Wolf         if (!strcmp(value, "disk")) {
86333cb7dc8SKevin Wolf             media = MEDIA_DISK;
86433cb7dc8SKevin Wolf         } else if (!strcmp(value, "cdrom")) {
86533cb7dc8SKevin Wolf             media = MEDIA_CDROM;
866a7fdbcf0SFam Zheng             read_only = true;
86733cb7dc8SKevin Wolf         } else {
868c4f26c9fSMarkus Armbruster             error_setg(errp, "'%s' invalid media", value);
86933cb7dc8SKevin Wolf             goto fail;
87033cb7dc8SKevin Wolf         }
87133cb7dc8SKevin Wolf     }
87233cb7dc8SKevin Wolf 
8730ebd24e0SKevin Wolf     /* copy-on-read is disabled with a warning for read-only devices */
8744e200cf8SAlberto Garcia     read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
8750ebd24e0SKevin Wolf     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
8760ebd24e0SKevin Wolf 
8770ebd24e0SKevin Wolf     if (read_only && copy_on_read) {
8783dc6f869SAlistair Francis         warn_report("disabling copy-on-read on read-only drive");
8790ebd24e0SKevin Wolf         copy_on_read = false;
8800ebd24e0SKevin Wolf     }
8810ebd24e0SKevin Wolf 
88246f5ac20SEric Blake     qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
88346f5ac20SEric Blake     qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
8840ebd24e0SKevin Wolf 
885593d464bSKevin Wolf     /* Controller type */
886593d464bSKevin Wolf     value = qemu_opt_get(legacy_opts, "if");
887593d464bSKevin Wolf     if (value) {
888593d464bSKevin Wolf         for (type = 0;
889593d464bSKevin Wolf              type < IF_COUNT && strcmp(value, if_name[type]);
890593d464bSKevin Wolf              type++) {
891593d464bSKevin Wolf         }
892593d464bSKevin Wolf         if (type == IF_COUNT) {
893c4f26c9fSMarkus Armbruster             error_setg(errp, "unsupported bus type '%s'", value);
894593d464bSKevin Wolf             goto fail;
895593d464bSKevin Wolf         }
896593d464bSKevin Wolf     } else {
897593d464bSKevin Wolf         type = block_default_type;
898593d464bSKevin Wolf     }
899593d464bSKevin Wolf 
90087a899c5SKevin Wolf     /* Device address specified by bus/unit or index.
90187a899c5SKevin Wolf      * If none was specified, try to find the first free one. */
90287a899c5SKevin Wolf     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
90387a899c5SKevin Wolf     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
90487a899c5SKevin Wolf     index   = qemu_opt_get_number(legacy_opts, "index", -1);
90587a899c5SKevin Wolf 
90687a899c5SKevin Wolf     max_devs = if_max_devs[type];
90787a899c5SKevin Wolf 
90887a899c5SKevin Wolf     if (index != -1) {
90987a899c5SKevin Wolf         if (bus_id != 0 || unit_id != -1) {
910c4f26c9fSMarkus Armbruster             error_setg(errp, "index cannot be used with bus and unit");
91187a899c5SKevin Wolf             goto fail;
91287a899c5SKevin Wolf         }
91387a899c5SKevin Wolf         bus_id = drive_index_to_bus_id(type, index);
91487a899c5SKevin Wolf         unit_id = drive_index_to_unit_id(type, index);
91587a899c5SKevin Wolf     }
91687a899c5SKevin Wolf 
91787a899c5SKevin Wolf     if (unit_id == -1) {
91887a899c5SKevin Wolf        unit_id = 0;
91987a899c5SKevin Wolf        while (drive_get(type, bus_id, unit_id) != NULL) {
92087a899c5SKevin Wolf            unit_id++;
92187a899c5SKevin Wolf            if (max_devs && unit_id >= max_devs) {
92287a899c5SKevin Wolf                unit_id -= max_devs;
92387a899c5SKevin Wolf                bus_id++;
92487a899c5SKevin Wolf            }
92587a899c5SKevin Wolf        }
92687a899c5SKevin Wolf     }
92787a899c5SKevin Wolf 
92887a899c5SKevin Wolf     if (max_devs && unit_id >= max_devs) {
929c4f26c9fSMarkus Armbruster         error_setg(errp, "unit %d too big (max is %d)", unit_id, max_devs - 1);
93087a899c5SKevin Wolf         goto fail;
93187a899c5SKevin Wolf     }
93287a899c5SKevin Wolf 
93387a899c5SKevin Wolf     if (drive_get(type, bus_id, unit_id) != NULL) {
934c4f26c9fSMarkus Armbruster         error_setg(errp, "drive with bus=%d, unit=%d (index=%d) exists",
93587a899c5SKevin Wolf                    bus_id, unit_id, index);
93687a899c5SKevin Wolf         goto fail;
93787a899c5SKevin Wolf     }
93887a899c5SKevin Wolf 
93987a899c5SKevin Wolf     /* no id supplied -> create one */
94087a899c5SKevin Wolf     if (qemu_opts_id(all_opts) == NULL) {
94187a899c5SKevin Wolf         char *new_id;
94287a899c5SKevin Wolf         const char *mediastr = "";
94387a899c5SKevin Wolf         if (type == IF_IDE || type == IF_SCSI) {
94487a899c5SKevin Wolf             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
94587a899c5SKevin Wolf         }
94687a899c5SKevin Wolf         if (max_devs) {
94787a899c5SKevin Wolf             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
94887a899c5SKevin Wolf                                      mediastr, unit_id);
94987a899c5SKevin Wolf         } else {
95087a899c5SKevin Wolf             new_id = g_strdup_printf("%s%s%i", if_name[type],
95187a899c5SKevin Wolf                                      mediastr, unit_id);
95287a899c5SKevin Wolf         }
95346f5ac20SEric Blake         qdict_put_str(bs_opts, "id", new_id);
95487a899c5SKevin Wolf         g_free(new_id);
95587a899c5SKevin Wolf     }
95687a899c5SKevin Wolf 
957394c7d4dSKevin Wolf     /* Add virtio block device */
958394c7d4dSKevin Wolf     if (type == IF_VIRTIO) {
959394c7d4dSKevin Wolf         QemuOpts *devopts;
96087ea75d5SPeter Crosthwaite         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
96187ea75d5SPeter Crosthwaite                                    &error_abort);
962394c7d4dSKevin Wolf         if (arch_type == QEMU_ARCH_S390X) {
9631f68f1d3SAlexander Graf             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
964394c7d4dSKevin Wolf         } else {
965f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
966394c7d4dSKevin Wolf         }
967f43e47dbSMarkus Armbruster         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
968f43e47dbSMarkus Armbruster                      &error_abort);
969394c7d4dSKevin Wolf     }
970394c7d4dSKevin Wolf 
971d095b465SMax Reitz     filename = qemu_opt_get(legacy_opts, "file");
972d095b465SMax Reitz 
973ee13ed1cSKevin Wolf     /* Check werror/rerror compatibility with if=... */
974ee13ed1cSKevin Wolf     werror = qemu_opt_get(legacy_opts, "werror");
975ee13ed1cSKevin Wolf     if (werror != NULL) {
976ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
977ee13ed1cSKevin Wolf             type != IF_NONE) {
978c4f26c9fSMarkus Armbruster             error_setg(errp, "werror is not supported by this bus type");
979ee13ed1cSKevin Wolf             goto fail;
980ee13ed1cSKevin Wolf         }
98146f5ac20SEric Blake         qdict_put_str(bs_opts, "werror", werror);
982ee13ed1cSKevin Wolf     }
983ee13ed1cSKevin Wolf 
984ee13ed1cSKevin Wolf     rerror = qemu_opt_get(legacy_opts, "rerror");
985ee13ed1cSKevin Wolf     if (rerror != NULL) {
986ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
987ee13ed1cSKevin Wolf             type != IF_NONE) {
988c4f26c9fSMarkus Armbruster             error_setg(errp, "rerror is not supported by this bus type");
989ee13ed1cSKevin Wolf             goto fail;
990ee13ed1cSKevin Wolf         }
99146f5ac20SEric Blake         qdict_put_str(bs_opts, "rerror", rerror);
992ee13ed1cSKevin Wolf     }
993ee13ed1cSKevin Wolf 
9942d246f01SKevin Wolf     /* Actual block device init: Functionality shared with blockdev-add */
99518e46a03SMarkus Armbruster     blk = blockdev_init(filename, bs_opts, &local_err);
9963cb0e25cSMarkus Armbruster     bs_opts = NULL;
99718e46a03SMarkus Armbruster     if (!blk) {
998c4f26c9fSMarkus Armbruster         error_propagate(errp, local_err);
9992d246f01SKevin Wolf         goto fail;
1000b681072dSKevin Wolf     } else {
100184d18f06SMarkus Armbruster         assert(!local_err);
10022d246f01SKevin Wolf     }
10032d246f01SKevin Wolf 
100426f8b3a8SMarkus Armbruster     /* Create legacy DriveInfo */
100526f8b3a8SMarkus Armbruster     dinfo = g_malloc0(sizeof(*dinfo));
1006f298d071SKevin Wolf     dinfo->opts = all_opts;
10072d246f01SKevin Wolf 
1008ee13ed1cSKevin Wolf     dinfo->type = type;
100987a899c5SKevin Wolf     dinfo->bus = bus_id;
101087a899c5SKevin Wolf     dinfo->unit = unit_id;
1011bcf83158SKevin Wolf 
101226f8b3a8SMarkus Armbruster     blk_set_legacy_dinfo(blk, dinfo);
101326f8b3a8SMarkus Armbruster 
1014e34ef046SKevin Wolf     switch(type) {
1015e34ef046SKevin Wolf     case IF_IDE:
1016e34ef046SKevin Wolf     case IF_SCSI:
1017e34ef046SKevin Wolf     case IF_XEN:
1018e34ef046SKevin Wolf     case IF_NONE:
1019e34ef046SKevin Wolf         dinfo->media_cd = media == MEDIA_CDROM;
1020e34ef046SKevin Wolf         break;
1021e34ef046SKevin Wolf     default:
1022e34ef046SKevin Wolf         break;
1023e34ef046SKevin Wolf     }
1024e34ef046SKevin Wolf 
10252d246f01SKevin Wolf fail:
102633cb7dc8SKevin Wolf     qemu_opts_del(legacy_opts);
1027cb3e7f08SMarc-André Lureau     qobject_unref(bs_opts);
10282d246f01SKevin Wolf     return dinfo;
102957975222SKevin Wolf }
103057975222SKevin Wolf 
1031b6c1bae5SKevin Wolf static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1032b6c1bae5SKevin Wolf {
1033b6c1bae5SKevin Wolf     BlockDriverState *bs;
1034b6c1bae5SKevin Wolf 
1035b6c1bae5SKevin Wolf     bs = bdrv_lookup_bs(name, name, errp);
1036b6c1bae5SKevin Wolf     if (bs == NULL) {
1037b6c1bae5SKevin Wolf         return NULL;
1038b6c1bae5SKevin Wolf     }
1039b6c1bae5SKevin Wolf 
1040b6c1bae5SKevin Wolf     if (!bdrv_is_root_node(bs)) {
1041b6c1bae5SKevin Wolf         error_setg(errp, "Need a root block node");
1042b6c1bae5SKevin Wolf         return NULL;
1043b6c1bae5SKevin Wolf     }
1044b6c1bae5SKevin Wolf 
1045b6c1bae5SKevin Wolf     if (!bdrv_is_inserted(bs)) {
1046b6c1bae5SKevin Wolf         error_setg(errp, "Device has no medium");
1047b6c1bae5SKevin Wolf         return NULL;
1048b6c1bae5SKevin Wolf     }
1049b6c1bae5SKevin Wolf 
1050b6c1bae5SKevin Wolf     return bs;
1051b6c1bae5SKevin Wolf }
1052b6c1bae5SKevin Wolf 
1053b33945cfSKevin Wolf static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1054b33945cfSKevin Wolf                                  Error **errp)
1055b33945cfSKevin Wolf {
1056b33945cfSKevin Wolf     BlockBackend *blk;
1057b33945cfSKevin Wolf 
1058b33945cfSKevin Wolf     if (!blk_name == !qdev_id) {
1059b33945cfSKevin Wolf         error_setg(errp, "Need exactly one of 'device' and 'id'");
1060b33945cfSKevin Wolf         return NULL;
1061b33945cfSKevin Wolf     }
1062b33945cfSKevin Wolf 
1063b33945cfSKevin Wolf     if (qdev_id) {
1064b33945cfSKevin Wolf         blk = blk_by_qdev_id(qdev_id, errp);
1065b33945cfSKevin Wolf     } else {
1066b33945cfSKevin Wolf         blk = blk_by_name(blk_name);
1067b33945cfSKevin Wolf         if (blk == NULL) {
1068b33945cfSKevin Wolf             error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1069b33945cfSKevin Wolf                       "Device '%s' not found", blk_name);
1070b33945cfSKevin Wolf         }
1071b33945cfSKevin Wolf     }
1072b33945cfSKevin Wolf 
1073b33945cfSKevin Wolf     return blk;
1074b33945cfSKevin Wolf }
1075b33945cfSKevin Wolf 
10763e5a50d6SMarkus Armbruster void hmp_commit(Monitor *mon, const QDict *qdict)
1077666daa68SMarkus Armbruster {
1078666daa68SMarkus Armbruster     const char *device = qdict_get_str(qdict, "device");
1079a0e8544cSFam Zheng     BlockBackend *blk;
10802d3735d3SStefan Hajnoczi     int ret;
10812d3735d3SStefan Hajnoczi 
1082e8877497SStefan Hajnoczi     if (!strcmp(device, "all")) {
1083da31d594SMax Reitz         ret = blk_commit_all();
1084e8877497SStefan Hajnoczi     } else {
108584aa0140SStefan Hajnoczi         BlockDriverState *bs;
108684aa0140SStefan Hajnoczi         AioContext *aio_context;
108784aa0140SStefan Hajnoczi 
1088a0e8544cSFam Zheng         blk = blk_by_name(device);
1089a0e8544cSFam Zheng         if (!blk) {
109058513bdeSJeff Cody             monitor_printf(mon, "Device '%s' not found\n", device);
1091ac59eb95SMarkus Armbruster             return;
10926ab4b5abSMarkus Armbruster         }
10935433c24fSMax Reitz         if (!blk_is_available(blk)) {
10945433c24fSMax Reitz             monitor_printf(mon, "Device '%s' has no medium\n", device);
10955433c24fSMax Reitz             return;
10965433c24fSMax Reitz         }
109784aa0140SStefan Hajnoczi 
109884aa0140SStefan Hajnoczi         bs = blk_bs(blk);
109984aa0140SStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
110084aa0140SStefan Hajnoczi         aio_context_acquire(aio_context);
110184aa0140SStefan Hajnoczi 
110284aa0140SStefan Hajnoczi         ret = bdrv_commit(bs);
110384aa0140SStefan Hajnoczi 
110484aa0140SStefan Hajnoczi         aio_context_release(aio_context);
11052d3735d3SStefan Hajnoczi     }
110658513bdeSJeff Cody     if (ret < 0) {
110758513bdeSJeff Cody         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
110858513bdeSJeff Cody                        strerror(-ret));
1109666daa68SMarkus Armbruster     }
1110666daa68SMarkus Armbruster }
1111666daa68SMarkus Armbruster 
111210f75907SEric Blake static void blockdev_do_action(TransactionAction *action, Error **errp)
11136cc2a415SPaolo Bonzini {
1114c8a83e85SKevin Wolf     TransactionActionList list;
11156cc2a415SPaolo Bonzini 
111610f75907SEric Blake     list.value = action;
11176cc2a415SPaolo Bonzini     list.next = NULL;
111894d16a64SJohn Snow     qmp_transaction(&list, false, NULL, errp);
11196cc2a415SPaolo Bonzini }
11206cc2a415SPaolo Bonzini 
11210901f67eSBenoît Canet void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
11220901f67eSBenoît Canet                                 bool has_node_name, const char *node_name,
11230901f67eSBenoît Canet                                 const char *snapshot_file,
11240901f67eSBenoît Canet                                 bool has_snapshot_node_name,
11250901f67eSBenoît Canet                                 const char *snapshot_node_name,
11266106e249SLuiz Capitulino                                 bool has_format, const char *format,
11270901f67eSBenoît Canet                                 bool has_mode, NewImageMode mode, Error **errp)
1128f8882568SJes Sorensen {
1129a911e6aeSAlberto Garcia     BlockdevSnapshotSync snapshot = {
11300901f67eSBenoît Canet         .has_device = has_device,
11316cc2a415SPaolo Bonzini         .device = (char *) device,
11320901f67eSBenoît Canet         .has_node_name = has_node_name,
11330901f67eSBenoît Canet         .node_name = (char *) node_name,
11346cc2a415SPaolo Bonzini         .snapshot_file = (char *) snapshot_file,
11350901f67eSBenoît Canet         .has_snapshot_node_name = has_snapshot_node_name,
11360901f67eSBenoît Canet         .snapshot_node_name = (char *) snapshot_node_name,
11376cc2a415SPaolo Bonzini         .has_format = has_format,
11386cc2a415SPaolo Bonzini         .format = (char *) format,
11396cc2a415SPaolo Bonzini         .has_mode = has_mode,
11406cc2a415SPaolo Bonzini         .mode = mode,
11416cc2a415SPaolo Bonzini     };
114210f75907SEric Blake     TransactionAction action = {
114310f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
114432bafa8fSEric Blake         .u.blockdev_snapshot_sync.data = &snapshot,
114510f75907SEric Blake     };
114610f75907SEric Blake     blockdev_do_action(&action, errp);
1147f8882568SJes Sorensen }
1148f8882568SJes Sorensen 
114943de7e2dSAlberto Garcia void qmp_blockdev_snapshot(const char *node, const char *overlay,
115043de7e2dSAlberto Garcia                            Error **errp)
115143de7e2dSAlberto Garcia {
115243de7e2dSAlberto Garcia     BlockdevSnapshot snapshot_data = {
115343de7e2dSAlberto Garcia         .node = (char *) node,
115443de7e2dSAlberto Garcia         .overlay = (char *) overlay
115543de7e2dSAlberto Garcia     };
115610f75907SEric Blake     TransactionAction action = {
115710f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
115832bafa8fSEric Blake         .u.blockdev_snapshot.data = &snapshot_data,
115910f75907SEric Blake     };
116010f75907SEric Blake     blockdev_do_action(&action, errp);
116143de7e2dSAlberto Garcia }
116243de7e2dSAlberto Garcia 
1163f323bc9eSWenchao Xia void qmp_blockdev_snapshot_internal_sync(const char *device,
1164f323bc9eSWenchao Xia                                          const char *name,
1165f323bc9eSWenchao Xia                                          Error **errp)
1166f323bc9eSWenchao Xia {
1167f323bc9eSWenchao Xia     BlockdevSnapshotInternal snapshot = {
1168f323bc9eSWenchao Xia         .device = (char *) device,
1169f323bc9eSWenchao Xia         .name = (char *) name
1170f323bc9eSWenchao Xia     };
117110f75907SEric Blake     TransactionAction action = {
117210f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
117332bafa8fSEric Blake         .u.blockdev_snapshot_internal_sync.data = &snapshot,
117410f75907SEric Blake     };
117510f75907SEric Blake     blockdev_do_action(&action, errp);
1176f323bc9eSWenchao Xia }
1177f323bc9eSWenchao Xia 
117844e3e053SWenchao Xia SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
117944e3e053SWenchao Xia                                                          bool has_id,
118044e3e053SWenchao Xia                                                          const char *id,
118144e3e053SWenchao Xia                                                          bool has_name,
118244e3e053SWenchao Xia                                                          const char *name,
118344e3e053SWenchao Xia                                                          Error **errp)
118444e3e053SWenchao Xia {
1185a0e8544cSFam Zheng     BlockDriverState *bs;
11864ef3982aSStefan Hajnoczi     AioContext *aio_context;
118744e3e053SWenchao Xia     QEMUSnapshotInfo sn;
118844e3e053SWenchao Xia     Error *local_err = NULL;
118944e3e053SWenchao Xia     SnapshotInfo *info = NULL;
119044e3e053SWenchao Xia     int ret;
119144e3e053SWenchao Xia 
11922dfb4c03SKevin Wolf     bs = qmp_get_root_bs(device, errp);
11932dfb4c03SKevin Wolf     if (!bs) {
119444e3e053SWenchao Xia         return NULL;
119544e3e053SWenchao Xia     }
11962dfb4c03SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
11975433c24fSMax Reitz     aio_context_acquire(aio_context);
119844e3e053SWenchao Xia 
119944e3e053SWenchao Xia     if (!has_id) {
120044e3e053SWenchao Xia         id = NULL;
120144e3e053SWenchao Xia     }
120244e3e053SWenchao Xia 
120344e3e053SWenchao Xia     if (!has_name) {
120444e3e053SWenchao Xia         name = NULL;
120544e3e053SWenchao Xia     }
120644e3e053SWenchao Xia 
120744e3e053SWenchao Xia     if (!id && !name) {
120844e3e053SWenchao Xia         error_setg(errp, "Name or id must be provided");
12095433c24fSMax Reitz         goto out_aio_context;
121044e3e053SWenchao Xia     }
121144e3e053SWenchao Xia 
12120b928854SStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
12130b928854SStefan Hajnoczi         goto out_aio_context;
12140b928854SStefan Hajnoczi     }
12150b928854SStefan Hajnoczi 
121644e3e053SWenchao Xia     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
121784d18f06SMarkus Armbruster     if (local_err) {
121844e3e053SWenchao Xia         error_propagate(errp, local_err);
12194ef3982aSStefan Hajnoczi         goto out_aio_context;
122044e3e053SWenchao Xia     }
122144e3e053SWenchao Xia     if (!ret) {
122244e3e053SWenchao Xia         error_setg(errp,
122344e3e053SWenchao Xia                    "Snapshot with id '%s' and name '%s' does not exist on "
122444e3e053SWenchao Xia                    "device '%s'",
122544e3e053SWenchao Xia                    STR_OR_NULL(id), STR_OR_NULL(name), device);
12264ef3982aSStefan Hajnoczi         goto out_aio_context;
122744e3e053SWenchao Xia     }
122844e3e053SWenchao Xia 
122944e3e053SWenchao Xia     bdrv_snapshot_delete(bs, id, name, &local_err);
123084d18f06SMarkus Armbruster     if (local_err) {
123144e3e053SWenchao Xia         error_propagate(errp, local_err);
12324ef3982aSStefan Hajnoczi         goto out_aio_context;
123344e3e053SWenchao Xia     }
123444e3e053SWenchao Xia 
12354ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
12364ef3982aSStefan Hajnoczi 
12375839e53bSMarkus Armbruster     info = g_new0(SnapshotInfo, 1);
123844e3e053SWenchao Xia     info->id = g_strdup(sn.id_str);
123944e3e053SWenchao Xia     info->name = g_strdup(sn.name);
124044e3e053SWenchao Xia     info->date_nsec = sn.date_nsec;
124144e3e053SWenchao Xia     info->date_sec = sn.date_sec;
124244e3e053SWenchao Xia     info->vm_state_size = sn.vm_state_size;
124344e3e053SWenchao Xia     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
124444e3e053SWenchao Xia     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
124544e3e053SWenchao Xia 
124644e3e053SWenchao Xia     return info;
12474ef3982aSStefan Hajnoczi 
12484ef3982aSStefan Hajnoczi out_aio_context:
12494ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
12504ef3982aSStefan Hajnoczi     return NULL;
125144e3e053SWenchao Xia }
12528802d1fdSJeff Cody 
1253341ebc2fSJohn Snow /**
1254341ebc2fSJohn Snow  * block_dirty_bitmap_lookup:
1255341ebc2fSJohn Snow  * Return a dirty bitmap (if present), after validating
1256341ebc2fSJohn Snow  * the node reference and bitmap names.
1257341ebc2fSJohn Snow  *
1258341ebc2fSJohn Snow  * @node: The name of the BDS node to search for bitmaps
1259341ebc2fSJohn Snow  * @name: The name of the bitmap to search for
1260341ebc2fSJohn Snow  * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1261341ebc2fSJohn Snow  * @errp: Output pointer for error information. Can be NULL.
1262341ebc2fSJohn Snow  *
1263341ebc2fSJohn Snow  * @return: A bitmap object on success, or NULL on failure.
1264341ebc2fSJohn Snow  */
1265341ebc2fSJohn Snow static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1266341ebc2fSJohn Snow                                                   const char *name,
1267341ebc2fSJohn Snow                                                   BlockDriverState **pbs,
1268341ebc2fSJohn Snow                                                   Error **errp)
1269341ebc2fSJohn Snow {
1270341ebc2fSJohn Snow     BlockDriverState *bs;
1271341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
1272341ebc2fSJohn Snow 
1273341ebc2fSJohn Snow     if (!node) {
1274341ebc2fSJohn Snow         error_setg(errp, "Node cannot be NULL");
1275341ebc2fSJohn Snow         return NULL;
1276341ebc2fSJohn Snow     }
1277341ebc2fSJohn Snow     if (!name) {
1278341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be NULL");
1279341ebc2fSJohn Snow         return NULL;
1280341ebc2fSJohn Snow     }
1281341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, NULL);
1282341ebc2fSJohn Snow     if (!bs) {
1283341ebc2fSJohn Snow         error_setg(errp, "Node '%s' not found", node);
1284341ebc2fSJohn Snow         return NULL;
1285341ebc2fSJohn Snow     }
1286341ebc2fSJohn Snow 
1287341ebc2fSJohn Snow     bitmap = bdrv_find_dirty_bitmap(bs, name);
1288341ebc2fSJohn Snow     if (!bitmap) {
1289341ebc2fSJohn Snow         error_setg(errp, "Dirty bitmap '%s' not found", name);
12902119882cSPaolo Bonzini         return NULL;
1291341ebc2fSJohn Snow     }
1292341ebc2fSJohn Snow 
1293341ebc2fSJohn Snow     if (pbs) {
1294341ebc2fSJohn Snow         *pbs = bs;
1295341ebc2fSJohn Snow     }
1296341ebc2fSJohn Snow 
1297341ebc2fSJohn Snow     return bitmap;
1298341ebc2fSJohn Snow }
1299341ebc2fSJohn Snow 
1300b756b9ceSStefan Hajnoczi /* New and old BlockDriverState structs for atomic group operations */
1301ba0c86a3SWenchao Xia 
130250f43f0fSJohn Snow typedef struct BlkActionState BlkActionState;
1303ba0c86a3SWenchao Xia 
130450f43f0fSJohn Snow /**
130550f43f0fSJohn Snow  * BlkActionOps:
130650f43f0fSJohn Snow  * Table of operations that define an Action.
130750f43f0fSJohn Snow  *
130850f43f0fSJohn Snow  * @instance_size: Size of state struct, in bytes.
130950f43f0fSJohn Snow  * @prepare: Prepare the work, must NOT be NULL.
131050f43f0fSJohn Snow  * @commit: Commit the changes, can be NULL.
131150f43f0fSJohn Snow  * @abort: Abort the changes on fail, can be NULL.
131250f43f0fSJohn Snow  * @clean: Clean up resources after all transaction actions have called
131350f43f0fSJohn Snow  *         commit() or abort(). Can be NULL.
131450f43f0fSJohn Snow  *
131550f43f0fSJohn Snow  * Only prepare() may fail. In a single transaction, only one of commit() or
131650f43f0fSJohn Snow  * abort() will be called. clean() will always be called if it is present.
1317ba0c86a3SWenchao Xia  */
131850f43f0fSJohn Snow typedef struct BlkActionOps {
131950f43f0fSJohn Snow     size_t instance_size;
132050f43f0fSJohn Snow     void (*prepare)(BlkActionState *common, Error **errp);
132150f43f0fSJohn Snow     void (*commit)(BlkActionState *common);
132250f43f0fSJohn Snow     void (*abort)(BlkActionState *common);
132350f43f0fSJohn Snow     void (*clean)(BlkActionState *common);
132450f43f0fSJohn Snow } BlkActionOps;
132550f43f0fSJohn Snow 
132650f43f0fSJohn Snow /**
132750f43f0fSJohn Snow  * BlkActionState:
132850f43f0fSJohn Snow  * Describes one Action's state within a Transaction.
132950f43f0fSJohn Snow  *
133050f43f0fSJohn Snow  * @action: QAPI-defined enum identifying which Action to perform.
133150f43f0fSJohn Snow  * @ops: Table of ActionOps this Action can perform.
133294d16a64SJohn Snow  * @block_job_txn: Transaction which this action belongs to.
133350f43f0fSJohn Snow  * @entry: List membership for all Actions in this Transaction.
133450f43f0fSJohn Snow  *
133550f43f0fSJohn Snow  * This structure must be arranged as first member in a subclassed type,
133650f43f0fSJohn Snow  * assuming that the compiler will also arrange it to the same offsets as the
133750f43f0fSJohn Snow  * base class.
133850f43f0fSJohn Snow  */
133950f43f0fSJohn Snow struct BlkActionState {
1340c8a83e85SKevin Wolf     TransactionAction *action;
134150f43f0fSJohn Snow     const BlkActionOps *ops;
134262c9e416SKevin Wolf     JobTxn *block_job_txn;
134394d16a64SJohn Snow     TransactionProperties *txn_props;
1344f4de0f8cSJohn Snow     QTAILQ_ENTRY(BlkActionState) entry;
1345ba0c86a3SWenchao Xia };
1346ba0c86a3SWenchao Xia 
1347bbe86010SWenchao Xia /* internal snapshot private data */
1348bbe86010SWenchao Xia typedef struct InternalSnapshotState {
134950f43f0fSJohn Snow     BlkActionState common;
1350bbe86010SWenchao Xia     BlockDriverState *bs;
1351bbe86010SWenchao Xia     QEMUSnapshotInfo sn;
1352507306ccSFam Zheng     bool created;
1353bbe86010SWenchao Xia } InternalSnapshotState;
1354bbe86010SWenchao Xia 
135594d16a64SJohn Snow 
135694d16a64SJohn Snow static int action_check_completion_mode(BlkActionState *s, Error **errp)
135794d16a64SJohn Snow {
135894d16a64SJohn Snow     if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
135994d16a64SJohn Snow         error_setg(errp,
136094d16a64SJohn Snow                    "Action '%s' does not support Transaction property "
136194d16a64SJohn Snow                    "completion-mode = %s",
1362977c736fSMarkus Armbruster                    TransactionActionKind_str(s->action->type),
1363977c736fSMarkus Armbruster                    ActionCompletionMode_str(s->txn_props->completion_mode));
136494d16a64SJohn Snow         return -1;
136594d16a64SJohn Snow     }
136694d16a64SJohn Snow     return 0;
136794d16a64SJohn Snow }
136894d16a64SJohn Snow 
136950f43f0fSJohn Snow static void internal_snapshot_prepare(BlkActionState *common,
1370bbe86010SWenchao Xia                                       Error **errp)
1371bbe86010SWenchao Xia {
1372f70edf99SMarkus Armbruster     Error *local_err = NULL;
1373bbe86010SWenchao Xia     const char *device;
1374bbe86010SWenchao Xia     const char *name;
1375bbe86010SWenchao Xia     BlockDriverState *bs;
1376bbe86010SWenchao Xia     QEMUSnapshotInfo old_sn, *sn;
1377bbe86010SWenchao Xia     bool ret;
1378bbe86010SWenchao Xia     qemu_timeval tv;
1379bbe86010SWenchao Xia     BlockdevSnapshotInternal *internal;
1380bbe86010SWenchao Xia     InternalSnapshotState *state;
1381a36e458cSStefan Hajnoczi     AioContext *aio_context;
1382bbe86010SWenchao Xia     int ret1;
1383bbe86010SWenchao Xia 
13846a8f9661SEric Blake     g_assert(common->action->type ==
1385bbe86010SWenchao Xia              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
138632bafa8fSEric Blake     internal = common->action->u.blockdev_snapshot_internal_sync.data;
1387bbe86010SWenchao Xia     state = DO_UPCAST(InternalSnapshotState, common, common);
1388bbe86010SWenchao Xia 
1389bbe86010SWenchao Xia     /* 1. parse input */
1390bbe86010SWenchao Xia     device = internal->device;
1391bbe86010SWenchao Xia     name = internal->name;
1392bbe86010SWenchao Xia 
1393bbe86010SWenchao Xia     /* 2. check for validation */
139494d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
139594d16a64SJohn Snow         return;
139694d16a64SJohn Snow     }
139794d16a64SJohn Snow 
139875dfd402SKevin Wolf     bs = qmp_get_root_bs(device, errp);
139975dfd402SKevin Wolf     if (!bs) {
1400bbe86010SWenchao Xia         return;
1401bbe86010SWenchao Xia     }
1402bbe86010SWenchao Xia 
1403a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
1404a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
14055d6e96efSStefan Hajnoczi 
1406507306ccSFam Zheng     state->bs = bs;
1407a36e458cSStefan Hajnoczi 
1408a36e458cSStefan Hajnoczi     /* Paired with .clean() */
1409507306ccSFam Zheng     bdrv_drained_begin(bs);
1410507306ccSFam Zheng 
14113dc7ca3cSStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1412a36e458cSStefan Hajnoczi         goto out;
14133dc7ca3cSStefan Hajnoczi     }
14143dc7ca3cSStefan Hajnoczi 
1415bbe86010SWenchao Xia     if (bdrv_is_read_only(bs)) {
141681e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
1417a36e458cSStefan Hajnoczi         goto out;
1418bbe86010SWenchao Xia     }
1419bbe86010SWenchao Xia 
1420bbe86010SWenchao Xia     if (!bdrv_can_snapshot(bs)) {
142181e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by device '%s' "
142281e5f78aSAlberto Garcia                    "does not support internal snapshots",
142381e5f78aSAlberto Garcia                    bs->drv->format_name, device);
1424a36e458cSStefan Hajnoczi         goto out;
1425bbe86010SWenchao Xia     }
1426bbe86010SWenchao Xia 
1427bbe86010SWenchao Xia     if (!strlen(name)) {
1428bbe86010SWenchao Xia         error_setg(errp, "Name is empty");
1429a36e458cSStefan Hajnoczi         goto out;
1430bbe86010SWenchao Xia     }
1431bbe86010SWenchao Xia 
1432bbe86010SWenchao Xia     /* check whether a snapshot with name exist */
1433f70edf99SMarkus Armbruster     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1434f70edf99SMarkus Armbruster                                             &local_err);
1435f70edf99SMarkus Armbruster     if (local_err) {
1436f70edf99SMarkus Armbruster         error_propagate(errp, local_err);
1437a36e458cSStefan Hajnoczi         goto out;
1438bbe86010SWenchao Xia     } else if (ret) {
1439bbe86010SWenchao Xia         error_setg(errp,
1440bbe86010SWenchao Xia                    "Snapshot with name '%s' already exists on device '%s'",
1441bbe86010SWenchao Xia                    name, device);
1442a36e458cSStefan Hajnoczi         goto out;
1443bbe86010SWenchao Xia     }
1444bbe86010SWenchao Xia 
1445bbe86010SWenchao Xia     /* 3. take the snapshot */
1446bbe86010SWenchao Xia     sn = &state->sn;
1447bbe86010SWenchao Xia     pstrcpy(sn->name, sizeof(sn->name), name);
1448bbe86010SWenchao Xia     qemu_gettimeofday(&tv);
1449bbe86010SWenchao Xia     sn->date_sec = tv.tv_sec;
1450bbe86010SWenchao Xia     sn->date_nsec = tv.tv_usec * 1000;
1451bbe86010SWenchao Xia     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1452bbe86010SWenchao Xia 
1453bbe86010SWenchao Xia     ret1 = bdrv_snapshot_create(bs, sn);
1454bbe86010SWenchao Xia     if (ret1 < 0) {
1455bbe86010SWenchao Xia         error_setg_errno(errp, -ret1,
1456bbe86010SWenchao Xia                          "Failed to create snapshot '%s' on device '%s'",
1457bbe86010SWenchao Xia                          name, device);
1458a36e458cSStefan Hajnoczi         goto out;
1459bbe86010SWenchao Xia     }
1460bbe86010SWenchao Xia 
1461bbe86010SWenchao Xia     /* 4. succeed, mark a snapshot is created */
1462507306ccSFam Zheng     state->created = true;
1463a36e458cSStefan Hajnoczi 
1464a36e458cSStefan Hajnoczi out:
1465a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
1466bbe86010SWenchao Xia }
1467bbe86010SWenchao Xia 
146850f43f0fSJohn Snow static void internal_snapshot_abort(BlkActionState *common)
1469bbe86010SWenchao Xia {
1470bbe86010SWenchao Xia     InternalSnapshotState *state =
1471bbe86010SWenchao Xia                              DO_UPCAST(InternalSnapshotState, common, common);
1472bbe86010SWenchao Xia     BlockDriverState *bs = state->bs;
1473bbe86010SWenchao Xia     QEMUSnapshotInfo *sn = &state->sn;
1474a36e458cSStefan Hajnoczi     AioContext *aio_context;
1475bbe86010SWenchao Xia     Error *local_error = NULL;
1476bbe86010SWenchao Xia 
1477507306ccSFam Zheng     if (!state->created) {
1478bbe86010SWenchao Xia         return;
1479bbe86010SWenchao Xia     }
1480bbe86010SWenchao Xia 
1481a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1482a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
1483a36e458cSStefan Hajnoczi 
1484bbe86010SWenchao Xia     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1485c29b77f9SMarkus Armbruster         error_reportf_err(local_error,
1486c29b77f9SMarkus Armbruster                           "Failed to delete snapshot with id '%s' and "
1487c29b77f9SMarkus Armbruster                           "name '%s' on device '%s' in abort: ",
1488c29b77f9SMarkus Armbruster                           sn->id_str, sn->name,
1489c29b77f9SMarkus Armbruster                           bdrv_get_device_name(bs));
1490bbe86010SWenchao Xia     }
1491a36e458cSStefan Hajnoczi 
1492a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
1493bbe86010SWenchao Xia }
1494bbe86010SWenchao Xia 
149550f43f0fSJohn Snow static void internal_snapshot_clean(BlkActionState *common)
14965d6e96efSStefan Hajnoczi {
14975d6e96efSStefan Hajnoczi     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
14985d6e96efSStefan Hajnoczi                                              common, common);
1499a36e458cSStefan Hajnoczi     AioContext *aio_context;
15005d6e96efSStefan Hajnoczi 
1501a36e458cSStefan Hajnoczi     if (!state->bs) {
1502a36e458cSStefan Hajnoczi         return;
1503a36e458cSStefan Hajnoczi     }
1504a36e458cSStefan Hajnoczi 
1505a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1506a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
1507a36e458cSStefan Hajnoczi 
1508507306ccSFam Zheng     bdrv_drained_end(state->bs);
1509a36e458cSStefan Hajnoczi 
1510a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
15115d6e96efSStefan Hajnoczi }
15125d6e96efSStefan Hajnoczi 
1513ba0c86a3SWenchao Xia /* external snapshot private data */
1514ba5d6ab6SStefan Hajnoczi typedef struct ExternalSnapshotState {
151550f43f0fSJohn Snow     BlkActionState common;
15168802d1fdSJeff Cody     BlockDriverState *old_bs;
15178802d1fdSJeff Cody     BlockDriverState *new_bs;
1518067acf28SKevin Wolf     bool overlay_appended;
1519ba5d6ab6SStefan Hajnoczi } ExternalSnapshotState;
15208802d1fdSJeff Cody 
152150f43f0fSJohn Snow static void external_snapshot_prepare(BlkActionState *common,
15229b9877eeSWenchao Xia                                       Error **errp)
15239b9877eeSWenchao Xia {
15245b363937SMax Reitz     int flags = 0;
152543de7e2dSAlberto Garcia     QDict *options = NULL;
15269b9877eeSWenchao Xia     Error *local_err = NULL;
152743de7e2dSAlberto Garcia     /* Device and node name of the image to generate the snapshot from */
1528e2a31e87SWenchao Xia     const char *device;
15290901f67eSBenoît Canet     const char *node_name;
153043de7e2dSAlberto Garcia     /* Reference to the new image (for 'blockdev-snapshot') */
153143de7e2dSAlberto Garcia     const char *snapshot_ref;
153243de7e2dSAlberto Garcia     /* File name of the new image (for 'blockdev-snapshot-sync') */
1533e2a31e87SWenchao Xia     const char *new_image_file;
1534ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1535ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1536c8a83e85SKevin Wolf     TransactionAction *action = common->action;
15372d24b60bSStefan Hajnoczi     AioContext *aio_context;
15389b9877eeSWenchao Xia 
153943de7e2dSAlberto Garcia     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
154043de7e2dSAlberto Garcia      * purpose but a different set of parameters */
154143de7e2dSAlberto Garcia     switch (action->type) {
154243de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
154343de7e2dSAlberto Garcia         {
154432bafa8fSEric Blake             BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
154543de7e2dSAlberto Garcia             device = s->node;
154643de7e2dSAlberto Garcia             node_name = s->node;
154743de7e2dSAlberto Garcia             new_image_file = NULL;
154843de7e2dSAlberto Garcia             snapshot_ref = s->overlay;
1549e2a31e87SWenchao Xia         }
155043de7e2dSAlberto Garcia         break;
155143de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
155243de7e2dSAlberto Garcia         {
155332bafa8fSEric Blake             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
155443de7e2dSAlberto Garcia             device = s->has_device ? s->device : NULL;
155543de7e2dSAlberto Garcia             node_name = s->has_node_name ? s->node_name : NULL;
155643de7e2dSAlberto Garcia             new_image_file = s->snapshot_file;
155743de7e2dSAlberto Garcia             snapshot_ref = NULL;
155843de7e2dSAlberto Garcia         }
155943de7e2dSAlberto Garcia         break;
156043de7e2dSAlberto Garcia     default:
156143de7e2dSAlberto Garcia         g_assert_not_reached();
1562e2a31e87SWenchao Xia     }
1563e2a31e87SWenchao Xia 
1564e2a31e87SWenchao Xia     /* start processing */
156594d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
156694d16a64SJohn Snow         return;
156794d16a64SJohn Snow     }
156894d16a64SJohn Snow 
156943de7e2dSAlberto Garcia     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
157043de7e2dSAlberto Garcia     if (!state->old_bs) {
15719b9877eeSWenchao Xia         return;
15729b9877eeSWenchao Xia     }
15739b9877eeSWenchao Xia 
15742d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
15752d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
15762d24b60bSStefan Hajnoczi 
15772d24b60bSStefan Hajnoczi     /* Paired with .clean() */
1578da763e83SFam Zheng     bdrv_drained_begin(state->old_bs);
15795d6e96efSStefan Hajnoczi 
1580ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_inserted(state->old_bs)) {
1581c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
15822d24b60bSStefan Hajnoczi         goto out;
15839b9877eeSWenchao Xia     }
15849b9877eeSWenchao Xia 
15853718d8abSFam Zheng     if (bdrv_op_is_blocked(state->old_bs,
15863718d8abSFam Zheng                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
15872d24b60bSStefan Hajnoczi         goto out;
15889b9877eeSWenchao Xia     }
15899b9877eeSWenchao Xia 
1590ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_read_only(state->old_bs)) {
1591ba5d6ab6SStefan Hajnoczi         if (bdrv_flush(state->old_bs)) {
1592c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_IO_ERROR);
15932d24b60bSStefan Hajnoczi             goto out;
15949b9877eeSWenchao Xia         }
15959b9877eeSWenchao Xia     }
15969b9877eeSWenchao Xia 
1597212a5a8fSBenoît Canet     if (!bdrv_is_first_non_filter(state->old_bs)) {
1598c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
15992d24b60bSStefan Hajnoczi         goto out;
1600f6186f49SBenoît Canet     }
1601f6186f49SBenoît Canet 
160243de7e2dSAlberto Garcia     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
160332bafa8fSEric Blake         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
160443de7e2dSAlberto Garcia         const char *format = s->has_format ? s->format : "qcow2";
160543de7e2dSAlberto Garcia         enum NewImageMode mode;
160643de7e2dSAlberto Garcia         const char *snapshot_node_name =
160743de7e2dSAlberto Garcia             s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
160843de7e2dSAlberto Garcia 
160943de7e2dSAlberto Garcia         if (node_name && !snapshot_node_name) {
161043de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name missing");
16112d24b60bSStefan Hajnoczi             goto out;
161243de7e2dSAlberto Garcia         }
161343de7e2dSAlberto Garcia 
161443de7e2dSAlberto Garcia         if (snapshot_node_name &&
161543de7e2dSAlberto Garcia             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
161643de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name already in use");
16172d24b60bSStefan Hajnoczi             goto out;
161843de7e2dSAlberto Garcia         }
161943de7e2dSAlberto Garcia 
1620ba5d6ab6SStefan Hajnoczi         flags = state->old_bs->open_flags;
16212a32c6e8SJohn Snow         flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
16222a32c6e8SJohn Snow         flags |= BDRV_O_NO_BACKING;
16239b9877eeSWenchao Xia 
16249b9877eeSWenchao Xia         /* create new image w/backing file */
162543de7e2dSAlberto Garcia         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
16269b9877eeSWenchao Xia         if (mode != NEW_IMAGE_MODE_EXISTING) {
1627f86b8b58SKevin Wolf             int64_t size = bdrv_getlength(state->old_bs);
1628f86b8b58SKevin Wolf             if (size < 0) {
1629f86b8b58SKevin Wolf                 error_setg_errno(errp, -size, "bdrv_getlength failed");
16302d24b60bSStefan Hajnoczi                 goto out;
1631f86b8b58SKevin Wolf             }
1632f30c66baSMax Reitz             bdrv_refresh_filename(state->old_bs);
16339b9877eeSWenchao Xia             bdrv_img_create(new_image_file, format,
1634ba5d6ab6SStefan Hajnoczi                             state->old_bs->filename,
1635ba5d6ab6SStefan Hajnoczi                             state->old_bs->drv->format_name,
16369217283dSFam Zheng                             NULL, size, flags, false, &local_err);
163784d18f06SMarkus Armbruster             if (local_err) {
16389b9877eeSWenchao Xia                 error_propagate(errp, local_err);
16392d24b60bSStefan Hajnoczi                 goto out;
16409b9877eeSWenchao Xia             }
16419b9877eeSWenchao Xia         }
16429b9877eeSWenchao Xia 
16430901f67eSBenoît Canet         options = qdict_new();
1644d52e1a0eSPeter Maydell         if (snapshot_node_name) {
164546f5ac20SEric Blake             qdict_put_str(options, "node-name", snapshot_node_name);
16460901f67eSBenoît Canet         }
164746f5ac20SEric Blake         qdict_put_str(options, "driver", format);
164843de7e2dSAlberto Garcia     }
164943de7e2dSAlberto Garcia 
16505b363937SMax Reitz     state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
16515b363937SMax Reitz                               errp);
1652f67503e5SMax Reitz     /* We will manually add the backing_hd field to the bs later */
16535b363937SMax Reitz     if (!state->new_bs) {
16542d24b60bSStefan Hajnoczi         goto out;
165543de7e2dSAlberto Garcia     }
165643de7e2dSAlberto Garcia 
16571f0c461bSKevin Wolf     if (bdrv_has_blk(state->new_bs)) {
1658e467da7bSKevin Wolf         error_setg(errp, "The snapshot is already in use");
16592d24b60bSStefan Hajnoczi         goto out;
166043de7e2dSAlberto Garcia     }
166143de7e2dSAlberto Garcia 
166243de7e2dSAlberto Garcia     if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
166343de7e2dSAlberto Garcia                            errp)) {
16642d24b60bSStefan Hajnoczi         goto out;
166543de7e2dSAlberto Garcia     }
166643de7e2dSAlberto Garcia 
166743de7e2dSAlberto Garcia     if (state->new_bs->backing != NULL) {
166843de7e2dSAlberto Garcia         error_setg(errp, "The snapshot already has a backing image");
16692d24b60bSStefan Hajnoczi         goto out;
167008b24cfeSAlberto Garcia     }
167108b24cfeSAlberto Garcia 
167208b24cfeSAlberto Garcia     if (!state->new_bs->drv->supports_backing) {
167308b24cfeSAlberto Garcia         error_setg(errp, "The snapshot does not support backing images");
16742d24b60bSStefan Hajnoczi         goto out;
1675b2c2832cSKevin Wolf     }
1676b2c2832cSKevin Wolf 
16772d24b60bSStefan Hajnoczi     bdrv_set_aio_context(state->new_bs, aio_context);
1678c26a5ab7SFam Zheng 
1679b2c2832cSKevin Wolf     /* This removes our old bs and adds the new bs. This is an operation that
1680b2c2832cSKevin Wolf      * can fail, so we need to do it in .prepare; undoing it for abort is
1681b2c2832cSKevin Wolf      * always possible. */
1682b2c2832cSKevin Wolf     bdrv_ref(state->new_bs);
1683b2c2832cSKevin Wolf     bdrv_append(state->new_bs, state->old_bs, &local_err);
1684b2c2832cSKevin Wolf     if (local_err) {
1685b2c2832cSKevin Wolf         error_propagate(errp, local_err);
16862d24b60bSStefan Hajnoczi         goto out;
16879b9877eeSWenchao Xia     }
1688067acf28SKevin Wolf     state->overlay_appended = true;
16892d24b60bSStefan Hajnoczi 
16902d24b60bSStefan Hajnoczi out:
16912d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
16929b9877eeSWenchao Xia }
16939b9877eeSWenchao Xia 
169450f43f0fSJohn Snow static void external_snapshot_commit(BlkActionState *common)
16953b0047e8SWenchao Xia {
1696ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1697ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
16982d24b60bSStefan Hajnoczi     AioContext *aio_context;
16992d24b60bSStefan Hajnoczi 
17002d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
17012d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
1702ba0c86a3SWenchao Xia 
17033b0047e8SWenchao Xia     /* We don't need (or want) to use the transactional
17043b0047e8SWenchao Xia      * bdrv_reopen_multiple() across all the entries at once, because we
17053b0047e8SWenchao Xia      * don't want to abort all of them if one of them fails the reopen */
1706d3faa13eSPaolo Bonzini     if (!atomic_read(&state->old_bs->copy_on_read)) {
17071b57774fSAlberto Garcia         bdrv_reopen_set_read_only(state->old_bs, true, NULL);
17083b0047e8SWenchao Xia     }
17092d24b60bSStefan Hajnoczi 
17102d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
17114c844983SKevin Wolf }
17123b0047e8SWenchao Xia 
171350f43f0fSJohn Snow static void external_snapshot_abort(BlkActionState *common)
171496b86bf7SWenchao Xia {
1715ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1716ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1717ba5d6ab6SStefan Hajnoczi     if (state->new_bs) {
1718067acf28SKevin Wolf         if (state->overlay_appended) {
17192d24b60bSStefan Hajnoczi             AioContext *aio_context;
17202d24b60bSStefan Hajnoczi 
17212d24b60bSStefan Hajnoczi             aio_context = bdrv_get_aio_context(state->old_bs);
17222d24b60bSStefan Hajnoczi             aio_context_acquire(aio_context);
17232d24b60bSStefan Hajnoczi 
1724719fc28cSJeff Cody             bdrv_ref(state->old_bs);   /* we can't let bdrv_set_backind_hd()
1725719fc28cSJeff Cody                                           close state->old_bs; we need it */
1726719fc28cSJeff Cody             bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
17275fe31c25SKevin Wolf             bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1728719fc28cSJeff Cody             bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
17292d24b60bSStefan Hajnoczi 
17302d24b60bSStefan Hajnoczi             aio_context_release(aio_context);
1731b2c2832cSKevin Wolf         }
173296b86bf7SWenchao Xia     }
1733da763e83SFam Zheng }
1734da763e83SFam Zheng 
173550f43f0fSJohn Snow static void external_snapshot_clean(BlkActionState *common)
1736da763e83SFam Zheng {
1737da763e83SFam Zheng     ExternalSnapshotState *state =
1738da763e83SFam Zheng                              DO_UPCAST(ExternalSnapshotState, common, common);
17392d24b60bSStefan Hajnoczi     AioContext *aio_context;
17402d24b60bSStefan Hajnoczi 
17412d24b60bSStefan Hajnoczi     if (!state->old_bs) {
17422d24b60bSStefan Hajnoczi         return;
17432d24b60bSStefan Hajnoczi     }
17442d24b60bSStefan Hajnoczi 
17452d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
17462d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
17472d24b60bSStefan Hajnoczi 
1748da763e83SFam Zheng     bdrv_drained_end(state->old_bs);
1749b2c2832cSKevin Wolf     bdrv_unref(state->new_bs);
17502d24b60bSStefan Hajnoczi 
17512d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
175296b86bf7SWenchao Xia }
175396b86bf7SWenchao Xia 
17543037f364SStefan Hajnoczi typedef struct DriveBackupState {
175550f43f0fSJohn Snow     BlkActionState common;
17563037f364SStefan Hajnoczi     BlockDriverState *bs;
17573037f364SStefan Hajnoczi     BlockJob *job;
17583037f364SStefan Hajnoczi } DriveBackupState;
17593037f364SStefan Hajnoczi 
176062c9e416SKevin Wolf static BlockJob *do_drive_backup(DriveBackup *backup, JobTxn *txn,
176181206a89SPavel Butsykin                             Error **errp);
176278f51fdeSJohn Snow 
176350f43f0fSJohn Snow static void drive_backup_prepare(BlkActionState *common, Error **errp)
17643037f364SStefan Hajnoczi {
17653037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1766b7e4fa22SKevin Wolf     BlockDriverState *bs;
17673037f364SStefan Hajnoczi     DriveBackup *backup;
176866d56054SStefan Hajnoczi     AioContext *aio_context;
17693037f364SStefan Hajnoczi     Error *local_err = NULL;
17703037f364SStefan Hajnoczi 
17716a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
177232bafa8fSEric Blake     backup = common->action->u.drive_backup.data;
17733037f364SStefan Hajnoczi 
1774b7e4fa22SKevin Wolf     bs = qmp_get_root_bs(backup->device, errp);
1775b7e4fa22SKevin Wolf     if (!bs) {
17761fdd4b7bSFam Zheng         return;
17771fdd4b7bSFam Zheng     }
17781fdd4b7bSFam Zheng 
177966d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
178066d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
178166d56054SStefan Hajnoczi 
178266d56054SStefan Hajnoczi     /* Paired with .clean() */
1783b7e4fa22SKevin Wolf     bdrv_drained_begin(bs);
178466d56054SStefan Hajnoczi 
1785b7e4fa22SKevin Wolf     state->bs = bs;
17865d6e96efSStefan Hajnoczi 
1787111049a4SJohn Snow     state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
178884d18f06SMarkus Armbruster     if (local_err) {
17893037f364SStefan Hajnoczi         error_propagate(errp, local_err);
179066d56054SStefan Hajnoczi         goto out;
17913037f364SStefan Hajnoczi     }
179266d56054SStefan Hajnoczi 
179366d56054SStefan Hajnoczi out:
179466d56054SStefan Hajnoczi     aio_context_release(aio_context);
1795111049a4SJohn Snow }
17963037f364SStefan Hajnoczi 
1797111049a4SJohn Snow static void drive_backup_commit(BlkActionState *common)
1798111049a4SJohn Snow {
1799111049a4SJohn Snow     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
180066d56054SStefan Hajnoczi     AioContext *aio_context;
180166d56054SStefan Hajnoczi 
180266d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
180366d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
180466d56054SStefan Hajnoczi 
1805111049a4SJohn Snow     assert(state->job);
1806da01ff7fSKevin Wolf     job_start(&state->job->job);
180766d56054SStefan Hajnoczi 
180866d56054SStefan Hajnoczi     aio_context_release(aio_context);
18093037f364SStefan Hajnoczi }
18103037f364SStefan Hajnoczi 
181150f43f0fSJohn Snow static void drive_backup_abort(BlkActionState *common)
18123037f364SStefan Hajnoczi {
18133037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
18143037f364SStefan Hajnoczi 
1815111049a4SJohn Snow     if (state->job) {
181666d56054SStefan Hajnoczi         AioContext *aio_context;
181766d56054SStefan Hajnoczi 
181866d56054SStefan Hajnoczi         aio_context = bdrv_get_aio_context(state->bs);
181966d56054SStefan Hajnoczi         aio_context_acquire(aio_context);
182066d56054SStefan Hajnoczi 
18213d70ff53SKevin Wolf         job_cancel_sync(&state->job->job);
182266d56054SStefan Hajnoczi 
182366d56054SStefan Hajnoczi         aio_context_release(aio_context);
18243037f364SStefan Hajnoczi     }
18253037f364SStefan Hajnoczi }
18263037f364SStefan Hajnoczi 
182750f43f0fSJohn Snow static void drive_backup_clean(BlkActionState *common)
18285d6e96efSStefan Hajnoczi {
18295d6e96efSStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
183066d56054SStefan Hajnoczi     AioContext *aio_context;
18315d6e96efSStefan Hajnoczi 
183266d56054SStefan Hajnoczi     if (!state->bs) {
183366d56054SStefan Hajnoczi         return;
18345d6e96efSStefan Hajnoczi     }
183566d56054SStefan Hajnoczi 
183666d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
183766d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
183866d56054SStefan Hajnoczi 
183966d56054SStefan Hajnoczi     bdrv_drained_end(state->bs);
184066d56054SStefan Hajnoczi 
184166d56054SStefan Hajnoczi     aio_context_release(aio_context);
18425d6e96efSStefan Hajnoczi }
18435d6e96efSStefan Hajnoczi 
1844bd8baecdSFam Zheng typedef struct BlockdevBackupState {
184550f43f0fSJohn Snow     BlkActionState common;
1846bd8baecdSFam Zheng     BlockDriverState *bs;
1847bd8baecdSFam Zheng     BlockJob *job;
1848bd8baecdSFam Zheng } BlockdevBackupState;
1849bd8baecdSFam Zheng 
185062c9e416SKevin Wolf static BlockJob *do_blockdev_backup(BlockdevBackup *backup, JobTxn *txn,
1851dc7a4a9eSPavel Butsykin                                     Error **errp);
185278f51fdeSJohn Snow 
185350f43f0fSJohn Snow static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1854bd8baecdSFam Zheng {
1855bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1856bd8baecdSFam Zheng     BlockdevBackup *backup;
1857cef34eebSKevin Wolf     BlockDriverState *bs, *target;
1858edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1859bd8baecdSFam Zheng     Error *local_err = NULL;
1860bd8baecdSFam Zheng 
18616a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
186232bafa8fSEric Blake     backup = common->action->u.blockdev_backup.data;
1863bd8baecdSFam Zheng 
1864930fe17fSVladimir Sementsov-Ogievskiy     bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1865cef34eebSKevin Wolf     if (!bs) {
1866ff52bf36SFam Zheng         return;
1867ff52bf36SFam Zheng     }
1868ff52bf36SFam Zheng 
186939d990acSKevin Wolf     target = bdrv_lookup_bs(backup->target, backup->target, errp);
18705433c24fSMax Reitz     if (!target) {
1871bd8baecdSFam Zheng         return;
1872bd8baecdSFam Zheng     }
1873bd8baecdSFam Zheng 
1874edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
1875edd5adeeSStefan Hajnoczi     if (aio_context != bdrv_get_aio_context(target)) {
1876bd8baecdSFam Zheng         error_setg(errp, "Backup between two IO threads is not implemented");
1877bd8baecdSFam Zheng         return;
1878bd8baecdSFam Zheng     }
1879edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1880cef34eebSKevin Wolf     state->bs = bs;
1881edd5adeeSStefan Hajnoczi 
1882edd5adeeSStefan Hajnoczi     /* Paired with .clean() */
1883ff52bf36SFam Zheng     bdrv_drained_begin(state->bs);
1884bd8baecdSFam Zheng 
1885111049a4SJohn Snow     state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
1886bd8baecdSFam Zheng     if (local_err) {
1887bd8baecdSFam Zheng         error_propagate(errp, local_err);
1888edd5adeeSStefan Hajnoczi         goto out;
1889bd8baecdSFam Zheng     }
1890edd5adeeSStefan Hajnoczi 
1891edd5adeeSStefan Hajnoczi out:
1892edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1893111049a4SJohn Snow }
1894bd8baecdSFam Zheng 
1895111049a4SJohn Snow static void blockdev_backup_commit(BlkActionState *common)
1896111049a4SJohn Snow {
1897111049a4SJohn Snow     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1898edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1899edd5adeeSStefan Hajnoczi 
1900edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1901edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1902edd5adeeSStefan Hajnoczi 
1903111049a4SJohn Snow     assert(state->job);
1904da01ff7fSKevin Wolf     job_start(&state->job->job);
1905edd5adeeSStefan Hajnoczi 
1906edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1907bd8baecdSFam Zheng }
1908bd8baecdSFam Zheng 
190950f43f0fSJohn Snow static void blockdev_backup_abort(BlkActionState *common)
1910bd8baecdSFam Zheng {
1911bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1912bd8baecdSFam Zheng 
1913111049a4SJohn Snow     if (state->job) {
1914edd5adeeSStefan Hajnoczi         AioContext *aio_context;
1915edd5adeeSStefan Hajnoczi 
1916edd5adeeSStefan Hajnoczi         aio_context = bdrv_get_aio_context(state->bs);
1917edd5adeeSStefan Hajnoczi         aio_context_acquire(aio_context);
1918edd5adeeSStefan Hajnoczi 
19193d70ff53SKevin Wolf         job_cancel_sync(&state->job->job);
1920edd5adeeSStefan Hajnoczi 
1921edd5adeeSStefan Hajnoczi         aio_context_release(aio_context);
1922bd8baecdSFam Zheng     }
1923bd8baecdSFam Zheng }
1924bd8baecdSFam Zheng 
192550f43f0fSJohn Snow static void blockdev_backup_clean(BlkActionState *common)
1926bd8baecdSFam Zheng {
1927bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1928edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1929bd8baecdSFam Zheng 
1930edd5adeeSStefan Hajnoczi     if (!state->bs) {
1931edd5adeeSStefan Hajnoczi         return;
1932bd8baecdSFam Zheng     }
1933edd5adeeSStefan Hajnoczi 
1934edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1935edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1936edd5adeeSStefan Hajnoczi 
1937edd5adeeSStefan Hajnoczi     bdrv_drained_end(state->bs);
1938edd5adeeSStefan Hajnoczi 
1939edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1940bd8baecdSFam Zheng }
1941bd8baecdSFam Zheng 
1942df9a681dSFam Zheng typedef struct BlockDirtyBitmapState {
194350f43f0fSJohn Snow     BlkActionState common;
1944df9a681dSFam Zheng     BdrvDirtyBitmap *bitmap;
1945df9a681dSFam Zheng     BlockDriverState *bs;
1946df9a681dSFam Zheng     HBitmap *backup;
1947df9a681dSFam Zheng     bool prepared;
1948c6490447SVladimir Sementsov-Ogievskiy     bool was_enabled;
1949df9a681dSFam Zheng } BlockDirtyBitmapState;
1950df9a681dSFam Zheng 
195150f43f0fSJohn Snow static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1952df9a681dSFam Zheng                                            Error **errp)
1953df9a681dSFam Zheng {
1954df9a681dSFam Zheng     Error *local_err = NULL;
1955df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
1956df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1957df9a681dSFam Zheng                                              common, common);
1958df9a681dSFam Zheng 
195994d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
196094d16a64SJohn Snow         return;
196194d16a64SJohn Snow     }
196294d16a64SJohn Snow 
196332bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
1964df9a681dSFam Zheng     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1965df9a681dSFam Zheng     qmp_block_dirty_bitmap_add(action->node, action->name,
1966df9a681dSFam Zheng                                action->has_granularity, action->granularity,
1967fd5ae4ccSVladimir Sementsov-Ogievskiy                                action->has_persistent, action->persistent,
1968eb738bb5SVladimir Sementsov-Ogievskiy                                action->has_autoload, action->autoload,
19690e2b7f09SJohn Snow                                action->has_disabled, action->disabled,
1970df9a681dSFam Zheng                                &local_err);
1971df9a681dSFam Zheng 
1972df9a681dSFam Zheng     if (!local_err) {
1973df9a681dSFam Zheng         state->prepared = true;
1974df9a681dSFam Zheng     } else {
1975df9a681dSFam Zheng         error_propagate(errp, local_err);
1976df9a681dSFam Zheng     }
1977df9a681dSFam Zheng }
1978df9a681dSFam Zheng 
197950f43f0fSJohn Snow static void block_dirty_bitmap_add_abort(BlkActionState *common)
1980df9a681dSFam Zheng {
1981df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
1982df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1983df9a681dSFam Zheng                                              common, common);
1984df9a681dSFam Zheng 
198532bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
1986df9a681dSFam Zheng     /* Should not be able to fail: IF the bitmap was added via .prepare(),
1987df9a681dSFam Zheng      * then the node reference and bitmap name must have been valid.
1988df9a681dSFam Zheng      */
1989df9a681dSFam Zheng     if (state->prepared) {
1990df9a681dSFam Zheng         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
1991df9a681dSFam Zheng     }
1992df9a681dSFam Zheng }
1993df9a681dSFam Zheng 
199450f43f0fSJohn Snow static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
1995df9a681dSFam Zheng                                              Error **errp)
1996df9a681dSFam Zheng {
1997df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1998df9a681dSFam Zheng                                              common, common);
1999df9a681dSFam Zheng     BlockDirtyBitmap *action;
2000df9a681dSFam Zheng 
200194d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
200294d16a64SJohn Snow         return;
200394d16a64SJohn Snow     }
200494d16a64SJohn Snow 
200532bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_clear.data;
2006df9a681dSFam Zheng     state->bitmap = block_dirty_bitmap_lookup(action->node,
2007df9a681dSFam Zheng                                               action->name,
2008df9a681dSFam Zheng                                               &state->bs,
2009df9a681dSFam Zheng                                               errp);
2010df9a681dSFam Zheng     if (!state->bitmap) {
2011df9a681dSFam Zheng         return;
2012df9a681dSFam Zheng     }
2013df9a681dSFam Zheng 
20143ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_DEFAULT, errp)) {
2015d6883bc9SVladimir Sementsov-Ogievskiy         return;
2016df9a681dSFam Zheng     }
2017df9a681dSFam Zheng 
2018df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2019df9a681dSFam Zheng }
2020df9a681dSFam Zheng 
20215c4cf8b2SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_restore(BlkActionState *common)
2022df9a681dSFam Zheng {
2023df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2024df9a681dSFam Zheng                                              common, common);
2025df9a681dSFam Zheng 
2026184dd9c4SJohn Snow     if (state->backup) {
202756bd6624SVladimir Sementsov-Ogievskiy         bdrv_restore_dirty_bitmap(state->bitmap, state->backup);
2028df9a681dSFam Zheng     }
2029184dd9c4SJohn Snow }
2030df9a681dSFam Zheng 
20315c4cf8b2SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_free_backup(BlkActionState *common)
2032df9a681dSFam Zheng {
2033df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2034df9a681dSFam Zheng                                              common, common);
2035df9a681dSFam Zheng 
2036df9a681dSFam Zheng     hbitmap_free(state->backup);
2037df9a681dSFam Zheng }
2038df9a681dSFam Zheng 
2039c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_enable_prepare(BlkActionState *common,
2040c6490447SVladimir Sementsov-Ogievskiy                                               Error **errp)
2041c6490447SVladimir Sementsov-Ogievskiy {
2042c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmap *action;
2043c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2044c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2045c6490447SVladimir Sementsov-Ogievskiy 
2046c6490447SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
2047c6490447SVladimir Sementsov-Ogievskiy         return;
2048c6490447SVladimir Sementsov-Ogievskiy     }
2049c6490447SVladimir Sementsov-Ogievskiy 
20500e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_enable.data;
2051c6490447SVladimir Sementsov-Ogievskiy     state->bitmap = block_dirty_bitmap_lookup(action->node,
2052c6490447SVladimir Sementsov-Ogievskiy                                               action->name,
2053c6490447SVladimir Sementsov-Ogievskiy                                               NULL,
2054c6490447SVladimir Sementsov-Ogievskiy                                               errp);
2055c6490447SVladimir Sementsov-Ogievskiy     if (!state->bitmap) {
2056c6490447SVladimir Sementsov-Ogievskiy         return;
2057c6490447SVladimir Sementsov-Ogievskiy     }
2058c6490447SVladimir Sementsov-Ogievskiy 
20593ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2060b053bb55SJohn Snow         return;
2061b053bb55SJohn Snow     }
2062b053bb55SJohn Snow 
2063c6490447SVladimir Sementsov-Ogievskiy     state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2064c6490447SVladimir Sementsov-Ogievskiy     bdrv_enable_dirty_bitmap(state->bitmap);
2065c6490447SVladimir Sementsov-Ogievskiy }
2066c6490447SVladimir Sementsov-Ogievskiy 
2067c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_enable_abort(BlkActionState *common)
2068c6490447SVladimir Sementsov-Ogievskiy {
2069c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2070c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2071c6490447SVladimir Sementsov-Ogievskiy 
2072c6490447SVladimir Sementsov-Ogievskiy     if (!state->was_enabled) {
2073c6490447SVladimir Sementsov-Ogievskiy         bdrv_disable_dirty_bitmap(state->bitmap);
2074c6490447SVladimir Sementsov-Ogievskiy     }
2075c6490447SVladimir Sementsov-Ogievskiy }
2076c6490447SVladimir Sementsov-Ogievskiy 
2077c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_disable_prepare(BlkActionState *common,
2078c6490447SVladimir Sementsov-Ogievskiy                                                Error **errp)
2079c6490447SVladimir Sementsov-Ogievskiy {
2080c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmap *action;
2081c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2082c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2083c6490447SVladimir Sementsov-Ogievskiy 
2084c6490447SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
2085c6490447SVladimir Sementsov-Ogievskiy         return;
2086c6490447SVladimir Sementsov-Ogievskiy     }
2087c6490447SVladimir Sementsov-Ogievskiy 
20880e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_disable.data;
2089c6490447SVladimir Sementsov-Ogievskiy     state->bitmap = block_dirty_bitmap_lookup(action->node,
2090c6490447SVladimir Sementsov-Ogievskiy                                               action->name,
2091c6490447SVladimir Sementsov-Ogievskiy                                               NULL,
2092c6490447SVladimir Sementsov-Ogievskiy                                               errp);
2093c6490447SVladimir Sementsov-Ogievskiy     if (!state->bitmap) {
2094c6490447SVladimir Sementsov-Ogievskiy         return;
2095c6490447SVladimir Sementsov-Ogievskiy     }
2096c6490447SVladimir Sementsov-Ogievskiy 
20973ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2098b053bb55SJohn Snow         return;
2099b053bb55SJohn Snow     }
2100b053bb55SJohn Snow 
2101c6490447SVladimir Sementsov-Ogievskiy     state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2102c6490447SVladimir Sementsov-Ogievskiy     bdrv_disable_dirty_bitmap(state->bitmap);
2103c6490447SVladimir Sementsov-Ogievskiy }
2104c6490447SVladimir Sementsov-Ogievskiy 
2105c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_disable_abort(BlkActionState *common)
2106c6490447SVladimir Sementsov-Ogievskiy {
2107c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2108c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2109c6490447SVladimir Sementsov-Ogievskiy 
2110c6490447SVladimir Sementsov-Ogievskiy     if (state->was_enabled) {
2111c6490447SVladimir Sementsov-Ogievskiy         bdrv_enable_dirty_bitmap(state->bitmap);
2112c6490447SVladimir Sementsov-Ogievskiy     }
2113c6490447SVladimir Sementsov-Ogievskiy }
2114c6490447SVladimir Sementsov-Ogievskiy 
2115*eff0829bSVladimir Sementsov-Ogievskiy static BdrvDirtyBitmap *do_block_dirty_bitmap_merge(
2116*eff0829bSVladimir Sementsov-Ogievskiy         const char *node, const char *target,
2117*eff0829bSVladimir Sementsov-Ogievskiy         BlockDirtyBitmapMergeSourceList *bitmaps,
2118*eff0829bSVladimir Sementsov-Ogievskiy         HBitmap **backup, Error **errp);
2119360d4e4eSJohn Snow 
21206fd2e407SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_merge_prepare(BlkActionState *common,
21216fd2e407SVladimir Sementsov-Ogievskiy                                              Error **errp)
21226fd2e407SVladimir Sementsov-Ogievskiy {
21236fd2e407SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapMerge *action;
21246fd2e407SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
21256fd2e407SVladimir Sementsov-Ogievskiy                                              common, common);
21266fd2e407SVladimir Sementsov-Ogievskiy 
21276fd2e407SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
21286fd2e407SVladimir Sementsov-Ogievskiy         return;
21296fd2e407SVladimir Sementsov-Ogievskiy     }
21306fd2e407SVladimir Sementsov-Ogievskiy 
21310e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_merge.data;
2132360d4e4eSJohn Snow 
2133360d4e4eSJohn Snow     state->bitmap = do_block_dirty_bitmap_merge(action->node, action->target,
2134360d4e4eSJohn Snow                                                 action->bitmaps, &state->backup,
21356fd2e407SVladimir Sementsov-Ogievskiy                                                 errp);
21366fd2e407SVladimir Sementsov-Ogievskiy }
21376fd2e407SVladimir Sementsov-Ogievskiy 
213850f43f0fSJohn Snow static void abort_prepare(BlkActionState *common, Error **errp)
213978b18b78SStefan Hajnoczi {
214078b18b78SStefan Hajnoczi     error_setg(errp, "Transaction aborted using Abort action");
214178b18b78SStefan Hajnoczi }
214278b18b78SStefan Hajnoczi 
214350f43f0fSJohn Snow static void abort_commit(BlkActionState *common)
214478b18b78SStefan Hajnoczi {
2145dfc6f865SStefan Weil     g_assert_not_reached(); /* this action never succeeds */
214678b18b78SStefan Hajnoczi }
214778b18b78SStefan Hajnoczi 
214850f43f0fSJohn Snow static const BlkActionOps actions[] = {
214943de7e2dSAlberto Garcia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
215043de7e2dSAlberto Garcia         .instance_size = sizeof(ExternalSnapshotState),
215143de7e2dSAlberto Garcia         .prepare  = external_snapshot_prepare,
215243de7e2dSAlberto Garcia         .commit   = external_snapshot_commit,
215343de7e2dSAlberto Garcia         .abort = external_snapshot_abort,
21544ad6f3dbSAlberto Garcia         .clean = external_snapshot_clean,
215543de7e2dSAlberto Garcia     },
2156c8a83e85SKevin Wolf     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2157ba5d6ab6SStefan Hajnoczi         .instance_size = sizeof(ExternalSnapshotState),
2158ba0c86a3SWenchao Xia         .prepare  = external_snapshot_prepare,
2159ba0c86a3SWenchao Xia         .commit   = external_snapshot_commit,
2160ba0c86a3SWenchao Xia         .abort = external_snapshot_abort,
2161da763e83SFam Zheng         .clean = external_snapshot_clean,
2162ba0c86a3SWenchao Xia     },
21633037f364SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
21643037f364SStefan Hajnoczi         .instance_size = sizeof(DriveBackupState),
21653037f364SStefan Hajnoczi         .prepare = drive_backup_prepare,
2166111049a4SJohn Snow         .commit = drive_backup_commit,
21673037f364SStefan Hajnoczi         .abort = drive_backup_abort,
21685d6e96efSStefan Hajnoczi         .clean = drive_backup_clean,
21693037f364SStefan Hajnoczi     },
2170bd8baecdSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2171bd8baecdSFam Zheng         .instance_size = sizeof(BlockdevBackupState),
2172bd8baecdSFam Zheng         .prepare = blockdev_backup_prepare,
2173111049a4SJohn Snow         .commit = blockdev_backup_commit,
2174bd8baecdSFam Zheng         .abort = blockdev_backup_abort,
2175bd8baecdSFam Zheng         .clean = blockdev_backup_clean,
2176bd8baecdSFam Zheng     },
217778b18b78SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_ABORT] = {
217850f43f0fSJohn Snow         .instance_size = sizeof(BlkActionState),
217978b18b78SStefan Hajnoczi         .prepare = abort_prepare,
218078b18b78SStefan Hajnoczi         .commit = abort_commit,
218178b18b78SStefan Hajnoczi     },
2182bbe86010SWenchao Xia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2183bbe86010SWenchao Xia         .instance_size = sizeof(InternalSnapshotState),
2184bbe86010SWenchao Xia         .prepare  = internal_snapshot_prepare,
2185bbe86010SWenchao Xia         .abort = internal_snapshot_abort,
21865d6e96efSStefan Hajnoczi         .clean = internal_snapshot_clean,
2187bbe86010SWenchao Xia     },
2188df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2189df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2190df9a681dSFam Zheng         .prepare = block_dirty_bitmap_add_prepare,
2191df9a681dSFam Zheng         .abort = block_dirty_bitmap_add_abort,
2192df9a681dSFam Zheng     },
2193df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2194df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2195df9a681dSFam Zheng         .prepare = block_dirty_bitmap_clear_prepare,
21965c4cf8b2SVladimir Sementsov-Ogievskiy         .commit = block_dirty_bitmap_free_backup,
21975c4cf8b2SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_restore,
2198c6490447SVladimir Sementsov-Ogievskiy     },
21990e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ENABLE] = {
2200c6490447SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
2201c6490447SVladimir Sementsov-Ogievskiy         .prepare = block_dirty_bitmap_enable_prepare,
2202c6490447SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_enable_abort,
2203c6490447SVladimir Sementsov-Ogievskiy     },
22040e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_DISABLE] = {
2205c6490447SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
2206c6490447SVladimir Sementsov-Ogievskiy         .prepare = block_dirty_bitmap_disable_prepare,
2207c6490447SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_disable_abort,
220866da04ddSJohn Snow     },
22090e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_MERGE] = {
22106fd2e407SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
22116fd2e407SVladimir Sementsov-Ogievskiy         .prepare = block_dirty_bitmap_merge_prepare,
22126fd2e407SVladimir Sementsov-Ogievskiy         .commit = block_dirty_bitmap_free_backup,
22136fd2e407SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_restore,
22146fd2e407SVladimir Sementsov-Ogievskiy     },
221566da04ddSJohn Snow     /* Where are transactions for MIRROR, COMMIT and STREAM?
221666da04ddSJohn Snow      * Although these blockjobs use transaction callbacks like the backup job,
221766da04ddSJohn Snow      * these jobs do not necessarily adhere to transaction semantics.
221866da04ddSJohn Snow      * These jobs may not fully undo all of their actions on abort, nor do they
221966da04ddSJohn Snow      * necessarily work in transactions with more than one job in them.
222066da04ddSJohn Snow      */
2221ba0c86a3SWenchao Xia };
2222ba0c86a3SWenchao Xia 
222394d16a64SJohn Snow /**
222494d16a64SJohn Snow  * Allocate a TransactionProperties structure if necessary, and fill
222594d16a64SJohn Snow  * that structure with desired defaults if they are unset.
222694d16a64SJohn Snow  */
222794d16a64SJohn Snow static TransactionProperties *get_transaction_properties(
222894d16a64SJohn Snow     TransactionProperties *props)
222994d16a64SJohn Snow {
223094d16a64SJohn Snow     if (!props) {
223194d16a64SJohn Snow         props = g_new0(TransactionProperties, 1);
223294d16a64SJohn Snow     }
223394d16a64SJohn Snow 
223494d16a64SJohn Snow     if (!props->has_completion_mode) {
223594d16a64SJohn Snow         props->has_completion_mode = true;
223694d16a64SJohn Snow         props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
223794d16a64SJohn Snow     }
223894d16a64SJohn Snow 
223994d16a64SJohn Snow     return props;
224094d16a64SJohn Snow }
224194d16a64SJohn Snow 
22428802d1fdSJeff Cody /*
2243b756b9ceSStefan Hajnoczi  * 'Atomic' group operations.  The operations are performed as a set, and if
2244b756b9ceSStefan Hajnoczi  * any fail then we roll back all operations in the group.
22458802d1fdSJeff Cody  */
224694d16a64SJohn Snow void qmp_transaction(TransactionActionList *dev_list,
224794d16a64SJohn Snow                      bool has_props,
224894d16a64SJohn Snow                      struct TransactionProperties *props,
224994d16a64SJohn Snow                      Error **errp)
22508802d1fdSJeff Cody {
2251c8a83e85SKevin Wolf     TransactionActionList *dev_entry = dev_list;
225262c9e416SKevin Wolf     JobTxn *block_job_txn = NULL;
225350f43f0fSJohn Snow     BlkActionState *state, *next;
225443e17041SLuiz Capitulino     Error *local_err = NULL;
22558802d1fdSJeff Cody 
2256f4de0f8cSJohn Snow     QTAILQ_HEAD(, BlkActionState) snap_bdrv_states;
2257f4de0f8cSJohn Snow     QTAILQ_INIT(&snap_bdrv_states);
22588802d1fdSJeff Cody 
225994d16a64SJohn Snow     /* Does this transaction get canceled as a group on failure?
226062c9e416SKevin Wolf      * If not, we don't really need to make a JobTxn.
226194d16a64SJohn Snow      */
226294d16a64SJohn Snow     props = get_transaction_properties(props);
226394d16a64SJohn Snow     if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
22647eaa8fb5SKevin Wolf         block_job_txn = job_txn_new();
226594d16a64SJohn Snow     }
226694d16a64SJohn Snow 
2267b756b9ceSStefan Hajnoczi     /* drain all i/o before any operations */
22688802d1fdSJeff Cody     bdrv_drain_all();
22698802d1fdSJeff Cody 
2270b756b9ceSStefan Hajnoczi     /* We don't do anything in this loop that commits us to the operations */
22718802d1fdSJeff Cody     while (NULL != dev_entry) {
2272c8a83e85SKevin Wolf         TransactionAction *dev_info = NULL;
227350f43f0fSJohn Snow         const BlkActionOps *ops;
227452e7c241SPaolo Bonzini 
22758802d1fdSJeff Cody         dev_info = dev_entry->value;
22768802d1fdSJeff Cody         dev_entry = dev_entry->next;
22778802d1fdSJeff Cody 
22786a8f9661SEric Blake         assert(dev_info->type < ARRAY_SIZE(actions));
2279ba0c86a3SWenchao Xia 
22806a8f9661SEric Blake         ops = &actions[dev_info->type];
2281aa3fe714SMax Reitz         assert(ops->instance_size > 0);
2282aa3fe714SMax Reitz 
2283ba5d6ab6SStefan Hajnoczi         state = g_malloc0(ops->instance_size);
2284ba5d6ab6SStefan Hajnoczi         state->ops = ops;
2285ba5d6ab6SStefan Hajnoczi         state->action = dev_info;
228694d16a64SJohn Snow         state->block_job_txn = block_job_txn;
228794d16a64SJohn Snow         state->txn_props = props;
2288f4de0f8cSJohn Snow         QTAILQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
22898802d1fdSJeff Cody 
2290ba5d6ab6SStefan Hajnoczi         state->ops->prepare(state, &local_err);
229184d18f06SMarkus Armbruster         if (local_err) {
22929b9877eeSWenchao Xia             error_propagate(errp, local_err);
22939b9877eeSWenchao Xia             goto delete_and_fail;
22949b9877eeSWenchao Xia         }
229552e7c241SPaolo Bonzini     }
22968802d1fdSJeff Cody 
2297f4de0f8cSJohn Snow     QTAILQ_FOREACH(state, &snap_bdrv_states, entry) {
2298f9ea81e8SStefan Hajnoczi         if (state->ops->commit) {
2299ba5d6ab6SStefan Hajnoczi             state->ops->commit(state);
23008802d1fdSJeff Cody         }
2301f9ea81e8SStefan Hajnoczi     }
23028802d1fdSJeff Cody 
23038802d1fdSJeff Cody     /* success */
23048802d1fdSJeff Cody     goto exit;
23058802d1fdSJeff Cody 
23068802d1fdSJeff Cody delete_and_fail:
2307b756b9ceSStefan Hajnoczi     /* failure, and it is all-or-none; roll back all operations */
2308f4de0f8cSJohn Snow     QTAILQ_FOREACH_REVERSE(state, &snap_bdrv_states, entry) {
2309ba5d6ab6SStefan Hajnoczi         if (state->ops->abort) {
2310ba5d6ab6SStefan Hajnoczi             state->ops->abort(state);
2311ba0c86a3SWenchao Xia         }
23128802d1fdSJeff Cody     }
23138802d1fdSJeff Cody exit:
2314f4de0f8cSJohn Snow     QTAILQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2315ba5d6ab6SStefan Hajnoczi         if (state->ops->clean) {
2316ba5d6ab6SStefan Hajnoczi             state->ops->clean(state);
2317ba0c86a3SWenchao Xia         }
2318ba5d6ab6SStefan Hajnoczi         g_free(state);
23198802d1fdSJeff Cody     }
232094d16a64SJohn Snow     if (!has_props) {
232194d16a64SJohn Snow         qapi_free_TransactionProperties(props);
232294d16a64SJohn Snow     }
23237eaa8fb5SKevin Wolf     job_txn_unref(block_job_txn);
23248802d1fdSJeff Cody }
23258802d1fdSJeff Cody 
2326fbe2d816SKevin Wolf void qmp_eject(bool has_device, const char *device,
2327fbe2d816SKevin Wolf                bool has_id, const char *id,
2328fbe2d816SKevin Wolf                bool has_force, bool force, Error **errp)
2329666daa68SMarkus Armbruster {
233038f54bd1SMax Reitz     Error *local_err = NULL;
23313a3086b7SJohn Snow     int rc;
2332666daa68SMarkus Armbruster 
23333a3086b7SJohn Snow     if (!has_force) {
23343a3086b7SJohn Snow         force = false;
23353a3086b7SJohn Snow     }
23363a3086b7SJohn Snow 
2337fbe2d816SKevin Wolf     rc = do_open_tray(has_device ? device : NULL,
2338fbe2d816SKevin Wolf                       has_id ? id : NULL,
2339fbe2d816SKevin Wolf                       force, &local_err);
2340bf18bee5SColin Lord     if (rc && rc != -ENOSYS) {
234138f54bd1SMax Reitz         error_propagate(errp, local_err);
2342c245b6a3SLuiz Capitulino         return;
2343666daa68SMarkus Armbruster     }
2344bf18bee5SColin Lord     error_free(local_err);
23453a3086b7SJohn Snow 
234682fcf66eSMax Reitz     blockdev_remove_medium(has_device, device, has_id, id, errp);
2347666daa68SMarkus Armbruster }
2348666daa68SMarkus Armbruster 
234912d3ba82SBenoît Canet void qmp_block_passwd(bool has_device, const char *device,
235012d3ba82SBenoît Canet                       bool has_node_name, const char *node_name,
235112d3ba82SBenoît Canet                       const char *password, Error **errp)
2352666daa68SMarkus Armbruster {
2353c01c214bSDaniel P. Berrange     error_setg(errp,
2354c01c214bSDaniel P. Berrange                "Setting block passwords directly is no longer supported");
2355e3442099SStefan Hajnoczi }
2356e3442099SStefan Hajnoczi 
2357bf18bee5SColin Lord /*
2358bf18bee5SColin Lord  * Attempt to open the tray of @device.
2359bf18bee5SColin Lord  * If @force, ignore its tray lock.
2360bf18bee5SColin Lord  * Else, if the tray is locked, don't open it, but ask the guest to open it.
2361bf18bee5SColin Lord  * On error, store an error through @errp and return -errno.
2362bf18bee5SColin Lord  * If @device does not exist, return -ENODEV.
2363bf18bee5SColin Lord  * If it has no removable media, return -ENOTSUP.
2364bf18bee5SColin Lord  * If it has no tray, return -ENOSYS.
2365bf18bee5SColin Lord  * If the guest was asked to open the tray, return -EINPROGRESS.
2366bf18bee5SColin Lord  * Else, return 0.
23673a3086b7SJohn Snow  */
2368b33945cfSKevin Wolf static int do_open_tray(const char *blk_name, const char *qdev_id,
2369b33945cfSKevin Wolf                         bool force, Error **errp)
23707d8a9f71SMax Reitz {
23717d8a9f71SMax Reitz     BlockBackend *blk;
2372b33945cfSKevin Wolf     const char *device = qdev_id ?: blk_name;
23737d8a9f71SMax Reitz     bool locked;
23747d8a9f71SMax Reitz 
2375b33945cfSKevin Wolf     blk = qmp_get_blk(blk_name, qdev_id, errp);
23767d8a9f71SMax Reitz     if (!blk) {
23773a3086b7SJohn Snow         return -ENODEV;
23787d8a9f71SMax Reitz     }
23797d8a9f71SMax Reitz 
23807d8a9f71SMax Reitz     if (!blk_dev_has_removable_media(blk)) {
23817d8a9f71SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
23823a3086b7SJohn Snow         return -ENOTSUP;
23837d8a9f71SMax Reitz     }
23847d8a9f71SMax Reitz 
238512c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
2386bf18bee5SColin Lord         error_setg(errp, "Device '%s' does not have a tray", device);
2387bf18bee5SColin Lord         return -ENOSYS;
238812c7ec87SMax Reitz     }
238912c7ec87SMax Reitz 
23907d8a9f71SMax Reitz     if (blk_dev_is_tray_open(blk)) {
23913a3086b7SJohn Snow         return 0;
23927d8a9f71SMax Reitz     }
23937d8a9f71SMax Reitz 
23947d8a9f71SMax Reitz     locked = blk_dev_is_medium_locked(blk);
23957d8a9f71SMax Reitz     if (locked) {
23967d8a9f71SMax Reitz         blk_dev_eject_request(blk, force);
23977d8a9f71SMax Reitz     }
23987d8a9f71SMax Reitz 
23997d8a9f71SMax Reitz     if (!locked || force) {
240039829a01SKevin Wolf         blk_dev_change_media_cb(blk, false, &error_abort);
24017d8a9f71SMax Reitz     }
24023a3086b7SJohn Snow 
24033a3086b7SJohn Snow     if (locked && !force) {
2404bf18bee5SColin Lord         error_setg(errp, "Device '%s' is locked and force was not specified, "
2405bf18bee5SColin Lord                    "wait for tray to open and try again", device);
2406bf18bee5SColin Lord         return -EINPROGRESS;
24073a3086b7SJohn Snow     }
24083a3086b7SJohn Snow 
24093a3086b7SJohn Snow     return 0;
24103a3086b7SJohn Snow }
24113a3086b7SJohn Snow 
2412b33945cfSKevin Wolf void qmp_blockdev_open_tray(bool has_device, const char *device,
2413b33945cfSKevin Wolf                             bool has_id, const char *id,
2414b33945cfSKevin Wolf                             bool has_force, bool force,
24153a3086b7SJohn Snow                             Error **errp)
24163a3086b7SJohn Snow {
2417bf18bee5SColin Lord     Error *local_err = NULL;
2418bf18bee5SColin Lord     int rc;
2419bf18bee5SColin Lord 
24203a3086b7SJohn Snow     if (!has_force) {
24213a3086b7SJohn Snow         force = false;
24223a3086b7SJohn Snow     }
2423b33945cfSKevin Wolf     rc = do_open_tray(has_device ? device : NULL,
2424b33945cfSKevin Wolf                       has_id ? id : NULL,
2425b33945cfSKevin Wolf                       force, &local_err);
2426bf18bee5SColin Lord     if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2427bf18bee5SColin Lord         error_propagate(errp, local_err);
2428bf18bee5SColin Lord         return;
2429bf18bee5SColin Lord     }
2430bf18bee5SColin Lord     error_free(local_err);
24317d8a9f71SMax Reitz }
24327d8a9f71SMax Reitz 
2433b33945cfSKevin Wolf void qmp_blockdev_close_tray(bool has_device, const char *device,
2434b33945cfSKevin Wolf                              bool has_id, const char *id,
2435b33945cfSKevin Wolf                              Error **errp)
2436abaaf59dSMax Reitz {
2437abaaf59dSMax Reitz     BlockBackend *blk;
243839829a01SKevin Wolf     Error *local_err = NULL;
2439abaaf59dSMax Reitz 
2440b33945cfSKevin Wolf     device = has_device ? device : NULL;
2441b33945cfSKevin Wolf     id = has_id ? id : NULL;
2442b33945cfSKevin Wolf 
2443b33945cfSKevin Wolf     blk = qmp_get_blk(device, id, errp);
2444abaaf59dSMax Reitz     if (!blk) {
2445abaaf59dSMax Reitz         return;
2446abaaf59dSMax Reitz     }
2447abaaf59dSMax Reitz 
2448abaaf59dSMax Reitz     if (!blk_dev_has_removable_media(blk)) {
2449b33945cfSKevin Wolf         error_setg(errp, "Device '%s' is not removable", device ?: id);
2450abaaf59dSMax Reitz         return;
2451abaaf59dSMax Reitz     }
2452abaaf59dSMax Reitz 
245312c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
245412c7ec87SMax Reitz         /* Ignore this command on tray-less devices */
245512c7ec87SMax Reitz         return;
245612c7ec87SMax Reitz     }
245712c7ec87SMax Reitz 
2458abaaf59dSMax Reitz     if (!blk_dev_is_tray_open(blk)) {
2459abaaf59dSMax Reitz         return;
2460abaaf59dSMax Reitz     }
2461abaaf59dSMax Reitz 
246239829a01SKevin Wolf     blk_dev_change_media_cb(blk, true, &local_err);
246339829a01SKevin Wolf     if (local_err) {
246439829a01SKevin Wolf         error_propagate(errp, local_err);
246539829a01SKevin Wolf         return;
246639829a01SKevin Wolf     }
2467abaaf59dSMax Reitz }
2468abaaf59dSMax Reitz 
246982fcf66eSMax Reitz static void blockdev_remove_medium(bool has_device, const char *device,
247000949babSKevin Wolf                                    bool has_id, const char *id, Error **errp)
24712814f672SMax Reitz {
24722814f672SMax Reitz     BlockBackend *blk;
24732814f672SMax Reitz     BlockDriverState *bs;
24742814f672SMax Reitz     AioContext *aio_context;
247500949babSKevin Wolf     bool has_attached_device;
24762814f672SMax Reitz 
247700949babSKevin Wolf     device = has_device ? device : NULL;
247800949babSKevin Wolf     id = has_id ? id : NULL;
247900949babSKevin Wolf 
248000949babSKevin Wolf     blk = qmp_get_blk(device, id, errp);
24812814f672SMax Reitz     if (!blk) {
24822814f672SMax Reitz         return;
24832814f672SMax Reitz     }
24842814f672SMax Reitz 
24852814f672SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
248600949babSKevin Wolf     has_attached_device = blk_get_attached_dev(blk);
24872814f672SMax Reitz 
248800949babSKevin Wolf     if (has_attached_device && !blk_dev_has_removable_media(blk)) {
248900949babSKevin Wolf         error_setg(errp, "Device '%s' is not removable", device ?: id);
24902814f672SMax Reitz         return;
24912814f672SMax Reitz     }
24922814f672SMax Reitz 
249300949babSKevin Wolf     if (has_attached_device && blk_dev_has_tray(blk) &&
249400949babSKevin Wolf         !blk_dev_is_tray_open(blk))
249500949babSKevin Wolf     {
249600949babSKevin Wolf         error_setg(errp, "Tray of device '%s' is not open", device ?: id);
24972814f672SMax Reitz         return;
24982814f672SMax Reitz     }
24992814f672SMax Reitz 
25002814f672SMax Reitz     bs = blk_bs(blk);
25012814f672SMax Reitz     if (!bs) {
25022814f672SMax Reitz         return;
25032814f672SMax Reitz     }
25042814f672SMax Reitz 
25052814f672SMax Reitz     aio_context = bdrv_get_aio_context(bs);
25062814f672SMax Reitz     aio_context_acquire(aio_context);
25072814f672SMax Reitz 
25082814f672SMax Reitz     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
25092814f672SMax Reitz         goto out;
25102814f672SMax Reitz     }
25112814f672SMax Reitz 
25122814f672SMax Reitz     blk_remove_bs(blk);
25132814f672SMax Reitz 
251412c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
251512c7ec87SMax Reitz         /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
251612c7ec87SMax Reitz          * called at all); therefore, the medium needs to be ejected here.
251712c7ec87SMax Reitz          * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
251812c7ec87SMax Reitz          * value passed here (i.e. false). */
251939829a01SKevin Wolf         blk_dev_change_media_cb(blk, false, &error_abort);
252012c7ec87SMax Reitz     }
252112c7ec87SMax Reitz 
25222814f672SMax Reitz out:
25232814f672SMax Reitz     aio_context_release(aio_context);
25242814f672SMax Reitz }
25252814f672SMax Reitz 
252634ce1111SMax Reitz void qmp_blockdev_remove_medium(const char *id, Error **errp)
252782fcf66eSMax Reitz {
252882fcf66eSMax Reitz     blockdev_remove_medium(false, NULL, true, id, errp);
252982fcf66eSMax Reitz }
253082fcf66eSMax Reitz 
2531716df217SKevin Wolf static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2532d1299882SMax Reitz                                             BlockDriverState *bs, Error **errp)
2533d1299882SMax Reitz {
253439829a01SKevin Wolf     Error *local_err = NULL;
2535d1299882SMax Reitz     bool has_device;
2536d7086422SKevin Wolf     int ret;
2537d1299882SMax Reitz 
2538d1299882SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
2539d1299882SMax Reitz     has_device = blk_get_attached_dev(blk);
2540d1299882SMax Reitz 
2541d1299882SMax Reitz     if (has_device && !blk_dev_has_removable_media(blk)) {
2542716df217SKevin Wolf         error_setg(errp, "Device is not removable");
2543d1299882SMax Reitz         return;
2544d1299882SMax Reitz     }
2545d1299882SMax Reitz 
254612c7ec87SMax Reitz     if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2547716df217SKevin Wolf         error_setg(errp, "Tray of the device is not open");
2548d1299882SMax Reitz         return;
2549d1299882SMax Reitz     }
2550d1299882SMax Reitz 
2551d1299882SMax Reitz     if (blk_bs(blk)) {
2552716df217SKevin Wolf         error_setg(errp, "There already is a medium in the device");
2553d1299882SMax Reitz         return;
2554d1299882SMax Reitz     }
2555d1299882SMax Reitz 
2556d7086422SKevin Wolf     ret = blk_insert_bs(blk, bs, errp);
2557d7086422SKevin Wolf     if (ret < 0) {
2558d7086422SKevin Wolf         return;
2559d7086422SKevin Wolf     }
2560d1299882SMax Reitz 
256112c7ec87SMax Reitz     if (!blk_dev_has_tray(blk)) {
256212c7ec87SMax Reitz         /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
256312c7ec87SMax Reitz          * called at all); therefore, the medium needs to be pushed into the
256412c7ec87SMax Reitz          * slot here.
256512c7ec87SMax Reitz          * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
256612c7ec87SMax Reitz          * value passed here (i.e. true). */
256739829a01SKevin Wolf         blk_dev_change_media_cb(blk, true, &local_err);
256839829a01SKevin Wolf         if (local_err) {
256939829a01SKevin Wolf             error_propagate(errp, local_err);
257039829a01SKevin Wolf             blk_remove_bs(blk);
257139829a01SKevin Wolf             return;
257239829a01SKevin Wolf         }
257312c7ec87SMax Reitz     }
2574d1299882SMax Reitz }
2575d1299882SMax Reitz 
257682fcf66eSMax Reitz static void blockdev_insert_medium(bool has_device, const char *device,
2577716df217SKevin Wolf                                    bool has_id, const char *id,
2578716df217SKevin Wolf                                    const char *node_name, Error **errp)
2579d1299882SMax Reitz {
2580716df217SKevin Wolf     BlockBackend *blk;
2581d1299882SMax Reitz     BlockDriverState *bs;
2582d1299882SMax Reitz 
2583716df217SKevin Wolf     blk = qmp_get_blk(has_device ? device : NULL,
2584716df217SKevin Wolf                       has_id ? id : NULL,
2585716df217SKevin Wolf                       errp);
2586716df217SKevin Wolf     if (!blk) {
2587716df217SKevin Wolf         return;
2588716df217SKevin Wolf     }
2589716df217SKevin Wolf 
2590d1299882SMax Reitz     bs = bdrv_find_node(node_name);
2591d1299882SMax Reitz     if (!bs) {
2592d1299882SMax Reitz         error_setg(errp, "Node '%s' not found", node_name);
2593d1299882SMax Reitz         return;
2594d1299882SMax Reitz     }
2595d1299882SMax Reitz 
25961f0c461bSKevin Wolf     if (bdrv_has_blk(bs)) {
2597e467da7bSKevin Wolf         error_setg(errp, "Node '%s' is already in use", node_name);
2598d1299882SMax Reitz         return;
2599d1299882SMax Reitz     }
2600d1299882SMax Reitz 
2601716df217SKevin Wolf     qmp_blockdev_insert_anon_medium(blk, bs, errp);
2602d1299882SMax Reitz }
2603d1299882SMax Reitz 
260434ce1111SMax Reitz void qmp_blockdev_insert_medium(const char *id, const char *node_name,
260582fcf66eSMax Reitz                                 Error **errp)
260682fcf66eSMax Reitz {
260782fcf66eSMax Reitz     blockdev_insert_medium(false, NULL, true, id, node_name, errp);
260882fcf66eSMax Reitz }
260982fcf66eSMax Reitz 
261070e2cb3bSKevin Wolf void qmp_blockdev_change_medium(bool has_device, const char *device,
261170e2cb3bSKevin Wolf                                 bool has_id, const char *id,
261270e2cb3bSKevin Wolf                                 const char *filename,
261324fb4133SMax Reitz                                 bool has_format, const char *format,
261439ff43d9SMax Reitz                                 bool has_read_only,
261539ff43d9SMax Reitz                                 BlockdevChangeReadOnlyMode read_only,
261624fb4133SMax Reitz                                 Error **errp)
2617de2c6c05SMax Reitz {
2618de2c6c05SMax Reitz     BlockBackend *blk;
2619de2c6c05SMax Reitz     BlockDriverState *medium_bs = NULL;
26205b363937SMax Reitz     int bdrv_flags;
2621b85114f8SKevin Wolf     bool detect_zeroes;
262238a53d50SColin Lord     int rc;
2623de2c6c05SMax Reitz     QDict *options = NULL;
2624de2c6c05SMax Reitz     Error *err = NULL;
2625de2c6c05SMax Reitz 
262670e2cb3bSKevin Wolf     blk = qmp_get_blk(has_device ? device : NULL,
262770e2cb3bSKevin Wolf                       has_id ? id : NULL,
262870e2cb3bSKevin Wolf                       errp);
2629de2c6c05SMax Reitz     if (!blk) {
2630de2c6c05SMax Reitz         goto fail;
2631de2c6c05SMax Reitz     }
2632de2c6c05SMax Reitz 
2633de2c6c05SMax Reitz     if (blk_bs(blk)) {
2634de2c6c05SMax Reitz         blk_update_root_state(blk);
2635de2c6c05SMax Reitz     }
2636de2c6c05SMax Reitz 
2637de2c6c05SMax Reitz     bdrv_flags = blk_get_open_flags_from_root_state(blk);
2638156abc2fSAlyssa Milburn     bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2639e35bdc12SKevin Wolf         BDRV_O_PROTOCOL | BDRV_O_AUTO_RDONLY);
2640de2c6c05SMax Reitz 
264139ff43d9SMax Reitz     if (!has_read_only) {
264239ff43d9SMax Reitz         read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
264339ff43d9SMax Reitz     }
264439ff43d9SMax Reitz 
264539ff43d9SMax Reitz     switch (read_only) {
264639ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
264739ff43d9SMax Reitz         break;
264839ff43d9SMax Reitz 
264939ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
265039ff43d9SMax Reitz         bdrv_flags &= ~BDRV_O_RDWR;
265139ff43d9SMax Reitz         break;
265239ff43d9SMax Reitz 
265339ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
265439ff43d9SMax Reitz         bdrv_flags |= BDRV_O_RDWR;
265539ff43d9SMax Reitz         break;
265639ff43d9SMax Reitz 
265739ff43d9SMax Reitz     default:
265839ff43d9SMax Reitz         abort();
265939ff43d9SMax Reitz     }
266039ff43d9SMax Reitz 
2661de2c6c05SMax Reitz     options = qdict_new();
2662b85114f8SKevin Wolf     detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
266346f5ac20SEric Blake     qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2664b85114f8SKevin Wolf 
2665b85114f8SKevin Wolf     if (has_format) {
266646f5ac20SEric Blake         qdict_put_str(options, "driver", format);
2667de2c6c05SMax Reitz     }
2668de2c6c05SMax Reitz 
26695b363937SMax Reitz     medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
26705b363937SMax Reitz     if (!medium_bs) {
2671de2c6c05SMax Reitz         goto fail;
2672de2c6c05SMax Reitz     }
2673de2c6c05SMax Reitz 
267470e2cb3bSKevin Wolf     rc = do_open_tray(has_device ? device : NULL,
267570e2cb3bSKevin Wolf                       has_id ? id : NULL,
267670e2cb3bSKevin Wolf                       false, &err);
267738a53d50SColin Lord     if (rc && rc != -ENOSYS) {
2678de2c6c05SMax Reitz         error_propagate(errp, err);
2679de2c6c05SMax Reitz         goto fail;
2680de2c6c05SMax Reitz     }
268138a53d50SColin Lord     error_free(err);
268238a53d50SColin Lord     err = NULL;
2683de2c6c05SMax Reitz 
268482fcf66eSMax Reitz     blockdev_remove_medium(has_device, device, has_id, id, &err);
2685de2c6c05SMax Reitz     if (err) {
2686de2c6c05SMax Reitz         error_propagate(errp, err);
2687de2c6c05SMax Reitz         goto fail;
2688de2c6c05SMax Reitz     }
2689de2c6c05SMax Reitz 
2690716df217SKevin Wolf     qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2691de2c6c05SMax Reitz     if (err) {
2692de2c6c05SMax Reitz         error_propagate(errp, err);
2693de2c6c05SMax Reitz         goto fail;
2694de2c6c05SMax Reitz     }
2695de2c6c05SMax Reitz 
269670e2cb3bSKevin Wolf     qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2697de2c6c05SMax Reitz 
2698de2c6c05SMax Reitz fail:
2699de2c6c05SMax Reitz     /* If the medium has been inserted, the device has its own reference, so
2700de2c6c05SMax Reitz      * ours must be relinquished; and if it has not been inserted successfully,
2701de2c6c05SMax Reitz      * the reference must be relinquished anyway */
2702de2c6c05SMax Reitz     bdrv_unref(medium_bs);
2703de2c6c05SMax Reitz }
2704de2c6c05SMax Reitz 
2705727f005eSZhi Yong Wu /* throttling disk I/O limits */
27064dc9397bSEric Blake void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2707727f005eSZhi Yong Wu {
2708cc0681c4SBenoît Canet     ThrottleConfig cfg;
2709727f005eSZhi Yong Wu     BlockDriverState *bs;
2710a0e8544cSFam Zheng     BlockBackend *blk;
2711b15446fdSStefan Hajnoczi     AioContext *aio_context;
2712727f005eSZhi Yong Wu 
27137a9877a0SKevin Wolf     blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
27147a9877a0SKevin Wolf                       arg->has_id ? arg->id : NULL,
27157a9877a0SKevin Wolf                       errp);
2716a0e8544cSFam Zheng     if (!blk) {
271780047da5SLuiz Capitulino         return;
2718727f005eSZhi Yong Wu     }
27195433c24fSMax Reitz 
27205433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
27215433c24fSMax Reitz     aio_context_acquire(aio_context);
27225433c24fSMax Reitz 
2723a0e8544cSFam Zheng     bs = blk_bs(blk);
27245433c24fSMax Reitz     if (!bs) {
27257a9877a0SKevin Wolf         error_setg(errp, "Device has no medium");
27265433c24fSMax Reitz         goto out;
27275433c24fSMax Reitz     }
2728727f005eSZhi Yong Wu 
27291588ab5dSAlberto Garcia     throttle_config_init(&cfg);
27304dc9397bSEric Blake     cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
27314dc9397bSEric Blake     cfg.buckets[THROTTLE_BPS_READ].avg  = arg->bps_rd;
27324dc9397bSEric Blake     cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2733727f005eSZhi Yong Wu 
27344dc9397bSEric Blake     cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
27354dc9397bSEric Blake     cfg.buckets[THROTTLE_OPS_READ].avg  = arg->iops_rd;
27364dc9397bSEric Blake     cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2737cc0681c4SBenoît Canet 
27384dc9397bSEric Blake     if (arg->has_bps_max) {
27394dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
27403e9fab69SBenoît Canet     }
27414dc9397bSEric Blake     if (arg->has_bps_rd_max) {
27424dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
27433e9fab69SBenoît Canet     }
27444dc9397bSEric Blake     if (arg->has_bps_wr_max) {
27454dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
27463e9fab69SBenoît Canet     }
27474dc9397bSEric Blake     if (arg->has_iops_max) {
27484dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
27493e9fab69SBenoît Canet     }
27504dc9397bSEric Blake     if (arg->has_iops_rd_max) {
27514dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
27523e9fab69SBenoît Canet     }
27534dc9397bSEric Blake     if (arg->has_iops_wr_max) {
27544dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
27553e9fab69SBenoît Canet     }
2756cc0681c4SBenoît Canet 
27574dc9397bSEric Blake     if (arg->has_bps_max_length) {
27584dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2759dce13204SAlberto Garcia     }
27604dc9397bSEric Blake     if (arg->has_bps_rd_max_length) {
27614dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2762dce13204SAlberto Garcia     }
27634dc9397bSEric Blake     if (arg->has_bps_wr_max_length) {
27644dc9397bSEric Blake         cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2765dce13204SAlberto Garcia     }
27664dc9397bSEric Blake     if (arg->has_iops_max_length) {
27674dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2768dce13204SAlberto Garcia     }
27694dc9397bSEric Blake     if (arg->has_iops_rd_max_length) {
27704dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2771dce13204SAlberto Garcia     }
27724dc9397bSEric Blake     if (arg->has_iops_wr_max_length) {
27734dc9397bSEric Blake         cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2774dce13204SAlberto Garcia     }
2775dce13204SAlberto Garcia 
27764dc9397bSEric Blake     if (arg->has_iops_size) {
27774dc9397bSEric Blake         cfg.op_size = arg->iops_size;
27782024c1dfSBenoît Canet     }
2779cc0681c4SBenoît Canet 
2780d5851089SAlberto Garcia     if (!throttle_is_valid(&cfg, errp)) {
27815433c24fSMax Reitz         goto out;
2782727f005eSZhi Yong Wu     }
2783727f005eSZhi Yong Wu 
278476f4afb4SAlberto Garcia     if (throttle_enabled(&cfg)) {
278576f4afb4SAlberto Garcia         /* Enable I/O limits if they're not enabled yet, otherwise
278676f4afb4SAlberto Garcia          * just update the throttling group. */
2787022cdc9fSManos Pitsidianakis         if (!blk_get_public(blk)->throttle_group_member.throttle_state) {
27884dc9397bSEric Blake             blk_io_limits_enable(blk,
27897a9877a0SKevin Wolf                                  arg->has_group ? arg->group :
27907a9877a0SKevin Wolf                                  arg->has_device ? arg->device :
27917a9877a0SKevin Wolf                                  arg->id);
27924dc9397bSEric Blake         } else if (arg->has_group) {
27934dc9397bSEric Blake             blk_io_limits_update_group(blk, arg->group);
2794727f005eSZhi Yong Wu         }
279576f4afb4SAlberto Garcia         /* Set the new throttling configuration */
279697148076SKevin Wolf         blk_set_io_limits(blk, &cfg);
2797022cdc9fSManos Pitsidianakis     } else if (blk_get_public(blk)->throttle_group_member.throttle_state) {
279876f4afb4SAlberto Garcia         /* If all throttling settings are set to 0, disable I/O limits */
279997148076SKevin Wolf         blk_io_limits_disable(blk);
2800727f005eSZhi Yong Wu     }
2801b15446fdSStefan Hajnoczi 
28025433c24fSMax Reitz out:
2803b15446fdSStefan Hajnoczi     aio_context_release(aio_context);
2804727f005eSZhi Yong Wu }
2805727f005eSZhi Yong Wu 
2806341ebc2fSJohn Snow void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2807341ebc2fSJohn Snow                                 bool has_granularity, uint32_t granularity,
2808fd5ae4ccSVladimir Sementsov-Ogievskiy                                 bool has_persistent, bool persistent,
2809eb738bb5SVladimir Sementsov-Ogievskiy                                 bool has_autoload, bool autoload,
2810a6e2ca5fSVladimir Sementsov-Ogievskiy                                 bool has_disabled, bool disabled,
2811341ebc2fSJohn Snow                                 Error **errp)
2812341ebc2fSJohn Snow {
2813341ebc2fSJohn Snow     BlockDriverState *bs;
2814fd5ae4ccSVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
28150a6c86d0SJohn Snow     AioContext *aio_context = NULL;
2816341ebc2fSJohn Snow 
2817341ebc2fSJohn Snow     if (!name || name[0] == '\0') {
2818341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be empty");
2819341ebc2fSJohn Snow         return;
2820341ebc2fSJohn Snow     }
2821341ebc2fSJohn Snow 
2822341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, errp);
2823341ebc2fSJohn Snow     if (!bs) {
2824341ebc2fSJohn Snow         return;
2825341ebc2fSJohn Snow     }
2826341ebc2fSJohn Snow 
2827341ebc2fSJohn Snow     if (has_granularity) {
2828341ebc2fSJohn Snow         if (granularity < 512 || !is_power_of_2(granularity)) {
2829341ebc2fSJohn Snow             error_setg(errp, "Granularity must be power of 2 "
2830341ebc2fSJohn Snow                              "and at least 512");
28312119882cSPaolo Bonzini             return;
2832341ebc2fSJohn Snow         }
2833341ebc2fSJohn Snow     } else {
2834341ebc2fSJohn Snow         /* Default to cluster size, if available: */
2835341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(bs);
2836341ebc2fSJohn Snow     }
2837341ebc2fSJohn Snow 
2838fd5ae4ccSVladimir Sementsov-Ogievskiy     if (!has_persistent) {
2839fd5ae4ccSVladimir Sementsov-Ogievskiy         persistent = false;
2840fd5ae4ccSVladimir Sementsov-Ogievskiy     }
2841eb738bb5SVladimir Sementsov-Ogievskiy 
28423e99da5eSVladimir Sementsov-Ogievskiy     if (has_autoload) {
28433e99da5eSVladimir Sementsov-Ogievskiy         warn_report("Autoload option is deprecated and its value is ignored");
2844eb738bb5SVladimir Sementsov-Ogievskiy     }
2845fd5ae4ccSVladimir Sementsov-Ogievskiy 
2846a6e2ca5fSVladimir Sementsov-Ogievskiy     if (!has_disabled) {
2847a6e2ca5fSVladimir Sementsov-Ogievskiy         disabled = false;
2848a6e2ca5fSVladimir Sementsov-Ogievskiy     }
2849a6e2ca5fSVladimir Sementsov-Ogievskiy 
28500a6c86d0SJohn Snow     if (persistent) {
28510a6c86d0SJohn Snow         aio_context = bdrv_get_aio_context(bs);
28520a6c86d0SJohn Snow         aio_context_acquire(aio_context);
28530a6c86d0SJohn Snow         if (!bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp)) {
28540a6c86d0SJohn Snow             goto out;
28550a6c86d0SJohn Snow         }
2856fd5ae4ccSVladimir Sementsov-Ogievskiy     }
2857fd5ae4ccSVladimir Sementsov-Ogievskiy 
2858fd5ae4ccSVladimir Sementsov-Ogievskiy     bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2859eb738bb5SVladimir Sementsov-Ogievskiy     if (bitmap == NULL) {
28600a6c86d0SJohn Snow         goto out;
2861fd5ae4ccSVladimir Sementsov-Ogievskiy     }
2862eb738bb5SVladimir Sementsov-Ogievskiy 
2863a6e2ca5fSVladimir Sementsov-Ogievskiy     if (disabled) {
2864a6e2ca5fSVladimir Sementsov-Ogievskiy         bdrv_disable_dirty_bitmap(bitmap);
2865a6e2ca5fSVladimir Sementsov-Ogievskiy     }
2866a6e2ca5fSVladimir Sementsov-Ogievskiy 
2867796a3798SEric Blake     bdrv_dirty_bitmap_set_persistence(bitmap, persistent);
28680a6c86d0SJohn Snow  out:
28690a6c86d0SJohn Snow     if (aio_context) {
28700a6c86d0SJohn Snow         aio_context_release(aio_context);
28710a6c86d0SJohn Snow     }
2872341ebc2fSJohn Snow }
2873341ebc2fSJohn Snow 
2874341ebc2fSJohn Snow void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2875341ebc2fSJohn Snow                                    Error **errp)
2876341ebc2fSJohn Snow {
2877341ebc2fSJohn Snow     BlockDriverState *bs;
2878341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
28795c36c1afSVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
28800a6c86d0SJohn Snow     AioContext *aio_context = 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 
2887c3edf13cSJohn Snow     if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_BUSY | BDRV_BITMAP_RO,
2888c3edf13cSJohn Snow                                 errp)) {
28894f43e953SVladimir Sementsov-Ogievskiy         return;
28909bd2b08fSJohn Snow     }
28915c36c1afSVladimir Sementsov-Ogievskiy 
2892796a3798SEric Blake     if (bdrv_dirty_bitmap_get_persistence(bitmap)) {
28930a6c86d0SJohn Snow         aio_context = bdrv_get_aio_context(bs);
28940a6c86d0SJohn Snow         aio_context_acquire(aio_context);
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);
28980a6c86d0SJohn Snow             goto out;
28995c36c1afSVladimir Sementsov-Ogievskiy         }
29005c36c1afSVladimir Sementsov-Ogievskiy     }
29015c36c1afSVladimir Sementsov-Ogievskiy 
2902341ebc2fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
29030a6c86d0SJohn Snow  out:
29040a6c86d0SJohn Snow     if (aio_context) {
29050a6c86d0SJohn Snow         aio_context_release(aio_context);
29060a6c86d0SJohn Snow     }
2907341ebc2fSJohn Snow }
2908341ebc2fSJohn Snow 
2909e74e6b78SJohn Snow /**
2910e74e6b78SJohn Snow  * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2911e74e6b78SJohn Snow  * immediately after a full backup operation.
2912e74e6b78SJohn Snow  */
2913e74e6b78SJohn Snow void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2914e74e6b78SJohn Snow                                   Error **errp)
2915e74e6b78SJohn Snow {
2916e74e6b78SJohn Snow     BdrvDirtyBitmap *bitmap;
2917e74e6b78SJohn Snow     BlockDriverState *bs;
2918e74e6b78SJohn Snow 
29192119882cSPaolo Bonzini     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2920e74e6b78SJohn Snow     if (!bitmap || !bs) {
2921e74e6b78SJohn Snow         return;
2922e74e6b78SJohn Snow     }
2923e74e6b78SJohn Snow 
29243ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_DEFAULT, errp)) {
2925d6883bc9SVladimir Sementsov-Ogievskiy         return;
2926e74e6b78SJohn Snow     }
2927e74e6b78SJohn Snow 
2928df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(bitmap, NULL);
2929e74e6b78SJohn Snow }
2930e74e6b78SJohn Snow 
29310e2b7f09SJohn Snow void qmp_block_dirty_bitmap_enable(const char *node, const char *name,
29325c5d2e50SVladimir Sementsov-Ogievskiy                                    Error **errp)
29335c5d2e50SVladimir Sementsov-Ogievskiy {
29345c5d2e50SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
29355c5d2e50SVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
29365c5d2e50SVladimir Sementsov-Ogievskiy 
29375c5d2e50SVladimir Sementsov-Ogievskiy     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
29385c5d2e50SVladimir Sementsov-Ogievskiy     if (!bitmap) {
29395c5d2e50SVladimir Sementsov-Ogievskiy         return;
29405c5d2e50SVladimir Sementsov-Ogievskiy     }
29415c5d2e50SVladimir Sementsov-Ogievskiy 
29423ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
29435c5d2e50SVladimir Sementsov-Ogievskiy         return;
29445c5d2e50SVladimir Sementsov-Ogievskiy     }
29455c5d2e50SVladimir Sementsov-Ogievskiy 
29465c5d2e50SVladimir Sementsov-Ogievskiy     bdrv_enable_dirty_bitmap(bitmap);
29475c5d2e50SVladimir Sementsov-Ogievskiy }
29485c5d2e50SVladimir Sementsov-Ogievskiy 
29490e2b7f09SJohn Snow void qmp_block_dirty_bitmap_disable(const char *node, const char *name,
29505c5d2e50SVladimir Sementsov-Ogievskiy                                     Error **errp)
29515c5d2e50SVladimir Sementsov-Ogievskiy {
29525c5d2e50SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
29535c5d2e50SVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
29545c5d2e50SVladimir Sementsov-Ogievskiy 
29555c5d2e50SVladimir Sementsov-Ogievskiy     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
29565c5d2e50SVladimir Sementsov-Ogievskiy     if (!bitmap) {
29575c5d2e50SVladimir Sementsov-Ogievskiy         return;
29585c5d2e50SVladimir Sementsov-Ogievskiy     }
29595c5d2e50SVladimir Sementsov-Ogievskiy 
29603ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
29615c5d2e50SVladimir Sementsov-Ogievskiy         return;
29625c5d2e50SVladimir Sementsov-Ogievskiy     }
29635c5d2e50SVladimir Sementsov-Ogievskiy 
29645c5d2e50SVladimir Sementsov-Ogievskiy     bdrv_disable_dirty_bitmap(bitmap);
29655c5d2e50SVladimir Sementsov-Ogievskiy }
29665c5d2e50SVladimir Sementsov-Ogievskiy 
2967*eff0829bSVladimir Sementsov-Ogievskiy static BdrvDirtyBitmap *do_block_dirty_bitmap_merge(
2968*eff0829bSVladimir Sementsov-Ogievskiy         const char *node, const char *target,
2969*eff0829bSVladimir Sementsov-Ogievskiy         BlockDirtyBitmapMergeSourceList *bitmaps,
2970*eff0829bSVladimir Sementsov-Ogievskiy         HBitmap **backup, Error **errp)
2971b598e531SVladimir Sementsov-Ogievskiy {
2972b598e531SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
2973360d4e4eSJohn Snow     BdrvDirtyBitmap *dst, *src, *anon;
2974*eff0829bSVladimir Sementsov-Ogievskiy     BlockDirtyBitmapMergeSourceList *lst;
2975360d4e4eSJohn Snow     Error *local_err = NULL;
2976b598e531SVladimir Sementsov-Ogievskiy 
2977360d4e4eSJohn Snow     dst = block_dirty_bitmap_lookup(node, target, &bs, errp);
2978b598e531SVladimir Sementsov-Ogievskiy     if (!dst) {
2979360d4e4eSJohn Snow         return NULL;
2980b598e531SVladimir Sementsov-Ogievskiy     }
2981b598e531SVladimir Sementsov-Ogievskiy 
2982360d4e4eSJohn Snow     anon = bdrv_create_dirty_bitmap(bs, bdrv_dirty_bitmap_granularity(dst),
2983360d4e4eSJohn Snow                                     NULL, errp);
2984360d4e4eSJohn Snow     if (!anon) {
2985360d4e4eSJohn Snow         return NULL;
2986360d4e4eSJohn Snow     }
2987360d4e4eSJohn Snow 
2988360d4e4eSJohn Snow     for (lst = bitmaps; lst; lst = lst->next) {
2989*eff0829bSVladimir Sementsov-Ogievskiy         switch (lst->value->type) {
2990*eff0829bSVladimir Sementsov-Ogievskiy             const char *name, *node;
2991*eff0829bSVladimir Sementsov-Ogievskiy         case QTYPE_QSTRING:
2992*eff0829bSVladimir Sementsov-Ogievskiy             name = lst->value->u.local;
2993*eff0829bSVladimir Sementsov-Ogievskiy             src = bdrv_find_dirty_bitmap(bs, name);
2994b598e531SVladimir Sementsov-Ogievskiy             if (!src) {
2995*eff0829bSVladimir Sementsov-Ogievskiy                 error_setg(errp, "Dirty bitmap '%s' not found", name);
2996360d4e4eSJohn Snow                 dst = NULL;
2997360d4e4eSJohn Snow                 goto out;
2998b598e531SVladimir Sementsov-Ogievskiy             }
2999*eff0829bSVladimir Sementsov-Ogievskiy             break;
3000*eff0829bSVladimir Sementsov-Ogievskiy         case QTYPE_QDICT:
3001*eff0829bSVladimir Sementsov-Ogievskiy             node = lst->value->u.external.node;
3002*eff0829bSVladimir Sementsov-Ogievskiy             name = lst->value->u.external.name;
3003*eff0829bSVladimir Sementsov-Ogievskiy             src = block_dirty_bitmap_lookup(node, name, NULL, errp);
3004*eff0829bSVladimir Sementsov-Ogievskiy             if (!src) {
3005*eff0829bSVladimir Sementsov-Ogievskiy                 dst = NULL;
3006*eff0829bSVladimir Sementsov-Ogievskiy                 goto out;
3007*eff0829bSVladimir Sementsov-Ogievskiy             }
3008*eff0829bSVladimir Sementsov-Ogievskiy             break;
3009*eff0829bSVladimir Sementsov-Ogievskiy         default:
3010*eff0829bSVladimir Sementsov-Ogievskiy             abort();
3011*eff0829bSVladimir Sementsov-Ogievskiy         }
3012b598e531SVladimir Sementsov-Ogievskiy 
3013360d4e4eSJohn Snow         bdrv_merge_dirty_bitmap(anon, src, NULL, &local_err);
3014360d4e4eSJohn Snow         if (local_err) {
3015360d4e4eSJohn Snow             error_propagate(errp, local_err);
3016360d4e4eSJohn Snow             dst = NULL;
3017360d4e4eSJohn Snow             goto out;
3018360d4e4eSJohn Snow         }
3019360d4e4eSJohn Snow     }
3020360d4e4eSJohn Snow 
3021360d4e4eSJohn Snow     /* Merge into dst; dst is unchanged on failure. */
3022360d4e4eSJohn Snow     bdrv_merge_dirty_bitmap(dst, anon, backup, errp);
3023360d4e4eSJohn Snow 
3024360d4e4eSJohn Snow  out:
3025360d4e4eSJohn Snow     bdrv_release_dirty_bitmap(bs, anon);
3026360d4e4eSJohn Snow     return dst;
3027360d4e4eSJohn Snow }
3028360d4e4eSJohn Snow 
30290e2b7f09SJohn Snow void qmp_block_dirty_bitmap_merge(const char *node, const char *target,
3030*eff0829bSVladimir Sementsov-Ogievskiy                                   BlockDirtyBitmapMergeSourceList *bitmaps,
3031*eff0829bSVladimir Sementsov-Ogievskiy                                   Error **errp)
3032360d4e4eSJohn Snow {
3033360d4e4eSJohn Snow     do_block_dirty_bitmap_merge(node, target, bitmaps, NULL, errp);
3034b598e531SVladimir Sementsov-Ogievskiy }
3035b598e531SVladimir Sementsov-Ogievskiy 
3036a3b52535SVladimir Sementsov-Ogievskiy BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
3037a3b52535SVladimir Sementsov-Ogievskiy                                                               const char *name,
3038a3b52535SVladimir Sementsov-Ogievskiy                                                               Error **errp)
3039a3b52535SVladimir Sementsov-Ogievskiy {
3040a3b52535SVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
3041a3b52535SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
3042a3b52535SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapSha256 *ret = NULL;
3043a3b52535SVladimir Sementsov-Ogievskiy     char *sha256;
3044a3b52535SVladimir Sementsov-Ogievskiy 
3045a3b52535SVladimir Sementsov-Ogievskiy     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3046a3b52535SVladimir Sementsov-Ogievskiy     if (!bitmap || !bs) {
3047a3b52535SVladimir Sementsov-Ogievskiy         return NULL;
3048a3b52535SVladimir Sementsov-Ogievskiy     }
3049a3b52535SVladimir Sementsov-Ogievskiy 
3050a3b52535SVladimir Sementsov-Ogievskiy     sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
3051a3b52535SVladimir Sementsov-Ogievskiy     if (sha256 == NULL) {
3052a3b52535SVladimir Sementsov-Ogievskiy         return NULL;
3053a3b52535SVladimir Sementsov-Ogievskiy     }
3054a3b52535SVladimir Sementsov-Ogievskiy 
3055a3b52535SVladimir Sementsov-Ogievskiy     ret = g_new(BlockDirtyBitmapSha256, 1);
3056a3b52535SVladimir Sementsov-Ogievskiy     ret->sha256 = sha256;
3057a3b52535SVladimir Sementsov-Ogievskiy 
3058a3b52535SVladimir Sementsov-Ogievskiy     return ret;
3059a3b52535SVladimir Sementsov-Ogievskiy }
3060a3b52535SVladimir Sementsov-Ogievskiy 
3061072ebe6bSMarkus Armbruster void hmp_drive_del(Monitor *mon, const QDict *qdict)
30629063f814SRyan Harper {
30639063f814SRyan Harper     const char *id = qdict_get_str(qdict, "id");
30647e7d56d9SMarkus Armbruster     BlockBackend *blk;
30659063f814SRyan Harper     BlockDriverState *bs;
30668ad4202bSStefan Hajnoczi     AioContext *aio_context;
30673718d8abSFam Zheng     Error *local_err = NULL;
30689063f814SRyan Harper 
30692073d410SKevin Wolf     bs = bdrv_find_node(id);
30702073d410SKevin Wolf     if (bs) {
307179b7a77eSMarkus Armbruster         qmp_blockdev_del(id, &local_err);
30722073d410SKevin Wolf         if (local_err) {
30732073d410SKevin Wolf             error_report_err(local_err);
30742073d410SKevin Wolf         }
30752073d410SKevin Wolf         return;
30762073d410SKevin Wolf     }
30772073d410SKevin Wolf 
30787e7d56d9SMarkus Armbruster     blk = blk_by_name(id);
30797e7d56d9SMarkus Armbruster     if (!blk) {
3080b1422f20SMarkus Armbruster         error_report("Device '%s' not found", id);
3081072ebe6bSMarkus Armbruster         return;
30829063f814SRyan Harper     }
30838ad4202bSStefan Hajnoczi 
308426f8b3a8SMarkus Armbruster     if (!blk_legacy_dinfo(blk)) {
308548f364ddSMarkus Armbruster         error_report("Deleting device added with blockdev-add"
308648f364ddSMarkus Armbruster                      " is not supported");
3087072ebe6bSMarkus Armbruster         return;
308848f364ddSMarkus Armbruster     }
308948f364ddSMarkus Armbruster 
30905433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
30918ad4202bSStefan Hajnoczi     aio_context_acquire(aio_context);
30928ad4202bSStefan Hajnoczi 
30935433c24fSMax Reitz     bs = blk_bs(blk);
30945433c24fSMax Reitz     if (bs) {
30953718d8abSFam Zheng         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
3096565f65d2SMarkus Armbruster             error_report_err(local_err);
30978ad4202bSStefan Hajnoczi             aio_context_release(aio_context);
3098072ebe6bSMarkus Armbruster             return;
30998591675fSMarcelo Tosatti         }
31009063f814SRyan Harper 
3101938abd43SMax Reitz         blk_remove_bs(blk);
31025433c24fSMax Reitz     }
31039063f814SRyan Harper 
31047c735873SMax Reitz     /* Make the BlockBackend and the attached BlockDriverState anonymous */
3105efaa7c4eSMax Reitz     monitor_remove_blk(blk);
3106efaa7c4eSMax Reitz 
31077c735873SMax Reitz     /* If this BlockBackend has a device attached to it, its refcount will be
31087c735873SMax Reitz      * decremented when the device is removed; otherwise we have to do so here.
3109d22b2f41SRyan Harper      */
3110a7f53e26SMarkus Armbruster     if (blk_get_attached_dev(blk)) {
3111293c51a6SStefan Hajnoczi         /* Further I/O must not pause the guest */
3112373340b2SMax Reitz         blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
3113293c51a6SStefan Hajnoczi                          BLOCKDEV_ON_ERROR_REPORT);
3114d22b2f41SRyan Harper     } else {
3115b9fe8a7aSMarkus Armbruster         blk_unref(blk);
3116d22b2f41SRyan Harper     }
31179063f814SRyan Harper 
31188ad4202bSStefan Hajnoczi     aio_context_release(aio_context);
31199063f814SRyan Harper }
31206d4a2b3aSChristoph Hellwig 
31213b1dbd11SBenoît Canet void qmp_block_resize(bool has_device, const char *device,
31223b1dbd11SBenoît Canet                       bool has_node_name, const char *node_name,
31233b1dbd11SBenoît Canet                       int64_t size, Error **errp)
31246d4a2b3aSChristoph Hellwig {
31253b1dbd11SBenoît Canet     Error *local_err = NULL;
31267dad9ee6SKevin Wolf     BlockBackend *blk = NULL;
31276d4a2b3aSChristoph Hellwig     BlockDriverState *bs;
3128927e0e76SStefan Hajnoczi     AioContext *aio_context;
31298732901eSKevin Wolf     int ret;
31306d4a2b3aSChristoph Hellwig 
31313b1dbd11SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
31323b1dbd11SBenoît Canet                         has_node_name ? node_name : NULL,
31333b1dbd11SBenoît Canet                         &local_err);
313484d18f06SMarkus Armbruster     if (local_err) {
31353b1dbd11SBenoît Canet         error_propagate(errp, local_err);
31363b1dbd11SBenoît Canet         return;
31373b1dbd11SBenoît Canet     }
31383b1dbd11SBenoît Canet 
3139927e0e76SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
3140927e0e76SStefan Hajnoczi     aio_context_acquire(aio_context);
3141927e0e76SStefan Hajnoczi 
31423b1dbd11SBenoît Canet     if (!bdrv_is_first_non_filter(bs)) {
3143c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "resize");
3144927e0e76SStefan Hajnoczi         goto out;
31456d4a2b3aSChristoph Hellwig     }
31466d4a2b3aSChristoph Hellwig 
31476d4a2b3aSChristoph Hellwig     if (size < 0) {
3148c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
3149927e0e76SStefan Hajnoczi         goto out;
31506d4a2b3aSChristoph Hellwig     }
31516d4a2b3aSChristoph Hellwig 
31529c75e168SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
3153c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
3154927e0e76SStefan Hajnoczi         goto out;
31559c75e168SJeff Cody     }
31569c75e168SJeff Cody 
31576d0eb64dSKevin Wolf     blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
3158d7086422SKevin Wolf     ret = blk_insert_bs(blk, bs, errp);
3159d7086422SKevin Wolf     if (ret < 0) {
3160d7086422SKevin Wolf         goto out;
3161d7086422SKevin Wolf     }
31627dad9ee6SKevin Wolf 
3163698bdfa0SJohn Snow     bdrv_drained_begin(bs);
31643a691c50SMax Reitz     ret = blk_truncate(blk, size, PREALLOC_MODE_OFF, errp);
3165698bdfa0SJohn Snow     bdrv_drained_end(bs);
3166927e0e76SStefan Hajnoczi 
3167927e0e76SStefan Hajnoczi out:
31687dad9ee6SKevin Wolf     blk_unref(blk);
3169927e0e76SStefan Hajnoczi     aio_context_release(aio_context);
31706d4a2b3aSChristoph Hellwig }
317112bd451fSStefan Hajnoczi 
31722323322eSAlberto Garcia void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
317313d8cc51SJeff Cody                       bool has_base, const char *base,
3174312fe09cSAlberto Garcia                       bool has_base_node, const char *base_node,
317513d8cc51SJeff Cody                       bool has_backing_file, const char *backing_file,
317613d8cc51SJeff Cody                       bool has_speed, int64_t speed,
31771d809098SPaolo Bonzini                       bool has_on_error, BlockdevOnError on_error,
3178241ca1abSJohn Snow                       bool has_auto_finalize, bool auto_finalize,
3179241ca1abSJohn Snow                       bool has_auto_dismiss, bool auto_dismiss,
31801d809098SPaolo Bonzini                       Error **errp)
318112bd451fSStefan Hajnoczi {
3182554b6147SAlberto Garcia     BlockDriverState *bs, *iter;
3183c8c3080fSMarcelo Tosatti     BlockDriverState *base_bs = NULL;
3184f3e69bebSStefan Hajnoczi     AioContext *aio_context;
3185fd7f8c65SStefan Hajnoczi     Error *local_err = NULL;
318613d8cc51SJeff Cody     const char *base_name = NULL;
3187cf6320dfSJohn Snow     int job_flags = JOB_DEFAULT;
318812bd451fSStefan Hajnoczi 
31891d809098SPaolo Bonzini     if (!has_on_error) {
31901d809098SPaolo Bonzini         on_error = BLOCKDEV_ON_ERROR_REPORT;
31911d809098SPaolo Bonzini     }
31921d809098SPaolo Bonzini 
3193554b6147SAlberto Garcia     bs = bdrv_lookup_bs(device, device, errp);
3194b6c1bae5SKevin Wolf     if (!bs) {
319512bd451fSStefan Hajnoczi         return;
319612bd451fSStefan Hajnoczi     }
319712bd451fSStefan Hajnoczi 
3198b6c1bae5SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3199f3e69bebSStefan Hajnoczi     aio_context_acquire(aio_context);
3200f3e69bebSStefan Hajnoczi 
3201312fe09cSAlberto Garcia     if (has_base && has_base_node) {
3202312fe09cSAlberto Garcia         error_setg(errp, "'base' and 'base-node' cannot be specified "
3203312fe09cSAlberto Garcia                    "at the same time");
3204312fe09cSAlberto Garcia         goto out;
3205312fe09cSAlberto Garcia     }
3206312fe09cSAlberto Garcia 
320713d8cc51SJeff Cody     if (has_base) {
3208c8c3080fSMarcelo Tosatti         base_bs = bdrv_find_backing_image(bs, base);
3209c8c3080fSMarcelo Tosatti         if (base_bs == NULL) {
3210c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_BASE_NOT_FOUND, base);
3211f3e69bebSStefan Hajnoczi             goto out;
321212bd451fSStefan Hajnoczi         }
3213f3e69bebSStefan Hajnoczi         assert(bdrv_get_aio_context(base_bs) == aio_context);
321413d8cc51SJeff Cody         base_name = base;
3215c8c3080fSMarcelo Tosatti     }
321612bd451fSStefan Hajnoczi 
3217312fe09cSAlberto Garcia     if (has_base_node) {
3218312fe09cSAlberto Garcia         base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3219312fe09cSAlberto Garcia         if (!base_bs) {
3220312fe09cSAlberto Garcia             goto out;
3221312fe09cSAlberto Garcia         }
3222312fe09cSAlberto Garcia         if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3223312fe09cSAlberto Garcia             error_setg(errp, "Node '%s' is not a backing image of '%s'",
3224312fe09cSAlberto Garcia                        base_node, device);
3225312fe09cSAlberto Garcia             goto out;
3226312fe09cSAlberto Garcia         }
3227312fe09cSAlberto Garcia         assert(bdrv_get_aio_context(base_bs) == aio_context);
3228f30c66baSMax Reitz         bdrv_refresh_filename(base_bs);
3229312fe09cSAlberto Garcia         base_name = base_bs->filename;
3230312fe09cSAlberto Garcia     }
3231312fe09cSAlberto Garcia 
3232554b6147SAlberto Garcia     /* Check for op blockers in the whole chain between bs and base */
3233554b6147SAlberto Garcia     for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3234554b6147SAlberto Garcia         if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3235554b6147SAlberto Garcia             goto out;
3236554b6147SAlberto Garcia         }
3237554b6147SAlberto Garcia     }
3238554b6147SAlberto Garcia 
323913d8cc51SJeff Cody     /* if we are streaming the entire chain, the result will have no backing
324013d8cc51SJeff Cody      * file, and specifying one is therefore an error */
324113d8cc51SJeff Cody     if (base_bs == NULL && has_backing_file) {
324213d8cc51SJeff Cody         error_setg(errp, "backing file specified, but streaming the "
324313d8cc51SJeff Cody                          "entire chain");
3244f3e69bebSStefan Hajnoczi         goto out;
324513d8cc51SJeff Cody     }
324613d8cc51SJeff Cody 
324713d8cc51SJeff Cody     /* backing_file string overrides base bs filename */
324813d8cc51SJeff Cody     base_name = has_backing_file ? backing_file : base_name;
324913d8cc51SJeff Cody 
3250241ca1abSJohn Snow     if (has_auto_finalize && !auto_finalize) {
3251241ca1abSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
3252241ca1abSJohn Snow     }
3253241ca1abSJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
3254241ca1abSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
3255241ca1abSJohn Snow     }
3256241ca1abSJohn Snow 
32572323322eSAlberto Garcia     stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3258cf6320dfSJohn Snow                  job_flags, has_speed ? speed : 0, on_error, &local_err);
325984d18f06SMarkus Armbruster     if (local_err) {
3260fd7f8c65SStefan Hajnoczi         error_propagate(errp, local_err);
3261f3e69bebSStefan Hajnoczi         goto out;
326212bd451fSStefan Hajnoczi     }
326312bd451fSStefan Hajnoczi 
326412bd451fSStefan Hajnoczi     trace_qmp_block_stream(bs, bs->job);
3265f3e69bebSStefan Hajnoczi 
3266f3e69bebSStefan Hajnoczi out:
3267f3e69bebSStefan Hajnoczi     aio_context_release(aio_context);
326812bd451fSStefan Hajnoczi }
32692d47c6e9SStefan Hajnoczi 
3270fd62c609SAlberto Garcia void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
32713c605f40SKevin Wolf                       bool has_base_node, const char *base_node,
32727676e2c5SJeff Cody                       bool has_base, const char *base,
32733c605f40SKevin Wolf                       bool has_top_node, const char *top_node,
32747676e2c5SJeff Cody                       bool has_top, const char *top,
327554e26900SJeff Cody                       bool has_backing_file, const char *backing_file,
3276ed61fc10SJeff Cody                       bool has_speed, int64_t speed,
32770db832f4SKevin Wolf                       bool has_filter_node_name, const char *filter_node_name,
327896fbf534SJohn Snow                       bool has_auto_finalize, bool auto_finalize,
327996fbf534SJohn Snow                       bool has_auto_dismiss, bool auto_dismiss,
3280ed61fc10SJeff Cody                       Error **errp)
3281ed61fc10SJeff Cody {
3282ed61fc10SJeff Cody     BlockDriverState *bs;
3283058223a6SAlberto Garcia     BlockDriverState *iter;
3284ed61fc10SJeff Cody     BlockDriverState *base_bs, *top_bs;
32859e85cd5cSStefan Hajnoczi     AioContext *aio_context;
3286ed61fc10SJeff Cody     Error *local_err = NULL;
3287ed61fc10SJeff Cody     /* This will be part of the QMP command, if/when the
3288ed61fc10SJeff Cody      * BlockdevOnError change for blkmirror makes it in
3289ed61fc10SJeff Cody      */
329092aa5c6dSPaolo Bonzini     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
32915360782dSJohn Snow     int job_flags = JOB_DEFAULT;
3292ed61fc10SJeff Cody 
329354504663SMax Reitz     if (!has_speed) {
329454504663SMax Reitz         speed = 0;
329554504663SMax Reitz     }
32960db832f4SKevin Wolf     if (!has_filter_node_name) {
32970db832f4SKevin Wolf         filter_node_name = NULL;
32980db832f4SKevin Wolf     }
329996fbf534SJohn Snow     if (has_auto_finalize && !auto_finalize) {
330096fbf534SJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
330196fbf534SJohn Snow     }
330296fbf534SJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
330396fbf534SJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
330496fbf534SJohn Snow     }
330554504663SMax Reitz 
33067676e2c5SJeff Cody     /* Important Note:
33077676e2c5SJeff Cody      *  libvirt relies on the DeviceNotFound error class in order to probe for
33087676e2c5SJeff Cody      *  live commit feature versions; for this to work, we must make sure to
33097676e2c5SJeff Cody      *  perform the device lookup before any generic errors that may occur in a
33107676e2c5SJeff Cody      *  scenario in which all optional arguments are omitted. */
33111d13b167SKevin Wolf     bs = qmp_get_root_bs(device, &local_err);
33121d13b167SKevin Wolf     if (!bs) {
33131d13b167SKevin Wolf         bs = bdrv_lookup_bs(device, device, NULL);
33141d13b167SKevin Wolf         if (!bs) {
33151d13b167SKevin Wolf             error_free(local_err);
331675158ebbSMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
331775158ebbSMarkus Armbruster                       "Device '%s' not found", device);
33181d13b167SKevin Wolf         } else {
33191d13b167SKevin Wolf             error_propagate(errp, local_err);
33201d13b167SKevin Wolf         }
3321ed61fc10SJeff Cody         return;
3322ed61fc10SJeff Cody     }
3323ed61fc10SJeff Cody 
33241d13b167SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
33259e85cd5cSStefan Hajnoczi     aio_context_acquire(aio_context);
33269e85cd5cSStefan Hajnoczi 
3327bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
33289e85cd5cSStefan Hajnoczi         goto out;
3329628ff683SFam Zheng     }
3330628ff683SFam Zheng 
3331ed61fc10SJeff Cody     /* default top_bs is the active layer */
3332ed61fc10SJeff Cody     top_bs = bs;
3333ed61fc10SJeff Cody 
33343c605f40SKevin Wolf     if (has_top_node && has_top) {
33353c605f40SKevin Wolf         error_setg(errp, "'top-node' and 'top' are mutually exclusive");
33363c605f40SKevin Wolf         goto out;
33373c605f40SKevin Wolf     } else if (has_top_node) {
33383c605f40SKevin Wolf         top_bs = bdrv_lookup_bs(NULL, top_node, errp);
33393c605f40SKevin Wolf         if (top_bs == NULL) {
33403c605f40SKevin Wolf             goto out;
33413c605f40SKevin Wolf         }
33423c605f40SKevin Wolf         if (!bdrv_chain_contains(bs, top_bs)) {
33433c605f40SKevin Wolf             error_setg(errp, "'%s' is not in this backing file chain",
33443c605f40SKevin Wolf                        top_node);
33453c605f40SKevin Wolf             goto out;
33463c605f40SKevin Wolf         }
33473c605f40SKevin Wolf     } else if (has_top && top) {
3348f30c66baSMax Reitz         /* This strcmp() is just a shortcut, there is no need to
3349f30c66baSMax Reitz          * refresh @bs's filename.  If it mismatches,
3350f30c66baSMax Reitz          * bdrv_find_backing_image() will do the refresh and may still
3351f30c66baSMax Reitz          * return @bs. */
3352ed61fc10SJeff Cody         if (strcmp(bs->filename, top) != 0) {
3353ed61fc10SJeff Cody             top_bs = bdrv_find_backing_image(bs, top);
3354ed61fc10SJeff Cody         }
3355ed61fc10SJeff Cody     }
3356ed61fc10SJeff Cody 
3357ed61fc10SJeff Cody     if (top_bs == NULL) {
3358ed61fc10SJeff Cody         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
33599e85cd5cSStefan Hajnoczi         goto out;
3360ed61fc10SJeff Cody     }
3361ed61fc10SJeff Cody 
33629e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(top_bs) == aio_context);
33639e85cd5cSStefan Hajnoczi 
33643c605f40SKevin Wolf     if (has_base_node && has_base) {
33653c605f40SKevin Wolf         error_setg(errp, "'base-node' and 'base' are mutually exclusive");
33663c605f40SKevin Wolf         goto out;
33673c605f40SKevin Wolf     } else if (has_base_node) {
33683c605f40SKevin Wolf         base_bs = bdrv_lookup_bs(NULL, base_node, errp);
33693c605f40SKevin Wolf         if (base_bs == NULL) {
33703c605f40SKevin Wolf             goto out;
33713c605f40SKevin Wolf         }
33723c605f40SKevin Wolf         if (!bdrv_chain_contains(top_bs, base_bs)) {
33733c605f40SKevin Wolf             error_setg(errp, "'%s' is not in this backing file chain",
33743c605f40SKevin Wolf                        base_node);
33753c605f40SKevin Wolf             goto out;
33763c605f40SKevin Wolf         }
33773c605f40SKevin Wolf     } else if (has_base && base) {
3378d5208c45SJeff Cody         base_bs = bdrv_find_backing_image(top_bs, base);
3379d5208c45SJeff Cody     } else {
3380d5208c45SJeff Cody         base_bs = bdrv_find_base(top_bs);
3381d5208c45SJeff Cody     }
3382d5208c45SJeff Cody 
3383d5208c45SJeff Cody     if (base_bs == NULL) {
3384c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
33859e85cd5cSStefan Hajnoczi         goto out;
3386d5208c45SJeff Cody     }
3387d5208c45SJeff Cody 
33889e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(base_bs) == aio_context);
33899e85cd5cSStefan Hajnoczi 
3390058223a6SAlberto Garcia     for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3391058223a6SAlberto Garcia         if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3392bb00021dSFam Zheng             goto out;
3393bb00021dSFam Zheng         }
3394058223a6SAlberto Garcia     }
3395bb00021dSFam Zheng 
33967676e2c5SJeff Cody     /* Do not allow attempts to commit an image into itself */
33977676e2c5SJeff Cody     if (top_bs == base_bs) {
33987676e2c5SJeff Cody         error_setg(errp, "cannot commit an image into itself");
33999e85cd5cSStefan Hajnoczi         goto out;
34007676e2c5SJeff Cody     }
34017676e2c5SJeff Cody 
340220a63d2cSFam Zheng     if (top_bs == bs) {
340354e26900SJeff Cody         if (has_backing_file) {
340454e26900SJeff Cody             error_setg(errp, "'backing-file' specified,"
340554e26900SJeff Cody                              " but 'top' is the active layer");
34069e85cd5cSStefan Hajnoczi             goto out;
340754e26900SJeff Cody         }
340847970dfbSJohn Snow         commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
34095360782dSJohn Snow                             job_flags, speed, on_error,
341078bbd910SFam Zheng                             filter_node_name, NULL, NULL, false, &local_err);
341120a63d2cSFam Zheng     } else {
3412058223a6SAlberto Garcia         BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3413058223a6SAlberto Garcia         if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3414058223a6SAlberto Garcia             goto out;
3415058223a6SAlberto Garcia         }
34165360782dSJohn Snow         commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, job_flags,
34175360782dSJohn Snow                      speed, on_error, has_backing_file ? backing_file : NULL,
34180db832f4SKevin Wolf                      filter_node_name, &local_err);
341920a63d2cSFam Zheng     }
3420ed61fc10SJeff Cody     if (local_err != NULL) {
3421ed61fc10SJeff Cody         error_propagate(errp, local_err);
34229e85cd5cSStefan Hajnoczi         goto out;
3423ed61fc10SJeff Cody     }
34249e85cd5cSStefan Hajnoczi 
34259e85cd5cSStefan Hajnoczi out:
34269e85cd5cSStefan Hajnoczi     aio_context_release(aio_context);
3427ed61fc10SJeff Cody }
3428ed61fc10SJeff Cody 
342962c9e416SKevin Wolf static BlockJob *do_drive_backup(DriveBackup *backup, JobTxn *txn,
3430111049a4SJohn Snow                                  Error **errp)
343199a9addfSStefan Hajnoczi {
343299a9addfSStefan Hajnoczi     BlockDriverState *bs;
343399a9addfSStefan Hajnoczi     BlockDriverState *target_bs;
3434fc5d3f84SIan Main     BlockDriverState *source = NULL;
3435111049a4SJohn Snow     BlockJob *job = NULL;
3436d58d8453SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
3437761731b1SStefan Hajnoczi     AioContext *aio_context;
3438e6641719SMax Reitz     QDict *options = NULL;
343999a9addfSStefan Hajnoczi     Error *local_err = NULL;
3440bb02b65cSKevin Wolf     int flags, job_flags = JOB_DEFAULT;
344199a9addfSStefan Hajnoczi     int64_t size;
3442fc0932fdSFam Zheng     bool set_backing_hd = false;
344399a9addfSStefan Hajnoczi 
344481206a89SPavel Butsykin     if (!backup->has_speed) {
344581206a89SPavel Butsykin         backup->speed = 0;
344699a9addfSStefan Hajnoczi     }
344781206a89SPavel Butsykin     if (!backup->has_on_source_error) {
344881206a89SPavel Butsykin         backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
344999a9addfSStefan Hajnoczi     }
345081206a89SPavel Butsykin     if (!backup->has_on_target_error) {
345181206a89SPavel Butsykin         backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
345299a9addfSStefan Hajnoczi     }
345381206a89SPavel Butsykin     if (!backup->has_mode) {
345481206a89SPavel Butsykin         backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
345581206a89SPavel Butsykin     }
345681206a89SPavel Butsykin     if (!backup->has_job_id) {
345781206a89SPavel Butsykin         backup->job_id = NULL;
345899a9addfSStefan Hajnoczi     }
3459b40dacdcSJohn Snow     if (!backup->has_auto_finalize) {
3460b40dacdcSJohn Snow         backup->auto_finalize = true;
3461b40dacdcSJohn Snow     }
3462b40dacdcSJohn Snow     if (!backup->has_auto_dismiss) {
3463b40dacdcSJohn Snow         backup->auto_dismiss = true;
3464b40dacdcSJohn Snow     }
346513b9414bSPavel Butsykin     if (!backup->has_compress) {
346613b9414bSPavel Butsykin         backup->compress = false;
346713b9414bSPavel Butsykin     }
346899a9addfSStefan Hajnoczi 
346981206a89SPavel Butsykin     bs = qmp_get_root_bs(backup->device, errp);
3470b7e4fa22SKevin Wolf     if (!bs) {
3471111049a4SJohn Snow         return NULL;
347299a9addfSStefan Hajnoczi     }
347399a9addfSStefan Hajnoczi 
3474b7e4fa22SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3475761731b1SStefan Hajnoczi     aio_context_acquire(aio_context);
3476761731b1SStefan Hajnoczi 
347781206a89SPavel Butsykin     if (!backup->has_format) {
347881206a89SPavel Butsykin         backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
347981206a89SPavel Butsykin                          NULL : (char*) bs->drv->format_name;
348099a9addfSStefan Hajnoczi     }
348199a9addfSStefan Hajnoczi 
3482c29c1dd3SFam Zheng     /* Early check to avoid creating target */
34833718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3484761731b1SStefan Hajnoczi         goto out;
348599a9addfSStefan Hajnoczi     }
348699a9addfSStefan Hajnoczi 
348761de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
348899a9addfSStefan Hajnoczi 
3489fc5d3f84SIan Main     /* See if we have a backing HD we can use to create our new image
3490fc5d3f84SIan Main      * on top of. */
349181206a89SPavel Butsykin     if (backup->sync == MIRROR_SYNC_MODE_TOP) {
3492760e0063SKevin Wolf         source = backing_bs(bs);
3493fc5d3f84SIan Main         if (!source) {
349481206a89SPavel Butsykin             backup->sync = MIRROR_SYNC_MODE_FULL;
3495fc5d3f84SIan Main         }
3496fc5d3f84SIan Main     }
349781206a89SPavel Butsykin     if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3498fc5d3f84SIan Main         source = bs;
3499fc0932fdSFam Zheng         flags |= BDRV_O_NO_BACKING;
3500fc0932fdSFam Zheng         set_backing_hd = true;
3501fc5d3f84SIan Main     }
3502fc5d3f84SIan Main 
350399a9addfSStefan Hajnoczi     size = bdrv_getlength(bs);
350499a9addfSStefan Hajnoczi     if (size < 0) {
350599a9addfSStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
3506761731b1SStefan Hajnoczi         goto out;
350799a9addfSStefan Hajnoczi     }
350899a9addfSStefan Hajnoczi 
350981206a89SPavel Butsykin     if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
351081206a89SPavel Butsykin         assert(backup->format);
3511fc5d3f84SIan Main         if (source) {
3512f30c66baSMax Reitz             bdrv_refresh_filename(source);
351381206a89SPavel Butsykin             bdrv_img_create(backup->target, backup->format, source->filename,
3514fc5d3f84SIan Main                             source->drv->format_name, NULL,
35159217283dSFam Zheng                             size, flags, false, &local_err);
3516fc5d3f84SIan Main         } else {
351781206a89SPavel Butsykin             bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
35189217283dSFam Zheng                             size, flags, false, &local_err);
3519fc5d3f84SIan Main         }
352099a9addfSStefan Hajnoczi     }
352199a9addfSStefan Hajnoczi 
352284d18f06SMarkus Armbruster     if (local_err) {
352399a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3524761731b1SStefan Hajnoczi         goto out;
352599a9addfSStefan Hajnoczi     }
352699a9addfSStefan Hajnoczi 
352781206a89SPavel Butsykin     if (backup->format) {
3528fc0932fdSFam Zheng         if (!options) {
3529e6641719SMax Reitz             options = qdict_new();
3530fc0932fdSFam Zheng         }
353146f5ac20SEric Blake         qdict_put_str(options, "driver", backup->format);
3532e6641719SMax Reitz     }
3533e6641719SMax Reitz 
353481206a89SPavel Butsykin     target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
35355b363937SMax Reitz     if (!target_bs) {
3536761731b1SStefan Hajnoczi         goto out;
353799a9addfSStefan Hajnoczi     }
353899a9addfSStefan Hajnoczi 
3539761731b1SStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
3540761731b1SStefan Hajnoczi 
3541fc0932fdSFam Zheng     if (set_backing_hd) {
3542fc0932fdSFam Zheng         bdrv_set_backing_hd(target_bs, source, &local_err);
3543fc0932fdSFam Zheng         if (local_err) {
3544fc0932fdSFam Zheng             bdrv_unref(target_bs);
3545fc0932fdSFam Zheng             goto out;
3546fc0932fdSFam Zheng         }
3547fc0932fdSFam Zheng     }
3548fc0932fdSFam Zheng 
354981206a89SPavel Butsykin     if (backup->has_bitmap) {
355081206a89SPavel Butsykin         bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3551d58d8453SJohn Snow         if (!bmap) {
355281206a89SPavel Butsykin             error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
35530702d3d8SMax Reitz             bdrv_unref(target_bs);
3554d58d8453SJohn Snow             goto out;
3555d58d8453SJohn Snow         }
3556a54a0c11SJohn Snow         if (bdrv_dirty_bitmap_check(bmap, BDRV_BITMAP_DEFAULT, errp)) {
35574f43e953SVladimir Sementsov-Ogievskiy             goto out;
35584f43e953SVladimir Sementsov-Ogievskiy         }
3559d58d8453SJohn Snow     }
3560b40dacdcSJohn Snow     if (!backup->auto_finalize) {
3561bb02b65cSKevin Wolf         job_flags |= JOB_MANUAL_FINALIZE;
3562b40dacdcSJohn Snow     }
3563b40dacdcSJohn Snow     if (!backup->auto_dismiss) {
3564bb02b65cSKevin Wolf         job_flags |= JOB_MANUAL_DISMISS;
3565b40dacdcSJohn Snow     }
3566d58d8453SJohn Snow 
3567111049a4SJohn Snow     job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3568111049a4SJohn Snow                             backup->sync, bmap, backup->compress,
3569111049a4SJohn Snow                             backup->on_source_error, backup->on_target_error,
3570b40dacdcSJohn Snow                             job_flags, NULL, NULL, txn, &local_err);
35714f6fd349SFam Zheng     bdrv_unref(target_bs);
35725c438bc6SKevin Wolf     if (local_err != NULL) {
357399a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3574761731b1SStefan Hajnoczi         goto out;
357599a9addfSStefan Hajnoczi     }
3576761731b1SStefan Hajnoczi 
3577761731b1SStefan Hajnoczi out:
3578761731b1SStefan Hajnoczi     aio_context_release(aio_context);
3579111049a4SJohn Snow     return job;
358099a9addfSStefan Hajnoczi }
358199a9addfSStefan Hajnoczi 
358281206a89SPavel Butsykin void qmp_drive_backup(DriveBackup *arg, Error **errp)
358378f51fdeSJohn Snow {
3584111049a4SJohn Snow 
3585111049a4SJohn Snow     BlockJob *job;
3586111049a4SJohn Snow     job = do_drive_backup(arg, NULL, errp);
3587111049a4SJohn Snow     if (job) {
3588da01ff7fSKevin Wolf         job_start(&job->job);
3589111049a4SJohn Snow     }
359078f51fdeSJohn Snow }
359178f51fdeSJohn Snow 
3592c13163fbSBenoît Canet BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3593c13163fbSBenoît Canet {
3594d5a8ee60SAlberto Garcia     return bdrv_named_nodes_list(errp);
3595c13163fbSBenoît Canet }
3596c13163fbSBenoît Canet 
35975d3b4e99SVladimir Sementsov-Ogievskiy XDbgBlockGraph *qmp_x_debug_query_block_graph(Error **errp)
35985d3b4e99SVladimir Sementsov-Ogievskiy {
35995d3b4e99SVladimir Sementsov-Ogievskiy     return bdrv_get_xdbg_block_graph(errp);
36005d3b4e99SVladimir Sementsov-Ogievskiy }
36015d3b4e99SVladimir Sementsov-Ogievskiy 
360262c9e416SKevin Wolf BlockJob *do_blockdev_backup(BlockdevBackup *backup, JobTxn *txn,
3603111049a4SJohn Snow                              Error **errp)
3604c29c1dd3SFam Zheng {
3605c29c1dd3SFam Zheng     BlockDriverState *bs;
3606c29c1dd3SFam Zheng     BlockDriverState *target_bs;
3607c29c1dd3SFam Zheng     Error *local_err = NULL;
3608945c1ee0SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
3609c29c1dd3SFam Zheng     AioContext *aio_context;
3610111049a4SJohn Snow     BlockJob *job = NULL;
3611bb02b65cSKevin Wolf     int job_flags = JOB_DEFAULT;
3612c29c1dd3SFam Zheng 
3613dc7a4a9eSPavel Butsykin     if (!backup->has_speed) {
3614dc7a4a9eSPavel Butsykin         backup->speed = 0;
3615c29c1dd3SFam Zheng     }
3616dc7a4a9eSPavel Butsykin     if (!backup->has_on_source_error) {
3617dc7a4a9eSPavel Butsykin         backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3618c29c1dd3SFam Zheng     }
3619dc7a4a9eSPavel Butsykin     if (!backup->has_on_target_error) {
3620dc7a4a9eSPavel Butsykin         backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3621dc7a4a9eSPavel Butsykin     }
3622dc7a4a9eSPavel Butsykin     if (!backup->has_job_id) {
3623dc7a4a9eSPavel Butsykin         backup->job_id = NULL;
3624c29c1dd3SFam Zheng     }
3625b40dacdcSJohn Snow     if (!backup->has_auto_finalize) {
3626b40dacdcSJohn Snow         backup->auto_finalize = true;
3627b40dacdcSJohn Snow     }
3628b40dacdcSJohn Snow     if (!backup->has_auto_dismiss) {
3629b40dacdcSJohn Snow         backup->auto_dismiss = true;
3630b40dacdcSJohn Snow     }
36313b7b1236SPavel Butsykin     if (!backup->has_compress) {
36323b7b1236SPavel Butsykin         backup->compress = false;
36333b7b1236SPavel Butsykin     }
3634c29c1dd3SFam Zheng 
3635930fe17fSVladimir Sementsov-Ogievskiy     bs = bdrv_lookup_bs(backup->device, backup->device, errp);
3636cef34eebSKevin Wolf     if (!bs) {
3637111049a4SJohn Snow         return NULL;
3638c29c1dd3SFam Zheng     }
3639c29c1dd3SFam Zheng 
3640cef34eebSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3641c29c1dd3SFam Zheng     aio_context_acquire(aio_context);
3642c29c1dd3SFam Zheng 
3643dc7a4a9eSPavel Butsykin     target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
36440d978913SFam Zheng     if (!target_bs) {
3645c29c1dd3SFam Zheng         goto out;
3646c29c1dd3SFam Zheng     }
36475433c24fSMax Reitz 
3648efd75567SFam Zheng     if (bdrv_get_aio_context(target_bs) != aio_context) {
3649efd75567SFam Zheng         if (!bdrv_has_blk(target_bs)) {
3650efd75567SFam Zheng             /* The target BDS is not attached, we can safely move it to another
3651efd75567SFam Zheng              * AioContext. */
3652c29c1dd3SFam Zheng             bdrv_set_aio_context(target_bs, aio_context);
3653efd75567SFam Zheng         } else {
3654efd75567SFam Zheng             error_setg(errp, "Target is attached to a different thread from "
3655efd75567SFam Zheng                              "source.");
3656efd75567SFam Zheng             goto out;
3657efd75567SFam Zheng         }
3658efd75567SFam Zheng     }
3659945c1ee0SJohn Snow 
3660945c1ee0SJohn Snow     if (backup->has_bitmap) {
3661945c1ee0SJohn Snow         bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3662945c1ee0SJohn Snow         if (!bmap) {
3663945c1ee0SJohn Snow             error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3664945c1ee0SJohn Snow             goto out;
3665945c1ee0SJohn Snow         }
3666a54a0c11SJohn Snow         if (bdrv_dirty_bitmap_check(bmap, BDRV_BITMAP_DEFAULT, errp)) {
3667945c1ee0SJohn Snow             goto out;
3668945c1ee0SJohn Snow         }
3669945c1ee0SJohn Snow     }
3670945c1ee0SJohn Snow 
3671b40dacdcSJohn Snow     if (!backup->auto_finalize) {
3672bb02b65cSKevin Wolf         job_flags |= JOB_MANUAL_FINALIZE;
3673b40dacdcSJohn Snow     }
3674b40dacdcSJohn Snow     if (!backup->auto_dismiss) {
3675bb02b65cSKevin Wolf         job_flags |= JOB_MANUAL_DISMISS;
3676b40dacdcSJohn Snow     }
3677111049a4SJohn Snow     job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3678945c1ee0SJohn Snow                             backup->sync, bmap, backup->compress,
3679111049a4SJohn Snow                             backup->on_source_error, backup->on_target_error,
3680b40dacdcSJohn Snow                             job_flags, NULL, NULL, txn, &local_err);
3681c29c1dd3SFam Zheng     if (local_err != NULL) {
3682c29c1dd3SFam Zheng         error_propagate(errp, local_err);
3683c29c1dd3SFam Zheng     }
3684c29c1dd3SFam Zheng out:
3685c29c1dd3SFam Zheng     aio_context_release(aio_context);
3686111049a4SJohn Snow     return job;
3687c29c1dd3SFam Zheng }
3688c29c1dd3SFam Zheng 
3689dc7a4a9eSPavel Butsykin void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
369078f51fdeSJohn Snow {
3691111049a4SJohn Snow     BlockJob *job;
3692111049a4SJohn Snow     job = do_blockdev_backup(arg, NULL, errp);
3693111049a4SJohn Snow     if (job) {
3694da01ff7fSKevin Wolf         job_start(&job->job);
3695111049a4SJohn Snow     }
369678f51fdeSJohn Snow }
369778f51fdeSJohn Snow 
36984193cdd7SFam Zheng /* Parameter check and block job starting for drive mirroring.
36994193cdd7SFam Zheng  * Caller should hold @device and @target's aio context (must be the same).
37004193cdd7SFam Zheng  **/
370171aa9867SAlberto Garcia static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
37024193cdd7SFam Zheng                                    BlockDriverState *target,
370309158f00SBenoît Canet                                    bool has_replaces, const char *replaces,
3704d9b902dbSPaolo Bonzini                                    enum MirrorSyncMode sync,
3705274fcceeSMax Reitz                                    BlockMirrorBackingMode backing_mode,
3706b952b558SPaolo Bonzini                                    bool has_speed, int64_t speed,
3707eee13dfeSPaolo Bonzini                                    bool has_granularity, uint32_t granularity,
370808e4ed6cSPaolo Bonzini                                    bool has_buf_size, int64_t buf_size,
37094193cdd7SFam Zheng                                    bool has_on_source_error,
37104193cdd7SFam Zheng                                    BlockdevOnError on_source_error,
37114193cdd7SFam Zheng                                    bool has_on_target_error,
37124193cdd7SFam Zheng                                    BlockdevOnError on_target_error,
37130fc9f8eaSFam Zheng                                    bool has_unmap, bool unmap,
37146cdbceb1SKevin Wolf                                    bool has_filter_node_name,
37156cdbceb1SKevin Wolf                                    const char *filter_node_name,
3716481debaaSMax Reitz                                    bool has_copy_mode, MirrorCopyMode copy_mode,
3717a6b58adeSJohn Snow                                    bool has_auto_finalize, bool auto_finalize,
3718a6b58adeSJohn Snow                                    bool has_auto_dismiss, bool auto_dismiss,
3719b952b558SPaolo Bonzini                                    Error **errp)
3720d9b902dbSPaolo Bonzini {
3721a1999b33SJohn Snow     int job_flags = JOB_DEFAULT;
3722d9b902dbSPaolo Bonzini 
3723d9b902dbSPaolo Bonzini     if (!has_speed) {
3724d9b902dbSPaolo Bonzini         speed = 0;
3725d9b902dbSPaolo Bonzini     }
3726b952b558SPaolo Bonzini     if (!has_on_source_error) {
3727b952b558SPaolo Bonzini         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3728b952b558SPaolo Bonzini     }
3729b952b558SPaolo Bonzini     if (!has_on_target_error) {
3730b952b558SPaolo Bonzini         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3731b952b558SPaolo Bonzini     }
3732eee13dfeSPaolo Bonzini     if (!has_granularity) {
3733eee13dfeSPaolo Bonzini         granularity = 0;
3734eee13dfeSPaolo Bonzini     }
373508e4ed6cSPaolo Bonzini     if (!has_buf_size) {
373648ac0a4dSWen Congyang         buf_size = 0;
373708e4ed6cSPaolo Bonzini     }
37380fc9f8eaSFam Zheng     if (!has_unmap) {
37390fc9f8eaSFam Zheng         unmap = true;
37400fc9f8eaSFam Zheng     }
37416cdbceb1SKevin Wolf     if (!has_filter_node_name) {
37426cdbceb1SKevin Wolf         filter_node_name = NULL;
37436cdbceb1SKevin Wolf     }
3744481debaaSMax Reitz     if (!has_copy_mode) {
3745481debaaSMax Reitz         copy_mode = MIRROR_COPY_MODE_BACKGROUND;
3746481debaaSMax Reitz     }
3747a6b58adeSJohn Snow     if (has_auto_finalize && !auto_finalize) {
3748a6b58adeSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
3749a6b58adeSJohn Snow     }
3750a6b58adeSJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
3751a6b58adeSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
3752a6b58adeSJohn Snow     }
375308e4ed6cSPaolo Bonzini 
3754eee13dfeSPaolo Bonzini     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3755c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
37563cbbe9fdSStefan Hajnoczi                    "a value in range [512B, 64MB]");
3757eee13dfeSPaolo Bonzini         return;
3758eee13dfeSPaolo Bonzini     }
3759eee13dfeSPaolo Bonzini     if (granularity & (granularity - 1)) {
3760c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3761c6bd8c70SMarkus Armbruster                    "power of 2");
3762eee13dfeSPaolo Bonzini         return;
3763eee13dfeSPaolo Bonzini     }
3764d9b902dbSPaolo Bonzini 
37654193cdd7SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
37664193cdd7SFam Zheng         return;
37674193cdd7SFam Zheng     }
3768e40e5027SFam Zheng     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3769e40e5027SFam Zheng         return;
3770e40e5027SFam Zheng     }
37714193cdd7SFam Zheng 
37724193cdd7SFam Zheng     if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
37734193cdd7SFam Zheng         sync = MIRROR_SYNC_MODE_FULL;
37744193cdd7SFam Zheng     }
37754193cdd7SFam Zheng 
377674ce9e46SMax Reitz     if (has_replaces) {
377774ce9e46SMax Reitz         BlockDriverState *to_replace_bs;
377874ce9e46SMax Reitz         AioContext *replace_aio_context;
377974ce9e46SMax Reitz         int64_t bs_size, replace_size;
378074ce9e46SMax Reitz 
378174ce9e46SMax Reitz         bs_size = bdrv_getlength(bs);
378274ce9e46SMax Reitz         if (bs_size < 0) {
378374ce9e46SMax Reitz             error_setg_errno(errp, -bs_size, "Failed to query device's size");
378474ce9e46SMax Reitz             return;
378574ce9e46SMax Reitz         }
378674ce9e46SMax Reitz 
378774ce9e46SMax Reitz         to_replace_bs = check_to_replace_node(bs, replaces, errp);
378874ce9e46SMax Reitz         if (!to_replace_bs) {
378974ce9e46SMax Reitz             return;
379074ce9e46SMax Reitz         }
379174ce9e46SMax Reitz 
379274ce9e46SMax Reitz         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
379374ce9e46SMax Reitz         aio_context_acquire(replace_aio_context);
379474ce9e46SMax Reitz         replace_size = bdrv_getlength(to_replace_bs);
379574ce9e46SMax Reitz         aio_context_release(replace_aio_context);
379674ce9e46SMax Reitz 
379774ce9e46SMax Reitz         if (replace_size < 0) {
379874ce9e46SMax Reitz             error_setg_errno(errp, -replace_size,
379974ce9e46SMax Reitz                              "Failed to query the replacement node's size");
380074ce9e46SMax Reitz             return;
380174ce9e46SMax Reitz         }
380274ce9e46SMax Reitz         if (bs_size != replace_size) {
380374ce9e46SMax Reitz             error_setg(errp, "cannot replace image with a mirror image of "
380474ce9e46SMax Reitz                              "different size");
380574ce9e46SMax Reitz             return;
380674ce9e46SMax Reitz         }
380774ce9e46SMax Reitz     }
380874ce9e46SMax Reitz 
38094193cdd7SFam Zheng     /* pass the node name to replace to mirror start since it's loose coupling
38104193cdd7SFam Zheng      * and will allow to check whether the node still exist at mirror completion
38114193cdd7SFam Zheng      */
381271aa9867SAlberto Garcia     mirror_start(job_id, bs, target,
3813a1999b33SJohn Snow                  has_replaces ? replaces : NULL, job_flags,
3814274fcceeSMax Reitz                  speed, granularity, buf_size, sync, backing_mode,
38156cdbceb1SKevin Wolf                  on_source_error, on_target_error, unmap, filter_node_name,
3816481debaaSMax Reitz                  copy_mode, errp);
38174193cdd7SFam Zheng }
38184193cdd7SFam Zheng 
3819faecd40aSEric Blake void qmp_drive_mirror(DriveMirror *arg, Error **errp)
38204193cdd7SFam Zheng {
38214193cdd7SFam Zheng     BlockDriverState *bs;
38224193cdd7SFam Zheng     BlockDriverState *source, *target_bs;
38234193cdd7SFam Zheng     AioContext *aio_context;
3824274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode;
38254193cdd7SFam Zheng     Error *local_err = NULL;
38264193cdd7SFam Zheng     QDict *options = NULL;
38274193cdd7SFam Zheng     int flags;
38284193cdd7SFam Zheng     int64_t size;
3829faecd40aSEric Blake     const char *format = arg->format;
38304193cdd7SFam Zheng 
38310524e93aSKevin Wolf     bs = qmp_get_root_bs(arg->device, errp);
38320524e93aSKevin Wolf     if (!bs) {
3833d9b902dbSPaolo Bonzini         return;
3834d9b902dbSPaolo Bonzini     }
3835d9b902dbSPaolo Bonzini 
3836cb2af917SPaolo Bonzini     /* Early check to avoid creating target */
3837cb2af917SPaolo Bonzini     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3838cb2af917SPaolo Bonzini         return;
3839cb2af917SPaolo Bonzini     }
3840cb2af917SPaolo Bonzini 
38410524e93aSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
38425a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
38435a7e7a0bSStefan Hajnoczi 
3844faecd40aSEric Blake     if (!arg->has_mode) {
3845faecd40aSEric Blake         arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
38464193cdd7SFam Zheng     }
3847d9b902dbSPaolo Bonzini 
3848faecd40aSEric Blake     if (!arg->has_format) {
3849faecd40aSEric Blake         format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3850faecd40aSEric Blake                   ? NULL : bs->drv->format_name);
3851d9b902dbSPaolo Bonzini     }
3852d9b902dbSPaolo Bonzini 
385361de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
3854760e0063SKevin Wolf     source = backing_bs(bs);
3855faecd40aSEric Blake     if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3856faecd40aSEric Blake         arg->sync = MIRROR_SYNC_MODE_FULL;
3857d9b902dbSPaolo Bonzini     }
3858faecd40aSEric Blake     if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3859117e0c82SMax Reitz         source = bs;
3860117e0c82SMax Reitz     }
3861d9b902dbSPaolo Bonzini 
3862ac3c5d83SStefan Hajnoczi     size = bdrv_getlength(bs);
3863ac3c5d83SStefan Hajnoczi     if (size < 0) {
3864ac3c5d83SStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
38655a7e7a0bSStefan Hajnoczi         goto out;
3866ac3c5d83SStefan Hajnoczi     }
3867ac3c5d83SStefan Hajnoczi 
3868faecd40aSEric Blake     if (arg->has_replaces) {
3869faecd40aSEric Blake         if (!arg->has_node_name) {
387009158f00SBenoît Canet             error_setg(errp, "a node-name must be provided when replacing a"
387109158f00SBenoît Canet                              " named node of the graph");
38725a7e7a0bSStefan Hajnoczi             goto out;
387309158f00SBenoît Canet         }
387409158f00SBenoît Canet     }
387509158f00SBenoît Canet 
3876faecd40aSEric Blake     if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3877274fcceeSMax Reitz         backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3878274fcceeSMax Reitz     } else {
3879274fcceeSMax Reitz         backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3880274fcceeSMax Reitz     }
3881274fcceeSMax Reitz 
38822a32c6e8SJohn Snow     /* Don't open backing image in create() */
38832a32c6e8SJohn Snow     flags |= BDRV_O_NO_BACKING;
38842a32c6e8SJohn Snow 
3885faecd40aSEric Blake     if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3886faecd40aSEric Blake         && arg->mode != NEW_IMAGE_MODE_EXISTING)
388714526864SMax Reitz     {
3888d9b902dbSPaolo Bonzini         /* create new image w/o backing file */
3889e6641719SMax Reitz         assert(format);
3890faecd40aSEric Blake         bdrv_img_create(arg->target, format,
38919217283dSFam Zheng                         NULL, NULL, NULL, size, flags, false, &local_err);
3892d9b902dbSPaolo Bonzini     } else {
3893faecd40aSEric Blake         switch (arg->mode) {
3894d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_EXISTING:
3895d9b902dbSPaolo Bonzini             break;
3896d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3897d9b902dbSPaolo Bonzini             /* create new image with backing file */
3898f30c66baSMax Reitz             bdrv_refresh_filename(source);
3899faecd40aSEric Blake             bdrv_img_create(arg->target, format,
3900d9b902dbSPaolo Bonzini                             source->filename,
3901d9b902dbSPaolo Bonzini                             source->drv->format_name,
39029217283dSFam Zheng                             NULL, size, flags, false, &local_err);
3903d9b902dbSPaolo Bonzini             break;
3904d9b902dbSPaolo Bonzini         default:
3905d9b902dbSPaolo Bonzini             abort();
3906d9b902dbSPaolo Bonzini         }
3907d9b902dbSPaolo Bonzini     }
3908d9b902dbSPaolo Bonzini 
390984d18f06SMarkus Armbruster     if (local_err) {
3910cf8f2426SLuiz Capitulino         error_propagate(errp, local_err);
39115a7e7a0bSStefan Hajnoczi         goto out;
3912d9b902dbSPaolo Bonzini     }
3913d9b902dbSPaolo Bonzini 
39144c828dc6SBenoît Canet     options = qdict_new();
3915faecd40aSEric Blake     if (arg->has_node_name) {
391646f5ac20SEric Blake         qdict_put_str(options, "node-name", arg->node_name);
39174c828dc6SBenoît Canet     }
3918e6641719SMax Reitz     if (format) {
391946f5ac20SEric Blake         qdict_put_str(options, "driver", format);
3920e6641719SMax Reitz     }
39214c828dc6SBenoît Canet 
3922b812f671SPaolo Bonzini     /* Mirroring takes care of copy-on-write using the source's backing
3923b812f671SPaolo Bonzini      * file.
3924b812f671SPaolo Bonzini      */
39252a32c6e8SJohn Snow     target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
39265b363937SMax Reitz     if (!target_bs) {
39275a7e7a0bSStefan Hajnoczi         goto out;
3928d9b902dbSPaolo Bonzini     }
3929d9b902dbSPaolo Bonzini 
39305a7e7a0bSStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
39315a7e7a0bSStefan Hajnoczi 
3932faecd40aSEric Blake     blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3933faecd40aSEric Blake                            arg->has_replaces, arg->replaces, arg->sync,
3934faecd40aSEric Blake                            backing_mode, arg->has_speed, arg->speed,
3935faecd40aSEric Blake                            arg->has_granularity, arg->granularity,
3936faecd40aSEric Blake                            arg->has_buf_size, arg->buf_size,
3937faecd40aSEric Blake                            arg->has_on_source_error, arg->on_source_error,
3938faecd40aSEric Blake                            arg->has_on_target_error, arg->on_target_error,
3939faecd40aSEric Blake                            arg->has_unmap, arg->unmap,
39406cdbceb1SKevin Wolf                            false, NULL,
3941481debaaSMax Reitz                            arg->has_copy_mode, arg->copy_mode,
3942a6b58adeSJohn Snow                            arg->has_auto_finalize, arg->auto_finalize,
3943a6b58adeSJohn Snow                            arg->has_auto_dismiss, arg->auto_dismiss,
39444193cdd7SFam Zheng                            &local_err);
3945e253f4b8SKevin Wolf     bdrv_unref(target_bs);
3946d9b902dbSPaolo Bonzini     error_propagate(errp, local_err);
39475a7e7a0bSStefan Hajnoczi out:
39485a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
3949d9b902dbSPaolo Bonzini }
3950d9b902dbSPaolo Bonzini 
395171aa9867SAlberto Garcia void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
395271aa9867SAlberto Garcia                          const char *device, const char *target,
3953df92562eSFam Zheng                          bool has_replaces, const char *replaces,
3954df92562eSFam Zheng                          MirrorSyncMode sync,
3955df92562eSFam Zheng                          bool has_speed, int64_t speed,
3956df92562eSFam Zheng                          bool has_granularity, uint32_t granularity,
3957df92562eSFam Zheng                          bool has_buf_size, int64_t buf_size,
3958df92562eSFam Zheng                          bool has_on_source_error,
3959df92562eSFam Zheng                          BlockdevOnError on_source_error,
3960df92562eSFam Zheng                          bool has_on_target_error,
3961df92562eSFam Zheng                          BlockdevOnError on_target_error,
39626cdbceb1SKevin Wolf                          bool has_filter_node_name,
39636cdbceb1SKevin Wolf                          const char *filter_node_name,
3964481debaaSMax Reitz                          bool has_copy_mode, MirrorCopyMode copy_mode,
3965a6b58adeSJohn Snow                          bool has_auto_finalize, bool auto_finalize,
3966a6b58adeSJohn Snow                          bool has_auto_dismiss, bool auto_dismiss,
3967df92562eSFam Zheng                          Error **errp)
3968df92562eSFam Zheng {
3969df92562eSFam Zheng     BlockDriverState *bs;
3970df92562eSFam Zheng     BlockDriverState *target_bs;
3971df92562eSFam Zheng     AioContext *aio_context;
3972274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3973df92562eSFam Zheng     Error *local_err = NULL;
3974df92562eSFam Zheng 
397507eec652SKevin Wolf     bs = qmp_get_root_bs(device, errp);
3976df92562eSFam Zheng     if (!bs) {
3977df92562eSFam Zheng         return;
3978df92562eSFam Zheng     }
3979df92562eSFam Zheng 
3980df92562eSFam Zheng     target_bs = bdrv_lookup_bs(target, target, errp);
3981df92562eSFam Zheng     if (!target_bs) {
3982df92562eSFam Zheng         return;
3983df92562eSFam Zheng     }
3984df92562eSFam Zheng 
3985df92562eSFam Zheng     aio_context = bdrv_get_aio_context(bs);
3986df92562eSFam Zheng     aio_context_acquire(aio_context);
3987df92562eSFam Zheng 
3988df92562eSFam Zheng     bdrv_set_aio_context(target_bs, aio_context);
3989df92562eSFam Zheng 
399071aa9867SAlberto Garcia     blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3991274fcceeSMax Reitz                            has_replaces, replaces, sync, backing_mode,
3992df92562eSFam Zheng                            has_speed, speed,
3993df92562eSFam Zheng                            has_granularity, granularity,
3994df92562eSFam Zheng                            has_buf_size, buf_size,
3995df92562eSFam Zheng                            has_on_source_error, on_source_error,
3996df92562eSFam Zheng                            has_on_target_error, on_target_error,
3997df92562eSFam Zheng                            true, true,
39986cdbceb1SKevin Wolf                            has_filter_node_name, filter_node_name,
3999481debaaSMax Reitz                            has_copy_mode, copy_mode,
4000a6b58adeSJohn Snow                            has_auto_finalize, auto_finalize,
4001a6b58adeSJohn Snow                            has_auto_dismiss, auto_dismiss,
4002df92562eSFam Zheng                            &local_err);
4003df92562eSFam Zheng     error_propagate(errp, local_err);
4004df92562eSFam Zheng 
4005df92562eSFam Zheng     aio_context_release(aio_context);
4006df92562eSFam Zheng }
4007df92562eSFam Zheng 
40083ddf3efeSAlberto Garcia /* Get a block job using its ID and acquire its AioContext */
40093ddf3efeSAlberto Garcia static BlockJob *find_block_job(const char *id, AioContext **aio_context,
401024d6bffeSMarkus Armbruster                                 Error **errp)
40112d47c6e9SStefan Hajnoczi {
40123ddf3efeSAlberto Garcia     BlockJob *job;
40133ddf3efeSAlberto Garcia 
40143ddf3efeSAlberto Garcia     assert(id != NULL);
40152d47c6e9SStefan Hajnoczi 
40165433c24fSMax Reitz     *aio_context = NULL;
40175433c24fSMax Reitz 
40183ddf3efeSAlberto Garcia     job = block_job_get(id);
40193ddf3efeSAlberto Garcia 
40203ddf3efeSAlberto Garcia     if (!job) {
40213ddf3efeSAlberto Garcia         error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
40223ddf3efeSAlberto Garcia                   "Block job '%s' not found", id);
40233ddf3efeSAlberto Garcia         return NULL;
40242d47c6e9SStefan Hajnoczi     }
40253d948cdfSStefan Hajnoczi 
40263ddf3efeSAlberto Garcia     *aio_context = blk_get_aio_context(job->blk);
40273d948cdfSStefan Hajnoczi     aio_context_acquire(*aio_context);
40283d948cdfSStefan Hajnoczi 
40293ddf3efeSAlberto Garcia     return job;
40302d47c6e9SStefan Hajnoczi }
40312d47c6e9SStefan Hajnoczi 
4032882ec7ceSStefan Hajnoczi void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
40332d47c6e9SStefan Hajnoczi {
40343d948cdfSStefan Hajnoczi     AioContext *aio_context;
403524d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
40362d47c6e9SStefan Hajnoczi 
40372d47c6e9SStefan Hajnoczi     if (!job) {
40382d47c6e9SStefan Hajnoczi         return;
40392d47c6e9SStefan Hajnoczi     }
40402d47c6e9SStefan Hajnoczi 
4041882ec7ceSStefan Hajnoczi     block_job_set_speed(job, speed, errp);
40423d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
40432d47c6e9SStefan Hajnoczi }
4044370521a1SStefan Hajnoczi 
40456e37fb81SPaolo Bonzini void qmp_block_job_cancel(const char *device,
40466e37fb81SPaolo Bonzini                           bool has_force, bool force, Error **errp)
40476e37fb81SPaolo Bonzini {
40483d948cdfSStefan Hajnoczi     AioContext *aio_context;
404924d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
40506e37fb81SPaolo Bonzini 
40516e37fb81SPaolo Bonzini     if (!job) {
40526e37fb81SPaolo Bonzini         return;
40536e37fb81SPaolo Bonzini     }
40543d948cdfSStefan Hajnoczi 
40553d948cdfSStefan Hajnoczi     if (!has_force) {
40563d948cdfSStefan Hajnoczi         force = false;
40573d948cdfSStefan Hajnoczi     }
40583d948cdfSStefan Hajnoczi 
4059b15de828SKevin Wolf     if (job_user_paused(&job->job) && !force) {
4060f231b88dSCole Robinson         error_setg(errp, "The block job for device '%s' is currently paused",
4061f231b88dSCole Robinson                    device);
40623d948cdfSStefan Hajnoczi         goto out;
40636e37fb81SPaolo Bonzini     }
40646e37fb81SPaolo Bonzini 
40656e37fb81SPaolo Bonzini     trace_qmp_block_job_cancel(job);
40663d70ff53SKevin Wolf     job_user_cancel(&job->job, force, errp);
40673d948cdfSStefan Hajnoczi out:
40683d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
40696e37fb81SPaolo Bonzini }
40706e37fb81SPaolo Bonzini 
40716e37fb81SPaolo Bonzini void qmp_block_job_pause(const char *device, Error **errp)
4072370521a1SStefan Hajnoczi {
40733d948cdfSStefan Hajnoczi     AioContext *aio_context;
407424d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
4075370521a1SStefan Hajnoczi 
40760ec4dfb8SJohn Snow     if (!job) {
4077370521a1SStefan Hajnoczi         return;
4078370521a1SStefan Hajnoczi     }
40796e37fb81SPaolo Bonzini 
40806e37fb81SPaolo Bonzini     trace_qmp_block_job_pause(job);
4081b15de828SKevin Wolf     job_user_pause(&job->job, errp);
40823d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
40836e37fb81SPaolo Bonzini }
40846e37fb81SPaolo Bonzini 
40856e37fb81SPaolo Bonzini void qmp_block_job_resume(const char *device, Error **errp)
40866e37fb81SPaolo Bonzini {
40873d948cdfSStefan Hajnoczi     AioContext *aio_context;
408824d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
40896e37fb81SPaolo Bonzini 
40900ec4dfb8SJohn Snow     if (!job) {
40918acc72a4SPaolo Bonzini         return;
40928acc72a4SPaolo Bonzini     }
4093370521a1SStefan Hajnoczi 
40946e37fb81SPaolo Bonzini     trace_qmp_block_job_resume(job);
4095b15de828SKevin Wolf     job_user_resume(&job->job, errp);
40963d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
4097370521a1SStefan Hajnoczi }
4098fb5458cdSStefan Hajnoczi 
4099aeae883bSPaolo Bonzini void qmp_block_job_complete(const char *device, Error **errp)
4100aeae883bSPaolo Bonzini {
41013d948cdfSStefan Hajnoczi     AioContext *aio_context;
410224d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
4103aeae883bSPaolo Bonzini 
4104aeae883bSPaolo Bonzini     if (!job) {
4105aeae883bSPaolo Bonzini         return;
4106aeae883bSPaolo Bonzini     }
4107aeae883bSPaolo Bonzini 
4108aeae883bSPaolo Bonzini     trace_qmp_block_job_complete(job);
41093453d972SKevin Wolf     job_complete(&job->job, errp);
41103d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
4111aeae883bSPaolo Bonzini }
4112aeae883bSPaolo Bonzini 
411311b61fbcSJohn Snow void qmp_block_job_finalize(const char *id, Error **errp)
411411b61fbcSJohn Snow {
411511b61fbcSJohn Snow     AioContext *aio_context;
411611b61fbcSJohn Snow     BlockJob *job = find_block_job(id, &aio_context, errp);
411711b61fbcSJohn Snow 
411811b61fbcSJohn Snow     if (!job) {
411911b61fbcSJohn Snow         return;
412011b61fbcSJohn Snow     }
412111b61fbcSJohn Snow 
412211b61fbcSJohn Snow     trace_qmp_block_job_finalize(job);
41237eaa8fb5SKevin Wolf     job_finalize(&job->job, errp);
412411b61fbcSJohn Snow     aio_context_release(aio_context);
412511b61fbcSJohn Snow }
412611b61fbcSJohn Snow 
412775f71059SJohn Snow void qmp_block_job_dismiss(const char *id, Error **errp)
412875f71059SJohn Snow {
412975f71059SJohn Snow     AioContext *aio_context;
41305f9a6a08SKevin Wolf     BlockJob *bjob = find_block_job(id, &aio_context, errp);
41315f9a6a08SKevin Wolf     Job *job;
413275f71059SJohn Snow 
41335f9a6a08SKevin Wolf     if (!bjob) {
413475f71059SJohn Snow         return;
413575f71059SJohn Snow     }
413675f71059SJohn Snow 
41375f9a6a08SKevin Wolf     trace_qmp_block_job_dismiss(bjob);
41385f9a6a08SKevin Wolf     job = &bjob->job;
41395f9a6a08SKevin Wolf     job_dismiss(&job, errp);
414075f71059SJohn Snow     aio_context_release(aio_context);
414175f71059SJohn Snow }
414275f71059SJohn Snow 
4143fa40e656SJeff Cody void qmp_change_backing_file(const char *device,
4144fa40e656SJeff Cody                              const char *image_node_name,
4145fa40e656SJeff Cody                              const char *backing_file,
4146fa40e656SJeff Cody                              Error **errp)
4147fa40e656SJeff Cody {
4148fa40e656SJeff Cody     BlockDriverState *bs = NULL;
4149729962f6SStefan Hajnoczi     AioContext *aio_context;
4150fa40e656SJeff Cody     BlockDriverState *image_bs = NULL;
4151fa40e656SJeff Cody     Error *local_err = NULL;
4152fa40e656SJeff Cody     bool ro;
4153fa40e656SJeff Cody     int ret;
4154fa40e656SJeff Cody 
41557b5dca3fSKevin Wolf     bs = qmp_get_root_bs(device, errp);
41567b5dca3fSKevin Wolf     if (!bs) {
4157fa40e656SJeff Cody         return;
4158fa40e656SJeff Cody     }
4159fa40e656SJeff Cody 
41607b5dca3fSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
4161729962f6SStefan Hajnoczi     aio_context_acquire(aio_context);
4162729962f6SStefan Hajnoczi 
4163fa40e656SJeff Cody     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
4164fa40e656SJeff Cody     if (local_err) {
4165fa40e656SJeff Cody         error_propagate(errp, local_err);
4166729962f6SStefan Hajnoczi         goto out;
4167fa40e656SJeff Cody     }
4168fa40e656SJeff Cody 
4169fa40e656SJeff Cody     if (!image_bs) {
4170fa40e656SJeff Cody         error_setg(errp, "image file not found");
4171729962f6SStefan Hajnoczi         goto out;
4172fa40e656SJeff Cody     }
4173fa40e656SJeff Cody 
4174fa40e656SJeff Cody     if (bdrv_find_base(image_bs) == image_bs) {
4175fa40e656SJeff Cody         error_setg(errp, "not allowing backing file change on an image "
4176fa40e656SJeff Cody                          "without a backing file");
4177729962f6SStefan Hajnoczi         goto out;
4178fa40e656SJeff Cody     }
4179fa40e656SJeff Cody 
4180fa40e656SJeff Cody     /* even though we are not necessarily operating on bs, we need it to
4181fa40e656SJeff Cody      * determine if block ops are currently prohibited on the chain */
4182fa40e656SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
4183729962f6SStefan Hajnoczi         goto out;
4184fa40e656SJeff Cody     }
4185fa40e656SJeff Cody 
4186fa40e656SJeff Cody     /* final sanity check */
4187fa40e656SJeff Cody     if (!bdrv_chain_contains(bs, image_bs)) {
4188fa40e656SJeff Cody         error_setg(errp, "'%s' and image file are not in the same chain",
4189fa40e656SJeff Cody                    device);
4190729962f6SStefan Hajnoczi         goto out;
4191fa40e656SJeff Cody     }
4192fa40e656SJeff Cody 
4193fa40e656SJeff Cody     /* if not r/w, reopen to make r/w */
4194fa40e656SJeff Cody     ro = bdrv_is_read_only(image_bs);
4195fa40e656SJeff Cody 
4196fa40e656SJeff Cody     if (ro) {
4197051a60f6SAlberto Garcia         if (bdrv_reopen_set_read_only(image_bs, false, errp) != 0) {
4198729962f6SStefan Hajnoczi             goto out;
4199fa40e656SJeff Cody         }
4200fa40e656SJeff Cody     }
4201fa40e656SJeff Cody 
4202fa40e656SJeff Cody     ret = bdrv_change_backing_file(image_bs, backing_file,
4203fa40e656SJeff Cody                                image_bs->drv ? image_bs->drv->format_name : "");
4204fa40e656SJeff Cody 
4205fa40e656SJeff Cody     if (ret < 0) {
4206fa40e656SJeff Cody         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
4207fa40e656SJeff Cody                          backing_file);
4208fa40e656SJeff Cody         /* don't exit here, so we can try to restore open flags if
4209fa40e656SJeff Cody          * appropriate */
4210fa40e656SJeff Cody     }
4211fa40e656SJeff Cody 
4212fa40e656SJeff Cody     if (ro) {
4213051a60f6SAlberto Garcia         bdrv_reopen_set_read_only(image_bs, true, &local_err);
4214621ff94dSEduardo Habkost         error_propagate(errp, local_err);
4215fa40e656SJeff Cody     }
4216729962f6SStefan Hajnoczi 
4217729962f6SStefan Hajnoczi out:
4218729962f6SStefan Hajnoczi     aio_context_release(aio_context);
4219fa40e656SJeff Cody }
4220fa40e656SJeff Cody 
4221abb21ac3SKevin Wolf void hmp_drive_add_node(Monitor *mon, const char *optstr)
4222abb21ac3SKevin Wolf {
4223abb21ac3SKevin Wolf     QemuOpts *opts;
4224abb21ac3SKevin Wolf     QDict *qdict;
4225abb21ac3SKevin Wolf     Error *local_err = NULL;
4226abb21ac3SKevin Wolf 
4227abb21ac3SKevin Wolf     opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
4228abb21ac3SKevin Wolf     if (!opts) {
4229abb21ac3SKevin Wolf         return;
4230abb21ac3SKevin Wolf     }
4231abb21ac3SKevin Wolf 
4232abb21ac3SKevin Wolf     qdict = qemu_opts_to_qdict(opts, NULL);
4233abb21ac3SKevin Wolf 
4234abb21ac3SKevin Wolf     if (!qdict_get_try_str(qdict, "node-name")) {
4235cb3e7f08SMarc-André Lureau         qobject_unref(qdict);
4236abb21ac3SKevin Wolf         error_report("'node-name' needs to be specified");
4237abb21ac3SKevin Wolf         goto out;
4238abb21ac3SKevin Wolf     }
4239abb21ac3SKevin Wolf 
4240abb21ac3SKevin Wolf     BlockDriverState *bs = bds_tree_init(qdict, &local_err);
4241abb21ac3SKevin Wolf     if (!bs) {
4242abb21ac3SKevin Wolf         error_report_err(local_err);
4243abb21ac3SKevin Wolf         goto out;
4244abb21ac3SKevin Wolf     }
4245abb21ac3SKevin Wolf 
4246abb21ac3SKevin Wolf     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4247abb21ac3SKevin Wolf 
4248abb21ac3SKevin Wolf out:
4249abb21ac3SKevin Wolf     qemu_opts_del(opts);
4250abb21ac3SKevin Wolf }
4251abb21ac3SKevin Wolf 
4252d26c9a15SKevin Wolf void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
4253d26c9a15SKevin Wolf {
4254be4b67bcSMax Reitz     BlockDriverState *bs;
4255d26c9a15SKevin Wolf     QObject *obj;
42567d5e199aSDaniel P. Berrange     Visitor *v = qobject_output_visitor_new(&obj);
4257d26c9a15SKevin Wolf     QDict *qdict;
4258d26c9a15SKevin Wolf     Error *local_err = NULL;
4259d26c9a15SKevin Wolf 
42603b098d56SEric Blake     visit_type_BlockdevOptions(v, NULL, &options, &local_err);
426184d18f06SMarkus Armbruster     if (local_err) {
4262d26c9a15SKevin Wolf         error_propagate(errp, local_err);
4263d26c9a15SKevin Wolf         goto fail;
4264d26c9a15SKevin Wolf     }
4265d26c9a15SKevin Wolf 
42663b098d56SEric Blake     visit_complete(v, &obj);
42677dc847ebSMax Reitz     qdict = qobject_to(QDict, obj);
4268d26c9a15SKevin Wolf 
4269d26c9a15SKevin Wolf     qdict_flatten(qdict);
4270d26c9a15SKevin Wolf 
4271be4b67bcSMax Reitz     if (!qdict_get_try_str(qdict, "node-name")) {
42729ec8873eSKevin Wolf         error_setg(errp, "'node-name' must be specified for the root node");
4273be4b67bcSMax Reitz         goto fail;
4274be4b67bcSMax Reitz     }
4275be4b67bcSMax Reitz 
4276bd745e23SMax Reitz     bs = bds_tree_init(qdict, errp);
4277bd745e23SMax Reitz     if (!bs) {
4278be4b67bcSMax Reitz         goto fail;
4279be4b67bcSMax Reitz     }
42809c4218e9SMax Reitz 
42819c4218e9SMax Reitz     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4282be4b67bcSMax Reitz 
4283d26c9a15SKevin Wolf fail:
42843b098d56SEric Blake     visit_free(v);
4285d26c9a15SKevin Wolf }
4286d26c9a15SKevin Wolf 
42871479c730SAlberto Garcia void qmp_x_blockdev_reopen(BlockdevOptions *options, Error **errp)
42881479c730SAlberto Garcia {
42891479c730SAlberto Garcia     BlockDriverState *bs;
42901479c730SAlberto Garcia     AioContext *ctx;
42911479c730SAlberto Garcia     QObject *obj;
42921479c730SAlberto Garcia     Visitor *v = qobject_output_visitor_new(&obj);
42931479c730SAlberto Garcia     Error *local_err = NULL;
42941479c730SAlberto Garcia     BlockReopenQueue *queue;
42951479c730SAlberto Garcia     QDict *qdict;
42961479c730SAlberto Garcia 
42971479c730SAlberto Garcia     /* Check for the selected node name */
42981479c730SAlberto Garcia     if (!options->has_node_name) {
42991479c730SAlberto Garcia         error_setg(errp, "Node name not specified");
43001479c730SAlberto Garcia         goto fail;
43011479c730SAlberto Garcia     }
43021479c730SAlberto Garcia 
43031479c730SAlberto Garcia     bs = bdrv_find_node(options->node_name);
43041479c730SAlberto Garcia     if (!bs) {
43051479c730SAlberto Garcia         error_setg(errp, "Cannot find node named '%s'", options->node_name);
43061479c730SAlberto Garcia         goto fail;
43071479c730SAlberto Garcia     }
43081479c730SAlberto Garcia 
43091479c730SAlberto Garcia     /* Put all options in a QDict and flatten it */
43101479c730SAlberto Garcia     visit_type_BlockdevOptions(v, NULL, &options, &local_err);
43111479c730SAlberto Garcia     if (local_err) {
43121479c730SAlberto Garcia         error_propagate(errp, local_err);
43131479c730SAlberto Garcia         goto fail;
43141479c730SAlberto Garcia     }
43151479c730SAlberto Garcia 
43161479c730SAlberto Garcia     visit_complete(v, &obj);
43171479c730SAlberto Garcia     qdict = qobject_to(QDict, obj);
43181479c730SAlberto Garcia 
43191479c730SAlberto Garcia     qdict_flatten(qdict);
43201479c730SAlberto Garcia 
43211479c730SAlberto Garcia     /* Perform the reopen operation */
43221479c730SAlberto Garcia     ctx = bdrv_get_aio_context(bs);
43231479c730SAlberto Garcia     aio_context_acquire(ctx);
43241479c730SAlberto Garcia     bdrv_subtree_drained_begin(bs);
43251479c730SAlberto Garcia     queue = bdrv_reopen_queue(NULL, bs, qdict, false);
43261479c730SAlberto Garcia     bdrv_reopen_multiple(queue, errp);
43271479c730SAlberto Garcia     bdrv_subtree_drained_end(bs);
43281479c730SAlberto Garcia     aio_context_release(ctx);
43291479c730SAlberto Garcia 
43301479c730SAlberto Garcia fail:
43311479c730SAlberto Garcia     visit_free(v);
43321479c730SAlberto Garcia }
43331479c730SAlberto Garcia 
433479b7a77eSMarkus Armbruster void qmp_blockdev_del(const char *node_name, Error **errp)
433581b936aeSAlberto Garcia {
433681b936aeSAlberto Garcia     AioContext *aio_context;
433781b936aeSAlberto Garcia     BlockDriverState *bs;
433881b936aeSAlberto Garcia 
433981b936aeSAlberto Garcia     bs = bdrv_find_node(node_name);
434081b936aeSAlberto Garcia     if (!bs) {
434181b936aeSAlberto Garcia         error_setg(errp, "Cannot find node %s", node_name);
434281b936aeSAlberto Garcia         return;
434381b936aeSAlberto Garcia     }
43441f0c461bSKevin Wolf     if (bdrv_has_blk(bs)) {
4345e467da7bSKevin Wolf         error_setg(errp, "Node %s is in use", node_name);
434681b936aeSAlberto Garcia         return;
434781b936aeSAlberto Garcia     }
434881b936aeSAlberto Garcia     aio_context = bdrv_get_aio_context(bs);
434981b936aeSAlberto Garcia     aio_context_acquire(aio_context);
435081b936aeSAlberto Garcia 
435181b936aeSAlberto Garcia     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
435281b936aeSAlberto Garcia         goto out;
435381b936aeSAlberto Garcia     }
435481b936aeSAlberto Garcia 
435570537ed5SPaolo Bonzini     if (!QTAILQ_IN_USE(bs, monitor_list)) {
43569c4218e9SMax Reitz         error_setg(errp, "Node %s is not owned by the monitor",
43579c4218e9SMax Reitz                    bs->node_name);
43589c4218e9SMax Reitz         goto out;
43599c4218e9SMax Reitz     }
43609c4218e9SMax Reitz 
43619c4218e9SMax Reitz     if (bs->refcnt > 1) {
436281b936aeSAlberto Garcia         error_setg(errp, "Block device %s is in use",
436381b936aeSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
436481b936aeSAlberto Garcia         goto out;
436581b936aeSAlberto Garcia     }
436681b936aeSAlberto Garcia 
43679c4218e9SMax Reitz     QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
436881b936aeSAlberto Garcia     bdrv_unref(bs);
436981b936aeSAlberto Garcia 
437081b936aeSAlberto Garcia out:
437181b936aeSAlberto Garcia     aio_context_release(aio_context);
437281b936aeSAlberto Garcia }
437381b936aeSAlberto Garcia 
43747f821597SWen Congyang static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
43757f821597SWen Congyang                                   const char *child_name)
43767f821597SWen Congyang {
43777f821597SWen Congyang     BdrvChild *child;
43787f821597SWen Congyang 
43797f821597SWen Congyang     QLIST_FOREACH(child, &parent_bs->children, next) {
43807f821597SWen Congyang         if (strcmp(child->name, child_name) == 0) {
43817f821597SWen Congyang             return child;
43827f821597SWen Congyang         }
43837f821597SWen Congyang     }
43847f821597SWen Congyang 
43857f821597SWen Congyang     return NULL;
43867f821597SWen Congyang }
43877f821597SWen Congyang 
43887f821597SWen Congyang void qmp_x_blockdev_change(const char *parent, bool has_child,
43897f821597SWen Congyang                            const char *child, bool has_node,
43907f821597SWen Congyang                            const char *node, Error **errp)
43917f821597SWen Congyang {
43927f821597SWen Congyang     BlockDriverState *parent_bs, *new_bs = NULL;
43937f821597SWen Congyang     BdrvChild *p_child;
43947f821597SWen Congyang 
43957f821597SWen Congyang     parent_bs = bdrv_lookup_bs(parent, parent, errp);
43967f821597SWen Congyang     if (!parent_bs) {
43977f821597SWen Congyang         return;
43987f821597SWen Congyang     }
43997f821597SWen Congyang 
44007f821597SWen Congyang     if (has_child == has_node) {
44017f821597SWen Congyang         if (has_child) {
44027f821597SWen Congyang             error_setg(errp, "The parameters child and node are in conflict");
44037f821597SWen Congyang         } else {
44047f821597SWen Congyang             error_setg(errp, "Either child or node must be specified");
44057f821597SWen Congyang         }
44067f821597SWen Congyang         return;
44077f821597SWen Congyang     }
44087f821597SWen Congyang 
44097f821597SWen Congyang     if (has_child) {
44107f821597SWen Congyang         p_child = bdrv_find_child(parent_bs, child);
44117f821597SWen Congyang         if (!p_child) {
44127f821597SWen Congyang             error_setg(errp, "Node '%s' does not have child '%s'",
44137f821597SWen Congyang                        parent, child);
44147f821597SWen Congyang             return;
44157f821597SWen Congyang         }
44167f821597SWen Congyang         bdrv_del_child(parent_bs, p_child, errp);
44177f821597SWen Congyang     }
44187f821597SWen Congyang 
44197f821597SWen Congyang     if (has_node) {
44207f821597SWen Congyang         new_bs = bdrv_find_node(node);
44217f821597SWen Congyang         if (!new_bs) {
44227f821597SWen Congyang             error_setg(errp, "Node '%s' not found", node);
44237f821597SWen Congyang             return;
44247f821597SWen Congyang         }
44257f821597SWen Congyang         bdrv_add_child(parent_bs, new_bs, errp);
44267f821597SWen Congyang     }
44277f821597SWen Congyang }
44287f821597SWen Congyang 
4429fb5458cdSStefan Hajnoczi BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4430fb5458cdSStefan Hajnoczi {
4431fea68bb6SMarkus Armbruster     BlockJobInfoList *head = NULL, **p_next = &head;
4432f0f55dedSAlberto Garcia     BlockJob *job;
4433fea68bb6SMarkus Armbruster 
4434f0f55dedSAlberto Garcia     for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4435559b935fSJohn Snow         BlockJobInfoList *elem;
4436559b935fSJohn Snow         AioContext *aio_context;
443769691e72SStefan Hajnoczi 
4438559b935fSJohn Snow         if (block_job_is_internal(job)) {
4439559b935fSJohn Snow             continue;
4440559b935fSJohn Snow         }
4441559b935fSJohn Snow         elem = g_new0(BlockJobInfoList, 1);
4442559b935fSJohn Snow         aio_context = blk_get_aio_context(job->blk);
444369691e72SStefan Hajnoczi         aio_context_acquire(aio_context);
4444559b935fSJohn Snow         elem->value = block_job_query(job, errp);
4445f0f55dedSAlberto Garcia         aio_context_release(aio_context);
4446559b935fSJohn Snow         if (!elem->value) {
4447559b935fSJohn Snow             g_free(elem);
4448559b935fSJohn Snow             qapi_free_BlockJobInfoList(head);
4449559b935fSJohn Snow             return NULL;
4450559b935fSJohn Snow         }
4451fea68bb6SMarkus Armbruster         *p_next = elem;
4452fea68bb6SMarkus Armbruster         p_next = &elem->next;
4453fea68bb6SMarkus Armbruster     }
445469691e72SStefan Hajnoczi 
4455fea68bb6SMarkus Armbruster     return head;
4456fb5458cdSStefan Hajnoczi }
44574d454574SPaolo Bonzini 
4458ca00bbb1SStefan Hajnoczi void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
4459882e9b89SStefan Hajnoczi                                  bool has_force, bool force, Error **errp)
4460ca00bbb1SStefan Hajnoczi {
4461ca00bbb1SStefan Hajnoczi     AioContext *old_context;
4462ca00bbb1SStefan Hajnoczi     AioContext *new_context;
4463ca00bbb1SStefan Hajnoczi     BlockDriverState *bs;
4464ca00bbb1SStefan Hajnoczi 
4465ca00bbb1SStefan Hajnoczi     bs = bdrv_find_node(node_name);
4466ca00bbb1SStefan Hajnoczi     if (!bs) {
4467ca00bbb1SStefan Hajnoczi         error_setg(errp, "Cannot find node %s", node_name);
4468ca00bbb1SStefan Hajnoczi         return;
4469ca00bbb1SStefan Hajnoczi     }
4470ca00bbb1SStefan Hajnoczi 
4471882e9b89SStefan Hajnoczi     /* Protects against accidents. */
4472882e9b89SStefan Hajnoczi     if (!(has_force && force) && bdrv_has_blk(bs)) {
4473882e9b89SStefan Hajnoczi         error_setg(errp, "Node %s is associated with a BlockBackend and could "
4474882e9b89SStefan Hajnoczi                          "be in use (use force=true to override this check)",
4475882e9b89SStefan Hajnoczi                          node_name);
4476ca00bbb1SStefan Hajnoczi         return;
4477ca00bbb1SStefan Hajnoczi     }
4478ca00bbb1SStefan Hajnoczi 
4479ca00bbb1SStefan Hajnoczi     if (iothread->type == QTYPE_QSTRING) {
4480ca00bbb1SStefan Hajnoczi         IOThread *obj = iothread_by_id(iothread->u.s);
4481ca00bbb1SStefan Hajnoczi         if (!obj) {
4482ca00bbb1SStefan Hajnoczi             error_setg(errp, "Cannot find iothread %s", iothread->u.s);
4483ca00bbb1SStefan Hajnoczi             return;
4484ca00bbb1SStefan Hajnoczi         }
4485ca00bbb1SStefan Hajnoczi 
4486ca00bbb1SStefan Hajnoczi         new_context = iothread_get_aio_context(obj);
4487ca00bbb1SStefan Hajnoczi     } else {
4488ca00bbb1SStefan Hajnoczi         new_context = qemu_get_aio_context();
4489ca00bbb1SStefan Hajnoczi     }
4490ca00bbb1SStefan Hajnoczi 
4491ca00bbb1SStefan Hajnoczi     old_context = bdrv_get_aio_context(bs);
4492ca00bbb1SStefan Hajnoczi     aio_context_acquire(old_context);
4493ca00bbb1SStefan Hajnoczi 
4494ca00bbb1SStefan Hajnoczi     bdrv_set_aio_context(bs, new_context);
4495ca00bbb1SStefan Hajnoczi 
4496ca00bbb1SStefan Hajnoczi     aio_context_release(old_context);
4497ca00bbb1SStefan Hajnoczi }
4498ca00bbb1SStefan Hajnoczi 
4499cb8aac37SVladimir Sementsov-Ogievskiy void qmp_block_latency_histogram_set(
4500af0a2265SVladimir Sementsov-Ogievskiy     const char *id,
45017e5c776dSVladimir Sementsov-Ogievskiy     bool has_boundaries, uint64List *boundaries,
45027e5c776dSVladimir Sementsov-Ogievskiy     bool has_boundaries_read, uint64List *boundaries_read,
45037e5c776dSVladimir Sementsov-Ogievskiy     bool has_boundaries_write, uint64List *boundaries_write,
45047e5c776dSVladimir Sementsov-Ogievskiy     bool has_boundaries_flush, uint64List *boundaries_flush,
45057e5c776dSVladimir Sementsov-Ogievskiy     Error **errp)
45067e5c776dSVladimir Sementsov-Ogievskiy {
4507af0a2265SVladimir Sementsov-Ogievskiy     BlockBackend *blk = qmp_get_blk(NULL, id, errp);
45087e5c776dSVladimir Sementsov-Ogievskiy     BlockAcctStats *stats;
450963d5341fSzhenwei pi     int ret;
45107e5c776dSVladimir Sementsov-Ogievskiy 
45117e5c776dSVladimir Sementsov-Ogievskiy     if (!blk) {
45127e5c776dSVladimir Sementsov-Ogievskiy         return;
45137e5c776dSVladimir Sementsov-Ogievskiy     }
4514af0a2265SVladimir Sementsov-Ogievskiy 
45157e5c776dSVladimir Sementsov-Ogievskiy     stats = blk_get_stats(blk);
45167e5c776dSVladimir Sementsov-Ogievskiy 
45177e5c776dSVladimir Sementsov-Ogievskiy     if (!has_boundaries && !has_boundaries_read && !has_boundaries_write &&
45187e5c776dSVladimir Sementsov-Ogievskiy         !has_boundaries_flush)
45197e5c776dSVladimir Sementsov-Ogievskiy     {
45207e5c776dSVladimir Sementsov-Ogievskiy         block_latency_histograms_clear(stats);
45217e5c776dSVladimir Sementsov-Ogievskiy         return;
45227e5c776dSVladimir Sementsov-Ogievskiy     }
45237e5c776dSVladimir Sementsov-Ogievskiy 
45247e5c776dSVladimir Sementsov-Ogievskiy     if (has_boundaries || has_boundaries_read) {
452563d5341fSzhenwei pi         ret = block_latency_histogram_set(
45267e5c776dSVladimir Sementsov-Ogievskiy             stats, BLOCK_ACCT_READ,
45277e5c776dSVladimir Sementsov-Ogievskiy             has_boundaries_read ? boundaries_read : boundaries);
452863d5341fSzhenwei pi         if (ret) {
4529af0a2265SVladimir Sementsov-Ogievskiy             error_setg(errp, "Device '%s' set read boundaries fail", id);
453063d5341fSzhenwei pi             return;
453163d5341fSzhenwei pi         }
45327e5c776dSVladimir Sementsov-Ogievskiy     }
45337e5c776dSVladimir Sementsov-Ogievskiy 
45347e5c776dSVladimir Sementsov-Ogievskiy     if (has_boundaries || has_boundaries_write) {
453563d5341fSzhenwei pi         ret = block_latency_histogram_set(
45367e5c776dSVladimir Sementsov-Ogievskiy             stats, BLOCK_ACCT_WRITE,
45377e5c776dSVladimir Sementsov-Ogievskiy             has_boundaries_write ? boundaries_write : boundaries);
453863d5341fSzhenwei pi         if (ret) {
4539af0a2265SVladimir Sementsov-Ogievskiy             error_setg(errp, "Device '%s' set write boundaries fail", id);
454063d5341fSzhenwei pi             return;
454163d5341fSzhenwei pi         }
45427e5c776dSVladimir Sementsov-Ogievskiy     }
45437e5c776dSVladimir Sementsov-Ogievskiy 
45447e5c776dSVladimir Sementsov-Ogievskiy     if (has_boundaries || has_boundaries_flush) {
454563d5341fSzhenwei pi         ret = block_latency_histogram_set(
45467e5c776dSVladimir Sementsov-Ogievskiy             stats, BLOCK_ACCT_FLUSH,
45477e5c776dSVladimir Sementsov-Ogievskiy             has_boundaries_flush ? boundaries_flush : boundaries);
454863d5341fSzhenwei pi         if (ret) {
4549af0a2265SVladimir Sementsov-Ogievskiy             error_setg(errp, "Device '%s' set flush boundaries fail", id);
455063d5341fSzhenwei pi             return;
455163d5341fSzhenwei pi         }
45527e5c776dSVladimir Sementsov-Ogievskiy     }
45537e5c776dSVladimir Sementsov-Ogievskiy }
45547e5c776dSVladimir Sementsov-Ogievskiy 
45550006383eSKevin Wolf QemuOptsList qemu_common_drive_opts = {
45564d454574SPaolo Bonzini     .name = "drive",
45570006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
45584d454574SPaolo Bonzini     .desc = {
45594d454574SPaolo Bonzini         {
45604d454574SPaolo Bonzini             .name = "snapshot",
45614d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
45624d454574SPaolo Bonzini             .help = "enable/disable snapshot mode",
45634d454574SPaolo Bonzini         },{
45644d454574SPaolo Bonzini             .name = "aio",
45654d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
45664d454574SPaolo Bonzini             .help = "host AIO implementation (threads, native)",
45674d454574SPaolo Bonzini         },{
4568e4b24b49SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
4569e4b24b49SKevin Wolf             .type = QEMU_OPT_BOOL,
4570e4b24b49SKevin Wolf             .help = "Enable writeback mode",
4571e4b24b49SKevin Wolf         },{
45724d454574SPaolo Bonzini             .name = "format",
45734d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
45744d454574SPaolo Bonzini             .help = "disk format (raw, qcow2, ...)",
45754d454574SPaolo Bonzini         },{
45764d454574SPaolo Bonzini             .name = "rerror",
45774d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
45784d454574SPaolo Bonzini             .help = "read error action",
45794d454574SPaolo Bonzini         },{
45804d454574SPaolo Bonzini             .name = "werror",
45814d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
45824d454574SPaolo Bonzini             .help = "write error action",
45834d454574SPaolo Bonzini         },{
45844e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
45854d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
45864d454574SPaolo Bonzini             .help = "open drive file as read-only",
4587a2a7862cSPradeep Jagadeesh         },
4588a2a7862cSPradeep Jagadeesh 
4589a2a7862cSPradeep Jagadeesh         THROTTLE_OPTS,
4590a2a7862cSPradeep Jagadeesh 
4591a2a7862cSPradeep Jagadeesh         {
459276f4afb4SAlberto Garcia             .name = "throttling.group",
459376f4afb4SAlberto Garcia             .type = QEMU_OPT_STRING,
459476f4afb4SAlberto Garcia             .help = "name of the block throttling group",
459576f4afb4SAlberto Garcia         },{
45964d454574SPaolo Bonzini             .name = "copy-on-read",
45974d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
45984d454574SPaolo Bonzini             .help = "copy read data from backing file into image file",
4599465bee1dSPeter Lieven         },{
4600465bee1dSPeter Lieven             .name = "detect-zeroes",
4601465bee1dSPeter Lieven             .type = QEMU_OPT_STRING,
4602465bee1dSPeter Lieven             .help = "try to optimize zero writes (off, on, unmap)",
4603362e9299SAlberto Garcia         },{
4604362e9299SAlberto Garcia             .name = "stats-account-invalid",
4605362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4606362e9299SAlberto Garcia             .help = "whether to account for invalid I/O operations "
4607362e9299SAlberto Garcia                     "in the statistics",
4608362e9299SAlberto Garcia         },{
4609362e9299SAlberto Garcia             .name = "stats-account-failed",
4610362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
4611362e9299SAlberto Garcia             .help = "whether to account for failed I/O operations "
4612362e9299SAlberto Garcia                     "in the statistics",
46134d454574SPaolo Bonzini         },
46144d454574SPaolo Bonzini         { /* end of list */ }
46154d454574SPaolo Bonzini     },
46164d454574SPaolo Bonzini };
46170006383eSKevin Wolf 
46180006383eSKevin Wolf QemuOptsList qemu_drive_opts = {
46190006383eSKevin Wolf     .name = "drive",
46200006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
46210006383eSKevin Wolf     .desc = {
4622492fdc6fSKevin Wolf         /*
4623492fdc6fSKevin Wolf          * no elements => accept any params
4624492fdc6fSKevin Wolf          * validation will happen later
4625492fdc6fSKevin Wolf          */
46260006383eSKevin Wolf         { /* end of list */ }
46270006383eSKevin Wolf     },
46280006383eSKevin Wolf };
4629