xref: /openbmc/qemu/blockdev.c (revision 3f072a7fb747413bbf6a63fd6476888b6b671a04)
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"
6154d31236SMarkus Armbruster #include "sysemu/runstate.h"
62f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
63f348b6d1SVeronia Bahaa #include "qemu/help_option.h"
64db725815SMarkus Armbruster #include "qemu/main-loop.h"
65a2a7862cSPradeep Jagadeesh #include "qemu/throttle-options.h"
66666daa68SMarkus Armbruster 
6789802d5aSMaxim Levitsky QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
689c4218e9SMax Reitz     QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
699c4218e9SMax Reitz 
7089802d5aSMaxim Levitsky void bdrv_set_monitor_owned(BlockDriverState *bs)
7189802d5aSMaxim Levitsky {
7289802d5aSMaxim Levitsky     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
7389802d5aSMaxim Levitsky }
7489802d5aSMaxim Levitsky 
751960966dSMarkus Armbruster static const char *const if_name[IF_COUNT] = {
761960966dSMarkus Armbruster     [IF_NONE] = "none",
771960966dSMarkus Armbruster     [IF_IDE] = "ide",
781960966dSMarkus Armbruster     [IF_SCSI] = "scsi",
791960966dSMarkus Armbruster     [IF_FLOPPY] = "floppy",
801960966dSMarkus Armbruster     [IF_PFLASH] = "pflash",
811960966dSMarkus Armbruster     [IF_MTD] = "mtd",
821960966dSMarkus Armbruster     [IF_SD] = "sd",
831960966dSMarkus Armbruster     [IF_VIRTIO] = "virtio",
841960966dSMarkus Armbruster     [IF_XEN] = "xen",
851960966dSMarkus Armbruster };
861960966dSMarkus Armbruster 
8721dff8cfSJohn Snow static int if_max_devs[IF_COUNT] = {
8827d6bf40SMarkus Armbruster     /*
8927d6bf40SMarkus Armbruster      * Do not change these numbers!  They govern how drive option
9027d6bf40SMarkus Armbruster      * index maps to unit and bus.  That mapping is ABI.
9127d6bf40SMarkus Armbruster      *
92547cb157SWei Jiangang      * All controllers used to implement if=T drives need to support
9327d6bf40SMarkus Armbruster      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
9427d6bf40SMarkus Armbruster      * Otherwise, some index values map to "impossible" bus, unit
9527d6bf40SMarkus Armbruster      * values.
9627d6bf40SMarkus Armbruster      *
9727d6bf40SMarkus Armbruster      * For instance, if you change [IF_SCSI] to 255, -drive
9827d6bf40SMarkus Armbruster      * if=scsi,index=12 no longer means bus=1,unit=5, but
9927d6bf40SMarkus Armbruster      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
10027d6bf40SMarkus Armbruster      * the drive can't be set up.  Regression.
10127d6bf40SMarkus Armbruster      */
10227d6bf40SMarkus Armbruster     [IF_IDE] = 2,
10327d6bf40SMarkus Armbruster     [IF_SCSI] = 7,
1041960966dSMarkus Armbruster };
1051960966dSMarkus Armbruster 
10621dff8cfSJohn Snow /**
10721dff8cfSJohn Snow  * Boards may call this to offer board-by-board overrides
10821dff8cfSJohn Snow  * of the default, global values.
10921dff8cfSJohn Snow  */
11021dff8cfSJohn Snow void override_max_devs(BlockInterfaceType type, int max_devs)
11121dff8cfSJohn Snow {
11218e46a03SMarkus Armbruster     BlockBackend *blk;
11321dff8cfSJohn Snow     DriveInfo *dinfo;
11421dff8cfSJohn Snow 
11521dff8cfSJohn Snow     if (max_devs <= 0) {
11621dff8cfSJohn Snow         return;
11721dff8cfSJohn Snow     }
11821dff8cfSJohn Snow 
11918e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
12018e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
12121dff8cfSJohn Snow         if (dinfo->type == type) {
12221dff8cfSJohn Snow             fprintf(stderr, "Cannot override units-per-bus property of"
12321dff8cfSJohn Snow                     " the %s interface, because a drive of that type has"
12421dff8cfSJohn Snow                     " already been added.\n", if_name[type]);
12521dff8cfSJohn Snow             g_assert_not_reached();
12621dff8cfSJohn Snow         }
12721dff8cfSJohn Snow     }
12821dff8cfSJohn Snow 
12921dff8cfSJohn Snow     if_max_devs[type] = max_devs;
13021dff8cfSJohn Snow }
13121dff8cfSJohn Snow 
13214bafc54SMarkus Armbruster /*
13314bafc54SMarkus Armbruster  * We automatically delete the drive when a device using it gets
13414bafc54SMarkus Armbruster  * unplugged.  Questionable feature, but we can't just drop it.
13514bafc54SMarkus Armbruster  * Device models call blockdev_mark_auto_del() to schedule the
13614bafc54SMarkus Armbruster  * automatic deletion, and generic qdev code calls blockdev_auto_del()
13714bafc54SMarkus Armbruster  * when deletion is actually safe.
13814bafc54SMarkus Armbruster  */
1394be74634SMarkus Armbruster void blockdev_mark_auto_del(BlockBackend *blk)
14014bafc54SMarkus Armbruster {
14118e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
1428164102fSVladimir Sementsov-Ogievskiy     BlockJob *job;
14314bafc54SMarkus Armbruster 
14426f8b3a8SMarkus Armbruster     if (!dinfo) {
1452d246f01SKevin Wolf         return;
1462d246f01SKevin Wolf     }
1472d246f01SKevin Wolf 
1488164102fSVladimir Sementsov-Ogievskiy     for (job = block_job_next(NULL); job; job = block_job_next(job)) {
1498164102fSVladimir Sementsov-Ogievskiy         if (block_job_has_bdrv(job, blk_bs(blk))) {
1508164102fSVladimir Sementsov-Ogievskiy             AioContext *aio_context = job->job.aio_context;
15191fddb0dSStefan Hajnoczi             aio_context_acquire(aio_context);
15291fddb0dSStefan Hajnoczi 
1538164102fSVladimir Sementsov-Ogievskiy             job_cancel(&job->job, false);
15491fddb0dSStefan Hajnoczi 
15591fddb0dSStefan Hajnoczi             aio_context_release(aio_context);
1565433c24fSMax Reitz         }
1578164102fSVladimir Sementsov-Ogievskiy     }
15891fddb0dSStefan Hajnoczi 
15914bafc54SMarkus Armbruster     dinfo->auto_del = 1;
16014bafc54SMarkus Armbruster }
16114bafc54SMarkus Armbruster 
1624be74634SMarkus Armbruster void blockdev_auto_del(BlockBackend *blk)
16314bafc54SMarkus Armbruster {
16418e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
16514bafc54SMarkus Armbruster 
1660fc0f1faSRyan Harper     if (dinfo && dinfo->auto_del) {
167efaa7c4eSMax Reitz         monitor_remove_blk(blk);
168b9fe8a7aSMarkus Armbruster         blk_unref(blk);
16914bafc54SMarkus Armbruster     }
17014bafc54SMarkus Armbruster }
17114bafc54SMarkus Armbruster 
172d8f94e1bSJohn Snow /**
173d8f94e1bSJohn Snow  * Returns the current mapping of how many units per bus
174d8f94e1bSJohn Snow  * a particular interface can support.
175d8f94e1bSJohn Snow  *
176d8f94e1bSJohn Snow  *  A positive integer indicates n units per bus.
177d8f94e1bSJohn Snow  *  0 implies the mapping has not been established.
178d8f94e1bSJohn Snow  * -1 indicates an invalid BlockInterfaceType was given.
179d8f94e1bSJohn Snow  */
180d8f94e1bSJohn Snow int drive_get_max_devs(BlockInterfaceType type)
181d8f94e1bSJohn Snow {
182d8f94e1bSJohn Snow     if (type >= IF_IDE && type < IF_COUNT) {
183d8f94e1bSJohn Snow         return if_max_devs[type];
184d8f94e1bSJohn Snow     }
185d8f94e1bSJohn Snow 
186d8f94e1bSJohn Snow     return -1;
187d8f94e1bSJohn Snow }
188d8f94e1bSJohn Snow 
189505a7fb1SMarkus Armbruster static int drive_index_to_bus_id(BlockInterfaceType type, int index)
190505a7fb1SMarkus Armbruster {
191505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
192505a7fb1SMarkus Armbruster     return max_devs ? index / max_devs : 0;
193505a7fb1SMarkus Armbruster }
194505a7fb1SMarkus Armbruster 
195505a7fb1SMarkus Armbruster static int drive_index_to_unit_id(BlockInterfaceType type, int index)
196505a7fb1SMarkus Armbruster {
197505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
198505a7fb1SMarkus Armbruster     return max_devs ? index % max_devs : index;
199505a7fb1SMarkus Armbruster }
200505a7fb1SMarkus Armbruster 
2012292ddaeSMarkus Armbruster QemuOpts *drive_def(const char *optstr)
2022292ddaeSMarkus Armbruster {
20370b94331SMarkus Armbruster     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
2042292ddaeSMarkus Armbruster }
2052292ddaeSMarkus Armbruster 
2062292ddaeSMarkus Armbruster QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
2075645b0f4SMarkus Armbruster                     const char *optstr)
208666daa68SMarkus Armbruster {
209666daa68SMarkus Armbruster     QemuOpts *opts;
210666daa68SMarkus Armbruster 
2112292ddaeSMarkus Armbruster     opts = drive_def(optstr);
212666daa68SMarkus Armbruster     if (!opts) {
213666daa68SMarkus Armbruster         return NULL;
214666daa68SMarkus Armbruster     }
2152292ddaeSMarkus Armbruster     if (type != IF_DEFAULT) {
216f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "if", if_name[type], &error_abort);
2172292ddaeSMarkus Armbruster     }
2182292ddaeSMarkus Armbruster     if (index >= 0) {
219a8b18f8fSMarkus Armbruster         qemu_opt_set_number(opts, "index", index, &error_abort);
2202292ddaeSMarkus Armbruster     }
221666daa68SMarkus Armbruster     if (file)
222f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "file", file, &error_abort);
223666daa68SMarkus Armbruster     return opts;
224666daa68SMarkus Armbruster }
225666daa68SMarkus Armbruster 
226666daa68SMarkus Armbruster DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
227666daa68SMarkus Armbruster {
22818e46a03SMarkus Armbruster     BlockBackend *blk;
229666daa68SMarkus Armbruster     DriveInfo *dinfo;
230666daa68SMarkus Armbruster 
23118e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
23218e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
23318e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type
23418e46a03SMarkus Armbruster             && dinfo->bus == bus && dinfo->unit == unit) {
235666daa68SMarkus Armbruster             return dinfo;
236666daa68SMarkus Armbruster         }
23718e46a03SMarkus Armbruster     }
238666daa68SMarkus Armbruster 
239666daa68SMarkus Armbruster     return NULL;
240666daa68SMarkus Armbruster }
241666daa68SMarkus Armbruster 
242a1b40bdaSMarkus Armbruster void drive_mark_claimed_by_board(void)
243a1b40bdaSMarkus Armbruster {
244a1b40bdaSMarkus Armbruster     BlockBackend *blk;
245a1b40bdaSMarkus Armbruster     DriveInfo *dinfo;
246a1b40bdaSMarkus Armbruster 
247a1b40bdaSMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
248a1b40bdaSMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
249a1b40bdaSMarkus Armbruster         if (dinfo && blk_get_attached_dev(blk)) {
250a1b40bdaSMarkus Armbruster             dinfo->claimed_by_board = true;
251a1b40bdaSMarkus Armbruster         }
252a1b40bdaSMarkus Armbruster     }
253a1b40bdaSMarkus Armbruster }
254a1b40bdaSMarkus Armbruster 
255720b8dc0SMarkus Armbruster void drive_check_orphaned(void)
256a66c9dc7SJohn Snow {
25718e46a03SMarkus Armbruster     BlockBackend *blk;
258a66c9dc7SJohn Snow     DriveInfo *dinfo;
259664cc623SMarkus Armbruster     Location loc;
260720b8dc0SMarkus Armbruster     bool orphans = false;
261a66c9dc7SJohn Snow 
26218e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
26318e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
264a1b40bdaSMarkus Armbruster         if (dinfo->is_default || dinfo->type == IF_NONE) {
265a1b40bdaSMarkus Armbruster             continue;
266a1b40bdaSMarkus Armbruster         }
267a1b40bdaSMarkus Armbruster         if (!blk_get_attached_dev(blk)) {
268664cc623SMarkus Armbruster             loc_push_none(&loc);
269664cc623SMarkus Armbruster             qemu_opts_loc_restore(dinfo->opts);
270720b8dc0SMarkus Armbruster             error_report("machine type does not support"
271664cc623SMarkus Armbruster                          " if=%s,bus=%d,unit=%d",
2725433c24fSMax Reitz                          if_name[dinfo->type], dinfo->bus, dinfo->unit);
273664cc623SMarkus Armbruster             loc_pop(&loc);
274720b8dc0SMarkus Armbruster             orphans = true;
275a1b40bdaSMarkus Armbruster             continue;
276a1b40bdaSMarkus Armbruster         }
277a1b40bdaSMarkus Armbruster         if (!dinfo->claimed_by_board && dinfo->type != IF_VIRTIO) {
278a1b40bdaSMarkus Armbruster             loc_push_none(&loc);
279a1b40bdaSMarkus Armbruster             qemu_opts_loc_restore(dinfo->opts);
280a1b40bdaSMarkus Armbruster             warn_report("bogus if=%s is deprecated, use if=none",
281a1b40bdaSMarkus Armbruster                         if_name[dinfo->type]);
282a1b40bdaSMarkus Armbruster             loc_pop(&loc);
283a66c9dc7SJohn Snow         }
284a66c9dc7SJohn Snow     }
285a66c9dc7SJohn Snow 
286720b8dc0SMarkus Armbruster     if (orphans) {
287720b8dc0SMarkus Armbruster         exit(1);
288720b8dc0SMarkus Armbruster     }
289a66c9dc7SJohn Snow }
290a66c9dc7SJohn Snow 
291f1bd51acSMarkus Armbruster DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
292f1bd51acSMarkus Armbruster {
293f1bd51acSMarkus Armbruster     return drive_get(type,
294f1bd51acSMarkus Armbruster                      drive_index_to_bus_id(type, index),
295f1bd51acSMarkus Armbruster                      drive_index_to_unit_id(type, index));
296f1bd51acSMarkus Armbruster }
297f1bd51acSMarkus Armbruster 
298666daa68SMarkus Armbruster int drive_get_max_bus(BlockInterfaceType type)
299666daa68SMarkus Armbruster {
300666daa68SMarkus Armbruster     int max_bus;
30118e46a03SMarkus Armbruster     BlockBackend *blk;
302666daa68SMarkus Armbruster     DriveInfo *dinfo;
303666daa68SMarkus Armbruster 
304666daa68SMarkus Armbruster     max_bus = -1;
30518e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
30618e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
30718e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
308666daa68SMarkus Armbruster             max_bus = dinfo->bus;
309666daa68SMarkus Armbruster         }
31018e46a03SMarkus Armbruster     }
311666daa68SMarkus Armbruster     return max_bus;
312666daa68SMarkus Armbruster }
313666daa68SMarkus Armbruster 
31413839974SMarkus Armbruster /* Get a block device.  This should only be used for single-drive devices
31513839974SMarkus Armbruster    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
31613839974SMarkus Armbruster    appropriate bus.  */
31713839974SMarkus Armbruster DriveInfo *drive_get_next(BlockInterfaceType type)
31813839974SMarkus Armbruster {
31913839974SMarkus Armbruster     static int next_block_unit[IF_COUNT];
32013839974SMarkus Armbruster 
32113839974SMarkus Armbruster     return drive_get(type, 0, next_block_unit[type]++);
32213839974SMarkus Armbruster }
32313839974SMarkus Armbruster 
324666daa68SMarkus Armbruster static void bdrv_format_print(void *opaque, const char *name)
325666daa68SMarkus Armbruster {
326cdcd4361SMarkus Armbruster     qemu_printf(" %s", name);
327666daa68SMarkus Armbruster }
328666daa68SMarkus Armbruster 
329aa398a5cSStefan Hajnoczi typedef struct {
330aa398a5cSStefan Hajnoczi     QEMUBH *bh;
331fa510ebfSFam Zheng     BlockDriverState *bs;
332fa510ebfSFam Zheng } BDRVPutRefBH;
333aa398a5cSStefan Hajnoczi 
334b681072dSKevin Wolf static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
335666daa68SMarkus Armbruster {
336666daa68SMarkus Armbruster     if (!strcmp(buf, "ignore")) {
33792aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_IGNORE;
338666daa68SMarkus Armbruster     } else if (!is_read && !strcmp(buf, "enospc")) {
33992aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_ENOSPC;
340666daa68SMarkus Armbruster     } else if (!strcmp(buf, "stop")) {
34192aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_STOP;
342666daa68SMarkus Armbruster     } else if (!strcmp(buf, "report")) {
34392aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_REPORT;
344666daa68SMarkus Armbruster     } else {
345b681072dSKevin Wolf         error_setg(errp, "'%s' invalid %s error action",
346666daa68SMarkus Armbruster                    buf, is_read ? "read" : "write");
347666daa68SMarkus Armbruster         return -1;
348666daa68SMarkus Armbruster     }
349666daa68SMarkus Armbruster }
350666daa68SMarkus Armbruster 
35140119effSAlberto Garcia static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
35240119effSAlberto Garcia                                   Error **errp)
35340119effSAlberto Garcia {
35440119effSAlberto Garcia     const QListEntry *entry;
35540119effSAlberto Garcia     for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
35640119effSAlberto Garcia         switch (qobject_type(entry->value)) {
35740119effSAlberto Garcia 
35840119effSAlberto Garcia         case QTYPE_QSTRING: {
35940119effSAlberto Garcia             unsigned long long length;
3607dc847ebSMax Reitz             const char *str = qstring_get_str(qobject_to(QString,
3617dc847ebSMax Reitz                                                          entry->value));
36240119effSAlberto Garcia             if (parse_uint_full(str, &length, 10) == 0 &&
36340119effSAlberto Garcia                 length > 0 && length <= UINT_MAX) {
36440119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
36540119effSAlberto Garcia             } else {
36640119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %s", str);
36740119effSAlberto Garcia                 return false;
36840119effSAlberto Garcia             }
36940119effSAlberto Garcia             break;
37040119effSAlberto Garcia         }
37140119effSAlberto Garcia 
37201b2ffceSMarc-André Lureau         case QTYPE_QNUM: {
3737dc847ebSMax Reitz             int64_t length = qnum_get_int(qobject_to(QNum, entry->value));
37401b2ffceSMarc-André Lureau 
37540119effSAlberto Garcia             if (length > 0 && length <= UINT_MAX) {
37640119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
37740119effSAlberto Garcia             } else {
37840119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %" PRId64, length);
37940119effSAlberto Garcia                 return false;
38040119effSAlberto Garcia             }
38140119effSAlberto Garcia             break;
38240119effSAlberto Garcia         }
38340119effSAlberto Garcia 
38440119effSAlberto Garcia         default:
38540119effSAlberto Garcia             error_setg(errp, "The specification of stats-intervals is invalid");
38640119effSAlberto Garcia             return false;
38740119effSAlberto Garcia         }
38840119effSAlberto Garcia     }
38940119effSAlberto Garcia     return true;
39040119effSAlberto Garcia }
39140119effSAlberto Garcia 
39233cb7dc8SKevin Wolf typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
39333cb7dc8SKevin Wolf 
394fbf8175eSMax Reitz /* All parameters but @opts are optional and may be set to NULL. */
395fbf8175eSMax Reitz static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
396fbf8175eSMax Reitz     const char **throttling_group, ThrottleConfig *throttle_cfg,
397fbf8175eSMax Reitz     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
398fbf8175eSMax Reitz {
399fbf8175eSMax Reitz     Error *local_error = NULL;
400fbf8175eSMax Reitz     const char *aio;
401fbf8175eSMax Reitz 
402fbf8175eSMax Reitz     if (bdrv_flags) {
403fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
404fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_COPY_ON_READ;
405fbf8175eSMax Reitz         }
406fbf8175eSMax Reitz 
407fbf8175eSMax Reitz         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
408f80f2673SAarushi Mehta             if (bdrv_parse_aio(aio, bdrv_flags) < 0) {
409fbf8175eSMax Reitz                 error_setg(errp, "invalid aio option");
410fbf8175eSMax Reitz                 return;
411fbf8175eSMax Reitz             }
412fbf8175eSMax Reitz         }
413fbf8175eSMax Reitz     }
414fbf8175eSMax Reitz 
415fbf8175eSMax Reitz     /* disk I/O throttling */
416fbf8175eSMax Reitz     if (throttling_group) {
417fbf8175eSMax Reitz         *throttling_group = qemu_opt_get(opts, "throttling.group");
418fbf8175eSMax Reitz     }
419fbf8175eSMax Reitz 
420fbf8175eSMax Reitz     if (throttle_cfg) {
4211588ab5dSAlberto Garcia         throttle_config_init(throttle_cfg);
422fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
423fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total", 0);
424fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
425fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read", 0);
426fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
427fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write", 0);
428fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
429fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total", 0);
430fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
431fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read", 0);
432fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
433fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write", 0);
434fbf8175eSMax Reitz 
435fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
436fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
437fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
438fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
439fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
440fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
441fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
442fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
443fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
444fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
445fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
446fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
447fbf8175eSMax Reitz 
4488a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
4498a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
4508a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length  =
4518a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
4528a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
4538a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
4548a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
4558a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
4568a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
4578a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
4588a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
4598a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
4608a0fc18dSAlberto Garcia 
461fbf8175eSMax Reitz         throttle_cfg->op_size =
462fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-size", 0);
463fbf8175eSMax Reitz 
464d5851089SAlberto Garcia         if (!throttle_is_valid(throttle_cfg, errp)) {
465fbf8175eSMax Reitz             return;
466fbf8175eSMax Reitz         }
467fbf8175eSMax Reitz     }
468fbf8175eSMax Reitz 
469fbf8175eSMax Reitz     if (detect_zeroes) {
470fbf8175eSMax Reitz         *detect_zeroes =
471f7abe0ecSMarc-André Lureau             qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
472fbf8175eSMax Reitz                             qemu_opt_get(opts, "detect-zeroes"),
473fbf8175eSMax Reitz                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
474fbf8175eSMax Reitz                             &local_error);
475fbf8175eSMax Reitz         if (local_error) {
476fbf8175eSMax Reitz             error_propagate(errp, local_error);
477fbf8175eSMax Reitz             return;
478fbf8175eSMax Reitz         }
479fbf8175eSMax Reitz     }
480fbf8175eSMax Reitz }
481fbf8175eSMax Reitz 
482f298d071SKevin Wolf /* Takes the ownership of bs_opts */
48318e46a03SMarkus Armbruster static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
484b681072dSKevin Wolf                                    Error **errp)
485666daa68SMarkus Armbruster {
486666daa68SMarkus Armbruster     const char *buf;
487666daa68SMarkus Armbruster     int bdrv_flags = 0;
488666daa68SMarkus Armbruster     int on_read_error, on_write_error;
489362e9299SAlberto Garcia     bool account_invalid, account_failed;
490f87a0e29SAlberto Garcia     bool writethrough, read_only;
49126f54e9aSMarkus Armbruster     BlockBackend *blk;
492a0f1eab1SMarkus Armbruster     BlockDriverState *bs;
493cc0681c4SBenoît Canet     ThrottleConfig cfg;
494666daa68SMarkus Armbruster     int snapshot = 0;
495c546194fSStefan Hajnoczi     Error *error = NULL;
4960006383eSKevin Wolf     QemuOpts *opts;
49740119effSAlberto Garcia     QDict *interval_dict = NULL;
49840119effSAlberto Garcia     QList *interval_list = NULL;
4990006383eSKevin Wolf     const char *id;
500fbf8175eSMax Reitz     BlockdevDetectZeroesOptions detect_zeroes =
501fbf8175eSMax Reitz         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
502fbf8175eSMax Reitz     const char *throttling_group = NULL;
503666daa68SMarkus Armbruster 
504f298d071SKevin Wolf     /* Check common options by copying from bs_opts to opts, all other options
505f298d071SKevin Wolf      * stay in bs_opts for processing by bdrv_open(). */
506f298d071SKevin Wolf     id = qdict_get_try_str(bs_opts, "id");
507c6ecec43SMarkus Armbruster     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, errp);
508c6ecec43SMarkus Armbruster     if (!opts) {
5096376f952SMarkus Armbruster         goto err_no_opts;
5100006383eSKevin Wolf     }
5110006383eSKevin Wolf 
512668f62ecSMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, bs_opts, errp)) {
513ec9c10d2SStefan Hajnoczi         goto early_err;
5140006383eSKevin Wolf     }
5150006383eSKevin Wolf 
5160006383eSKevin Wolf     if (id) {
5170006383eSKevin Wolf         qdict_del(bs_opts, "id");
5180006383eSKevin Wolf     }
5190006383eSKevin Wolf 
520666daa68SMarkus Armbruster     /* extract parameters */
521666daa68SMarkus Armbruster     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
522666daa68SMarkus Armbruster 
523362e9299SAlberto Garcia     account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
524362e9299SAlberto Garcia     account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
525362e9299SAlberto Garcia 
526e4b24b49SKevin Wolf     writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
527e4b24b49SKevin Wolf 
528ff356ee4SAlberto Garcia     id = qemu_opts_id(opts);
529ff356ee4SAlberto Garcia 
53040119effSAlberto Garcia     qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
53140119effSAlberto Garcia     qdict_array_split(interval_dict, &interval_list);
53240119effSAlberto Garcia 
53340119effSAlberto Garcia     if (qdict_size(interval_dict) != 0) {
53440119effSAlberto Garcia         error_setg(errp, "Invalid option stats-intervals.%s",
53540119effSAlberto Garcia                    qdict_first(interval_dict)->key);
53640119effSAlberto Garcia         goto early_err;
53740119effSAlberto Garcia     }
5382be5506fSAlberto Garcia 
539fbf8175eSMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
540fbf8175eSMax Reitz                                     &detect_zeroes, &error);
541fbf8175eSMax Reitz     if (error) {
542fbf8175eSMax Reitz         error_propagate(errp, error);
543ec9c10d2SStefan Hajnoczi         goto early_err;
544a9384affSPaolo Bonzini     }
545666daa68SMarkus Armbruster 
546666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
547c8057f95SPeter Maydell         if (is_help_option(buf)) {
548cdcd4361SMarkus Armbruster             qemu_printf("Supported formats:");
5499ac404c5SAndrey Shinkevich             bdrv_iterate_format(bdrv_format_print, NULL, false);
550cdcd4361SMarkus Armbruster             qemu_printf("\nSupported formats (read-only):");
5519ac404c5SAndrey Shinkevich             bdrv_iterate_format(bdrv_format_print, NULL, true);
552cdcd4361SMarkus Armbruster             qemu_printf("\n");
553ec9c10d2SStefan Hajnoczi             goto early_err;
554666daa68SMarkus Armbruster         }
55574fe54f2SKevin Wolf 
556e4342ce5SMax Reitz         if (qdict_haskey(bs_opts, "driver")) {
557e4342ce5SMax Reitz             error_setg(errp, "Cannot specify both 'driver' and 'format'");
558ec9c10d2SStefan Hajnoczi             goto early_err;
5596db5f5d6SMike Qiu         }
56046f5ac20SEric Blake         qdict_put_str(bs_opts, "driver", buf);
561666daa68SMarkus Armbruster     }
562666daa68SMarkus Armbruster 
56392aa5c6dSPaolo Bonzini     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
564666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
565b681072dSKevin Wolf         on_write_error = parse_block_error_action(buf, 0, &error);
56684d18f06SMarkus Armbruster         if (error) {
567b681072dSKevin Wolf             error_propagate(errp, error);
568ec9c10d2SStefan Hajnoczi             goto early_err;
569666daa68SMarkus Armbruster         }
570666daa68SMarkus Armbruster     }
571666daa68SMarkus Armbruster 
57292aa5c6dSPaolo Bonzini     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
573666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
574b681072dSKevin Wolf         on_read_error = parse_block_error_action(buf, 1, &error);
57584d18f06SMarkus Armbruster         if (error) {
576b681072dSKevin Wolf             error_propagate(errp, error);
577ec9c10d2SStefan Hajnoczi             goto early_err;
578666daa68SMarkus Armbruster         }
579666daa68SMarkus Armbruster     }
580666daa68SMarkus Armbruster 
581666daa68SMarkus Armbruster     if (snapshot) {
58291a097e7SKevin Wolf         bdrv_flags |= BDRV_O_SNAPSHOT;
583666daa68SMarkus Armbruster     }
584666daa68SMarkus Armbruster 
585f87a0e29SAlberto Garcia     read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
586f87a0e29SAlberto Garcia 
5875ec18f8cSMax Reitz     /* init */
58839c4ae94SKevin Wolf     if ((!file || !*file) && !qdict_size(bs_opts)) {
5895ec18f8cSMax Reitz         BlockBackendRootState *blk_rs;
5905ec18f8cSMax Reitz 
591d861ab3aSKevin Wolf         blk = blk_new(qemu_get_aio_context(), 0, BLK_PERM_ALL);
5925ec18f8cSMax Reitz         blk_rs = blk_get_root_state(blk);
5935ec18f8cSMax Reitz         blk_rs->open_flags    = bdrv_flags;
594f87a0e29SAlberto Garcia         blk_rs->read_only     = read_only;
5955ec18f8cSMax Reitz         blk_rs->detect_zeroes = detect_zeroes;
5965ec18f8cSMax Reitz 
597cb3e7f08SMarc-André Lureau         qobject_unref(bs_opts);
5985ec18f8cSMax Reitz     } else {
5995ec18f8cSMax Reitz         if (file && !*file) {
6005ec18f8cSMax Reitz             file = NULL;
6015ec18f8cSMax Reitz         }
6025ec18f8cSMax Reitz 
60391a097e7SKevin Wolf         /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
60491a097e7SKevin Wolf          * with other callers) rather than what we want as the real defaults.
60591a097e7SKevin Wolf          * Apply the defaults here instead. */
60691a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
60791a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
608f87a0e29SAlberto Garcia         qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
609f87a0e29SAlberto Garcia                               read_only ? "on" : "off");
6109384a444SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_AUTO_READ_ONLY, "on");
61172e775c7SKevin Wolf         assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
61291a097e7SKevin Wolf 
61312d5ee3aSKevin Wolf         if (runstate_check(RUN_STATE_INMIGRATE)) {
61412d5ee3aSKevin Wolf             bdrv_flags |= BDRV_O_INACTIVE;
61512d5ee3aSKevin Wolf         }
61612d5ee3aSKevin Wolf 
617efaa7c4eSMax Reitz         blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
618e4342ce5SMax Reitz         if (!blk) {
619e4342ce5SMax Reitz             goto err_no_bs_opts;
620e4342ce5SMax Reitz         }
621e4342ce5SMax Reitz         bs = blk_bs(blk);
6220006383eSKevin Wolf 
623e4342ce5SMax Reitz         bs->detect_zeroes = detect_zeroes;
624e4342ce5SMax Reitz 
6259caa6f3dSPaolo Bonzini         block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
6262be5506fSAlberto Garcia 
62740119effSAlberto Garcia         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
6282be5506fSAlberto Garcia             blk_unref(blk);
6292be5506fSAlberto Garcia             blk = NULL;
6302be5506fSAlberto Garcia             goto err_no_bs_opts;
6312be5506fSAlberto Garcia         }
6322be5506fSAlberto Garcia     }
6335ec18f8cSMax Reitz 
6347ca7f0f6SKevin Wolf     /* disk I/O throttling */
6357ca7f0f6SKevin Wolf     if (throttle_enabled(&cfg)) {
6367ca7f0f6SKevin Wolf         if (!throttling_group) {
637ff356ee4SAlberto Garcia             throttling_group = id;
6387ca7f0f6SKevin Wolf         }
6397ca7f0f6SKevin Wolf         blk_io_limits_enable(blk, throttling_group);
6407ca7f0f6SKevin Wolf         blk_set_io_limits(blk, &cfg);
6417ca7f0f6SKevin Wolf     }
6427ca7f0f6SKevin Wolf 
643e4b24b49SKevin Wolf     blk_set_enable_write_cache(blk, !writethrough);
6445ec18f8cSMax Reitz     blk_set_on_error(blk, on_read_error, on_write_error);
6450006383eSKevin Wolf 
646ff356ee4SAlberto Garcia     if (!monitor_add_blk(blk, id, errp)) {
647efaa7c4eSMax Reitz         blk_unref(blk);
648efaa7c4eSMax Reitz         blk = NULL;
649efaa7c4eSMax Reitz         goto err_no_bs_opts;
650efaa7c4eSMax Reitz     }
651efaa7c4eSMax Reitz 
652e4342ce5SMax Reitz err_no_bs_opts:
6530006383eSKevin Wolf     qemu_opts_del(opts);
654cb3e7f08SMarc-André Lureau     qobject_unref(interval_dict);
655cb3e7f08SMarc-André Lureau     qobject_unref(interval_list);
65618e46a03SMarkus Armbruster     return blk;
657a9ae2bffSMarkus Armbruster 
658ec9c10d2SStefan Hajnoczi early_err:
659ec9c10d2SStefan Hajnoczi     qemu_opts_del(opts);
660cb3e7f08SMarc-André Lureau     qobject_unref(interval_dict);
661cb3e7f08SMarc-André Lureau     qobject_unref(interval_list);
6626376f952SMarkus Armbruster err_no_opts:
663cb3e7f08SMarc-André Lureau     qobject_unref(bs_opts);
664a9ae2bffSMarkus Armbruster     return NULL;
665666daa68SMarkus Armbruster }
666666daa68SMarkus Armbruster 
667bd745e23SMax Reitz /* Takes the ownership of bs_opts */
66889802d5aSMaxim Levitsky BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
669bd745e23SMax Reitz {
670bd745e23SMax Reitz     int bdrv_flags = 0;
671bd745e23SMax Reitz 
672a81d6164SKevin Wolf     /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
673a81d6164SKevin Wolf      * with other callers) rather than what we want as the real defaults.
674a81d6164SKevin Wolf      * Apply the defaults here instead. */
675a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
676a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
677f87a0e29SAlberto Garcia     qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
678a81d6164SKevin Wolf 
67912d5ee3aSKevin Wolf     if (runstate_check(RUN_STATE_INMIGRATE)) {
68012d5ee3aSKevin Wolf         bdrv_flags |= BDRV_O_INACTIVE;
68112d5ee3aSKevin Wolf     }
68212d5ee3aSKevin Wolf 
68374e1ae7cSKevin Wolf     return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
684bd745e23SMax Reitz }
685bd745e23SMax Reitz 
6869c4218e9SMax Reitz void blockdev_close_all_bdrv_states(void)
6879c4218e9SMax Reitz {
6889c4218e9SMax Reitz     BlockDriverState *bs, *next_bs;
6899c4218e9SMax Reitz 
6909c4218e9SMax Reitz     QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
6919c4218e9SMax Reitz         AioContext *ctx = bdrv_get_aio_context(bs);
6929c4218e9SMax Reitz 
6939c4218e9SMax Reitz         aio_context_acquire(ctx);
6949c4218e9SMax Reitz         bdrv_unref(bs);
6959c4218e9SMax Reitz         aio_context_release(ctx);
6969c4218e9SMax Reitz     }
6979c4218e9SMax Reitz }
6989c4218e9SMax Reitz 
699262b4e8fSMax Reitz /* Iterates over the list of monitor-owned BlockDriverStates */
700262b4e8fSMax Reitz BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
701262b4e8fSMax Reitz {
702262b4e8fSMax Reitz     return bs ? QTAILQ_NEXT(bs, monitor_list)
703262b4e8fSMax Reitz               : QTAILQ_FIRST(&monitor_bdrv_states);
704262b4e8fSMax Reitz }
705262b4e8fSMax Reitz 
706c75d7f71SMarkus Armbruster static bool qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
7075abbf0eeSKevin Wolf                             Error **errp)
70857975222SKevin Wolf {
70957975222SKevin Wolf     const char *value;
71057975222SKevin Wolf 
71157975222SKevin Wolf     value = qemu_opt_get(opts, from);
71257975222SKevin Wolf     if (value) {
7135abbf0eeSKevin Wolf         if (qemu_opt_find(opts, to)) {
7145abbf0eeSKevin Wolf             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
7155abbf0eeSKevin Wolf                        "same time", to, from);
716c75d7f71SMarkus Armbruster             return false;
7175abbf0eeSKevin Wolf         }
71820d6cd47SJun Li     }
71920d6cd47SJun Li 
72020d6cd47SJun Li     /* rename all items in opts */
72120d6cd47SJun Li     while ((value = qemu_opt_get(opts, from))) {
722f43e47dbSMarkus Armbruster         qemu_opt_set(opts, to, value, &error_abort);
72357975222SKevin Wolf         qemu_opt_unset(opts, from);
72457975222SKevin Wolf     }
725c75d7f71SMarkus Armbruster     return true;
72657975222SKevin Wolf }
72757975222SKevin Wolf 
72833cb7dc8SKevin Wolf QemuOptsList qemu_legacy_drive_opts = {
72933cb7dc8SKevin Wolf     .name = "drive",
73033cb7dc8SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
73133cb7dc8SKevin Wolf     .desc = {
73233cb7dc8SKevin Wolf         {
73387a899c5SKevin Wolf             .name = "bus",
73487a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
73587a899c5SKevin Wolf             .help = "bus number",
73687a899c5SKevin Wolf         },{
73787a899c5SKevin Wolf             .name = "unit",
73887a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
73987a899c5SKevin Wolf             .help = "unit number (i.e. lun for scsi)",
74087a899c5SKevin Wolf         },{
74187a899c5SKevin Wolf             .name = "index",
74287a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
74387a899c5SKevin Wolf             .help = "index number",
74487a899c5SKevin Wolf         },{
74533cb7dc8SKevin Wolf             .name = "media",
74633cb7dc8SKevin Wolf             .type = QEMU_OPT_STRING,
74733cb7dc8SKevin Wolf             .help = "media type (disk, cdrom)",
748593d464bSKevin Wolf         },{
749593d464bSKevin Wolf             .name = "if",
750593d464bSKevin Wolf             .type = QEMU_OPT_STRING,
751593d464bSKevin Wolf             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
752b41a7338SKevin Wolf         },{
753d095b465SMax Reitz             .name = "file",
754d095b465SMax Reitz             .type = QEMU_OPT_STRING,
755d095b465SMax Reitz             .help = "file name",
75633cb7dc8SKevin Wolf         },
7570ebd24e0SKevin Wolf 
7580ebd24e0SKevin Wolf         /* Options that are passed on, but have special semantics with -drive */
7590ebd24e0SKevin Wolf         {
7604e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
7610ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
7620ebd24e0SKevin Wolf             .help = "open drive file as read-only",
7630ebd24e0SKevin Wolf         },{
764ee13ed1cSKevin Wolf             .name = "rerror",
765ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
766ee13ed1cSKevin Wolf             .help = "read error action",
767ee13ed1cSKevin Wolf         },{
768ee13ed1cSKevin Wolf             .name = "werror",
769ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
770ee13ed1cSKevin Wolf             .help = "write error action",
771ee13ed1cSKevin Wolf         },{
7720ebd24e0SKevin Wolf             .name = "copy-on-read",
7730ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
7740ebd24e0SKevin Wolf             .help = "copy read data from backing file into image file",
7750ebd24e0SKevin Wolf         },
7760ebd24e0SKevin Wolf 
77733cb7dc8SKevin Wolf         { /* end of list */ }
77833cb7dc8SKevin Wolf     },
77933cb7dc8SKevin Wolf };
78033cb7dc8SKevin Wolf 
781c4f26c9fSMarkus Armbruster DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
782c4f26c9fSMarkus Armbruster                      Error **errp)
78357975222SKevin Wolf {
78429c4e2b5SKevin Wolf     const char *value;
78518e46a03SMarkus Armbruster     BlockBackend *blk;
78633cb7dc8SKevin Wolf     DriveInfo *dinfo = NULL;
787f298d071SKevin Wolf     QDict *bs_opts;
78833cb7dc8SKevin Wolf     QemuOpts *legacy_opts;
78933cb7dc8SKevin Wolf     DriveMediaType media = MEDIA_DISK;
790593d464bSKevin Wolf     BlockInterfaceType type;
79187a899c5SKevin Wolf     int max_devs, bus_id, unit_id, index;
792ee13ed1cSKevin Wolf     const char *werror, *rerror;
793a7fdbcf0SFam Zheng     bool read_only = false;
794a7fdbcf0SFam Zheng     bool copy_on_read;
795d095b465SMax Reitz     const char *filename;
796247147fbSKevin Wolf     int i;
79729c4e2b5SKevin Wolf 
79857975222SKevin Wolf     /* Change legacy command line options into QMP ones */
799247147fbSKevin Wolf     static const struct {
800247147fbSKevin Wolf         const char *from;
801247147fbSKevin Wolf         const char *to;
802247147fbSKevin Wolf     } opt_renames[] = {
803247147fbSKevin Wolf         { "iops",           "throttling.iops-total" },
804247147fbSKevin Wolf         { "iops_rd",        "throttling.iops-read" },
805247147fbSKevin Wolf         { "iops_wr",        "throttling.iops-write" },
80657975222SKevin Wolf 
807247147fbSKevin Wolf         { "bps",            "throttling.bps-total" },
808247147fbSKevin Wolf         { "bps_rd",         "throttling.bps-read" },
809247147fbSKevin Wolf         { "bps_wr",         "throttling.bps-write" },
81057975222SKevin Wolf 
811247147fbSKevin Wolf         { "iops_max",       "throttling.iops-total-max" },
812247147fbSKevin Wolf         { "iops_rd_max",    "throttling.iops-read-max" },
813247147fbSKevin Wolf         { "iops_wr_max",    "throttling.iops-write-max" },
8143e9fab69SBenoît Canet 
815247147fbSKevin Wolf         { "bps_max",        "throttling.bps-total-max" },
816247147fbSKevin Wolf         { "bps_rd_max",     "throttling.bps-read-max" },
817247147fbSKevin Wolf         { "bps_wr_max",     "throttling.bps-write-max" },
8183e9fab69SBenoît Canet 
819247147fbSKevin Wolf         { "iops_size",      "throttling.iops-size" },
8202024c1dfSBenoît Canet 
82176f4afb4SAlberto Garcia         { "group",          "throttling.group" },
82276f4afb4SAlberto Garcia 
8234e200cf8SAlberto Garcia         { "readonly",       BDRV_OPT_READ_ONLY },
824247147fbSKevin Wolf     };
825247147fbSKevin Wolf 
826247147fbSKevin Wolf     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
827235e59cfSMarkus Armbruster         if (!qemu_opt_rename(all_opts, opt_renames[i].from,
828668f62ecSMarkus Armbruster                              opt_renames[i].to, errp)) {
8295abbf0eeSKevin Wolf             return NULL;
8305abbf0eeSKevin Wolf         }
831247147fbSKevin Wolf     }
8320f227a94SKevin Wolf 
83329c4e2b5SKevin Wolf     value = qemu_opt_get(all_opts, "cache");
83429c4e2b5SKevin Wolf     if (value) {
83529c4e2b5SKevin Wolf         int flags = 0;
83604feb4a5SKevin Wolf         bool writethrough;
83729c4e2b5SKevin Wolf 
83804feb4a5SKevin Wolf         if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
839c4f26c9fSMarkus Armbruster             error_setg(errp, "invalid cache option");
84029c4e2b5SKevin Wolf             return NULL;
84129c4e2b5SKevin Wolf         }
84229c4e2b5SKevin Wolf 
84329c4e2b5SKevin Wolf         /* Specific options take precedence */
84454861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
84554861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
84604feb4a5SKevin Wolf                               !writethrough, &error_abort);
84729c4e2b5SKevin Wolf         }
84854861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
84954861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
850cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NOCACHE), &error_abort);
85129c4e2b5SKevin Wolf         }
85254861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
85354861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
854cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
85529c4e2b5SKevin Wolf         }
85629c4e2b5SKevin Wolf         qemu_opt_unset(all_opts, "cache");
85729c4e2b5SKevin Wolf     }
85829c4e2b5SKevin Wolf 
859f298d071SKevin Wolf     /* Get a QDict for processing the options */
860f298d071SKevin Wolf     bs_opts = qdict_new();
861f298d071SKevin Wolf     qemu_opts_to_qdict(all_opts, bs_opts);
862f298d071SKevin Wolf 
86387ea75d5SPeter Crosthwaite     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
86487ea75d5SPeter Crosthwaite                                    &error_abort);
865af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(legacy_opts, bs_opts, errp)) {
86633cb7dc8SKevin Wolf         goto fail;
86733cb7dc8SKevin Wolf     }
86833cb7dc8SKevin Wolf 
86933cb7dc8SKevin Wolf     /* Media type */
87033cb7dc8SKevin Wolf     value = qemu_opt_get(legacy_opts, "media");
87133cb7dc8SKevin Wolf     if (value) {
87233cb7dc8SKevin Wolf         if (!strcmp(value, "disk")) {
87333cb7dc8SKevin Wolf             media = MEDIA_DISK;
87433cb7dc8SKevin Wolf         } else if (!strcmp(value, "cdrom")) {
87533cb7dc8SKevin Wolf             media = MEDIA_CDROM;
876a7fdbcf0SFam Zheng             read_only = true;
87733cb7dc8SKevin Wolf         } else {
878c4f26c9fSMarkus Armbruster             error_setg(errp, "'%s' invalid media", value);
87933cb7dc8SKevin Wolf             goto fail;
88033cb7dc8SKevin Wolf         }
88133cb7dc8SKevin Wolf     }
88233cb7dc8SKevin Wolf 
8830ebd24e0SKevin Wolf     /* copy-on-read is disabled with a warning for read-only devices */
8844e200cf8SAlberto Garcia     read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
8850ebd24e0SKevin Wolf     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
8860ebd24e0SKevin Wolf 
8870ebd24e0SKevin Wolf     if (read_only && copy_on_read) {
8883dc6f869SAlistair Francis         warn_report("disabling copy-on-read on read-only drive");
8890ebd24e0SKevin Wolf         copy_on_read = false;
8900ebd24e0SKevin Wolf     }
8910ebd24e0SKevin Wolf 
89246f5ac20SEric Blake     qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
89346f5ac20SEric Blake     qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
8940ebd24e0SKevin Wolf 
895593d464bSKevin Wolf     /* Controller type */
896593d464bSKevin Wolf     value = qemu_opt_get(legacy_opts, "if");
897593d464bSKevin Wolf     if (value) {
898593d464bSKevin Wolf         for (type = 0;
899593d464bSKevin Wolf              type < IF_COUNT && strcmp(value, if_name[type]);
900593d464bSKevin Wolf              type++) {
901593d464bSKevin Wolf         }
902593d464bSKevin Wolf         if (type == IF_COUNT) {
903c4f26c9fSMarkus Armbruster             error_setg(errp, "unsupported bus type '%s'", value);
904593d464bSKevin Wolf             goto fail;
905593d464bSKevin Wolf         }
906593d464bSKevin Wolf     } else {
907593d464bSKevin Wolf         type = block_default_type;
908593d464bSKevin Wolf     }
909593d464bSKevin Wolf 
91087a899c5SKevin Wolf     /* Device address specified by bus/unit or index.
91187a899c5SKevin Wolf      * If none was specified, try to find the first free one. */
91287a899c5SKevin Wolf     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
91387a899c5SKevin Wolf     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
91487a899c5SKevin Wolf     index   = qemu_opt_get_number(legacy_opts, "index", -1);
91587a899c5SKevin Wolf 
91687a899c5SKevin Wolf     max_devs = if_max_devs[type];
91787a899c5SKevin Wolf 
91887a899c5SKevin Wolf     if (index != -1) {
91987a899c5SKevin Wolf         if (bus_id != 0 || unit_id != -1) {
920c4f26c9fSMarkus Armbruster             error_setg(errp, "index cannot be used with bus and unit");
92187a899c5SKevin Wolf             goto fail;
92287a899c5SKevin Wolf         }
92387a899c5SKevin Wolf         bus_id = drive_index_to_bus_id(type, index);
92487a899c5SKevin Wolf         unit_id = drive_index_to_unit_id(type, index);
92587a899c5SKevin Wolf     }
92687a899c5SKevin Wolf 
92787a899c5SKevin Wolf     if (unit_id == -1) {
92887a899c5SKevin Wolf        unit_id = 0;
92987a899c5SKevin Wolf        while (drive_get(type, bus_id, unit_id) != NULL) {
93087a899c5SKevin Wolf            unit_id++;
93187a899c5SKevin Wolf            if (max_devs && unit_id >= max_devs) {
93287a899c5SKevin Wolf                unit_id -= max_devs;
93387a899c5SKevin Wolf                bus_id++;
93487a899c5SKevin Wolf            }
93587a899c5SKevin Wolf        }
93687a899c5SKevin Wolf     }
93787a899c5SKevin Wolf 
93887a899c5SKevin Wolf     if (max_devs && unit_id >= max_devs) {
939c4f26c9fSMarkus Armbruster         error_setg(errp, "unit %d too big (max is %d)", unit_id, max_devs - 1);
94087a899c5SKevin Wolf         goto fail;
94187a899c5SKevin Wolf     }
94287a899c5SKevin Wolf 
94387a899c5SKevin Wolf     if (drive_get(type, bus_id, unit_id) != NULL) {
944c4f26c9fSMarkus Armbruster         error_setg(errp, "drive with bus=%d, unit=%d (index=%d) exists",
94587a899c5SKevin Wolf                    bus_id, unit_id, index);
94687a899c5SKevin Wolf         goto fail;
94787a899c5SKevin Wolf     }
94887a899c5SKevin Wolf 
94987a899c5SKevin Wolf     /* no id supplied -> create one */
95087a899c5SKevin Wolf     if (qemu_opts_id(all_opts) == NULL) {
95187a899c5SKevin Wolf         char *new_id;
95287a899c5SKevin Wolf         const char *mediastr = "";
95387a899c5SKevin Wolf         if (type == IF_IDE || type == IF_SCSI) {
95487a899c5SKevin Wolf             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
95587a899c5SKevin Wolf         }
95687a899c5SKevin Wolf         if (max_devs) {
95787a899c5SKevin Wolf             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
95887a899c5SKevin Wolf                                      mediastr, unit_id);
95987a899c5SKevin Wolf         } else {
96087a899c5SKevin Wolf             new_id = g_strdup_printf("%s%s%i", if_name[type],
96187a899c5SKevin Wolf                                      mediastr, unit_id);
96287a899c5SKevin Wolf         }
96346f5ac20SEric Blake         qdict_put_str(bs_opts, "id", new_id);
96487a899c5SKevin Wolf         g_free(new_id);
96587a899c5SKevin Wolf     }
96687a899c5SKevin Wolf 
967394c7d4dSKevin Wolf     /* Add virtio block device */
968394c7d4dSKevin Wolf     if (type == IF_VIRTIO) {
969394c7d4dSKevin Wolf         QemuOpts *devopts;
97087ea75d5SPeter Crosthwaite         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
97187ea75d5SPeter Crosthwaite                                    &error_abort);
972394c7d4dSKevin Wolf         if (arch_type == QEMU_ARCH_S390X) {
9731f68f1d3SAlexander Graf             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
974394c7d4dSKevin Wolf         } else {
975f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
976394c7d4dSKevin Wolf         }
977f43e47dbSMarkus Armbruster         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
978f43e47dbSMarkus Armbruster                      &error_abort);
979394c7d4dSKevin Wolf     }
980394c7d4dSKevin Wolf 
981d095b465SMax Reitz     filename = qemu_opt_get(legacy_opts, "file");
982d095b465SMax Reitz 
983ee13ed1cSKevin Wolf     /* Check werror/rerror compatibility with if=... */
984ee13ed1cSKevin Wolf     werror = qemu_opt_get(legacy_opts, "werror");
985ee13ed1cSKevin Wolf     if (werror != NULL) {
986ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
987ee13ed1cSKevin Wolf             type != IF_NONE) {
988c4f26c9fSMarkus Armbruster             error_setg(errp, "werror is not supported by this bus type");
989ee13ed1cSKevin Wolf             goto fail;
990ee13ed1cSKevin Wolf         }
99146f5ac20SEric Blake         qdict_put_str(bs_opts, "werror", werror);
992ee13ed1cSKevin Wolf     }
993ee13ed1cSKevin Wolf 
994ee13ed1cSKevin Wolf     rerror = qemu_opt_get(legacy_opts, "rerror");
995ee13ed1cSKevin Wolf     if (rerror != NULL) {
996ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
997ee13ed1cSKevin Wolf             type != IF_NONE) {
998c4f26c9fSMarkus Armbruster             error_setg(errp, "rerror is not supported by this bus type");
999ee13ed1cSKevin Wolf             goto fail;
1000ee13ed1cSKevin Wolf         }
100146f5ac20SEric Blake         qdict_put_str(bs_opts, "rerror", rerror);
1002ee13ed1cSKevin Wolf     }
1003ee13ed1cSKevin Wolf 
10042d246f01SKevin Wolf     /* Actual block device init: Functionality shared with blockdev-add */
1005992861fbSMarkus Armbruster     blk = blockdev_init(filename, bs_opts, errp);
10063cb0e25cSMarkus Armbruster     bs_opts = NULL;
100718e46a03SMarkus Armbruster     if (!blk) {
10082d246f01SKevin Wolf         goto fail;
10092d246f01SKevin Wolf     }
10102d246f01SKevin Wolf 
101126f8b3a8SMarkus Armbruster     /* Create legacy DriveInfo */
101226f8b3a8SMarkus Armbruster     dinfo = g_malloc0(sizeof(*dinfo));
1013f298d071SKevin Wolf     dinfo->opts = all_opts;
10142d246f01SKevin Wolf 
1015ee13ed1cSKevin Wolf     dinfo->type = type;
101687a899c5SKevin Wolf     dinfo->bus = bus_id;
101787a899c5SKevin Wolf     dinfo->unit = unit_id;
1018bcf83158SKevin Wolf 
101926f8b3a8SMarkus Armbruster     blk_set_legacy_dinfo(blk, dinfo);
102026f8b3a8SMarkus Armbruster 
1021e34ef046SKevin Wolf     switch(type) {
1022e34ef046SKevin Wolf     case IF_IDE:
1023e34ef046SKevin Wolf     case IF_SCSI:
1024e34ef046SKevin Wolf     case IF_XEN:
1025e34ef046SKevin Wolf     case IF_NONE:
1026e34ef046SKevin Wolf         dinfo->media_cd = media == MEDIA_CDROM;
1027e34ef046SKevin Wolf         break;
1028e34ef046SKevin Wolf     default:
1029e34ef046SKevin Wolf         break;
1030e34ef046SKevin Wolf     }
1031e34ef046SKevin Wolf 
10322d246f01SKevin Wolf fail:
103333cb7dc8SKevin Wolf     qemu_opts_del(legacy_opts);
1034cb3e7f08SMarc-André Lureau     qobject_unref(bs_opts);
10352d246f01SKevin Wolf     return dinfo;
103657975222SKevin Wolf }
103757975222SKevin Wolf 
1038b6c1bae5SKevin Wolf static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1039b6c1bae5SKevin Wolf {
1040b6c1bae5SKevin Wolf     BlockDriverState *bs;
1041b6c1bae5SKevin Wolf 
1042b6c1bae5SKevin Wolf     bs = bdrv_lookup_bs(name, name, errp);
1043b6c1bae5SKevin Wolf     if (bs == NULL) {
1044b6c1bae5SKevin Wolf         return NULL;
1045b6c1bae5SKevin Wolf     }
1046b6c1bae5SKevin Wolf 
1047b6c1bae5SKevin Wolf     if (!bdrv_is_root_node(bs)) {
1048b6c1bae5SKevin Wolf         error_setg(errp, "Need a root block node");
1049b6c1bae5SKevin Wolf         return NULL;
1050b6c1bae5SKevin Wolf     }
1051b6c1bae5SKevin Wolf 
1052b6c1bae5SKevin Wolf     if (!bdrv_is_inserted(bs)) {
1053b6c1bae5SKevin Wolf         error_setg(errp, "Device has no medium");
1054b6c1bae5SKevin Wolf         return NULL;
1055b6c1bae5SKevin Wolf     }
1056b6c1bae5SKevin Wolf 
1057b6c1bae5SKevin Wolf     return bs;
1058b6c1bae5SKevin Wolf }
1059b6c1bae5SKevin Wolf 
106010f75907SEric Blake static void blockdev_do_action(TransactionAction *action, Error **errp)
10616cc2a415SPaolo Bonzini {
1062c8a83e85SKevin Wolf     TransactionActionList list;
10636cc2a415SPaolo Bonzini 
106410f75907SEric Blake     list.value = action;
10656cc2a415SPaolo Bonzini     list.next = NULL;
106694d16a64SJohn Snow     qmp_transaction(&list, false, NULL, errp);
10676cc2a415SPaolo Bonzini }
10686cc2a415SPaolo Bonzini 
10690901f67eSBenoît Canet void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
10700901f67eSBenoît Canet                                 bool has_node_name, const char *node_name,
10710901f67eSBenoît Canet                                 const char *snapshot_file,
10720901f67eSBenoît Canet                                 bool has_snapshot_node_name,
10730901f67eSBenoît Canet                                 const char *snapshot_node_name,
10746106e249SLuiz Capitulino                                 bool has_format, const char *format,
10750901f67eSBenoît Canet                                 bool has_mode, NewImageMode mode, Error **errp)
1076f8882568SJes Sorensen {
1077a911e6aeSAlberto Garcia     BlockdevSnapshotSync snapshot = {
10780901f67eSBenoît Canet         .has_device = has_device,
10796cc2a415SPaolo Bonzini         .device = (char *) device,
10800901f67eSBenoît Canet         .has_node_name = has_node_name,
10810901f67eSBenoît Canet         .node_name = (char *) node_name,
10826cc2a415SPaolo Bonzini         .snapshot_file = (char *) snapshot_file,
10830901f67eSBenoît Canet         .has_snapshot_node_name = has_snapshot_node_name,
10840901f67eSBenoît Canet         .snapshot_node_name = (char *) snapshot_node_name,
10856cc2a415SPaolo Bonzini         .has_format = has_format,
10866cc2a415SPaolo Bonzini         .format = (char *) format,
10876cc2a415SPaolo Bonzini         .has_mode = has_mode,
10886cc2a415SPaolo Bonzini         .mode = mode,
10896cc2a415SPaolo Bonzini     };
109010f75907SEric Blake     TransactionAction action = {
109110f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
109232bafa8fSEric Blake         .u.blockdev_snapshot_sync.data = &snapshot,
109310f75907SEric Blake     };
109410f75907SEric Blake     blockdev_do_action(&action, errp);
1095f8882568SJes Sorensen }
1096f8882568SJes Sorensen 
109743de7e2dSAlberto Garcia void qmp_blockdev_snapshot(const char *node, const char *overlay,
109843de7e2dSAlberto Garcia                            Error **errp)
109943de7e2dSAlberto Garcia {
110043de7e2dSAlberto Garcia     BlockdevSnapshot snapshot_data = {
110143de7e2dSAlberto Garcia         .node = (char *) node,
110243de7e2dSAlberto Garcia         .overlay = (char *) overlay
110343de7e2dSAlberto Garcia     };
110410f75907SEric Blake     TransactionAction action = {
110510f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
110632bafa8fSEric Blake         .u.blockdev_snapshot.data = &snapshot_data,
110710f75907SEric Blake     };
110810f75907SEric Blake     blockdev_do_action(&action, errp);
110943de7e2dSAlberto Garcia }
111043de7e2dSAlberto Garcia 
1111f323bc9eSWenchao Xia void qmp_blockdev_snapshot_internal_sync(const char *device,
1112f323bc9eSWenchao Xia                                          const char *name,
1113f323bc9eSWenchao Xia                                          Error **errp)
1114f323bc9eSWenchao Xia {
1115f323bc9eSWenchao Xia     BlockdevSnapshotInternal snapshot = {
1116f323bc9eSWenchao Xia         .device = (char *) device,
1117f323bc9eSWenchao Xia         .name = (char *) name
1118f323bc9eSWenchao Xia     };
111910f75907SEric Blake     TransactionAction action = {
112010f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
112132bafa8fSEric Blake         .u.blockdev_snapshot_internal_sync.data = &snapshot,
112210f75907SEric Blake     };
112310f75907SEric Blake     blockdev_do_action(&action, errp);
1124f323bc9eSWenchao Xia }
1125f323bc9eSWenchao Xia 
112644e3e053SWenchao Xia SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
112744e3e053SWenchao Xia                                                          bool has_id,
112844e3e053SWenchao Xia                                                          const char *id,
112944e3e053SWenchao Xia                                                          bool has_name,
113044e3e053SWenchao Xia                                                          const char *name,
113144e3e053SWenchao Xia                                                          Error **errp)
113244e3e053SWenchao Xia {
1133a0e8544cSFam Zheng     BlockDriverState *bs;
11344ef3982aSStefan Hajnoczi     AioContext *aio_context;
113544e3e053SWenchao Xia     QEMUSnapshotInfo sn;
113644e3e053SWenchao Xia     Error *local_err = NULL;
113744e3e053SWenchao Xia     SnapshotInfo *info = NULL;
113844e3e053SWenchao Xia     int ret;
113944e3e053SWenchao Xia 
11402dfb4c03SKevin Wolf     bs = qmp_get_root_bs(device, errp);
11412dfb4c03SKevin Wolf     if (!bs) {
114244e3e053SWenchao Xia         return NULL;
114344e3e053SWenchao Xia     }
11442dfb4c03SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
11455433c24fSMax Reitz     aio_context_acquire(aio_context);
114644e3e053SWenchao Xia 
114744e3e053SWenchao Xia     if (!has_id) {
114844e3e053SWenchao Xia         id = NULL;
114944e3e053SWenchao Xia     }
115044e3e053SWenchao Xia 
115144e3e053SWenchao Xia     if (!has_name) {
115244e3e053SWenchao Xia         name = NULL;
115344e3e053SWenchao Xia     }
115444e3e053SWenchao Xia 
115544e3e053SWenchao Xia     if (!id && !name) {
115644e3e053SWenchao Xia         error_setg(errp, "Name or id must be provided");
11575433c24fSMax Reitz         goto out_aio_context;
115844e3e053SWenchao Xia     }
115944e3e053SWenchao Xia 
11600b928854SStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
11610b928854SStefan Hajnoczi         goto out_aio_context;
11620b928854SStefan Hajnoczi     }
11630b928854SStefan Hajnoczi 
116444e3e053SWenchao Xia     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
116584d18f06SMarkus Armbruster     if (local_err) {
116644e3e053SWenchao Xia         error_propagate(errp, local_err);
11674ef3982aSStefan Hajnoczi         goto out_aio_context;
116844e3e053SWenchao Xia     }
116944e3e053SWenchao Xia     if (!ret) {
117044e3e053SWenchao Xia         error_setg(errp,
117144e3e053SWenchao Xia                    "Snapshot with id '%s' and name '%s' does not exist on "
117244e3e053SWenchao Xia                    "device '%s'",
117344e3e053SWenchao Xia                    STR_OR_NULL(id), STR_OR_NULL(name), device);
11744ef3982aSStefan Hajnoczi         goto out_aio_context;
117544e3e053SWenchao Xia     }
117644e3e053SWenchao Xia 
117744e3e053SWenchao Xia     bdrv_snapshot_delete(bs, id, name, &local_err);
117884d18f06SMarkus Armbruster     if (local_err) {
117944e3e053SWenchao Xia         error_propagate(errp, local_err);
11804ef3982aSStefan Hajnoczi         goto out_aio_context;
118144e3e053SWenchao Xia     }
118244e3e053SWenchao Xia 
11834ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
11844ef3982aSStefan Hajnoczi 
11855839e53bSMarkus Armbruster     info = g_new0(SnapshotInfo, 1);
118644e3e053SWenchao Xia     info->id = g_strdup(sn.id_str);
118744e3e053SWenchao Xia     info->name = g_strdup(sn.name);
118844e3e053SWenchao Xia     info->date_nsec = sn.date_nsec;
118944e3e053SWenchao Xia     info->date_sec = sn.date_sec;
119044e3e053SWenchao Xia     info->vm_state_size = sn.vm_state_size;
119144e3e053SWenchao Xia     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
119244e3e053SWenchao Xia     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
119344e3e053SWenchao Xia 
119444e3e053SWenchao Xia     return info;
11954ef3982aSStefan Hajnoczi 
11964ef3982aSStefan Hajnoczi out_aio_context:
11974ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
11984ef3982aSStefan Hajnoczi     return NULL;
119944e3e053SWenchao Xia }
12008802d1fdSJeff Cody 
1201b756b9ceSStefan Hajnoczi /* New and old BlockDriverState structs for atomic group operations */
1202ba0c86a3SWenchao Xia 
120350f43f0fSJohn Snow typedef struct BlkActionState BlkActionState;
1204ba0c86a3SWenchao Xia 
120550f43f0fSJohn Snow /**
120650f43f0fSJohn Snow  * BlkActionOps:
120750f43f0fSJohn Snow  * Table of operations that define an Action.
120850f43f0fSJohn Snow  *
120950f43f0fSJohn Snow  * @instance_size: Size of state struct, in bytes.
121050f43f0fSJohn Snow  * @prepare: Prepare the work, must NOT be NULL.
121150f43f0fSJohn Snow  * @commit: Commit the changes, can be NULL.
121250f43f0fSJohn Snow  * @abort: Abort the changes on fail, can be NULL.
121350f43f0fSJohn Snow  * @clean: Clean up resources after all transaction actions have called
121450f43f0fSJohn Snow  *         commit() or abort(). Can be NULL.
121550f43f0fSJohn Snow  *
121650f43f0fSJohn Snow  * Only prepare() may fail. In a single transaction, only one of commit() or
121750f43f0fSJohn Snow  * abort() will be called. clean() will always be called if it is present.
1218ba0c86a3SWenchao Xia  */
121950f43f0fSJohn Snow typedef struct BlkActionOps {
122050f43f0fSJohn Snow     size_t instance_size;
122150f43f0fSJohn Snow     void (*prepare)(BlkActionState *common, Error **errp);
122250f43f0fSJohn Snow     void (*commit)(BlkActionState *common);
122350f43f0fSJohn Snow     void (*abort)(BlkActionState *common);
122450f43f0fSJohn Snow     void (*clean)(BlkActionState *common);
122550f43f0fSJohn Snow } BlkActionOps;
122650f43f0fSJohn Snow 
122750f43f0fSJohn Snow /**
122850f43f0fSJohn Snow  * BlkActionState:
122950f43f0fSJohn Snow  * Describes one Action's state within a Transaction.
123050f43f0fSJohn Snow  *
123150f43f0fSJohn Snow  * @action: QAPI-defined enum identifying which Action to perform.
123250f43f0fSJohn Snow  * @ops: Table of ActionOps this Action can perform.
123394d16a64SJohn Snow  * @block_job_txn: Transaction which this action belongs to.
123450f43f0fSJohn Snow  * @entry: List membership for all Actions in this Transaction.
123550f43f0fSJohn Snow  *
123650f43f0fSJohn Snow  * This structure must be arranged as first member in a subclassed type,
123750f43f0fSJohn Snow  * assuming that the compiler will also arrange it to the same offsets as the
123850f43f0fSJohn Snow  * base class.
123950f43f0fSJohn Snow  */
124050f43f0fSJohn Snow struct BlkActionState {
1241c8a83e85SKevin Wolf     TransactionAction *action;
124250f43f0fSJohn Snow     const BlkActionOps *ops;
124362c9e416SKevin Wolf     JobTxn *block_job_txn;
124494d16a64SJohn Snow     TransactionProperties *txn_props;
1245f4de0f8cSJohn Snow     QTAILQ_ENTRY(BlkActionState) entry;
1246ba0c86a3SWenchao Xia };
1247ba0c86a3SWenchao Xia 
1248bbe86010SWenchao Xia /* internal snapshot private data */
1249bbe86010SWenchao Xia typedef struct InternalSnapshotState {
125050f43f0fSJohn Snow     BlkActionState common;
1251bbe86010SWenchao Xia     BlockDriverState *bs;
1252bbe86010SWenchao Xia     QEMUSnapshotInfo sn;
1253507306ccSFam Zheng     bool created;
1254bbe86010SWenchao Xia } InternalSnapshotState;
1255bbe86010SWenchao Xia 
125694d16a64SJohn Snow 
125794d16a64SJohn Snow static int action_check_completion_mode(BlkActionState *s, Error **errp)
125894d16a64SJohn Snow {
125994d16a64SJohn Snow     if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
126094d16a64SJohn Snow         error_setg(errp,
126194d16a64SJohn Snow                    "Action '%s' does not support Transaction property "
126294d16a64SJohn Snow                    "completion-mode = %s",
1263977c736fSMarkus Armbruster                    TransactionActionKind_str(s->action->type),
1264977c736fSMarkus Armbruster                    ActionCompletionMode_str(s->txn_props->completion_mode));
126594d16a64SJohn Snow         return -1;
126694d16a64SJohn Snow     }
126794d16a64SJohn Snow     return 0;
126894d16a64SJohn Snow }
126994d16a64SJohn Snow 
127050f43f0fSJohn Snow static void internal_snapshot_prepare(BlkActionState *common,
1271bbe86010SWenchao Xia                                       Error **errp)
1272bbe86010SWenchao Xia {
1273f70edf99SMarkus Armbruster     Error *local_err = NULL;
1274bbe86010SWenchao Xia     const char *device;
1275bbe86010SWenchao Xia     const char *name;
1276bbe86010SWenchao Xia     BlockDriverState *bs;
1277bbe86010SWenchao Xia     QEMUSnapshotInfo old_sn, *sn;
1278bbe86010SWenchao Xia     bool ret;
1279bbe86010SWenchao Xia     qemu_timeval tv;
1280bbe86010SWenchao Xia     BlockdevSnapshotInternal *internal;
1281bbe86010SWenchao Xia     InternalSnapshotState *state;
1282a36e458cSStefan Hajnoczi     AioContext *aio_context;
1283bbe86010SWenchao Xia     int ret1;
1284bbe86010SWenchao Xia 
12856a8f9661SEric Blake     g_assert(common->action->type ==
1286bbe86010SWenchao Xia              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
128732bafa8fSEric Blake     internal = common->action->u.blockdev_snapshot_internal_sync.data;
1288bbe86010SWenchao Xia     state = DO_UPCAST(InternalSnapshotState, common, common);
1289bbe86010SWenchao Xia 
1290bbe86010SWenchao Xia     /* 1. parse input */
1291bbe86010SWenchao Xia     device = internal->device;
1292bbe86010SWenchao Xia     name = internal->name;
1293bbe86010SWenchao Xia 
1294bbe86010SWenchao Xia     /* 2. check for validation */
129594d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
129694d16a64SJohn Snow         return;
129794d16a64SJohn Snow     }
129894d16a64SJohn Snow 
129975dfd402SKevin Wolf     bs = qmp_get_root_bs(device, errp);
130075dfd402SKevin Wolf     if (!bs) {
1301bbe86010SWenchao Xia         return;
1302bbe86010SWenchao Xia     }
1303bbe86010SWenchao Xia 
1304a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
1305a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
13065d6e96efSStefan Hajnoczi 
1307507306ccSFam Zheng     state->bs = bs;
1308a36e458cSStefan Hajnoczi 
1309a36e458cSStefan Hajnoczi     /* Paired with .clean() */
1310507306ccSFam Zheng     bdrv_drained_begin(bs);
1311507306ccSFam Zheng 
13123dc7ca3cSStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1313a36e458cSStefan Hajnoczi         goto out;
13143dc7ca3cSStefan Hajnoczi     }
13153dc7ca3cSStefan Hajnoczi 
1316bbe86010SWenchao Xia     if (bdrv_is_read_only(bs)) {
131781e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
1318a36e458cSStefan Hajnoczi         goto out;
1319bbe86010SWenchao Xia     }
1320bbe86010SWenchao Xia 
1321bbe86010SWenchao Xia     if (!bdrv_can_snapshot(bs)) {
132281e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by device '%s' "
132381e5f78aSAlberto Garcia                    "does not support internal snapshots",
132481e5f78aSAlberto Garcia                    bs->drv->format_name, device);
1325a36e458cSStefan Hajnoczi         goto out;
1326bbe86010SWenchao Xia     }
1327bbe86010SWenchao Xia 
1328bbe86010SWenchao Xia     if (!strlen(name)) {
1329bbe86010SWenchao Xia         error_setg(errp, "Name is empty");
1330a36e458cSStefan Hajnoczi         goto out;
1331bbe86010SWenchao Xia     }
1332bbe86010SWenchao Xia 
1333bbe86010SWenchao Xia     /* check whether a snapshot with name exist */
1334f70edf99SMarkus Armbruster     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1335f70edf99SMarkus Armbruster                                             &local_err);
1336f70edf99SMarkus Armbruster     if (local_err) {
1337f70edf99SMarkus Armbruster         error_propagate(errp, local_err);
1338a36e458cSStefan Hajnoczi         goto out;
1339bbe86010SWenchao Xia     } else if (ret) {
1340bbe86010SWenchao Xia         error_setg(errp,
1341bbe86010SWenchao Xia                    "Snapshot with name '%s' already exists on device '%s'",
1342bbe86010SWenchao Xia                    name, device);
1343a36e458cSStefan Hajnoczi         goto out;
1344bbe86010SWenchao Xia     }
1345bbe86010SWenchao Xia 
1346bbe86010SWenchao Xia     /* 3. take the snapshot */
1347bbe86010SWenchao Xia     sn = &state->sn;
1348bbe86010SWenchao Xia     pstrcpy(sn->name, sizeof(sn->name), name);
1349bbe86010SWenchao Xia     qemu_gettimeofday(&tv);
1350bbe86010SWenchao Xia     sn->date_sec = tv.tv_sec;
1351bbe86010SWenchao Xia     sn->date_nsec = tv.tv_usec * 1000;
1352bbe86010SWenchao Xia     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1353bbe86010SWenchao Xia 
1354bbe86010SWenchao Xia     ret1 = bdrv_snapshot_create(bs, sn);
1355bbe86010SWenchao Xia     if (ret1 < 0) {
1356bbe86010SWenchao Xia         error_setg_errno(errp, -ret1,
1357bbe86010SWenchao Xia                          "Failed to create snapshot '%s' on device '%s'",
1358bbe86010SWenchao Xia                          name, device);
1359a36e458cSStefan Hajnoczi         goto out;
1360bbe86010SWenchao Xia     }
1361bbe86010SWenchao Xia 
1362bbe86010SWenchao Xia     /* 4. succeed, mark a snapshot is created */
1363507306ccSFam Zheng     state->created = true;
1364a36e458cSStefan Hajnoczi 
1365a36e458cSStefan Hajnoczi out:
1366a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
1367bbe86010SWenchao Xia }
1368bbe86010SWenchao Xia 
136950f43f0fSJohn Snow static void internal_snapshot_abort(BlkActionState *common)
1370bbe86010SWenchao Xia {
1371bbe86010SWenchao Xia     InternalSnapshotState *state =
1372bbe86010SWenchao Xia                              DO_UPCAST(InternalSnapshotState, common, common);
1373bbe86010SWenchao Xia     BlockDriverState *bs = state->bs;
1374bbe86010SWenchao Xia     QEMUSnapshotInfo *sn = &state->sn;
1375a36e458cSStefan Hajnoczi     AioContext *aio_context;
1376bbe86010SWenchao Xia     Error *local_error = NULL;
1377bbe86010SWenchao Xia 
1378507306ccSFam Zheng     if (!state->created) {
1379bbe86010SWenchao Xia         return;
1380bbe86010SWenchao Xia     }
1381bbe86010SWenchao Xia 
1382a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1383a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
1384a36e458cSStefan Hajnoczi 
1385bbe86010SWenchao Xia     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1386c29b77f9SMarkus Armbruster         error_reportf_err(local_error,
1387c29b77f9SMarkus Armbruster                           "Failed to delete snapshot with id '%s' and "
1388c29b77f9SMarkus Armbruster                           "name '%s' on device '%s' in abort: ",
1389c29b77f9SMarkus Armbruster                           sn->id_str, sn->name,
1390c29b77f9SMarkus Armbruster                           bdrv_get_device_name(bs));
1391bbe86010SWenchao Xia     }
1392a36e458cSStefan Hajnoczi 
1393a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
1394bbe86010SWenchao Xia }
1395bbe86010SWenchao Xia 
139650f43f0fSJohn Snow static void internal_snapshot_clean(BlkActionState *common)
13975d6e96efSStefan Hajnoczi {
13985d6e96efSStefan Hajnoczi     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
13995d6e96efSStefan Hajnoczi                                              common, common);
1400a36e458cSStefan Hajnoczi     AioContext *aio_context;
14015d6e96efSStefan Hajnoczi 
1402a36e458cSStefan Hajnoczi     if (!state->bs) {
1403a36e458cSStefan Hajnoczi         return;
1404a36e458cSStefan Hajnoczi     }
1405a36e458cSStefan Hajnoczi 
1406a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1407a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
1408a36e458cSStefan Hajnoczi 
1409507306ccSFam Zheng     bdrv_drained_end(state->bs);
1410a36e458cSStefan Hajnoczi 
1411a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
14125d6e96efSStefan Hajnoczi }
14135d6e96efSStefan Hajnoczi 
1414ba0c86a3SWenchao Xia /* external snapshot private data */
1415ba5d6ab6SStefan Hajnoczi typedef struct ExternalSnapshotState {
141650f43f0fSJohn Snow     BlkActionState common;
14178802d1fdSJeff Cody     BlockDriverState *old_bs;
14188802d1fdSJeff Cody     BlockDriverState *new_bs;
1419067acf28SKevin Wolf     bool overlay_appended;
1420ba5d6ab6SStefan Hajnoczi } ExternalSnapshotState;
14218802d1fdSJeff Cody 
142250f43f0fSJohn Snow static void external_snapshot_prepare(BlkActionState *common,
14239b9877eeSWenchao Xia                                       Error **errp)
14249b9877eeSWenchao Xia {
14255b363937SMax Reitz     int flags = 0;
142643de7e2dSAlberto Garcia     QDict *options = NULL;
14279b9877eeSWenchao Xia     Error *local_err = NULL;
142843de7e2dSAlberto Garcia     /* Device and node name of the image to generate the snapshot from */
1429e2a31e87SWenchao Xia     const char *device;
14300901f67eSBenoît Canet     const char *node_name;
143143de7e2dSAlberto Garcia     /* Reference to the new image (for 'blockdev-snapshot') */
143243de7e2dSAlberto Garcia     const char *snapshot_ref;
143343de7e2dSAlberto Garcia     /* File name of the new image (for 'blockdev-snapshot-sync') */
1434e2a31e87SWenchao Xia     const char *new_image_file;
1435ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1436ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1437c8a83e85SKevin Wolf     TransactionAction *action = common->action;
14382d24b60bSStefan Hajnoczi     AioContext *aio_context;
1439d29d3d1fSKevin Wolf     uint64_t perm, shared;
14409b9877eeSWenchao Xia 
144143de7e2dSAlberto Garcia     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
144243de7e2dSAlberto Garcia      * purpose but a different set of parameters */
144343de7e2dSAlberto Garcia     switch (action->type) {
144443de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
144543de7e2dSAlberto Garcia         {
144632bafa8fSEric Blake             BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
144743de7e2dSAlberto Garcia             device = s->node;
144843de7e2dSAlberto Garcia             node_name = s->node;
144943de7e2dSAlberto Garcia             new_image_file = NULL;
145043de7e2dSAlberto Garcia             snapshot_ref = s->overlay;
1451e2a31e87SWenchao Xia         }
145243de7e2dSAlberto Garcia         break;
145343de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
145443de7e2dSAlberto Garcia         {
145532bafa8fSEric Blake             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
145643de7e2dSAlberto Garcia             device = s->has_device ? s->device : NULL;
145743de7e2dSAlberto Garcia             node_name = s->has_node_name ? s->node_name : NULL;
145843de7e2dSAlberto Garcia             new_image_file = s->snapshot_file;
145943de7e2dSAlberto Garcia             snapshot_ref = NULL;
146043de7e2dSAlberto Garcia         }
146143de7e2dSAlberto Garcia         break;
146243de7e2dSAlberto Garcia     default:
146343de7e2dSAlberto Garcia         g_assert_not_reached();
1464e2a31e87SWenchao Xia     }
1465e2a31e87SWenchao Xia 
1466e2a31e87SWenchao Xia     /* start processing */
146794d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
146894d16a64SJohn Snow         return;
146994d16a64SJohn Snow     }
147094d16a64SJohn Snow 
147143de7e2dSAlberto Garcia     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
147243de7e2dSAlberto Garcia     if (!state->old_bs) {
14739b9877eeSWenchao Xia         return;
14749b9877eeSWenchao Xia     }
14759b9877eeSWenchao Xia 
14762d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
14772d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
14782d24b60bSStefan Hajnoczi 
14792d24b60bSStefan Hajnoczi     /* Paired with .clean() */
1480da763e83SFam Zheng     bdrv_drained_begin(state->old_bs);
14815d6e96efSStefan Hajnoczi 
1482ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_inserted(state->old_bs)) {
1483c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
14842d24b60bSStefan Hajnoczi         goto out;
14859b9877eeSWenchao Xia     }
14869b9877eeSWenchao Xia 
14873718d8abSFam Zheng     if (bdrv_op_is_blocked(state->old_bs,
14883718d8abSFam Zheng                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
14892d24b60bSStefan Hajnoczi         goto out;
14909b9877eeSWenchao Xia     }
14919b9877eeSWenchao Xia 
1492ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_read_only(state->old_bs)) {
1493ba5d6ab6SStefan Hajnoczi         if (bdrv_flush(state->old_bs)) {
1494c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_IO_ERROR);
14952d24b60bSStefan Hajnoczi             goto out;
14969b9877eeSWenchao Xia         }
14979b9877eeSWenchao Xia     }
14989b9877eeSWenchao Xia 
149943de7e2dSAlberto Garcia     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
150032bafa8fSEric Blake         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
150143de7e2dSAlberto Garcia         const char *format = s->has_format ? s->format : "qcow2";
150243de7e2dSAlberto Garcia         enum NewImageMode mode;
150343de7e2dSAlberto Garcia         const char *snapshot_node_name =
150443de7e2dSAlberto Garcia             s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
150543de7e2dSAlberto Garcia 
150643de7e2dSAlberto Garcia         if (node_name && !snapshot_node_name) {
1507a2bb6f8cSMax Reitz             error_setg(errp, "New overlay node name missing");
15082d24b60bSStefan Hajnoczi             goto out;
150943de7e2dSAlberto Garcia         }
151043de7e2dSAlberto Garcia 
151143de7e2dSAlberto Garcia         if (snapshot_node_name &&
151243de7e2dSAlberto Garcia             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1513a2bb6f8cSMax Reitz             error_setg(errp, "New overlay node name already in use");
15142d24b60bSStefan Hajnoczi             goto out;
151543de7e2dSAlberto Garcia         }
151643de7e2dSAlberto Garcia 
1517ba5d6ab6SStefan Hajnoczi         flags = state->old_bs->open_flags;
15182a32c6e8SJohn Snow         flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
15192a32c6e8SJohn Snow         flags |= BDRV_O_NO_BACKING;
15209b9877eeSWenchao Xia 
15219b9877eeSWenchao Xia         /* create new image w/backing file */
152243de7e2dSAlberto Garcia         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
15239b9877eeSWenchao Xia         if (mode != NEW_IMAGE_MODE_EXISTING) {
1524f86b8b58SKevin Wolf             int64_t size = bdrv_getlength(state->old_bs);
1525f86b8b58SKevin Wolf             if (size < 0) {
1526f86b8b58SKevin Wolf                 error_setg_errno(errp, -size, "bdrv_getlength failed");
15272d24b60bSStefan Hajnoczi                 goto out;
1528f86b8b58SKevin Wolf             }
1529f30c66baSMax Reitz             bdrv_refresh_filename(state->old_bs);
15309b9877eeSWenchao Xia             bdrv_img_create(new_image_file, format,
1531ba5d6ab6SStefan Hajnoczi                             state->old_bs->filename,
1532ba5d6ab6SStefan Hajnoczi                             state->old_bs->drv->format_name,
15339217283dSFam Zheng                             NULL, size, flags, false, &local_err);
153484d18f06SMarkus Armbruster             if (local_err) {
15359b9877eeSWenchao Xia                 error_propagate(errp, local_err);
15362d24b60bSStefan Hajnoczi                 goto out;
15379b9877eeSWenchao Xia             }
15389b9877eeSWenchao Xia         }
15399b9877eeSWenchao Xia 
15400901f67eSBenoît Canet         options = qdict_new();
1541d52e1a0eSPeter Maydell         if (snapshot_node_name) {
154246f5ac20SEric Blake             qdict_put_str(options, "node-name", snapshot_node_name);
15430901f67eSBenoît Canet         }
154446f5ac20SEric Blake         qdict_put_str(options, "driver", format);
154543de7e2dSAlberto Garcia     }
154643de7e2dSAlberto Garcia 
15475b363937SMax Reitz     state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
15485b363937SMax Reitz                               errp);
1549f67503e5SMax Reitz     /* We will manually add the backing_hd field to the bs later */
15505b363937SMax Reitz     if (!state->new_bs) {
15512d24b60bSStefan Hajnoczi         goto out;
155243de7e2dSAlberto Garcia     }
155343de7e2dSAlberto Garcia 
1554d29d3d1fSKevin Wolf     /*
1555d29d3d1fSKevin Wolf      * Allow attaching a backing file to an overlay that's already in use only
1556d29d3d1fSKevin Wolf      * if the parents don't assume that they are already seeing a valid image.
1557d29d3d1fSKevin Wolf      * (Specifically, allow it as a mirror target, which is write-only access.)
1558d29d3d1fSKevin Wolf      */
1559d29d3d1fSKevin Wolf     bdrv_get_cumulative_perm(state->new_bs, &perm, &shared);
1560d29d3d1fSKevin Wolf     if (perm & BLK_PERM_CONSISTENT_READ) {
1561a2bb6f8cSMax Reitz         error_setg(errp, "The overlay is already in use");
15622d24b60bSStefan Hajnoczi         goto out;
156343de7e2dSAlberto Garcia     }
156443de7e2dSAlberto Garcia 
15657cc734a9SMax Reitz     if (state->new_bs->drv->is_filter) {
15667cc734a9SMax Reitz         error_setg(errp, "Filters cannot be used as overlays");
15677cc734a9SMax Reitz         goto out;
15687cc734a9SMax Reitz     }
15697cc734a9SMax Reitz 
15707cc734a9SMax Reitz     if (bdrv_cow_child(state->new_bs)) {
1571a2bb6f8cSMax Reitz         error_setg(errp, "The overlay already has a backing image");
15722d24b60bSStefan Hajnoczi         goto out;
157308b24cfeSAlberto Garcia     }
157408b24cfeSAlberto Garcia 
157508b24cfeSAlberto Garcia     if (!state->new_bs->drv->supports_backing) {
1576a2bb6f8cSMax Reitz         error_setg(errp, "The overlay does not support backing images");
15772d24b60bSStefan Hajnoczi         goto out;
1578b2c2832cSKevin Wolf     }
1579b2c2832cSKevin Wolf 
1580b2c2832cSKevin Wolf     /* This removes our old bs and adds the new bs. This is an operation that
1581b2c2832cSKevin Wolf      * can fail, so we need to do it in .prepare; undoing it for abort is
1582b2c2832cSKevin Wolf      * always possible. */
1583b2c2832cSKevin Wolf     bdrv_ref(state->new_bs);
1584b2c2832cSKevin Wolf     bdrv_append(state->new_bs, state->old_bs, &local_err);
1585b2c2832cSKevin Wolf     if (local_err) {
1586b2c2832cSKevin Wolf         error_propagate(errp, local_err);
15872d24b60bSStefan Hajnoczi         goto out;
15889b9877eeSWenchao Xia     }
1589067acf28SKevin Wolf     state->overlay_appended = true;
15902d24b60bSStefan Hajnoczi 
15912d24b60bSStefan Hajnoczi out:
15922d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
15939b9877eeSWenchao Xia }
15949b9877eeSWenchao Xia 
159550f43f0fSJohn Snow static void external_snapshot_commit(BlkActionState *common)
15963b0047e8SWenchao Xia {
1597ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1598ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
15992d24b60bSStefan Hajnoczi     AioContext *aio_context;
16002d24b60bSStefan Hajnoczi 
16012d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
16022d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
1603ba0c86a3SWenchao Xia 
16043b0047e8SWenchao Xia     /* We don't need (or want) to use the transactional
16053b0047e8SWenchao Xia      * bdrv_reopen_multiple() across all the entries at once, because we
16063b0047e8SWenchao Xia      * don't want to abort all of them if one of them fails the reopen */
1607d3faa13eSPaolo Bonzini     if (!atomic_read(&state->old_bs->copy_on_read)) {
16081b57774fSAlberto Garcia         bdrv_reopen_set_read_only(state->old_bs, true, NULL);
16093b0047e8SWenchao Xia     }
16102d24b60bSStefan Hajnoczi 
16112d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
16124c844983SKevin Wolf }
16133b0047e8SWenchao Xia 
161450f43f0fSJohn Snow static void external_snapshot_abort(BlkActionState *common)
161596b86bf7SWenchao Xia {
1616ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1617ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1618ba5d6ab6SStefan Hajnoczi     if (state->new_bs) {
1619067acf28SKevin Wolf         if (state->overlay_appended) {
16202d24b60bSStefan Hajnoczi             AioContext *aio_context;
1621377410f6SSergio Lopez             AioContext *tmp_context;
1622377410f6SSergio Lopez             int ret;
16232d24b60bSStefan Hajnoczi 
16242d24b60bSStefan Hajnoczi             aio_context = bdrv_get_aio_context(state->old_bs);
16252d24b60bSStefan Hajnoczi             aio_context_acquire(aio_context);
16262d24b60bSStefan Hajnoczi 
1627719fc28cSJeff Cody             bdrv_ref(state->old_bs);   /* we can't let bdrv_set_backind_hd()
1628719fc28cSJeff Cody                                           close state->old_bs; we need it */
1629719fc28cSJeff Cody             bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1630377410f6SSergio Lopez 
1631377410f6SSergio Lopez             /*
1632377410f6SSergio Lopez              * The call to bdrv_set_backing_hd() above returns state->old_bs to
1633377410f6SSergio Lopez              * the main AioContext. As we're still going to be using it, return
1634377410f6SSergio Lopez              * it to the AioContext it was before.
1635377410f6SSergio Lopez              */
1636377410f6SSergio Lopez             tmp_context = bdrv_get_aio_context(state->old_bs);
1637377410f6SSergio Lopez             if (aio_context != tmp_context) {
1638377410f6SSergio Lopez                 aio_context_release(aio_context);
1639377410f6SSergio Lopez                 aio_context_acquire(tmp_context);
1640377410f6SSergio Lopez 
1641377410f6SSergio Lopez                 ret = bdrv_try_set_aio_context(state->old_bs,
1642377410f6SSergio Lopez                                                aio_context, NULL);
1643377410f6SSergio Lopez                 assert(ret == 0);
1644377410f6SSergio Lopez 
1645377410f6SSergio Lopez                 aio_context_release(tmp_context);
1646377410f6SSergio Lopez                 aio_context_acquire(aio_context);
1647377410f6SSergio Lopez             }
1648377410f6SSergio Lopez 
16495fe31c25SKevin Wolf             bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1650719fc28cSJeff Cody             bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
16512d24b60bSStefan Hajnoczi 
16522d24b60bSStefan Hajnoczi             aio_context_release(aio_context);
1653b2c2832cSKevin Wolf         }
165496b86bf7SWenchao Xia     }
1655da763e83SFam Zheng }
1656da763e83SFam Zheng 
165750f43f0fSJohn Snow static void external_snapshot_clean(BlkActionState *common)
1658da763e83SFam Zheng {
1659da763e83SFam Zheng     ExternalSnapshotState *state =
1660da763e83SFam Zheng                              DO_UPCAST(ExternalSnapshotState, common, common);
16612d24b60bSStefan Hajnoczi     AioContext *aio_context;
16622d24b60bSStefan Hajnoczi 
16632d24b60bSStefan Hajnoczi     if (!state->old_bs) {
16642d24b60bSStefan Hajnoczi         return;
16652d24b60bSStefan Hajnoczi     }
16662d24b60bSStefan Hajnoczi 
16672d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
16682d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
16692d24b60bSStefan Hajnoczi 
1670da763e83SFam Zheng     bdrv_drained_end(state->old_bs);
1671b2c2832cSKevin Wolf     bdrv_unref(state->new_bs);
16722d24b60bSStefan Hajnoczi 
16732d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
167496b86bf7SWenchao Xia }
167596b86bf7SWenchao Xia 
16763037f364SStefan Hajnoczi typedef struct DriveBackupState {
167750f43f0fSJohn Snow     BlkActionState common;
16783037f364SStefan Hajnoczi     BlockDriverState *bs;
16793037f364SStefan Hajnoczi     BlockJob *job;
16803037f364SStefan Hajnoczi } DriveBackupState;
16813037f364SStefan Hajnoczi 
16822288ccfaSSergio Lopez static BlockJob *do_backup_common(BackupCommon *backup,
16832288ccfaSSergio Lopez                                   BlockDriverState *bs,
16842288ccfaSSergio Lopez                                   BlockDriverState *target_bs,
16852288ccfaSSergio Lopez                                   AioContext *aio_context,
16862288ccfaSSergio Lopez                                   JobTxn *txn, Error **errp);
168778f51fdeSJohn Snow 
168850f43f0fSJohn Snow static void drive_backup_prepare(BlkActionState *common, Error **errp)
16893037f364SStefan Hajnoczi {
16903037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
16913037f364SStefan Hajnoczi     DriveBackup *backup;
16922288ccfaSSergio Lopez     BlockDriverState *bs;
16932288ccfaSSergio Lopez     BlockDriverState *target_bs;
16942288ccfaSSergio Lopez     BlockDriverState *source = NULL;
169566d56054SStefan Hajnoczi     AioContext *aio_context;
16963ea67e08SSergio Lopez     AioContext *old_context;
16972288ccfaSSergio Lopez     QDict *options;
16983037f364SStefan Hajnoczi     Error *local_err = NULL;
16992288ccfaSSergio Lopez     int flags;
17002288ccfaSSergio Lopez     int64_t size;
17012288ccfaSSergio Lopez     bool set_backing_hd = false;
17023ea67e08SSergio Lopez     int ret;
17033037f364SStefan Hajnoczi 
17046a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
170532bafa8fSEric Blake     backup = common->action->u.drive_backup.data;
17063037f364SStefan Hajnoczi 
17072288ccfaSSergio Lopez     if (!backup->has_mode) {
17082288ccfaSSergio Lopez         backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
17092288ccfaSSergio Lopez     }
17102288ccfaSSergio Lopez 
171185c9d133SVladimir Sementsov-Ogievskiy     bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1712b7e4fa22SKevin Wolf     if (!bs) {
17131fdd4b7bSFam Zheng         return;
17141fdd4b7bSFam Zheng     }
17151fdd4b7bSFam Zheng 
17162288ccfaSSergio Lopez     if (!bs->drv) {
17172288ccfaSSergio Lopez         error_setg(errp, "Device has no medium");
17182288ccfaSSergio Lopez         return;
17192288ccfaSSergio Lopez     }
17202288ccfaSSergio Lopez 
172166d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
172266d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
172366d56054SStefan Hajnoczi 
172466d56054SStefan Hajnoczi     /* Paired with .clean() */
1725b7e4fa22SKevin Wolf     bdrv_drained_begin(bs);
172666d56054SStefan Hajnoczi 
17272288ccfaSSergio Lopez     if (!backup->has_format) {
17282288ccfaSSergio Lopez         backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
17292288ccfaSSergio Lopez                          NULL : (char *) bs->drv->format_name;
17302288ccfaSSergio Lopez     }
17315d6e96efSStefan Hajnoczi 
17322288ccfaSSergio Lopez     /* Early check to avoid creating target */
17332288ccfaSSergio Lopez     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
17342288ccfaSSergio Lopez         goto out;
17352288ccfaSSergio Lopez     }
17362288ccfaSSergio Lopez 
17372288ccfaSSergio Lopez     flags = bs->open_flags | BDRV_O_RDWR;
17382288ccfaSSergio Lopez 
17392288ccfaSSergio Lopez     /*
17402288ccfaSSergio Lopez      * See if we have a backing HD we can use to create our new image
17412288ccfaSSergio Lopez      * on top of.
17422288ccfaSSergio Lopez      */
17432288ccfaSSergio Lopez     if (backup->sync == MIRROR_SYNC_MODE_TOP) {
17442288ccfaSSergio Lopez         source = backing_bs(bs);
17452288ccfaSSergio Lopez         if (!source) {
17462288ccfaSSergio Lopez             backup->sync = MIRROR_SYNC_MODE_FULL;
17472288ccfaSSergio Lopez         }
17482288ccfaSSergio Lopez     }
17492288ccfaSSergio Lopez     if (backup->sync == MIRROR_SYNC_MODE_NONE) {
17502288ccfaSSergio Lopez         source = bs;
17512288ccfaSSergio Lopez         flags |= BDRV_O_NO_BACKING;
17522288ccfaSSergio Lopez         set_backing_hd = true;
17532288ccfaSSergio Lopez     }
17542288ccfaSSergio Lopez 
17552288ccfaSSergio Lopez     size = bdrv_getlength(bs);
17562288ccfaSSergio Lopez     if (size < 0) {
17572288ccfaSSergio Lopez         error_setg_errno(errp, -size, "bdrv_getlength failed");
17582288ccfaSSergio Lopez         goto out;
17592288ccfaSSergio Lopez     }
17602288ccfaSSergio Lopez 
17612288ccfaSSergio Lopez     if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
17622288ccfaSSergio Lopez         assert(backup->format);
17632288ccfaSSergio Lopez         if (source) {
17642288ccfaSSergio Lopez             bdrv_refresh_filename(source);
17652288ccfaSSergio Lopez             bdrv_img_create(backup->target, backup->format, source->filename,
17662288ccfaSSergio Lopez                             source->drv->format_name, NULL,
17672288ccfaSSergio Lopez                             size, flags, false, &local_err);
17682288ccfaSSergio Lopez         } else {
17692288ccfaSSergio Lopez             bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
17702288ccfaSSergio Lopez                             size, flags, false, &local_err);
17712288ccfaSSergio Lopez         }
17722288ccfaSSergio Lopez     }
17732288ccfaSSergio Lopez 
177484d18f06SMarkus Armbruster     if (local_err) {
17753037f364SStefan Hajnoczi         error_propagate(errp, local_err);
177666d56054SStefan Hajnoczi         goto out;
17773037f364SStefan Hajnoczi     }
177866d56054SStefan Hajnoczi 
17792288ccfaSSergio Lopez     options = qdict_new();
17802288ccfaSSergio Lopez     qdict_put_str(options, "discard", "unmap");
17812288ccfaSSergio Lopez     qdict_put_str(options, "detect-zeroes", "unmap");
17822288ccfaSSergio Lopez     if (backup->format) {
17832288ccfaSSergio Lopez         qdict_put_str(options, "driver", backup->format);
17842288ccfaSSergio Lopez     }
17852288ccfaSSergio Lopez 
17862288ccfaSSergio Lopez     target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
17872288ccfaSSergio Lopez     if (!target_bs) {
17882288ccfaSSergio Lopez         goto out;
17892288ccfaSSergio Lopez     }
17902288ccfaSSergio Lopez 
17913ea67e08SSergio Lopez     /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
17923ea67e08SSergio Lopez     old_context = bdrv_get_aio_context(target_bs);
17933ea67e08SSergio Lopez     aio_context_release(aio_context);
17943ea67e08SSergio Lopez     aio_context_acquire(old_context);
17953ea67e08SSergio Lopez 
17963ea67e08SSergio Lopez     ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
17973ea67e08SSergio Lopez     if (ret < 0) {
17983ea67e08SSergio Lopez         bdrv_unref(target_bs);
17993ea67e08SSergio Lopez         aio_context_release(old_context);
18003ea67e08SSergio Lopez         return;
18013ea67e08SSergio Lopez     }
18023ea67e08SSergio Lopez 
18033ea67e08SSergio Lopez     aio_context_release(old_context);
18043ea67e08SSergio Lopez     aio_context_acquire(aio_context);
18053ea67e08SSergio Lopez 
18062288ccfaSSergio Lopez     if (set_backing_hd) {
18072288ccfaSSergio Lopez         bdrv_set_backing_hd(target_bs, source, &local_err);
18082288ccfaSSergio Lopez         if (local_err) {
18092288ccfaSSergio Lopez             goto unref;
18102288ccfaSSergio Lopez         }
18112288ccfaSSergio Lopez     }
18122288ccfaSSergio Lopez 
18132288ccfaSSergio Lopez     state->bs = bs;
18142288ccfaSSergio Lopez 
18152288ccfaSSergio Lopez     state->job = do_backup_common(qapi_DriveBackup_base(backup),
18162288ccfaSSergio Lopez                                   bs, target_bs, aio_context,
18172288ccfaSSergio Lopez                                   common->block_job_txn, errp);
18182288ccfaSSergio Lopez 
18192288ccfaSSergio Lopez unref:
18202288ccfaSSergio Lopez     bdrv_unref(target_bs);
182166d56054SStefan Hajnoczi out:
182266d56054SStefan Hajnoczi     aio_context_release(aio_context);
1823111049a4SJohn Snow }
18243037f364SStefan Hajnoczi 
1825111049a4SJohn Snow static void drive_backup_commit(BlkActionState *common)
1826111049a4SJohn Snow {
1827111049a4SJohn Snow     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
182866d56054SStefan Hajnoczi     AioContext *aio_context;
182966d56054SStefan Hajnoczi 
183066d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
183166d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
183266d56054SStefan Hajnoczi 
1833111049a4SJohn Snow     assert(state->job);
1834da01ff7fSKevin Wolf     job_start(&state->job->job);
183566d56054SStefan Hajnoczi 
183666d56054SStefan Hajnoczi     aio_context_release(aio_context);
18373037f364SStefan Hajnoczi }
18383037f364SStefan Hajnoczi 
183950f43f0fSJohn Snow static void drive_backup_abort(BlkActionState *common)
18403037f364SStefan Hajnoczi {
18413037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
18423037f364SStefan Hajnoczi 
1843111049a4SJohn Snow     if (state->job) {
184466d56054SStefan Hajnoczi         AioContext *aio_context;
184566d56054SStefan Hajnoczi 
184666d56054SStefan Hajnoczi         aio_context = bdrv_get_aio_context(state->bs);
184766d56054SStefan Hajnoczi         aio_context_acquire(aio_context);
184866d56054SStefan Hajnoczi 
18493d70ff53SKevin Wolf         job_cancel_sync(&state->job->job);
185066d56054SStefan Hajnoczi 
185166d56054SStefan Hajnoczi         aio_context_release(aio_context);
18523037f364SStefan Hajnoczi     }
18533037f364SStefan Hajnoczi }
18543037f364SStefan Hajnoczi 
185550f43f0fSJohn Snow static void drive_backup_clean(BlkActionState *common)
18565d6e96efSStefan Hajnoczi {
18575d6e96efSStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
185866d56054SStefan Hajnoczi     AioContext *aio_context;
18595d6e96efSStefan Hajnoczi 
186066d56054SStefan Hajnoczi     if (!state->bs) {
186166d56054SStefan Hajnoczi         return;
18625d6e96efSStefan Hajnoczi     }
186366d56054SStefan Hajnoczi 
186466d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
186566d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
186666d56054SStefan Hajnoczi 
186766d56054SStefan Hajnoczi     bdrv_drained_end(state->bs);
186866d56054SStefan Hajnoczi 
186966d56054SStefan Hajnoczi     aio_context_release(aio_context);
18705d6e96efSStefan Hajnoczi }
18715d6e96efSStefan Hajnoczi 
1872bd8baecdSFam Zheng typedef struct BlockdevBackupState {
187350f43f0fSJohn Snow     BlkActionState common;
1874bd8baecdSFam Zheng     BlockDriverState *bs;
1875bd8baecdSFam Zheng     BlockJob *job;
1876bd8baecdSFam Zheng } BlockdevBackupState;
1877bd8baecdSFam Zheng 
187850f43f0fSJohn Snow static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1879bd8baecdSFam Zheng {
1880bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1881bd8baecdSFam Zheng     BlockdevBackup *backup;
18825b7bfe51SSergio Lopez     BlockDriverState *bs;
18835b7bfe51SSergio Lopez     BlockDriverState *target_bs;
1884edd5adeeSStefan Hajnoczi     AioContext *aio_context;
18853ea67e08SSergio Lopez     AioContext *old_context;
18863ea67e08SSergio Lopez     int ret;
1887bd8baecdSFam Zheng 
18886a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
188932bafa8fSEric Blake     backup = common->action->u.blockdev_backup.data;
1890bd8baecdSFam Zheng 
1891930fe17fSVladimir Sementsov-Ogievskiy     bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1892cef34eebSKevin Wolf     if (!bs) {
1893ff52bf36SFam Zheng         return;
1894ff52bf36SFam Zheng     }
1895ff52bf36SFam Zheng 
18965b7bfe51SSergio Lopez     target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
18975b7bfe51SSergio Lopez     if (!target_bs) {
1898bd8baecdSFam Zheng         return;
1899bd8baecdSFam Zheng     }
1900bd8baecdSFam Zheng 
19013ea67e08SSergio Lopez     /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
1902edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
19033ea67e08SSergio Lopez     old_context = bdrv_get_aio_context(target_bs);
19043ea67e08SSergio Lopez     aio_context_acquire(old_context);
19053ea67e08SSergio Lopez 
19063ea67e08SSergio Lopez     ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
19073ea67e08SSergio Lopez     if (ret < 0) {
19083ea67e08SSergio Lopez         aio_context_release(old_context);
19093ea67e08SSergio Lopez         return;
19103ea67e08SSergio Lopez     }
19113ea67e08SSergio Lopez 
19123ea67e08SSergio Lopez     aio_context_release(old_context);
1913edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1914cef34eebSKevin Wolf     state->bs = bs;
1915edd5adeeSStefan Hajnoczi 
1916edd5adeeSStefan Hajnoczi     /* Paired with .clean() */
1917ff52bf36SFam Zheng     bdrv_drained_begin(state->bs);
1918bd8baecdSFam Zheng 
19195b7bfe51SSergio Lopez     state->job = do_backup_common(qapi_BlockdevBackup_base(backup),
19205b7bfe51SSergio Lopez                                   bs, target_bs, aio_context,
19215b7bfe51SSergio Lopez                                   common->block_job_txn, errp);
1922edd5adeeSStefan Hajnoczi 
1923edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1924111049a4SJohn Snow }
1925bd8baecdSFam Zheng 
1926111049a4SJohn Snow static void blockdev_backup_commit(BlkActionState *common)
1927111049a4SJohn Snow {
1928111049a4SJohn Snow     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1929edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1930edd5adeeSStefan Hajnoczi 
1931edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1932edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1933edd5adeeSStefan Hajnoczi 
1934111049a4SJohn Snow     assert(state->job);
1935da01ff7fSKevin Wolf     job_start(&state->job->job);
1936edd5adeeSStefan Hajnoczi 
1937edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1938bd8baecdSFam Zheng }
1939bd8baecdSFam Zheng 
194050f43f0fSJohn Snow static void blockdev_backup_abort(BlkActionState *common)
1941bd8baecdSFam Zheng {
1942bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1943bd8baecdSFam Zheng 
1944111049a4SJohn Snow     if (state->job) {
1945edd5adeeSStefan Hajnoczi         AioContext *aio_context;
1946edd5adeeSStefan Hajnoczi 
1947edd5adeeSStefan Hajnoczi         aio_context = bdrv_get_aio_context(state->bs);
1948edd5adeeSStefan Hajnoczi         aio_context_acquire(aio_context);
1949edd5adeeSStefan Hajnoczi 
19503d70ff53SKevin Wolf         job_cancel_sync(&state->job->job);
1951edd5adeeSStefan Hajnoczi 
1952edd5adeeSStefan Hajnoczi         aio_context_release(aio_context);
1953bd8baecdSFam Zheng     }
1954bd8baecdSFam Zheng }
1955bd8baecdSFam Zheng 
195650f43f0fSJohn Snow static void blockdev_backup_clean(BlkActionState *common)
1957bd8baecdSFam Zheng {
1958bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1959edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1960bd8baecdSFam Zheng 
1961edd5adeeSStefan Hajnoczi     if (!state->bs) {
1962edd5adeeSStefan Hajnoczi         return;
1963bd8baecdSFam Zheng     }
1964edd5adeeSStefan Hajnoczi 
1965edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1966edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1967edd5adeeSStefan Hajnoczi 
1968edd5adeeSStefan Hajnoczi     bdrv_drained_end(state->bs);
1969edd5adeeSStefan Hajnoczi 
1970edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1971bd8baecdSFam Zheng }
1972bd8baecdSFam Zheng 
1973df9a681dSFam Zheng typedef struct BlockDirtyBitmapState {
197450f43f0fSJohn Snow     BlkActionState common;
1975df9a681dSFam Zheng     BdrvDirtyBitmap *bitmap;
1976df9a681dSFam Zheng     BlockDriverState *bs;
1977df9a681dSFam Zheng     HBitmap *backup;
1978df9a681dSFam Zheng     bool prepared;
1979c6490447SVladimir Sementsov-Ogievskiy     bool was_enabled;
1980df9a681dSFam Zheng } BlockDirtyBitmapState;
1981df9a681dSFam Zheng 
198250f43f0fSJohn Snow static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1983df9a681dSFam Zheng                                            Error **errp)
1984df9a681dSFam Zheng {
1985df9a681dSFam Zheng     Error *local_err = NULL;
1986df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
1987df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1988df9a681dSFam Zheng                                              common, common);
1989df9a681dSFam Zheng 
199094d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
199194d16a64SJohn Snow         return;
199294d16a64SJohn Snow     }
199394d16a64SJohn Snow 
199432bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
1995df9a681dSFam Zheng     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1996df9a681dSFam Zheng     qmp_block_dirty_bitmap_add(action->node, action->name,
1997df9a681dSFam Zheng                                action->has_granularity, action->granularity,
1998fd5ae4ccSVladimir Sementsov-Ogievskiy                                action->has_persistent, action->persistent,
19990e2b7f09SJohn Snow                                action->has_disabled, action->disabled,
2000df9a681dSFam Zheng                                &local_err);
2001df9a681dSFam Zheng 
2002df9a681dSFam Zheng     if (!local_err) {
2003df9a681dSFam Zheng         state->prepared = true;
2004df9a681dSFam Zheng     } else {
2005df9a681dSFam Zheng         error_propagate(errp, local_err);
2006df9a681dSFam Zheng     }
2007df9a681dSFam Zheng }
2008df9a681dSFam Zheng 
200950f43f0fSJohn Snow static void block_dirty_bitmap_add_abort(BlkActionState *common)
2010df9a681dSFam Zheng {
2011df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
2012df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2013df9a681dSFam Zheng                                              common, common);
2014df9a681dSFam Zheng 
201532bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
2016df9a681dSFam Zheng     /* Should not be able to fail: IF the bitmap was added via .prepare(),
2017df9a681dSFam Zheng      * then the node reference and bitmap name must have been valid.
2018df9a681dSFam Zheng      */
2019df9a681dSFam Zheng     if (state->prepared) {
2020df9a681dSFam Zheng         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2021df9a681dSFam Zheng     }
2022df9a681dSFam Zheng }
2023df9a681dSFam Zheng 
202450f43f0fSJohn Snow static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2025df9a681dSFam Zheng                                              Error **errp)
2026df9a681dSFam Zheng {
2027df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2028df9a681dSFam Zheng                                              common, common);
2029df9a681dSFam Zheng     BlockDirtyBitmap *action;
2030df9a681dSFam Zheng 
203194d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
203294d16a64SJohn Snow         return;
203394d16a64SJohn Snow     }
203494d16a64SJohn Snow 
203532bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_clear.data;
2036df9a681dSFam Zheng     state->bitmap = block_dirty_bitmap_lookup(action->node,
2037df9a681dSFam Zheng                                               action->name,
2038df9a681dSFam Zheng                                               &state->bs,
2039df9a681dSFam Zheng                                               errp);
2040df9a681dSFam Zheng     if (!state->bitmap) {
2041df9a681dSFam Zheng         return;
2042df9a681dSFam Zheng     }
2043df9a681dSFam Zheng 
20443ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_DEFAULT, errp)) {
2045d6883bc9SVladimir Sementsov-Ogievskiy         return;
2046df9a681dSFam Zheng     }
2047df9a681dSFam Zheng 
2048df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2049df9a681dSFam Zheng }
2050df9a681dSFam Zheng 
20515c4cf8b2SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_restore(BlkActionState *common)
2052df9a681dSFam Zheng {
2053df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2054df9a681dSFam Zheng                                              common, common);
2055df9a681dSFam Zheng 
2056184dd9c4SJohn Snow     if (state->backup) {
205756bd6624SVladimir Sementsov-Ogievskiy         bdrv_restore_dirty_bitmap(state->bitmap, state->backup);
2058df9a681dSFam Zheng     }
2059184dd9c4SJohn Snow }
2060df9a681dSFam Zheng 
20615c4cf8b2SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_free_backup(BlkActionState *common)
2062df9a681dSFam Zheng {
2063df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2064df9a681dSFam Zheng                                              common, common);
2065df9a681dSFam Zheng 
2066df9a681dSFam Zheng     hbitmap_free(state->backup);
2067df9a681dSFam Zheng }
2068df9a681dSFam Zheng 
2069c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_enable_prepare(BlkActionState *common,
2070c6490447SVladimir Sementsov-Ogievskiy                                               Error **errp)
2071c6490447SVladimir Sementsov-Ogievskiy {
2072c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmap *action;
2073c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2074c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2075c6490447SVladimir Sementsov-Ogievskiy 
2076c6490447SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
2077c6490447SVladimir Sementsov-Ogievskiy         return;
2078c6490447SVladimir Sementsov-Ogievskiy     }
2079c6490447SVladimir Sementsov-Ogievskiy 
20800e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_enable.data;
2081c6490447SVladimir Sementsov-Ogievskiy     state->bitmap = block_dirty_bitmap_lookup(action->node,
2082c6490447SVladimir Sementsov-Ogievskiy                                               action->name,
2083c6490447SVladimir Sementsov-Ogievskiy                                               NULL,
2084c6490447SVladimir Sementsov-Ogievskiy                                               errp);
2085c6490447SVladimir Sementsov-Ogievskiy     if (!state->bitmap) {
2086c6490447SVladimir Sementsov-Ogievskiy         return;
2087c6490447SVladimir Sementsov-Ogievskiy     }
2088c6490447SVladimir Sementsov-Ogievskiy 
20893ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2090b053bb55SJohn Snow         return;
2091b053bb55SJohn Snow     }
2092b053bb55SJohn Snow 
2093c6490447SVladimir Sementsov-Ogievskiy     state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2094c6490447SVladimir Sementsov-Ogievskiy     bdrv_enable_dirty_bitmap(state->bitmap);
2095c6490447SVladimir Sementsov-Ogievskiy }
2096c6490447SVladimir Sementsov-Ogievskiy 
2097c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_enable_abort(BlkActionState *common)
2098c6490447SVladimir Sementsov-Ogievskiy {
2099c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2100c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2101c6490447SVladimir Sementsov-Ogievskiy 
2102c6490447SVladimir Sementsov-Ogievskiy     if (!state->was_enabled) {
2103c6490447SVladimir Sementsov-Ogievskiy         bdrv_disable_dirty_bitmap(state->bitmap);
2104c6490447SVladimir Sementsov-Ogievskiy     }
2105c6490447SVladimir Sementsov-Ogievskiy }
2106c6490447SVladimir Sementsov-Ogievskiy 
2107c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_disable_prepare(BlkActionState *common,
2108c6490447SVladimir Sementsov-Ogievskiy                                                Error **errp)
2109c6490447SVladimir Sementsov-Ogievskiy {
2110c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmap *action;
2111c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2112c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2113c6490447SVladimir Sementsov-Ogievskiy 
2114c6490447SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
2115c6490447SVladimir Sementsov-Ogievskiy         return;
2116c6490447SVladimir Sementsov-Ogievskiy     }
2117c6490447SVladimir Sementsov-Ogievskiy 
21180e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_disable.data;
2119c6490447SVladimir Sementsov-Ogievskiy     state->bitmap = block_dirty_bitmap_lookup(action->node,
2120c6490447SVladimir Sementsov-Ogievskiy                                               action->name,
2121c6490447SVladimir Sementsov-Ogievskiy                                               NULL,
2122c6490447SVladimir Sementsov-Ogievskiy                                               errp);
2123c6490447SVladimir Sementsov-Ogievskiy     if (!state->bitmap) {
2124c6490447SVladimir Sementsov-Ogievskiy         return;
2125c6490447SVladimir Sementsov-Ogievskiy     }
2126c6490447SVladimir Sementsov-Ogievskiy 
21273ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2128b053bb55SJohn Snow         return;
2129b053bb55SJohn Snow     }
2130b053bb55SJohn Snow 
2131c6490447SVladimir Sementsov-Ogievskiy     state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2132c6490447SVladimir Sementsov-Ogievskiy     bdrv_disable_dirty_bitmap(state->bitmap);
2133c6490447SVladimir Sementsov-Ogievskiy }
2134c6490447SVladimir Sementsov-Ogievskiy 
2135c6490447SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_disable_abort(BlkActionState *common)
2136c6490447SVladimir Sementsov-Ogievskiy {
2137c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2138c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2139c6490447SVladimir Sementsov-Ogievskiy 
2140c6490447SVladimir Sementsov-Ogievskiy     if (state->was_enabled) {
2141c6490447SVladimir Sementsov-Ogievskiy         bdrv_enable_dirty_bitmap(state->bitmap);
2142c6490447SVladimir Sementsov-Ogievskiy     }
2143c6490447SVladimir Sementsov-Ogievskiy }
2144c6490447SVladimir Sementsov-Ogievskiy 
21456fd2e407SVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_merge_prepare(BlkActionState *common,
21466fd2e407SVladimir Sementsov-Ogievskiy                                              Error **errp)
21476fd2e407SVladimir Sementsov-Ogievskiy {
21486fd2e407SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapMerge *action;
21496fd2e407SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
21506fd2e407SVladimir Sementsov-Ogievskiy                                              common, common);
21516fd2e407SVladimir Sementsov-Ogievskiy 
21526fd2e407SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
21536fd2e407SVladimir Sementsov-Ogievskiy         return;
21546fd2e407SVladimir Sementsov-Ogievskiy     }
21556fd2e407SVladimir Sementsov-Ogievskiy 
21560e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_merge.data;
2157360d4e4eSJohn Snow 
2158c6996cf9SEric Blake     state->bitmap = block_dirty_bitmap_merge(action->node, action->target,
2159360d4e4eSJohn Snow                                              action->bitmaps, &state->backup,
21606fd2e407SVladimir Sementsov-Ogievskiy                                              errp);
21616fd2e407SVladimir Sementsov-Ogievskiy }
21626fd2e407SVladimir Sementsov-Ogievskiy 
2163c4e4b0faSJohn Snow static void block_dirty_bitmap_remove_prepare(BlkActionState *common,
2164c4e4b0faSJohn Snow                                               Error **errp)
2165c4e4b0faSJohn Snow {
2166c4e4b0faSJohn Snow     BlockDirtyBitmap *action;
2167c4e4b0faSJohn Snow     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2168c4e4b0faSJohn Snow                                              common, common);
2169c4e4b0faSJohn Snow 
2170c4e4b0faSJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
2171c4e4b0faSJohn Snow         return;
2172c4e4b0faSJohn Snow     }
2173c4e4b0faSJohn Snow 
2174c4e4b0faSJohn Snow     action = common->action->u.block_dirty_bitmap_remove.data;
2175c4e4b0faSJohn Snow 
2176c6996cf9SEric Blake     state->bitmap = block_dirty_bitmap_remove(action->node, action->name,
2177c4e4b0faSJohn Snow                                               false, &state->bs, errp);
2178c4e4b0faSJohn Snow     if (state->bitmap) {
2179c4e4b0faSJohn Snow         bdrv_dirty_bitmap_skip_store(state->bitmap, true);
2180c4e4b0faSJohn Snow         bdrv_dirty_bitmap_set_busy(state->bitmap, true);
2181c4e4b0faSJohn Snow     }
2182c4e4b0faSJohn Snow }
2183c4e4b0faSJohn Snow 
2184c4e4b0faSJohn Snow static void block_dirty_bitmap_remove_abort(BlkActionState *common)
2185c4e4b0faSJohn Snow {
2186c4e4b0faSJohn Snow     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2187c4e4b0faSJohn Snow                                              common, common);
2188c4e4b0faSJohn Snow 
2189c4e4b0faSJohn Snow     if (state->bitmap) {
2190c4e4b0faSJohn Snow         bdrv_dirty_bitmap_skip_store(state->bitmap, false);
2191c4e4b0faSJohn Snow         bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2192c4e4b0faSJohn Snow     }
2193c4e4b0faSJohn Snow }
2194c4e4b0faSJohn Snow 
2195c4e4b0faSJohn Snow static void block_dirty_bitmap_remove_commit(BlkActionState *common)
2196c4e4b0faSJohn Snow {
2197c4e4b0faSJohn Snow     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2198c4e4b0faSJohn Snow                                              common, common);
2199c4e4b0faSJohn Snow 
2200c4e4b0faSJohn Snow     bdrv_dirty_bitmap_set_busy(state->bitmap, false);
22015deb6cbdSVladimir Sementsov-Ogievskiy     bdrv_release_dirty_bitmap(state->bitmap);
2202c4e4b0faSJohn Snow }
2203c4e4b0faSJohn Snow 
220450f43f0fSJohn Snow static void abort_prepare(BlkActionState *common, Error **errp)
220578b18b78SStefan Hajnoczi {
220678b18b78SStefan Hajnoczi     error_setg(errp, "Transaction aborted using Abort action");
220778b18b78SStefan Hajnoczi }
220878b18b78SStefan Hajnoczi 
220950f43f0fSJohn Snow static void abort_commit(BlkActionState *common)
221078b18b78SStefan Hajnoczi {
2211dfc6f865SStefan Weil     g_assert_not_reached(); /* this action never succeeds */
221278b18b78SStefan Hajnoczi }
221378b18b78SStefan Hajnoczi 
221450f43f0fSJohn Snow static const BlkActionOps actions[] = {
221543de7e2dSAlberto Garcia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
221643de7e2dSAlberto Garcia         .instance_size = sizeof(ExternalSnapshotState),
221743de7e2dSAlberto Garcia         .prepare  = external_snapshot_prepare,
221843de7e2dSAlberto Garcia         .commit   = external_snapshot_commit,
221943de7e2dSAlberto Garcia         .abort = external_snapshot_abort,
22204ad6f3dbSAlberto Garcia         .clean = external_snapshot_clean,
222143de7e2dSAlberto Garcia     },
2222c8a83e85SKevin Wolf     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2223ba5d6ab6SStefan Hajnoczi         .instance_size = sizeof(ExternalSnapshotState),
2224ba0c86a3SWenchao Xia         .prepare  = external_snapshot_prepare,
2225ba0c86a3SWenchao Xia         .commit   = external_snapshot_commit,
2226ba0c86a3SWenchao Xia         .abort = external_snapshot_abort,
2227da763e83SFam Zheng         .clean = external_snapshot_clean,
2228ba0c86a3SWenchao Xia     },
22293037f364SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
22303037f364SStefan Hajnoczi         .instance_size = sizeof(DriveBackupState),
22313037f364SStefan Hajnoczi         .prepare = drive_backup_prepare,
2232111049a4SJohn Snow         .commit = drive_backup_commit,
22333037f364SStefan Hajnoczi         .abort = drive_backup_abort,
22345d6e96efSStefan Hajnoczi         .clean = drive_backup_clean,
22353037f364SStefan Hajnoczi     },
2236bd8baecdSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2237bd8baecdSFam Zheng         .instance_size = sizeof(BlockdevBackupState),
2238bd8baecdSFam Zheng         .prepare = blockdev_backup_prepare,
2239111049a4SJohn Snow         .commit = blockdev_backup_commit,
2240bd8baecdSFam Zheng         .abort = blockdev_backup_abort,
2241bd8baecdSFam Zheng         .clean = blockdev_backup_clean,
2242bd8baecdSFam Zheng     },
224378b18b78SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_ABORT] = {
224450f43f0fSJohn Snow         .instance_size = sizeof(BlkActionState),
224578b18b78SStefan Hajnoczi         .prepare = abort_prepare,
224678b18b78SStefan Hajnoczi         .commit = abort_commit,
224778b18b78SStefan Hajnoczi     },
2248bbe86010SWenchao Xia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2249bbe86010SWenchao Xia         .instance_size = sizeof(InternalSnapshotState),
2250bbe86010SWenchao Xia         .prepare  = internal_snapshot_prepare,
2251bbe86010SWenchao Xia         .abort = internal_snapshot_abort,
22525d6e96efSStefan Hajnoczi         .clean = internal_snapshot_clean,
2253bbe86010SWenchao Xia     },
2254df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2255df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2256df9a681dSFam Zheng         .prepare = block_dirty_bitmap_add_prepare,
2257df9a681dSFam Zheng         .abort = block_dirty_bitmap_add_abort,
2258df9a681dSFam Zheng     },
2259df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2260df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2261df9a681dSFam Zheng         .prepare = block_dirty_bitmap_clear_prepare,
22625c4cf8b2SVladimir Sementsov-Ogievskiy         .commit = block_dirty_bitmap_free_backup,
22635c4cf8b2SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_restore,
2264c6490447SVladimir Sementsov-Ogievskiy     },
22650e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ENABLE] = {
2266c6490447SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
2267c6490447SVladimir Sementsov-Ogievskiy         .prepare = block_dirty_bitmap_enable_prepare,
2268c6490447SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_enable_abort,
2269c6490447SVladimir Sementsov-Ogievskiy     },
22700e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_DISABLE] = {
2271c6490447SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
2272c6490447SVladimir Sementsov-Ogievskiy         .prepare = block_dirty_bitmap_disable_prepare,
2273c6490447SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_disable_abort,
227466da04ddSJohn Snow     },
22750e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_MERGE] = {
22766fd2e407SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
22776fd2e407SVladimir Sementsov-Ogievskiy         .prepare = block_dirty_bitmap_merge_prepare,
22786fd2e407SVladimir Sementsov-Ogievskiy         .commit = block_dirty_bitmap_free_backup,
22796fd2e407SVladimir Sementsov-Ogievskiy         .abort = block_dirty_bitmap_restore,
22806fd2e407SVladimir Sementsov-Ogievskiy     },
2281c4e4b0faSJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_REMOVE] = {
2282c4e4b0faSJohn Snow         .instance_size = sizeof(BlockDirtyBitmapState),
2283c4e4b0faSJohn Snow         .prepare = block_dirty_bitmap_remove_prepare,
2284c4e4b0faSJohn Snow         .commit = block_dirty_bitmap_remove_commit,
2285c4e4b0faSJohn Snow         .abort = block_dirty_bitmap_remove_abort,
2286c4e4b0faSJohn Snow     },
228766da04ddSJohn Snow     /* Where are transactions for MIRROR, COMMIT and STREAM?
228866da04ddSJohn Snow      * Although these blockjobs use transaction callbacks like the backup job,
228966da04ddSJohn Snow      * these jobs do not necessarily adhere to transaction semantics.
229066da04ddSJohn Snow      * These jobs may not fully undo all of their actions on abort, nor do they
229166da04ddSJohn Snow      * necessarily work in transactions with more than one job in them.
229266da04ddSJohn Snow      */
2293ba0c86a3SWenchao Xia };
2294ba0c86a3SWenchao Xia 
229594d16a64SJohn Snow /**
229694d16a64SJohn Snow  * Allocate a TransactionProperties structure if necessary, and fill
229794d16a64SJohn Snow  * that structure with desired defaults if they are unset.
229894d16a64SJohn Snow  */
229994d16a64SJohn Snow static TransactionProperties *get_transaction_properties(
230094d16a64SJohn Snow     TransactionProperties *props)
230194d16a64SJohn Snow {
230294d16a64SJohn Snow     if (!props) {
230394d16a64SJohn Snow         props = g_new0(TransactionProperties, 1);
230494d16a64SJohn Snow     }
230594d16a64SJohn Snow 
230694d16a64SJohn Snow     if (!props->has_completion_mode) {
230794d16a64SJohn Snow         props->has_completion_mode = true;
230894d16a64SJohn Snow         props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
230994d16a64SJohn Snow     }
231094d16a64SJohn Snow 
231194d16a64SJohn Snow     return props;
231294d16a64SJohn Snow }
231394d16a64SJohn Snow 
23148802d1fdSJeff Cody /*
2315b756b9ceSStefan Hajnoczi  * 'Atomic' group operations.  The operations are performed as a set, and if
2316b756b9ceSStefan Hajnoczi  * any fail then we roll back all operations in the group.
23178802d1fdSJeff Cody  */
231894d16a64SJohn Snow void qmp_transaction(TransactionActionList *dev_list,
231994d16a64SJohn Snow                      bool has_props,
232094d16a64SJohn Snow                      struct TransactionProperties *props,
232194d16a64SJohn Snow                      Error **errp)
23228802d1fdSJeff Cody {
2323c8a83e85SKevin Wolf     TransactionActionList *dev_entry = dev_list;
232462c9e416SKevin Wolf     JobTxn *block_job_txn = NULL;
232550f43f0fSJohn Snow     BlkActionState *state, *next;
232643e17041SLuiz Capitulino     Error *local_err = NULL;
23278802d1fdSJeff Cody 
2328f4de0f8cSJohn Snow     QTAILQ_HEAD(, BlkActionState) snap_bdrv_states;
2329f4de0f8cSJohn Snow     QTAILQ_INIT(&snap_bdrv_states);
23308802d1fdSJeff Cody 
233194d16a64SJohn Snow     /* Does this transaction get canceled as a group on failure?
233262c9e416SKevin Wolf      * If not, we don't really need to make a JobTxn.
233394d16a64SJohn Snow      */
233494d16a64SJohn Snow     props = get_transaction_properties(props);
233594d16a64SJohn Snow     if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
23367eaa8fb5SKevin Wolf         block_job_txn = job_txn_new();
233794d16a64SJohn Snow     }
233894d16a64SJohn Snow 
2339b756b9ceSStefan Hajnoczi     /* drain all i/o before any operations */
23408802d1fdSJeff Cody     bdrv_drain_all();
23418802d1fdSJeff Cody 
2342b756b9ceSStefan Hajnoczi     /* We don't do anything in this loop that commits us to the operations */
23438802d1fdSJeff Cody     while (NULL != dev_entry) {
2344c8a83e85SKevin Wolf         TransactionAction *dev_info = NULL;
234550f43f0fSJohn Snow         const BlkActionOps *ops;
234652e7c241SPaolo Bonzini 
23478802d1fdSJeff Cody         dev_info = dev_entry->value;
23488802d1fdSJeff Cody         dev_entry = dev_entry->next;
23498802d1fdSJeff Cody 
23506a8f9661SEric Blake         assert(dev_info->type < ARRAY_SIZE(actions));
2351ba0c86a3SWenchao Xia 
23526a8f9661SEric Blake         ops = &actions[dev_info->type];
2353aa3fe714SMax Reitz         assert(ops->instance_size > 0);
2354aa3fe714SMax Reitz 
2355ba5d6ab6SStefan Hajnoczi         state = g_malloc0(ops->instance_size);
2356ba5d6ab6SStefan Hajnoczi         state->ops = ops;
2357ba5d6ab6SStefan Hajnoczi         state->action = dev_info;
235894d16a64SJohn Snow         state->block_job_txn = block_job_txn;
235994d16a64SJohn Snow         state->txn_props = props;
2360f4de0f8cSJohn Snow         QTAILQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
23618802d1fdSJeff Cody 
2362ba5d6ab6SStefan Hajnoczi         state->ops->prepare(state, &local_err);
236384d18f06SMarkus Armbruster         if (local_err) {
23649b9877eeSWenchao Xia             error_propagate(errp, local_err);
23659b9877eeSWenchao Xia             goto delete_and_fail;
23669b9877eeSWenchao Xia         }
236752e7c241SPaolo Bonzini     }
23688802d1fdSJeff Cody 
2369f4de0f8cSJohn Snow     QTAILQ_FOREACH(state, &snap_bdrv_states, entry) {
2370f9ea81e8SStefan Hajnoczi         if (state->ops->commit) {
2371ba5d6ab6SStefan Hajnoczi             state->ops->commit(state);
23728802d1fdSJeff Cody         }
2373f9ea81e8SStefan Hajnoczi     }
23748802d1fdSJeff Cody 
23758802d1fdSJeff Cody     /* success */
23768802d1fdSJeff Cody     goto exit;
23778802d1fdSJeff Cody 
23788802d1fdSJeff Cody delete_and_fail:
2379b756b9ceSStefan Hajnoczi     /* failure, and it is all-or-none; roll back all operations */
2380f4de0f8cSJohn Snow     QTAILQ_FOREACH_REVERSE(state, &snap_bdrv_states, entry) {
2381ba5d6ab6SStefan Hajnoczi         if (state->ops->abort) {
2382ba5d6ab6SStefan Hajnoczi             state->ops->abort(state);
2383ba0c86a3SWenchao Xia         }
23848802d1fdSJeff Cody     }
23858802d1fdSJeff Cody exit:
2386f4de0f8cSJohn Snow     QTAILQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2387ba5d6ab6SStefan Hajnoczi         if (state->ops->clean) {
2388ba5d6ab6SStefan Hajnoczi             state->ops->clean(state);
2389ba0c86a3SWenchao Xia         }
2390ba5d6ab6SStefan Hajnoczi         g_free(state);
23918802d1fdSJeff Cody     }
239294d16a64SJohn Snow     if (!has_props) {
239394d16a64SJohn Snow         qapi_free_TransactionProperties(props);
239494d16a64SJohn Snow     }
23957eaa8fb5SKevin Wolf     job_txn_unref(block_job_txn);
23968802d1fdSJeff Cody }
23978802d1fdSJeff Cody 
239812d3ba82SBenoît Canet void qmp_block_passwd(bool has_device, const char *device,
239912d3ba82SBenoît Canet                       bool has_node_name, const char *node_name,
240012d3ba82SBenoît Canet                       const char *password, Error **errp)
2401666daa68SMarkus Armbruster {
2402c01c214bSDaniel P. Berrange     error_setg(errp,
2403c01c214bSDaniel P. Berrange                "Setting block passwords directly is no longer supported");
2404e3442099SStefan Hajnoczi }
2405e3442099SStefan Hajnoczi 
2406a3b52535SVladimir Sementsov-Ogievskiy BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
2407a3b52535SVladimir Sementsov-Ogievskiy                                                               const char *name,
2408a3b52535SVladimir Sementsov-Ogievskiy                                                               Error **errp)
2409a3b52535SVladimir Sementsov-Ogievskiy {
2410a3b52535SVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
2411a3b52535SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
2412a3b52535SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapSha256 *ret = NULL;
2413a3b52535SVladimir Sementsov-Ogievskiy     char *sha256;
2414a3b52535SVladimir Sementsov-Ogievskiy 
2415a3b52535SVladimir Sementsov-Ogievskiy     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2416a3b52535SVladimir Sementsov-Ogievskiy     if (!bitmap || !bs) {
2417a3b52535SVladimir Sementsov-Ogievskiy         return NULL;
2418a3b52535SVladimir Sementsov-Ogievskiy     }
2419a3b52535SVladimir Sementsov-Ogievskiy 
2420a3b52535SVladimir Sementsov-Ogievskiy     sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
2421a3b52535SVladimir Sementsov-Ogievskiy     if (sha256 == NULL) {
2422a3b52535SVladimir Sementsov-Ogievskiy         return NULL;
2423a3b52535SVladimir Sementsov-Ogievskiy     }
2424a3b52535SVladimir Sementsov-Ogievskiy 
2425a3b52535SVladimir Sementsov-Ogievskiy     ret = g_new(BlockDirtyBitmapSha256, 1);
2426a3b52535SVladimir Sementsov-Ogievskiy     ret->sha256 = sha256;
2427a3b52535SVladimir Sementsov-Ogievskiy 
2428a3b52535SVladimir Sementsov-Ogievskiy     return ret;
2429a3b52535SVladimir Sementsov-Ogievskiy }
2430a3b52535SVladimir Sementsov-Ogievskiy 
24313b1dbd11SBenoît Canet void qmp_block_resize(bool has_device, const char *device,
24323b1dbd11SBenoît Canet                       bool has_node_name, const char *node_name,
24333b1dbd11SBenoît Canet                       int64_t size, Error **errp)
24346d4a2b3aSChristoph Hellwig {
24353b1dbd11SBenoît Canet     Error *local_err = NULL;
24367dad9ee6SKevin Wolf     BlockBackend *blk = NULL;
24376d4a2b3aSChristoph Hellwig     BlockDriverState *bs;
2438927e0e76SStefan Hajnoczi     AioContext *aio_context;
24396d4a2b3aSChristoph Hellwig 
24403b1dbd11SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
24413b1dbd11SBenoît Canet                         has_node_name ? node_name : NULL,
24423b1dbd11SBenoît Canet                         &local_err);
244384d18f06SMarkus Armbruster     if (local_err) {
24443b1dbd11SBenoît Canet         error_propagate(errp, local_err);
24453b1dbd11SBenoît Canet         return;
24463b1dbd11SBenoît Canet     }
24473b1dbd11SBenoît Canet 
2448927e0e76SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
2449927e0e76SStefan Hajnoczi     aio_context_acquire(aio_context);
2450927e0e76SStefan Hajnoczi 
24516d4a2b3aSChristoph Hellwig     if (size < 0) {
2452c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2453927e0e76SStefan Hajnoczi         goto out;
24546d4a2b3aSChristoph Hellwig     }
24556d4a2b3aSChristoph Hellwig 
24569c75e168SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2457c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2458927e0e76SStefan Hajnoczi         goto out;
24599c75e168SJeff Cody     }
24609c75e168SJeff Cody 
2461a3aeeab5SEric Blake     blk = blk_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL, errp);
2462a3aeeab5SEric Blake     if (!blk) {
2463d7086422SKevin Wolf         goto out;
2464d7086422SKevin Wolf     }
24657dad9ee6SKevin Wolf 
2466698bdfa0SJohn Snow     bdrv_drained_begin(bs);
2467a3aeeab5SEric Blake     blk_truncate(blk, size, false, PREALLOC_MODE_OFF, 0, errp);
2468698bdfa0SJohn Snow     bdrv_drained_end(bs);
2469927e0e76SStefan Hajnoczi 
2470927e0e76SStefan Hajnoczi out:
24717dad9ee6SKevin Wolf     blk_unref(blk);
2472927e0e76SStefan Hajnoczi     aio_context_release(aio_context);
24736d4a2b3aSChristoph Hellwig }
247412bd451fSStefan Hajnoczi 
24752323322eSAlberto Garcia void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
247613d8cc51SJeff Cody                       bool has_base, const char *base,
2477312fe09cSAlberto Garcia                       bool has_base_node, const char *base_node,
247813d8cc51SJeff Cody                       bool has_backing_file, const char *backing_file,
247913d8cc51SJeff Cody                       bool has_speed, int64_t speed,
24801d809098SPaolo Bonzini                       bool has_on_error, BlockdevOnError on_error,
2481241ca1abSJohn Snow                       bool has_auto_finalize, bool auto_finalize,
2482241ca1abSJohn Snow                       bool has_auto_dismiss, bool auto_dismiss,
24831d809098SPaolo Bonzini                       Error **errp)
248412bd451fSStefan Hajnoczi {
2485554b6147SAlberto Garcia     BlockDriverState *bs, *iter;
2486c8c3080fSMarcelo Tosatti     BlockDriverState *base_bs = NULL;
2487f3e69bebSStefan Hajnoczi     AioContext *aio_context;
2488fd7f8c65SStefan Hajnoczi     Error *local_err = NULL;
248913d8cc51SJeff Cody     const char *base_name = NULL;
2490cf6320dfSJohn Snow     int job_flags = JOB_DEFAULT;
249112bd451fSStefan Hajnoczi 
24921d809098SPaolo Bonzini     if (!has_on_error) {
24931d809098SPaolo Bonzini         on_error = BLOCKDEV_ON_ERROR_REPORT;
24941d809098SPaolo Bonzini     }
24951d809098SPaolo Bonzini 
2496554b6147SAlberto Garcia     bs = bdrv_lookup_bs(device, device, errp);
2497b6c1bae5SKevin Wolf     if (!bs) {
249812bd451fSStefan Hajnoczi         return;
249912bd451fSStefan Hajnoczi     }
250012bd451fSStefan Hajnoczi 
2501b6c1bae5SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
2502f3e69bebSStefan Hajnoczi     aio_context_acquire(aio_context);
2503f3e69bebSStefan Hajnoczi 
2504312fe09cSAlberto Garcia     if (has_base && has_base_node) {
2505312fe09cSAlberto Garcia         error_setg(errp, "'base' and 'base-node' cannot be specified "
2506312fe09cSAlberto Garcia                    "at the same time");
2507312fe09cSAlberto Garcia         goto out;
2508312fe09cSAlberto Garcia     }
2509312fe09cSAlberto Garcia 
251013d8cc51SJeff Cody     if (has_base) {
2511c8c3080fSMarcelo Tosatti         base_bs = bdrv_find_backing_image(bs, base);
2512c8c3080fSMarcelo Tosatti         if (base_bs == NULL) {
2513c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_BASE_NOT_FOUND, base);
2514f3e69bebSStefan Hajnoczi             goto out;
251512bd451fSStefan Hajnoczi         }
2516f3e69bebSStefan Hajnoczi         assert(bdrv_get_aio_context(base_bs) == aio_context);
251713d8cc51SJeff Cody         base_name = base;
2518c8c3080fSMarcelo Tosatti     }
251912bd451fSStefan Hajnoczi 
2520312fe09cSAlberto Garcia     if (has_base_node) {
2521312fe09cSAlberto Garcia         base_bs = bdrv_lookup_bs(NULL, base_node, errp);
2522312fe09cSAlberto Garcia         if (!base_bs) {
2523312fe09cSAlberto Garcia             goto out;
2524312fe09cSAlberto Garcia         }
2525312fe09cSAlberto Garcia         if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
2526312fe09cSAlberto Garcia             error_setg(errp, "Node '%s' is not a backing image of '%s'",
2527312fe09cSAlberto Garcia                        base_node, device);
2528312fe09cSAlberto Garcia             goto out;
2529312fe09cSAlberto Garcia         }
2530312fe09cSAlberto Garcia         assert(bdrv_get_aio_context(base_bs) == aio_context);
2531f30c66baSMax Reitz         bdrv_refresh_filename(base_bs);
2532312fe09cSAlberto Garcia         base_name = base_bs->filename;
2533312fe09cSAlberto Garcia     }
2534312fe09cSAlberto Garcia 
2535554b6147SAlberto Garcia     /* Check for op blockers in the whole chain between bs and base */
253667acfd21SMax Reitz     for (iter = bs; iter && iter != base_bs;
253767acfd21SMax Reitz          iter = bdrv_filter_or_cow_bs(iter))
253867acfd21SMax Reitz     {
2539554b6147SAlberto Garcia         if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
2540554b6147SAlberto Garcia             goto out;
2541554b6147SAlberto Garcia         }
2542554b6147SAlberto Garcia     }
2543554b6147SAlberto Garcia 
254413d8cc51SJeff Cody     /* if we are streaming the entire chain, the result will have no backing
254513d8cc51SJeff Cody      * file, and specifying one is therefore an error */
254613d8cc51SJeff Cody     if (base_bs == NULL && has_backing_file) {
254713d8cc51SJeff Cody         error_setg(errp, "backing file specified, but streaming the "
254813d8cc51SJeff Cody                          "entire chain");
2549f3e69bebSStefan Hajnoczi         goto out;
255013d8cc51SJeff Cody     }
255113d8cc51SJeff Cody 
255213d8cc51SJeff Cody     /* backing_file string overrides base bs filename */
255313d8cc51SJeff Cody     base_name = has_backing_file ? backing_file : base_name;
255413d8cc51SJeff Cody 
2555241ca1abSJohn Snow     if (has_auto_finalize && !auto_finalize) {
2556241ca1abSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
2557241ca1abSJohn Snow     }
2558241ca1abSJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
2559241ca1abSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
2560241ca1abSJohn Snow     }
2561241ca1abSJohn Snow 
25622323322eSAlberto Garcia     stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
2563cf6320dfSJohn Snow                  job_flags, has_speed ? speed : 0, on_error, &local_err);
256484d18f06SMarkus Armbruster     if (local_err) {
2565fd7f8c65SStefan Hajnoczi         error_propagate(errp, local_err);
2566f3e69bebSStefan Hajnoczi         goto out;
256712bd451fSStefan Hajnoczi     }
256812bd451fSStefan Hajnoczi 
2569b23c580cSVladimir Sementsov-Ogievskiy     trace_qmp_block_stream(bs);
2570f3e69bebSStefan Hajnoczi 
2571f3e69bebSStefan Hajnoczi out:
2572f3e69bebSStefan Hajnoczi     aio_context_release(aio_context);
257312bd451fSStefan Hajnoczi }
25742d47c6e9SStefan Hajnoczi 
2575fd62c609SAlberto Garcia void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
25763c605f40SKevin Wolf                       bool has_base_node, const char *base_node,
25777676e2c5SJeff Cody                       bool has_base, const char *base,
25783c605f40SKevin Wolf                       bool has_top_node, const char *top_node,
25797676e2c5SJeff Cody                       bool has_top, const char *top,
258054e26900SJeff Cody                       bool has_backing_file, const char *backing_file,
2581ed61fc10SJeff Cody                       bool has_speed, int64_t speed,
25828faad1c7SKevin Wolf                       bool has_on_error, BlockdevOnError on_error,
25830db832f4SKevin Wolf                       bool has_filter_node_name, const char *filter_node_name,
258496fbf534SJohn Snow                       bool has_auto_finalize, bool auto_finalize,
258596fbf534SJohn Snow                       bool has_auto_dismiss, bool auto_dismiss,
2586ed61fc10SJeff Cody                       Error **errp)
2587ed61fc10SJeff Cody {
2588ed61fc10SJeff Cody     BlockDriverState *bs;
2589058223a6SAlberto Garcia     BlockDriverState *iter;
2590ed61fc10SJeff Cody     BlockDriverState *base_bs, *top_bs;
25919e85cd5cSStefan Hajnoczi     AioContext *aio_context;
2592ed61fc10SJeff Cody     Error *local_err = NULL;
25935360782dSJohn Snow     int job_flags = JOB_DEFAULT;
2594ed61fc10SJeff Cody 
259554504663SMax Reitz     if (!has_speed) {
259654504663SMax Reitz         speed = 0;
259754504663SMax Reitz     }
25988faad1c7SKevin Wolf     if (!has_on_error) {
25998faad1c7SKevin Wolf         on_error = BLOCKDEV_ON_ERROR_REPORT;
26008faad1c7SKevin Wolf     }
26010db832f4SKevin Wolf     if (!has_filter_node_name) {
26020db832f4SKevin Wolf         filter_node_name = NULL;
26030db832f4SKevin Wolf     }
260496fbf534SJohn Snow     if (has_auto_finalize && !auto_finalize) {
260596fbf534SJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
260696fbf534SJohn Snow     }
260796fbf534SJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
260896fbf534SJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
260996fbf534SJohn Snow     }
261054504663SMax Reitz 
26117676e2c5SJeff Cody     /* Important Note:
26127676e2c5SJeff Cody      *  libvirt relies on the DeviceNotFound error class in order to probe for
26137676e2c5SJeff Cody      *  live commit feature versions; for this to work, we must make sure to
26147676e2c5SJeff Cody      *  perform the device lookup before any generic errors that may occur in a
26157676e2c5SJeff Cody      *  scenario in which all optional arguments are omitted. */
26161d13b167SKevin Wolf     bs = qmp_get_root_bs(device, &local_err);
26171d13b167SKevin Wolf     if (!bs) {
26181d13b167SKevin Wolf         bs = bdrv_lookup_bs(device, device, NULL);
26191d13b167SKevin Wolf         if (!bs) {
26201d13b167SKevin Wolf             error_free(local_err);
262175158ebbSMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
262275158ebbSMarkus Armbruster                       "Device '%s' not found", device);
26231d13b167SKevin Wolf         } else {
26241d13b167SKevin Wolf             error_propagate(errp, local_err);
26251d13b167SKevin Wolf         }
2626ed61fc10SJeff Cody         return;
2627ed61fc10SJeff Cody     }
2628ed61fc10SJeff Cody 
26291d13b167SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
26309e85cd5cSStefan Hajnoczi     aio_context_acquire(aio_context);
26319e85cd5cSStefan Hajnoczi 
2632bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
26339e85cd5cSStefan Hajnoczi         goto out;
2634628ff683SFam Zheng     }
2635628ff683SFam Zheng 
2636ed61fc10SJeff Cody     /* default top_bs is the active layer */
2637ed61fc10SJeff Cody     top_bs = bs;
2638ed61fc10SJeff Cody 
26393c605f40SKevin Wolf     if (has_top_node && has_top) {
26403c605f40SKevin Wolf         error_setg(errp, "'top-node' and 'top' are mutually exclusive");
26413c605f40SKevin Wolf         goto out;
26423c605f40SKevin Wolf     } else if (has_top_node) {
26433c605f40SKevin Wolf         top_bs = bdrv_lookup_bs(NULL, top_node, errp);
26443c605f40SKevin Wolf         if (top_bs == NULL) {
26453c605f40SKevin Wolf             goto out;
26463c605f40SKevin Wolf         }
26473c605f40SKevin Wolf         if (!bdrv_chain_contains(bs, top_bs)) {
26483c605f40SKevin Wolf             error_setg(errp, "'%s' is not in this backing file chain",
26493c605f40SKevin Wolf                        top_node);
26503c605f40SKevin Wolf             goto out;
26513c605f40SKevin Wolf         }
26523c605f40SKevin Wolf     } else if (has_top && top) {
2653f30c66baSMax Reitz         /* This strcmp() is just a shortcut, there is no need to
2654f30c66baSMax Reitz          * refresh @bs's filename.  If it mismatches,
2655f30c66baSMax Reitz          * bdrv_find_backing_image() will do the refresh and may still
2656f30c66baSMax Reitz          * return @bs. */
2657ed61fc10SJeff Cody         if (strcmp(bs->filename, top) != 0) {
2658ed61fc10SJeff Cody             top_bs = bdrv_find_backing_image(bs, top);
2659ed61fc10SJeff Cody         }
2660ed61fc10SJeff Cody     }
2661ed61fc10SJeff Cody 
2662ed61fc10SJeff Cody     if (top_bs == NULL) {
2663ed61fc10SJeff Cody         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
26649e85cd5cSStefan Hajnoczi         goto out;
2665ed61fc10SJeff Cody     }
2666ed61fc10SJeff Cody 
26679e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(top_bs) == aio_context);
26689e85cd5cSStefan Hajnoczi 
26693c605f40SKevin Wolf     if (has_base_node && has_base) {
26703c605f40SKevin Wolf         error_setg(errp, "'base-node' and 'base' are mutually exclusive");
26713c605f40SKevin Wolf         goto out;
26723c605f40SKevin Wolf     } else if (has_base_node) {
26733c605f40SKevin Wolf         base_bs = bdrv_lookup_bs(NULL, base_node, errp);
26743c605f40SKevin Wolf         if (base_bs == NULL) {
26753c605f40SKevin Wolf             goto out;
26763c605f40SKevin Wolf         }
26773c605f40SKevin Wolf         if (!bdrv_chain_contains(top_bs, base_bs)) {
26783c605f40SKevin Wolf             error_setg(errp, "'%s' is not in this backing file chain",
26793c605f40SKevin Wolf                        base_node);
26803c605f40SKevin Wolf             goto out;
26813c605f40SKevin Wolf         }
26823c605f40SKevin Wolf     } else if (has_base && base) {
2683d5208c45SJeff Cody         base_bs = bdrv_find_backing_image(top_bs, base);
2684d5208c45SJeff Cody     } else {
2685d5208c45SJeff Cody         base_bs = bdrv_find_base(top_bs);
2686d5208c45SJeff Cody     }
2687d5208c45SJeff Cody 
2688d5208c45SJeff Cody     if (base_bs == NULL) {
2689c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
26909e85cd5cSStefan Hajnoczi         goto out;
2691d5208c45SJeff Cody     }
2692d5208c45SJeff Cody 
26939e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(base_bs) == aio_context);
26949e85cd5cSStefan Hajnoczi 
2695058223a6SAlberto Garcia     for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
2696058223a6SAlberto Garcia         if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2697bb00021dSFam Zheng             goto out;
2698bb00021dSFam Zheng         }
2699058223a6SAlberto Garcia     }
2700bb00021dSFam Zheng 
27017676e2c5SJeff Cody     /* Do not allow attempts to commit an image into itself */
27027676e2c5SJeff Cody     if (top_bs == base_bs) {
27037676e2c5SJeff Cody         error_setg(errp, "cannot commit an image into itself");
27049e85cd5cSStefan Hajnoczi         goto out;
27057676e2c5SJeff Cody     }
27067676e2c5SJeff Cody 
270720a63d2cSFam Zheng     if (top_bs == bs) {
270854e26900SJeff Cody         if (has_backing_file) {
270954e26900SJeff Cody             error_setg(errp, "'backing-file' specified,"
271054e26900SJeff Cody                              " but 'top' is the active layer");
27119e85cd5cSStefan Hajnoczi             goto out;
271254e26900SJeff Cody         }
271347970dfbSJohn Snow         commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
27145360782dSJohn Snow                             job_flags, speed, on_error,
271578bbd910SFam Zheng                             filter_node_name, NULL, NULL, false, &local_err);
271620a63d2cSFam Zheng     } else {
2717058223a6SAlberto Garcia         BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
2718058223a6SAlberto Garcia         if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2719058223a6SAlberto Garcia             goto out;
2720058223a6SAlberto Garcia         }
27215360782dSJohn Snow         commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, job_flags,
27225360782dSJohn Snow                      speed, on_error, has_backing_file ? backing_file : NULL,
27230db832f4SKevin Wolf                      filter_node_name, &local_err);
272420a63d2cSFam Zheng     }
2725ed61fc10SJeff Cody     if (local_err != NULL) {
2726ed61fc10SJeff Cody         error_propagate(errp, local_err);
27279e85cd5cSStefan Hajnoczi         goto out;
2728ed61fc10SJeff Cody     }
27299e85cd5cSStefan Hajnoczi 
27309e85cd5cSStefan Hajnoczi out:
27319e85cd5cSStefan Hajnoczi     aio_context_release(aio_context);
2732ed61fc10SJeff Cody }
2733ed61fc10SJeff Cody 
27347b0b870bSJohn Snow /* Common QMP interface for drive-backup and blockdev-backup */
27357b0b870bSJohn Snow static BlockJob *do_backup_common(BackupCommon *backup,
27367b0b870bSJohn Snow                                   BlockDriverState *bs,
27377b0b870bSJohn Snow                                   BlockDriverState *target_bs,
27387b0b870bSJohn Snow                                   AioContext *aio_context,
27397b0b870bSJohn Snow                                   JobTxn *txn, Error **errp)
274099a9addfSStefan Hajnoczi {
2741111049a4SJohn Snow     BlockJob *job = NULL;
2742d58d8453SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
27437b0b870bSJohn Snow     int job_flags = JOB_DEFAULT;
274499a9addfSStefan Hajnoczi 
274581206a89SPavel Butsykin     if (!backup->has_speed) {
274681206a89SPavel Butsykin         backup->speed = 0;
274799a9addfSStefan Hajnoczi     }
274881206a89SPavel Butsykin     if (!backup->has_on_source_error) {
274981206a89SPavel Butsykin         backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
275099a9addfSStefan Hajnoczi     }
275181206a89SPavel Butsykin     if (!backup->has_on_target_error) {
275281206a89SPavel Butsykin         backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
275399a9addfSStefan Hajnoczi     }
275481206a89SPavel Butsykin     if (!backup->has_job_id) {
275581206a89SPavel Butsykin         backup->job_id = NULL;
275699a9addfSStefan Hajnoczi     }
2757b40dacdcSJohn Snow     if (!backup->has_auto_finalize) {
2758b40dacdcSJohn Snow         backup->auto_finalize = true;
2759b40dacdcSJohn Snow     }
2760b40dacdcSJohn Snow     if (!backup->has_auto_dismiss) {
2761b40dacdcSJohn Snow         backup->auto_dismiss = true;
2762b40dacdcSJohn Snow     }
276313b9414bSPavel Butsykin     if (!backup->has_compress) {
276413b9414bSPavel Butsykin         backup->compress = false;
276513b9414bSPavel Butsykin     }
276699a9addfSStefan Hajnoczi 
2767a6c9365aSJohn Snow     if ((backup->sync == MIRROR_SYNC_MODE_BITMAP) ||
2768a6c9365aSJohn Snow         (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL)) {
2769a6c9365aSJohn Snow         /* done before desugaring 'incremental' to print the right message */
2770a6c9365aSJohn Snow         if (!backup->has_bitmap) {
2771a6c9365aSJohn Snow             error_setg(errp, "must provide a valid bitmap name for "
2772a6c9365aSJohn Snow                        "'%s' sync mode", MirrorSyncMode_str(backup->sync));
2773a6c9365aSJohn Snow             return NULL;
2774a6c9365aSJohn Snow         }
2775a6c9365aSJohn Snow     }
2776a6c9365aSJohn Snow 
2777c8b56501SJohn Snow     if (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL) {
2778c8b56501SJohn Snow         if (backup->has_bitmap_mode &&
2779c8b56501SJohn Snow             backup->bitmap_mode != BITMAP_SYNC_MODE_ON_SUCCESS) {
2780c8b56501SJohn Snow             error_setg(errp, "Bitmap sync mode must be '%s' "
2781c8b56501SJohn Snow                        "when using sync mode '%s'",
2782c8b56501SJohn Snow                        BitmapSyncMode_str(BITMAP_SYNC_MODE_ON_SUCCESS),
2783c8b56501SJohn Snow                        MirrorSyncMode_str(backup->sync));
2784c8b56501SJohn Snow             return NULL;
2785c8b56501SJohn Snow         }
2786c8b56501SJohn Snow         backup->has_bitmap_mode = true;
2787c8b56501SJohn Snow         backup->sync = MIRROR_SYNC_MODE_BITMAP;
2788c8b56501SJohn Snow         backup->bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
2789c8b56501SJohn Snow     }
2790c8b56501SJohn Snow 
27917b0b870bSJohn Snow     if (backup->has_bitmap) {
27927b0b870bSJohn Snow         bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
27937b0b870bSJohn Snow         if (!bmap) {
27947b0b870bSJohn Snow             error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
27957b0b870bSJohn Snow             return NULL;
27967b0b870bSJohn Snow         }
2797c8b56501SJohn Snow         if (!backup->has_bitmap_mode) {
2798c8b56501SJohn Snow             error_setg(errp, "Bitmap sync mode must be given "
2799c8b56501SJohn Snow                        "when providing a bitmap");
2800c8b56501SJohn Snow             return NULL;
2801c8b56501SJohn Snow         }
2802b30ffbefSJohn Snow         if (bdrv_dirty_bitmap_check(bmap, BDRV_BITMAP_ALLOW_RO, errp)) {
28037b0b870bSJohn Snow             return NULL;
28047b0b870bSJohn Snow         }
28051a2b8b40SJohn Snow 
28061a2b8b40SJohn Snow         /* This does not produce a useful bitmap artifact: */
28071a2b8b40SJohn Snow         if (backup->sync == MIRROR_SYNC_MODE_NONE) {
28081a2b8b40SJohn Snow             error_setg(errp, "sync mode '%s' does not produce meaningful bitmap"
28091a2b8b40SJohn Snow                        " outputs", MirrorSyncMode_str(backup->sync));
28101a2b8b40SJohn Snow             return NULL;
28111a2b8b40SJohn Snow         }
28121a2b8b40SJohn Snow 
28131a2b8b40SJohn Snow         /* If the bitmap isn't used for input or output, this is useless: */
28141a2b8b40SJohn Snow         if (backup->bitmap_mode == BITMAP_SYNC_MODE_NEVER &&
28151a2b8b40SJohn Snow             backup->sync != MIRROR_SYNC_MODE_BITMAP) {
28161a2b8b40SJohn Snow             error_setg(errp, "Bitmap sync mode '%s' has no meaningful effect"
28171a2b8b40SJohn Snow                        " when combined with sync mode '%s'",
28181a2b8b40SJohn Snow                        BitmapSyncMode_str(backup->bitmap_mode),
28191a2b8b40SJohn Snow                        MirrorSyncMode_str(backup->sync));
28201a2b8b40SJohn Snow             return NULL;
28211a2b8b40SJohn Snow         }
28221a2b8b40SJohn Snow     }
28231a2b8b40SJohn Snow 
28241a2b8b40SJohn Snow     if (!backup->has_bitmap && backup->has_bitmap_mode) {
28251a2b8b40SJohn Snow         error_setg(errp, "Cannot specify bitmap sync mode without a bitmap");
28261a2b8b40SJohn Snow         return NULL;
28277b0b870bSJohn Snow     }
28287b0b870bSJohn Snow 
28297b0b870bSJohn Snow     if (!backup->auto_finalize) {
28307b0b870bSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
28317b0b870bSJohn Snow     }
28327b0b870bSJohn Snow     if (!backup->auto_dismiss) {
28337b0b870bSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
28347b0b870bSJohn Snow     }
28357b0b870bSJohn Snow 
28367b0b870bSJohn Snow     job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
2837c8b56501SJohn Snow                             backup->sync, bmap, backup->bitmap_mode,
2838c8b56501SJohn Snow                             backup->compress,
283900e30f05SVladimir Sementsov-Ogievskiy                             backup->filter_node_name,
2840c8b56501SJohn Snow                             backup->on_source_error,
2841c8b56501SJohn Snow                             backup->on_target_error,
28427b0b870bSJohn Snow                             job_flags, NULL, NULL, txn, errp);
28437b0b870bSJohn Snow     return job;
28447b0b870bSJohn Snow }
28457b0b870bSJohn Snow 
28462288ccfaSSergio Lopez void qmp_drive_backup(DriveBackup *backup, Error **errp)
28477b0b870bSJohn Snow {
28482288ccfaSSergio Lopez     TransactionAction action = {
28492288ccfaSSergio Lopez         .type = TRANSACTION_ACTION_KIND_DRIVE_BACKUP,
28502288ccfaSSergio Lopez         .u.drive_backup.data = backup,
28512288ccfaSSergio Lopez     };
28522288ccfaSSergio Lopez     blockdev_do_action(&action, errp);
285378f51fdeSJohn Snow }
285478f51fdeSJohn Snow 
2855facda544SPeter Krempa BlockDeviceInfoList *qmp_query_named_block_nodes(bool has_flat,
2856facda544SPeter Krempa                                                  bool flat,
2857facda544SPeter Krempa                                                  Error **errp)
2858c13163fbSBenoît Canet {
2859facda544SPeter Krempa     bool return_flat = has_flat && flat;
2860facda544SPeter Krempa 
2861facda544SPeter Krempa     return bdrv_named_nodes_list(return_flat, errp);
2862c13163fbSBenoît Canet }
2863c13163fbSBenoît Canet 
28645d3b4e99SVladimir Sementsov-Ogievskiy XDbgBlockGraph *qmp_x_debug_query_block_graph(Error **errp)
28655d3b4e99SVladimir Sementsov-Ogievskiy {
28665d3b4e99SVladimir Sementsov-Ogievskiy     return bdrv_get_xdbg_block_graph(errp);
28675d3b4e99SVladimir Sementsov-Ogievskiy }
28685d3b4e99SVladimir Sementsov-Ogievskiy 
28695b7bfe51SSergio Lopez void qmp_blockdev_backup(BlockdevBackup *backup, Error **errp)
2870c29c1dd3SFam Zheng {
28715b7bfe51SSergio Lopez     TransactionAction action = {
28725b7bfe51SSergio Lopez         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP,
28735b7bfe51SSergio Lopez         .u.blockdev_backup.data = backup,
28745b7bfe51SSergio Lopez     };
28755b7bfe51SSergio Lopez     blockdev_do_action(&action, errp);
287678f51fdeSJohn Snow }
287778f51fdeSJohn Snow 
28784193cdd7SFam Zheng /* Parameter check and block job starting for drive mirroring.
28794193cdd7SFam Zheng  * Caller should hold @device and @target's aio context (must be the same).
28804193cdd7SFam Zheng  **/
288171aa9867SAlberto Garcia static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
28824193cdd7SFam Zheng                                    BlockDriverState *target,
288309158f00SBenoît Canet                                    bool has_replaces, const char *replaces,
2884d9b902dbSPaolo Bonzini                                    enum MirrorSyncMode sync,
2885274fcceeSMax Reitz                                    BlockMirrorBackingMode backing_mode,
2886cdf3bc93SMax Reitz                                    bool zero_target,
2887b952b558SPaolo Bonzini                                    bool has_speed, int64_t speed,
2888eee13dfeSPaolo Bonzini                                    bool has_granularity, uint32_t granularity,
288908e4ed6cSPaolo Bonzini                                    bool has_buf_size, int64_t buf_size,
28904193cdd7SFam Zheng                                    bool has_on_source_error,
28914193cdd7SFam Zheng                                    BlockdevOnError on_source_error,
28924193cdd7SFam Zheng                                    bool has_on_target_error,
28934193cdd7SFam Zheng                                    BlockdevOnError on_target_error,
28940fc9f8eaSFam Zheng                                    bool has_unmap, bool unmap,
28956cdbceb1SKevin Wolf                                    bool has_filter_node_name,
28966cdbceb1SKevin Wolf                                    const char *filter_node_name,
2897481debaaSMax Reitz                                    bool has_copy_mode, MirrorCopyMode copy_mode,
2898a6b58adeSJohn Snow                                    bool has_auto_finalize, bool auto_finalize,
2899a6b58adeSJohn Snow                                    bool has_auto_dismiss, bool auto_dismiss,
2900b952b558SPaolo Bonzini                                    Error **errp)
2901d9b902dbSPaolo Bonzini {
2902*3f072a7fSMax Reitz     BlockDriverState *unfiltered_bs;
2903a1999b33SJohn Snow     int job_flags = JOB_DEFAULT;
2904d9b902dbSPaolo Bonzini 
2905d9b902dbSPaolo Bonzini     if (!has_speed) {
2906d9b902dbSPaolo Bonzini         speed = 0;
2907d9b902dbSPaolo Bonzini     }
2908b952b558SPaolo Bonzini     if (!has_on_source_error) {
2909b952b558SPaolo Bonzini         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2910b952b558SPaolo Bonzini     }
2911b952b558SPaolo Bonzini     if (!has_on_target_error) {
2912b952b558SPaolo Bonzini         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2913b952b558SPaolo Bonzini     }
2914eee13dfeSPaolo Bonzini     if (!has_granularity) {
2915eee13dfeSPaolo Bonzini         granularity = 0;
2916eee13dfeSPaolo Bonzini     }
291708e4ed6cSPaolo Bonzini     if (!has_buf_size) {
291848ac0a4dSWen Congyang         buf_size = 0;
291908e4ed6cSPaolo Bonzini     }
29200fc9f8eaSFam Zheng     if (!has_unmap) {
29210fc9f8eaSFam Zheng         unmap = true;
29220fc9f8eaSFam Zheng     }
29236cdbceb1SKevin Wolf     if (!has_filter_node_name) {
29246cdbceb1SKevin Wolf         filter_node_name = NULL;
29256cdbceb1SKevin Wolf     }
2926481debaaSMax Reitz     if (!has_copy_mode) {
2927481debaaSMax Reitz         copy_mode = MIRROR_COPY_MODE_BACKGROUND;
2928481debaaSMax Reitz     }
2929a6b58adeSJohn Snow     if (has_auto_finalize && !auto_finalize) {
2930a6b58adeSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
2931a6b58adeSJohn Snow     }
2932a6b58adeSJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
2933a6b58adeSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
2934a6b58adeSJohn Snow     }
293508e4ed6cSPaolo Bonzini 
2936eee13dfeSPaolo Bonzini     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2937c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
29383cbbe9fdSStefan Hajnoczi                    "a value in range [512B, 64MB]");
2939eee13dfeSPaolo Bonzini         return;
2940eee13dfeSPaolo Bonzini     }
2941eee13dfeSPaolo Bonzini     if (granularity & (granularity - 1)) {
2942c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2943c6bd8c70SMarkus Armbruster                    "power of 2");
2944eee13dfeSPaolo Bonzini         return;
2945eee13dfeSPaolo Bonzini     }
2946d9b902dbSPaolo Bonzini 
29474193cdd7SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
29484193cdd7SFam Zheng         return;
29494193cdd7SFam Zheng     }
2950e40e5027SFam Zheng     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
2951e40e5027SFam Zheng         return;
2952e40e5027SFam Zheng     }
29534193cdd7SFam Zheng 
2954*3f072a7fSMax Reitz     if (!bdrv_backing_chain_next(bs) && sync == MIRROR_SYNC_MODE_TOP) {
29554193cdd7SFam Zheng         sync = MIRROR_SYNC_MODE_FULL;
29564193cdd7SFam Zheng     }
29574193cdd7SFam Zheng 
2958*3f072a7fSMax Reitz     if (!has_replaces) {
2959*3f072a7fSMax Reitz         /* We want to mirror from @bs, but keep implicit filters on top */
2960*3f072a7fSMax Reitz         unfiltered_bs = bdrv_skip_implicit_filters(bs);
2961*3f072a7fSMax Reitz         if (unfiltered_bs != bs) {
2962*3f072a7fSMax Reitz             replaces = unfiltered_bs->node_name;
2963*3f072a7fSMax Reitz             has_replaces = true;
2964*3f072a7fSMax Reitz         }
2965*3f072a7fSMax Reitz     }
2966*3f072a7fSMax Reitz 
296774ce9e46SMax Reitz     if (has_replaces) {
296874ce9e46SMax Reitz         BlockDriverState *to_replace_bs;
296974ce9e46SMax Reitz         AioContext *replace_aio_context;
297074ce9e46SMax Reitz         int64_t bs_size, replace_size;
297174ce9e46SMax Reitz 
297274ce9e46SMax Reitz         bs_size = bdrv_getlength(bs);
297374ce9e46SMax Reitz         if (bs_size < 0) {
297474ce9e46SMax Reitz             error_setg_errno(errp, -bs_size, "Failed to query device's size");
297574ce9e46SMax Reitz             return;
297674ce9e46SMax Reitz         }
297774ce9e46SMax Reitz 
297874ce9e46SMax Reitz         to_replace_bs = check_to_replace_node(bs, replaces, errp);
297974ce9e46SMax Reitz         if (!to_replace_bs) {
298074ce9e46SMax Reitz             return;
298174ce9e46SMax Reitz         }
298274ce9e46SMax Reitz 
298374ce9e46SMax Reitz         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
298474ce9e46SMax Reitz         aio_context_acquire(replace_aio_context);
298574ce9e46SMax Reitz         replace_size = bdrv_getlength(to_replace_bs);
298674ce9e46SMax Reitz         aio_context_release(replace_aio_context);
298774ce9e46SMax Reitz 
298874ce9e46SMax Reitz         if (replace_size < 0) {
298974ce9e46SMax Reitz             error_setg_errno(errp, -replace_size,
299074ce9e46SMax Reitz                              "Failed to query the replacement node's size");
299174ce9e46SMax Reitz             return;
299274ce9e46SMax Reitz         }
299374ce9e46SMax Reitz         if (bs_size != replace_size) {
299474ce9e46SMax Reitz             error_setg(errp, "cannot replace image with a mirror image of "
299574ce9e46SMax Reitz                              "different size");
299674ce9e46SMax Reitz             return;
299774ce9e46SMax Reitz         }
299874ce9e46SMax Reitz     }
299974ce9e46SMax Reitz 
30004193cdd7SFam Zheng     /* pass the node name to replace to mirror start since it's loose coupling
30014193cdd7SFam Zheng      * and will allow to check whether the node still exist at mirror completion
30024193cdd7SFam Zheng      */
300371aa9867SAlberto Garcia     mirror_start(job_id, bs, target,
3004a1999b33SJohn Snow                  has_replaces ? replaces : NULL, job_flags,
3005cdf3bc93SMax Reitz                  speed, granularity, buf_size, sync, backing_mode, zero_target,
30066cdbceb1SKevin Wolf                  on_source_error, on_target_error, unmap, filter_node_name,
3007481debaaSMax Reitz                  copy_mode, errp);
30084193cdd7SFam Zheng }
30094193cdd7SFam Zheng 
3010faecd40aSEric Blake void qmp_drive_mirror(DriveMirror *arg, Error **errp)
30114193cdd7SFam Zheng {
30124193cdd7SFam Zheng     BlockDriverState *bs;
3013*3f072a7fSMax Reitz     BlockDriverState *target_backing_bs, *target_bs;
30144193cdd7SFam Zheng     AioContext *aio_context;
30153ea67e08SSergio Lopez     AioContext *old_context;
3016274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode;
30174193cdd7SFam Zheng     Error *local_err = NULL;
30184193cdd7SFam Zheng     QDict *options = NULL;
30194193cdd7SFam Zheng     int flags;
30204193cdd7SFam Zheng     int64_t size;
3021faecd40aSEric Blake     const char *format = arg->format;
3022cdf3bc93SMax Reitz     bool zero_target;
30238ed7d42fSKevin Wolf     int ret;
30244193cdd7SFam Zheng 
30250524e93aSKevin Wolf     bs = qmp_get_root_bs(arg->device, errp);
30260524e93aSKevin Wolf     if (!bs) {
3027d9b902dbSPaolo Bonzini         return;
3028d9b902dbSPaolo Bonzini     }
3029d9b902dbSPaolo Bonzini 
3030cb2af917SPaolo Bonzini     /* Early check to avoid creating target */
3031cb2af917SPaolo Bonzini     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3032cb2af917SPaolo Bonzini         return;
3033cb2af917SPaolo Bonzini     }
3034cb2af917SPaolo Bonzini 
30350524e93aSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
30365a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
30375a7e7a0bSStefan Hajnoczi 
3038faecd40aSEric Blake     if (!arg->has_mode) {
3039faecd40aSEric Blake         arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
30404193cdd7SFam Zheng     }
3041d9b902dbSPaolo Bonzini 
3042faecd40aSEric Blake     if (!arg->has_format) {
3043faecd40aSEric Blake         format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3044faecd40aSEric Blake                   ? NULL : bs->drv->format_name);
3045d9b902dbSPaolo Bonzini     }
3046d9b902dbSPaolo Bonzini 
304761de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
3048*3f072a7fSMax Reitz     target_backing_bs = bdrv_cow_bs(bdrv_skip_filters(bs));
3049*3f072a7fSMax Reitz     if (!target_backing_bs && arg->sync == MIRROR_SYNC_MODE_TOP) {
3050faecd40aSEric Blake         arg->sync = MIRROR_SYNC_MODE_FULL;
3051d9b902dbSPaolo Bonzini     }
3052faecd40aSEric Blake     if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3053*3f072a7fSMax Reitz         target_backing_bs = bs;
3054117e0c82SMax Reitz     }
3055d9b902dbSPaolo Bonzini 
3056ac3c5d83SStefan Hajnoczi     size = bdrv_getlength(bs);
3057ac3c5d83SStefan Hajnoczi     if (size < 0) {
3058ac3c5d83SStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
30595a7e7a0bSStefan Hajnoczi         goto out;
3060ac3c5d83SStefan Hajnoczi     }
3061ac3c5d83SStefan Hajnoczi 
3062faecd40aSEric Blake     if (arg->has_replaces) {
3063faecd40aSEric Blake         if (!arg->has_node_name) {
306409158f00SBenoît Canet             error_setg(errp, "a node-name must be provided when replacing a"
306509158f00SBenoît Canet                              " named node of the graph");
30665a7e7a0bSStefan Hajnoczi             goto out;
306709158f00SBenoît Canet         }
306809158f00SBenoît Canet     }
306909158f00SBenoît Canet 
3070faecd40aSEric Blake     if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3071274fcceeSMax Reitz         backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3072274fcceeSMax Reitz     } else {
3073274fcceeSMax Reitz         backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3074274fcceeSMax Reitz     }
3075274fcceeSMax Reitz 
30762a32c6e8SJohn Snow     /* Don't open backing image in create() */
30772a32c6e8SJohn Snow     flags |= BDRV_O_NO_BACKING;
30782a32c6e8SJohn Snow 
3079*3f072a7fSMax Reitz     if ((arg->sync == MIRROR_SYNC_MODE_FULL || !target_backing_bs)
3080faecd40aSEric Blake         && arg->mode != NEW_IMAGE_MODE_EXISTING)
308114526864SMax Reitz     {
3082d9b902dbSPaolo Bonzini         /* create new image w/o backing file */
3083e6641719SMax Reitz         assert(format);
3084faecd40aSEric Blake         bdrv_img_create(arg->target, format,
30859217283dSFam Zheng                         NULL, NULL, NULL, size, flags, false, &local_err);
3086d9b902dbSPaolo Bonzini     } else {
3087*3f072a7fSMax Reitz         /* Implicit filters should not appear in the filename */
3088*3f072a7fSMax Reitz         BlockDriverState *explicit_backing =
3089*3f072a7fSMax Reitz             bdrv_skip_implicit_filters(target_backing_bs);
3090*3f072a7fSMax Reitz 
3091faecd40aSEric Blake         switch (arg->mode) {
3092d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_EXISTING:
3093d9b902dbSPaolo Bonzini             break;
3094d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3095d9b902dbSPaolo Bonzini             /* create new image with backing file */
3096*3f072a7fSMax Reitz             bdrv_refresh_filename(explicit_backing);
3097faecd40aSEric Blake             bdrv_img_create(arg->target, format,
3098*3f072a7fSMax Reitz                             explicit_backing->filename,
3099*3f072a7fSMax Reitz                             explicit_backing->drv->format_name,
31009217283dSFam Zheng                             NULL, size, flags, false, &local_err);
3101d9b902dbSPaolo Bonzini             break;
3102d9b902dbSPaolo Bonzini         default:
3103d9b902dbSPaolo Bonzini             abort();
3104d9b902dbSPaolo Bonzini         }
3105d9b902dbSPaolo Bonzini     }
3106d9b902dbSPaolo Bonzini 
310784d18f06SMarkus Armbruster     if (local_err) {
3108cf8f2426SLuiz Capitulino         error_propagate(errp, local_err);
31095a7e7a0bSStefan Hajnoczi         goto out;
3110d9b902dbSPaolo Bonzini     }
3111d9b902dbSPaolo Bonzini 
31124c828dc6SBenoît Canet     options = qdict_new();
3113faecd40aSEric Blake     if (arg->has_node_name) {
311446f5ac20SEric Blake         qdict_put_str(options, "node-name", arg->node_name);
31154c828dc6SBenoît Canet     }
3116e6641719SMax Reitz     if (format) {
311746f5ac20SEric Blake         qdict_put_str(options, "driver", format);
3118e6641719SMax Reitz     }
31194c828dc6SBenoît Canet 
3120b812f671SPaolo Bonzini     /* Mirroring takes care of copy-on-write using the source's backing
3121b812f671SPaolo Bonzini      * file.
3122b812f671SPaolo Bonzini      */
31232a32c6e8SJohn Snow     target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
31245b363937SMax Reitz     if (!target_bs) {
31255a7e7a0bSStefan Hajnoczi         goto out;
3126d9b902dbSPaolo Bonzini     }
3127d9b902dbSPaolo Bonzini 
3128cdf3bc93SMax Reitz     zero_target = (arg->sync == MIRROR_SYNC_MODE_FULL &&
3129cdf3bc93SMax Reitz                    (arg->mode == NEW_IMAGE_MODE_EXISTING ||
3130cdf3bc93SMax Reitz                     !bdrv_has_zero_init(target_bs)));
3131cdf3bc93SMax Reitz 
31323ea67e08SSergio Lopez 
31333ea67e08SSergio Lopez     /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
31343ea67e08SSergio Lopez     old_context = bdrv_get_aio_context(target_bs);
31353ea67e08SSergio Lopez     aio_context_release(aio_context);
31363ea67e08SSergio Lopez     aio_context_acquire(old_context);
31373ea67e08SSergio Lopez 
31388ed7d42fSKevin Wolf     ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
31398ed7d42fSKevin Wolf     if (ret < 0) {
31408ed7d42fSKevin Wolf         bdrv_unref(target_bs);
31413ea67e08SSergio Lopez         aio_context_release(old_context);
31423ea67e08SSergio Lopez         return;
31438ed7d42fSKevin Wolf     }
31445a7e7a0bSStefan Hajnoczi 
31453ea67e08SSergio Lopez     aio_context_release(old_context);
31463ea67e08SSergio Lopez     aio_context_acquire(aio_context);
31473ea67e08SSergio Lopez 
3148faecd40aSEric Blake     blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3149faecd40aSEric Blake                            arg->has_replaces, arg->replaces, arg->sync,
3150cdf3bc93SMax Reitz                            backing_mode, zero_target,
3151cdf3bc93SMax Reitz                            arg->has_speed, arg->speed,
3152faecd40aSEric Blake                            arg->has_granularity, arg->granularity,
3153faecd40aSEric Blake                            arg->has_buf_size, arg->buf_size,
3154faecd40aSEric Blake                            arg->has_on_source_error, arg->on_source_error,
3155faecd40aSEric Blake                            arg->has_on_target_error, arg->on_target_error,
3156faecd40aSEric Blake                            arg->has_unmap, arg->unmap,
31576cdbceb1SKevin Wolf                            false, NULL,
3158481debaaSMax Reitz                            arg->has_copy_mode, arg->copy_mode,
3159a6b58adeSJohn Snow                            arg->has_auto_finalize, arg->auto_finalize,
3160a6b58adeSJohn Snow                            arg->has_auto_dismiss, arg->auto_dismiss,
3161992861fbSMarkus Armbruster                            errp);
3162e253f4b8SKevin Wolf     bdrv_unref(target_bs);
31635a7e7a0bSStefan Hajnoczi out:
31645a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
3165d9b902dbSPaolo Bonzini }
3166d9b902dbSPaolo Bonzini 
316771aa9867SAlberto Garcia void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
316871aa9867SAlberto Garcia                          const char *device, const char *target,
3169df92562eSFam Zheng                          bool has_replaces, const char *replaces,
3170df92562eSFam Zheng                          MirrorSyncMode sync,
3171df92562eSFam Zheng                          bool has_speed, int64_t speed,
3172df92562eSFam Zheng                          bool has_granularity, uint32_t granularity,
3173df92562eSFam Zheng                          bool has_buf_size, int64_t buf_size,
3174df92562eSFam Zheng                          bool has_on_source_error,
3175df92562eSFam Zheng                          BlockdevOnError on_source_error,
3176df92562eSFam Zheng                          bool has_on_target_error,
3177df92562eSFam Zheng                          BlockdevOnError on_target_error,
31786cdbceb1SKevin Wolf                          bool has_filter_node_name,
31796cdbceb1SKevin Wolf                          const char *filter_node_name,
3180481debaaSMax Reitz                          bool has_copy_mode, MirrorCopyMode copy_mode,
3181a6b58adeSJohn Snow                          bool has_auto_finalize, bool auto_finalize,
3182a6b58adeSJohn Snow                          bool has_auto_dismiss, bool auto_dismiss,
3183df92562eSFam Zheng                          Error **errp)
3184df92562eSFam Zheng {
3185df92562eSFam Zheng     BlockDriverState *bs;
3186df92562eSFam Zheng     BlockDriverState *target_bs;
3187df92562eSFam Zheng     AioContext *aio_context;
31883ea67e08SSergio Lopez     AioContext *old_context;
3189274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3190cdf3bc93SMax Reitz     bool zero_target;
31918ed7d42fSKevin Wolf     int ret;
3192df92562eSFam Zheng 
319307eec652SKevin Wolf     bs = qmp_get_root_bs(device, errp);
3194df92562eSFam Zheng     if (!bs) {
3195df92562eSFam Zheng         return;
3196df92562eSFam Zheng     }
3197df92562eSFam Zheng 
3198df92562eSFam Zheng     target_bs = bdrv_lookup_bs(target, target, errp);
3199df92562eSFam Zheng     if (!target_bs) {
3200df92562eSFam Zheng         return;
3201df92562eSFam Zheng     }
3202df92562eSFam Zheng 
3203cdf3bc93SMax Reitz     zero_target = (sync == MIRROR_SYNC_MODE_FULL);
3204cdf3bc93SMax Reitz 
32053ea67e08SSergio Lopez     /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
32063ea67e08SSergio Lopez     old_context = bdrv_get_aio_context(target_bs);
3207df92562eSFam Zheng     aio_context = bdrv_get_aio_context(bs);
32083ea67e08SSergio Lopez     aio_context_acquire(old_context);
3209df92562eSFam Zheng 
32108ed7d42fSKevin Wolf     ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
32113ea67e08SSergio Lopez 
32123ea67e08SSergio Lopez     aio_context_release(old_context);
32133ea67e08SSergio Lopez     aio_context_acquire(aio_context);
32143ea67e08SSergio Lopez 
32158ed7d42fSKevin Wolf     if (ret < 0) {
32168ed7d42fSKevin Wolf         goto out;
32178ed7d42fSKevin Wolf     }
3218df92562eSFam Zheng 
321971aa9867SAlberto Garcia     blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
3220274fcceeSMax Reitz                            has_replaces, replaces, sync, backing_mode,
3221cdf3bc93SMax Reitz                            zero_target, has_speed, speed,
3222df92562eSFam Zheng                            has_granularity, granularity,
3223df92562eSFam Zheng                            has_buf_size, buf_size,
3224df92562eSFam Zheng                            has_on_source_error, on_source_error,
3225df92562eSFam Zheng                            has_on_target_error, on_target_error,
3226df92562eSFam Zheng                            true, true,
32276cdbceb1SKevin Wolf                            has_filter_node_name, filter_node_name,
3228481debaaSMax Reitz                            has_copy_mode, copy_mode,
3229a6b58adeSJohn Snow                            has_auto_finalize, auto_finalize,
3230a6b58adeSJohn Snow                            has_auto_dismiss, auto_dismiss,
3231992861fbSMarkus Armbruster                            errp);
32328ed7d42fSKevin Wolf out:
3233df92562eSFam Zheng     aio_context_release(aio_context);
3234df92562eSFam Zheng }
3235df92562eSFam Zheng 
32363ddf3efeSAlberto Garcia /* Get a block job using its ID and acquire its AioContext */
32373ddf3efeSAlberto Garcia static BlockJob *find_block_job(const char *id, AioContext **aio_context,
323824d6bffeSMarkus Armbruster                                 Error **errp)
32392d47c6e9SStefan Hajnoczi {
32403ddf3efeSAlberto Garcia     BlockJob *job;
32413ddf3efeSAlberto Garcia 
32423ddf3efeSAlberto Garcia     assert(id != NULL);
32432d47c6e9SStefan Hajnoczi 
32445433c24fSMax Reitz     *aio_context = NULL;
32455433c24fSMax Reitz 
32463ddf3efeSAlberto Garcia     job = block_job_get(id);
32473ddf3efeSAlberto Garcia 
32483ddf3efeSAlberto Garcia     if (!job) {
32493ddf3efeSAlberto Garcia         error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
32503ddf3efeSAlberto Garcia                   "Block job '%s' not found", id);
32513ddf3efeSAlberto Garcia         return NULL;
32522d47c6e9SStefan Hajnoczi     }
32533d948cdfSStefan Hajnoczi 
32543ddf3efeSAlberto Garcia     *aio_context = blk_get_aio_context(job->blk);
32553d948cdfSStefan Hajnoczi     aio_context_acquire(*aio_context);
32563d948cdfSStefan Hajnoczi 
32573ddf3efeSAlberto Garcia     return job;
32582d47c6e9SStefan Hajnoczi }
32592d47c6e9SStefan Hajnoczi 
3260882ec7ceSStefan Hajnoczi void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
32612d47c6e9SStefan Hajnoczi {
32623d948cdfSStefan Hajnoczi     AioContext *aio_context;
326324d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
32642d47c6e9SStefan Hajnoczi 
32652d47c6e9SStefan Hajnoczi     if (!job) {
32662d47c6e9SStefan Hajnoczi         return;
32672d47c6e9SStefan Hajnoczi     }
32682d47c6e9SStefan Hajnoczi 
3269882ec7ceSStefan Hajnoczi     block_job_set_speed(job, speed, errp);
32703d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
32712d47c6e9SStefan Hajnoczi }
3272370521a1SStefan Hajnoczi 
32736e37fb81SPaolo Bonzini void qmp_block_job_cancel(const char *device,
32746e37fb81SPaolo Bonzini                           bool has_force, bool force, Error **errp)
32756e37fb81SPaolo Bonzini {
32763d948cdfSStefan Hajnoczi     AioContext *aio_context;
327724d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
32786e37fb81SPaolo Bonzini 
32796e37fb81SPaolo Bonzini     if (!job) {
32806e37fb81SPaolo Bonzini         return;
32816e37fb81SPaolo Bonzini     }
32823d948cdfSStefan Hajnoczi 
32833d948cdfSStefan Hajnoczi     if (!has_force) {
32843d948cdfSStefan Hajnoczi         force = false;
32853d948cdfSStefan Hajnoczi     }
32863d948cdfSStefan Hajnoczi 
3287b15de828SKevin Wolf     if (job_user_paused(&job->job) && !force) {
3288f231b88dSCole Robinson         error_setg(errp, "The block job for device '%s' is currently paused",
3289f231b88dSCole Robinson                    device);
32903d948cdfSStefan Hajnoczi         goto out;
32916e37fb81SPaolo Bonzini     }
32926e37fb81SPaolo Bonzini 
32936e37fb81SPaolo Bonzini     trace_qmp_block_job_cancel(job);
32943d70ff53SKevin Wolf     job_user_cancel(&job->job, force, errp);
32953d948cdfSStefan Hajnoczi out:
32963d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
32976e37fb81SPaolo Bonzini }
32986e37fb81SPaolo Bonzini 
32996e37fb81SPaolo Bonzini void qmp_block_job_pause(const char *device, Error **errp)
3300370521a1SStefan Hajnoczi {
33013d948cdfSStefan Hajnoczi     AioContext *aio_context;
330224d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3303370521a1SStefan Hajnoczi 
33040ec4dfb8SJohn Snow     if (!job) {
3305370521a1SStefan Hajnoczi         return;
3306370521a1SStefan Hajnoczi     }
33076e37fb81SPaolo Bonzini 
33086e37fb81SPaolo Bonzini     trace_qmp_block_job_pause(job);
3309b15de828SKevin Wolf     job_user_pause(&job->job, errp);
33103d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
33116e37fb81SPaolo Bonzini }
33126e37fb81SPaolo Bonzini 
33136e37fb81SPaolo Bonzini void qmp_block_job_resume(const char *device, Error **errp)
33146e37fb81SPaolo Bonzini {
33153d948cdfSStefan Hajnoczi     AioContext *aio_context;
331624d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
33176e37fb81SPaolo Bonzini 
33180ec4dfb8SJohn Snow     if (!job) {
33198acc72a4SPaolo Bonzini         return;
33208acc72a4SPaolo Bonzini     }
3321370521a1SStefan Hajnoczi 
33226e37fb81SPaolo Bonzini     trace_qmp_block_job_resume(job);
3323b15de828SKevin Wolf     job_user_resume(&job->job, errp);
33243d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3325370521a1SStefan Hajnoczi }
3326fb5458cdSStefan Hajnoczi 
3327aeae883bSPaolo Bonzini void qmp_block_job_complete(const char *device, Error **errp)
3328aeae883bSPaolo Bonzini {
33293d948cdfSStefan Hajnoczi     AioContext *aio_context;
333024d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3331aeae883bSPaolo Bonzini 
3332aeae883bSPaolo Bonzini     if (!job) {
3333aeae883bSPaolo Bonzini         return;
3334aeae883bSPaolo Bonzini     }
3335aeae883bSPaolo Bonzini 
3336aeae883bSPaolo Bonzini     trace_qmp_block_job_complete(job);
33373453d972SKevin Wolf     job_complete(&job->job, errp);
33383d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3339aeae883bSPaolo Bonzini }
3340aeae883bSPaolo Bonzini 
334111b61fbcSJohn Snow void qmp_block_job_finalize(const char *id, Error **errp)
334211b61fbcSJohn Snow {
334311b61fbcSJohn Snow     AioContext *aio_context;
334411b61fbcSJohn Snow     BlockJob *job = find_block_job(id, &aio_context, errp);
334511b61fbcSJohn Snow 
334611b61fbcSJohn Snow     if (!job) {
334711b61fbcSJohn Snow         return;
334811b61fbcSJohn Snow     }
334911b61fbcSJohn Snow 
335011b61fbcSJohn Snow     trace_qmp_block_job_finalize(job);
3351b660a84bSStefan Reiter     job_ref(&job->job);
33527eaa8fb5SKevin Wolf     job_finalize(&job->job, errp);
3353b660a84bSStefan Reiter 
3354b660a84bSStefan Reiter     /*
3355b660a84bSStefan Reiter      * Job's context might have changed via job_finalize (and job_txn_apply
3356b660a84bSStefan Reiter      * automatically acquires the new one), so make sure we release the correct
3357b660a84bSStefan Reiter      * one.
3358b660a84bSStefan Reiter      */
3359b660a84bSStefan Reiter     aio_context = blk_get_aio_context(job->blk);
3360b660a84bSStefan Reiter     job_unref(&job->job);
336111b61fbcSJohn Snow     aio_context_release(aio_context);
336211b61fbcSJohn Snow }
336311b61fbcSJohn Snow 
336475f71059SJohn Snow void qmp_block_job_dismiss(const char *id, Error **errp)
336575f71059SJohn Snow {
336675f71059SJohn Snow     AioContext *aio_context;
33675f9a6a08SKevin Wolf     BlockJob *bjob = find_block_job(id, &aio_context, errp);
33685f9a6a08SKevin Wolf     Job *job;
336975f71059SJohn Snow 
33705f9a6a08SKevin Wolf     if (!bjob) {
337175f71059SJohn Snow         return;
337275f71059SJohn Snow     }
337375f71059SJohn Snow 
33745f9a6a08SKevin Wolf     trace_qmp_block_job_dismiss(bjob);
33755f9a6a08SKevin Wolf     job = &bjob->job;
33765f9a6a08SKevin Wolf     job_dismiss(&job, errp);
337775f71059SJohn Snow     aio_context_release(aio_context);
337875f71059SJohn Snow }
337975f71059SJohn Snow 
3380fa40e656SJeff Cody void qmp_change_backing_file(const char *device,
3381fa40e656SJeff Cody                              const char *image_node_name,
3382fa40e656SJeff Cody                              const char *backing_file,
3383fa40e656SJeff Cody                              Error **errp)
3384fa40e656SJeff Cody {
3385fa40e656SJeff Cody     BlockDriverState *bs = NULL;
3386729962f6SStefan Hajnoczi     AioContext *aio_context;
3387fa40e656SJeff Cody     BlockDriverState *image_bs = NULL;
3388fa40e656SJeff Cody     Error *local_err = NULL;
3389fa40e656SJeff Cody     bool ro;
3390fa40e656SJeff Cody     int ret;
3391fa40e656SJeff Cody 
33927b5dca3fSKevin Wolf     bs = qmp_get_root_bs(device, errp);
33937b5dca3fSKevin Wolf     if (!bs) {
3394fa40e656SJeff Cody         return;
3395fa40e656SJeff Cody     }
3396fa40e656SJeff Cody 
33977b5dca3fSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3398729962f6SStefan Hajnoczi     aio_context_acquire(aio_context);
3399729962f6SStefan Hajnoczi 
3400fa40e656SJeff Cody     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3401fa40e656SJeff Cody     if (local_err) {
3402fa40e656SJeff Cody         error_propagate(errp, local_err);
3403729962f6SStefan Hajnoczi         goto out;
3404fa40e656SJeff Cody     }
3405fa40e656SJeff Cody 
3406fa40e656SJeff Cody     if (!image_bs) {
3407fa40e656SJeff Cody         error_setg(errp, "image file not found");
3408729962f6SStefan Hajnoczi         goto out;
3409fa40e656SJeff Cody     }
3410fa40e656SJeff Cody 
3411fa40e656SJeff Cody     if (bdrv_find_base(image_bs) == image_bs) {
3412fa40e656SJeff Cody         error_setg(errp, "not allowing backing file change on an image "
3413fa40e656SJeff Cody                          "without a backing file");
3414729962f6SStefan Hajnoczi         goto out;
3415fa40e656SJeff Cody     }
3416fa40e656SJeff Cody 
3417fa40e656SJeff Cody     /* even though we are not necessarily operating on bs, we need it to
3418fa40e656SJeff Cody      * determine if block ops are currently prohibited on the chain */
3419fa40e656SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3420729962f6SStefan Hajnoczi         goto out;
3421fa40e656SJeff Cody     }
3422fa40e656SJeff Cody 
3423fa40e656SJeff Cody     /* final sanity check */
3424fa40e656SJeff Cody     if (!bdrv_chain_contains(bs, image_bs)) {
3425fa40e656SJeff Cody         error_setg(errp, "'%s' and image file are not in the same chain",
3426fa40e656SJeff Cody                    device);
3427729962f6SStefan Hajnoczi         goto out;
3428fa40e656SJeff Cody     }
3429fa40e656SJeff Cody 
3430fa40e656SJeff Cody     /* if not r/w, reopen to make r/w */
3431fa40e656SJeff Cody     ro = bdrv_is_read_only(image_bs);
3432fa40e656SJeff Cody 
3433fa40e656SJeff Cody     if (ro) {
3434051a60f6SAlberto Garcia         if (bdrv_reopen_set_read_only(image_bs, false, errp) != 0) {
3435729962f6SStefan Hajnoczi             goto out;
3436fa40e656SJeff Cody         }
3437fa40e656SJeff Cody     }
3438fa40e656SJeff Cody 
3439fa40e656SJeff Cody     ret = bdrv_change_backing_file(image_bs, backing_file,
3440e54ee1b3SEric Blake                                    image_bs->drv ? image_bs->drv->format_name : "",
3441e54ee1b3SEric Blake                                    false);
3442fa40e656SJeff Cody 
3443fa40e656SJeff Cody     if (ret < 0) {
3444fa40e656SJeff Cody         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3445fa40e656SJeff Cody                          backing_file);
3446fa40e656SJeff Cody         /* don't exit here, so we can try to restore open flags if
3447fa40e656SJeff Cody          * appropriate */
3448fa40e656SJeff Cody     }
3449fa40e656SJeff Cody 
3450fa40e656SJeff Cody     if (ro) {
3451992861fbSMarkus Armbruster         bdrv_reopen_set_read_only(image_bs, true, errp);
3452fa40e656SJeff Cody     }
3453729962f6SStefan Hajnoczi 
3454729962f6SStefan Hajnoczi out:
3455729962f6SStefan Hajnoczi     aio_context_release(aio_context);
3456fa40e656SJeff Cody }
3457fa40e656SJeff Cody 
3458d26c9a15SKevin Wolf void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3459d26c9a15SKevin Wolf {
3460be4b67bcSMax Reitz     BlockDriverState *bs;
3461d26c9a15SKevin Wolf     QObject *obj;
34627d5e199aSDaniel P. Berrange     Visitor *v = qobject_output_visitor_new(&obj);
3463d26c9a15SKevin Wolf     QDict *qdict;
3464d26c9a15SKevin Wolf 
34651f584248SMarkus Armbruster     visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
34663b098d56SEric Blake     visit_complete(v, &obj);
34677dc847ebSMax Reitz     qdict = qobject_to(QDict, obj);
3468d26c9a15SKevin Wolf 
3469d26c9a15SKevin Wolf     qdict_flatten(qdict);
3470d26c9a15SKevin Wolf 
3471be4b67bcSMax Reitz     if (!qdict_get_try_str(qdict, "node-name")) {
34729ec8873eSKevin Wolf         error_setg(errp, "'node-name' must be specified for the root node");
3473be4b67bcSMax Reitz         goto fail;
3474be4b67bcSMax Reitz     }
3475be4b67bcSMax Reitz 
3476bd745e23SMax Reitz     bs = bds_tree_init(qdict, errp);
3477bd745e23SMax Reitz     if (!bs) {
3478be4b67bcSMax Reitz         goto fail;
3479be4b67bcSMax Reitz     }
34809c4218e9SMax Reitz 
348189802d5aSMaxim Levitsky     bdrv_set_monitor_owned(bs);
3482be4b67bcSMax Reitz 
3483d26c9a15SKevin Wolf fail:
34843b098d56SEric Blake     visit_free(v);
3485d26c9a15SKevin Wolf }
3486d26c9a15SKevin Wolf 
34871479c730SAlberto Garcia void qmp_x_blockdev_reopen(BlockdevOptions *options, Error **errp)
34881479c730SAlberto Garcia {
34891479c730SAlberto Garcia     BlockDriverState *bs;
34901479c730SAlberto Garcia     AioContext *ctx;
34911479c730SAlberto Garcia     QObject *obj;
34921479c730SAlberto Garcia     Visitor *v = qobject_output_visitor_new(&obj);
34931479c730SAlberto Garcia     BlockReopenQueue *queue;
34941479c730SAlberto Garcia     QDict *qdict;
34951479c730SAlberto Garcia 
34961479c730SAlberto Garcia     /* Check for the selected node name */
34971479c730SAlberto Garcia     if (!options->has_node_name) {
34981479c730SAlberto Garcia         error_setg(errp, "Node name not specified");
34991479c730SAlberto Garcia         goto fail;
35001479c730SAlberto Garcia     }
35011479c730SAlberto Garcia 
35021479c730SAlberto Garcia     bs = bdrv_find_node(options->node_name);
35031479c730SAlberto Garcia     if (!bs) {
35041479c730SAlberto Garcia         error_setg(errp, "Cannot find node named '%s'", options->node_name);
35051479c730SAlberto Garcia         goto fail;
35061479c730SAlberto Garcia     }
35071479c730SAlberto Garcia 
35081479c730SAlberto Garcia     /* Put all options in a QDict and flatten it */
35091f584248SMarkus Armbruster     visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
35101479c730SAlberto Garcia     visit_complete(v, &obj);
35111479c730SAlberto Garcia     qdict = qobject_to(QDict, obj);
35121479c730SAlberto Garcia 
35131479c730SAlberto Garcia     qdict_flatten(qdict);
35141479c730SAlberto Garcia 
35151479c730SAlberto Garcia     /* Perform the reopen operation */
35161479c730SAlberto Garcia     ctx = bdrv_get_aio_context(bs);
35171479c730SAlberto Garcia     aio_context_acquire(ctx);
35181479c730SAlberto Garcia     bdrv_subtree_drained_begin(bs);
35191479c730SAlberto Garcia     queue = bdrv_reopen_queue(NULL, bs, qdict, false);
35201479c730SAlberto Garcia     bdrv_reopen_multiple(queue, errp);
35211479c730SAlberto Garcia     bdrv_subtree_drained_end(bs);
35221479c730SAlberto Garcia     aio_context_release(ctx);
35231479c730SAlberto Garcia 
35241479c730SAlberto Garcia fail:
35251479c730SAlberto Garcia     visit_free(v);
35261479c730SAlberto Garcia }
35271479c730SAlberto Garcia 
352879b7a77eSMarkus Armbruster void qmp_blockdev_del(const char *node_name, Error **errp)
352981b936aeSAlberto Garcia {
353081b936aeSAlberto Garcia     AioContext *aio_context;
353181b936aeSAlberto Garcia     BlockDriverState *bs;
353281b936aeSAlberto Garcia 
353381b936aeSAlberto Garcia     bs = bdrv_find_node(node_name);
353481b936aeSAlberto Garcia     if (!bs) {
353581b936aeSAlberto Garcia         error_setg(errp, "Cannot find node %s", node_name);
353681b936aeSAlberto Garcia         return;
353781b936aeSAlberto Garcia     }
35381f0c461bSKevin Wolf     if (bdrv_has_blk(bs)) {
3539e467da7bSKevin Wolf         error_setg(errp, "Node %s is in use", node_name);
354081b936aeSAlberto Garcia         return;
354181b936aeSAlberto Garcia     }
354281b936aeSAlberto Garcia     aio_context = bdrv_get_aio_context(bs);
354381b936aeSAlberto Garcia     aio_context_acquire(aio_context);
354481b936aeSAlberto Garcia 
354581b936aeSAlberto Garcia     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
354681b936aeSAlberto Garcia         goto out;
354781b936aeSAlberto Garcia     }
354881b936aeSAlberto Garcia 
354970537ed5SPaolo Bonzini     if (!QTAILQ_IN_USE(bs, monitor_list)) {
35509c4218e9SMax Reitz         error_setg(errp, "Node %s is not owned by the monitor",
35519c4218e9SMax Reitz                    bs->node_name);
35529c4218e9SMax Reitz         goto out;
35539c4218e9SMax Reitz     }
35549c4218e9SMax Reitz 
35559c4218e9SMax Reitz     if (bs->refcnt > 1) {
355681b936aeSAlberto Garcia         error_setg(errp, "Block device %s is in use",
355781b936aeSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
355881b936aeSAlberto Garcia         goto out;
355981b936aeSAlberto Garcia     }
356081b936aeSAlberto Garcia 
35619c4218e9SMax Reitz     QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
356281b936aeSAlberto Garcia     bdrv_unref(bs);
356381b936aeSAlberto Garcia 
356481b936aeSAlberto Garcia out:
356581b936aeSAlberto Garcia     aio_context_release(aio_context);
356681b936aeSAlberto Garcia }
356781b936aeSAlberto Garcia 
35687f821597SWen Congyang static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
35697f821597SWen Congyang                                   const char *child_name)
35707f821597SWen Congyang {
35717f821597SWen Congyang     BdrvChild *child;
35727f821597SWen Congyang 
35737f821597SWen Congyang     QLIST_FOREACH(child, &parent_bs->children, next) {
35747f821597SWen Congyang         if (strcmp(child->name, child_name) == 0) {
35757f821597SWen Congyang             return child;
35767f821597SWen Congyang         }
35777f821597SWen Congyang     }
35787f821597SWen Congyang 
35797f821597SWen Congyang     return NULL;
35807f821597SWen Congyang }
35817f821597SWen Congyang 
35827f821597SWen Congyang void qmp_x_blockdev_change(const char *parent, bool has_child,
35837f821597SWen Congyang                            const char *child, bool has_node,
35847f821597SWen Congyang                            const char *node, Error **errp)
35857f821597SWen Congyang {
35867f821597SWen Congyang     BlockDriverState *parent_bs, *new_bs = NULL;
35877f821597SWen Congyang     BdrvChild *p_child;
35887f821597SWen Congyang 
35897f821597SWen Congyang     parent_bs = bdrv_lookup_bs(parent, parent, errp);
35907f821597SWen Congyang     if (!parent_bs) {
35917f821597SWen Congyang         return;
35927f821597SWen Congyang     }
35937f821597SWen Congyang 
35947f821597SWen Congyang     if (has_child == has_node) {
35957f821597SWen Congyang         if (has_child) {
35967f821597SWen Congyang             error_setg(errp, "The parameters child and node are in conflict");
35977f821597SWen Congyang         } else {
35987f821597SWen Congyang             error_setg(errp, "Either child or node must be specified");
35997f821597SWen Congyang         }
36007f821597SWen Congyang         return;
36017f821597SWen Congyang     }
36027f821597SWen Congyang 
36037f821597SWen Congyang     if (has_child) {
36047f821597SWen Congyang         p_child = bdrv_find_child(parent_bs, child);
36057f821597SWen Congyang         if (!p_child) {
36067f821597SWen Congyang             error_setg(errp, "Node '%s' does not have child '%s'",
36077f821597SWen Congyang                        parent, child);
36087f821597SWen Congyang             return;
36097f821597SWen Congyang         }
36107f821597SWen Congyang         bdrv_del_child(parent_bs, p_child, errp);
36117f821597SWen Congyang     }
36127f821597SWen Congyang 
36137f821597SWen Congyang     if (has_node) {
36147f821597SWen Congyang         new_bs = bdrv_find_node(node);
36157f821597SWen Congyang         if (!new_bs) {
36167f821597SWen Congyang             error_setg(errp, "Node '%s' not found", node);
36177f821597SWen Congyang             return;
36187f821597SWen Congyang         }
36197f821597SWen Congyang         bdrv_add_child(parent_bs, new_bs, errp);
36207f821597SWen Congyang     }
36217f821597SWen Congyang }
36227f821597SWen Congyang 
3623fb5458cdSStefan Hajnoczi BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3624fb5458cdSStefan Hajnoczi {
3625fea68bb6SMarkus Armbruster     BlockJobInfoList *head = NULL, **p_next = &head;
3626f0f55dedSAlberto Garcia     BlockJob *job;
3627fea68bb6SMarkus Armbruster 
3628f0f55dedSAlberto Garcia     for (job = block_job_next(NULL); job; job = block_job_next(job)) {
3629559b935fSJohn Snow         BlockJobInfoList *elem;
3630559b935fSJohn Snow         AioContext *aio_context;
363169691e72SStefan Hajnoczi 
3632559b935fSJohn Snow         if (block_job_is_internal(job)) {
3633559b935fSJohn Snow             continue;
3634559b935fSJohn Snow         }
3635559b935fSJohn Snow         elem = g_new0(BlockJobInfoList, 1);
3636559b935fSJohn Snow         aio_context = blk_get_aio_context(job->blk);
363769691e72SStefan Hajnoczi         aio_context_acquire(aio_context);
3638559b935fSJohn Snow         elem->value = block_job_query(job, errp);
3639f0f55dedSAlberto Garcia         aio_context_release(aio_context);
3640559b935fSJohn Snow         if (!elem->value) {
3641559b935fSJohn Snow             g_free(elem);
3642559b935fSJohn Snow             qapi_free_BlockJobInfoList(head);
3643559b935fSJohn Snow             return NULL;
3644559b935fSJohn Snow         }
3645fea68bb6SMarkus Armbruster         *p_next = elem;
3646fea68bb6SMarkus Armbruster         p_next = &elem->next;
3647fea68bb6SMarkus Armbruster     }
364869691e72SStefan Hajnoczi 
3649fea68bb6SMarkus Armbruster     return head;
3650fb5458cdSStefan Hajnoczi }
36514d454574SPaolo Bonzini 
3652ca00bbb1SStefan Hajnoczi void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
3653882e9b89SStefan Hajnoczi                                  bool has_force, bool force, Error **errp)
3654ca00bbb1SStefan Hajnoczi {
3655ca00bbb1SStefan Hajnoczi     AioContext *old_context;
3656ca00bbb1SStefan Hajnoczi     AioContext *new_context;
3657ca00bbb1SStefan Hajnoczi     BlockDriverState *bs;
3658ca00bbb1SStefan Hajnoczi 
3659ca00bbb1SStefan Hajnoczi     bs = bdrv_find_node(node_name);
3660ca00bbb1SStefan Hajnoczi     if (!bs) {
3661ca00bbb1SStefan Hajnoczi         error_setg(errp, "Cannot find node %s", node_name);
3662ca00bbb1SStefan Hajnoczi         return;
3663ca00bbb1SStefan Hajnoczi     }
3664ca00bbb1SStefan Hajnoczi 
3665882e9b89SStefan Hajnoczi     /* Protects against accidents. */
3666882e9b89SStefan Hajnoczi     if (!(has_force && force) && bdrv_has_blk(bs)) {
3667882e9b89SStefan Hajnoczi         error_setg(errp, "Node %s is associated with a BlockBackend and could "
3668882e9b89SStefan Hajnoczi                          "be in use (use force=true to override this check)",
3669882e9b89SStefan Hajnoczi                          node_name);
3670ca00bbb1SStefan Hajnoczi         return;
3671ca00bbb1SStefan Hajnoczi     }
3672ca00bbb1SStefan Hajnoczi 
3673ca00bbb1SStefan Hajnoczi     if (iothread->type == QTYPE_QSTRING) {
3674ca00bbb1SStefan Hajnoczi         IOThread *obj = iothread_by_id(iothread->u.s);
3675ca00bbb1SStefan Hajnoczi         if (!obj) {
3676ca00bbb1SStefan Hajnoczi             error_setg(errp, "Cannot find iothread %s", iothread->u.s);
3677ca00bbb1SStefan Hajnoczi             return;
3678ca00bbb1SStefan Hajnoczi         }
3679ca00bbb1SStefan Hajnoczi 
3680ca00bbb1SStefan Hajnoczi         new_context = iothread_get_aio_context(obj);
3681ca00bbb1SStefan Hajnoczi     } else {
3682ca00bbb1SStefan Hajnoczi         new_context = qemu_get_aio_context();
3683ca00bbb1SStefan Hajnoczi     }
3684ca00bbb1SStefan Hajnoczi 
3685ca00bbb1SStefan Hajnoczi     old_context = bdrv_get_aio_context(bs);
3686ca00bbb1SStefan Hajnoczi     aio_context_acquire(old_context);
3687ca00bbb1SStefan Hajnoczi 
36888ed7d42fSKevin Wolf     bdrv_try_set_aio_context(bs, new_context, errp);
3689ca00bbb1SStefan Hajnoczi 
3690ca00bbb1SStefan Hajnoczi     aio_context_release(old_context);
3691ca00bbb1SStefan Hajnoczi }
3692ca00bbb1SStefan Hajnoczi 
36930006383eSKevin Wolf QemuOptsList qemu_common_drive_opts = {
36944d454574SPaolo Bonzini     .name = "drive",
36950006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
36964d454574SPaolo Bonzini     .desc = {
36974d454574SPaolo Bonzini         {
36984d454574SPaolo Bonzini             .name = "snapshot",
36994d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
37004d454574SPaolo Bonzini             .help = "enable/disable snapshot mode",
37014d454574SPaolo Bonzini         },{
37024d454574SPaolo Bonzini             .name = "aio",
37034d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
3704f80f2673SAarushi Mehta             .help = "host AIO implementation (threads, native, io_uring)",
37054d454574SPaolo Bonzini         },{
3706e4b24b49SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
3707e4b24b49SKevin Wolf             .type = QEMU_OPT_BOOL,
3708e4b24b49SKevin Wolf             .help = "Enable writeback mode",
3709e4b24b49SKevin Wolf         },{
37104d454574SPaolo Bonzini             .name = "format",
37114d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
37124d454574SPaolo Bonzini             .help = "disk format (raw, qcow2, ...)",
37134d454574SPaolo Bonzini         },{
37144d454574SPaolo Bonzini             .name = "rerror",
37154d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
37164d454574SPaolo Bonzini             .help = "read error action",
37174d454574SPaolo Bonzini         },{
37184d454574SPaolo Bonzini             .name = "werror",
37194d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
37204d454574SPaolo Bonzini             .help = "write error action",
37214d454574SPaolo Bonzini         },{
37224e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
37234d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
37244d454574SPaolo Bonzini             .help = "open drive file as read-only",
3725a2a7862cSPradeep Jagadeesh         },
3726a2a7862cSPradeep Jagadeesh 
3727a2a7862cSPradeep Jagadeesh         THROTTLE_OPTS,
3728a2a7862cSPradeep Jagadeesh 
3729a2a7862cSPradeep Jagadeesh         {
373076f4afb4SAlberto Garcia             .name = "throttling.group",
373176f4afb4SAlberto Garcia             .type = QEMU_OPT_STRING,
373276f4afb4SAlberto Garcia             .help = "name of the block throttling group",
373376f4afb4SAlberto Garcia         },{
37344d454574SPaolo Bonzini             .name = "copy-on-read",
37354d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
37364d454574SPaolo Bonzini             .help = "copy read data from backing file into image file",
3737465bee1dSPeter Lieven         },{
3738465bee1dSPeter Lieven             .name = "detect-zeroes",
3739465bee1dSPeter Lieven             .type = QEMU_OPT_STRING,
3740465bee1dSPeter Lieven             .help = "try to optimize zero writes (off, on, unmap)",
3741362e9299SAlberto Garcia         },{
3742362e9299SAlberto Garcia             .name = "stats-account-invalid",
3743362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
3744362e9299SAlberto Garcia             .help = "whether to account for invalid I/O operations "
3745362e9299SAlberto Garcia                     "in the statistics",
3746362e9299SAlberto Garcia         },{
3747362e9299SAlberto Garcia             .name = "stats-account-failed",
3748362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
3749362e9299SAlberto Garcia             .help = "whether to account for failed I/O operations "
3750362e9299SAlberto Garcia                     "in the statistics",
37514d454574SPaolo Bonzini         },
37524d454574SPaolo Bonzini         { /* end of list */ }
37534d454574SPaolo Bonzini     },
37544d454574SPaolo Bonzini };
37550006383eSKevin Wolf 
37560006383eSKevin Wolf QemuOptsList qemu_drive_opts = {
37570006383eSKevin Wolf     .name = "drive",
37580006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
37590006383eSKevin Wolf     .desc = {
3760492fdc6fSKevin Wolf         /*
3761492fdc6fSKevin Wolf          * no elements => accept any params
3762492fdc6fSKevin Wolf          * validation will happen later
3763492fdc6fSKevin Wolf          */
37640006383eSKevin Wolf         { /* end of list */ }
37650006383eSKevin Wolf     },
37660006383eSKevin Wolf };
3767