xref: /openbmc/qemu/blockdev.c (revision 8187f63c9c64c2f2322fc6730c478a57bc0ce9eb)
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"
38e2c1c34fSMarkus Armbruster #include "block/dirty-bitmap.h"
39609f45eaSMax Reitz #include "block/qdict.h"
4076f4afb4SAlberto Garcia #include "block/throttle-groups.h"
4183c9089eSPaolo Bonzini #include "monitor/monitor.h"
42d49b6836SMarkus Armbruster #include "qemu/error-report.h"
431de7afc9SPaolo Bonzini #include "qemu/option.h"
44cdcd4361SMarkus Armbruster #include "qemu/qemu-print.h"
451de7afc9SPaolo Bonzini #include "qemu/config-file.h"
469af23989SMarkus Armbruster #include "qapi/qapi-commands-block.h"
479af23989SMarkus Armbruster #include "qapi/qapi-commands-transaction.h"
489af23989SMarkus Armbruster #include "qapi/qapi-visit-block-core.h"
49452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
5015280c36SMarkus Armbruster #include "qapi/qmp/qnum.h"
516b673957SMarkus Armbruster #include "qapi/qmp/qstring.h"
52e688df6bSMarkus Armbruster #include "qapi/error.h"
53cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
5447e6b297SMarkus Armbruster #include "qapi/qmp/qlist.h"
55b3db211fSDaniel P. Berrange #include "qapi/qobject-output-visitor.h"
569c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
57ca00bbb1SStefan Hajnoczi #include "sysemu/iothread.h"
58737e150eSPaolo Bonzini #include "block/block_int.h"
590ab8ed18SDaniel P. Berrange #include "block/trace.h"
6054d31236SMarkus Armbruster #include "sysemu/runstate.h"
61b39847a5SPavel Dovgalyuk #include "sysemu/replay.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 
67ebc2752bSEmanuele Giuseppe Esposito /* Protected by BQL */
6889802d5aSMaxim Levitsky QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
699c4218e9SMax Reitz     QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
709c4218e9SMax Reitz 
7189802d5aSMaxim Levitsky void bdrv_set_monitor_owned(BlockDriverState *bs)
7289802d5aSMaxim Levitsky {
73b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7489802d5aSMaxim Levitsky     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
7589802d5aSMaxim Levitsky }
7689802d5aSMaxim Levitsky 
771960966dSMarkus Armbruster static const char *const if_name[IF_COUNT] = {
781960966dSMarkus Armbruster     [IF_NONE] = "none",
791960966dSMarkus Armbruster     [IF_IDE] = "ide",
801960966dSMarkus Armbruster     [IF_SCSI] = "scsi",
811960966dSMarkus Armbruster     [IF_FLOPPY] = "floppy",
821960966dSMarkus Armbruster     [IF_PFLASH] = "pflash",
831960966dSMarkus Armbruster     [IF_MTD] = "mtd",
841960966dSMarkus Armbruster     [IF_SD] = "sd",
851960966dSMarkus Armbruster     [IF_VIRTIO] = "virtio",
861960966dSMarkus Armbruster     [IF_XEN] = "xen",
871960966dSMarkus Armbruster };
881960966dSMarkus Armbruster 
8921dff8cfSJohn Snow static int if_max_devs[IF_COUNT] = {
9027d6bf40SMarkus Armbruster     /*
9127d6bf40SMarkus Armbruster      * Do not change these numbers!  They govern how drive option
9227d6bf40SMarkus Armbruster      * index maps to unit and bus.  That mapping is ABI.
9327d6bf40SMarkus Armbruster      *
94547cb157SWei Jiangang      * All controllers used to implement if=T drives need to support
9527d6bf40SMarkus Armbruster      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
9627d6bf40SMarkus Armbruster      * Otherwise, some index values map to "impossible" bus, unit
9727d6bf40SMarkus Armbruster      * values.
9827d6bf40SMarkus Armbruster      *
9927d6bf40SMarkus Armbruster      * For instance, if you change [IF_SCSI] to 255, -drive
10027d6bf40SMarkus Armbruster      * if=scsi,index=12 no longer means bus=1,unit=5, but
10127d6bf40SMarkus Armbruster      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
10227d6bf40SMarkus Armbruster      * the drive can't be set up.  Regression.
10327d6bf40SMarkus Armbruster      */
10427d6bf40SMarkus Armbruster     [IF_IDE] = 2,
10527d6bf40SMarkus Armbruster     [IF_SCSI] = 7,
1061960966dSMarkus Armbruster };
1071960966dSMarkus Armbruster 
10821dff8cfSJohn Snow /**
10921dff8cfSJohn Snow  * Boards may call this to offer board-by-board overrides
11021dff8cfSJohn Snow  * of the default, global values.
11121dff8cfSJohn Snow  */
11221dff8cfSJohn Snow void override_max_devs(BlockInterfaceType type, int max_devs)
11321dff8cfSJohn Snow {
11418e46a03SMarkus Armbruster     BlockBackend *blk;
11521dff8cfSJohn Snow     DriveInfo *dinfo;
11621dff8cfSJohn Snow 
117c5be7445SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
118c5be7445SEmanuele Giuseppe Esposito 
11921dff8cfSJohn Snow     if (max_devs <= 0) {
12021dff8cfSJohn Snow         return;
12121dff8cfSJohn Snow     }
12221dff8cfSJohn Snow 
12318e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
12418e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
12521dff8cfSJohn Snow         if (dinfo->type == type) {
12621dff8cfSJohn Snow             fprintf(stderr, "Cannot override units-per-bus property of"
12721dff8cfSJohn Snow                     " the %s interface, because a drive of that type has"
12821dff8cfSJohn Snow                     " already been added.\n", if_name[type]);
12921dff8cfSJohn Snow             g_assert_not_reached();
13021dff8cfSJohn Snow         }
13121dff8cfSJohn Snow     }
13221dff8cfSJohn Snow 
13321dff8cfSJohn Snow     if_max_devs[type] = max_devs;
13421dff8cfSJohn Snow }
13521dff8cfSJohn Snow 
13614bafc54SMarkus Armbruster /*
13714bafc54SMarkus Armbruster  * We automatically delete the drive when a device using it gets
13814bafc54SMarkus Armbruster  * unplugged.  Questionable feature, but we can't just drop it.
13914bafc54SMarkus Armbruster  * Device models call blockdev_mark_auto_del() to schedule the
14014bafc54SMarkus Armbruster  * automatic deletion, and generic qdev code calls blockdev_auto_del()
14114bafc54SMarkus Armbruster  * when deletion is actually safe.
14214bafc54SMarkus Armbruster  */
1434be74634SMarkus Armbruster void blockdev_mark_auto_del(BlockBackend *blk)
14414bafc54SMarkus Armbruster {
14518e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
1468164102fSVladimir Sementsov-Ogievskiy     BlockJob *job;
14714bafc54SMarkus Armbruster 
148c5be7445SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
149c5be7445SEmanuele Giuseppe Esposito 
15026f8b3a8SMarkus Armbruster     if (!dinfo) {
1512d246f01SKevin Wolf         return;
1522d246f01SKevin Wolf     }
1532d246f01SKevin Wolf 
154880eeec6SEmanuele Giuseppe Esposito     JOB_LOCK_GUARD();
155880eeec6SEmanuele Giuseppe Esposito 
156e2626874SKevin Wolf     do {
157e2626874SKevin Wolf         job = block_job_next_locked(NULL);
158e2626874SKevin Wolf         while (job && (job->job.cancelled ||
159e2626874SKevin Wolf                        job->job.deferred_to_main_loop ||
160e2626874SKevin Wolf                        !block_job_has_bdrv(job, blk_bs(blk))))
161e2626874SKevin Wolf         {
162e2626874SKevin Wolf             job = block_job_next_locked(job);
163e2626874SKevin Wolf         }
164e2626874SKevin Wolf         if (job) {
165e2626874SKevin Wolf             /*
166e2626874SKevin Wolf              * This drops the job lock temporarily and polls, so we need to
167e2626874SKevin Wolf              * restart processing the list from the start after this.
168e2626874SKevin Wolf              */
169880eeec6SEmanuele Giuseppe Esposito             job_cancel_locked(&job->job, false);
1705433c24fSMax Reitz         }
171e2626874SKevin Wolf     } while (job);
17291fddb0dSStefan Hajnoczi 
17314bafc54SMarkus Armbruster     dinfo->auto_del = 1;
17414bafc54SMarkus Armbruster }
17514bafc54SMarkus Armbruster 
1764be74634SMarkus Armbruster void blockdev_auto_del(BlockBackend *blk)
17714bafc54SMarkus Armbruster {
17818e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
179c5be7445SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
18014bafc54SMarkus Armbruster 
1810fc0f1faSRyan Harper     if (dinfo && dinfo->auto_del) {
182efaa7c4eSMax Reitz         monitor_remove_blk(blk);
183b9fe8a7aSMarkus Armbruster         blk_unref(blk);
18414bafc54SMarkus Armbruster     }
18514bafc54SMarkus Armbruster }
18614bafc54SMarkus Armbruster 
187505a7fb1SMarkus Armbruster static int drive_index_to_bus_id(BlockInterfaceType type, int index)
188505a7fb1SMarkus Armbruster {
189505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
190505a7fb1SMarkus Armbruster     return max_devs ? index / max_devs : 0;
191505a7fb1SMarkus Armbruster }
192505a7fb1SMarkus Armbruster 
193505a7fb1SMarkus Armbruster static int drive_index_to_unit_id(BlockInterfaceType type, int index)
194505a7fb1SMarkus Armbruster {
195505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
196505a7fb1SMarkus Armbruster     return max_devs ? index % max_devs : index;
197505a7fb1SMarkus Armbruster }
198505a7fb1SMarkus Armbruster 
1992292ddaeSMarkus Armbruster QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
2005645b0f4SMarkus Armbruster                     const char *optstr)
201666daa68SMarkus Armbruster {
202666daa68SMarkus Armbruster     QemuOpts *opts;
203666daa68SMarkus Armbruster 
204c5be7445SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
205c5be7445SEmanuele Giuseppe Esposito 
206cc67f28eSEmanuele Giuseppe Esposito     opts = qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
207666daa68SMarkus Armbruster     if (!opts) {
208666daa68SMarkus Armbruster         return NULL;
209666daa68SMarkus Armbruster     }
2102292ddaeSMarkus Armbruster     if (type != IF_DEFAULT) {
211f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "if", if_name[type], &error_abort);
2122292ddaeSMarkus Armbruster     }
2132292ddaeSMarkus Armbruster     if (index >= 0) {
214a8b18f8fSMarkus Armbruster         qemu_opt_set_number(opts, "index", index, &error_abort);
2152292ddaeSMarkus Armbruster     }
216666daa68SMarkus Armbruster     if (file)
217f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "file", file, &error_abort);
218666daa68SMarkus Armbruster     return opts;
219666daa68SMarkus Armbruster }
220666daa68SMarkus Armbruster 
221666daa68SMarkus Armbruster DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
222666daa68SMarkus Armbruster {
22318e46a03SMarkus Armbruster     BlockBackend *blk;
224666daa68SMarkus Armbruster     DriveInfo *dinfo;
225666daa68SMarkus Armbruster 
226c5be7445SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
227c5be7445SEmanuele Giuseppe Esposito 
22818e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
22918e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
23018e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type
23118e46a03SMarkus Armbruster             && dinfo->bus == bus && dinfo->unit == unit) {
232666daa68SMarkus Armbruster             return dinfo;
233666daa68SMarkus Armbruster         }
23418e46a03SMarkus Armbruster     }
235666daa68SMarkus Armbruster 
236666daa68SMarkus Armbruster     return NULL;
237666daa68SMarkus Armbruster }
238666daa68SMarkus Armbruster 
239fe9f70a1SMarkus Armbruster /*
240fe9f70a1SMarkus Armbruster  * Check board claimed all -drive that are meant to be claimed.
241fe9f70a1SMarkus Armbruster  * Fatal error if any remain unclaimed.
242fe9f70a1SMarkus Armbruster  */
243720b8dc0SMarkus Armbruster void drive_check_orphaned(void)
244a66c9dc7SJohn Snow {
24518e46a03SMarkus Armbruster     BlockBackend *blk;
246a66c9dc7SJohn Snow     DriveInfo *dinfo;
247664cc623SMarkus Armbruster     Location loc;
248720b8dc0SMarkus Armbruster     bool orphans = false;
249a66c9dc7SJohn Snow 
250c5be7445SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
251c5be7445SEmanuele Giuseppe Esposito 
25218e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
25318e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
254fe9f70a1SMarkus Armbruster         /*
255fe9f70a1SMarkus Armbruster          * Ignore default drives, because we create certain default
256fe9f70a1SMarkus Armbruster          * drives unconditionally, then leave them unclaimed.  Not the
257fe9f70a1SMarkus Armbruster          * users fault.
258fe9f70a1SMarkus Armbruster          * Ignore IF_VIRTIO, because it gets desugared into -device,
259fe9f70a1SMarkus Armbruster          * so we can leave failing to -device.
260fe9f70a1SMarkus Armbruster          * Ignore IF_NONE, because leaving unclaimed IF_NONE remains
261fe9f70a1SMarkus Armbruster          * available for device_add is a feature.
262fe9f70a1SMarkus Armbruster          */
263fe9f70a1SMarkus Armbruster         if (dinfo->is_default || dinfo->type == IF_VIRTIO
264fe9f70a1SMarkus Armbruster             || 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;
275a66c9dc7SJohn Snow         }
276a66c9dc7SJohn Snow     }
277a66c9dc7SJohn Snow 
278720b8dc0SMarkus Armbruster     if (orphans) {
279720b8dc0SMarkus Armbruster         exit(1);
280720b8dc0SMarkus Armbruster     }
281a66c9dc7SJohn Snow }
282a66c9dc7SJohn Snow 
283f1bd51acSMarkus Armbruster DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
284f1bd51acSMarkus Armbruster {
285c5be7445SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
286f1bd51acSMarkus Armbruster     return drive_get(type,
287f1bd51acSMarkus Armbruster                      drive_index_to_bus_id(type, index),
288f1bd51acSMarkus Armbruster                      drive_index_to_unit_id(type, index));
289f1bd51acSMarkus Armbruster }
290f1bd51acSMarkus Armbruster 
291666daa68SMarkus Armbruster int drive_get_max_bus(BlockInterfaceType type)
292666daa68SMarkus Armbruster {
293666daa68SMarkus Armbruster     int max_bus;
29418e46a03SMarkus Armbruster     BlockBackend *blk;
295666daa68SMarkus Armbruster     DriveInfo *dinfo;
296666daa68SMarkus Armbruster 
297c5be7445SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
298c5be7445SEmanuele Giuseppe Esposito 
299666daa68SMarkus Armbruster     max_bus = -1;
30018e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
30118e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
30218e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
303666daa68SMarkus Armbruster             max_bus = dinfo->bus;
304666daa68SMarkus Armbruster         }
30518e46a03SMarkus Armbruster     }
306666daa68SMarkus Armbruster     return max_bus;
307666daa68SMarkus Armbruster }
308666daa68SMarkus Armbruster 
309666daa68SMarkus Armbruster static void bdrv_format_print(void *opaque, const char *name)
310666daa68SMarkus Armbruster {
311cdcd4361SMarkus Armbruster     qemu_printf(" %s", name);
312666daa68SMarkus Armbruster }
313666daa68SMarkus Armbruster 
314aa398a5cSStefan Hajnoczi typedef struct {
315aa398a5cSStefan Hajnoczi     QEMUBH *bh;
316fa510ebfSFam Zheng     BlockDriverState *bs;
317fa510ebfSFam Zheng } BDRVPutRefBH;
318aa398a5cSStefan Hajnoczi 
319b681072dSKevin Wolf static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
320666daa68SMarkus Armbruster {
321666daa68SMarkus Armbruster     if (!strcmp(buf, "ignore")) {
32292aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_IGNORE;
323666daa68SMarkus Armbruster     } else if (!is_read && !strcmp(buf, "enospc")) {
32492aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_ENOSPC;
325666daa68SMarkus Armbruster     } else if (!strcmp(buf, "stop")) {
32692aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_STOP;
327666daa68SMarkus Armbruster     } else if (!strcmp(buf, "report")) {
32892aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_REPORT;
329666daa68SMarkus Armbruster     } else {
330b681072dSKevin Wolf         error_setg(errp, "'%s' invalid %s error action",
331666daa68SMarkus Armbruster                    buf, is_read ? "read" : "write");
332666daa68SMarkus Armbruster         return -1;
333666daa68SMarkus Armbruster     }
334666daa68SMarkus Armbruster }
335666daa68SMarkus Armbruster 
33640119effSAlberto Garcia static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
33740119effSAlberto Garcia                                   Error **errp)
33840119effSAlberto Garcia {
33940119effSAlberto Garcia     const QListEntry *entry;
34040119effSAlberto Garcia     for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
34140119effSAlberto Garcia         switch (qobject_type(entry->value)) {
34240119effSAlberto Garcia 
34340119effSAlberto Garcia         case QTYPE_QSTRING: {
34440119effSAlberto Garcia             unsigned long long length;
3457dc847ebSMax Reitz             const char *str = qstring_get_str(qobject_to(QString,
3467dc847ebSMax Reitz                                                          entry->value));
34740119effSAlberto Garcia             if (parse_uint_full(str, &length, 10) == 0 &&
34840119effSAlberto Garcia                 length > 0 && length <= UINT_MAX) {
34940119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
35040119effSAlberto Garcia             } else {
35140119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %s", str);
35240119effSAlberto Garcia                 return false;
35340119effSAlberto Garcia             }
35440119effSAlberto Garcia             break;
35540119effSAlberto Garcia         }
35640119effSAlberto Garcia 
35701b2ffceSMarc-André Lureau         case QTYPE_QNUM: {
3587dc847ebSMax Reitz             int64_t length = qnum_get_int(qobject_to(QNum, entry->value));
35901b2ffceSMarc-André Lureau 
36040119effSAlberto Garcia             if (length > 0 && length <= UINT_MAX) {
36140119effSAlberto Garcia                 block_acct_add_interval(stats, (unsigned) length);
36240119effSAlberto Garcia             } else {
36340119effSAlberto Garcia                 error_setg(errp, "Invalid interval length: %" PRId64, length);
36440119effSAlberto Garcia                 return false;
36540119effSAlberto Garcia             }
36640119effSAlberto Garcia             break;
36740119effSAlberto Garcia         }
36840119effSAlberto Garcia 
36940119effSAlberto Garcia         default:
37040119effSAlberto Garcia             error_setg(errp, "The specification of stats-intervals is invalid");
37140119effSAlberto Garcia             return false;
37240119effSAlberto Garcia         }
37340119effSAlberto Garcia     }
37440119effSAlberto Garcia     return true;
37540119effSAlberto Garcia }
37640119effSAlberto Garcia 
37733cb7dc8SKevin Wolf typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
37833cb7dc8SKevin Wolf 
379fbf8175eSMax Reitz /* All parameters but @opts are optional and may be set to NULL. */
380fbf8175eSMax Reitz static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
381fbf8175eSMax Reitz     const char **throttling_group, ThrottleConfig *throttle_cfg,
382fbf8175eSMax Reitz     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
383fbf8175eSMax Reitz {
384fbf8175eSMax Reitz     Error *local_error = NULL;
385fbf8175eSMax Reitz     const char *aio;
386fbf8175eSMax Reitz 
387fbf8175eSMax Reitz     if (bdrv_flags) {
388fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
389fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_COPY_ON_READ;
390fbf8175eSMax Reitz         }
391fbf8175eSMax Reitz 
392fbf8175eSMax Reitz         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
393f80f2673SAarushi Mehta             if (bdrv_parse_aio(aio, bdrv_flags) < 0) {
394fbf8175eSMax Reitz                 error_setg(errp, "invalid aio option");
395fbf8175eSMax Reitz                 return;
396fbf8175eSMax Reitz             }
397fbf8175eSMax Reitz         }
398fbf8175eSMax Reitz     }
399fbf8175eSMax Reitz 
400fbf8175eSMax Reitz     /* disk I/O throttling */
401fbf8175eSMax Reitz     if (throttling_group) {
402fbf8175eSMax Reitz         *throttling_group = qemu_opt_get(opts, "throttling.group");
403fbf8175eSMax Reitz     }
404fbf8175eSMax Reitz 
405fbf8175eSMax Reitz     if (throttle_cfg) {
4061588ab5dSAlberto Garcia         throttle_config_init(throttle_cfg);
407fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
408fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total", 0);
409fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
410fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read", 0);
411fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
412fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write", 0);
413fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
414fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total", 0);
415fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
416fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read", 0);
417fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
418fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write", 0);
419fbf8175eSMax Reitz 
420fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
421fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
422fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
423fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
424fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
425fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
426fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
427fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
428fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
429fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
430fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
431fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
432fbf8175eSMax Reitz 
4338a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
4348a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
4358a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length  =
4368a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
4378a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
4388a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
4398a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
4408a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
4418a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
4428a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
4438a0fc18dSAlberto Garcia         throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
4448a0fc18dSAlberto Garcia             qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
4458a0fc18dSAlberto Garcia 
446fbf8175eSMax Reitz         throttle_cfg->op_size =
447fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-size", 0);
448fbf8175eSMax Reitz 
449d5851089SAlberto Garcia         if (!throttle_is_valid(throttle_cfg, errp)) {
450fbf8175eSMax Reitz             return;
451fbf8175eSMax Reitz         }
452fbf8175eSMax Reitz     }
453fbf8175eSMax Reitz 
454fbf8175eSMax Reitz     if (detect_zeroes) {
455fbf8175eSMax Reitz         *detect_zeroes =
456f7abe0ecSMarc-André Lureau             qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
457fbf8175eSMax Reitz                             qemu_opt_get(opts, "detect-zeroes"),
458fbf8175eSMax Reitz                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
459fbf8175eSMax Reitz                             &local_error);
460fbf8175eSMax Reitz         if (local_error) {
461fbf8175eSMax Reitz             error_propagate(errp, local_error);
462fbf8175eSMax Reitz             return;
463fbf8175eSMax Reitz         }
464fbf8175eSMax Reitz     }
465fbf8175eSMax Reitz }
466fbf8175eSMax Reitz 
467b2aaf354SDenis V. Lunev static OnOffAuto account_get_opt(QemuOpts *opts, const char *name)
468b2aaf354SDenis V. Lunev {
469b2aaf354SDenis V. Lunev     if (!qemu_opt_find(opts, name)) {
470b2aaf354SDenis V. Lunev         return ON_OFF_AUTO_AUTO;
471b2aaf354SDenis V. Lunev     }
472b2aaf354SDenis V. Lunev     if (qemu_opt_get_bool(opts, name, true)) {
473b2aaf354SDenis V. Lunev         return ON_OFF_AUTO_ON;
474b2aaf354SDenis V. Lunev     }
475b2aaf354SDenis V. Lunev     return ON_OFF_AUTO_OFF;
476b2aaf354SDenis V. Lunev }
477b2aaf354SDenis V. Lunev 
478f298d071SKevin Wolf /* Takes the ownership of bs_opts */
47918e46a03SMarkus Armbruster static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
480b681072dSKevin Wolf                                    Error **errp)
481666daa68SMarkus Armbruster {
482666daa68SMarkus Armbruster     const char *buf;
483666daa68SMarkus Armbruster     int bdrv_flags = 0;
484666daa68SMarkus Armbruster     int on_read_error, on_write_error;
485b2aaf354SDenis V. Lunev     OnOffAuto account_invalid, account_failed;
486f87a0e29SAlberto Garcia     bool writethrough, read_only;
48726f54e9aSMarkus Armbruster     BlockBackend *blk;
488a0f1eab1SMarkus Armbruster     BlockDriverState *bs;
489cc0681c4SBenoît Canet     ThrottleConfig cfg;
490666daa68SMarkus Armbruster     int snapshot = 0;
491c546194fSStefan Hajnoczi     Error *error = NULL;
4920006383eSKevin Wolf     QemuOpts *opts;
49340119effSAlberto Garcia     QDict *interval_dict = NULL;
49440119effSAlberto Garcia     QList *interval_list = NULL;
4950006383eSKevin Wolf     const char *id;
496fbf8175eSMax Reitz     BlockdevDetectZeroesOptions detect_zeroes =
497fbf8175eSMax Reitz         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
498fbf8175eSMax Reitz     const char *throttling_group = NULL;
499666daa68SMarkus Armbruster 
500f298d071SKevin Wolf     /* Check common options by copying from bs_opts to opts, all other options
501f298d071SKevin Wolf      * stay in bs_opts for processing by bdrv_open(). */
502f298d071SKevin Wolf     id = qdict_get_try_str(bs_opts, "id");
503c6ecec43SMarkus Armbruster     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, errp);
504c6ecec43SMarkus Armbruster     if (!opts) {
5056376f952SMarkus Armbruster         goto err_no_opts;
5060006383eSKevin Wolf     }
5070006383eSKevin Wolf 
508668f62ecSMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, bs_opts, errp)) {
509ec9c10d2SStefan Hajnoczi         goto early_err;
5100006383eSKevin Wolf     }
5110006383eSKevin Wolf 
5120006383eSKevin Wolf     if (id) {
5130006383eSKevin Wolf         qdict_del(bs_opts, "id");
5140006383eSKevin Wolf     }
5150006383eSKevin Wolf 
516666daa68SMarkus Armbruster     /* extract parameters */
517666daa68SMarkus Armbruster     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
518666daa68SMarkus Armbruster 
519b2aaf354SDenis V. Lunev     account_invalid = account_get_opt(opts, "stats-account-invalid");
520b2aaf354SDenis V. Lunev     account_failed = account_get_opt(opts, "stats-account-failed");
521362e9299SAlberto Garcia 
522e4b24b49SKevin Wolf     writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
523e4b24b49SKevin Wolf 
524ff356ee4SAlberto Garcia     id = qemu_opts_id(opts);
525ff356ee4SAlberto Garcia 
52640119effSAlberto Garcia     qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
52740119effSAlberto Garcia     qdict_array_split(interval_dict, &interval_list);
52840119effSAlberto Garcia 
52940119effSAlberto Garcia     if (qdict_size(interval_dict) != 0) {
53040119effSAlberto Garcia         error_setg(errp, "Invalid option stats-intervals.%s",
53140119effSAlberto Garcia                    qdict_first(interval_dict)->key);
53240119effSAlberto Garcia         goto early_err;
53340119effSAlberto Garcia     }
5342be5506fSAlberto Garcia 
535fbf8175eSMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
536fbf8175eSMax Reitz                                     &detect_zeroes, &error);
537fbf8175eSMax Reitz     if (error) {
538fbf8175eSMax Reitz         error_propagate(errp, error);
539ec9c10d2SStefan Hajnoczi         goto early_err;
540a9384affSPaolo Bonzini     }
541666daa68SMarkus Armbruster 
542666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
543c8057f95SPeter Maydell         if (is_help_option(buf)) {
544cdcd4361SMarkus Armbruster             qemu_printf("Supported formats:");
5459ac404c5SAndrey Shinkevich             bdrv_iterate_format(bdrv_format_print, NULL, false);
546cdcd4361SMarkus Armbruster             qemu_printf("\nSupported formats (read-only):");
5479ac404c5SAndrey Shinkevich             bdrv_iterate_format(bdrv_format_print, NULL, true);
548cdcd4361SMarkus Armbruster             qemu_printf("\n");
549ec9c10d2SStefan Hajnoczi             goto early_err;
550666daa68SMarkus Armbruster         }
55174fe54f2SKevin Wolf 
552e4342ce5SMax Reitz         if (qdict_haskey(bs_opts, "driver")) {
553e4342ce5SMax Reitz             error_setg(errp, "Cannot specify both 'driver' and 'format'");
554ec9c10d2SStefan Hajnoczi             goto early_err;
5556db5f5d6SMike Qiu         }
55646f5ac20SEric Blake         qdict_put_str(bs_opts, "driver", buf);
557666daa68SMarkus Armbruster     }
558666daa68SMarkus Armbruster 
55992aa5c6dSPaolo Bonzini     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
560666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
561b681072dSKevin Wolf         on_write_error = parse_block_error_action(buf, 0, &error);
56284d18f06SMarkus Armbruster         if (error) {
563b681072dSKevin Wolf             error_propagate(errp, error);
564ec9c10d2SStefan Hajnoczi             goto early_err;
565666daa68SMarkus Armbruster         }
566666daa68SMarkus Armbruster     }
567666daa68SMarkus Armbruster 
56892aa5c6dSPaolo Bonzini     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
569666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
570b681072dSKevin Wolf         on_read_error = parse_block_error_action(buf, 1, &error);
57184d18f06SMarkus Armbruster         if (error) {
572b681072dSKevin Wolf             error_propagate(errp, error);
573ec9c10d2SStefan Hajnoczi             goto early_err;
574666daa68SMarkus Armbruster         }
575666daa68SMarkus Armbruster     }
576666daa68SMarkus Armbruster 
577666daa68SMarkus Armbruster     if (snapshot) {
57891a097e7SKevin Wolf         bdrv_flags |= BDRV_O_SNAPSHOT;
579666daa68SMarkus Armbruster     }
580666daa68SMarkus Armbruster 
581f87a0e29SAlberto Garcia     read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
582f87a0e29SAlberto Garcia 
5835ec18f8cSMax Reitz     /* init */
58439c4ae94SKevin Wolf     if ((!file || !*file) && !qdict_size(bs_opts)) {
5855ec18f8cSMax Reitz         BlockBackendRootState *blk_rs;
5865ec18f8cSMax Reitz 
587d861ab3aSKevin Wolf         blk = blk_new(qemu_get_aio_context(), 0, BLK_PERM_ALL);
5885ec18f8cSMax Reitz         blk_rs = blk_get_root_state(blk);
589260242a8SVladimir Sementsov-Ogievskiy         blk_rs->open_flags    = bdrv_flags | (read_only ? 0 : BDRV_O_RDWR);
5905ec18f8cSMax Reitz         blk_rs->detect_zeroes = detect_zeroes;
5915ec18f8cSMax Reitz 
592cb3e7f08SMarc-André Lureau         qobject_unref(bs_opts);
5935ec18f8cSMax Reitz     } else {
5945ec18f8cSMax Reitz         if (file && !*file) {
5955ec18f8cSMax Reitz             file = NULL;
5965ec18f8cSMax Reitz         }
5975ec18f8cSMax Reitz 
59891a097e7SKevin Wolf         /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
59991a097e7SKevin Wolf          * with other callers) rather than what we want as the real defaults.
60091a097e7SKevin Wolf          * Apply the defaults here instead. */
60191a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
60291a097e7SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
603f87a0e29SAlberto Garcia         qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
604f87a0e29SAlberto Garcia                               read_only ? "on" : "off");
6059384a444SKevin Wolf         qdict_set_default_str(bs_opts, BDRV_OPT_AUTO_READ_ONLY, "on");
60672e775c7SKevin Wolf         assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
60791a097e7SKevin Wolf 
60812d5ee3aSKevin Wolf         if (runstate_check(RUN_STATE_INMIGRATE)) {
60912d5ee3aSKevin Wolf             bdrv_flags |= BDRV_O_INACTIVE;
61012d5ee3aSKevin Wolf         }
61112d5ee3aSKevin Wolf 
612efaa7c4eSMax Reitz         blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
613e4342ce5SMax Reitz         if (!blk) {
614e4342ce5SMax Reitz             goto err_no_bs_opts;
615e4342ce5SMax Reitz         }
616e4342ce5SMax Reitz         bs = blk_bs(blk);
6170006383eSKevin Wolf 
618e4342ce5SMax Reitz         bs->detect_zeroes = detect_zeroes;
619e4342ce5SMax Reitz 
6209caa6f3dSPaolo Bonzini         block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
6212be5506fSAlberto Garcia 
62240119effSAlberto Garcia         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
6232be5506fSAlberto Garcia             blk_unref(blk);
6242be5506fSAlberto Garcia             blk = NULL;
6252be5506fSAlberto Garcia             goto err_no_bs_opts;
6262be5506fSAlberto Garcia         }
6272be5506fSAlberto Garcia     }
6285ec18f8cSMax Reitz 
6297ca7f0f6SKevin Wolf     /* disk I/O throttling */
6307ca7f0f6SKevin Wolf     if (throttle_enabled(&cfg)) {
6317ca7f0f6SKevin Wolf         if (!throttling_group) {
632ff356ee4SAlberto Garcia             throttling_group = id;
6337ca7f0f6SKevin Wolf         }
6347ca7f0f6SKevin Wolf         blk_io_limits_enable(blk, throttling_group);
6357ca7f0f6SKevin Wolf         blk_set_io_limits(blk, &cfg);
6367ca7f0f6SKevin Wolf     }
6377ca7f0f6SKevin Wolf 
638e4b24b49SKevin Wolf     blk_set_enable_write_cache(blk, !writethrough);
6395ec18f8cSMax Reitz     blk_set_on_error(blk, on_read_error, on_write_error);
6400006383eSKevin Wolf 
641ff356ee4SAlberto Garcia     if (!monitor_add_blk(blk, id, errp)) {
642efaa7c4eSMax Reitz         blk_unref(blk);
643efaa7c4eSMax Reitz         blk = NULL;
644efaa7c4eSMax Reitz         goto err_no_bs_opts;
645efaa7c4eSMax Reitz     }
646efaa7c4eSMax Reitz 
647e4342ce5SMax Reitz err_no_bs_opts:
6480006383eSKevin Wolf     qemu_opts_del(opts);
649cb3e7f08SMarc-André Lureau     qobject_unref(interval_dict);
650cb3e7f08SMarc-André Lureau     qobject_unref(interval_list);
65118e46a03SMarkus Armbruster     return blk;
652a9ae2bffSMarkus Armbruster 
653ec9c10d2SStefan Hajnoczi early_err:
654ec9c10d2SStefan Hajnoczi     qemu_opts_del(opts);
655cb3e7f08SMarc-André Lureau     qobject_unref(interval_dict);
656cb3e7f08SMarc-André Lureau     qobject_unref(interval_list);
6576376f952SMarkus Armbruster err_no_opts:
658cb3e7f08SMarc-André Lureau     qobject_unref(bs_opts);
659a9ae2bffSMarkus Armbruster     return NULL;
660666daa68SMarkus Armbruster }
661666daa68SMarkus Armbruster 
662bd745e23SMax Reitz /* Takes the ownership of bs_opts */
66389802d5aSMaxim Levitsky BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
664bd745e23SMax Reitz {
665bd745e23SMax Reitz     int bdrv_flags = 0;
666bd745e23SMax Reitz 
667b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
668a81d6164SKevin Wolf     /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
669a81d6164SKevin Wolf      * with other callers) rather than what we want as the real defaults.
670a81d6164SKevin Wolf      * Apply the defaults here instead. */
671a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
672a81d6164SKevin Wolf     qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
673f87a0e29SAlberto Garcia     qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
674a81d6164SKevin Wolf 
67512d5ee3aSKevin Wolf     if (runstate_check(RUN_STATE_INMIGRATE)) {
67612d5ee3aSKevin Wolf         bdrv_flags |= BDRV_O_INACTIVE;
67712d5ee3aSKevin Wolf     }
67812d5ee3aSKevin Wolf 
67974e1ae7cSKevin Wolf     return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
680bd745e23SMax Reitz }
681bd745e23SMax Reitz 
6829c4218e9SMax Reitz void blockdev_close_all_bdrv_states(void)
6839c4218e9SMax Reitz {
6849c4218e9SMax Reitz     BlockDriverState *bs, *next_bs;
6859c4218e9SMax Reitz 
686b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6879c4218e9SMax Reitz     QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
6889c4218e9SMax Reitz         AioContext *ctx = bdrv_get_aio_context(bs);
6899c4218e9SMax Reitz 
6909c4218e9SMax Reitz         aio_context_acquire(ctx);
6919c4218e9SMax Reitz         bdrv_unref(bs);
6929c4218e9SMax Reitz         aio_context_release(ctx);
6939c4218e9SMax Reitz     }
6949c4218e9SMax Reitz }
6959c4218e9SMax Reitz 
696262b4e8fSMax Reitz /* Iterates over the list of monitor-owned BlockDriverStates */
697262b4e8fSMax Reitz BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
698262b4e8fSMax Reitz {
699f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
700262b4e8fSMax Reitz     return bs ? QTAILQ_NEXT(bs, monitor_list)
701262b4e8fSMax Reitz               : QTAILQ_FIRST(&monitor_bdrv_states);
702262b4e8fSMax Reitz }
703262b4e8fSMax Reitz 
704c75d7f71SMarkus Armbruster static bool qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
7055abbf0eeSKevin Wolf                             Error **errp)
70657975222SKevin Wolf {
70757975222SKevin Wolf     const char *value;
70857975222SKevin Wolf 
70957975222SKevin Wolf     value = qemu_opt_get(opts, from);
71057975222SKevin Wolf     if (value) {
7115abbf0eeSKevin Wolf         if (qemu_opt_find(opts, to)) {
7125abbf0eeSKevin Wolf             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
7135abbf0eeSKevin Wolf                        "same time", to, from);
714c75d7f71SMarkus Armbruster             return false;
7155abbf0eeSKevin Wolf         }
71620d6cd47SJun Li     }
71720d6cd47SJun Li 
71820d6cd47SJun Li     /* rename all items in opts */
71920d6cd47SJun Li     while ((value = qemu_opt_get(opts, from))) {
720f43e47dbSMarkus Armbruster         qemu_opt_set(opts, to, value, &error_abort);
72157975222SKevin Wolf         qemu_opt_unset(opts, from);
72257975222SKevin Wolf     }
723c75d7f71SMarkus Armbruster     return true;
72457975222SKevin Wolf }
72557975222SKevin Wolf 
72633cb7dc8SKevin Wolf QemuOptsList qemu_legacy_drive_opts = {
72733cb7dc8SKevin Wolf     .name = "drive",
72833cb7dc8SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
72933cb7dc8SKevin Wolf     .desc = {
73033cb7dc8SKevin Wolf         {
73187a899c5SKevin Wolf             .name = "bus",
73287a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
73387a899c5SKevin Wolf             .help = "bus number",
73487a899c5SKevin Wolf         },{
73587a899c5SKevin Wolf             .name = "unit",
73687a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
73787a899c5SKevin Wolf             .help = "unit number (i.e. lun for scsi)",
73887a899c5SKevin Wolf         },{
73987a899c5SKevin Wolf             .name = "index",
74087a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
74187a899c5SKevin Wolf             .help = "index number",
74287a899c5SKevin Wolf         },{
74333cb7dc8SKevin Wolf             .name = "media",
74433cb7dc8SKevin Wolf             .type = QEMU_OPT_STRING,
74533cb7dc8SKevin Wolf             .help = "media type (disk, cdrom)",
746593d464bSKevin Wolf         },{
747593d464bSKevin Wolf             .name = "if",
748593d464bSKevin Wolf             .type = QEMU_OPT_STRING,
749593d464bSKevin Wolf             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
750b41a7338SKevin Wolf         },{
751d095b465SMax Reitz             .name = "file",
752d095b465SMax Reitz             .type = QEMU_OPT_STRING,
753d095b465SMax Reitz             .help = "file name",
75433cb7dc8SKevin Wolf         },
7550ebd24e0SKevin Wolf 
7560ebd24e0SKevin Wolf         /* Options that are passed on, but have special semantics with -drive */
7570ebd24e0SKevin Wolf         {
7584e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
7590ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
7600ebd24e0SKevin Wolf             .help = "open drive file as read-only",
7610ebd24e0SKevin Wolf         },{
762ee13ed1cSKevin Wolf             .name = "rerror",
763ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
764ee13ed1cSKevin Wolf             .help = "read error action",
765ee13ed1cSKevin Wolf         },{
766ee13ed1cSKevin Wolf             .name = "werror",
767ee13ed1cSKevin Wolf             .type = QEMU_OPT_STRING,
768ee13ed1cSKevin Wolf             .help = "write error action",
769ee13ed1cSKevin Wolf         },{
7700ebd24e0SKevin Wolf             .name = "copy-on-read",
7710ebd24e0SKevin Wolf             .type = QEMU_OPT_BOOL,
7720ebd24e0SKevin Wolf             .help = "copy read data from backing file into image file",
7730ebd24e0SKevin Wolf         },
7740ebd24e0SKevin Wolf 
77533cb7dc8SKevin Wolf         { /* end of list */ }
77633cb7dc8SKevin Wolf     },
77733cb7dc8SKevin Wolf };
77833cb7dc8SKevin Wolf 
779c4f26c9fSMarkus Armbruster DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
780c4f26c9fSMarkus Armbruster                      Error **errp)
78157975222SKevin Wolf {
78229c4e2b5SKevin Wolf     const char *value;
78318e46a03SMarkus Armbruster     BlockBackend *blk;
78433cb7dc8SKevin Wolf     DriveInfo *dinfo = NULL;
785f298d071SKevin Wolf     QDict *bs_opts;
78633cb7dc8SKevin Wolf     QemuOpts *legacy_opts;
78733cb7dc8SKevin Wolf     DriveMediaType media = MEDIA_DISK;
788593d464bSKevin Wolf     BlockInterfaceType type;
78987a899c5SKevin Wolf     int max_devs, bus_id, unit_id, index;
790ee13ed1cSKevin Wolf     const char *werror, *rerror;
791a7fdbcf0SFam Zheng     bool read_only = false;
792a7fdbcf0SFam Zheng     bool copy_on_read;
793d095b465SMax Reitz     const char *filename;
794247147fbSKevin Wolf     int i;
79529c4e2b5SKevin Wolf 
796c5be7445SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
797c5be7445SEmanuele Giuseppe Esposito 
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);
9729db1d3a2SLaurent Vivier         qemu_opt_set(devopts, "driver", "virtio-blk", &error_abort);
973f43e47dbSMarkus Armbruster         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
974f43e47dbSMarkus Armbruster                      &error_abort);
975394c7d4dSKevin Wolf     }
976394c7d4dSKevin Wolf 
977d095b465SMax Reitz     filename = qemu_opt_get(legacy_opts, "file");
978d095b465SMax Reitz 
979ee13ed1cSKevin Wolf     /* Check werror/rerror compatibility with if=... */
980ee13ed1cSKevin Wolf     werror = qemu_opt_get(legacy_opts, "werror");
981ee13ed1cSKevin Wolf     if (werror != NULL) {
982ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
983ee13ed1cSKevin Wolf             type != IF_NONE) {
984c4f26c9fSMarkus Armbruster             error_setg(errp, "werror is not supported by this bus type");
985ee13ed1cSKevin Wolf             goto fail;
986ee13ed1cSKevin Wolf         }
98746f5ac20SEric Blake         qdict_put_str(bs_opts, "werror", werror);
988ee13ed1cSKevin Wolf     }
989ee13ed1cSKevin Wolf 
990ee13ed1cSKevin Wolf     rerror = qemu_opt_get(legacy_opts, "rerror");
991ee13ed1cSKevin Wolf     if (rerror != NULL) {
992ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
993ee13ed1cSKevin Wolf             type != IF_NONE) {
994c4f26c9fSMarkus Armbruster             error_setg(errp, "rerror is not supported by this bus type");
995ee13ed1cSKevin Wolf             goto fail;
996ee13ed1cSKevin Wolf         }
99746f5ac20SEric Blake         qdict_put_str(bs_opts, "rerror", rerror);
998ee13ed1cSKevin Wolf     }
999ee13ed1cSKevin Wolf 
10002d246f01SKevin Wolf     /* Actual block device init: Functionality shared with blockdev-add */
1001992861fbSMarkus Armbruster     blk = blockdev_init(filename, bs_opts, errp);
10023cb0e25cSMarkus Armbruster     bs_opts = NULL;
100318e46a03SMarkus Armbruster     if (!blk) {
10042d246f01SKevin Wolf         goto fail;
10052d246f01SKevin Wolf     }
10062d246f01SKevin Wolf 
100726f8b3a8SMarkus Armbruster     /* Create legacy DriveInfo */
100826f8b3a8SMarkus Armbruster     dinfo = g_malloc0(sizeof(*dinfo));
1009f298d071SKevin Wolf     dinfo->opts = all_opts;
10102d246f01SKevin Wolf 
1011ee13ed1cSKevin Wolf     dinfo->type = type;
101287a899c5SKevin Wolf     dinfo->bus = bus_id;
101387a899c5SKevin Wolf     dinfo->unit = unit_id;
1014bcf83158SKevin Wolf 
101526f8b3a8SMarkus Armbruster     blk_set_legacy_dinfo(blk, dinfo);
101626f8b3a8SMarkus Armbruster 
1017e34ef046SKevin Wolf     switch(type) {
1018e34ef046SKevin Wolf     case IF_IDE:
1019e34ef046SKevin Wolf     case IF_SCSI:
1020e34ef046SKevin Wolf     case IF_XEN:
1021e34ef046SKevin Wolf     case IF_NONE:
1022e34ef046SKevin Wolf         dinfo->media_cd = media == MEDIA_CDROM;
1023e34ef046SKevin Wolf         break;
1024e34ef046SKevin Wolf     default:
1025e34ef046SKevin Wolf         break;
1026e34ef046SKevin Wolf     }
1027e34ef046SKevin Wolf 
10282d246f01SKevin Wolf fail:
102933cb7dc8SKevin Wolf     qemu_opts_del(legacy_opts);
1030cb3e7f08SMarc-André Lureau     qobject_unref(bs_opts);
10312d246f01SKevin Wolf     return dinfo;
103257975222SKevin Wolf }
103357975222SKevin Wolf 
1034b6c1bae5SKevin Wolf static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1035b6c1bae5SKevin Wolf {
1036b6c1bae5SKevin Wolf     BlockDriverState *bs;
10371e97be91SEmanuele Giuseppe Esposito     AioContext *aio_context;
1038b6c1bae5SKevin Wolf 
1039b6c1bae5SKevin Wolf     bs = bdrv_lookup_bs(name, name, errp);
1040b6c1bae5SKevin Wolf     if (bs == NULL) {
1041b6c1bae5SKevin Wolf         return NULL;
1042b6c1bae5SKevin Wolf     }
1043b6c1bae5SKevin Wolf 
1044b6c1bae5SKevin Wolf     if (!bdrv_is_root_node(bs)) {
1045b6c1bae5SKevin Wolf         error_setg(errp, "Need a root block node");
1046b6c1bae5SKevin Wolf         return NULL;
1047b6c1bae5SKevin Wolf     }
1048b6c1bae5SKevin Wolf 
10491e97be91SEmanuele Giuseppe Esposito     aio_context = bdrv_get_aio_context(bs);
10501e97be91SEmanuele Giuseppe Esposito     aio_context_acquire(aio_context);
10511e97be91SEmanuele Giuseppe Esposito 
1052b6c1bae5SKevin Wolf     if (!bdrv_is_inserted(bs)) {
1053b6c1bae5SKevin Wolf         error_setg(errp, "Device has no medium");
10541e97be91SEmanuele Giuseppe Esposito         bs = NULL;
1055b6c1bae5SKevin Wolf     }
1056b6c1bae5SKevin Wolf 
10571e97be91SEmanuele Giuseppe Esposito     aio_context_release(aio_context);
10581e97be91SEmanuele Giuseppe Esposito 
1059b6c1bae5SKevin Wolf     return bs;
1060b6c1bae5SKevin Wolf }
1061b6c1bae5SKevin Wolf 
106210f75907SEric Blake static void blockdev_do_action(TransactionAction *action, Error **errp)
10636cc2a415SPaolo Bonzini {
1064c8a83e85SKevin Wolf     TransactionActionList list;
10656cc2a415SPaolo Bonzini 
106610f75907SEric Blake     list.value = action;
10676cc2a415SPaolo Bonzini     list.next = NULL;
1068238e9202SMarkus Armbruster     qmp_transaction(&list, NULL, errp);
10696cc2a415SPaolo Bonzini }
10706cc2a415SPaolo Bonzini 
107154fde4ffSMarkus Armbruster void qmp_blockdev_snapshot_sync(const char *device, const char *node_name,
10720901f67eSBenoît Canet                                 const char *snapshot_file,
10730901f67eSBenoît Canet                                 const char *snapshot_node_name,
107454fde4ffSMarkus Armbruster                                 const char *format,
10750901f67eSBenoît Canet                                 bool has_mode, NewImageMode mode, Error **errp)
1076f8882568SJes Sorensen {
1077a911e6aeSAlberto Garcia     BlockdevSnapshotSync snapshot = {
10786cc2a415SPaolo Bonzini         .device = (char *) device,
10790901f67eSBenoît Canet         .node_name = (char *) node_name,
10806cc2a415SPaolo Bonzini         .snapshot_file = (char *) snapshot_file,
10810901f67eSBenoît Canet         .snapshot_node_name = (char *) snapshot_node_name,
10826cc2a415SPaolo Bonzini         .format = (char *) format,
10836cc2a415SPaolo Bonzini         .has_mode = has_mode,
10846cc2a415SPaolo Bonzini         .mode = mode,
10856cc2a415SPaolo Bonzini     };
108610f75907SEric Blake     TransactionAction action = {
108710f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
108832bafa8fSEric Blake         .u.blockdev_snapshot_sync.data = &snapshot,
108910f75907SEric Blake     };
109010f75907SEric Blake     blockdev_do_action(&action, errp);
1091f8882568SJes Sorensen }
1092f8882568SJes Sorensen 
109343de7e2dSAlberto Garcia void qmp_blockdev_snapshot(const char *node, const char *overlay,
109443de7e2dSAlberto Garcia                            Error **errp)
109543de7e2dSAlberto Garcia {
109643de7e2dSAlberto Garcia     BlockdevSnapshot snapshot_data = {
109743de7e2dSAlberto Garcia         .node = (char *) node,
109843de7e2dSAlberto Garcia         .overlay = (char *) overlay
109943de7e2dSAlberto Garcia     };
110010f75907SEric Blake     TransactionAction action = {
110110f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
110232bafa8fSEric Blake         .u.blockdev_snapshot.data = &snapshot_data,
110310f75907SEric Blake     };
110410f75907SEric Blake     blockdev_do_action(&action, errp);
110543de7e2dSAlberto Garcia }
110643de7e2dSAlberto Garcia 
1107f323bc9eSWenchao Xia void qmp_blockdev_snapshot_internal_sync(const char *device,
1108f323bc9eSWenchao Xia                                          const char *name,
1109f323bc9eSWenchao Xia                                          Error **errp)
1110f323bc9eSWenchao Xia {
1111f323bc9eSWenchao Xia     BlockdevSnapshotInternal snapshot = {
1112f323bc9eSWenchao Xia         .device = (char *) device,
1113f323bc9eSWenchao Xia         .name = (char *) name
1114f323bc9eSWenchao Xia     };
111510f75907SEric Blake     TransactionAction action = {
111610f75907SEric Blake         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
111732bafa8fSEric Blake         .u.blockdev_snapshot_internal_sync.data = &snapshot,
111810f75907SEric Blake     };
111910f75907SEric Blake     blockdev_do_action(&action, errp);
1120f323bc9eSWenchao Xia }
1121f323bc9eSWenchao Xia 
112244e3e053SWenchao Xia SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
112344e3e053SWenchao Xia                                                          const char *id,
112444e3e053SWenchao Xia                                                          const char *name,
112544e3e053SWenchao Xia                                                          Error **errp)
112644e3e053SWenchao Xia {
1127a0e8544cSFam Zheng     BlockDriverState *bs;
11284ef3982aSStefan Hajnoczi     AioContext *aio_context;
112944e3e053SWenchao Xia     QEMUSnapshotInfo sn;
113044e3e053SWenchao Xia     Error *local_err = NULL;
113144e3e053SWenchao Xia     SnapshotInfo *info = NULL;
113244e3e053SWenchao Xia     int ret;
113344e3e053SWenchao Xia 
11342dfb4c03SKevin Wolf     bs = qmp_get_root_bs(device, errp);
11352dfb4c03SKevin Wolf     if (!bs) {
113644e3e053SWenchao Xia         return NULL;
113744e3e053SWenchao Xia     }
11382dfb4c03SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
11395433c24fSMax Reitz     aio_context_acquire(aio_context);
114044e3e053SWenchao Xia 
114144e3e053SWenchao Xia     if (!id && !name) {
114244e3e053SWenchao Xia         error_setg(errp, "Name or id must be provided");
11435433c24fSMax Reitz         goto out_aio_context;
114444e3e053SWenchao Xia     }
114544e3e053SWenchao Xia 
11460b928854SStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
11470b928854SStefan Hajnoczi         goto out_aio_context;
11480b928854SStefan Hajnoczi     }
11490b928854SStefan Hajnoczi 
115044e3e053SWenchao Xia     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
115184d18f06SMarkus Armbruster     if (local_err) {
115244e3e053SWenchao Xia         error_propagate(errp, local_err);
11534ef3982aSStefan Hajnoczi         goto out_aio_context;
115444e3e053SWenchao Xia     }
115544e3e053SWenchao Xia     if (!ret) {
115644e3e053SWenchao Xia         error_setg(errp,
115744e3e053SWenchao Xia                    "Snapshot with id '%s' and name '%s' does not exist on "
115844e3e053SWenchao Xia                    "device '%s'",
115944e3e053SWenchao Xia                    STR_OR_NULL(id), STR_OR_NULL(name), device);
11604ef3982aSStefan Hajnoczi         goto out_aio_context;
116144e3e053SWenchao Xia     }
116244e3e053SWenchao Xia 
116344e3e053SWenchao Xia     bdrv_snapshot_delete(bs, id, name, &local_err);
116484d18f06SMarkus Armbruster     if (local_err) {
116544e3e053SWenchao Xia         error_propagate(errp, local_err);
11664ef3982aSStefan Hajnoczi         goto out_aio_context;
116744e3e053SWenchao Xia     }
116844e3e053SWenchao Xia 
11694ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
11704ef3982aSStefan Hajnoczi 
11715839e53bSMarkus Armbruster     info = g_new0(SnapshotInfo, 1);
117244e3e053SWenchao Xia     info->id = g_strdup(sn.id_str);
117344e3e053SWenchao Xia     info->name = g_strdup(sn.name);
117444e3e053SWenchao Xia     info->date_nsec = sn.date_nsec;
117544e3e053SWenchao Xia     info->date_sec = sn.date_sec;
117644e3e053SWenchao Xia     info->vm_state_size = sn.vm_state_size;
117744e3e053SWenchao Xia     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
117844e3e053SWenchao Xia     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1179b39847a5SPavel Dovgalyuk     if (sn.icount != -1ULL) {
1180b39847a5SPavel Dovgalyuk         info->icount = sn.icount;
1181b39847a5SPavel Dovgalyuk         info->has_icount = true;
1182b39847a5SPavel Dovgalyuk     }
118344e3e053SWenchao Xia 
118444e3e053SWenchao Xia     return info;
11854ef3982aSStefan Hajnoczi 
11864ef3982aSStefan Hajnoczi out_aio_context:
11874ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
11884ef3982aSStefan Hajnoczi     return NULL;
118944e3e053SWenchao Xia }
11908802d1fdSJeff Cody 
1191b756b9ceSStefan Hajnoczi /* New and old BlockDriverState structs for atomic group operations */
1192ba0c86a3SWenchao Xia 
119350f43f0fSJohn Snow typedef struct BlkActionState BlkActionState;
1194ba0c86a3SWenchao Xia 
119550f43f0fSJohn Snow /**
119650f43f0fSJohn Snow  * BlkActionOps:
119750f43f0fSJohn Snow  * Table of operations that define an Action.
119850f43f0fSJohn Snow  *
119950f43f0fSJohn Snow  * @instance_size: Size of state struct, in bytes.
120050f43f0fSJohn Snow  * @prepare: Prepare the work, must NOT be NULL.
120150f43f0fSJohn Snow  * @commit: Commit the changes, can be NULL.
120250f43f0fSJohn Snow  * @abort: Abort the changes on fail, can be NULL.
120350f43f0fSJohn Snow  * @clean: Clean up resources after all transaction actions have called
120450f43f0fSJohn Snow  *         commit() or abort(). Can be NULL.
120550f43f0fSJohn Snow  *
120650f43f0fSJohn Snow  * Only prepare() may fail. In a single transaction, only one of commit() or
120750f43f0fSJohn Snow  * abort() will be called. clean() will always be called if it is present.
1208ebc2752bSEmanuele Giuseppe Esposito  *
1209ebc2752bSEmanuele Giuseppe Esposito  * Always run under BQL.
1210ba0c86a3SWenchao Xia  */
121150f43f0fSJohn Snow typedef struct BlkActionOps {
121250f43f0fSJohn Snow     size_t instance_size;
1213*8187f63cSVladimir Sementsov-Ogievskiy     void (*action)(BlkActionState *common, Transaction *tran, Error **errp);
121450f43f0fSJohn Snow } BlkActionOps;
121550f43f0fSJohn Snow 
121650f43f0fSJohn Snow /**
121750f43f0fSJohn Snow  * BlkActionState:
121850f43f0fSJohn Snow  * Describes one Action's state within a Transaction.
121950f43f0fSJohn Snow  *
122050f43f0fSJohn Snow  * @action: QAPI-defined enum identifying which Action to perform.
122150f43f0fSJohn Snow  * @ops: Table of ActionOps this Action can perform.
122294d16a64SJohn Snow  * @block_job_txn: Transaction which this action belongs to.
122350f43f0fSJohn Snow  * @entry: List membership for all Actions in this Transaction.
122450f43f0fSJohn Snow  *
122550f43f0fSJohn Snow  * This structure must be arranged as first member in a subclassed type,
122650f43f0fSJohn Snow  * assuming that the compiler will also arrange it to the same offsets as the
122750f43f0fSJohn Snow  * base class.
122850f43f0fSJohn Snow  */
122950f43f0fSJohn Snow struct BlkActionState {
1230c8a83e85SKevin Wolf     TransactionAction *action;
123150f43f0fSJohn Snow     const BlkActionOps *ops;
123262c9e416SKevin Wolf     JobTxn *block_job_txn;
123394d16a64SJohn Snow     TransactionProperties *txn_props;
1234f4de0f8cSJohn Snow     QTAILQ_ENTRY(BlkActionState) entry;
1235ba0c86a3SWenchao Xia };
1236ba0c86a3SWenchao Xia 
1237bbe86010SWenchao Xia /* internal snapshot private data */
1238bbe86010SWenchao Xia typedef struct InternalSnapshotState {
123950f43f0fSJohn Snow     BlkActionState common;
1240bbe86010SWenchao Xia     BlockDriverState *bs;
1241bbe86010SWenchao Xia     QEMUSnapshotInfo sn;
1242507306ccSFam Zheng     bool created;
1243bbe86010SWenchao Xia } InternalSnapshotState;
1244bbe86010SWenchao Xia 
1245*8187f63cSVladimir Sementsov-Ogievskiy static void internal_snapshot_abort(void *opaque);
1246*8187f63cSVladimir Sementsov-Ogievskiy static void internal_snapshot_clean(void *opaque);
1247*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv internal_snapshot_drv = {
1248*8187f63cSVladimir Sementsov-Ogievskiy     .abort = internal_snapshot_abort,
1249*8187f63cSVladimir Sementsov-Ogievskiy     .clean = internal_snapshot_clean,
1250*8187f63cSVladimir Sementsov-Ogievskiy };
125194d16a64SJohn Snow 
125294d16a64SJohn Snow static int action_check_completion_mode(BlkActionState *s, Error **errp)
125394d16a64SJohn Snow {
125494d16a64SJohn Snow     if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
125594d16a64SJohn Snow         error_setg(errp,
125694d16a64SJohn Snow                    "Action '%s' does not support Transaction property "
125794d16a64SJohn Snow                    "completion-mode = %s",
1258977c736fSMarkus Armbruster                    TransactionActionKind_str(s->action->type),
1259977c736fSMarkus Armbruster                    ActionCompletionMode_str(s->txn_props->completion_mode));
126094d16a64SJohn Snow         return -1;
126194d16a64SJohn Snow     }
126294d16a64SJohn Snow     return 0;
126394d16a64SJohn Snow }
126494d16a64SJohn Snow 
1265*8187f63cSVladimir Sementsov-Ogievskiy static void internal_snapshot_action(BlkActionState *common,
1266*8187f63cSVladimir Sementsov-Ogievskiy                                      Transaction *tran, Error **errp)
1267bbe86010SWenchao Xia {
1268f70edf99SMarkus Armbruster     Error *local_err = NULL;
1269bbe86010SWenchao Xia     const char *device;
1270bbe86010SWenchao Xia     const char *name;
1271bbe86010SWenchao Xia     BlockDriverState *bs;
1272bbe86010SWenchao Xia     QEMUSnapshotInfo old_sn, *sn;
1273bbe86010SWenchao Xia     bool ret;
1274f793dde0SMarc-André Lureau     int64_t rt;
1275bbe86010SWenchao Xia     BlockdevSnapshotInternal *internal;
1276bbe86010SWenchao Xia     InternalSnapshotState *state;
1277a36e458cSStefan Hajnoczi     AioContext *aio_context;
1278bbe86010SWenchao Xia     int ret1;
1279bbe86010SWenchao Xia 
12806a8f9661SEric Blake     g_assert(common->action->type ==
1281bbe86010SWenchao Xia              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
128232bafa8fSEric Blake     internal = common->action->u.blockdev_snapshot_internal_sync.data;
1283bbe86010SWenchao Xia     state = DO_UPCAST(InternalSnapshotState, common, common);
1284bbe86010SWenchao Xia 
1285*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &internal_snapshot_drv, state);
1286*8187f63cSVladimir Sementsov-Ogievskiy 
1287bbe86010SWenchao Xia     /* 1. parse input */
1288bbe86010SWenchao Xia     device = internal->device;
1289bbe86010SWenchao Xia     name = internal->name;
1290bbe86010SWenchao Xia 
1291bbe86010SWenchao Xia     /* 2. check for validation */
129294d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
129394d16a64SJohn Snow         return;
129494d16a64SJohn Snow     }
129594d16a64SJohn Snow 
129675dfd402SKevin Wolf     bs = qmp_get_root_bs(device, errp);
129775dfd402SKevin Wolf     if (!bs) {
1298bbe86010SWenchao Xia         return;
1299bbe86010SWenchao Xia     }
1300bbe86010SWenchao Xia 
1301a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
1302a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
13035d6e96efSStefan Hajnoczi 
1304507306ccSFam Zheng     state->bs = bs;
1305a36e458cSStefan Hajnoczi 
1306a36e458cSStefan Hajnoczi     /* Paired with .clean() */
1307507306ccSFam Zheng     bdrv_drained_begin(bs);
1308507306ccSFam Zheng 
13093dc7ca3cSStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1310a36e458cSStefan Hajnoczi         goto out;
13113dc7ca3cSStefan Hajnoczi     }
13123dc7ca3cSStefan Hajnoczi 
1313bbe86010SWenchao Xia     if (bdrv_is_read_only(bs)) {
131481e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
1315a36e458cSStefan Hajnoczi         goto out;
1316bbe86010SWenchao Xia     }
1317bbe86010SWenchao Xia 
1318bbe86010SWenchao Xia     if (!bdrv_can_snapshot(bs)) {
131981e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by device '%s' "
132081e5f78aSAlberto Garcia                    "does not support internal snapshots",
132181e5f78aSAlberto Garcia                    bs->drv->format_name, device);
1322a36e458cSStefan Hajnoczi         goto out;
1323bbe86010SWenchao Xia     }
1324bbe86010SWenchao Xia 
1325bbe86010SWenchao Xia     if (!strlen(name)) {
1326bbe86010SWenchao Xia         error_setg(errp, "Name is empty");
1327a36e458cSStefan Hajnoczi         goto out;
1328bbe86010SWenchao Xia     }
1329bbe86010SWenchao Xia 
1330bbe86010SWenchao Xia     /* check whether a snapshot with name exist */
1331f70edf99SMarkus Armbruster     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1332f70edf99SMarkus Armbruster                                             &local_err);
1333f70edf99SMarkus Armbruster     if (local_err) {
1334f70edf99SMarkus Armbruster         error_propagate(errp, local_err);
1335a36e458cSStefan Hajnoczi         goto out;
1336bbe86010SWenchao Xia     } else if (ret) {
1337bbe86010SWenchao Xia         error_setg(errp,
1338bbe86010SWenchao Xia                    "Snapshot with name '%s' already exists on device '%s'",
1339bbe86010SWenchao Xia                    name, device);
1340a36e458cSStefan Hajnoczi         goto out;
1341bbe86010SWenchao Xia     }
1342bbe86010SWenchao Xia 
1343bbe86010SWenchao Xia     /* 3. take the snapshot */
1344bbe86010SWenchao Xia     sn = &state->sn;
1345bbe86010SWenchao Xia     pstrcpy(sn->name, sizeof(sn->name), name);
1346f793dde0SMarc-André Lureau     rt = g_get_real_time();
1347f793dde0SMarc-André Lureau     sn->date_sec = rt / G_USEC_PER_SEC;
1348f793dde0SMarc-André Lureau     sn->date_nsec = (rt % G_USEC_PER_SEC) * 1000;
1349bbe86010SWenchao Xia     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1350b39847a5SPavel Dovgalyuk     if (replay_mode != REPLAY_MODE_NONE) {
1351b39847a5SPavel Dovgalyuk         sn->icount = replay_get_current_icount();
1352b39847a5SPavel Dovgalyuk     } else {
1353b39847a5SPavel Dovgalyuk         sn->icount = -1ULL;
1354b39847a5SPavel Dovgalyuk     }
1355bbe86010SWenchao Xia 
1356bbe86010SWenchao Xia     ret1 = bdrv_snapshot_create(bs, sn);
1357bbe86010SWenchao Xia     if (ret1 < 0) {
1358bbe86010SWenchao Xia         error_setg_errno(errp, -ret1,
1359bbe86010SWenchao Xia                          "Failed to create snapshot '%s' on device '%s'",
1360bbe86010SWenchao Xia                          name, device);
1361a36e458cSStefan Hajnoczi         goto out;
1362bbe86010SWenchao Xia     }
1363bbe86010SWenchao Xia 
1364bbe86010SWenchao Xia     /* 4. succeed, mark a snapshot is created */
1365507306ccSFam Zheng     state->created = true;
1366a36e458cSStefan Hajnoczi 
1367a36e458cSStefan Hajnoczi out:
1368a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
1369bbe86010SWenchao Xia }
1370bbe86010SWenchao Xia 
1371*8187f63cSVladimir Sementsov-Ogievskiy static void internal_snapshot_abort(void *opaque)
1372bbe86010SWenchao Xia {
1373*8187f63cSVladimir Sementsov-Ogievskiy     InternalSnapshotState *state = opaque;
1374bbe86010SWenchao Xia     BlockDriverState *bs = state->bs;
1375bbe86010SWenchao Xia     QEMUSnapshotInfo *sn = &state->sn;
1376a36e458cSStefan Hajnoczi     AioContext *aio_context;
1377bbe86010SWenchao Xia     Error *local_error = NULL;
1378bbe86010SWenchao Xia 
1379507306ccSFam Zheng     if (!state->created) {
1380bbe86010SWenchao Xia         return;
1381bbe86010SWenchao Xia     }
1382bbe86010SWenchao Xia 
1383a36e458cSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1384a36e458cSStefan Hajnoczi     aio_context_acquire(aio_context);
1385a36e458cSStefan Hajnoczi 
1386bbe86010SWenchao Xia     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1387c29b77f9SMarkus Armbruster         error_reportf_err(local_error,
1388c29b77f9SMarkus Armbruster                           "Failed to delete snapshot with id '%s' and "
1389c29b77f9SMarkus Armbruster                           "name '%s' on device '%s' in abort: ",
1390c29b77f9SMarkus Armbruster                           sn->id_str, sn->name,
1391c29b77f9SMarkus Armbruster                           bdrv_get_device_name(bs));
1392bbe86010SWenchao Xia     }
1393a36e458cSStefan Hajnoczi 
1394a36e458cSStefan Hajnoczi     aio_context_release(aio_context);
1395bbe86010SWenchao Xia }
1396bbe86010SWenchao Xia 
1397*8187f63cSVladimir Sementsov-Ogievskiy static void internal_snapshot_clean(void *opaque)
13985d6e96efSStefan Hajnoczi {
1399*8187f63cSVladimir Sementsov-Ogievskiy     g_autofree InternalSnapshotState *state = opaque;
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 
1422*8187f63cSVladimir Sementsov-Ogievskiy static void external_snapshot_commit(void *opaque);
1423*8187f63cSVladimir Sementsov-Ogievskiy static void external_snapshot_abort(void *opaque);
1424*8187f63cSVladimir Sementsov-Ogievskiy static void external_snapshot_clean(void *opaque);
1425*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv external_snapshot_drv = {
1426*8187f63cSVladimir Sementsov-Ogievskiy     .commit = external_snapshot_commit,
1427*8187f63cSVladimir Sementsov-Ogievskiy     .abort = external_snapshot_abort,
1428*8187f63cSVladimir Sementsov-Ogievskiy     .clean = external_snapshot_clean,
1429*8187f63cSVladimir Sementsov-Ogievskiy };
1430*8187f63cSVladimir Sementsov-Ogievskiy 
1431*8187f63cSVladimir Sementsov-Ogievskiy static void external_snapshot_action(BlkActionState *common, Transaction *tran,
14329b9877eeSWenchao Xia                                      Error **errp)
14339b9877eeSWenchao Xia {
1434934aee14SVladimir Sementsov-Ogievskiy     int ret;
14355b363937SMax Reitz     int flags = 0;
143643de7e2dSAlberto Garcia     QDict *options = NULL;
14379b9877eeSWenchao Xia     Error *local_err = NULL;
143843de7e2dSAlberto Garcia     /* Device and node name of the image to generate the snapshot from */
1439e2a31e87SWenchao Xia     const char *device;
14400901f67eSBenoît Canet     const char *node_name;
144143de7e2dSAlberto Garcia     /* Reference to the new image (for 'blockdev-snapshot') */
144243de7e2dSAlberto Garcia     const char *snapshot_ref;
144343de7e2dSAlberto Garcia     /* File name of the new image (for 'blockdev-snapshot-sync') */
1444e2a31e87SWenchao Xia     const char *new_image_file;
1445ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1446ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1447c8a83e85SKevin Wolf     TransactionAction *action = common->action;
14482d24b60bSStefan Hajnoczi     AioContext *aio_context;
1449d29d3d1fSKevin Wolf     uint64_t perm, shared;
14509b9877eeSWenchao Xia 
1451*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &external_snapshot_drv, state);
1452*8187f63cSVladimir Sementsov-Ogievskiy 
145343de7e2dSAlberto Garcia     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
145443de7e2dSAlberto Garcia      * purpose but a different set of parameters */
145543de7e2dSAlberto Garcia     switch (action->type) {
145643de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
145743de7e2dSAlberto Garcia         {
145832bafa8fSEric Blake             BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
145943de7e2dSAlberto Garcia             device = s->node;
146043de7e2dSAlberto Garcia             node_name = s->node;
146143de7e2dSAlberto Garcia             new_image_file = NULL;
146243de7e2dSAlberto Garcia             snapshot_ref = s->overlay;
1463e2a31e87SWenchao Xia         }
146443de7e2dSAlberto Garcia         break;
146543de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
146643de7e2dSAlberto Garcia         {
146732bafa8fSEric Blake             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
146854fde4ffSMarkus Armbruster             device = s->device;
146954fde4ffSMarkus Armbruster             node_name = s->node_name;
147043de7e2dSAlberto Garcia             new_image_file = s->snapshot_file;
147143de7e2dSAlberto Garcia             snapshot_ref = NULL;
147243de7e2dSAlberto Garcia         }
147343de7e2dSAlberto Garcia         break;
147443de7e2dSAlberto Garcia     default:
147543de7e2dSAlberto Garcia         g_assert_not_reached();
1476e2a31e87SWenchao Xia     }
1477e2a31e87SWenchao Xia 
1478e2a31e87SWenchao Xia     /* start processing */
147994d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
148094d16a64SJohn Snow         return;
148194d16a64SJohn Snow     }
148294d16a64SJohn Snow 
148343de7e2dSAlberto Garcia     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
148443de7e2dSAlberto Garcia     if (!state->old_bs) {
14859b9877eeSWenchao Xia         return;
14869b9877eeSWenchao Xia     }
14879b9877eeSWenchao Xia 
14882d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
14892d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
14902d24b60bSStefan Hajnoczi 
14912d24b60bSStefan Hajnoczi     /* Paired with .clean() */
1492da763e83SFam Zheng     bdrv_drained_begin(state->old_bs);
14935d6e96efSStefan Hajnoczi 
1494ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_inserted(state->old_bs)) {
1495c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
14962d24b60bSStefan Hajnoczi         goto out;
14979b9877eeSWenchao Xia     }
14989b9877eeSWenchao Xia 
14993718d8abSFam Zheng     if (bdrv_op_is_blocked(state->old_bs,
15003718d8abSFam Zheng                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
15012d24b60bSStefan Hajnoczi         goto out;
15029b9877eeSWenchao Xia     }
15039b9877eeSWenchao Xia 
1504ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_read_only(state->old_bs)) {
1505ba5d6ab6SStefan Hajnoczi         if (bdrv_flush(state->old_bs)) {
1506c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_IO_ERROR);
15072d24b60bSStefan Hajnoczi             goto out;
15089b9877eeSWenchao Xia         }
15099b9877eeSWenchao Xia     }
15109b9877eeSWenchao Xia 
151143de7e2dSAlberto Garcia     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
151232bafa8fSEric Blake         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
151354fde4ffSMarkus Armbruster         const char *format = s->format ?: "qcow2";
151443de7e2dSAlberto Garcia         enum NewImageMode mode;
151554fde4ffSMarkus Armbruster         const char *snapshot_node_name = s->snapshot_node_name;
151643de7e2dSAlberto Garcia 
151743de7e2dSAlberto Garcia         if (node_name && !snapshot_node_name) {
1518ef2e38a1SConnor Kuehl             error_setg(errp, "New overlay node-name missing");
15192d24b60bSStefan Hajnoczi             goto out;
152043de7e2dSAlberto Garcia         }
152143de7e2dSAlberto Garcia 
152243de7e2dSAlberto Garcia         if (snapshot_node_name &&
152343de7e2dSAlberto Garcia             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1524ef2e38a1SConnor Kuehl             error_setg(errp, "New overlay node-name already in use");
15252d24b60bSStefan Hajnoczi             goto out;
152643de7e2dSAlberto Garcia         }
152743de7e2dSAlberto Garcia 
1528ba5d6ab6SStefan Hajnoczi         flags = state->old_bs->open_flags;
15292a32c6e8SJohn Snow         flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
15302a32c6e8SJohn Snow         flags |= BDRV_O_NO_BACKING;
15319b9877eeSWenchao Xia 
15329b9877eeSWenchao Xia         /* create new image w/backing file */
153343de7e2dSAlberto Garcia         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
15349b9877eeSWenchao Xia         if (mode != NEW_IMAGE_MODE_EXISTING) {
1535f86b8b58SKevin Wolf             int64_t size = bdrv_getlength(state->old_bs);
1536f86b8b58SKevin Wolf             if (size < 0) {
1537f86b8b58SKevin Wolf                 error_setg_errno(errp, -size, "bdrv_getlength failed");
15382d24b60bSStefan Hajnoczi                 goto out;
1539f86b8b58SKevin Wolf             }
1540f30c66baSMax Reitz             bdrv_refresh_filename(state->old_bs);
1541e1355055SKevin Wolf 
1542e1355055SKevin Wolf             aio_context_release(aio_context);
15439b9877eeSWenchao Xia             bdrv_img_create(new_image_file, format,
1544ba5d6ab6SStefan Hajnoczi                             state->old_bs->filename,
1545ba5d6ab6SStefan Hajnoczi                             state->old_bs->drv->format_name,
15469217283dSFam Zheng                             NULL, size, flags, false, &local_err);
1547e1355055SKevin Wolf             aio_context_acquire(aio_context);
1548e1355055SKevin Wolf 
154984d18f06SMarkus Armbruster             if (local_err) {
15509b9877eeSWenchao Xia                 error_propagate(errp, local_err);
15512d24b60bSStefan Hajnoczi                 goto out;
15529b9877eeSWenchao Xia             }
15539b9877eeSWenchao Xia         }
15549b9877eeSWenchao Xia 
15550901f67eSBenoît Canet         options = qdict_new();
1556d52e1a0eSPeter Maydell         if (snapshot_node_name) {
155746f5ac20SEric Blake             qdict_put_str(options, "node-name", snapshot_node_name);
15580901f67eSBenoît Canet         }
155946f5ac20SEric Blake         qdict_put_str(options, "driver", format);
156043de7e2dSAlberto Garcia     }
156143de7e2dSAlberto Garcia 
15625b363937SMax Reitz     state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
15635b363937SMax Reitz                               errp);
1564f67503e5SMax Reitz     /* We will manually add the backing_hd field to the bs later */
15655b363937SMax Reitz     if (!state->new_bs) {
15662d24b60bSStefan Hajnoczi         goto out;
156743de7e2dSAlberto Garcia     }
156843de7e2dSAlberto Garcia 
1569d29d3d1fSKevin Wolf     /*
1570d29d3d1fSKevin Wolf      * Allow attaching a backing file to an overlay that's already in use only
1571d29d3d1fSKevin Wolf      * if the parents don't assume that they are already seeing a valid image.
1572d29d3d1fSKevin Wolf      * (Specifically, allow it as a mirror target, which is write-only access.)
1573d29d3d1fSKevin Wolf      */
1574d29d3d1fSKevin Wolf     bdrv_get_cumulative_perm(state->new_bs, &perm, &shared);
1575d29d3d1fSKevin Wolf     if (perm & BLK_PERM_CONSISTENT_READ) {
1576a2bb6f8cSMax Reitz         error_setg(errp, "The overlay is already in use");
15772d24b60bSStefan Hajnoczi         goto out;
157843de7e2dSAlberto Garcia     }
157943de7e2dSAlberto Garcia 
15807cc734a9SMax Reitz     if (state->new_bs->drv->is_filter) {
15817cc734a9SMax Reitz         error_setg(errp, "Filters cannot be used as overlays");
15827cc734a9SMax Reitz         goto out;
15837cc734a9SMax Reitz     }
15847cc734a9SMax Reitz 
15857cc734a9SMax Reitz     if (bdrv_cow_child(state->new_bs)) {
1586a2bb6f8cSMax Reitz         error_setg(errp, "The overlay already has a backing image");
15872d24b60bSStefan Hajnoczi         goto out;
158808b24cfeSAlberto Garcia     }
158908b24cfeSAlberto Garcia 
159008b24cfeSAlberto Garcia     if (!state->new_bs->drv->supports_backing) {
1591a2bb6f8cSMax Reitz         error_setg(errp, "The overlay does not support backing images");
15922d24b60bSStefan Hajnoczi         goto out;
1593b2c2832cSKevin Wolf     }
1594b2c2832cSKevin Wolf 
1595934aee14SVladimir Sementsov-Ogievskiy     ret = bdrv_append(state->new_bs, state->old_bs, errp);
1596934aee14SVladimir Sementsov-Ogievskiy     if (ret < 0) {
15972d24b60bSStefan Hajnoczi         goto out;
15989b9877eeSWenchao Xia     }
1599067acf28SKevin Wolf     state->overlay_appended = true;
16002d24b60bSStefan Hajnoczi 
16012d24b60bSStefan Hajnoczi out:
16022d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
16039b9877eeSWenchao Xia }
16049b9877eeSWenchao Xia 
1605*8187f63cSVladimir Sementsov-Ogievskiy static void external_snapshot_commit(void *opaque)
16063b0047e8SWenchao Xia {
1607*8187f63cSVladimir Sementsov-Ogievskiy     ExternalSnapshotState *state = opaque;
16082d24b60bSStefan Hajnoczi     AioContext *aio_context;
16092d24b60bSStefan Hajnoczi 
16102d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
16112d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
1612ba0c86a3SWenchao Xia 
16133b0047e8SWenchao Xia     /* We don't need (or want) to use the transactional
16143b0047e8SWenchao Xia      * bdrv_reopen_multiple() across all the entries at once, because we
16153b0047e8SWenchao Xia      * don't want to abort all of them if one of them fails the reopen */
1616d73415a3SStefan Hajnoczi     if (!qatomic_read(&state->old_bs->copy_on_read)) {
16171b57774fSAlberto Garcia         bdrv_reopen_set_read_only(state->old_bs, true, NULL);
16183b0047e8SWenchao Xia     }
16192d24b60bSStefan Hajnoczi 
16202d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
16214c844983SKevin Wolf }
16223b0047e8SWenchao Xia 
1623*8187f63cSVladimir Sementsov-Ogievskiy static void external_snapshot_abort(void *opaque)
162496b86bf7SWenchao Xia {
1625*8187f63cSVladimir Sementsov-Ogievskiy     ExternalSnapshotState *state = opaque;
1626ba5d6ab6SStefan Hajnoczi     if (state->new_bs) {
1627067acf28SKevin Wolf         if (state->overlay_appended) {
16282d24b60bSStefan Hajnoczi             AioContext *aio_context;
1629377410f6SSergio Lopez             AioContext *tmp_context;
1630377410f6SSergio Lopez             int ret;
16312d24b60bSStefan Hajnoczi 
16322d24b60bSStefan Hajnoczi             aio_context = bdrv_get_aio_context(state->old_bs);
16332d24b60bSStefan Hajnoczi             aio_context_acquire(aio_context);
16342d24b60bSStefan Hajnoczi 
1635719fc28cSJeff Cody             bdrv_ref(state->old_bs);   /* we can't let bdrv_set_backind_hd()
1636719fc28cSJeff Cody                                           close state->old_bs; we need it */
1637719fc28cSJeff Cody             bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1638377410f6SSergio Lopez 
1639377410f6SSergio Lopez             /*
1640377410f6SSergio Lopez              * The call to bdrv_set_backing_hd() above returns state->old_bs to
1641377410f6SSergio Lopez              * the main AioContext. As we're still going to be using it, return
1642377410f6SSergio Lopez              * it to the AioContext it was before.
1643377410f6SSergio Lopez              */
1644377410f6SSergio Lopez             tmp_context = bdrv_get_aio_context(state->old_bs);
1645377410f6SSergio Lopez             if (aio_context != tmp_context) {
1646377410f6SSergio Lopez                 aio_context_release(aio_context);
1647377410f6SSergio Lopez                 aio_context_acquire(tmp_context);
1648377410f6SSergio Lopez 
1649142e6907SEmanuele Giuseppe Esposito                 ret = bdrv_try_change_aio_context(state->old_bs,
1650142e6907SEmanuele Giuseppe Esposito                                                   aio_context, NULL, NULL);
1651377410f6SSergio Lopez                 assert(ret == 0);
1652377410f6SSergio Lopez 
1653377410f6SSergio Lopez                 aio_context_release(tmp_context);
1654377410f6SSergio Lopez                 aio_context_acquire(aio_context);
1655377410f6SSergio Lopez             }
1656377410f6SSergio Lopez 
16575fe31c25SKevin Wolf             bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1658719fc28cSJeff Cody             bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
16592d24b60bSStefan Hajnoczi 
16602d24b60bSStefan Hajnoczi             aio_context_release(aio_context);
1661b2c2832cSKevin Wolf         }
166296b86bf7SWenchao Xia     }
1663da763e83SFam Zheng }
1664da763e83SFam Zheng 
1665*8187f63cSVladimir Sementsov-Ogievskiy static void external_snapshot_clean(void *opaque)
1666da763e83SFam Zheng {
1667*8187f63cSVladimir Sementsov-Ogievskiy     g_autofree ExternalSnapshotState *state = opaque;
16682d24b60bSStefan Hajnoczi     AioContext *aio_context;
16692d24b60bSStefan Hajnoczi 
16702d24b60bSStefan Hajnoczi     if (!state->old_bs) {
16712d24b60bSStefan Hajnoczi         return;
16722d24b60bSStefan Hajnoczi     }
16732d24b60bSStefan Hajnoczi 
16742d24b60bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->old_bs);
16752d24b60bSStefan Hajnoczi     aio_context_acquire(aio_context);
16762d24b60bSStefan Hajnoczi 
1677da763e83SFam Zheng     bdrv_drained_end(state->old_bs);
1678b2c2832cSKevin Wolf     bdrv_unref(state->new_bs);
16792d24b60bSStefan Hajnoczi 
16802d24b60bSStefan Hajnoczi     aio_context_release(aio_context);
168196b86bf7SWenchao Xia }
168296b86bf7SWenchao Xia 
16833037f364SStefan Hajnoczi typedef struct DriveBackupState {
168450f43f0fSJohn Snow     BlkActionState common;
16853037f364SStefan Hajnoczi     BlockDriverState *bs;
16863037f364SStefan Hajnoczi     BlockJob *job;
16873037f364SStefan Hajnoczi } DriveBackupState;
16883037f364SStefan Hajnoczi 
16892288ccfaSSergio Lopez static BlockJob *do_backup_common(BackupCommon *backup,
16902288ccfaSSergio Lopez                                   BlockDriverState *bs,
16912288ccfaSSergio Lopez                                   BlockDriverState *target_bs,
16922288ccfaSSergio Lopez                                   AioContext *aio_context,
16932288ccfaSSergio Lopez                                   JobTxn *txn, Error **errp);
169478f51fdeSJohn Snow 
1695*8187f63cSVladimir Sementsov-Ogievskiy static void drive_backup_commit(void *opaque);
1696*8187f63cSVladimir Sementsov-Ogievskiy static void drive_backup_abort(void *opaque);
1697*8187f63cSVladimir Sementsov-Ogievskiy static void drive_backup_clean(void *opaque);
1698*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv drive_backup_drv = {
1699*8187f63cSVladimir Sementsov-Ogievskiy     .commit = drive_backup_commit,
1700*8187f63cSVladimir Sementsov-Ogievskiy     .abort = drive_backup_abort,
1701*8187f63cSVladimir Sementsov-Ogievskiy     .clean = drive_backup_clean,
1702*8187f63cSVladimir Sementsov-Ogievskiy };
1703*8187f63cSVladimir Sementsov-Ogievskiy 
1704*8187f63cSVladimir Sementsov-Ogievskiy static void drive_backup_action(BlkActionState *common, Transaction *tran,
1705*8187f63cSVladimir Sementsov-Ogievskiy                                 Error **errp)
17063037f364SStefan Hajnoczi {
17073037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
17083037f364SStefan Hajnoczi     DriveBackup *backup;
17092288ccfaSSergio Lopez     BlockDriverState *bs;
17102288ccfaSSergio Lopez     BlockDriverState *target_bs;
17112288ccfaSSergio Lopez     BlockDriverState *source = NULL;
171266d56054SStefan Hajnoczi     AioContext *aio_context;
17133ea67e08SSergio Lopez     AioContext *old_context;
171404658a5bSMarkus Armbruster     const char *format;
17152288ccfaSSergio Lopez     QDict *options;
17163037f364SStefan Hajnoczi     Error *local_err = NULL;
17172288ccfaSSergio Lopez     int flags;
17182288ccfaSSergio Lopez     int64_t size;
17192288ccfaSSergio Lopez     bool set_backing_hd = false;
17203ea67e08SSergio Lopez     int ret;
17213037f364SStefan Hajnoczi 
1722*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &drive_backup_drv, state);
1723*8187f63cSVladimir Sementsov-Ogievskiy 
17246a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
172532bafa8fSEric Blake     backup = common->action->u.drive_backup.data;
17263037f364SStefan Hajnoczi 
17272288ccfaSSergio Lopez     if (!backup->has_mode) {
17282288ccfaSSergio Lopez         backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
17292288ccfaSSergio Lopez     }
17302288ccfaSSergio Lopez 
173185c9d133SVladimir Sementsov-Ogievskiy     bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1732b7e4fa22SKevin Wolf     if (!bs) {
17331fdd4b7bSFam Zheng         return;
17341fdd4b7bSFam Zheng     }
17351fdd4b7bSFam Zheng 
17362288ccfaSSergio Lopez     if (!bs->drv) {
17372288ccfaSSergio Lopez         error_setg(errp, "Device has no medium");
17382288ccfaSSergio Lopez         return;
17392288ccfaSSergio Lopez     }
17402288ccfaSSergio Lopez 
174166d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
174266d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
174366d56054SStefan Hajnoczi 
17442842ff2dSVladimir Sementsov-Ogievskiy     state->bs = bs;
174566d56054SStefan Hajnoczi     /* Paired with .clean() */
1746b7e4fa22SKevin Wolf     bdrv_drained_begin(bs);
174766d56054SStefan Hajnoczi 
174804658a5bSMarkus Armbruster     format = backup->format;
174904658a5bSMarkus Armbruster     if (!format && backup->mode != NEW_IMAGE_MODE_EXISTING) {
175004658a5bSMarkus Armbruster         format = bs->drv->format_name;
17512288ccfaSSergio Lopez     }
17525d6e96efSStefan Hajnoczi 
17532288ccfaSSergio Lopez     /* Early check to avoid creating target */
17542288ccfaSSergio Lopez     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
17552288ccfaSSergio Lopez         goto out;
17562288ccfaSSergio Lopez     }
17572288ccfaSSergio Lopez 
17582288ccfaSSergio Lopez     flags = bs->open_flags | BDRV_O_RDWR;
17592288ccfaSSergio Lopez 
17602288ccfaSSergio Lopez     /*
17612288ccfaSSergio Lopez      * See if we have a backing HD we can use to create our new image
17622288ccfaSSergio Lopez      * on top of.
17632288ccfaSSergio Lopez      */
17642288ccfaSSergio Lopez     if (backup->sync == MIRROR_SYNC_MODE_TOP) {
17652b088c60SMax Reitz         /*
17662b088c60SMax Reitz          * Backup will not replace the source by the target, so none
17672b088c60SMax Reitz          * of the filters skipped here will be removed (in contrast to
17682b088c60SMax Reitz          * mirror).  Therefore, we can skip all of them when looking
17692b088c60SMax Reitz          * for the first COW relationship.
17702b088c60SMax Reitz          */
17712b088c60SMax Reitz         source = bdrv_cow_bs(bdrv_skip_filters(bs));
17722288ccfaSSergio Lopez         if (!source) {
17732288ccfaSSergio Lopez             backup->sync = MIRROR_SYNC_MODE_FULL;
17742288ccfaSSergio Lopez         }
17752288ccfaSSergio Lopez     }
17762288ccfaSSergio Lopez     if (backup->sync == MIRROR_SYNC_MODE_NONE) {
17772288ccfaSSergio Lopez         source = bs;
17782288ccfaSSergio Lopez         flags |= BDRV_O_NO_BACKING;
17792288ccfaSSergio Lopez         set_backing_hd = true;
17802288ccfaSSergio Lopez     }
17812288ccfaSSergio Lopez 
17822288ccfaSSergio Lopez     size = bdrv_getlength(bs);
17832288ccfaSSergio Lopez     if (size < 0) {
17842288ccfaSSergio Lopez         error_setg_errno(errp, -size, "bdrv_getlength failed");
17852288ccfaSSergio Lopez         goto out;
17862288ccfaSSergio Lopez     }
17872288ccfaSSergio Lopez 
17882288ccfaSSergio Lopez     if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
178904658a5bSMarkus Armbruster         assert(format);
17902288ccfaSSergio Lopez         if (source) {
17912b088c60SMax Reitz             /* Implicit filters should not appear in the filename */
17922b088c60SMax Reitz             BlockDriverState *explicit_backing =
17932b088c60SMax Reitz                 bdrv_skip_implicit_filters(source);
17942b088c60SMax Reitz 
17952b088c60SMax Reitz             bdrv_refresh_filename(explicit_backing);
179604658a5bSMarkus Armbruster             bdrv_img_create(backup->target, format,
17972b088c60SMax Reitz                             explicit_backing->filename,
17982b088c60SMax Reitz                             explicit_backing->drv->format_name, NULL,
17992288ccfaSSergio Lopez                             size, flags, false, &local_err);
18002288ccfaSSergio Lopez         } else {
180104658a5bSMarkus Armbruster             bdrv_img_create(backup->target, format, NULL, NULL, NULL,
18022288ccfaSSergio Lopez                             size, flags, false, &local_err);
18032288ccfaSSergio Lopez         }
18042288ccfaSSergio Lopez     }
18052288ccfaSSergio Lopez 
180684d18f06SMarkus Armbruster     if (local_err) {
18073037f364SStefan Hajnoczi         error_propagate(errp, local_err);
180866d56054SStefan Hajnoczi         goto out;
18093037f364SStefan Hajnoczi     }
181066d56054SStefan Hajnoczi 
18112288ccfaSSergio Lopez     options = qdict_new();
18122288ccfaSSergio Lopez     qdict_put_str(options, "discard", "unmap");
18132288ccfaSSergio Lopez     qdict_put_str(options, "detect-zeroes", "unmap");
181404658a5bSMarkus Armbruster     if (format) {
181504658a5bSMarkus Armbruster         qdict_put_str(options, "driver", format);
18162288ccfaSSergio Lopez     }
18172288ccfaSSergio Lopez 
18182288ccfaSSergio Lopez     target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
18192288ccfaSSergio Lopez     if (!target_bs) {
18202288ccfaSSergio Lopez         goto out;
18212288ccfaSSergio Lopez     }
18222288ccfaSSergio Lopez 
1823142e6907SEmanuele Giuseppe Esposito     /* Honor bdrv_try_change_aio_context() context acquisition requirements. */
18243ea67e08SSergio Lopez     old_context = bdrv_get_aio_context(target_bs);
18253ea67e08SSergio Lopez     aio_context_release(aio_context);
18263ea67e08SSergio Lopez     aio_context_acquire(old_context);
18273ea67e08SSergio Lopez 
1828142e6907SEmanuele Giuseppe Esposito     ret = bdrv_try_change_aio_context(target_bs, aio_context, NULL, errp);
18293ea67e08SSergio Lopez     if (ret < 0) {
18303ea67e08SSergio Lopez         bdrv_unref(target_bs);
18313ea67e08SSergio Lopez         aio_context_release(old_context);
18323ea67e08SSergio Lopez         return;
18333ea67e08SSergio Lopez     }
18343ea67e08SSergio Lopez 
18353ea67e08SSergio Lopez     aio_context_release(old_context);
18363ea67e08SSergio Lopez     aio_context_acquire(aio_context);
18373ea67e08SSergio Lopez 
18382288ccfaSSergio Lopez     if (set_backing_hd) {
18395a11a1caSVladimir Sementsov-Ogievskiy         if (bdrv_set_backing_hd(target_bs, source, errp) < 0) {
18402288ccfaSSergio Lopez             goto unref;
18412288ccfaSSergio Lopez         }
18422288ccfaSSergio Lopez     }
18432288ccfaSSergio Lopez 
18442288ccfaSSergio Lopez     state->job = do_backup_common(qapi_DriveBackup_base(backup),
18452288ccfaSSergio Lopez                                   bs, target_bs, aio_context,
18462288ccfaSSergio Lopez                                   common->block_job_txn, errp);
18472288ccfaSSergio Lopez 
18482288ccfaSSergio Lopez unref:
18492288ccfaSSergio Lopez     bdrv_unref(target_bs);
185066d56054SStefan Hajnoczi out:
185166d56054SStefan Hajnoczi     aio_context_release(aio_context);
1852111049a4SJohn Snow }
18533037f364SStefan Hajnoczi 
1854*8187f63cSVladimir Sementsov-Ogievskiy static void drive_backup_commit(void *opaque)
1855111049a4SJohn Snow {
1856*8187f63cSVladimir Sementsov-Ogievskiy     DriveBackupState *state = opaque;
185766d56054SStefan Hajnoczi     AioContext *aio_context;
185866d56054SStefan Hajnoczi 
185966d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
186066d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
186166d56054SStefan Hajnoczi 
1862111049a4SJohn Snow     assert(state->job);
1863da01ff7fSKevin Wolf     job_start(&state->job->job);
186466d56054SStefan Hajnoczi 
186566d56054SStefan Hajnoczi     aio_context_release(aio_context);
18663037f364SStefan Hajnoczi }
18673037f364SStefan Hajnoczi 
1868*8187f63cSVladimir Sementsov-Ogievskiy static void drive_backup_abort(void *opaque)
18693037f364SStefan Hajnoczi {
1870*8187f63cSVladimir Sementsov-Ogievskiy     DriveBackupState *state = opaque;
18713037f364SStefan Hajnoczi 
1872111049a4SJohn Snow     if (state->job) {
18734cfb3f05SHanna Reitz         job_cancel_sync(&state->job->job, true);
18743037f364SStefan Hajnoczi     }
18753037f364SStefan Hajnoczi }
18763037f364SStefan Hajnoczi 
1877*8187f63cSVladimir Sementsov-Ogievskiy static void drive_backup_clean(void *opaque)
18785d6e96efSStefan Hajnoczi {
1879*8187f63cSVladimir Sementsov-Ogievskiy     g_autofree DriveBackupState *state = opaque;
188066d56054SStefan Hajnoczi     AioContext *aio_context;
18815d6e96efSStefan Hajnoczi 
188266d56054SStefan Hajnoczi     if (!state->bs) {
188366d56054SStefan Hajnoczi         return;
18845d6e96efSStefan Hajnoczi     }
188566d56054SStefan Hajnoczi 
188666d56054SStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
188766d56054SStefan Hajnoczi     aio_context_acquire(aio_context);
188866d56054SStefan Hajnoczi 
188966d56054SStefan Hajnoczi     bdrv_drained_end(state->bs);
189066d56054SStefan Hajnoczi 
189166d56054SStefan Hajnoczi     aio_context_release(aio_context);
18925d6e96efSStefan Hajnoczi }
18935d6e96efSStefan Hajnoczi 
1894bd8baecdSFam Zheng typedef struct BlockdevBackupState {
189550f43f0fSJohn Snow     BlkActionState common;
1896bd8baecdSFam Zheng     BlockDriverState *bs;
1897bd8baecdSFam Zheng     BlockJob *job;
1898bd8baecdSFam Zheng } BlockdevBackupState;
1899bd8baecdSFam Zheng 
1900*8187f63cSVladimir Sementsov-Ogievskiy static void blockdev_backup_commit(void *opaque);
1901*8187f63cSVladimir Sementsov-Ogievskiy static void blockdev_backup_abort(void *opaque);
1902*8187f63cSVladimir Sementsov-Ogievskiy static void blockdev_backup_clean(void *opaque);
1903*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv blockdev_backup_drv = {
1904*8187f63cSVladimir Sementsov-Ogievskiy     .commit = blockdev_backup_commit,
1905*8187f63cSVladimir Sementsov-Ogievskiy     .abort = blockdev_backup_abort,
1906*8187f63cSVladimir Sementsov-Ogievskiy     .clean = blockdev_backup_clean,
1907*8187f63cSVladimir Sementsov-Ogievskiy };
1908*8187f63cSVladimir Sementsov-Ogievskiy 
1909*8187f63cSVladimir Sementsov-Ogievskiy static void blockdev_backup_action(BlkActionState *common, Transaction *tran,
1910*8187f63cSVladimir Sementsov-Ogievskiy                                    Error **errp)
1911bd8baecdSFam Zheng {
1912bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1913bd8baecdSFam Zheng     BlockdevBackup *backup;
19145b7bfe51SSergio Lopez     BlockDriverState *bs;
19155b7bfe51SSergio Lopez     BlockDriverState *target_bs;
1916edd5adeeSStefan Hajnoczi     AioContext *aio_context;
19173ea67e08SSergio Lopez     AioContext *old_context;
19183ea67e08SSergio Lopez     int ret;
1919bd8baecdSFam Zheng 
1920*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &blockdev_backup_drv, state);
1921*8187f63cSVladimir Sementsov-Ogievskiy 
19226a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
192332bafa8fSEric Blake     backup = common->action->u.blockdev_backup.data;
1924bd8baecdSFam Zheng 
1925930fe17fSVladimir Sementsov-Ogievskiy     bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1926cef34eebSKevin Wolf     if (!bs) {
1927ff52bf36SFam Zheng         return;
1928ff52bf36SFam Zheng     }
1929ff52bf36SFam Zheng 
19305b7bfe51SSergio Lopez     target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
19315b7bfe51SSergio Lopez     if (!target_bs) {
1932bd8baecdSFam Zheng         return;
1933bd8baecdSFam Zheng     }
1934bd8baecdSFam Zheng 
1935142e6907SEmanuele Giuseppe Esposito     /* Honor bdrv_try_change_aio_context() context acquisition requirements. */
1936edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
19373ea67e08SSergio Lopez     old_context = bdrv_get_aio_context(target_bs);
19383ea67e08SSergio Lopez     aio_context_acquire(old_context);
19393ea67e08SSergio Lopez 
1940142e6907SEmanuele Giuseppe Esposito     ret = bdrv_try_change_aio_context(target_bs, aio_context, NULL, errp);
19413ea67e08SSergio Lopez     if (ret < 0) {
19423ea67e08SSergio Lopez         aio_context_release(old_context);
19433ea67e08SSergio Lopez         return;
19443ea67e08SSergio Lopez     }
19453ea67e08SSergio Lopez 
19463ea67e08SSergio Lopez     aio_context_release(old_context);
1947edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1948cef34eebSKevin Wolf     state->bs = bs;
1949edd5adeeSStefan Hajnoczi 
1950edd5adeeSStefan Hajnoczi     /* Paired with .clean() */
1951ff52bf36SFam Zheng     bdrv_drained_begin(state->bs);
1952bd8baecdSFam Zheng 
19535b7bfe51SSergio Lopez     state->job = do_backup_common(qapi_BlockdevBackup_base(backup),
19545b7bfe51SSergio Lopez                                   bs, target_bs, aio_context,
19555b7bfe51SSergio Lopez                                   common->block_job_txn, errp);
1956edd5adeeSStefan Hajnoczi 
1957edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1958111049a4SJohn Snow }
1959bd8baecdSFam Zheng 
1960*8187f63cSVladimir Sementsov-Ogievskiy static void blockdev_backup_commit(void *opaque)
1961111049a4SJohn Snow {
1962*8187f63cSVladimir Sementsov-Ogievskiy     BlockdevBackupState *state = opaque;
1963edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1964edd5adeeSStefan Hajnoczi 
1965edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1966edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1967edd5adeeSStefan Hajnoczi 
1968111049a4SJohn Snow     assert(state->job);
1969da01ff7fSKevin Wolf     job_start(&state->job->job);
1970edd5adeeSStefan Hajnoczi 
1971edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1972bd8baecdSFam Zheng }
1973bd8baecdSFam Zheng 
1974*8187f63cSVladimir Sementsov-Ogievskiy static void blockdev_backup_abort(void *opaque)
1975bd8baecdSFam Zheng {
1976*8187f63cSVladimir Sementsov-Ogievskiy     BlockdevBackupState *state = opaque;
1977bd8baecdSFam Zheng 
1978111049a4SJohn Snow     if (state->job) {
19794cfb3f05SHanna Reitz         job_cancel_sync(&state->job->job, true);
1980bd8baecdSFam Zheng     }
1981bd8baecdSFam Zheng }
1982bd8baecdSFam Zheng 
1983*8187f63cSVladimir Sementsov-Ogievskiy static void blockdev_backup_clean(void *opaque)
1984bd8baecdSFam Zheng {
1985*8187f63cSVladimir Sementsov-Ogievskiy     g_autofree BlockdevBackupState *state = opaque;
1986edd5adeeSStefan Hajnoczi     AioContext *aio_context;
1987bd8baecdSFam Zheng 
1988edd5adeeSStefan Hajnoczi     if (!state->bs) {
1989edd5adeeSStefan Hajnoczi         return;
1990bd8baecdSFam Zheng     }
1991edd5adeeSStefan Hajnoczi 
1992edd5adeeSStefan Hajnoczi     aio_context = bdrv_get_aio_context(state->bs);
1993edd5adeeSStefan Hajnoczi     aio_context_acquire(aio_context);
1994edd5adeeSStefan Hajnoczi 
1995edd5adeeSStefan Hajnoczi     bdrv_drained_end(state->bs);
1996edd5adeeSStefan Hajnoczi 
1997edd5adeeSStefan Hajnoczi     aio_context_release(aio_context);
1998bd8baecdSFam Zheng }
1999bd8baecdSFam Zheng 
2000df9a681dSFam Zheng typedef struct BlockDirtyBitmapState {
200150f43f0fSJohn Snow     BlkActionState common;
2002df9a681dSFam Zheng     BdrvDirtyBitmap *bitmap;
2003df9a681dSFam Zheng     BlockDriverState *bs;
2004df9a681dSFam Zheng     HBitmap *backup;
2005df9a681dSFam Zheng     bool prepared;
2006c6490447SVladimir Sementsov-Ogievskiy     bool was_enabled;
2007df9a681dSFam Zheng } BlockDirtyBitmapState;
2008df9a681dSFam Zheng 
2009*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_add_abort(void *opaque);
2010*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv block_dirty_bitmap_add_drv = {
2011*8187f63cSVladimir Sementsov-Ogievskiy     .abort = block_dirty_bitmap_add_abort,
2012*8187f63cSVladimir Sementsov-Ogievskiy     .clean = g_free,
2013*8187f63cSVladimir Sementsov-Ogievskiy };
2014*8187f63cSVladimir Sementsov-Ogievskiy 
2015*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_add_action(BlkActionState *common,
2016*8187f63cSVladimir Sementsov-Ogievskiy                                           Transaction *tran, Error **errp)
2017df9a681dSFam Zheng {
2018df9a681dSFam Zheng     Error *local_err = NULL;
2019df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
2020df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2021df9a681dSFam Zheng                                              common, common);
2022df9a681dSFam Zheng 
2023*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &block_dirty_bitmap_add_drv, state);
2024*8187f63cSVladimir Sementsov-Ogievskiy 
202594d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
202694d16a64SJohn Snow         return;
202794d16a64SJohn Snow     }
202894d16a64SJohn Snow 
202932bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_add.data;
2030df9a681dSFam Zheng     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2031df9a681dSFam Zheng     qmp_block_dirty_bitmap_add(action->node, action->name,
2032df9a681dSFam Zheng                                action->has_granularity, action->granularity,
2033fd5ae4ccSVladimir Sementsov-Ogievskiy                                action->has_persistent, action->persistent,
20340e2b7f09SJohn Snow                                action->has_disabled, action->disabled,
2035df9a681dSFam Zheng                                &local_err);
2036df9a681dSFam Zheng 
2037df9a681dSFam Zheng     if (!local_err) {
2038df9a681dSFam Zheng         state->prepared = true;
2039df9a681dSFam Zheng     } else {
2040df9a681dSFam Zheng         error_propagate(errp, local_err);
2041df9a681dSFam Zheng     }
2042df9a681dSFam Zheng }
2043df9a681dSFam Zheng 
2044*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_add_abort(void *opaque)
2045df9a681dSFam Zheng {
2046df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
2047*8187f63cSVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = opaque;
2048df9a681dSFam Zheng 
2049*8187f63cSVladimir Sementsov-Ogievskiy     action = state->common.action->u.block_dirty_bitmap_add.data;
2050df9a681dSFam Zheng     /* Should not be able to fail: IF the bitmap was added via .prepare(),
2051df9a681dSFam Zheng      * then the node reference and bitmap name must have been valid.
2052df9a681dSFam Zheng      */
2053df9a681dSFam Zheng     if (state->prepared) {
2054df9a681dSFam Zheng         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2055df9a681dSFam Zheng     }
2056df9a681dSFam Zheng }
2057df9a681dSFam Zheng 
2058*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_restore(void *opaque);
2059*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_free_backup(void *opaque);
2060*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv block_dirty_bitmap_clear_drv = {
2061*8187f63cSVladimir Sementsov-Ogievskiy     .abort = block_dirty_bitmap_restore,
2062*8187f63cSVladimir Sementsov-Ogievskiy     .commit = block_dirty_bitmap_free_backup,
2063*8187f63cSVladimir Sementsov-Ogievskiy     .clean = g_free,
2064*8187f63cSVladimir Sementsov-Ogievskiy };
2065*8187f63cSVladimir Sementsov-Ogievskiy 
2066*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_clear_action(BlkActionState *common,
2067*8187f63cSVladimir Sementsov-Ogievskiy                                             Transaction *tran, Error **errp)
2068df9a681dSFam Zheng {
2069df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2070df9a681dSFam Zheng                                              common, common);
2071df9a681dSFam Zheng     BlockDirtyBitmap *action;
2072df9a681dSFam Zheng 
2073*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &block_dirty_bitmap_clear_drv, state);
2074*8187f63cSVladimir Sementsov-Ogievskiy 
207594d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
207694d16a64SJohn Snow         return;
207794d16a64SJohn Snow     }
207894d16a64SJohn Snow 
207932bafa8fSEric Blake     action = common->action->u.block_dirty_bitmap_clear.data;
2080df9a681dSFam Zheng     state->bitmap = block_dirty_bitmap_lookup(action->node,
2081df9a681dSFam Zheng                                               action->name,
2082df9a681dSFam Zheng                                               &state->bs,
2083df9a681dSFam Zheng                                               errp);
2084df9a681dSFam Zheng     if (!state->bitmap) {
2085df9a681dSFam Zheng         return;
2086df9a681dSFam Zheng     }
2087df9a681dSFam Zheng 
20883ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_DEFAULT, errp)) {
2089d6883bc9SVladimir Sementsov-Ogievskiy         return;
2090df9a681dSFam Zheng     }
2091df9a681dSFam Zheng 
2092df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2093df9a681dSFam Zheng }
2094df9a681dSFam Zheng 
2095*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_restore(void *opaque)
2096df9a681dSFam Zheng {
2097*8187f63cSVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = opaque;
2098df9a681dSFam Zheng 
2099184dd9c4SJohn Snow     if (state->backup) {
210056bd6624SVladimir Sementsov-Ogievskiy         bdrv_restore_dirty_bitmap(state->bitmap, state->backup);
2101df9a681dSFam Zheng     }
2102184dd9c4SJohn Snow }
2103df9a681dSFam Zheng 
2104*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_free_backup(void *opaque)
2105df9a681dSFam Zheng {
2106*8187f63cSVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = opaque;
2107df9a681dSFam Zheng 
2108df9a681dSFam Zheng     hbitmap_free(state->backup);
2109df9a681dSFam Zheng }
2110df9a681dSFam Zheng 
2111*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_enable_abort(void *opaque);
2112*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv block_dirty_bitmap_enable_drv = {
2113*8187f63cSVladimir Sementsov-Ogievskiy     .abort = block_dirty_bitmap_enable_abort,
2114*8187f63cSVladimir Sementsov-Ogievskiy     .clean = g_free,
2115*8187f63cSVladimir Sementsov-Ogievskiy };
2116*8187f63cSVladimir Sementsov-Ogievskiy 
2117*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_enable_action(BlkActionState *common,
2118*8187f63cSVladimir Sementsov-Ogievskiy                                              Transaction *tran, Error **errp)
2119c6490447SVladimir Sementsov-Ogievskiy {
2120c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmap *action;
2121c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2122c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2123c6490447SVladimir Sementsov-Ogievskiy 
2124*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &block_dirty_bitmap_enable_drv, state);
2125*8187f63cSVladimir Sementsov-Ogievskiy 
2126c6490447SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
2127c6490447SVladimir Sementsov-Ogievskiy         return;
2128c6490447SVladimir Sementsov-Ogievskiy     }
2129c6490447SVladimir Sementsov-Ogievskiy 
21300e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_enable.data;
2131c6490447SVladimir Sementsov-Ogievskiy     state->bitmap = block_dirty_bitmap_lookup(action->node,
2132c6490447SVladimir Sementsov-Ogievskiy                                               action->name,
2133c6490447SVladimir Sementsov-Ogievskiy                                               NULL,
2134c6490447SVladimir Sementsov-Ogievskiy                                               errp);
2135c6490447SVladimir Sementsov-Ogievskiy     if (!state->bitmap) {
2136c6490447SVladimir Sementsov-Ogievskiy         return;
2137c6490447SVladimir Sementsov-Ogievskiy     }
2138c6490447SVladimir Sementsov-Ogievskiy 
21393ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2140b053bb55SJohn Snow         return;
2141b053bb55SJohn Snow     }
2142b053bb55SJohn Snow 
2143c6490447SVladimir Sementsov-Ogievskiy     state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2144c6490447SVladimir Sementsov-Ogievskiy     bdrv_enable_dirty_bitmap(state->bitmap);
2145c6490447SVladimir Sementsov-Ogievskiy }
2146c6490447SVladimir Sementsov-Ogievskiy 
2147*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_enable_abort(void *opaque)
2148c6490447SVladimir Sementsov-Ogievskiy {
2149*8187f63cSVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = opaque;
2150c6490447SVladimir Sementsov-Ogievskiy 
2151c6490447SVladimir Sementsov-Ogievskiy     if (!state->was_enabled) {
2152c6490447SVladimir Sementsov-Ogievskiy         bdrv_disable_dirty_bitmap(state->bitmap);
2153c6490447SVladimir Sementsov-Ogievskiy     }
2154c6490447SVladimir Sementsov-Ogievskiy }
2155c6490447SVladimir Sementsov-Ogievskiy 
2156*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_disable_abort(void *opaque);
2157*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv block_dirty_bitmap_disable_drv = {
2158*8187f63cSVladimir Sementsov-Ogievskiy     .abort = block_dirty_bitmap_disable_abort,
2159*8187f63cSVladimir Sementsov-Ogievskiy     .clean = g_free,
2160*8187f63cSVladimir Sementsov-Ogievskiy };
2161*8187f63cSVladimir Sementsov-Ogievskiy 
2162*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_disable_action(BlkActionState *common,
2163*8187f63cSVladimir Sementsov-Ogievskiy                                               Transaction *tran, Error **errp)
2164c6490447SVladimir Sementsov-Ogievskiy {
2165c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmap *action;
2166c6490447SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2167c6490447SVladimir Sementsov-Ogievskiy                                              common, common);
2168c6490447SVladimir Sementsov-Ogievskiy 
2169*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &block_dirty_bitmap_disable_drv, state);
2170*8187f63cSVladimir Sementsov-Ogievskiy 
2171c6490447SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
2172c6490447SVladimir Sementsov-Ogievskiy         return;
2173c6490447SVladimir Sementsov-Ogievskiy     }
2174c6490447SVladimir Sementsov-Ogievskiy 
21750e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_disable.data;
2176c6490447SVladimir Sementsov-Ogievskiy     state->bitmap = block_dirty_bitmap_lookup(action->node,
2177c6490447SVladimir Sementsov-Ogievskiy                                               action->name,
2178c6490447SVladimir Sementsov-Ogievskiy                                               NULL,
2179c6490447SVladimir Sementsov-Ogievskiy                                               errp);
2180c6490447SVladimir Sementsov-Ogievskiy     if (!state->bitmap) {
2181c6490447SVladimir Sementsov-Ogievskiy         return;
2182c6490447SVladimir Sementsov-Ogievskiy     }
2183c6490447SVladimir Sementsov-Ogievskiy 
21843ae96d66SJohn Snow     if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2185b053bb55SJohn Snow         return;
2186b053bb55SJohn Snow     }
2187b053bb55SJohn Snow 
2188c6490447SVladimir Sementsov-Ogievskiy     state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2189c6490447SVladimir Sementsov-Ogievskiy     bdrv_disable_dirty_bitmap(state->bitmap);
2190c6490447SVladimir Sementsov-Ogievskiy }
2191c6490447SVladimir Sementsov-Ogievskiy 
2192*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_disable_abort(void *opaque)
2193c6490447SVladimir Sementsov-Ogievskiy {
2194*8187f63cSVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = opaque;
2195c6490447SVladimir Sementsov-Ogievskiy 
2196c6490447SVladimir Sementsov-Ogievskiy     if (state->was_enabled) {
2197c6490447SVladimir Sementsov-Ogievskiy         bdrv_enable_dirty_bitmap(state->bitmap);
2198c6490447SVladimir Sementsov-Ogievskiy     }
2199c6490447SVladimir Sementsov-Ogievskiy }
2200c6490447SVladimir Sementsov-Ogievskiy 
2201*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv block_dirty_bitmap_merge_drv = {
2202*8187f63cSVladimir Sementsov-Ogievskiy     .commit = block_dirty_bitmap_free_backup,
2203*8187f63cSVladimir Sementsov-Ogievskiy     .abort = block_dirty_bitmap_restore,
2204*8187f63cSVladimir Sementsov-Ogievskiy     .clean = g_free,
2205*8187f63cSVladimir Sementsov-Ogievskiy };
2206*8187f63cSVladimir Sementsov-Ogievskiy 
2207*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_merge_action(BlkActionState *common,
2208*8187f63cSVladimir Sementsov-Ogievskiy                                             Transaction *tran, Error **errp)
22096fd2e407SVladimir Sementsov-Ogievskiy {
22106fd2e407SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapMerge *action;
22116fd2e407SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
22126fd2e407SVladimir Sementsov-Ogievskiy                                              common, common);
22136fd2e407SVladimir Sementsov-Ogievskiy 
2214*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &block_dirty_bitmap_merge_drv, state);
2215*8187f63cSVladimir Sementsov-Ogievskiy 
22166fd2e407SVladimir Sementsov-Ogievskiy     if (action_check_completion_mode(common, errp) < 0) {
22176fd2e407SVladimir Sementsov-Ogievskiy         return;
22186fd2e407SVladimir Sementsov-Ogievskiy     }
22196fd2e407SVladimir Sementsov-Ogievskiy 
22200e2b7f09SJohn Snow     action = common->action->u.block_dirty_bitmap_merge.data;
2221360d4e4eSJohn Snow 
2222c6996cf9SEric Blake     state->bitmap = block_dirty_bitmap_merge(action->node, action->target,
2223360d4e4eSJohn Snow                                              action->bitmaps, &state->backup,
22246fd2e407SVladimir Sementsov-Ogievskiy                                              errp);
22256fd2e407SVladimir Sementsov-Ogievskiy }
22266fd2e407SVladimir Sementsov-Ogievskiy 
2227*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_remove_commit(void *opaque);
2228*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_remove_abort(void *opaque);
2229*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv block_dirty_bitmap_remove_drv = {
2230*8187f63cSVladimir Sementsov-Ogievskiy     .commit = block_dirty_bitmap_remove_commit,
2231*8187f63cSVladimir Sementsov-Ogievskiy     .abort = block_dirty_bitmap_remove_abort,
2232*8187f63cSVladimir Sementsov-Ogievskiy     .clean = g_free,
2233*8187f63cSVladimir Sementsov-Ogievskiy };
2234*8187f63cSVladimir Sementsov-Ogievskiy 
2235*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_remove_action(BlkActionState *common,
2236*8187f63cSVladimir Sementsov-Ogievskiy                                              Transaction *tran, Error **errp)
2237c4e4b0faSJohn Snow {
2238c4e4b0faSJohn Snow     BlockDirtyBitmap *action;
2239c4e4b0faSJohn Snow     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2240c4e4b0faSJohn Snow                                              common, common);
2241c4e4b0faSJohn Snow 
2242*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &block_dirty_bitmap_remove_drv, state);
2243*8187f63cSVladimir Sementsov-Ogievskiy 
2244c4e4b0faSJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
2245c4e4b0faSJohn Snow         return;
2246c4e4b0faSJohn Snow     }
2247c4e4b0faSJohn Snow 
2248c4e4b0faSJohn Snow     action = common->action->u.block_dirty_bitmap_remove.data;
2249c4e4b0faSJohn Snow 
2250c6996cf9SEric Blake     state->bitmap = block_dirty_bitmap_remove(action->node, action->name,
2251c4e4b0faSJohn Snow                                               false, &state->bs, errp);
2252c4e4b0faSJohn Snow     if (state->bitmap) {
2253c4e4b0faSJohn Snow         bdrv_dirty_bitmap_skip_store(state->bitmap, true);
2254c4e4b0faSJohn Snow         bdrv_dirty_bitmap_set_busy(state->bitmap, true);
2255c4e4b0faSJohn Snow     }
2256c4e4b0faSJohn Snow }
2257c4e4b0faSJohn Snow 
2258*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_remove_abort(void *opaque)
2259c4e4b0faSJohn Snow {
2260*8187f63cSVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = opaque;
2261c4e4b0faSJohn Snow 
2262c4e4b0faSJohn Snow     if (state->bitmap) {
2263c4e4b0faSJohn Snow         bdrv_dirty_bitmap_skip_store(state->bitmap, false);
2264c4e4b0faSJohn Snow         bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2265c4e4b0faSJohn Snow     }
2266c4e4b0faSJohn Snow }
2267c4e4b0faSJohn Snow 
2268*8187f63cSVladimir Sementsov-Ogievskiy static void block_dirty_bitmap_remove_commit(void *opaque)
2269c4e4b0faSJohn Snow {
2270*8187f63cSVladimir Sementsov-Ogievskiy     BlockDirtyBitmapState *state = opaque;
2271c4e4b0faSJohn Snow 
2272c4e4b0faSJohn Snow     bdrv_dirty_bitmap_set_busy(state->bitmap, false);
22735deb6cbdSVladimir Sementsov-Ogievskiy     bdrv_release_dirty_bitmap(state->bitmap);
2274c4e4b0faSJohn Snow }
2275c4e4b0faSJohn Snow 
2276*8187f63cSVladimir Sementsov-Ogievskiy static void abort_commit(void *opaque);
2277*8187f63cSVladimir Sementsov-Ogievskiy TransactionActionDrv abort_drv = {
2278*8187f63cSVladimir Sementsov-Ogievskiy     .commit = abort_commit,
2279*8187f63cSVladimir Sementsov-Ogievskiy     .clean = g_free,
2280*8187f63cSVladimir Sementsov-Ogievskiy };
2281*8187f63cSVladimir Sementsov-Ogievskiy 
2282*8187f63cSVladimir Sementsov-Ogievskiy static void abort_action(BlkActionState *common, Transaction *tran,
2283*8187f63cSVladimir Sementsov-Ogievskiy                          Error **errp)
228478b18b78SStefan Hajnoczi {
2285*8187f63cSVladimir Sementsov-Ogievskiy     tran_add(tran, &abort_drv, common);
228678b18b78SStefan Hajnoczi     error_setg(errp, "Transaction aborted using Abort action");
228778b18b78SStefan Hajnoczi }
228878b18b78SStefan Hajnoczi 
2289*8187f63cSVladimir Sementsov-Ogievskiy static void abort_commit(void *opaque)
229078b18b78SStefan Hajnoczi {
2291dfc6f865SStefan Weil     g_assert_not_reached(); /* this action never succeeds */
229278b18b78SStefan Hajnoczi }
229378b18b78SStefan Hajnoczi 
229450f43f0fSJohn Snow static const BlkActionOps actions[] = {
229543de7e2dSAlberto Garcia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
229643de7e2dSAlberto Garcia         .instance_size = sizeof(ExternalSnapshotState),
2297*8187f63cSVladimir Sementsov-Ogievskiy         .action  = external_snapshot_action,
229843de7e2dSAlberto Garcia     },
2299c8a83e85SKevin Wolf     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2300ba5d6ab6SStefan Hajnoczi         .instance_size = sizeof(ExternalSnapshotState),
2301*8187f63cSVladimir Sementsov-Ogievskiy         .action  = external_snapshot_action,
2302ba0c86a3SWenchao Xia     },
23033037f364SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
23043037f364SStefan Hajnoczi         .instance_size = sizeof(DriveBackupState),
2305*8187f63cSVladimir Sementsov-Ogievskiy         .action = drive_backup_action,
23063037f364SStefan Hajnoczi     },
2307bd8baecdSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2308bd8baecdSFam Zheng         .instance_size = sizeof(BlockdevBackupState),
2309*8187f63cSVladimir Sementsov-Ogievskiy         .action = blockdev_backup_action,
2310bd8baecdSFam Zheng     },
231178b18b78SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_ABORT] = {
231250f43f0fSJohn Snow         .instance_size = sizeof(BlkActionState),
2313*8187f63cSVladimir Sementsov-Ogievskiy         .action = abort_action,
231478b18b78SStefan Hajnoczi     },
2315bbe86010SWenchao Xia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2316bbe86010SWenchao Xia         .instance_size = sizeof(InternalSnapshotState),
2317*8187f63cSVladimir Sementsov-Ogievskiy         .action  = internal_snapshot_action,
2318bbe86010SWenchao Xia     },
2319df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2320df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2321*8187f63cSVladimir Sementsov-Ogievskiy         .action = block_dirty_bitmap_add_action,
2322df9a681dSFam Zheng     },
2323df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2324df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2325*8187f63cSVladimir Sementsov-Ogievskiy         .action = block_dirty_bitmap_clear_action,
2326c6490447SVladimir Sementsov-Ogievskiy     },
23270e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ENABLE] = {
2328c6490447SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
2329*8187f63cSVladimir Sementsov-Ogievskiy         .action = block_dirty_bitmap_enable_action,
2330c6490447SVladimir Sementsov-Ogievskiy     },
23310e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_DISABLE] = {
2332c6490447SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
2333*8187f63cSVladimir Sementsov-Ogievskiy         .action = block_dirty_bitmap_disable_action,
233466da04ddSJohn Snow     },
23350e2b7f09SJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_MERGE] = {
23366fd2e407SVladimir Sementsov-Ogievskiy         .instance_size = sizeof(BlockDirtyBitmapState),
2337*8187f63cSVladimir Sementsov-Ogievskiy         .action = block_dirty_bitmap_merge_action,
23386fd2e407SVladimir Sementsov-Ogievskiy     },
2339c4e4b0faSJohn Snow     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_REMOVE] = {
2340c4e4b0faSJohn Snow         .instance_size = sizeof(BlockDirtyBitmapState),
2341*8187f63cSVladimir Sementsov-Ogievskiy         .action = block_dirty_bitmap_remove_action,
2342c4e4b0faSJohn Snow     },
234366da04ddSJohn Snow     /* Where are transactions for MIRROR, COMMIT and STREAM?
234466da04ddSJohn Snow      * Although these blockjobs use transaction callbacks like the backup job,
234566da04ddSJohn Snow      * these jobs do not necessarily adhere to transaction semantics.
234666da04ddSJohn Snow      * These jobs may not fully undo all of their actions on abort, nor do they
234766da04ddSJohn Snow      * necessarily work in transactions with more than one job in them.
234866da04ddSJohn Snow      */
2349ba0c86a3SWenchao Xia };
2350ba0c86a3SWenchao Xia 
235194d16a64SJohn Snow /**
235294d16a64SJohn Snow  * Allocate a TransactionProperties structure if necessary, and fill
235394d16a64SJohn Snow  * that structure with desired defaults if they are unset.
235494d16a64SJohn Snow  */
235594d16a64SJohn Snow static TransactionProperties *get_transaction_properties(
235694d16a64SJohn Snow     TransactionProperties *props)
235794d16a64SJohn Snow {
235894d16a64SJohn Snow     if (!props) {
235994d16a64SJohn Snow         props = g_new0(TransactionProperties, 1);
236094d16a64SJohn Snow     }
236194d16a64SJohn Snow 
236294d16a64SJohn Snow     if (!props->has_completion_mode) {
236394d16a64SJohn Snow         props->has_completion_mode = true;
236494d16a64SJohn Snow         props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
236594d16a64SJohn Snow     }
236694d16a64SJohn Snow 
236794d16a64SJohn Snow     return props;
236894d16a64SJohn Snow }
236994d16a64SJohn Snow 
23708802d1fdSJeff Cody /*
2371b756b9ceSStefan Hajnoczi  * 'Atomic' group operations.  The operations are performed as a set, and if
2372b756b9ceSStefan Hajnoczi  * any fail then we roll back all operations in the group.
2373ebc2752bSEmanuele Giuseppe Esposito  *
2374ebc2752bSEmanuele Giuseppe Esposito  * Always run under BQL.
23758802d1fdSJeff Cody  */
237694d16a64SJohn Snow void qmp_transaction(TransactionActionList *dev_list,
237794d16a64SJohn Snow                      struct TransactionProperties *props,
237894d16a64SJohn Snow                      Error **errp)
23798802d1fdSJeff Cody {
2380c8a83e85SKevin Wolf     TransactionActionList *dev_entry = dev_list;
2381238e9202SMarkus Armbruster     bool has_props = !!props;
238262c9e416SKevin Wolf     JobTxn *block_job_txn = NULL;
238343e17041SLuiz Capitulino     Error *local_err = NULL;
2384*8187f63cSVladimir Sementsov-Ogievskiy     Transaction *tran = tran_new();
23858802d1fdSJeff Cody 
2386b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2387b4ad82aaSEmanuele Giuseppe Esposito 
238894d16a64SJohn Snow     /* Does this transaction get canceled as a group on failure?
238962c9e416SKevin Wolf      * If not, we don't really need to make a JobTxn.
239094d16a64SJohn Snow      */
239194d16a64SJohn Snow     props = get_transaction_properties(props);
239294d16a64SJohn Snow     if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
23937eaa8fb5SKevin Wolf         block_job_txn = job_txn_new();
239494d16a64SJohn Snow     }
239594d16a64SJohn Snow 
2396b756b9ceSStefan Hajnoczi     /* drain all i/o before any operations */
23978802d1fdSJeff Cody     bdrv_drain_all();
23988802d1fdSJeff Cody 
2399b756b9ceSStefan Hajnoczi     /* We don't do anything in this loop that commits us to the operations */
24008802d1fdSJeff Cody     while (NULL != dev_entry) {
2401c8a83e85SKevin Wolf         TransactionAction *dev_info = NULL;
240250f43f0fSJohn Snow         const BlkActionOps *ops;
2403*8187f63cSVladimir Sementsov-Ogievskiy         BlkActionState *state;
240452e7c241SPaolo Bonzini 
24058802d1fdSJeff Cody         dev_info = dev_entry->value;
24068802d1fdSJeff Cody         dev_entry = dev_entry->next;
24078802d1fdSJeff Cody 
24086a8f9661SEric Blake         assert(dev_info->type < ARRAY_SIZE(actions));
2409ba0c86a3SWenchao Xia 
24106a8f9661SEric Blake         ops = &actions[dev_info->type];
2411aa3fe714SMax Reitz         assert(ops->instance_size > 0);
2412aa3fe714SMax Reitz 
2413ba5d6ab6SStefan Hajnoczi         state = g_malloc0(ops->instance_size);
2414ba5d6ab6SStefan Hajnoczi         state->ops = ops;
2415ba5d6ab6SStefan Hajnoczi         state->action = dev_info;
241694d16a64SJohn Snow         state->block_job_txn = block_job_txn;
241794d16a64SJohn Snow         state->txn_props = props;
24188802d1fdSJeff Cody 
2419*8187f63cSVladimir Sementsov-Ogievskiy         state->ops->action(state, tran, &local_err);
242084d18f06SMarkus Armbruster         if (local_err) {
24219b9877eeSWenchao Xia             error_propagate(errp, local_err);
24229b9877eeSWenchao Xia             goto delete_and_fail;
24239b9877eeSWenchao Xia         }
242452e7c241SPaolo Bonzini     }
24258802d1fdSJeff Cody 
2426*8187f63cSVladimir Sementsov-Ogievskiy     tran_commit(tran);
24278802d1fdSJeff Cody 
24288802d1fdSJeff Cody     /* success */
24298802d1fdSJeff Cody     goto exit;
24308802d1fdSJeff Cody 
24318802d1fdSJeff Cody delete_and_fail:
2432b756b9ceSStefan Hajnoczi     /* failure, and it is all-or-none; roll back all operations */
2433*8187f63cSVladimir Sementsov-Ogievskiy     tran_abort(tran);
24348802d1fdSJeff Cody exit:
243594d16a64SJohn Snow     if (!has_props) {
243694d16a64SJohn Snow         qapi_free_TransactionProperties(props);
243794d16a64SJohn Snow     }
24387eaa8fb5SKevin Wolf     job_txn_unref(block_job_txn);
24398802d1fdSJeff Cody }
24408802d1fdSJeff Cody 
2441a3b52535SVladimir Sementsov-Ogievskiy BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
2442a3b52535SVladimir Sementsov-Ogievskiy                                                               const char *name,
2443a3b52535SVladimir Sementsov-Ogievskiy                                                               Error **errp)
2444a3b52535SVladimir Sementsov-Ogievskiy {
2445a3b52535SVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bitmap;
2446a3b52535SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
2447a3b52535SVladimir Sementsov-Ogievskiy     BlockDirtyBitmapSha256 *ret = NULL;
2448a3b52535SVladimir Sementsov-Ogievskiy     char *sha256;
2449a3b52535SVladimir Sementsov-Ogievskiy 
2450a3b52535SVladimir Sementsov-Ogievskiy     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
2451a3b52535SVladimir Sementsov-Ogievskiy     if (!bitmap || !bs) {
2452a3b52535SVladimir Sementsov-Ogievskiy         return NULL;
2453a3b52535SVladimir Sementsov-Ogievskiy     }
2454a3b52535SVladimir Sementsov-Ogievskiy 
2455a3b52535SVladimir Sementsov-Ogievskiy     sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
2456a3b52535SVladimir Sementsov-Ogievskiy     if (sha256 == NULL) {
2457a3b52535SVladimir Sementsov-Ogievskiy         return NULL;
2458a3b52535SVladimir Sementsov-Ogievskiy     }
2459a3b52535SVladimir Sementsov-Ogievskiy 
2460a3b52535SVladimir Sementsov-Ogievskiy     ret = g_new(BlockDirtyBitmapSha256, 1);
2461a3b52535SVladimir Sementsov-Ogievskiy     ret->sha256 = sha256;
2462a3b52535SVladimir Sementsov-Ogievskiy 
2463a3b52535SVladimir Sementsov-Ogievskiy     return ret;
2464a3b52535SVladimir Sementsov-Ogievskiy }
2465a3b52535SVladimir Sementsov-Ogievskiy 
246654fde4ffSMarkus Armbruster void coroutine_fn qmp_block_resize(const char *device, const char *node_name,
24673b1dbd11SBenoît Canet                                    int64_t size, Error **errp)
24686d4a2b3aSChristoph Hellwig {
24693b1dbd11SBenoît Canet     Error *local_err = NULL;
2470d9dbf25fSKevin Wolf     BlockBackend *blk;
24716d4a2b3aSChristoph Hellwig     BlockDriverState *bs;
2472eb94b81aSKevin Wolf     AioContext *old_ctx;
24736d4a2b3aSChristoph Hellwig 
247454fde4ffSMarkus Armbruster     bs = bdrv_lookup_bs(device, node_name, &local_err);
247584d18f06SMarkus Armbruster     if (local_err) {
24763b1dbd11SBenoît Canet         error_propagate(errp, local_err);
24773b1dbd11SBenoît Canet         return;
24783b1dbd11SBenoît Canet     }
24793b1dbd11SBenoît Canet 
24806d4a2b3aSChristoph Hellwig     if (size < 0) {
2481c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2482d9dbf25fSKevin Wolf         return;
24836d4a2b3aSChristoph Hellwig     }
24846d4a2b3aSChristoph Hellwig 
24859c75e168SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2486c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2487d9dbf25fSKevin Wolf         return;
24889c75e168SJeff Cody     }
24899c75e168SJeff Cody 
24900c7d204fSKevin Wolf     blk = blk_co_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL, errp);
2491a3aeeab5SEric Blake     if (!blk) {
2492d9dbf25fSKevin Wolf         return;
2493d7086422SKevin Wolf     }
24947dad9ee6SKevin Wolf 
24958089eab2SKevin Wolf     bdrv_co_lock(bs);
2496698bdfa0SJohn Snow     bdrv_drained_begin(bs);
24978089eab2SKevin Wolf     bdrv_co_unlock(bs);
24988089eab2SKevin Wolf 
2499eb94b81aSKevin Wolf     old_ctx = bdrv_co_enter(bs);
2500247cf5c0SAlberto Faria     blk_co_truncate(blk, size, false, PREALLOC_MODE_OFF, 0, errp);
2501eb94b81aSKevin Wolf     bdrv_co_leave(bs, old_ctx);
2502927e0e76SStefan Hajnoczi 
2503eb94b81aSKevin Wolf     bdrv_co_lock(bs);
25048089eab2SKevin Wolf     bdrv_drained_end(bs);
25050c7d204fSKevin Wolf     blk_co_unref(blk);
2506eb94b81aSKevin Wolf     bdrv_co_unlock(bs);
25076d4a2b3aSChristoph Hellwig }
250812bd451fSStefan Hajnoczi 
250954fde4ffSMarkus Armbruster void qmp_block_stream(const char *job_id, const char *device,
251054fde4ffSMarkus Armbruster                       const char *base,
251154fde4ffSMarkus Armbruster                       const char *base_node,
251254fde4ffSMarkus Armbruster                       const char *backing_file,
251354fde4ffSMarkus Armbruster                       const char *bottom,
251413d8cc51SJeff Cody                       bool has_speed, int64_t speed,
25151d809098SPaolo Bonzini                       bool has_on_error, BlockdevOnError on_error,
251654fde4ffSMarkus Armbruster                       const char *filter_node_name,
2517241ca1abSJohn Snow                       bool has_auto_finalize, bool auto_finalize,
2518241ca1abSJohn Snow                       bool has_auto_dismiss, bool auto_dismiss,
25191d809098SPaolo Bonzini                       Error **errp)
252012bd451fSStefan Hajnoczi {
25217f4a396dSVladimir Sementsov-Ogievskiy     BlockDriverState *bs, *iter, *iter_end;
2522c8c3080fSMarcelo Tosatti     BlockDriverState *base_bs = NULL;
25237f4a396dSVladimir Sementsov-Ogievskiy     BlockDriverState *bottom_bs = NULL;
2524f3e69bebSStefan Hajnoczi     AioContext *aio_context;
2525fd7f8c65SStefan Hajnoczi     Error *local_err = NULL;
2526cf6320dfSJohn Snow     int job_flags = JOB_DEFAULT;
252712bd451fSStefan Hajnoczi 
252854fde4ffSMarkus Armbruster     if (base && base_node) {
25297f4a396dSVladimir Sementsov-Ogievskiy         error_setg(errp, "'base' and 'base-node' cannot be specified "
25307f4a396dSVladimir Sementsov-Ogievskiy                    "at the same time");
25317f4a396dSVladimir Sementsov-Ogievskiy         return;
25327f4a396dSVladimir Sementsov-Ogievskiy     }
25337f4a396dSVladimir Sementsov-Ogievskiy 
253454fde4ffSMarkus Armbruster     if (base && bottom) {
25357f4a396dSVladimir Sementsov-Ogievskiy         error_setg(errp, "'base' and 'bottom' cannot be specified "
25367f4a396dSVladimir Sementsov-Ogievskiy                    "at the same time");
25377f4a396dSVladimir Sementsov-Ogievskiy         return;
25387f4a396dSVladimir Sementsov-Ogievskiy     }
25397f4a396dSVladimir Sementsov-Ogievskiy 
254054fde4ffSMarkus Armbruster     if (bottom && base_node) {
25417f4a396dSVladimir Sementsov-Ogievskiy         error_setg(errp, "'bottom' and 'base-node' cannot be specified "
25427f4a396dSVladimir Sementsov-Ogievskiy                    "at the same time");
25437f4a396dSVladimir Sementsov-Ogievskiy         return;
25447f4a396dSVladimir Sementsov-Ogievskiy     }
25457f4a396dSVladimir Sementsov-Ogievskiy 
25461d809098SPaolo Bonzini     if (!has_on_error) {
25471d809098SPaolo Bonzini         on_error = BLOCKDEV_ON_ERROR_REPORT;
25481d809098SPaolo Bonzini     }
25491d809098SPaolo Bonzini 
2550554b6147SAlberto Garcia     bs = bdrv_lookup_bs(device, device, errp);
2551b6c1bae5SKevin Wolf     if (!bs) {
255212bd451fSStefan Hajnoczi         return;
255312bd451fSStefan Hajnoczi     }
255412bd451fSStefan Hajnoczi 
2555b6c1bae5SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
2556f3e69bebSStefan Hajnoczi     aio_context_acquire(aio_context);
2557f3e69bebSStefan Hajnoczi 
255854fde4ffSMarkus Armbruster     if (base) {
2559c8c3080fSMarcelo Tosatti         base_bs = bdrv_find_backing_image(bs, base);
2560c8c3080fSMarcelo Tosatti         if (base_bs == NULL) {
2561b0d7be2aSMarkus Armbruster             error_setg(errp, "Can't find '%s' in the backing chain", base);
2562f3e69bebSStefan Hajnoczi             goto out;
256312bd451fSStefan Hajnoczi         }
2564f3e69bebSStefan Hajnoczi         assert(bdrv_get_aio_context(base_bs) == aio_context);
2565c8c3080fSMarcelo Tosatti     }
256612bd451fSStefan Hajnoczi 
256754fde4ffSMarkus Armbruster     if (base_node) {
2568312fe09cSAlberto Garcia         base_bs = bdrv_lookup_bs(NULL, base_node, errp);
2569312fe09cSAlberto Garcia         if (!base_bs) {
2570312fe09cSAlberto Garcia             goto out;
2571312fe09cSAlberto Garcia         }
2572312fe09cSAlberto Garcia         if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
2573312fe09cSAlberto Garcia             error_setg(errp, "Node '%s' is not a backing image of '%s'",
2574312fe09cSAlberto Garcia                        base_node, device);
2575312fe09cSAlberto Garcia             goto out;
2576312fe09cSAlberto Garcia         }
2577312fe09cSAlberto Garcia         assert(bdrv_get_aio_context(base_bs) == aio_context);
2578f30c66baSMax Reitz         bdrv_refresh_filename(base_bs);
2579312fe09cSAlberto Garcia     }
2580312fe09cSAlberto Garcia 
258154fde4ffSMarkus Armbruster     if (bottom) {
25827f4a396dSVladimir Sementsov-Ogievskiy         bottom_bs = bdrv_lookup_bs(NULL, bottom, errp);
25837f4a396dSVladimir Sementsov-Ogievskiy         if (!bottom_bs) {
25847f4a396dSVladimir Sementsov-Ogievskiy             goto out;
25857f4a396dSVladimir Sementsov-Ogievskiy         }
25867f4a396dSVladimir Sementsov-Ogievskiy         if (!bottom_bs->drv) {
25877f4a396dSVladimir Sementsov-Ogievskiy             error_setg(errp, "Node '%s' is not open", bottom);
25887f4a396dSVladimir Sementsov-Ogievskiy             goto out;
25897f4a396dSVladimir Sementsov-Ogievskiy         }
25907f4a396dSVladimir Sementsov-Ogievskiy         if (bottom_bs->drv->is_filter) {
25917f4a396dSVladimir Sementsov-Ogievskiy             error_setg(errp, "Node '%s' is a filter, use a non-filter node "
25927f4a396dSVladimir Sementsov-Ogievskiy                        "as 'bottom'", bottom);
25937f4a396dSVladimir Sementsov-Ogievskiy             goto out;
25947f4a396dSVladimir Sementsov-Ogievskiy         }
25957f4a396dSVladimir Sementsov-Ogievskiy         if (!bdrv_chain_contains(bs, bottom_bs)) {
25967f4a396dSVladimir Sementsov-Ogievskiy             error_setg(errp, "Node '%s' is not in a chain starting from '%s'",
25977f4a396dSVladimir Sementsov-Ogievskiy                        bottom, device);
25987f4a396dSVladimir Sementsov-Ogievskiy             goto out;
25997f4a396dSVladimir Sementsov-Ogievskiy         }
26007f4a396dSVladimir Sementsov-Ogievskiy         assert(bdrv_get_aio_context(bottom_bs) == aio_context);
26017f4a396dSVladimir Sementsov-Ogievskiy     }
26027f4a396dSVladimir Sementsov-Ogievskiy 
26037f4a396dSVladimir Sementsov-Ogievskiy     /*
26047f4a396dSVladimir Sementsov-Ogievskiy      * Check for op blockers in the whole chain between bs and base (or bottom)
26057f4a396dSVladimir Sementsov-Ogievskiy      */
260654fde4ffSMarkus Armbruster     iter_end = bottom ? bdrv_filter_or_cow_bs(bottom_bs) : base_bs;
26077f4a396dSVladimir Sementsov-Ogievskiy     for (iter = bs; iter && iter != iter_end;
260867acfd21SMax Reitz          iter = bdrv_filter_or_cow_bs(iter))
260967acfd21SMax Reitz     {
2610554b6147SAlberto Garcia         if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
2611554b6147SAlberto Garcia             goto out;
2612554b6147SAlberto Garcia         }
2613554b6147SAlberto Garcia     }
2614554b6147SAlberto Garcia 
261513d8cc51SJeff Cody     /* if we are streaming the entire chain, the result will have no backing
261613d8cc51SJeff Cody      * file, and specifying one is therefore an error */
261754fde4ffSMarkus Armbruster     if (!base_bs && backing_file) {
261813d8cc51SJeff Cody         error_setg(errp, "backing file specified, but streaming the "
261913d8cc51SJeff Cody                          "entire chain");
2620f3e69bebSStefan Hajnoczi         goto out;
262113d8cc51SJeff Cody     }
262213d8cc51SJeff Cody 
2623241ca1abSJohn Snow     if (has_auto_finalize && !auto_finalize) {
2624241ca1abSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
2625241ca1abSJohn Snow     }
2626241ca1abSJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
2627241ca1abSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
2628241ca1abSJohn Snow     }
2629241ca1abSJohn Snow 
263054fde4ffSMarkus Armbruster     stream_start(job_id, bs, base_bs, backing_file,
26317f4a396dSVladimir Sementsov-Ogievskiy                  bottom_bs, job_flags, has_speed ? speed : 0, on_error,
2632880747a8SAndrey Shinkevich                  filter_node_name, &local_err);
263384d18f06SMarkus Armbruster     if (local_err) {
2634fd7f8c65SStefan Hajnoczi         error_propagate(errp, local_err);
2635f3e69bebSStefan Hajnoczi         goto out;
263612bd451fSStefan Hajnoczi     }
263712bd451fSStefan Hajnoczi 
2638b23c580cSVladimir Sementsov-Ogievskiy     trace_qmp_block_stream(bs);
2639f3e69bebSStefan Hajnoczi 
2640f3e69bebSStefan Hajnoczi out:
2641f3e69bebSStefan Hajnoczi     aio_context_release(aio_context);
264212bd451fSStefan Hajnoczi }
26432d47c6e9SStefan Hajnoczi 
264454fde4ffSMarkus Armbruster void qmp_block_commit(const char *job_id, const char *device,
264554fde4ffSMarkus Armbruster                       const char *base_node,
264654fde4ffSMarkus Armbruster                       const char *base,
264754fde4ffSMarkus Armbruster                       const char *top_node,
264854fde4ffSMarkus Armbruster                       const char *top,
264954fde4ffSMarkus Armbruster                       const char *backing_file,
2650ed61fc10SJeff Cody                       bool has_speed, int64_t speed,
26518faad1c7SKevin Wolf                       bool has_on_error, BlockdevOnError on_error,
265254fde4ffSMarkus Armbruster                       const char *filter_node_name,
265396fbf534SJohn Snow                       bool has_auto_finalize, bool auto_finalize,
265496fbf534SJohn Snow                       bool has_auto_dismiss, bool auto_dismiss,
2655ed61fc10SJeff Cody                       Error **errp)
2656ed61fc10SJeff Cody {
2657ed61fc10SJeff Cody     BlockDriverState *bs;
2658058223a6SAlberto Garcia     BlockDriverState *iter;
2659ed61fc10SJeff Cody     BlockDriverState *base_bs, *top_bs;
26609e85cd5cSStefan Hajnoczi     AioContext *aio_context;
2661ed61fc10SJeff Cody     Error *local_err = NULL;
26625360782dSJohn Snow     int job_flags = JOB_DEFAULT;
266305ea385aSMax Reitz     uint64_t top_perm, top_shared;
2664ed61fc10SJeff Cody 
266554504663SMax Reitz     if (!has_speed) {
266654504663SMax Reitz         speed = 0;
266754504663SMax Reitz     }
26688faad1c7SKevin Wolf     if (!has_on_error) {
26698faad1c7SKevin Wolf         on_error = BLOCKDEV_ON_ERROR_REPORT;
26708faad1c7SKevin Wolf     }
267196fbf534SJohn Snow     if (has_auto_finalize && !auto_finalize) {
267296fbf534SJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
267396fbf534SJohn Snow     }
267496fbf534SJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
267596fbf534SJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
267696fbf534SJohn Snow     }
267754504663SMax Reitz 
26787676e2c5SJeff Cody     /* Important Note:
26797676e2c5SJeff Cody      *  libvirt relies on the DeviceNotFound error class in order to probe for
26807676e2c5SJeff Cody      *  live commit feature versions; for this to work, we must make sure to
26817676e2c5SJeff Cody      *  perform the device lookup before any generic errors that may occur in a
26827676e2c5SJeff Cody      *  scenario in which all optional arguments are omitted. */
26831d13b167SKevin Wolf     bs = qmp_get_root_bs(device, &local_err);
26841d13b167SKevin Wolf     if (!bs) {
26851d13b167SKevin Wolf         bs = bdrv_lookup_bs(device, device, NULL);
26861d13b167SKevin Wolf         if (!bs) {
26871d13b167SKevin Wolf             error_free(local_err);
268875158ebbSMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
268975158ebbSMarkus Armbruster                       "Device '%s' not found", device);
26901d13b167SKevin Wolf         } else {
26911d13b167SKevin Wolf             error_propagate(errp, local_err);
26921d13b167SKevin Wolf         }
2693ed61fc10SJeff Cody         return;
2694ed61fc10SJeff Cody     }
2695ed61fc10SJeff Cody 
26961d13b167SKevin Wolf     aio_context = bdrv_get_aio_context(bs);
26979e85cd5cSStefan Hajnoczi     aio_context_acquire(aio_context);
26989e85cd5cSStefan Hajnoczi 
2699bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
27009e85cd5cSStefan Hajnoczi         goto out;
2701628ff683SFam Zheng     }
2702628ff683SFam Zheng 
2703ed61fc10SJeff Cody     /* default top_bs is the active layer */
2704ed61fc10SJeff Cody     top_bs = bs;
2705ed61fc10SJeff Cody 
270654fde4ffSMarkus Armbruster     if (top_node && top) {
27073c605f40SKevin Wolf         error_setg(errp, "'top-node' and 'top' are mutually exclusive");
27083c605f40SKevin Wolf         goto out;
270954fde4ffSMarkus Armbruster     } else if (top_node) {
27103c605f40SKevin Wolf         top_bs = bdrv_lookup_bs(NULL, top_node, errp);
27113c605f40SKevin Wolf         if (top_bs == NULL) {
27123c605f40SKevin Wolf             goto out;
27133c605f40SKevin Wolf         }
27143c605f40SKevin Wolf         if (!bdrv_chain_contains(bs, top_bs)) {
27153c605f40SKevin Wolf             error_setg(errp, "'%s' is not in this backing file chain",
27163c605f40SKevin Wolf                        top_node);
27173c605f40SKevin Wolf             goto out;
27183c605f40SKevin Wolf         }
271954fde4ffSMarkus Armbruster     } else if (top) {
2720f30c66baSMax Reitz         /* This strcmp() is just a shortcut, there is no need to
2721f30c66baSMax Reitz          * refresh @bs's filename.  If it mismatches,
2722f30c66baSMax Reitz          * bdrv_find_backing_image() will do the refresh and may still
2723f30c66baSMax Reitz          * return @bs. */
2724ed61fc10SJeff Cody         if (strcmp(bs->filename, top) != 0) {
2725ed61fc10SJeff Cody             top_bs = bdrv_find_backing_image(bs, top);
2726ed61fc10SJeff Cody         }
2727ed61fc10SJeff Cody     }
2728ed61fc10SJeff Cody 
2729ed61fc10SJeff Cody     if (top_bs == NULL) {
2730ed61fc10SJeff Cody         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
27319e85cd5cSStefan Hajnoczi         goto out;
2732ed61fc10SJeff Cody     }
2733ed61fc10SJeff Cody 
27349e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(top_bs) == aio_context);
27359e85cd5cSStefan Hajnoczi 
273654fde4ffSMarkus Armbruster     if (base_node && base) {
27373c605f40SKevin Wolf         error_setg(errp, "'base-node' and 'base' are mutually exclusive");
27383c605f40SKevin Wolf         goto out;
273954fde4ffSMarkus Armbruster     } else if (base_node) {
27403c605f40SKevin Wolf         base_bs = bdrv_lookup_bs(NULL, base_node, errp);
27413c605f40SKevin Wolf         if (base_bs == NULL) {
27423c605f40SKevin Wolf             goto out;
27433c605f40SKevin Wolf         }
27443c605f40SKevin Wolf         if (!bdrv_chain_contains(top_bs, base_bs)) {
27453c605f40SKevin Wolf             error_setg(errp, "'%s' is not in this backing file chain",
27463c605f40SKevin Wolf                        base_node);
27473c605f40SKevin Wolf             goto out;
27483c605f40SKevin Wolf         }
274954fde4ffSMarkus Armbruster     } else if (base) {
2750d5208c45SJeff Cody         base_bs = bdrv_find_backing_image(top_bs, base);
2751b0d7be2aSMarkus Armbruster         if (base_bs == NULL) {
2752b0d7be2aSMarkus Armbruster             error_setg(errp, "Can't find '%s' in the backing chain", base);
2753b0d7be2aSMarkus Armbruster             goto out;
2754b0d7be2aSMarkus Armbruster         }
2755d5208c45SJeff Cody     } else {
2756d5208c45SJeff Cody         base_bs = bdrv_find_base(top_bs);
2757d5208c45SJeff Cody         if (base_bs == NULL) {
2758b0d7be2aSMarkus Armbruster             error_setg(errp, "There is no backimg image");
27599e85cd5cSStefan Hajnoczi             goto out;
2760d5208c45SJeff Cody         }
2761b0d7be2aSMarkus Armbruster     }
2762d5208c45SJeff Cody 
27639e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(base_bs) == aio_context);
27649e85cd5cSStefan Hajnoczi 
27659a71b9deSMax Reitz     for (iter = top_bs; iter != bdrv_filter_or_cow_bs(base_bs);
27669a71b9deSMax Reitz          iter = bdrv_filter_or_cow_bs(iter))
27679a71b9deSMax Reitz     {
2768058223a6SAlberto Garcia         if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2769bb00021dSFam Zheng             goto out;
2770bb00021dSFam Zheng         }
2771058223a6SAlberto Garcia     }
2772bb00021dSFam Zheng 
27737676e2c5SJeff Cody     /* Do not allow attempts to commit an image into itself */
27747676e2c5SJeff Cody     if (top_bs == base_bs) {
27757676e2c5SJeff Cody         error_setg(errp, "cannot commit an image into itself");
27769e85cd5cSStefan Hajnoczi         goto out;
27777676e2c5SJeff Cody     }
27787676e2c5SJeff Cody 
277905ea385aSMax Reitz     /*
278005ea385aSMax Reitz      * Active commit is required if and only if someone has taken a
278105ea385aSMax Reitz      * WRITE permission on the top node.  Historically, we have always
278205ea385aSMax Reitz      * used active commit for top nodes, so continue that practice
278305ea385aSMax Reitz      * lest we possibly break clients that rely on this behavior, e.g.
278405ea385aSMax Reitz      * to later attach this node to a writing parent.
278505ea385aSMax Reitz      * (Active commit is never really wrong.)
278605ea385aSMax Reitz      */
278705ea385aSMax Reitz     bdrv_get_cumulative_perm(top_bs, &top_perm, &top_shared);
278805ea385aSMax Reitz     if (top_perm & BLK_PERM_WRITE ||
278905ea385aSMax Reitz         bdrv_skip_filters(top_bs) == bdrv_skip_filters(bs))
279005ea385aSMax Reitz     {
279154fde4ffSMarkus Armbruster         if (backing_file) {
279205ea385aSMax Reitz             if (bdrv_skip_filters(top_bs) == bdrv_skip_filters(bs)) {
279354e26900SJeff Cody                 error_setg(errp, "'backing-file' specified,"
279454e26900SJeff Cody                                  " but 'top' is the active layer");
279505ea385aSMax Reitz             } else {
279605ea385aSMax Reitz                 error_setg(errp, "'backing-file' specified, but 'top' has a "
279705ea385aSMax Reitz                                  "writer on it");
279805ea385aSMax Reitz             }
27999e85cd5cSStefan Hajnoczi             goto out;
280054e26900SJeff Cody         }
280154fde4ffSMarkus Armbruster         if (!job_id) {
280205ea385aSMax Reitz             /*
280305ea385aSMax Reitz              * Emulate here what block_job_create() does, because it
280405ea385aSMax Reitz              * is possible that @bs != @top_bs (the block job should
280505ea385aSMax Reitz              * be named after @bs, even if @top_bs is the actual
280605ea385aSMax Reitz              * source)
280705ea385aSMax Reitz              */
280805ea385aSMax Reitz             job_id = bdrv_get_device_name(bs);
280905ea385aSMax Reitz         }
281005ea385aSMax Reitz         commit_active_start(job_id, top_bs, base_bs, job_flags, speed, on_error,
281178bbd910SFam Zheng                             filter_node_name, NULL, NULL, false, &local_err);
281220a63d2cSFam Zheng     } else {
2813058223a6SAlberto Garcia         BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
2814058223a6SAlberto Garcia         if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2815058223a6SAlberto Garcia             goto out;
2816058223a6SAlberto Garcia         }
281754fde4ffSMarkus Armbruster         commit_start(job_id, bs, base_bs, top_bs, job_flags,
281854fde4ffSMarkus Armbruster                      speed, on_error, backing_file,
28190db832f4SKevin Wolf                      filter_node_name, &local_err);
282020a63d2cSFam Zheng     }
2821ed61fc10SJeff Cody     if (local_err != NULL) {
2822ed61fc10SJeff Cody         error_propagate(errp, local_err);
28239e85cd5cSStefan Hajnoczi         goto out;
2824ed61fc10SJeff Cody     }
28259e85cd5cSStefan Hajnoczi 
28269e85cd5cSStefan Hajnoczi out:
28279e85cd5cSStefan Hajnoczi     aio_context_release(aio_context);
2828ed61fc10SJeff Cody }
2829ed61fc10SJeff Cody 
28307b0b870bSJohn Snow /* Common QMP interface for drive-backup and blockdev-backup */
28317b0b870bSJohn Snow static BlockJob *do_backup_common(BackupCommon *backup,
28327b0b870bSJohn Snow                                   BlockDriverState *bs,
28337b0b870bSJohn Snow                                   BlockDriverState *target_bs,
28347b0b870bSJohn Snow                                   AioContext *aio_context,
28357b0b870bSJohn Snow                                   JobTxn *txn, Error **errp)
283699a9addfSStefan Hajnoczi {
2837111049a4SJohn Snow     BlockJob *job = NULL;
2838d58d8453SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
28396a30f663SVladimir Sementsov-Ogievskiy     BackupPerf perf = { .max_workers = 64 };
28407b0b870bSJohn Snow     int job_flags = JOB_DEFAULT;
284199a9addfSStefan Hajnoczi 
284281206a89SPavel Butsykin     if (!backup->has_speed) {
284381206a89SPavel Butsykin         backup->speed = 0;
284499a9addfSStefan Hajnoczi     }
284581206a89SPavel Butsykin     if (!backup->has_on_source_error) {
284681206a89SPavel Butsykin         backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
284799a9addfSStefan Hajnoczi     }
284881206a89SPavel Butsykin     if (!backup->has_on_target_error) {
284981206a89SPavel Butsykin         backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
285099a9addfSStefan Hajnoczi     }
2851b40dacdcSJohn Snow     if (!backup->has_auto_finalize) {
2852b40dacdcSJohn Snow         backup->auto_finalize = true;
2853b40dacdcSJohn Snow     }
2854b40dacdcSJohn Snow     if (!backup->has_auto_dismiss) {
2855b40dacdcSJohn Snow         backup->auto_dismiss = true;
2856b40dacdcSJohn Snow     }
285713b9414bSPavel Butsykin     if (!backup->has_compress) {
285813b9414bSPavel Butsykin         backup->compress = false;
285913b9414bSPavel Butsykin     }
286099a9addfSStefan Hajnoczi 
286186c6a3b6SVladimir Sementsov-Ogievskiy     if (backup->x_perf) {
286286c6a3b6SVladimir Sementsov-Ogievskiy         if (backup->x_perf->has_use_copy_range) {
286386c6a3b6SVladimir Sementsov-Ogievskiy             perf.use_copy_range = backup->x_perf->use_copy_range;
286486c6a3b6SVladimir Sementsov-Ogievskiy         }
28652c59fd83SVladimir Sementsov-Ogievskiy         if (backup->x_perf->has_max_workers) {
28662c59fd83SVladimir Sementsov-Ogievskiy             perf.max_workers = backup->x_perf->max_workers;
28672c59fd83SVladimir Sementsov-Ogievskiy         }
28682c59fd83SVladimir Sementsov-Ogievskiy         if (backup->x_perf->has_max_chunk) {
28692c59fd83SVladimir Sementsov-Ogievskiy             perf.max_chunk = backup->x_perf->max_chunk;
28702c59fd83SVladimir Sementsov-Ogievskiy         }
287186c6a3b6SVladimir Sementsov-Ogievskiy     }
287286c6a3b6SVladimir Sementsov-Ogievskiy 
2873a6c9365aSJohn Snow     if ((backup->sync == MIRROR_SYNC_MODE_BITMAP) ||
2874a6c9365aSJohn Snow         (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL)) {
2875a6c9365aSJohn Snow         /* done before desugaring 'incremental' to print the right message */
287654fde4ffSMarkus Armbruster         if (!backup->bitmap) {
2877a6c9365aSJohn Snow             error_setg(errp, "must provide a valid bitmap name for "
2878a6c9365aSJohn Snow                        "'%s' sync mode", MirrorSyncMode_str(backup->sync));
2879a6c9365aSJohn Snow             return NULL;
2880a6c9365aSJohn Snow         }
2881a6c9365aSJohn Snow     }
2882a6c9365aSJohn Snow 
2883c8b56501SJohn Snow     if (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL) {
2884c8b56501SJohn Snow         if (backup->has_bitmap_mode &&
2885c8b56501SJohn Snow             backup->bitmap_mode != BITMAP_SYNC_MODE_ON_SUCCESS) {
2886c8b56501SJohn Snow             error_setg(errp, "Bitmap sync mode must be '%s' "
2887c8b56501SJohn Snow                        "when using sync mode '%s'",
2888c8b56501SJohn Snow                        BitmapSyncMode_str(BITMAP_SYNC_MODE_ON_SUCCESS),
2889c8b56501SJohn Snow                        MirrorSyncMode_str(backup->sync));
2890c8b56501SJohn Snow             return NULL;
2891c8b56501SJohn Snow         }
2892c8b56501SJohn Snow         backup->has_bitmap_mode = true;
2893c8b56501SJohn Snow         backup->sync = MIRROR_SYNC_MODE_BITMAP;
2894c8b56501SJohn Snow         backup->bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
2895c8b56501SJohn Snow     }
2896c8b56501SJohn Snow 
289754fde4ffSMarkus Armbruster     if (backup->bitmap) {
28987b0b870bSJohn Snow         bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
28997b0b870bSJohn Snow         if (!bmap) {
29007b0b870bSJohn Snow             error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
29017b0b870bSJohn Snow             return NULL;
29027b0b870bSJohn Snow         }
2903c8b56501SJohn Snow         if (!backup->has_bitmap_mode) {
2904c8b56501SJohn Snow             error_setg(errp, "Bitmap sync mode must be given "
2905c8b56501SJohn Snow                        "when providing a bitmap");
2906c8b56501SJohn Snow             return NULL;
2907c8b56501SJohn Snow         }
2908b30ffbefSJohn Snow         if (bdrv_dirty_bitmap_check(bmap, BDRV_BITMAP_ALLOW_RO, errp)) {
29097b0b870bSJohn Snow             return NULL;
29107b0b870bSJohn Snow         }
29111a2b8b40SJohn Snow 
29121a2b8b40SJohn Snow         /* This does not produce a useful bitmap artifact: */
29131a2b8b40SJohn Snow         if (backup->sync == MIRROR_SYNC_MODE_NONE) {
29141a2b8b40SJohn Snow             error_setg(errp, "sync mode '%s' does not produce meaningful bitmap"
29151a2b8b40SJohn Snow                        " outputs", MirrorSyncMode_str(backup->sync));
29161a2b8b40SJohn Snow             return NULL;
29171a2b8b40SJohn Snow         }
29181a2b8b40SJohn Snow 
29191a2b8b40SJohn Snow         /* If the bitmap isn't used for input or output, this is useless: */
29201a2b8b40SJohn Snow         if (backup->bitmap_mode == BITMAP_SYNC_MODE_NEVER &&
29211a2b8b40SJohn Snow             backup->sync != MIRROR_SYNC_MODE_BITMAP) {
29221a2b8b40SJohn Snow             error_setg(errp, "Bitmap sync mode '%s' has no meaningful effect"
29231a2b8b40SJohn Snow                        " when combined with sync mode '%s'",
29241a2b8b40SJohn Snow                        BitmapSyncMode_str(backup->bitmap_mode),
29251a2b8b40SJohn Snow                        MirrorSyncMode_str(backup->sync));
29261a2b8b40SJohn Snow             return NULL;
29271a2b8b40SJohn Snow         }
29281a2b8b40SJohn Snow     }
29291a2b8b40SJohn Snow 
293054fde4ffSMarkus Armbruster     if (!backup->bitmap && backup->has_bitmap_mode) {
29311a2b8b40SJohn Snow         error_setg(errp, "Cannot specify bitmap sync mode without a bitmap");
29321a2b8b40SJohn Snow         return NULL;
29337b0b870bSJohn Snow     }
29347b0b870bSJohn Snow 
29357b0b870bSJohn Snow     if (!backup->auto_finalize) {
29367b0b870bSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
29377b0b870bSJohn Snow     }
29387b0b870bSJohn Snow     if (!backup->auto_dismiss) {
29397b0b870bSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
29407b0b870bSJohn Snow     }
29417b0b870bSJohn Snow 
29427b0b870bSJohn Snow     job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
2943c8b56501SJohn Snow                             backup->sync, bmap, backup->bitmap_mode,
2944c8b56501SJohn Snow                             backup->compress,
294500e30f05SVladimir Sementsov-Ogievskiy                             backup->filter_node_name,
294686c6a3b6SVladimir Sementsov-Ogievskiy                             &perf,
2947c8b56501SJohn Snow                             backup->on_source_error,
2948c8b56501SJohn Snow                             backup->on_target_error,
29497b0b870bSJohn Snow                             job_flags, NULL, NULL, txn, errp);
29507b0b870bSJohn Snow     return job;
29517b0b870bSJohn Snow }
29527b0b870bSJohn Snow 
29532288ccfaSSergio Lopez void qmp_drive_backup(DriveBackup *backup, Error **errp)
29547b0b870bSJohn Snow {
29552288ccfaSSergio Lopez     TransactionAction action = {
29562288ccfaSSergio Lopez         .type = TRANSACTION_ACTION_KIND_DRIVE_BACKUP,
29572288ccfaSSergio Lopez         .u.drive_backup.data = backup,
29582288ccfaSSergio Lopez     };
29592288ccfaSSergio Lopez     blockdev_do_action(&action, errp);
296078f51fdeSJohn Snow }
296178f51fdeSJohn Snow 
2962facda544SPeter Krempa BlockDeviceInfoList *qmp_query_named_block_nodes(bool has_flat,
2963facda544SPeter Krempa                                                  bool flat,
2964facda544SPeter Krempa                                                  Error **errp)
2965c13163fbSBenoît Canet {
2966facda544SPeter Krempa     bool return_flat = has_flat && flat;
2967facda544SPeter Krempa 
2968facda544SPeter Krempa     return bdrv_named_nodes_list(return_flat, errp);
2969c13163fbSBenoît Canet }
2970c13163fbSBenoît Canet 
29715d3b4e99SVladimir Sementsov-Ogievskiy XDbgBlockGraph *qmp_x_debug_query_block_graph(Error **errp)
29725d3b4e99SVladimir Sementsov-Ogievskiy {
29735d3b4e99SVladimir Sementsov-Ogievskiy     return bdrv_get_xdbg_block_graph(errp);
29745d3b4e99SVladimir Sementsov-Ogievskiy }
29755d3b4e99SVladimir Sementsov-Ogievskiy 
29765b7bfe51SSergio Lopez void qmp_blockdev_backup(BlockdevBackup *backup, Error **errp)
2977c29c1dd3SFam Zheng {
29785b7bfe51SSergio Lopez     TransactionAction action = {
29795b7bfe51SSergio Lopez         .type = TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP,
29805b7bfe51SSergio Lopez         .u.blockdev_backup.data = backup,
29815b7bfe51SSergio Lopez     };
29825b7bfe51SSergio Lopez     blockdev_do_action(&action, errp);
298378f51fdeSJohn Snow }
298478f51fdeSJohn Snow 
29854193cdd7SFam Zheng /* Parameter check and block job starting for drive mirroring.
29864193cdd7SFam Zheng  * Caller should hold @device and @target's aio context (must be the same).
29874193cdd7SFam Zheng  **/
298871aa9867SAlberto Garcia static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
29894193cdd7SFam Zheng                                    BlockDriverState *target,
299054fde4ffSMarkus Armbruster                                    const char *replaces,
2991d9b902dbSPaolo Bonzini                                    enum MirrorSyncMode sync,
2992274fcceeSMax Reitz                                    BlockMirrorBackingMode backing_mode,
2993cdf3bc93SMax Reitz                                    bool zero_target,
2994b952b558SPaolo Bonzini                                    bool has_speed, int64_t speed,
2995eee13dfeSPaolo Bonzini                                    bool has_granularity, uint32_t granularity,
299608e4ed6cSPaolo Bonzini                                    bool has_buf_size, int64_t buf_size,
29974193cdd7SFam Zheng                                    bool has_on_source_error,
29984193cdd7SFam Zheng                                    BlockdevOnError on_source_error,
29994193cdd7SFam Zheng                                    bool has_on_target_error,
30004193cdd7SFam Zheng                                    BlockdevOnError on_target_error,
30010fc9f8eaSFam Zheng                                    bool has_unmap, bool unmap,
30026cdbceb1SKevin Wolf                                    const char *filter_node_name,
3003481debaaSMax Reitz                                    bool has_copy_mode, MirrorCopyMode copy_mode,
3004a6b58adeSJohn Snow                                    bool has_auto_finalize, bool auto_finalize,
3005a6b58adeSJohn Snow                                    bool has_auto_dismiss, bool auto_dismiss,
3006b952b558SPaolo Bonzini                                    Error **errp)
3007d9b902dbSPaolo Bonzini {
30083f072a7fSMax Reitz     BlockDriverState *unfiltered_bs;
3009a1999b33SJohn Snow     int job_flags = JOB_DEFAULT;
3010d9b902dbSPaolo Bonzini 
3011533c6e4eSKevin Wolf     GLOBAL_STATE_CODE();
3012533c6e4eSKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
3013533c6e4eSKevin Wolf 
3014d9b902dbSPaolo Bonzini     if (!has_speed) {
3015d9b902dbSPaolo Bonzini         speed = 0;
3016d9b902dbSPaolo Bonzini     }
3017b952b558SPaolo Bonzini     if (!has_on_source_error) {
3018b952b558SPaolo Bonzini         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3019b952b558SPaolo Bonzini     }
3020b952b558SPaolo Bonzini     if (!has_on_target_error) {
3021b952b558SPaolo Bonzini         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3022b952b558SPaolo Bonzini     }
3023eee13dfeSPaolo Bonzini     if (!has_granularity) {
3024eee13dfeSPaolo Bonzini         granularity = 0;
3025eee13dfeSPaolo Bonzini     }
302608e4ed6cSPaolo Bonzini     if (!has_buf_size) {
302748ac0a4dSWen Congyang         buf_size = 0;
302808e4ed6cSPaolo Bonzini     }
30290fc9f8eaSFam Zheng     if (!has_unmap) {
30300fc9f8eaSFam Zheng         unmap = true;
30310fc9f8eaSFam Zheng     }
3032481debaaSMax Reitz     if (!has_copy_mode) {
3033481debaaSMax Reitz         copy_mode = MIRROR_COPY_MODE_BACKGROUND;
3034481debaaSMax Reitz     }
3035a6b58adeSJohn Snow     if (has_auto_finalize && !auto_finalize) {
3036a6b58adeSJohn Snow         job_flags |= JOB_MANUAL_FINALIZE;
3037a6b58adeSJohn Snow     }
3038a6b58adeSJohn Snow     if (has_auto_dismiss && !auto_dismiss) {
3039a6b58adeSJohn Snow         job_flags |= JOB_MANUAL_DISMISS;
3040a6b58adeSJohn Snow     }
304108e4ed6cSPaolo Bonzini 
3042eee13dfeSPaolo Bonzini     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3043c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
30443cbbe9fdSStefan Hajnoczi                    "a value in range [512B, 64MB]");
3045eee13dfeSPaolo Bonzini         return;
3046eee13dfeSPaolo Bonzini     }
3047eee13dfeSPaolo Bonzini     if (granularity & (granularity - 1)) {
3048c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
30496cc0667dSMarkus Armbruster                    "a power of 2");
3050eee13dfeSPaolo Bonzini         return;
3051eee13dfeSPaolo Bonzini     }
3052d9b902dbSPaolo Bonzini 
30534193cdd7SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
30544193cdd7SFam Zheng         return;
30554193cdd7SFam Zheng     }
3056e40e5027SFam Zheng     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3057e40e5027SFam Zheng         return;
3058e40e5027SFam Zheng     }
30594193cdd7SFam Zheng 
30603f072a7fSMax Reitz     if (!bdrv_backing_chain_next(bs) && sync == MIRROR_SYNC_MODE_TOP) {
30614193cdd7SFam Zheng         sync = MIRROR_SYNC_MODE_FULL;
30624193cdd7SFam Zheng     }
30634193cdd7SFam Zheng 
306454fde4ffSMarkus Armbruster     if (!replaces) {
30653f072a7fSMax Reitz         /* We want to mirror from @bs, but keep implicit filters on top */
30663f072a7fSMax Reitz         unfiltered_bs = bdrv_skip_implicit_filters(bs);
30673f072a7fSMax Reitz         if (unfiltered_bs != bs) {
30683f072a7fSMax Reitz             replaces = unfiltered_bs->node_name;
30693f072a7fSMax Reitz         }
30703f072a7fSMax Reitz     }
30713f072a7fSMax Reitz 
307254fde4ffSMarkus Armbruster     if (replaces) {
307374ce9e46SMax Reitz         BlockDriverState *to_replace_bs;
307474ce9e46SMax Reitz         AioContext *replace_aio_context;
307574ce9e46SMax Reitz         int64_t bs_size, replace_size;
307674ce9e46SMax Reitz 
307774ce9e46SMax Reitz         bs_size = bdrv_getlength(bs);
307874ce9e46SMax Reitz         if (bs_size < 0) {
307974ce9e46SMax Reitz             error_setg_errno(errp, -bs_size, "Failed to query device's size");
308074ce9e46SMax Reitz             return;
308174ce9e46SMax Reitz         }
308274ce9e46SMax Reitz 
308374ce9e46SMax Reitz         to_replace_bs = check_to_replace_node(bs, replaces, errp);
308474ce9e46SMax Reitz         if (!to_replace_bs) {
308574ce9e46SMax Reitz             return;
308674ce9e46SMax Reitz         }
308774ce9e46SMax Reitz 
308874ce9e46SMax Reitz         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
308974ce9e46SMax Reitz         aio_context_acquire(replace_aio_context);
309074ce9e46SMax Reitz         replace_size = bdrv_getlength(to_replace_bs);
309174ce9e46SMax Reitz         aio_context_release(replace_aio_context);
309274ce9e46SMax Reitz 
309374ce9e46SMax Reitz         if (replace_size < 0) {
309474ce9e46SMax Reitz             error_setg_errno(errp, -replace_size,
309574ce9e46SMax Reitz                              "Failed to query the replacement node's size");
309674ce9e46SMax Reitz             return;
309774ce9e46SMax Reitz         }
309874ce9e46SMax Reitz         if (bs_size != replace_size) {
309974ce9e46SMax Reitz             error_setg(errp, "cannot replace image with a mirror image of "
310074ce9e46SMax Reitz                              "different size");
310174ce9e46SMax Reitz             return;
310274ce9e46SMax Reitz         }
310374ce9e46SMax Reitz     }
310474ce9e46SMax Reitz 
31054193cdd7SFam Zheng     /* pass the node name to replace to mirror start since it's loose coupling
31064193cdd7SFam Zheng      * and will allow to check whether the node still exist at mirror completion
31074193cdd7SFam Zheng      */
310871aa9867SAlberto Garcia     mirror_start(job_id, bs, target,
310954fde4ffSMarkus Armbruster                  replaces, job_flags,
3110cdf3bc93SMax Reitz                  speed, granularity, buf_size, sync, backing_mode, zero_target,
31116cdbceb1SKevin Wolf                  on_source_error, on_target_error, unmap, filter_node_name,
3112481debaaSMax Reitz                  copy_mode, errp);
31134193cdd7SFam Zheng }
31144193cdd7SFam Zheng 
3115faecd40aSEric Blake void qmp_drive_mirror(DriveMirror *arg, Error **errp)
31164193cdd7SFam Zheng {
31174193cdd7SFam Zheng     BlockDriverState *bs;
31183f072a7fSMax Reitz     BlockDriverState *target_backing_bs, *target_bs;
31194193cdd7SFam Zheng     AioContext *aio_context;
31203ea67e08SSergio Lopez     AioContext *old_context;
3121274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode;
31224193cdd7SFam Zheng     Error *local_err = NULL;
31234193cdd7SFam Zheng     QDict *options = NULL;
31244193cdd7SFam Zheng     int flags;
31254193cdd7SFam Zheng     int64_t size;
3126faecd40aSEric Blake     const char *format = arg->format;
3127cdf3bc93SMax Reitz     bool zero_target;
31288ed7d42fSKevin Wolf     int ret;
31294193cdd7SFam Zheng 
31300524e93aSKevin Wolf     bs = qmp_get_root_bs(arg->device, errp);
31310524e93aSKevin Wolf     if (!bs) {
3132d9b902dbSPaolo Bonzini         return;
3133d9b902dbSPaolo Bonzini     }
3134d9b902dbSPaolo Bonzini 
3135cb2af917SPaolo Bonzini     /* Early check to avoid creating target */
3136cb2af917SPaolo Bonzini     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3137cb2af917SPaolo Bonzini         return;
3138cb2af917SPaolo Bonzini     }
3139cb2af917SPaolo Bonzini 
31400524e93aSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
31415a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
31425a7e7a0bSStefan Hajnoczi 
3143faecd40aSEric Blake     if (!arg->has_mode) {
3144faecd40aSEric Blake         arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
31454193cdd7SFam Zheng     }
3146d9b902dbSPaolo Bonzini 
314754fde4ffSMarkus Armbruster     if (!arg->format) {
3148faecd40aSEric Blake         format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3149faecd40aSEric Blake                   ? NULL : bs->drv->format_name);
3150d9b902dbSPaolo Bonzini     }
3151d9b902dbSPaolo Bonzini 
315261de4c68SKevin Wolf     flags = bs->open_flags | BDRV_O_RDWR;
31533f072a7fSMax Reitz     target_backing_bs = bdrv_cow_bs(bdrv_skip_filters(bs));
31543f072a7fSMax Reitz     if (!target_backing_bs && arg->sync == MIRROR_SYNC_MODE_TOP) {
3155faecd40aSEric Blake         arg->sync = MIRROR_SYNC_MODE_FULL;
3156d9b902dbSPaolo Bonzini     }
3157faecd40aSEric Blake     if (arg->sync == MIRROR_SYNC_MODE_NONE) {
31583f072a7fSMax Reitz         target_backing_bs = bs;
3159117e0c82SMax Reitz     }
3160d9b902dbSPaolo Bonzini 
3161ac3c5d83SStefan Hajnoczi     size = bdrv_getlength(bs);
3162ac3c5d83SStefan Hajnoczi     if (size < 0) {
3163ac3c5d83SStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
31645a7e7a0bSStefan Hajnoczi         goto out;
3165ac3c5d83SStefan Hajnoczi     }
3166ac3c5d83SStefan Hajnoczi 
316754fde4ffSMarkus Armbruster     if (arg->replaces) {
316854fde4ffSMarkus Armbruster         if (!arg->node_name) {
316909158f00SBenoît Canet             error_setg(errp, "a node-name must be provided when replacing a"
317009158f00SBenoît Canet                              " named node of the graph");
31715a7e7a0bSStefan Hajnoczi             goto out;
317209158f00SBenoît Canet         }
317309158f00SBenoît Canet     }
317409158f00SBenoît Canet 
3175faecd40aSEric Blake     if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3176274fcceeSMax Reitz         backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3177274fcceeSMax Reitz     } else {
3178274fcceeSMax Reitz         backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3179274fcceeSMax Reitz     }
3180274fcceeSMax Reitz 
31812a32c6e8SJohn Snow     /* Don't open backing image in create() */
31822a32c6e8SJohn Snow     flags |= BDRV_O_NO_BACKING;
31832a32c6e8SJohn Snow 
31843f072a7fSMax Reitz     if ((arg->sync == MIRROR_SYNC_MODE_FULL || !target_backing_bs)
3185faecd40aSEric Blake         && arg->mode != NEW_IMAGE_MODE_EXISTING)
318614526864SMax Reitz     {
3187d9b902dbSPaolo Bonzini         /* create new image w/o backing file */
3188e6641719SMax Reitz         assert(format);
3189faecd40aSEric Blake         bdrv_img_create(arg->target, format,
31909217283dSFam Zheng                         NULL, NULL, NULL, size, flags, false, &local_err);
3191d9b902dbSPaolo Bonzini     } else {
31923f072a7fSMax Reitz         /* Implicit filters should not appear in the filename */
31933f072a7fSMax Reitz         BlockDriverState *explicit_backing =
31943f072a7fSMax Reitz             bdrv_skip_implicit_filters(target_backing_bs);
31953f072a7fSMax Reitz 
3196faecd40aSEric Blake         switch (arg->mode) {
3197d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_EXISTING:
3198d9b902dbSPaolo Bonzini             break;
3199d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3200d9b902dbSPaolo Bonzini             /* create new image with backing file */
32013f072a7fSMax Reitz             bdrv_refresh_filename(explicit_backing);
3202faecd40aSEric Blake             bdrv_img_create(arg->target, format,
32033f072a7fSMax Reitz                             explicit_backing->filename,
32043f072a7fSMax Reitz                             explicit_backing->drv->format_name,
32059217283dSFam Zheng                             NULL, size, flags, false, &local_err);
3206d9b902dbSPaolo Bonzini             break;
3207d9b902dbSPaolo Bonzini         default:
3208d9b902dbSPaolo Bonzini             abort();
3209d9b902dbSPaolo Bonzini         }
3210d9b902dbSPaolo Bonzini     }
3211d9b902dbSPaolo Bonzini 
321284d18f06SMarkus Armbruster     if (local_err) {
3213cf8f2426SLuiz Capitulino         error_propagate(errp, local_err);
32145a7e7a0bSStefan Hajnoczi         goto out;
3215d9b902dbSPaolo Bonzini     }
3216d9b902dbSPaolo Bonzini 
32174c828dc6SBenoît Canet     options = qdict_new();
321854fde4ffSMarkus Armbruster     if (arg->node_name) {
321946f5ac20SEric Blake         qdict_put_str(options, "node-name", arg->node_name);
32204c828dc6SBenoît Canet     }
3221e6641719SMax Reitz     if (format) {
322246f5ac20SEric Blake         qdict_put_str(options, "driver", format);
3223e6641719SMax Reitz     }
32244c828dc6SBenoît Canet 
3225b812f671SPaolo Bonzini     /* Mirroring takes care of copy-on-write using the source's backing
3226b812f671SPaolo Bonzini      * file.
3227b812f671SPaolo Bonzini      */
32282a32c6e8SJohn Snow     target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
32295b363937SMax Reitz     if (!target_bs) {
32305a7e7a0bSStefan Hajnoczi         goto out;
3231d9b902dbSPaolo Bonzini     }
3232d9b902dbSPaolo Bonzini 
3233cdf3bc93SMax Reitz     zero_target = (arg->sync == MIRROR_SYNC_MODE_FULL &&
3234cdf3bc93SMax Reitz                    (arg->mode == NEW_IMAGE_MODE_EXISTING ||
3235cdf3bc93SMax Reitz                     !bdrv_has_zero_init(target_bs)));
3236cdf3bc93SMax Reitz 
32373ea67e08SSergio Lopez 
3238142e6907SEmanuele Giuseppe Esposito     /* Honor bdrv_try_change_aio_context() context acquisition requirements. */
32393ea67e08SSergio Lopez     old_context = bdrv_get_aio_context(target_bs);
32403ea67e08SSergio Lopez     aio_context_release(aio_context);
32413ea67e08SSergio Lopez     aio_context_acquire(old_context);
32423ea67e08SSergio Lopez 
3243142e6907SEmanuele Giuseppe Esposito     ret = bdrv_try_change_aio_context(target_bs, aio_context, NULL, errp);
32448ed7d42fSKevin Wolf     if (ret < 0) {
32458ed7d42fSKevin Wolf         bdrv_unref(target_bs);
32463ea67e08SSergio Lopez         aio_context_release(old_context);
32473ea67e08SSergio Lopez         return;
32488ed7d42fSKevin Wolf     }
32495a7e7a0bSStefan Hajnoczi 
32503ea67e08SSergio Lopez     aio_context_release(old_context);
32513ea67e08SSergio Lopez     aio_context_acquire(aio_context);
32523ea67e08SSergio Lopez 
325354fde4ffSMarkus Armbruster     blockdev_mirror_common(arg->job_id, bs, target_bs,
325454fde4ffSMarkus Armbruster                            arg->replaces, arg->sync,
3255cdf3bc93SMax Reitz                            backing_mode, zero_target,
3256cdf3bc93SMax Reitz                            arg->has_speed, arg->speed,
3257faecd40aSEric Blake                            arg->has_granularity, arg->granularity,
3258faecd40aSEric Blake                            arg->has_buf_size, arg->buf_size,
3259faecd40aSEric Blake                            arg->has_on_source_error, arg->on_source_error,
3260faecd40aSEric Blake                            arg->has_on_target_error, arg->on_target_error,
3261faecd40aSEric Blake                            arg->has_unmap, arg->unmap,
326254fde4ffSMarkus Armbruster                            NULL,
3263481debaaSMax Reitz                            arg->has_copy_mode, arg->copy_mode,
3264a6b58adeSJohn Snow                            arg->has_auto_finalize, arg->auto_finalize,
3265a6b58adeSJohn Snow                            arg->has_auto_dismiss, arg->auto_dismiss,
3266992861fbSMarkus Armbruster                            errp);
3267e253f4b8SKevin Wolf     bdrv_unref(target_bs);
32685a7e7a0bSStefan Hajnoczi out:
32695a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
3270d9b902dbSPaolo Bonzini }
3271d9b902dbSPaolo Bonzini 
327254fde4ffSMarkus Armbruster void qmp_blockdev_mirror(const char *job_id,
327371aa9867SAlberto Garcia                          const char *device, const char *target,
327454fde4ffSMarkus Armbruster                          const char *replaces,
3275df92562eSFam Zheng                          MirrorSyncMode sync,
3276df92562eSFam Zheng                          bool has_speed, int64_t speed,
3277df92562eSFam Zheng                          bool has_granularity, uint32_t granularity,
3278df92562eSFam Zheng                          bool has_buf_size, int64_t buf_size,
3279df92562eSFam Zheng                          bool has_on_source_error,
3280df92562eSFam Zheng                          BlockdevOnError on_source_error,
3281df92562eSFam Zheng                          bool has_on_target_error,
3282df92562eSFam Zheng                          BlockdevOnError on_target_error,
32836cdbceb1SKevin Wolf                          const char *filter_node_name,
3284481debaaSMax Reitz                          bool has_copy_mode, MirrorCopyMode copy_mode,
3285a6b58adeSJohn Snow                          bool has_auto_finalize, bool auto_finalize,
3286a6b58adeSJohn Snow                          bool has_auto_dismiss, bool auto_dismiss,
3287df92562eSFam Zheng                          Error **errp)
3288df92562eSFam Zheng {
3289df92562eSFam Zheng     BlockDriverState *bs;
3290df92562eSFam Zheng     BlockDriverState *target_bs;
3291df92562eSFam Zheng     AioContext *aio_context;
32923ea67e08SSergio Lopez     AioContext *old_context;
3293274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
3294cdf3bc93SMax Reitz     bool zero_target;
32958ed7d42fSKevin Wolf     int ret;
3296df92562eSFam Zheng 
329707eec652SKevin Wolf     bs = qmp_get_root_bs(device, errp);
3298df92562eSFam Zheng     if (!bs) {
3299df92562eSFam Zheng         return;
3300df92562eSFam Zheng     }
3301df92562eSFam Zheng 
3302df92562eSFam Zheng     target_bs = bdrv_lookup_bs(target, target, errp);
3303df92562eSFam Zheng     if (!target_bs) {
3304df92562eSFam Zheng         return;
3305df92562eSFam Zheng     }
3306df92562eSFam Zheng 
3307cdf3bc93SMax Reitz     zero_target = (sync == MIRROR_SYNC_MODE_FULL);
3308cdf3bc93SMax Reitz 
3309142e6907SEmanuele Giuseppe Esposito     /* Honor bdrv_try_change_aio_context() context acquisition requirements. */
33103ea67e08SSergio Lopez     old_context = bdrv_get_aio_context(target_bs);
3311df92562eSFam Zheng     aio_context = bdrv_get_aio_context(bs);
33123ea67e08SSergio Lopez     aio_context_acquire(old_context);
3313df92562eSFam Zheng 
3314142e6907SEmanuele Giuseppe Esposito     ret = bdrv_try_change_aio_context(target_bs, aio_context, NULL, errp);
33153ea67e08SSergio Lopez 
33163ea67e08SSergio Lopez     aio_context_release(old_context);
33173ea67e08SSergio Lopez     aio_context_acquire(aio_context);
33183ea67e08SSergio Lopez 
33198ed7d42fSKevin Wolf     if (ret < 0) {
33208ed7d42fSKevin Wolf         goto out;
33218ed7d42fSKevin Wolf     }
3322df92562eSFam Zheng 
332354fde4ffSMarkus Armbruster     blockdev_mirror_common(job_id, bs, target_bs,
332454fde4ffSMarkus Armbruster                            replaces, sync, backing_mode,
3325cdf3bc93SMax Reitz                            zero_target, has_speed, speed,
3326df92562eSFam Zheng                            has_granularity, granularity,
3327df92562eSFam Zheng                            has_buf_size, buf_size,
3328df92562eSFam Zheng                            has_on_source_error, on_source_error,
3329df92562eSFam Zheng                            has_on_target_error, on_target_error,
333054fde4ffSMarkus Armbruster                            true, true, filter_node_name,
3331481debaaSMax Reitz                            has_copy_mode, copy_mode,
3332a6b58adeSJohn Snow                            has_auto_finalize, auto_finalize,
3333a6b58adeSJohn Snow                            has_auto_dismiss, auto_dismiss,
3334992861fbSMarkus Armbruster                            errp);
33358ed7d42fSKevin Wolf out:
3336df92562eSFam Zheng     aio_context_release(aio_context);
3337df92562eSFam Zheng }
3338df92562eSFam Zheng 
333996241124SEmanuele Giuseppe Esposito /*
33406f592e5aSEmanuele Giuseppe Esposito  * Get a block job using its ID. Called with job_mutex held.
334196241124SEmanuele Giuseppe Esposito  */
33426f592e5aSEmanuele Giuseppe Esposito static BlockJob *find_block_job_locked(const char *id, Error **errp)
33432d47c6e9SStefan Hajnoczi {
33443ddf3efeSAlberto Garcia     BlockJob *job;
33453ddf3efeSAlberto Garcia 
33463ddf3efeSAlberto Garcia     assert(id != NULL);
33472d47c6e9SStefan Hajnoczi 
334896241124SEmanuele Giuseppe Esposito     job = block_job_get_locked(id);
33493ddf3efeSAlberto Garcia 
33503ddf3efeSAlberto Garcia     if (!job) {
33513ddf3efeSAlberto Garcia         error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
33523ddf3efeSAlberto Garcia                   "Block job '%s' not found", id);
33533ddf3efeSAlberto Garcia         return NULL;
33542d47c6e9SStefan Hajnoczi     }
33553d948cdfSStefan Hajnoczi 
33563ddf3efeSAlberto Garcia     return job;
33572d47c6e9SStefan Hajnoczi }
33582d47c6e9SStefan Hajnoczi 
3359882ec7ceSStefan Hajnoczi void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
33602d47c6e9SStefan Hajnoczi {
336196241124SEmanuele Giuseppe Esposito     BlockJob *job;
336296241124SEmanuele Giuseppe Esposito 
336396241124SEmanuele Giuseppe Esposito     JOB_LOCK_GUARD();
33646f592e5aSEmanuele Giuseppe Esposito     job = find_block_job_locked(device, errp);
33652d47c6e9SStefan Hajnoczi 
33662d47c6e9SStefan Hajnoczi     if (!job) {
33672d47c6e9SStefan Hajnoczi         return;
33682d47c6e9SStefan Hajnoczi     }
33692d47c6e9SStefan Hajnoczi 
337096241124SEmanuele Giuseppe Esposito     block_job_set_speed_locked(job, speed, errp);
33712d47c6e9SStefan Hajnoczi }
3372370521a1SStefan Hajnoczi 
33736e37fb81SPaolo Bonzini void qmp_block_job_cancel(const char *device,
33746e37fb81SPaolo Bonzini                           bool has_force, bool force, Error **errp)
33756e37fb81SPaolo Bonzini {
337696241124SEmanuele Giuseppe Esposito     BlockJob *job;
337796241124SEmanuele Giuseppe Esposito 
337896241124SEmanuele Giuseppe Esposito     JOB_LOCK_GUARD();
33796f592e5aSEmanuele Giuseppe Esposito     job = find_block_job_locked(device, errp);
33806e37fb81SPaolo Bonzini 
33816e37fb81SPaolo Bonzini     if (!job) {
33826e37fb81SPaolo Bonzini         return;
33836e37fb81SPaolo Bonzini     }
33843d948cdfSStefan Hajnoczi 
33853d948cdfSStefan Hajnoczi     if (!has_force) {
33863d948cdfSStefan Hajnoczi         force = false;
33873d948cdfSStefan Hajnoczi     }
33883d948cdfSStefan Hajnoczi 
338996241124SEmanuele Giuseppe Esposito     if (job_user_paused_locked(&job->job) && !force) {
3390f231b88dSCole Robinson         error_setg(errp, "The block job for device '%s' is currently paused",
3391f231b88dSCole Robinson                    device);
33926f592e5aSEmanuele Giuseppe Esposito         return;
33936e37fb81SPaolo Bonzini     }
33946e37fb81SPaolo Bonzini 
33956e37fb81SPaolo Bonzini     trace_qmp_block_job_cancel(job);
339696241124SEmanuele Giuseppe Esposito     job_user_cancel_locked(&job->job, force, errp);
33976e37fb81SPaolo Bonzini }
33986e37fb81SPaolo Bonzini 
33996e37fb81SPaolo Bonzini void qmp_block_job_pause(const char *device, Error **errp)
3400370521a1SStefan Hajnoczi {
340196241124SEmanuele Giuseppe Esposito     BlockJob *job;
340296241124SEmanuele Giuseppe Esposito 
340396241124SEmanuele Giuseppe Esposito     JOB_LOCK_GUARD();
34046f592e5aSEmanuele Giuseppe Esposito     job = find_block_job_locked(device, errp);
3405370521a1SStefan Hajnoczi 
34060ec4dfb8SJohn Snow     if (!job) {
3407370521a1SStefan Hajnoczi         return;
3408370521a1SStefan Hajnoczi     }
34096e37fb81SPaolo Bonzini 
34106e37fb81SPaolo Bonzini     trace_qmp_block_job_pause(job);
341196241124SEmanuele Giuseppe Esposito     job_user_pause_locked(&job->job, errp);
34126e37fb81SPaolo Bonzini }
34136e37fb81SPaolo Bonzini 
34146e37fb81SPaolo Bonzini void qmp_block_job_resume(const char *device, Error **errp)
34156e37fb81SPaolo Bonzini {
341696241124SEmanuele Giuseppe Esposito     BlockJob *job;
341796241124SEmanuele Giuseppe Esposito 
341896241124SEmanuele Giuseppe Esposito     JOB_LOCK_GUARD();
34196f592e5aSEmanuele Giuseppe Esposito     job = find_block_job_locked(device, errp);
34206e37fb81SPaolo Bonzini 
34210ec4dfb8SJohn Snow     if (!job) {
34228acc72a4SPaolo Bonzini         return;
34238acc72a4SPaolo Bonzini     }
3424370521a1SStefan Hajnoczi 
34256e37fb81SPaolo Bonzini     trace_qmp_block_job_resume(job);
342696241124SEmanuele Giuseppe Esposito     job_user_resume_locked(&job->job, errp);
3427370521a1SStefan Hajnoczi }
3428fb5458cdSStefan Hajnoczi 
3429aeae883bSPaolo Bonzini void qmp_block_job_complete(const char *device, Error **errp)
3430aeae883bSPaolo Bonzini {
343196241124SEmanuele Giuseppe Esposito     BlockJob *job;
343296241124SEmanuele Giuseppe Esposito 
343396241124SEmanuele Giuseppe Esposito     JOB_LOCK_GUARD();
34346f592e5aSEmanuele Giuseppe Esposito     job = find_block_job_locked(device, errp);
3435aeae883bSPaolo Bonzini 
3436aeae883bSPaolo Bonzini     if (!job) {
3437aeae883bSPaolo Bonzini         return;
3438aeae883bSPaolo Bonzini     }
3439aeae883bSPaolo Bonzini 
3440aeae883bSPaolo Bonzini     trace_qmp_block_job_complete(job);
344196241124SEmanuele Giuseppe Esposito     job_complete_locked(&job->job, errp);
3442aeae883bSPaolo Bonzini }
3443aeae883bSPaolo Bonzini 
344411b61fbcSJohn Snow void qmp_block_job_finalize(const char *id, Error **errp)
344511b61fbcSJohn Snow {
344696241124SEmanuele Giuseppe Esposito     BlockJob *job;
344796241124SEmanuele Giuseppe Esposito 
344896241124SEmanuele Giuseppe Esposito     JOB_LOCK_GUARD();
34496f592e5aSEmanuele Giuseppe Esposito     job = find_block_job_locked(id, errp);
345011b61fbcSJohn Snow 
345111b61fbcSJohn Snow     if (!job) {
345211b61fbcSJohn Snow         return;
345311b61fbcSJohn Snow     }
345411b61fbcSJohn Snow 
345511b61fbcSJohn Snow     trace_qmp_block_job_finalize(job);
345696241124SEmanuele Giuseppe Esposito     job_ref_locked(&job->job);
345796241124SEmanuele Giuseppe Esposito     job_finalize_locked(&job->job, errp);
3458b660a84bSStefan Reiter 
345996241124SEmanuele Giuseppe Esposito     job_unref_locked(&job->job);
346011b61fbcSJohn Snow }
346111b61fbcSJohn Snow 
346275f71059SJohn Snow void qmp_block_job_dismiss(const char *id, Error **errp)
346375f71059SJohn Snow {
346496241124SEmanuele Giuseppe Esposito     BlockJob *bjob;
34655f9a6a08SKevin Wolf     Job *job;
346675f71059SJohn Snow 
346796241124SEmanuele Giuseppe Esposito     JOB_LOCK_GUARD();
34686f592e5aSEmanuele Giuseppe Esposito     bjob = find_block_job_locked(id, errp);
346996241124SEmanuele Giuseppe Esposito 
34705f9a6a08SKevin Wolf     if (!bjob) {
347175f71059SJohn Snow         return;
347275f71059SJohn Snow     }
347375f71059SJohn Snow 
34745f9a6a08SKevin Wolf     trace_qmp_block_job_dismiss(bjob);
34755f9a6a08SKevin Wolf     job = &bjob->job;
347696241124SEmanuele Giuseppe Esposito     job_dismiss_locked(&job, errp);
347775f71059SJohn Snow }
347875f71059SJohn Snow 
3479fa40e656SJeff Cody void qmp_change_backing_file(const char *device,
3480fa40e656SJeff Cody                              const char *image_node_name,
3481fa40e656SJeff Cody                              const char *backing_file,
3482fa40e656SJeff Cody                              Error **errp)
3483fa40e656SJeff Cody {
3484fa40e656SJeff Cody     BlockDriverState *bs = NULL;
3485729962f6SStefan Hajnoczi     AioContext *aio_context;
3486fa40e656SJeff Cody     BlockDriverState *image_bs = NULL;
3487fa40e656SJeff Cody     Error *local_err = NULL;
3488fa40e656SJeff Cody     bool ro;
3489fa40e656SJeff Cody     int ret;
3490fa40e656SJeff Cody 
34917b5dca3fSKevin Wolf     bs = qmp_get_root_bs(device, errp);
34927b5dca3fSKevin Wolf     if (!bs) {
3493fa40e656SJeff Cody         return;
3494fa40e656SJeff Cody     }
3495fa40e656SJeff Cody 
34967b5dca3fSKevin Wolf     aio_context = bdrv_get_aio_context(bs);
3497729962f6SStefan Hajnoczi     aio_context_acquire(aio_context);
3498729962f6SStefan Hajnoczi 
3499fa40e656SJeff Cody     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3500fa40e656SJeff Cody     if (local_err) {
3501fa40e656SJeff Cody         error_propagate(errp, local_err);
3502729962f6SStefan Hajnoczi         goto out;
3503fa40e656SJeff Cody     }
3504fa40e656SJeff Cody 
3505fa40e656SJeff Cody     if (!image_bs) {
3506fa40e656SJeff Cody         error_setg(errp, "image file not found");
3507729962f6SStefan Hajnoczi         goto out;
3508fa40e656SJeff Cody     }
3509fa40e656SJeff Cody 
3510fa40e656SJeff Cody     if (bdrv_find_base(image_bs) == image_bs) {
3511fa40e656SJeff Cody         error_setg(errp, "not allowing backing file change on an image "
3512fa40e656SJeff Cody                          "without a backing file");
3513729962f6SStefan Hajnoczi         goto out;
3514fa40e656SJeff Cody     }
3515fa40e656SJeff Cody 
3516fa40e656SJeff Cody     /* even though we are not necessarily operating on bs, we need it to
3517fa40e656SJeff Cody      * determine if block ops are currently prohibited on the chain */
3518fa40e656SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3519729962f6SStefan Hajnoczi         goto out;
3520fa40e656SJeff Cody     }
3521fa40e656SJeff Cody 
3522fa40e656SJeff Cody     /* final sanity check */
3523fa40e656SJeff Cody     if (!bdrv_chain_contains(bs, image_bs)) {
3524fa40e656SJeff Cody         error_setg(errp, "'%s' and image file are not in the same chain",
3525fa40e656SJeff Cody                    device);
3526729962f6SStefan Hajnoczi         goto out;
3527fa40e656SJeff Cody     }
3528fa40e656SJeff Cody 
3529fa40e656SJeff Cody     /* if not r/w, reopen to make r/w */
3530fa40e656SJeff Cody     ro = bdrv_is_read_only(image_bs);
3531fa40e656SJeff Cody 
3532fa40e656SJeff Cody     if (ro) {
3533051a60f6SAlberto Garcia         if (bdrv_reopen_set_read_only(image_bs, false, errp) != 0) {
3534729962f6SStefan Hajnoczi             goto out;
3535fa40e656SJeff Cody         }
3536fa40e656SJeff Cody     }
3537fa40e656SJeff Cody 
3538fa40e656SJeff Cody     ret = bdrv_change_backing_file(image_bs, backing_file,
3539e54ee1b3SEric Blake                                    image_bs->drv ? image_bs->drv->format_name : "",
3540e54ee1b3SEric Blake                                    false);
3541fa40e656SJeff Cody 
3542fa40e656SJeff Cody     if (ret < 0) {
3543fa40e656SJeff Cody         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3544fa40e656SJeff Cody                          backing_file);
3545fa40e656SJeff Cody         /* don't exit here, so we can try to restore open flags if
3546fa40e656SJeff Cody          * appropriate */
3547fa40e656SJeff Cody     }
3548fa40e656SJeff Cody 
3549fa40e656SJeff Cody     if (ro) {
3550992861fbSMarkus Armbruster         bdrv_reopen_set_read_only(image_bs, true, errp);
3551fa40e656SJeff Cody     }
3552729962f6SStefan Hajnoczi 
3553729962f6SStefan Hajnoczi out:
3554729962f6SStefan Hajnoczi     aio_context_release(aio_context);
3555fa40e656SJeff Cody }
3556fa40e656SJeff Cody 
3557d26c9a15SKevin Wolf void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3558d26c9a15SKevin Wolf {
3559be4b67bcSMax Reitz     BlockDriverState *bs;
3560d26c9a15SKevin Wolf     QObject *obj;
35617d5e199aSDaniel P. Berrange     Visitor *v = qobject_output_visitor_new(&obj);
3562d26c9a15SKevin Wolf     QDict *qdict;
3563d26c9a15SKevin Wolf 
35641f584248SMarkus Armbruster     visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
35653b098d56SEric Blake     visit_complete(v, &obj);
35667dc847ebSMax Reitz     qdict = qobject_to(QDict, obj);
3567d26c9a15SKevin Wolf 
3568d26c9a15SKevin Wolf     qdict_flatten(qdict);
3569d26c9a15SKevin Wolf 
3570be4b67bcSMax Reitz     if (!qdict_get_try_str(qdict, "node-name")) {
35719ec8873eSKevin Wolf         error_setg(errp, "'node-name' must be specified for the root node");
3572be4b67bcSMax Reitz         goto fail;
3573be4b67bcSMax Reitz     }
3574be4b67bcSMax Reitz 
3575bd745e23SMax Reitz     bs = bds_tree_init(qdict, errp);
3576bd745e23SMax Reitz     if (!bs) {
3577be4b67bcSMax Reitz         goto fail;
3578be4b67bcSMax Reitz     }
35799c4218e9SMax Reitz 
358089802d5aSMaxim Levitsky     bdrv_set_monitor_owned(bs);
3581be4b67bcSMax Reitz 
3582d26c9a15SKevin Wolf fail:
35833b098d56SEric Blake     visit_free(v);
3584d26c9a15SKevin Wolf }
3585d26c9a15SKevin Wolf 
3586e60edf69SAlberto Garcia void qmp_blockdev_reopen(BlockdevOptionsList *reopen_list, Error **errp)
35871479c730SAlberto Garcia {
35883908b7a8SAlberto Garcia     BlockReopenQueue *queue = NULL;
35893908b7a8SAlberto Garcia 
35903908b7a8SAlberto Garcia     /* Add each one of the BDS that we want to reopen to the queue */
35913908b7a8SAlberto Garcia     for (; reopen_list != NULL; reopen_list = reopen_list->next) {
35923908b7a8SAlberto Garcia         BlockdevOptions *options = reopen_list->value;
35931479c730SAlberto Garcia         BlockDriverState *bs;
35941479c730SAlberto Garcia         AioContext *ctx;
35951479c730SAlberto Garcia         QObject *obj;
35963908b7a8SAlberto Garcia         Visitor *v;
35971479c730SAlberto Garcia         QDict *qdict;
35981479c730SAlberto Garcia 
35991479c730SAlberto Garcia         /* Check for the selected node name */
360054fde4ffSMarkus Armbruster         if (!options->node_name) {
3601ef2e38a1SConnor Kuehl             error_setg(errp, "node-name not specified");
36021479c730SAlberto Garcia             goto fail;
36031479c730SAlberto Garcia         }
36041479c730SAlberto Garcia 
36051479c730SAlberto Garcia         bs = bdrv_find_node(options->node_name);
36061479c730SAlberto Garcia         if (!bs) {
3607ef2e38a1SConnor Kuehl             error_setg(errp, "Failed to find node with node-name='%s'",
3608ef2e38a1SConnor Kuehl                        options->node_name);
36091479c730SAlberto Garcia             goto fail;
36101479c730SAlberto Garcia         }
36111479c730SAlberto Garcia 
36121479c730SAlberto Garcia         /* Put all options in a QDict and flatten it */
36133908b7a8SAlberto Garcia         v = qobject_output_visitor_new(&obj);
36141f584248SMarkus Armbruster         visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
36151479c730SAlberto Garcia         visit_complete(v, &obj);
36163908b7a8SAlberto Garcia         visit_free(v);
36173908b7a8SAlberto Garcia 
36181479c730SAlberto Garcia         qdict = qobject_to(QDict, obj);
36191479c730SAlberto Garcia 
36201479c730SAlberto Garcia         qdict_flatten(qdict);
36211479c730SAlberto Garcia 
36221479c730SAlberto Garcia         ctx = bdrv_get_aio_context(bs);
36231479c730SAlberto Garcia         aio_context_acquire(ctx);
36243908b7a8SAlberto Garcia 
36253908b7a8SAlberto Garcia         queue = bdrv_reopen_queue(queue, bs, qdict, false);
36266cf42ca2SKevin Wolf 
36273908b7a8SAlberto Garcia         aio_context_release(ctx);
36283908b7a8SAlberto Garcia     }
36293908b7a8SAlberto Garcia 
36303908b7a8SAlberto Garcia     /* Perform the reopen operation */
36311479c730SAlberto Garcia     bdrv_reopen_multiple(queue, errp);
36323908b7a8SAlberto Garcia     queue = NULL;
36331479c730SAlberto Garcia 
36341479c730SAlberto Garcia fail:
36353908b7a8SAlberto Garcia     bdrv_reopen_queue_free(queue);
36361479c730SAlberto Garcia }
36371479c730SAlberto Garcia 
363879b7a77eSMarkus Armbruster void qmp_blockdev_del(const char *node_name, Error **errp)
363981b936aeSAlberto Garcia {
364081b936aeSAlberto Garcia     AioContext *aio_context;
364181b936aeSAlberto Garcia     BlockDriverState *bs;
364281b936aeSAlberto Garcia 
3643b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
3644b4ad82aaSEmanuele Giuseppe Esposito 
364581b936aeSAlberto Garcia     bs = bdrv_find_node(node_name);
364681b936aeSAlberto Garcia     if (!bs) {
3647ef2e38a1SConnor Kuehl         error_setg(errp, "Failed to find node with node-name='%s'", node_name);
364881b936aeSAlberto Garcia         return;
364981b936aeSAlberto Garcia     }
36501f0c461bSKevin Wolf     if (bdrv_has_blk(bs)) {
3651e467da7bSKevin Wolf         error_setg(errp, "Node %s is in use", node_name);
365281b936aeSAlberto Garcia         return;
365381b936aeSAlberto Garcia     }
365481b936aeSAlberto Garcia     aio_context = bdrv_get_aio_context(bs);
365581b936aeSAlberto Garcia     aio_context_acquire(aio_context);
365681b936aeSAlberto Garcia 
365781b936aeSAlberto Garcia     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
365881b936aeSAlberto Garcia         goto out;
365981b936aeSAlberto Garcia     }
366081b936aeSAlberto Garcia 
366170537ed5SPaolo Bonzini     if (!QTAILQ_IN_USE(bs, monitor_list)) {
36629c4218e9SMax Reitz         error_setg(errp, "Node %s is not owned by the monitor",
36639c4218e9SMax Reitz                    bs->node_name);
36649c4218e9SMax Reitz         goto out;
36659c4218e9SMax Reitz     }
36669c4218e9SMax Reitz 
36679c4218e9SMax Reitz     if (bs->refcnt > 1) {
366881b936aeSAlberto Garcia         error_setg(errp, "Block device %s is in use",
366981b936aeSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
367081b936aeSAlberto Garcia         goto out;
367181b936aeSAlberto Garcia     }
367281b936aeSAlberto Garcia 
36739c4218e9SMax Reitz     QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
367481b936aeSAlberto Garcia     bdrv_unref(bs);
367581b936aeSAlberto Garcia 
367681b936aeSAlberto Garcia out:
367781b936aeSAlberto Garcia     aio_context_release(aio_context);
367881b936aeSAlberto Garcia }
367981b936aeSAlberto Garcia 
36807f821597SWen Congyang static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
36817f821597SWen Congyang                                   const char *child_name)
36827f821597SWen Congyang {
36837f821597SWen Congyang     BdrvChild *child;
36847f821597SWen Congyang 
36857f821597SWen Congyang     QLIST_FOREACH(child, &parent_bs->children, next) {
36867f821597SWen Congyang         if (strcmp(child->name, child_name) == 0) {
36877f821597SWen Congyang             return child;
36887f821597SWen Congyang         }
36897f821597SWen Congyang     }
36907f821597SWen Congyang 
36917f821597SWen Congyang     return NULL;
36927f821597SWen Congyang }
36937f821597SWen Congyang 
369454fde4ffSMarkus Armbruster void qmp_x_blockdev_change(const char *parent, const char *child,
36957f821597SWen Congyang                            const char *node, Error **errp)
36967f821597SWen Congyang {
36977f821597SWen Congyang     BlockDriverState *parent_bs, *new_bs = NULL;
36987f821597SWen Congyang     BdrvChild *p_child;
36997f821597SWen Congyang 
37007f821597SWen Congyang     parent_bs = bdrv_lookup_bs(parent, parent, errp);
37017f821597SWen Congyang     if (!parent_bs) {
37027f821597SWen Congyang         return;
37037f821597SWen Congyang     }
37047f821597SWen Congyang 
370554fde4ffSMarkus Armbruster     if (!child == !node) {
370654fde4ffSMarkus Armbruster         if (child) {
37077f821597SWen Congyang             error_setg(errp, "The parameters child and node are in conflict");
37087f821597SWen Congyang         } else {
37097f821597SWen Congyang             error_setg(errp, "Either child or node must be specified");
37107f821597SWen Congyang         }
37117f821597SWen Congyang         return;
37127f821597SWen Congyang     }
37137f821597SWen Congyang 
371454fde4ffSMarkus Armbruster     if (child) {
37157f821597SWen Congyang         p_child = bdrv_find_child(parent_bs, child);
37167f821597SWen Congyang         if (!p_child) {
37177f821597SWen Congyang             error_setg(errp, "Node '%s' does not have child '%s'",
37187f821597SWen Congyang                        parent, child);
37197f821597SWen Congyang             return;
37207f821597SWen Congyang         }
37217f821597SWen Congyang         bdrv_del_child(parent_bs, p_child, errp);
37227f821597SWen Congyang     }
37237f821597SWen Congyang 
372454fde4ffSMarkus Armbruster     if (node) {
37257f821597SWen Congyang         new_bs = bdrv_find_node(node);
37267f821597SWen Congyang         if (!new_bs) {
37277f821597SWen Congyang             error_setg(errp, "Node '%s' not found", node);
37287f821597SWen Congyang             return;
37297f821597SWen Congyang         }
37307f821597SWen Congyang         bdrv_add_child(parent_bs, new_bs, errp);
37317f821597SWen Congyang     }
37327f821597SWen Congyang }
37337f821597SWen Congyang 
3734fb5458cdSStefan Hajnoczi BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3735fb5458cdSStefan Hajnoczi {
3736c3033fd3SEric Blake     BlockJobInfoList *head = NULL, **tail = &head;
3737f0f55dedSAlberto Garcia     BlockJob *job;
3738fea68bb6SMarkus Armbruster 
3739880eeec6SEmanuele Giuseppe Esposito     JOB_LOCK_GUARD();
3740880eeec6SEmanuele Giuseppe Esposito 
3741880eeec6SEmanuele Giuseppe Esposito     for (job = block_job_next_locked(NULL); job;
3742880eeec6SEmanuele Giuseppe Esposito          job = block_job_next_locked(job)) {
3743c3033fd3SEric Blake         BlockJobInfo *value;
374469691e72SStefan Hajnoczi 
3745559b935fSJohn Snow         if (block_job_is_internal(job)) {
3746559b935fSJohn Snow             continue;
3747559b935fSJohn Snow         }
3748880eeec6SEmanuele Giuseppe Esposito         value = block_job_query_locked(job, errp);
3749c3033fd3SEric Blake         if (!value) {
3750559b935fSJohn Snow             qapi_free_BlockJobInfoList(head);
3751559b935fSJohn Snow             return NULL;
3752559b935fSJohn Snow         }
3753c3033fd3SEric Blake         QAPI_LIST_APPEND(tail, value);
3754fea68bb6SMarkus Armbruster     }
375569691e72SStefan Hajnoczi 
3756fea68bb6SMarkus Armbruster     return head;
3757fb5458cdSStefan Hajnoczi }
37584d454574SPaolo Bonzini 
3759ca00bbb1SStefan Hajnoczi void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
3760882e9b89SStefan Hajnoczi                                  bool has_force, bool force, Error **errp)
3761ca00bbb1SStefan Hajnoczi {
3762ca00bbb1SStefan Hajnoczi     AioContext *old_context;
3763ca00bbb1SStefan Hajnoczi     AioContext *new_context;
3764ca00bbb1SStefan Hajnoczi     BlockDriverState *bs;
3765ca00bbb1SStefan Hajnoczi 
3766ca00bbb1SStefan Hajnoczi     bs = bdrv_find_node(node_name);
3767ca00bbb1SStefan Hajnoczi     if (!bs) {
3768ef2e38a1SConnor Kuehl         error_setg(errp, "Failed to find node with node-name='%s'", node_name);
3769ca00bbb1SStefan Hajnoczi         return;
3770ca00bbb1SStefan Hajnoczi     }
3771ca00bbb1SStefan Hajnoczi 
3772882e9b89SStefan Hajnoczi     /* Protects against accidents. */
3773882e9b89SStefan Hajnoczi     if (!(has_force && force) && bdrv_has_blk(bs)) {
3774882e9b89SStefan Hajnoczi         error_setg(errp, "Node %s is associated with a BlockBackend and could "
3775882e9b89SStefan Hajnoczi                          "be in use (use force=true to override this check)",
3776882e9b89SStefan Hajnoczi                          node_name);
3777ca00bbb1SStefan Hajnoczi         return;
3778ca00bbb1SStefan Hajnoczi     }
3779ca00bbb1SStefan Hajnoczi 
3780ca00bbb1SStefan Hajnoczi     if (iothread->type == QTYPE_QSTRING) {
3781ca00bbb1SStefan Hajnoczi         IOThread *obj = iothread_by_id(iothread->u.s);
3782ca00bbb1SStefan Hajnoczi         if (!obj) {
3783ca00bbb1SStefan Hajnoczi             error_setg(errp, "Cannot find iothread %s", iothread->u.s);
3784ca00bbb1SStefan Hajnoczi             return;
3785ca00bbb1SStefan Hajnoczi         }
3786ca00bbb1SStefan Hajnoczi 
3787ca00bbb1SStefan Hajnoczi         new_context = iothread_get_aio_context(obj);
3788ca00bbb1SStefan Hajnoczi     } else {
3789ca00bbb1SStefan Hajnoczi         new_context = qemu_get_aio_context();
3790ca00bbb1SStefan Hajnoczi     }
3791ca00bbb1SStefan Hajnoczi 
3792ca00bbb1SStefan Hajnoczi     old_context = bdrv_get_aio_context(bs);
3793ca00bbb1SStefan Hajnoczi     aio_context_acquire(old_context);
3794ca00bbb1SStefan Hajnoczi 
3795142e6907SEmanuele Giuseppe Esposito     bdrv_try_change_aio_context(bs, new_context, NULL, errp);
3796ca00bbb1SStefan Hajnoczi 
3797ca00bbb1SStefan Hajnoczi     aio_context_release(old_context);
3798ca00bbb1SStefan Hajnoczi }
3799ca00bbb1SStefan Hajnoczi 
38000006383eSKevin Wolf QemuOptsList qemu_common_drive_opts = {
38014d454574SPaolo Bonzini     .name = "drive",
38020006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
38034d454574SPaolo Bonzini     .desc = {
38044d454574SPaolo Bonzini         {
38054d454574SPaolo Bonzini             .name = "snapshot",
38064d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
38074d454574SPaolo Bonzini             .help = "enable/disable snapshot mode",
38084d454574SPaolo Bonzini         },{
38094d454574SPaolo Bonzini             .name = "aio",
38104d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
3811f80f2673SAarushi Mehta             .help = "host AIO implementation (threads, native, io_uring)",
38124d454574SPaolo Bonzini         },{
3813e4b24b49SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
3814e4b24b49SKevin Wolf             .type = QEMU_OPT_BOOL,
3815e4b24b49SKevin Wolf             .help = "Enable writeback mode",
3816e4b24b49SKevin Wolf         },{
38174d454574SPaolo Bonzini             .name = "format",
38184d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
38194d454574SPaolo Bonzini             .help = "disk format (raw, qcow2, ...)",
38204d454574SPaolo Bonzini         },{
38214d454574SPaolo Bonzini             .name = "rerror",
38224d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
38234d454574SPaolo Bonzini             .help = "read error action",
38244d454574SPaolo Bonzini         },{
38254d454574SPaolo Bonzini             .name = "werror",
38264d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
38274d454574SPaolo Bonzini             .help = "write error action",
38284d454574SPaolo Bonzini         },{
38294e200cf8SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
38304d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
38314d454574SPaolo Bonzini             .help = "open drive file as read-only",
3832a2a7862cSPradeep Jagadeesh         },
3833a2a7862cSPradeep Jagadeesh 
3834a2a7862cSPradeep Jagadeesh         THROTTLE_OPTS,
3835a2a7862cSPradeep Jagadeesh 
3836a2a7862cSPradeep Jagadeesh         {
383776f4afb4SAlberto Garcia             .name = "throttling.group",
383876f4afb4SAlberto Garcia             .type = QEMU_OPT_STRING,
383976f4afb4SAlberto Garcia             .help = "name of the block throttling group",
384076f4afb4SAlberto Garcia         },{
38414d454574SPaolo Bonzini             .name = "copy-on-read",
38424d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
38434d454574SPaolo Bonzini             .help = "copy read data from backing file into image file",
3844465bee1dSPeter Lieven         },{
3845465bee1dSPeter Lieven             .name = "detect-zeroes",
3846465bee1dSPeter Lieven             .type = QEMU_OPT_STRING,
3847465bee1dSPeter Lieven             .help = "try to optimize zero writes (off, on, unmap)",
3848362e9299SAlberto Garcia         },{
3849362e9299SAlberto Garcia             .name = "stats-account-invalid",
3850362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
3851362e9299SAlberto Garcia             .help = "whether to account for invalid I/O operations "
3852362e9299SAlberto Garcia                     "in the statistics",
3853362e9299SAlberto Garcia         },{
3854362e9299SAlberto Garcia             .name = "stats-account-failed",
3855362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
3856362e9299SAlberto Garcia             .help = "whether to account for failed I/O operations "
3857362e9299SAlberto Garcia                     "in the statistics",
38584d454574SPaolo Bonzini         },
38594d454574SPaolo Bonzini         { /* end of list */ }
38604d454574SPaolo Bonzini     },
38614d454574SPaolo Bonzini };
38620006383eSKevin Wolf 
38630006383eSKevin Wolf QemuOptsList qemu_drive_opts = {
38640006383eSKevin Wolf     .name = "drive",
38650006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
38660006383eSKevin Wolf     .desc = {
3867492fdc6fSKevin Wolf         /*
3868492fdc6fSKevin Wolf          * no elements => accept any params
3869492fdc6fSKevin Wolf          * validation will happen later
3870492fdc6fSKevin Wolf          */
38710006383eSKevin Wolf         { /* end of list */ }
38720006383eSKevin Wolf     },
38730006383eSKevin Wolf };
3874