xref: /openbmc/qemu/blockdev.c (revision 2be5506fc85d5fef1abdb2128d446cb0b14b12bc)
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 
3326f54e9aSMarkus Armbruster #include "sysemu/block-backend.h"
349c17d615SPaolo Bonzini #include "sysemu/blockdev.h"
350d09e41aSPaolo Bonzini #include "hw/block/block.h"
36737e150eSPaolo Bonzini #include "block/blockjob.h"
3776f4afb4SAlberto Garcia #include "block/throttle-groups.h"
3883c9089eSPaolo Bonzini #include "monitor/monitor.h"
39d49b6836SMarkus Armbruster #include "qemu/error-report.h"
401de7afc9SPaolo Bonzini #include "qemu/option.h"
411de7afc9SPaolo Bonzini #include "qemu/config-file.h"
427b1b5d19SPaolo Bonzini #include "qapi/qmp/types.h"
43d26c9a15SKevin Wolf #include "qapi-visit.h"
44cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
45d26c9a15SKevin Wolf #include "qapi/qmp-output-visitor.h"
469e7dac7cSPeter Lieven #include "qapi/util.h"
479c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
48737e150eSPaolo Bonzini #include "block/block_int.h"
49a4dea8a9SLuiz Capitulino #include "qmp-commands.h"
5012bd451fSStefan Hajnoczi #include "trace.h"
519c17d615SPaolo Bonzini #include "sysemu/arch_init.h"
52666daa68SMarkus Armbruster 
531960966dSMarkus Armbruster static const char *const if_name[IF_COUNT] = {
541960966dSMarkus Armbruster     [IF_NONE] = "none",
551960966dSMarkus Armbruster     [IF_IDE] = "ide",
561960966dSMarkus Armbruster     [IF_SCSI] = "scsi",
571960966dSMarkus Armbruster     [IF_FLOPPY] = "floppy",
581960966dSMarkus Armbruster     [IF_PFLASH] = "pflash",
591960966dSMarkus Armbruster     [IF_MTD] = "mtd",
601960966dSMarkus Armbruster     [IF_SD] = "sd",
611960966dSMarkus Armbruster     [IF_VIRTIO] = "virtio",
621960966dSMarkus Armbruster     [IF_XEN] = "xen",
631960966dSMarkus Armbruster };
641960966dSMarkus Armbruster 
6521dff8cfSJohn Snow static int if_max_devs[IF_COUNT] = {
6627d6bf40SMarkus Armbruster     /*
6727d6bf40SMarkus Armbruster      * Do not change these numbers!  They govern how drive option
6827d6bf40SMarkus Armbruster      * index maps to unit and bus.  That mapping is ABI.
6927d6bf40SMarkus Armbruster      *
7027d6bf40SMarkus Armbruster      * All controllers used to imlement if=T drives need to support
7127d6bf40SMarkus Armbruster      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
7227d6bf40SMarkus Armbruster      * Otherwise, some index values map to "impossible" bus, unit
7327d6bf40SMarkus Armbruster      * values.
7427d6bf40SMarkus Armbruster      *
7527d6bf40SMarkus Armbruster      * For instance, if you change [IF_SCSI] to 255, -drive
7627d6bf40SMarkus Armbruster      * if=scsi,index=12 no longer means bus=1,unit=5, but
7727d6bf40SMarkus Armbruster      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
7827d6bf40SMarkus Armbruster      * the drive can't be set up.  Regression.
7927d6bf40SMarkus Armbruster      */
8027d6bf40SMarkus Armbruster     [IF_IDE] = 2,
8127d6bf40SMarkus Armbruster     [IF_SCSI] = 7,
821960966dSMarkus Armbruster };
831960966dSMarkus Armbruster 
8421dff8cfSJohn Snow /**
8521dff8cfSJohn Snow  * Boards may call this to offer board-by-board overrides
8621dff8cfSJohn Snow  * of the default, global values.
8721dff8cfSJohn Snow  */
8821dff8cfSJohn Snow void override_max_devs(BlockInterfaceType type, int max_devs)
8921dff8cfSJohn Snow {
9018e46a03SMarkus Armbruster     BlockBackend *blk;
9121dff8cfSJohn Snow     DriveInfo *dinfo;
9221dff8cfSJohn Snow 
9321dff8cfSJohn Snow     if (max_devs <= 0) {
9421dff8cfSJohn Snow         return;
9521dff8cfSJohn Snow     }
9621dff8cfSJohn Snow 
9718e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
9818e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
9921dff8cfSJohn Snow         if (dinfo->type == type) {
10021dff8cfSJohn Snow             fprintf(stderr, "Cannot override units-per-bus property of"
10121dff8cfSJohn Snow                     " the %s interface, because a drive of that type has"
10221dff8cfSJohn Snow                     " already been added.\n", if_name[type]);
10321dff8cfSJohn Snow             g_assert_not_reached();
10421dff8cfSJohn Snow         }
10521dff8cfSJohn Snow     }
10621dff8cfSJohn Snow 
10721dff8cfSJohn Snow     if_max_devs[type] = max_devs;
10821dff8cfSJohn Snow }
10921dff8cfSJohn Snow 
11014bafc54SMarkus Armbruster /*
11114bafc54SMarkus Armbruster  * We automatically delete the drive when a device using it gets
11214bafc54SMarkus Armbruster  * unplugged.  Questionable feature, but we can't just drop it.
11314bafc54SMarkus Armbruster  * Device models call blockdev_mark_auto_del() to schedule the
11414bafc54SMarkus Armbruster  * automatic deletion, and generic qdev code calls blockdev_auto_del()
11514bafc54SMarkus Armbruster  * when deletion is actually safe.
11614bafc54SMarkus Armbruster  */
1174be74634SMarkus Armbruster void blockdev_mark_auto_del(BlockBackend *blk)
11814bafc54SMarkus Armbruster {
11918e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
1204be74634SMarkus Armbruster     BlockDriverState *bs = blk_bs(blk);
12191fddb0dSStefan Hajnoczi     AioContext *aio_context;
12214bafc54SMarkus Armbruster 
12326f8b3a8SMarkus Armbruster     if (!dinfo) {
1242d246f01SKevin Wolf         return;
1252d246f01SKevin Wolf     }
1262d246f01SKevin Wolf 
1275433c24fSMax Reitz     if (bs) {
12891fddb0dSStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
12991fddb0dSStefan Hajnoczi         aio_context_acquire(aio_context);
13091fddb0dSStefan Hajnoczi 
13112bde0eeSPaolo Bonzini         if (bs->job) {
13212bde0eeSPaolo Bonzini             block_job_cancel(bs->job);
13312bde0eeSPaolo Bonzini         }
13491fddb0dSStefan Hajnoczi 
13591fddb0dSStefan Hajnoczi         aio_context_release(aio_context);
1365433c24fSMax Reitz     }
13791fddb0dSStefan Hajnoczi 
13814bafc54SMarkus Armbruster     dinfo->auto_del = 1;
13914bafc54SMarkus Armbruster }
14014bafc54SMarkus Armbruster 
1414be74634SMarkus Armbruster void blockdev_auto_del(BlockBackend *blk)
14214bafc54SMarkus Armbruster {
14318e46a03SMarkus Armbruster     DriveInfo *dinfo = blk_legacy_dinfo(blk);
14414bafc54SMarkus Armbruster 
1450fc0f1faSRyan Harper     if (dinfo && dinfo->auto_del) {
146b9fe8a7aSMarkus Armbruster         blk_unref(blk);
14714bafc54SMarkus Armbruster     }
14814bafc54SMarkus Armbruster }
14914bafc54SMarkus Armbruster 
150d8f94e1bSJohn Snow /**
151d8f94e1bSJohn Snow  * Returns the current mapping of how many units per bus
152d8f94e1bSJohn Snow  * a particular interface can support.
153d8f94e1bSJohn Snow  *
154d8f94e1bSJohn Snow  *  A positive integer indicates n units per bus.
155d8f94e1bSJohn Snow  *  0 implies the mapping has not been established.
156d8f94e1bSJohn Snow  * -1 indicates an invalid BlockInterfaceType was given.
157d8f94e1bSJohn Snow  */
158d8f94e1bSJohn Snow int drive_get_max_devs(BlockInterfaceType type)
159d8f94e1bSJohn Snow {
160d8f94e1bSJohn Snow     if (type >= IF_IDE && type < IF_COUNT) {
161d8f94e1bSJohn Snow         return if_max_devs[type];
162d8f94e1bSJohn Snow     }
163d8f94e1bSJohn Snow 
164d8f94e1bSJohn Snow     return -1;
165d8f94e1bSJohn Snow }
166d8f94e1bSJohn Snow 
167505a7fb1SMarkus Armbruster static int drive_index_to_bus_id(BlockInterfaceType type, int index)
168505a7fb1SMarkus Armbruster {
169505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
170505a7fb1SMarkus Armbruster     return max_devs ? index / max_devs : 0;
171505a7fb1SMarkus Armbruster }
172505a7fb1SMarkus Armbruster 
173505a7fb1SMarkus Armbruster static int drive_index_to_unit_id(BlockInterfaceType type, int index)
174505a7fb1SMarkus Armbruster {
175505a7fb1SMarkus Armbruster     int max_devs = if_max_devs[type];
176505a7fb1SMarkus Armbruster     return max_devs ? index % max_devs : index;
177505a7fb1SMarkus Armbruster }
178505a7fb1SMarkus Armbruster 
1792292ddaeSMarkus Armbruster QemuOpts *drive_def(const char *optstr)
1802292ddaeSMarkus Armbruster {
18170b94331SMarkus Armbruster     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
1822292ddaeSMarkus Armbruster }
1832292ddaeSMarkus Armbruster 
1842292ddaeSMarkus Armbruster QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
1855645b0f4SMarkus Armbruster                     const char *optstr)
186666daa68SMarkus Armbruster {
187666daa68SMarkus Armbruster     QemuOpts *opts;
188666daa68SMarkus Armbruster 
1892292ddaeSMarkus Armbruster     opts = drive_def(optstr);
190666daa68SMarkus Armbruster     if (!opts) {
191666daa68SMarkus Armbruster         return NULL;
192666daa68SMarkus Armbruster     }
1932292ddaeSMarkus Armbruster     if (type != IF_DEFAULT) {
194f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "if", if_name[type], &error_abort);
1952292ddaeSMarkus Armbruster     }
1962292ddaeSMarkus Armbruster     if (index >= 0) {
197a8b18f8fSMarkus Armbruster         qemu_opt_set_number(opts, "index", index, &error_abort);
1982292ddaeSMarkus Armbruster     }
199666daa68SMarkus Armbruster     if (file)
200f43e47dbSMarkus Armbruster         qemu_opt_set(opts, "file", file, &error_abort);
201666daa68SMarkus Armbruster     return opts;
202666daa68SMarkus Armbruster }
203666daa68SMarkus Armbruster 
204666daa68SMarkus Armbruster DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
205666daa68SMarkus Armbruster {
20618e46a03SMarkus Armbruster     BlockBackend *blk;
207666daa68SMarkus Armbruster     DriveInfo *dinfo;
208666daa68SMarkus Armbruster 
20918e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
21018e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
21118e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type
21218e46a03SMarkus Armbruster             && dinfo->bus == bus && dinfo->unit == unit) {
213666daa68SMarkus Armbruster             return dinfo;
214666daa68SMarkus Armbruster         }
21518e46a03SMarkus Armbruster     }
216666daa68SMarkus Armbruster 
217666daa68SMarkus Armbruster     return NULL;
218666daa68SMarkus Armbruster }
219666daa68SMarkus Armbruster 
220a66c9dc7SJohn Snow bool drive_check_orphaned(void)
221a66c9dc7SJohn Snow {
22218e46a03SMarkus Armbruster     BlockBackend *blk;
223a66c9dc7SJohn Snow     DriveInfo *dinfo;
224a66c9dc7SJohn Snow     bool rs = false;
225a66c9dc7SJohn Snow 
22618e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
22718e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
228a66c9dc7SJohn Snow         /* If dinfo->bdrv->dev is NULL, it has no device attached. */
229a66c9dc7SJohn Snow         /* Unless this is a default drive, this may be an oversight. */
230a7f53e26SMarkus Armbruster         if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
231a66c9dc7SJohn Snow             dinfo->type != IF_NONE) {
232a66c9dc7SJohn Snow             fprintf(stderr, "Warning: Orphaned drive without device: "
233a66c9dc7SJohn Snow                     "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
2345433c24fSMax Reitz                     blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
2355433c24fSMax Reitz                     if_name[dinfo->type], dinfo->bus, dinfo->unit);
236a66c9dc7SJohn Snow             rs = true;
237a66c9dc7SJohn Snow         }
238a66c9dc7SJohn Snow     }
239a66c9dc7SJohn Snow 
240a66c9dc7SJohn Snow     return rs;
241a66c9dc7SJohn Snow }
242a66c9dc7SJohn Snow 
243f1bd51acSMarkus Armbruster DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
244f1bd51acSMarkus Armbruster {
245f1bd51acSMarkus Armbruster     return drive_get(type,
246f1bd51acSMarkus Armbruster                      drive_index_to_bus_id(type, index),
247f1bd51acSMarkus Armbruster                      drive_index_to_unit_id(type, index));
248f1bd51acSMarkus Armbruster }
249f1bd51acSMarkus Armbruster 
250666daa68SMarkus Armbruster int drive_get_max_bus(BlockInterfaceType type)
251666daa68SMarkus Armbruster {
252666daa68SMarkus Armbruster     int max_bus;
25318e46a03SMarkus Armbruster     BlockBackend *blk;
254666daa68SMarkus Armbruster     DriveInfo *dinfo;
255666daa68SMarkus Armbruster 
256666daa68SMarkus Armbruster     max_bus = -1;
25718e46a03SMarkus Armbruster     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
25818e46a03SMarkus Armbruster         dinfo = blk_legacy_dinfo(blk);
25918e46a03SMarkus Armbruster         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
260666daa68SMarkus Armbruster             max_bus = dinfo->bus;
261666daa68SMarkus Armbruster         }
26218e46a03SMarkus Armbruster     }
263666daa68SMarkus Armbruster     return max_bus;
264666daa68SMarkus Armbruster }
265666daa68SMarkus Armbruster 
26613839974SMarkus Armbruster /* Get a block device.  This should only be used for single-drive devices
26713839974SMarkus Armbruster    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
26813839974SMarkus Armbruster    appropriate bus.  */
26913839974SMarkus Armbruster DriveInfo *drive_get_next(BlockInterfaceType type)
27013839974SMarkus Armbruster {
27113839974SMarkus Armbruster     static int next_block_unit[IF_COUNT];
27213839974SMarkus Armbruster 
27313839974SMarkus Armbruster     return drive_get(type, 0, next_block_unit[type]++);
27413839974SMarkus Armbruster }
27513839974SMarkus Armbruster 
276666daa68SMarkus Armbruster static void bdrv_format_print(void *opaque, const char *name)
277666daa68SMarkus Armbruster {
278807105a7SMarkus Armbruster     error_printf(" %s", name);
279666daa68SMarkus Armbruster }
280666daa68SMarkus Armbruster 
281aa398a5cSStefan Hajnoczi typedef struct {
282aa398a5cSStefan Hajnoczi     QEMUBH *bh;
283fa510ebfSFam Zheng     BlockDriverState *bs;
284fa510ebfSFam Zheng } BDRVPutRefBH;
285aa398a5cSStefan Hajnoczi 
286b681072dSKevin Wolf static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
287666daa68SMarkus Armbruster {
288666daa68SMarkus Armbruster     if (!strcmp(buf, "ignore")) {
28992aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_IGNORE;
290666daa68SMarkus Armbruster     } else if (!is_read && !strcmp(buf, "enospc")) {
29192aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_ENOSPC;
292666daa68SMarkus Armbruster     } else if (!strcmp(buf, "stop")) {
29392aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_STOP;
294666daa68SMarkus Armbruster     } else if (!strcmp(buf, "report")) {
29592aa5c6dSPaolo Bonzini         return BLOCKDEV_ON_ERROR_REPORT;
296666daa68SMarkus Armbruster     } else {
297b681072dSKevin Wolf         error_setg(errp, "'%s' invalid %s error action",
298666daa68SMarkus Armbruster                    buf, is_read ? "read" : "write");
299666daa68SMarkus Armbruster         return -1;
300666daa68SMarkus Armbruster     }
301666daa68SMarkus Armbruster }
302666daa68SMarkus Armbruster 
303cc0681c4SBenoît Canet static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
3040563e191SZhi Yong Wu {
305cc0681c4SBenoît Canet     if (throttle_conflicting(cfg)) {
306cc0681c4SBenoît Canet         error_setg(errp, "bps/iops/max total values and read/write values"
307c546194fSStefan Hajnoczi                          " cannot be used at the same time");
3080563e191SZhi Yong Wu         return false;
3090563e191SZhi Yong Wu     }
3100563e191SZhi Yong Wu 
311cc0681c4SBenoît Canet     if (!throttle_is_valid(cfg)) {
312cc0681c4SBenoît Canet         error_setg(errp, "bps/iops/maxs values must be 0 or greater");
3137d81c141SStefan Hajnoczi         return false;
3147d81c141SStefan Hajnoczi     }
3157d81c141SStefan Hajnoczi 
316ee2bdc33SStefan Hajnoczi     if (throttle_max_is_missing_limit(cfg)) {
317ee2bdc33SStefan Hajnoczi         error_setg(errp, "bps_max/iops_max require corresponding"
318ee2bdc33SStefan Hajnoczi                          " bps/iops values");
319ee2bdc33SStefan Hajnoczi         return false;
320ee2bdc33SStefan Hajnoczi     }
321ee2bdc33SStefan Hajnoczi 
3220563e191SZhi Yong Wu     return true;
3230563e191SZhi Yong Wu }
3240563e191SZhi Yong Wu 
32533cb7dc8SKevin Wolf typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
32633cb7dc8SKevin Wolf 
327fbf8175eSMax Reitz /* All parameters but @opts are optional and may be set to NULL. */
328fbf8175eSMax Reitz static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
329fbf8175eSMax Reitz     const char **throttling_group, ThrottleConfig *throttle_cfg,
330fbf8175eSMax Reitz     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
331fbf8175eSMax Reitz {
332fbf8175eSMax Reitz     const char *discard;
333fbf8175eSMax Reitz     Error *local_error = NULL;
334fbf8175eSMax Reitz     const char *aio;
335fbf8175eSMax Reitz 
336fbf8175eSMax Reitz     if (bdrv_flags) {
337fbf8175eSMax Reitz         if (!qemu_opt_get_bool(opts, "read-only", false)) {
338fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_RDWR;
339fbf8175eSMax Reitz         }
340fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
341fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_COPY_ON_READ;
342fbf8175eSMax Reitz         }
343fbf8175eSMax Reitz 
344fbf8175eSMax Reitz         if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
345fbf8175eSMax Reitz             if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
346fbf8175eSMax Reitz                 error_setg(errp, "Invalid discard option");
347fbf8175eSMax Reitz                 return;
348fbf8175eSMax Reitz             }
349fbf8175eSMax Reitz         }
350fbf8175eSMax Reitz 
351fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true)) {
352fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_CACHE_WB;
353fbf8175eSMax Reitz         }
354fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
355fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_NOCACHE;
356fbf8175eSMax Reitz         }
357fbf8175eSMax Reitz         if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
358fbf8175eSMax Reitz             *bdrv_flags |= BDRV_O_NO_FLUSH;
359fbf8175eSMax Reitz         }
360fbf8175eSMax Reitz 
361fbf8175eSMax Reitz         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
362fbf8175eSMax Reitz             if (!strcmp(aio, "native")) {
363fbf8175eSMax Reitz                 *bdrv_flags |= BDRV_O_NATIVE_AIO;
364fbf8175eSMax Reitz             } else if (!strcmp(aio, "threads")) {
365fbf8175eSMax Reitz                 /* this is the default */
366fbf8175eSMax Reitz             } else {
367fbf8175eSMax Reitz                error_setg(errp, "invalid aio option");
368fbf8175eSMax Reitz                return;
369fbf8175eSMax Reitz             }
370fbf8175eSMax Reitz         }
371fbf8175eSMax Reitz     }
372fbf8175eSMax Reitz 
373fbf8175eSMax Reitz     /* disk I/O throttling */
374fbf8175eSMax Reitz     if (throttling_group) {
375fbf8175eSMax Reitz         *throttling_group = qemu_opt_get(opts, "throttling.group");
376fbf8175eSMax Reitz     }
377fbf8175eSMax Reitz 
378fbf8175eSMax Reitz     if (throttle_cfg) {
379fbf8175eSMax Reitz         memset(throttle_cfg, 0, sizeof(*throttle_cfg));
380fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
381fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total", 0);
382fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
383fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read", 0);
384fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
385fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write", 0);
386fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
387fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total", 0);
388fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
389fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read", 0);
390fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
391fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write", 0);
392fbf8175eSMax Reitz 
393fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
394fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
395fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
396fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
397fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
398fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
399fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
400fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
401fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
402fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
403fbf8175eSMax Reitz         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
404fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
405fbf8175eSMax Reitz 
406fbf8175eSMax Reitz         throttle_cfg->op_size =
407fbf8175eSMax Reitz             qemu_opt_get_number(opts, "throttling.iops-size", 0);
408fbf8175eSMax Reitz 
409fbf8175eSMax Reitz         if (!check_throttle_config(throttle_cfg, errp)) {
410fbf8175eSMax Reitz             return;
411fbf8175eSMax Reitz         }
412fbf8175eSMax Reitz     }
413fbf8175eSMax Reitz 
414fbf8175eSMax Reitz     if (detect_zeroes) {
415fbf8175eSMax Reitz         *detect_zeroes =
416fbf8175eSMax Reitz             qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
417fbf8175eSMax Reitz                             qemu_opt_get(opts, "detect-zeroes"),
418fbf8175eSMax Reitz                             BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
419fbf8175eSMax Reitz                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
420fbf8175eSMax Reitz                             &local_error);
421fbf8175eSMax Reitz         if (local_error) {
422fbf8175eSMax Reitz             error_propagate(errp, local_error);
423fbf8175eSMax Reitz             return;
424fbf8175eSMax Reitz         }
425fbf8175eSMax Reitz 
426fbf8175eSMax Reitz         if (bdrv_flags &&
427fbf8175eSMax Reitz             *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
428fbf8175eSMax Reitz             !(*bdrv_flags & BDRV_O_UNMAP))
429fbf8175eSMax Reitz         {
430fbf8175eSMax Reitz             error_setg(errp, "setting detect-zeroes to unmap is not allowed "
431fbf8175eSMax Reitz                              "without setting discard operation to unmap");
432fbf8175eSMax Reitz             return;
433fbf8175eSMax Reitz         }
434fbf8175eSMax Reitz     }
435fbf8175eSMax Reitz }
436fbf8175eSMax Reitz 
437f298d071SKevin Wolf /* Takes the ownership of bs_opts */
43818e46a03SMarkus Armbruster static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
439b681072dSKevin Wolf                                    Error **errp)
440666daa68SMarkus Armbruster {
441666daa68SMarkus Armbruster     const char *buf;
442666daa68SMarkus Armbruster     int bdrv_flags = 0;
443666daa68SMarkus Armbruster     int on_read_error, on_write_error;
444362e9299SAlberto Garcia     bool account_invalid, account_failed;
445*2be5506fSAlberto Garcia     const char *stats_intervals;
44626f54e9aSMarkus Armbruster     BlockBackend *blk;
447a0f1eab1SMarkus Armbruster     BlockDriverState *bs;
448cc0681c4SBenoît Canet     ThrottleConfig cfg;
449666daa68SMarkus Armbruster     int snapshot = 0;
450c546194fSStefan Hajnoczi     Error *error = NULL;
4510006383eSKevin Wolf     QemuOpts *opts;
4520006383eSKevin Wolf     const char *id;
45374fe54f2SKevin Wolf     bool has_driver_specific_opts;
454fbf8175eSMax Reitz     BlockdevDetectZeroesOptions detect_zeroes =
455fbf8175eSMax Reitz         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
456fbf8175eSMax Reitz     const char *throttling_group = NULL;
457666daa68SMarkus Armbruster 
458f298d071SKevin Wolf     /* Check common options by copying from bs_opts to opts, all other options
459f298d071SKevin Wolf      * stay in bs_opts for processing by bdrv_open(). */
460f298d071SKevin Wolf     id = qdict_get_try_str(bs_opts, "id");
4610006383eSKevin Wolf     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
46284d18f06SMarkus Armbruster     if (error) {
463b681072dSKevin Wolf         error_propagate(errp, error);
4646376f952SMarkus Armbruster         goto err_no_opts;
4650006383eSKevin Wolf     }
4660006383eSKevin Wolf 
4670006383eSKevin Wolf     qemu_opts_absorb_qdict(opts, bs_opts, &error);
46884d18f06SMarkus Armbruster     if (error) {
469b681072dSKevin Wolf         error_propagate(errp, error);
470ec9c10d2SStefan Hajnoczi         goto early_err;
4710006383eSKevin Wolf     }
4720006383eSKevin Wolf 
4730006383eSKevin Wolf     if (id) {
4740006383eSKevin Wolf         qdict_del(bs_opts, "id");
4750006383eSKevin Wolf     }
4760006383eSKevin Wolf 
47774fe54f2SKevin Wolf     has_driver_specific_opts = !!qdict_size(bs_opts);
47874fe54f2SKevin Wolf 
479666daa68SMarkus Armbruster     /* extract parameters */
480666daa68SMarkus Armbruster     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
481666daa68SMarkus Armbruster 
482362e9299SAlberto Garcia     account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
483362e9299SAlberto Garcia     account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
484362e9299SAlberto Garcia 
485*2be5506fSAlberto Garcia     stats_intervals = qemu_opt_get(opts, "stats-intervals");
486*2be5506fSAlberto Garcia 
487fbf8175eSMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
488fbf8175eSMax Reitz                                     &detect_zeroes, &error);
489fbf8175eSMax Reitz     if (error) {
490fbf8175eSMax Reitz         error_propagate(errp, error);
491ec9c10d2SStefan Hajnoczi         goto early_err;
492a9384affSPaolo Bonzini     }
493666daa68SMarkus Armbruster 
494666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
495c8057f95SPeter Maydell         if (is_help_option(buf)) {
496807105a7SMarkus Armbruster             error_printf("Supported formats:");
497666daa68SMarkus Armbruster             bdrv_iterate_format(bdrv_format_print, NULL);
498807105a7SMarkus Armbruster             error_printf("\n");
499ec9c10d2SStefan Hajnoczi             goto early_err;
500666daa68SMarkus Armbruster         }
50174fe54f2SKevin Wolf 
502e4342ce5SMax Reitz         if (qdict_haskey(bs_opts, "driver")) {
503e4342ce5SMax Reitz             error_setg(errp, "Cannot specify both 'driver' and 'format'");
504ec9c10d2SStefan Hajnoczi             goto early_err;
5056db5f5d6SMike Qiu         }
506e4342ce5SMax Reitz         qdict_put(bs_opts, "driver", qstring_from_str(buf));
507666daa68SMarkus Armbruster     }
508666daa68SMarkus Armbruster 
50992aa5c6dSPaolo Bonzini     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
510666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
511b681072dSKevin Wolf         on_write_error = parse_block_error_action(buf, 0, &error);
51284d18f06SMarkus Armbruster         if (error) {
513b681072dSKevin Wolf             error_propagate(errp, error);
514ec9c10d2SStefan Hajnoczi             goto early_err;
515666daa68SMarkus Armbruster         }
516666daa68SMarkus Armbruster     }
517666daa68SMarkus Armbruster 
51892aa5c6dSPaolo Bonzini     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
519666daa68SMarkus Armbruster     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
520b681072dSKevin Wolf         on_read_error = parse_block_error_action(buf, 1, &error);
52184d18f06SMarkus Armbruster         if (error) {
522b681072dSKevin Wolf             error_propagate(errp, error);
523ec9c10d2SStefan Hajnoczi             goto early_err;
524666daa68SMarkus Armbruster         }
525666daa68SMarkus Armbruster     }
526666daa68SMarkus Armbruster 
527666daa68SMarkus Armbruster     if (snapshot) {
528666daa68SMarkus Armbruster         /* always use cache=unsafe with snapshot */
529666daa68SMarkus Armbruster         bdrv_flags &= ~BDRV_O_CACHE_MASK;
530666daa68SMarkus Armbruster         bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
531666daa68SMarkus Armbruster     }
532666daa68SMarkus Armbruster 
5335ec18f8cSMax Reitz     /* init */
5345ec18f8cSMax Reitz     if ((!file || !*file) && !has_driver_specific_opts) {
5355ec18f8cSMax Reitz         BlockBackendRootState *blk_rs;
5365ec18f8cSMax Reitz 
5375ec18f8cSMax Reitz         blk = blk_new(qemu_opts_id(opts), errp);
5385ec18f8cSMax Reitz         if (!blk) {
5395ec18f8cSMax Reitz             goto early_err;
5405ec18f8cSMax Reitz         }
5415ec18f8cSMax Reitz 
5425ec18f8cSMax Reitz         blk_rs = blk_get_root_state(blk);
5435ec18f8cSMax Reitz         blk_rs->open_flags    = bdrv_flags;
544fbf8175eSMax Reitz         blk_rs->read_only     = !(bdrv_flags & BDRV_O_RDWR);
5455ec18f8cSMax Reitz         blk_rs->detect_zeroes = detect_zeroes;
5465ec18f8cSMax Reitz 
5475ec18f8cSMax Reitz         if (throttle_enabled(&cfg)) {
5485ec18f8cSMax Reitz             if (!throttling_group) {
5495ec18f8cSMax Reitz                 throttling_group = blk_name(blk);
5505ec18f8cSMax Reitz             }
5515ec18f8cSMax Reitz             blk_rs->throttle_group = g_strdup(throttling_group);
5525ec18f8cSMax Reitz             blk_rs->throttle_state = throttle_group_incref(throttling_group);
5535ec18f8cSMax Reitz             blk_rs->throttle_state->cfg = cfg;
5545ec18f8cSMax Reitz         }
5555ec18f8cSMax Reitz 
5565ec18f8cSMax Reitz         QDECREF(bs_opts);
5575ec18f8cSMax Reitz     } else {
5585ec18f8cSMax Reitz         if (file && !*file) {
5595ec18f8cSMax Reitz             file = NULL;
5605ec18f8cSMax Reitz         }
5615ec18f8cSMax Reitz 
562e4342ce5SMax Reitz         blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
563e4342ce5SMax Reitz                            errp);
564e4342ce5SMax Reitz         if (!blk) {
565e4342ce5SMax Reitz             goto err_no_bs_opts;
566e4342ce5SMax Reitz         }
567e4342ce5SMax Reitz         bs = blk_bs(blk);
5680006383eSKevin Wolf 
569e4342ce5SMax Reitz         bs->detect_zeroes = detect_zeroes;
570e4342ce5SMax Reitz 
571e4342ce5SMax Reitz         /* disk I/O throttling */
572e4342ce5SMax Reitz         if (throttle_enabled(&cfg)) {
57376f4afb4SAlberto Garcia             if (!throttling_group) {
57476f4afb4SAlberto Garcia                 throttling_group = blk_name(blk);
57576f4afb4SAlberto Garcia             }
57676f4afb4SAlberto Garcia             bdrv_io_limits_enable(bs, throttling_group);
577e4342ce5SMax Reitz             bdrv_set_io_limits(bs, &cfg);
578666daa68SMarkus Armbruster         }
579666daa68SMarkus Armbruster 
580a0f1eab1SMarkus Armbruster         if (bdrv_key_required(bs)) {
581666daa68SMarkus Armbruster             autostart = 0;
582a0f1eab1SMarkus Armbruster         }
583362e9299SAlberto Garcia 
584362e9299SAlberto Garcia         block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
585*2be5506fSAlberto Garcia 
586*2be5506fSAlberto Garcia         if (stats_intervals) {
587*2be5506fSAlberto Garcia             char **intervals = g_strsplit(stats_intervals, ":", 0);
588*2be5506fSAlberto Garcia             unsigned i;
589*2be5506fSAlberto Garcia 
590*2be5506fSAlberto Garcia             if (*stats_intervals == '\0') {
591*2be5506fSAlberto Garcia                 error_setg(&error, "stats-intervals can't have an empty value");
592*2be5506fSAlberto Garcia             }
593*2be5506fSAlberto Garcia 
594*2be5506fSAlberto Garcia             for (i = 0; !error && intervals[i] != NULL; i++) {
595*2be5506fSAlberto Garcia                 unsigned long long val;
596*2be5506fSAlberto Garcia                 if (parse_uint_full(intervals[i], &val, 10) == 0 &&
597*2be5506fSAlberto Garcia                     val > 0 && val <= UINT_MAX) {
598*2be5506fSAlberto Garcia                     block_acct_add_interval(blk_get_stats(blk), val);
599*2be5506fSAlberto Garcia                 } else {
600*2be5506fSAlberto Garcia                     error_setg(&error, "Invalid interval length: '%s'",
601*2be5506fSAlberto Garcia                                intervals[i]);
602*2be5506fSAlberto Garcia                 }
603*2be5506fSAlberto Garcia             }
604*2be5506fSAlberto Garcia 
605*2be5506fSAlberto Garcia             g_strfreev(intervals);
606*2be5506fSAlberto Garcia 
607*2be5506fSAlberto Garcia             if (error) {
608*2be5506fSAlberto Garcia                 error_propagate(errp, error);
609*2be5506fSAlberto Garcia                 blk_unref(blk);
610*2be5506fSAlberto Garcia                 blk = NULL;
611*2be5506fSAlberto Garcia                 goto err_no_bs_opts;
612*2be5506fSAlberto Garcia             }
613*2be5506fSAlberto Garcia         }
6145ec18f8cSMax Reitz     }
6155ec18f8cSMax Reitz 
6165ec18f8cSMax Reitz     blk_set_on_error(blk, on_read_error, on_write_error);
6170006383eSKevin Wolf 
618e4342ce5SMax Reitz err_no_bs_opts:
6190006383eSKevin Wolf     qemu_opts_del(opts);
62018e46a03SMarkus Armbruster     return blk;
621a9ae2bffSMarkus Armbruster 
622ec9c10d2SStefan Hajnoczi early_err:
623ec9c10d2SStefan Hajnoczi     qemu_opts_del(opts);
6246376f952SMarkus Armbruster err_no_opts:
6256376f952SMarkus Armbruster     QDECREF(bs_opts);
626a9ae2bffSMarkus Armbruster     return NULL;
627666daa68SMarkus Armbruster }
628666daa68SMarkus Armbruster 
629bd745e23SMax Reitz static QemuOptsList qemu_root_bds_opts;
630bd745e23SMax Reitz 
631bd745e23SMax Reitz /* Takes the ownership of bs_opts */
632bd745e23SMax Reitz static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
633bd745e23SMax Reitz {
634bd745e23SMax Reitz     BlockDriverState *bs;
635bd745e23SMax Reitz     QemuOpts *opts;
636bd745e23SMax Reitz     Error *local_error = NULL;
637bd745e23SMax Reitz     BlockdevDetectZeroesOptions detect_zeroes;
638bd745e23SMax Reitz     int ret;
639bd745e23SMax Reitz     int bdrv_flags = 0;
640bd745e23SMax Reitz 
641bd745e23SMax Reitz     opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
642bd745e23SMax Reitz     if (!opts) {
643bd745e23SMax Reitz         goto fail;
644bd745e23SMax Reitz     }
645bd745e23SMax Reitz 
646bd745e23SMax Reitz     qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
647bd745e23SMax Reitz     if (local_error) {
648bd745e23SMax Reitz         error_propagate(errp, local_error);
649bd745e23SMax Reitz         goto fail;
650bd745e23SMax Reitz     }
651bd745e23SMax Reitz 
652bd745e23SMax Reitz     extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
653bd745e23SMax Reitz                                     &detect_zeroes, &local_error);
654bd745e23SMax Reitz     if (local_error) {
655bd745e23SMax Reitz         error_propagate(errp, local_error);
656bd745e23SMax Reitz         goto fail;
657bd745e23SMax Reitz     }
658bd745e23SMax Reitz 
659bd745e23SMax Reitz     bs = NULL;
660bd745e23SMax Reitz     ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
661bd745e23SMax Reitz     if (ret < 0) {
662bd745e23SMax Reitz         goto fail_no_bs_opts;
663bd745e23SMax Reitz     }
664bd745e23SMax Reitz 
665bd745e23SMax Reitz     bs->detect_zeroes = detect_zeroes;
666bd745e23SMax Reitz 
667bd745e23SMax Reitz fail_no_bs_opts:
668bd745e23SMax Reitz     qemu_opts_del(opts);
669bd745e23SMax Reitz     return bs;
670bd745e23SMax Reitz 
671bd745e23SMax Reitz fail:
672bd745e23SMax Reitz     qemu_opts_del(opts);
673bd745e23SMax Reitz     QDECREF(bs_opts);
674bd745e23SMax Reitz     return NULL;
675bd745e23SMax Reitz }
676bd745e23SMax Reitz 
6775abbf0eeSKevin Wolf static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
6785abbf0eeSKevin Wolf                             Error **errp)
67957975222SKevin Wolf {
68057975222SKevin Wolf     const char *value;
68157975222SKevin Wolf 
68257975222SKevin Wolf     value = qemu_opt_get(opts, from);
68357975222SKevin Wolf     if (value) {
6845abbf0eeSKevin Wolf         if (qemu_opt_find(opts, to)) {
6855abbf0eeSKevin Wolf             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
6865abbf0eeSKevin Wolf                        "same time", to, from);
6875abbf0eeSKevin Wolf             return;
6885abbf0eeSKevin Wolf         }
68920d6cd47SJun Li     }
69020d6cd47SJun Li 
69120d6cd47SJun Li     /* rename all items in opts */
69220d6cd47SJun Li     while ((value = qemu_opt_get(opts, from))) {
693f43e47dbSMarkus Armbruster         qemu_opt_set(opts, to, value, &error_abort);
69457975222SKevin Wolf         qemu_opt_unset(opts, from);
69557975222SKevin Wolf     }
69657975222SKevin Wolf }
69757975222SKevin Wolf 
69833cb7dc8SKevin Wolf QemuOptsList qemu_legacy_drive_opts = {
69933cb7dc8SKevin Wolf     .name = "drive",
70033cb7dc8SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
70133cb7dc8SKevin Wolf     .desc = {
70233cb7dc8SKevin Wolf         {
70387a899c5SKevin Wolf             .name = "bus",
70487a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
70587a899c5SKevin Wolf             .help = "bus number",
70687a899c5SKevin Wolf         },{
70787a899c5SKevin Wolf             .name = "unit",
70887a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
70987a899c5SKevin Wolf             .help = "unit number (i.e. lun for scsi)",
71087a899c5SKevin Wolf         },{
71187a899c5SKevin Wolf             .name = "index",
71287a899c5SKevin Wolf             .type = QEMU_OPT_NUMBER,
71387a899c5SKevin Wolf             .help = "index number",
71487a899c5SKevin Wolf         },{
71533cb7dc8SKevin Wolf             .name = "media",
71633cb7dc8SKevin Wolf             .type = QEMU_OPT_STRING,
71733cb7dc8SKevin Wolf             .help = "media type (disk, cdrom)",
718593d464bSKevin Wolf         },{
719593d464bSKevin Wolf             .name = "if",
720593d464bSKevin Wolf             .type = QEMU_OPT_STRING,
721593d464bSKevin Wolf             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
722b41a7338SKevin Wolf         },{
723b41a7338SKevin Wolf             .name = "cyls",
724b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
725b41a7338SKevin Wolf             .help = "number of cylinders (ide disk geometry)",
726b41a7338SKevin Wolf         },{
727b41a7338SKevin Wolf             .name = "heads",
728b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
729b41a7338SKevin Wolf             .help = "number of heads (ide disk geometry)",
730b41a7338SKevin Wolf         },{
731b41a7338SKevin Wolf             .name = "secs",
732b41a7338SKevin Wolf             .type = QEMU_OPT_NUMBER,
733b41a7338SKevin Wolf             .help = "number of sectors (ide disk geometry)",
734b41a7338SKevin Wolf         },{
735b41a7338SKevin Wolf             .name = "trans",
736b41a7338SKevin Wolf             .type = QEMU_OPT_STRING,
737b41a7338SKevin Wolf             .help = "chs translation (auto, lba, none)",
73826929298SKevin Wolf         },{
73926929298SKevin Wolf             .name = "boot",
74026929298SKevin Wolf             .type = QEMU_OPT_BOOL,
74126929298SKevin Wolf             .help = "(deprecated, ignored)",
742394c7d4dSKevin Wolf         },{
743394c7d4dSKevin Wolf             .name = "addr",
744394c7d4dSKevin Wolf             .type = QEMU_OPT_STRING,
745394c7d4dSKevin Wolf             .help = "pci address (virtio only)",
746d095b465SMax Reitz         },{
747bcf83158SKevin Wolf             .name = "serial",
748bcf83158SKevin Wolf             .type = QEMU_OPT_STRING,
749bcf83158SKevin Wolf             .help = "disk serial number",
750bcf83158SKevin 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         {
7580ebd24e0SKevin Wolf             .name = "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 
77960e19e06SMarkus Armbruster DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
78057975222SKevin Wolf {
78129c4e2b5SKevin Wolf     const char *value;
78218e46a03SMarkus Armbruster     BlockBackend *blk;
78333cb7dc8SKevin Wolf     DriveInfo *dinfo = NULL;
784f298d071SKevin Wolf     QDict *bs_opts;
78533cb7dc8SKevin Wolf     QemuOpts *legacy_opts;
78633cb7dc8SKevin Wolf     DriveMediaType media = MEDIA_DISK;
787593d464bSKevin Wolf     BlockInterfaceType type;
788b41a7338SKevin Wolf     int cyls, heads, secs, translation;
78987a899c5SKevin Wolf     int max_devs, bus_id, unit_id, index;
790394c7d4dSKevin Wolf     const char *devaddr;
791ee13ed1cSKevin Wolf     const char *werror, *rerror;
792a7fdbcf0SFam Zheng     bool read_only = false;
793a7fdbcf0SFam Zheng     bool copy_on_read;
794bcf83158SKevin Wolf     const char *serial;
795d095b465SMax Reitz     const char *filename;
79633cb7dc8SKevin Wolf     Error *local_err = NULL;
797247147fbSKevin Wolf     int i;
79829c4e2b5SKevin Wolf 
79957975222SKevin Wolf     /* Change legacy command line options into QMP ones */
800247147fbSKevin Wolf     static const struct {
801247147fbSKevin Wolf         const char *from;
802247147fbSKevin Wolf         const char *to;
803247147fbSKevin Wolf     } opt_renames[] = {
804247147fbSKevin Wolf         { "iops",           "throttling.iops-total" },
805247147fbSKevin Wolf         { "iops_rd",        "throttling.iops-read" },
806247147fbSKevin Wolf         { "iops_wr",        "throttling.iops-write" },
80757975222SKevin Wolf 
808247147fbSKevin Wolf         { "bps",            "throttling.bps-total" },
809247147fbSKevin Wolf         { "bps_rd",         "throttling.bps-read" },
810247147fbSKevin Wolf         { "bps_wr",         "throttling.bps-write" },
81157975222SKevin Wolf 
812247147fbSKevin Wolf         { "iops_max",       "throttling.iops-total-max" },
813247147fbSKevin Wolf         { "iops_rd_max",    "throttling.iops-read-max" },
814247147fbSKevin Wolf         { "iops_wr_max",    "throttling.iops-write-max" },
8153e9fab69SBenoît Canet 
816247147fbSKevin Wolf         { "bps_max",        "throttling.bps-total-max" },
817247147fbSKevin Wolf         { "bps_rd_max",     "throttling.bps-read-max" },
818247147fbSKevin Wolf         { "bps_wr_max",     "throttling.bps-write-max" },
8193e9fab69SBenoît Canet 
820247147fbSKevin Wolf         { "iops_size",      "throttling.iops-size" },
8212024c1dfSBenoît Canet 
82276f4afb4SAlberto Garcia         { "group",          "throttling.group" },
82376f4afb4SAlberto Garcia 
824247147fbSKevin Wolf         { "readonly",       "read-only" },
825247147fbSKevin Wolf     };
826247147fbSKevin Wolf 
827247147fbSKevin Wolf     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
8285abbf0eeSKevin Wolf         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
8295abbf0eeSKevin Wolf                         &local_err);
8305abbf0eeSKevin Wolf         if (local_err) {
831565f65d2SMarkus Armbruster             error_report_err(local_err);
8325abbf0eeSKevin Wolf             return NULL;
8335abbf0eeSKevin Wolf         }
834247147fbSKevin Wolf     }
8350f227a94SKevin Wolf 
83629c4e2b5SKevin Wolf     value = qemu_opt_get(all_opts, "cache");
83729c4e2b5SKevin Wolf     if (value) {
83829c4e2b5SKevin Wolf         int flags = 0;
83929c4e2b5SKevin Wolf 
84029c4e2b5SKevin Wolf         if (bdrv_parse_cache_flags(value, &flags) != 0) {
84129c4e2b5SKevin Wolf             error_report("invalid cache option");
84229c4e2b5SKevin Wolf             return NULL;
84329c4e2b5SKevin Wolf         }
84429c4e2b5SKevin Wolf 
84529c4e2b5SKevin Wolf         /* Specific options take precedence */
84654861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
84754861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
848cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_CACHE_WB), &error_abort);
84929c4e2b5SKevin Wolf         }
85054861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
85154861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
852cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NOCACHE), &error_abort);
85329c4e2b5SKevin Wolf         }
85454861b92SKevin Wolf         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
85554861b92SKevin Wolf             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
856cccb7967SMarkus Armbruster                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
85729c4e2b5SKevin Wolf         }
85829c4e2b5SKevin Wolf         qemu_opt_unset(all_opts, "cache");
85929c4e2b5SKevin Wolf     }
86029c4e2b5SKevin Wolf 
861f298d071SKevin Wolf     /* Get a QDict for processing the options */
862f298d071SKevin Wolf     bs_opts = qdict_new();
863f298d071SKevin Wolf     qemu_opts_to_qdict(all_opts, bs_opts);
864f298d071SKevin Wolf 
86587ea75d5SPeter Crosthwaite     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
86687ea75d5SPeter Crosthwaite                                    &error_abort);
86733cb7dc8SKevin Wolf     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
86884d18f06SMarkus Armbruster     if (local_err) {
869565f65d2SMarkus Armbruster         error_report_err(local_err);
87033cb7dc8SKevin Wolf         goto fail;
87133cb7dc8SKevin Wolf     }
87233cb7dc8SKevin Wolf 
87326929298SKevin Wolf     /* Deprecated option boot=[on|off] */
87426929298SKevin Wolf     if (qemu_opt_get(legacy_opts, "boot") != NULL) {
87526929298SKevin Wolf         fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
87626929298SKevin Wolf                 "ignored. Future versions will reject this parameter. Please "
87726929298SKevin Wolf                 "update your scripts.\n");
87826929298SKevin Wolf     }
87926929298SKevin Wolf 
88033cb7dc8SKevin Wolf     /* Media type */
88133cb7dc8SKevin Wolf     value = qemu_opt_get(legacy_opts, "media");
88233cb7dc8SKevin Wolf     if (value) {
88333cb7dc8SKevin Wolf         if (!strcmp(value, "disk")) {
88433cb7dc8SKevin Wolf             media = MEDIA_DISK;
88533cb7dc8SKevin Wolf         } else if (!strcmp(value, "cdrom")) {
88633cb7dc8SKevin Wolf             media = MEDIA_CDROM;
887a7fdbcf0SFam Zheng             read_only = true;
88833cb7dc8SKevin Wolf         } else {
88933cb7dc8SKevin Wolf             error_report("'%s' invalid media", value);
89033cb7dc8SKevin Wolf             goto fail;
89133cb7dc8SKevin Wolf         }
89233cb7dc8SKevin Wolf     }
89333cb7dc8SKevin Wolf 
8940ebd24e0SKevin Wolf     /* copy-on-read is disabled with a warning for read-only devices */
895a7fdbcf0SFam Zheng     read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
8960ebd24e0SKevin Wolf     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
8970ebd24e0SKevin Wolf 
8980ebd24e0SKevin Wolf     if (read_only && copy_on_read) {
8990ebd24e0SKevin Wolf         error_report("warning: disabling copy-on-read on read-only drive");
9000ebd24e0SKevin Wolf         copy_on_read = false;
9010ebd24e0SKevin Wolf     }
9020ebd24e0SKevin Wolf 
9030ebd24e0SKevin Wolf     qdict_put(bs_opts, "read-only",
9040ebd24e0SKevin Wolf               qstring_from_str(read_only ? "on" : "off"));
9050ebd24e0SKevin Wolf     qdict_put(bs_opts, "copy-on-read",
9060ebd24e0SKevin Wolf               qstring_from_str(copy_on_read ? "on" :"off"));
9070ebd24e0SKevin Wolf 
908593d464bSKevin Wolf     /* Controller type */
909593d464bSKevin Wolf     value = qemu_opt_get(legacy_opts, "if");
910593d464bSKevin Wolf     if (value) {
911593d464bSKevin Wolf         for (type = 0;
912593d464bSKevin Wolf              type < IF_COUNT && strcmp(value, if_name[type]);
913593d464bSKevin Wolf              type++) {
914593d464bSKevin Wolf         }
915593d464bSKevin Wolf         if (type == IF_COUNT) {
916593d464bSKevin Wolf             error_report("unsupported bus type '%s'", value);
917593d464bSKevin Wolf             goto fail;
918593d464bSKevin Wolf         }
919593d464bSKevin Wolf     } else {
920593d464bSKevin Wolf         type = block_default_type;
921593d464bSKevin Wolf     }
922593d464bSKevin Wolf 
923b41a7338SKevin Wolf     /* Geometry */
924b41a7338SKevin Wolf     cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
925b41a7338SKevin Wolf     heads = qemu_opt_get_number(legacy_opts, "heads", 0);
926b41a7338SKevin Wolf     secs  = qemu_opt_get_number(legacy_opts, "secs", 0);
927b41a7338SKevin Wolf 
928b41a7338SKevin Wolf     if (cyls || heads || secs) {
929b41a7338SKevin Wolf         if (cyls < 1) {
930b41a7338SKevin Wolf             error_report("invalid physical cyls number");
931b41a7338SKevin Wolf             goto fail;
932b41a7338SKevin Wolf         }
933b41a7338SKevin Wolf         if (heads < 1) {
934b41a7338SKevin Wolf             error_report("invalid physical heads number");
935b41a7338SKevin Wolf             goto fail;
936b41a7338SKevin Wolf         }
937b41a7338SKevin Wolf         if (secs < 1) {
938b41a7338SKevin Wolf             error_report("invalid physical secs number");
939b41a7338SKevin Wolf             goto fail;
940b41a7338SKevin Wolf         }
941b41a7338SKevin Wolf     }
942b41a7338SKevin Wolf 
943b41a7338SKevin Wolf     translation = BIOS_ATA_TRANSLATION_AUTO;
944b41a7338SKevin Wolf     value = qemu_opt_get(legacy_opts, "trans");
945b41a7338SKevin Wolf     if (value != NULL) {
946b41a7338SKevin Wolf         if (!cyls) {
947b41a7338SKevin Wolf             error_report("'%s' trans must be used with cyls, heads and secs",
948b41a7338SKevin Wolf                          value);
949b41a7338SKevin Wolf             goto fail;
950b41a7338SKevin Wolf         }
951b41a7338SKevin Wolf         if (!strcmp(value, "none")) {
952b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_NONE;
953b41a7338SKevin Wolf         } else if (!strcmp(value, "lba")) {
954b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_LBA;
955f31c41ffSPaolo Bonzini         } else if (!strcmp(value, "large")) {
956f31c41ffSPaolo Bonzini             translation = BIOS_ATA_TRANSLATION_LARGE;
957f31c41ffSPaolo Bonzini         } else if (!strcmp(value, "rechs")) {
958f31c41ffSPaolo Bonzini             translation = BIOS_ATA_TRANSLATION_RECHS;
959b41a7338SKevin Wolf         } else if (!strcmp(value, "auto")) {
960b41a7338SKevin Wolf             translation = BIOS_ATA_TRANSLATION_AUTO;
961b41a7338SKevin Wolf         } else {
962b41a7338SKevin Wolf             error_report("'%s' invalid translation type", value);
963b41a7338SKevin Wolf             goto fail;
964b41a7338SKevin Wolf         }
965b41a7338SKevin Wolf     }
966b41a7338SKevin Wolf 
967b41a7338SKevin Wolf     if (media == MEDIA_CDROM) {
968b41a7338SKevin Wolf         if (cyls || secs || heads) {
969b41a7338SKevin Wolf             error_report("CHS can't be set with media=cdrom");
970b41a7338SKevin Wolf             goto fail;
971b41a7338SKevin Wolf         }
972b41a7338SKevin Wolf     }
973b41a7338SKevin Wolf 
97487a899c5SKevin Wolf     /* Device address specified by bus/unit or index.
97587a899c5SKevin Wolf      * If none was specified, try to find the first free one. */
97687a899c5SKevin Wolf     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
97787a899c5SKevin Wolf     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
97887a899c5SKevin Wolf     index   = qemu_opt_get_number(legacy_opts, "index", -1);
97987a899c5SKevin Wolf 
98087a899c5SKevin Wolf     max_devs = if_max_devs[type];
98187a899c5SKevin Wolf 
98287a899c5SKevin Wolf     if (index != -1) {
98387a899c5SKevin Wolf         if (bus_id != 0 || unit_id != -1) {
98487a899c5SKevin Wolf             error_report("index cannot be used with bus and unit");
98587a899c5SKevin Wolf             goto fail;
98687a899c5SKevin Wolf         }
98787a899c5SKevin Wolf         bus_id = drive_index_to_bus_id(type, index);
98887a899c5SKevin Wolf         unit_id = drive_index_to_unit_id(type, index);
98987a899c5SKevin Wolf     }
99087a899c5SKevin Wolf 
99187a899c5SKevin Wolf     if (unit_id == -1) {
99287a899c5SKevin Wolf        unit_id = 0;
99387a899c5SKevin Wolf        while (drive_get(type, bus_id, unit_id) != NULL) {
99487a899c5SKevin Wolf            unit_id++;
99587a899c5SKevin Wolf            if (max_devs && unit_id >= max_devs) {
99687a899c5SKevin Wolf                unit_id -= max_devs;
99787a899c5SKevin Wolf                bus_id++;
99887a899c5SKevin Wolf            }
99987a899c5SKevin Wolf        }
100087a899c5SKevin Wolf     }
100187a899c5SKevin Wolf 
100287a899c5SKevin Wolf     if (max_devs && unit_id >= max_devs) {
100387a899c5SKevin Wolf         error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
100487a899c5SKevin Wolf         goto fail;
100587a899c5SKevin Wolf     }
100687a899c5SKevin Wolf 
100787a899c5SKevin Wolf     if (drive_get(type, bus_id, unit_id) != NULL) {
100887a899c5SKevin Wolf         error_report("drive with bus=%d, unit=%d (index=%d) exists",
100987a899c5SKevin Wolf                      bus_id, unit_id, index);
101087a899c5SKevin Wolf         goto fail;
101187a899c5SKevin Wolf     }
101287a899c5SKevin Wolf 
1013bcf83158SKevin Wolf     /* Serial number */
1014bcf83158SKevin Wolf     serial = qemu_opt_get(legacy_opts, "serial");
1015bcf83158SKevin Wolf 
101687a899c5SKevin Wolf     /* no id supplied -> create one */
101787a899c5SKevin Wolf     if (qemu_opts_id(all_opts) == NULL) {
101887a899c5SKevin Wolf         char *new_id;
101987a899c5SKevin Wolf         const char *mediastr = "";
102087a899c5SKevin Wolf         if (type == IF_IDE || type == IF_SCSI) {
102187a899c5SKevin Wolf             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
102287a899c5SKevin Wolf         }
102387a899c5SKevin Wolf         if (max_devs) {
102487a899c5SKevin Wolf             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
102587a899c5SKevin Wolf                                      mediastr, unit_id);
102687a899c5SKevin Wolf         } else {
102787a899c5SKevin Wolf             new_id = g_strdup_printf("%s%s%i", if_name[type],
102887a899c5SKevin Wolf                                      mediastr, unit_id);
102987a899c5SKevin Wolf         }
103087a899c5SKevin Wolf         qdict_put(bs_opts, "id", qstring_from_str(new_id));
103187a899c5SKevin Wolf         g_free(new_id);
103287a899c5SKevin Wolf     }
103387a899c5SKevin Wolf 
1034394c7d4dSKevin Wolf     /* Add virtio block device */
1035394c7d4dSKevin Wolf     devaddr = qemu_opt_get(legacy_opts, "addr");
1036394c7d4dSKevin Wolf     if (devaddr && type != IF_VIRTIO) {
1037394c7d4dSKevin Wolf         error_report("addr is not supported by this bus type");
1038394c7d4dSKevin Wolf         goto fail;
1039394c7d4dSKevin Wolf     }
1040394c7d4dSKevin Wolf 
1041394c7d4dSKevin Wolf     if (type == IF_VIRTIO) {
1042394c7d4dSKevin Wolf         QemuOpts *devopts;
104387ea75d5SPeter Crosthwaite         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
104487ea75d5SPeter Crosthwaite                                    &error_abort);
1045394c7d4dSKevin Wolf         if (arch_type == QEMU_ARCH_S390X) {
10461f68f1d3SAlexander Graf             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1047394c7d4dSKevin Wolf         } else {
1048f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1049394c7d4dSKevin Wolf         }
1050f43e47dbSMarkus Armbruster         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1051f43e47dbSMarkus Armbruster                      &error_abort);
1052394c7d4dSKevin Wolf         if (devaddr) {
1053f43e47dbSMarkus Armbruster             qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1054394c7d4dSKevin Wolf         }
1055394c7d4dSKevin Wolf     }
1056394c7d4dSKevin Wolf 
1057d095b465SMax Reitz     filename = qemu_opt_get(legacy_opts, "file");
1058d095b465SMax Reitz 
1059ee13ed1cSKevin Wolf     /* Check werror/rerror compatibility with if=... */
1060ee13ed1cSKevin Wolf     werror = qemu_opt_get(legacy_opts, "werror");
1061ee13ed1cSKevin Wolf     if (werror != NULL) {
1062ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1063ee13ed1cSKevin Wolf             type != IF_NONE) {
1064ee13ed1cSKevin Wolf             error_report("werror is not supported by this bus type");
1065ee13ed1cSKevin Wolf             goto fail;
1066ee13ed1cSKevin Wolf         }
1067ee13ed1cSKevin Wolf         qdict_put(bs_opts, "werror", qstring_from_str(werror));
1068ee13ed1cSKevin Wolf     }
1069ee13ed1cSKevin Wolf 
1070ee13ed1cSKevin Wolf     rerror = qemu_opt_get(legacy_opts, "rerror");
1071ee13ed1cSKevin Wolf     if (rerror != NULL) {
1072ee13ed1cSKevin Wolf         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1073ee13ed1cSKevin Wolf             type != IF_NONE) {
1074ee13ed1cSKevin Wolf             error_report("rerror is not supported by this bus type");
1075ee13ed1cSKevin Wolf             goto fail;
1076ee13ed1cSKevin Wolf         }
1077ee13ed1cSKevin Wolf         qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1078ee13ed1cSKevin Wolf     }
1079ee13ed1cSKevin Wolf 
10802d246f01SKevin Wolf     /* Actual block device init: Functionality shared with blockdev-add */
108118e46a03SMarkus Armbruster     blk = blockdev_init(filename, bs_opts, &local_err);
10823cb0e25cSMarkus Armbruster     bs_opts = NULL;
108318e46a03SMarkus Armbruster     if (!blk) {
108484d18f06SMarkus Armbruster         if (local_err) {
1085565f65d2SMarkus Armbruster             error_report_err(local_err);
1086b681072dSKevin Wolf         }
10872d246f01SKevin Wolf         goto fail;
1088b681072dSKevin Wolf     } else {
108984d18f06SMarkus Armbruster         assert(!local_err);
10902d246f01SKevin Wolf     }
10912d246f01SKevin Wolf 
109226f8b3a8SMarkus Armbruster     /* Create legacy DriveInfo */
109326f8b3a8SMarkus Armbruster     dinfo = g_malloc0(sizeof(*dinfo));
1094f298d071SKevin Wolf     dinfo->opts = all_opts;
10952d246f01SKevin Wolf 
1096b41a7338SKevin Wolf     dinfo->cyls = cyls;
1097b41a7338SKevin Wolf     dinfo->heads = heads;
1098b41a7338SKevin Wolf     dinfo->secs = secs;
1099b41a7338SKevin Wolf     dinfo->trans = translation;
1100b41a7338SKevin Wolf 
1101ee13ed1cSKevin Wolf     dinfo->type = type;
110287a899c5SKevin Wolf     dinfo->bus = bus_id;
110387a899c5SKevin Wolf     dinfo->unit = unit_id;
1104394c7d4dSKevin Wolf     dinfo->devaddr = devaddr;
1105bcf83158SKevin Wolf     dinfo->serial = g_strdup(serial);
1106bcf83158SKevin Wolf 
110726f8b3a8SMarkus Armbruster     blk_set_legacy_dinfo(blk, dinfo);
110826f8b3a8SMarkus Armbruster 
1109e34ef046SKevin Wolf     switch(type) {
1110e34ef046SKevin Wolf     case IF_IDE:
1111e34ef046SKevin Wolf     case IF_SCSI:
1112e34ef046SKevin Wolf     case IF_XEN:
1113e34ef046SKevin Wolf     case IF_NONE:
1114e34ef046SKevin Wolf         dinfo->media_cd = media == MEDIA_CDROM;
1115e34ef046SKevin Wolf         break;
1116e34ef046SKevin Wolf     default:
1117e34ef046SKevin Wolf         break;
1118e34ef046SKevin Wolf     }
1119e34ef046SKevin Wolf 
11202d246f01SKevin Wolf fail:
112133cb7dc8SKevin Wolf     qemu_opts_del(legacy_opts);
11223cb0e25cSMarkus Armbruster     QDECREF(bs_opts);
11232d246f01SKevin Wolf     return dinfo;
112457975222SKevin Wolf }
112557975222SKevin Wolf 
11263e5a50d6SMarkus Armbruster void hmp_commit(Monitor *mon, const QDict *qdict)
1127666daa68SMarkus Armbruster {
1128666daa68SMarkus Armbruster     const char *device = qdict_get_str(qdict, "device");
1129a0e8544cSFam Zheng     BlockBackend *blk;
11302d3735d3SStefan Hajnoczi     int ret;
11312d3735d3SStefan Hajnoczi 
1132e8877497SStefan Hajnoczi     if (!strcmp(device, "all")) {
1133e8877497SStefan Hajnoczi         ret = bdrv_commit_all();
1134e8877497SStefan Hajnoczi     } else {
113584aa0140SStefan Hajnoczi         BlockDriverState *bs;
113684aa0140SStefan Hajnoczi         AioContext *aio_context;
113784aa0140SStefan Hajnoczi 
1138a0e8544cSFam Zheng         blk = blk_by_name(device);
1139a0e8544cSFam Zheng         if (!blk) {
114058513bdeSJeff Cody             monitor_printf(mon, "Device '%s' not found\n", device);
1141ac59eb95SMarkus Armbruster             return;
11426ab4b5abSMarkus Armbruster         }
11435433c24fSMax Reitz         if (!blk_is_available(blk)) {
11445433c24fSMax Reitz             monitor_printf(mon, "Device '%s' has no medium\n", device);
11455433c24fSMax Reitz             return;
11465433c24fSMax Reitz         }
114784aa0140SStefan Hajnoczi 
114884aa0140SStefan Hajnoczi         bs = blk_bs(blk);
114984aa0140SStefan Hajnoczi         aio_context = bdrv_get_aio_context(bs);
115084aa0140SStefan Hajnoczi         aio_context_acquire(aio_context);
115184aa0140SStefan Hajnoczi 
115284aa0140SStefan Hajnoczi         ret = bdrv_commit(bs);
115384aa0140SStefan Hajnoczi 
115484aa0140SStefan Hajnoczi         aio_context_release(aio_context);
11552d3735d3SStefan Hajnoczi     }
115658513bdeSJeff Cody     if (ret < 0) {
115758513bdeSJeff Cody         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
115858513bdeSJeff Cody                        strerror(-ret));
1159666daa68SMarkus Armbruster     }
1160666daa68SMarkus Armbruster }
1161666daa68SMarkus Armbruster 
11626a8f9661SEric Blake static void blockdev_do_action(TransactionActionKind type, void *data,
11636a8f9661SEric Blake                                Error **errp)
11646cc2a415SPaolo Bonzini {
1165c8a83e85SKevin Wolf     TransactionAction action;
1166c8a83e85SKevin Wolf     TransactionActionList list;
11676cc2a415SPaolo Bonzini 
11686a8f9661SEric Blake     action.type = type;
11696a8f9661SEric Blake     action.u.data = data;
11706cc2a415SPaolo Bonzini     list.value = &action;
11716cc2a415SPaolo Bonzini     list.next = NULL;
117294d16a64SJohn Snow     qmp_transaction(&list, false, NULL, errp);
11736cc2a415SPaolo Bonzini }
11746cc2a415SPaolo Bonzini 
11750901f67eSBenoît Canet void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
11760901f67eSBenoît Canet                                 bool has_node_name, const char *node_name,
11770901f67eSBenoît Canet                                 const char *snapshot_file,
11780901f67eSBenoît Canet                                 bool has_snapshot_node_name,
11790901f67eSBenoît Canet                                 const char *snapshot_node_name,
11806106e249SLuiz Capitulino                                 bool has_format, const char *format,
11810901f67eSBenoît Canet                                 bool has_mode, NewImageMode mode, Error **errp)
1182f8882568SJes Sorensen {
1183a911e6aeSAlberto Garcia     BlockdevSnapshotSync snapshot = {
11840901f67eSBenoît Canet         .has_device = has_device,
11856cc2a415SPaolo Bonzini         .device = (char *) device,
11860901f67eSBenoît Canet         .has_node_name = has_node_name,
11870901f67eSBenoît Canet         .node_name = (char *) node_name,
11886cc2a415SPaolo Bonzini         .snapshot_file = (char *) snapshot_file,
11890901f67eSBenoît Canet         .has_snapshot_node_name = has_snapshot_node_name,
11900901f67eSBenoît Canet         .snapshot_node_name = (char *) snapshot_node_name,
11916cc2a415SPaolo Bonzini         .has_format = has_format,
11926cc2a415SPaolo Bonzini         .format = (char *) format,
11936cc2a415SPaolo Bonzini         .has_mode = has_mode,
11946cc2a415SPaolo Bonzini         .mode = mode,
11956cc2a415SPaolo Bonzini     };
1196c8a83e85SKevin Wolf     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1197c8a83e85SKevin Wolf                        &snapshot, errp);
1198f8882568SJes Sorensen }
1199f8882568SJes Sorensen 
120043de7e2dSAlberto Garcia void qmp_blockdev_snapshot(const char *node, const char *overlay,
120143de7e2dSAlberto Garcia                            Error **errp)
120243de7e2dSAlberto Garcia {
120343de7e2dSAlberto Garcia     BlockdevSnapshot snapshot_data = {
120443de7e2dSAlberto Garcia         .node = (char *) node,
120543de7e2dSAlberto Garcia         .overlay = (char *) overlay
120643de7e2dSAlberto Garcia     };
120743de7e2dSAlberto Garcia 
120843de7e2dSAlberto Garcia     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
120943de7e2dSAlberto Garcia                        &snapshot_data, errp);
121043de7e2dSAlberto Garcia }
121143de7e2dSAlberto Garcia 
1212f323bc9eSWenchao Xia void qmp_blockdev_snapshot_internal_sync(const char *device,
1213f323bc9eSWenchao Xia                                          const char *name,
1214f323bc9eSWenchao Xia                                          Error **errp)
1215f323bc9eSWenchao Xia {
1216f323bc9eSWenchao Xia     BlockdevSnapshotInternal snapshot = {
1217f323bc9eSWenchao Xia         .device = (char *) device,
1218f323bc9eSWenchao Xia         .name = (char *) name
1219f323bc9eSWenchao Xia     };
1220f323bc9eSWenchao Xia 
1221f323bc9eSWenchao Xia     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1222f323bc9eSWenchao Xia                        &snapshot, errp);
1223f323bc9eSWenchao Xia }
1224f323bc9eSWenchao Xia 
122544e3e053SWenchao Xia SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
122644e3e053SWenchao Xia                                                          bool has_id,
122744e3e053SWenchao Xia                                                          const char *id,
122844e3e053SWenchao Xia                                                          bool has_name,
122944e3e053SWenchao Xia                                                          const char *name,
123044e3e053SWenchao Xia                                                          Error **errp)
123144e3e053SWenchao Xia {
1232a0e8544cSFam Zheng     BlockDriverState *bs;
1233a0e8544cSFam Zheng     BlockBackend *blk;
12344ef3982aSStefan Hajnoczi     AioContext *aio_context;
123544e3e053SWenchao Xia     QEMUSnapshotInfo sn;
123644e3e053SWenchao Xia     Error *local_err = NULL;
123744e3e053SWenchao Xia     SnapshotInfo *info = NULL;
123844e3e053SWenchao Xia     int ret;
123944e3e053SWenchao Xia 
1240a0e8544cSFam Zheng     blk = blk_by_name(device);
1241a0e8544cSFam Zheng     if (!blk) {
124275158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
124375158ebbSMarkus Armbruster                   "Device '%s' not found", device);
124444e3e053SWenchao Xia         return NULL;
124544e3e053SWenchao Xia     }
12465433c24fSMax Reitz 
12475433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
12485433c24fSMax Reitz     aio_context_acquire(aio_context);
124944e3e053SWenchao Xia 
125044e3e053SWenchao Xia     if (!has_id) {
125144e3e053SWenchao Xia         id = NULL;
125244e3e053SWenchao Xia     }
125344e3e053SWenchao Xia 
125444e3e053SWenchao Xia     if (!has_name) {
125544e3e053SWenchao Xia         name = NULL;
125644e3e053SWenchao Xia     }
125744e3e053SWenchao Xia 
125844e3e053SWenchao Xia     if (!id && !name) {
125944e3e053SWenchao Xia         error_setg(errp, "Name or id must be provided");
12605433c24fSMax Reitz         goto out_aio_context;
126144e3e053SWenchao Xia     }
126244e3e053SWenchao Xia 
12635433c24fSMax Reitz     if (!blk_is_available(blk)) {
12645433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
12655433c24fSMax Reitz         goto out_aio_context;
12665433c24fSMax Reitz     }
12675433c24fSMax Reitz     bs = blk_bs(blk);
12684ef3982aSStefan Hajnoczi 
12690b928854SStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
12700b928854SStefan Hajnoczi         goto out_aio_context;
12710b928854SStefan Hajnoczi     }
12720b928854SStefan Hajnoczi 
127344e3e053SWenchao Xia     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
127484d18f06SMarkus Armbruster     if (local_err) {
127544e3e053SWenchao Xia         error_propagate(errp, local_err);
12764ef3982aSStefan Hajnoczi         goto out_aio_context;
127744e3e053SWenchao Xia     }
127844e3e053SWenchao Xia     if (!ret) {
127944e3e053SWenchao Xia         error_setg(errp,
128044e3e053SWenchao Xia                    "Snapshot with id '%s' and name '%s' does not exist on "
128144e3e053SWenchao Xia                    "device '%s'",
128244e3e053SWenchao Xia                    STR_OR_NULL(id), STR_OR_NULL(name), device);
12834ef3982aSStefan Hajnoczi         goto out_aio_context;
128444e3e053SWenchao Xia     }
128544e3e053SWenchao Xia 
128644e3e053SWenchao Xia     bdrv_snapshot_delete(bs, id, name, &local_err);
128784d18f06SMarkus Armbruster     if (local_err) {
128844e3e053SWenchao Xia         error_propagate(errp, local_err);
12894ef3982aSStefan Hajnoczi         goto out_aio_context;
129044e3e053SWenchao Xia     }
129144e3e053SWenchao Xia 
12924ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
12934ef3982aSStefan Hajnoczi 
12945839e53bSMarkus Armbruster     info = g_new0(SnapshotInfo, 1);
129544e3e053SWenchao Xia     info->id = g_strdup(sn.id_str);
129644e3e053SWenchao Xia     info->name = g_strdup(sn.name);
129744e3e053SWenchao Xia     info->date_nsec = sn.date_nsec;
129844e3e053SWenchao Xia     info->date_sec = sn.date_sec;
129944e3e053SWenchao Xia     info->vm_state_size = sn.vm_state_size;
130044e3e053SWenchao Xia     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
130144e3e053SWenchao Xia     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
130244e3e053SWenchao Xia 
130344e3e053SWenchao Xia     return info;
13044ef3982aSStefan Hajnoczi 
13054ef3982aSStefan Hajnoczi out_aio_context:
13064ef3982aSStefan Hajnoczi     aio_context_release(aio_context);
13074ef3982aSStefan Hajnoczi     return NULL;
130844e3e053SWenchao Xia }
13098802d1fdSJeff Cody 
1310341ebc2fSJohn Snow /**
1311341ebc2fSJohn Snow  * block_dirty_bitmap_lookup:
1312341ebc2fSJohn Snow  * Return a dirty bitmap (if present), after validating
1313341ebc2fSJohn Snow  * the node reference and bitmap names.
1314341ebc2fSJohn Snow  *
1315341ebc2fSJohn Snow  * @node: The name of the BDS node to search for bitmaps
1316341ebc2fSJohn Snow  * @name: The name of the bitmap to search for
1317341ebc2fSJohn Snow  * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1318341ebc2fSJohn Snow  * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1319341ebc2fSJohn Snow  * @errp: Output pointer for error information. Can be NULL.
1320341ebc2fSJohn Snow  *
1321341ebc2fSJohn Snow  * @return: A bitmap object on success, or NULL on failure.
1322341ebc2fSJohn Snow  */
1323341ebc2fSJohn Snow static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1324341ebc2fSJohn Snow                                                   const char *name,
1325341ebc2fSJohn Snow                                                   BlockDriverState **pbs,
1326341ebc2fSJohn Snow                                                   AioContext **paio,
1327341ebc2fSJohn Snow                                                   Error **errp)
1328341ebc2fSJohn Snow {
1329341ebc2fSJohn Snow     BlockDriverState *bs;
1330341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
1331341ebc2fSJohn Snow     AioContext *aio_context;
1332341ebc2fSJohn Snow 
1333341ebc2fSJohn Snow     if (!node) {
1334341ebc2fSJohn Snow         error_setg(errp, "Node cannot be NULL");
1335341ebc2fSJohn Snow         return NULL;
1336341ebc2fSJohn Snow     }
1337341ebc2fSJohn Snow     if (!name) {
1338341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be NULL");
1339341ebc2fSJohn Snow         return NULL;
1340341ebc2fSJohn Snow     }
1341341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, NULL);
1342341ebc2fSJohn Snow     if (!bs) {
1343341ebc2fSJohn Snow         error_setg(errp, "Node '%s' not found", node);
1344341ebc2fSJohn Snow         return NULL;
1345341ebc2fSJohn Snow     }
1346341ebc2fSJohn Snow 
1347341ebc2fSJohn Snow     aio_context = bdrv_get_aio_context(bs);
1348341ebc2fSJohn Snow     aio_context_acquire(aio_context);
1349341ebc2fSJohn Snow 
1350341ebc2fSJohn Snow     bitmap = bdrv_find_dirty_bitmap(bs, name);
1351341ebc2fSJohn Snow     if (!bitmap) {
1352341ebc2fSJohn Snow         error_setg(errp, "Dirty bitmap '%s' not found", name);
1353341ebc2fSJohn Snow         goto fail;
1354341ebc2fSJohn Snow     }
1355341ebc2fSJohn Snow 
1356341ebc2fSJohn Snow     if (pbs) {
1357341ebc2fSJohn Snow         *pbs = bs;
1358341ebc2fSJohn Snow     }
1359341ebc2fSJohn Snow     if (paio) {
1360341ebc2fSJohn Snow         *paio = aio_context;
1361341ebc2fSJohn Snow     } else {
1362341ebc2fSJohn Snow         aio_context_release(aio_context);
1363341ebc2fSJohn Snow     }
1364341ebc2fSJohn Snow 
1365341ebc2fSJohn Snow     return bitmap;
1366341ebc2fSJohn Snow 
1367341ebc2fSJohn Snow  fail:
1368341ebc2fSJohn Snow     aio_context_release(aio_context);
1369341ebc2fSJohn Snow     return NULL;
1370341ebc2fSJohn Snow }
1371341ebc2fSJohn Snow 
1372b756b9ceSStefan Hajnoczi /* New and old BlockDriverState structs for atomic group operations */
1373ba0c86a3SWenchao Xia 
137450f43f0fSJohn Snow typedef struct BlkActionState BlkActionState;
1375ba0c86a3SWenchao Xia 
137650f43f0fSJohn Snow /**
137750f43f0fSJohn Snow  * BlkActionOps:
137850f43f0fSJohn Snow  * Table of operations that define an Action.
137950f43f0fSJohn Snow  *
138050f43f0fSJohn Snow  * @instance_size: Size of state struct, in bytes.
138150f43f0fSJohn Snow  * @prepare: Prepare the work, must NOT be NULL.
138250f43f0fSJohn Snow  * @commit: Commit the changes, can be NULL.
138350f43f0fSJohn Snow  * @abort: Abort the changes on fail, can be NULL.
138450f43f0fSJohn Snow  * @clean: Clean up resources after all transaction actions have called
138550f43f0fSJohn Snow  *         commit() or abort(). Can be NULL.
138650f43f0fSJohn Snow  *
138750f43f0fSJohn Snow  * Only prepare() may fail. In a single transaction, only one of commit() or
138850f43f0fSJohn Snow  * abort() will be called. clean() will always be called if it is present.
1389ba0c86a3SWenchao Xia  */
139050f43f0fSJohn Snow typedef struct BlkActionOps {
139150f43f0fSJohn Snow     size_t instance_size;
139250f43f0fSJohn Snow     void (*prepare)(BlkActionState *common, Error **errp);
139350f43f0fSJohn Snow     void (*commit)(BlkActionState *common);
139450f43f0fSJohn Snow     void (*abort)(BlkActionState *common);
139550f43f0fSJohn Snow     void (*clean)(BlkActionState *common);
139650f43f0fSJohn Snow } BlkActionOps;
139750f43f0fSJohn Snow 
139850f43f0fSJohn Snow /**
139950f43f0fSJohn Snow  * BlkActionState:
140050f43f0fSJohn Snow  * Describes one Action's state within a Transaction.
140150f43f0fSJohn Snow  *
140250f43f0fSJohn Snow  * @action: QAPI-defined enum identifying which Action to perform.
140350f43f0fSJohn Snow  * @ops: Table of ActionOps this Action can perform.
140494d16a64SJohn Snow  * @block_job_txn: Transaction which this action belongs to.
140550f43f0fSJohn Snow  * @entry: List membership for all Actions in this Transaction.
140650f43f0fSJohn Snow  *
140750f43f0fSJohn Snow  * This structure must be arranged as first member in a subclassed type,
140850f43f0fSJohn Snow  * assuming that the compiler will also arrange it to the same offsets as the
140950f43f0fSJohn Snow  * base class.
141050f43f0fSJohn Snow  */
141150f43f0fSJohn Snow struct BlkActionState {
1412c8a83e85SKevin Wolf     TransactionAction *action;
141350f43f0fSJohn Snow     const BlkActionOps *ops;
141494d16a64SJohn Snow     BlockJobTxn *block_job_txn;
141594d16a64SJohn Snow     TransactionProperties *txn_props;
141650f43f0fSJohn Snow     QSIMPLEQ_ENTRY(BlkActionState) entry;
1417ba0c86a3SWenchao Xia };
1418ba0c86a3SWenchao Xia 
1419bbe86010SWenchao Xia /* internal snapshot private data */
1420bbe86010SWenchao Xia typedef struct InternalSnapshotState {
142150f43f0fSJohn Snow     BlkActionState common;
1422bbe86010SWenchao Xia     BlockDriverState *bs;
14235d6e96efSStefan Hajnoczi     AioContext *aio_context;
1424bbe86010SWenchao Xia     QEMUSnapshotInfo sn;
1425507306ccSFam Zheng     bool created;
1426bbe86010SWenchao Xia } InternalSnapshotState;
1427bbe86010SWenchao Xia 
142894d16a64SJohn Snow 
142994d16a64SJohn Snow static int action_check_completion_mode(BlkActionState *s, Error **errp)
143094d16a64SJohn Snow {
143194d16a64SJohn Snow     if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
143294d16a64SJohn Snow         error_setg(errp,
143394d16a64SJohn Snow                    "Action '%s' does not support Transaction property "
143494d16a64SJohn Snow                    "completion-mode = %s",
143594d16a64SJohn Snow                    TransactionActionKind_lookup[s->action->type],
143694d16a64SJohn Snow                    ActionCompletionMode_lookup[s->txn_props->completion_mode]);
143794d16a64SJohn Snow         return -1;
143894d16a64SJohn Snow     }
143994d16a64SJohn Snow     return 0;
144094d16a64SJohn Snow }
144194d16a64SJohn Snow 
144250f43f0fSJohn Snow static void internal_snapshot_prepare(BlkActionState *common,
1443bbe86010SWenchao Xia                                       Error **errp)
1444bbe86010SWenchao Xia {
1445f70edf99SMarkus Armbruster     Error *local_err = NULL;
1446bbe86010SWenchao Xia     const char *device;
1447bbe86010SWenchao Xia     const char *name;
1448a0e8544cSFam Zheng     BlockBackend *blk;
1449bbe86010SWenchao Xia     BlockDriverState *bs;
1450bbe86010SWenchao Xia     QEMUSnapshotInfo old_sn, *sn;
1451bbe86010SWenchao Xia     bool ret;
1452bbe86010SWenchao Xia     qemu_timeval tv;
1453bbe86010SWenchao Xia     BlockdevSnapshotInternal *internal;
1454bbe86010SWenchao Xia     InternalSnapshotState *state;
1455bbe86010SWenchao Xia     int ret1;
1456bbe86010SWenchao Xia 
14576a8f9661SEric Blake     g_assert(common->action->type ==
1458bbe86010SWenchao Xia              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
14596a8f9661SEric Blake     internal = common->action->u.blockdev_snapshot_internal_sync;
1460bbe86010SWenchao Xia     state = DO_UPCAST(InternalSnapshotState, common, common);
1461bbe86010SWenchao Xia 
1462bbe86010SWenchao Xia     /* 1. parse input */
1463bbe86010SWenchao Xia     device = internal->device;
1464bbe86010SWenchao Xia     name = internal->name;
1465bbe86010SWenchao Xia 
1466bbe86010SWenchao Xia     /* 2. check for validation */
146794d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
146894d16a64SJohn Snow         return;
146994d16a64SJohn Snow     }
147094d16a64SJohn Snow 
1471a0e8544cSFam Zheng     blk = blk_by_name(device);
1472a0e8544cSFam Zheng     if (!blk) {
147375158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
147475158ebbSMarkus Armbruster                   "Device '%s' not found", device);
1475bbe86010SWenchao Xia         return;
1476bbe86010SWenchao Xia     }
1477bbe86010SWenchao Xia 
14785d6e96efSStefan Hajnoczi     /* AioContext is released in .clean() */
14795433c24fSMax Reitz     state->aio_context = blk_get_aio_context(blk);
14805d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
14815d6e96efSStefan Hajnoczi 
14825433c24fSMax Reitz     if (!blk_is_available(blk)) {
1483c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1484bbe86010SWenchao Xia         return;
1485bbe86010SWenchao Xia     }
14865433c24fSMax Reitz     bs = blk_bs(blk);
1487bbe86010SWenchao Xia 
1488507306ccSFam Zheng     state->bs = bs;
1489507306ccSFam Zheng     bdrv_drained_begin(bs);
1490507306ccSFam Zheng 
14913dc7ca3cSStefan Hajnoczi     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
14923dc7ca3cSStefan Hajnoczi         return;
14933dc7ca3cSStefan Hajnoczi     }
14943dc7ca3cSStefan Hajnoczi 
1495bbe86010SWenchao Xia     if (bdrv_is_read_only(bs)) {
149681e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
1497bbe86010SWenchao Xia         return;
1498bbe86010SWenchao Xia     }
1499bbe86010SWenchao Xia 
1500bbe86010SWenchao Xia     if (!bdrv_can_snapshot(bs)) {
150181e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by device '%s' "
150281e5f78aSAlberto Garcia                    "does not support internal snapshots",
150381e5f78aSAlberto Garcia                    bs->drv->format_name, device);
1504bbe86010SWenchao Xia         return;
1505bbe86010SWenchao Xia     }
1506bbe86010SWenchao Xia 
1507bbe86010SWenchao Xia     if (!strlen(name)) {
1508bbe86010SWenchao Xia         error_setg(errp, "Name is empty");
1509bbe86010SWenchao Xia         return;
1510bbe86010SWenchao Xia     }
1511bbe86010SWenchao Xia 
1512bbe86010SWenchao Xia     /* check whether a snapshot with name exist */
1513f70edf99SMarkus Armbruster     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1514f70edf99SMarkus Armbruster                                             &local_err);
1515f70edf99SMarkus Armbruster     if (local_err) {
1516f70edf99SMarkus Armbruster         error_propagate(errp, local_err);
1517bbe86010SWenchao Xia         return;
1518bbe86010SWenchao Xia     } else if (ret) {
1519bbe86010SWenchao Xia         error_setg(errp,
1520bbe86010SWenchao Xia                    "Snapshot with name '%s' already exists on device '%s'",
1521bbe86010SWenchao Xia                    name, device);
1522bbe86010SWenchao Xia         return;
1523bbe86010SWenchao Xia     }
1524bbe86010SWenchao Xia 
1525bbe86010SWenchao Xia     /* 3. take the snapshot */
1526bbe86010SWenchao Xia     sn = &state->sn;
1527bbe86010SWenchao Xia     pstrcpy(sn->name, sizeof(sn->name), name);
1528bbe86010SWenchao Xia     qemu_gettimeofday(&tv);
1529bbe86010SWenchao Xia     sn->date_sec = tv.tv_sec;
1530bbe86010SWenchao Xia     sn->date_nsec = tv.tv_usec * 1000;
1531bbe86010SWenchao Xia     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1532bbe86010SWenchao Xia 
1533bbe86010SWenchao Xia     ret1 = bdrv_snapshot_create(bs, sn);
1534bbe86010SWenchao Xia     if (ret1 < 0) {
1535bbe86010SWenchao Xia         error_setg_errno(errp, -ret1,
1536bbe86010SWenchao Xia                          "Failed to create snapshot '%s' on device '%s'",
1537bbe86010SWenchao Xia                          name, device);
1538bbe86010SWenchao Xia         return;
1539bbe86010SWenchao Xia     }
1540bbe86010SWenchao Xia 
1541bbe86010SWenchao Xia     /* 4. succeed, mark a snapshot is created */
1542507306ccSFam Zheng     state->created = true;
1543bbe86010SWenchao Xia }
1544bbe86010SWenchao Xia 
154550f43f0fSJohn Snow static void internal_snapshot_abort(BlkActionState *common)
1546bbe86010SWenchao Xia {
1547bbe86010SWenchao Xia     InternalSnapshotState *state =
1548bbe86010SWenchao Xia                              DO_UPCAST(InternalSnapshotState, common, common);
1549bbe86010SWenchao Xia     BlockDriverState *bs = state->bs;
1550bbe86010SWenchao Xia     QEMUSnapshotInfo *sn = &state->sn;
1551bbe86010SWenchao Xia     Error *local_error = NULL;
1552bbe86010SWenchao Xia 
1553507306ccSFam Zheng     if (!state->created) {
1554bbe86010SWenchao Xia         return;
1555bbe86010SWenchao Xia     }
1556bbe86010SWenchao Xia 
1557bbe86010SWenchao Xia     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1558bbe86010SWenchao Xia         error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1559bbe86010SWenchao Xia                      "device '%s' in abort: %s",
1560bbe86010SWenchao Xia                      sn->id_str,
1561bbe86010SWenchao Xia                      sn->name,
1562bbe86010SWenchao Xia                      bdrv_get_device_name(bs),
1563bbe86010SWenchao Xia                      error_get_pretty(local_error));
1564bbe86010SWenchao Xia         error_free(local_error);
1565bbe86010SWenchao Xia     }
1566bbe86010SWenchao Xia }
1567bbe86010SWenchao Xia 
156850f43f0fSJohn Snow static void internal_snapshot_clean(BlkActionState *common)
15695d6e96efSStefan Hajnoczi {
15705d6e96efSStefan Hajnoczi     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
15715d6e96efSStefan Hajnoczi                                              common, common);
15725d6e96efSStefan Hajnoczi 
15735d6e96efSStefan Hajnoczi     if (state->aio_context) {
1574507306ccSFam Zheng         if (state->bs) {
1575507306ccSFam Zheng             bdrv_drained_end(state->bs);
1576507306ccSFam Zheng         }
15775d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
15785d6e96efSStefan Hajnoczi     }
15795d6e96efSStefan Hajnoczi }
15805d6e96efSStefan Hajnoczi 
1581ba0c86a3SWenchao Xia /* external snapshot private data */
1582ba5d6ab6SStefan Hajnoczi typedef struct ExternalSnapshotState {
158350f43f0fSJohn Snow     BlkActionState common;
15848802d1fdSJeff Cody     BlockDriverState *old_bs;
15858802d1fdSJeff Cody     BlockDriverState *new_bs;
15865d6e96efSStefan Hajnoczi     AioContext *aio_context;
1587ba5d6ab6SStefan Hajnoczi } ExternalSnapshotState;
15888802d1fdSJeff Cody 
158950f43f0fSJohn Snow static void external_snapshot_prepare(BlkActionState *common,
15909b9877eeSWenchao Xia                                       Error **errp)
15919b9877eeSWenchao Xia {
159243de7e2dSAlberto Garcia     int flags = 0, ret;
159343de7e2dSAlberto Garcia     QDict *options = NULL;
15949b9877eeSWenchao Xia     Error *local_err = NULL;
159543de7e2dSAlberto Garcia     /* Device and node name of the image to generate the snapshot from */
1596e2a31e87SWenchao Xia     const char *device;
15970901f67eSBenoît Canet     const char *node_name;
159843de7e2dSAlberto Garcia     /* Reference to the new image (for 'blockdev-snapshot') */
159943de7e2dSAlberto Garcia     const char *snapshot_ref;
160043de7e2dSAlberto Garcia     /* File name of the new image (for 'blockdev-snapshot-sync') */
1601e2a31e87SWenchao Xia     const char *new_image_file;
1602ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1603ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1604c8a83e85SKevin Wolf     TransactionAction *action = common->action;
16059b9877eeSWenchao Xia 
160643de7e2dSAlberto Garcia     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
160743de7e2dSAlberto Garcia      * purpose but a different set of parameters */
160843de7e2dSAlberto Garcia     switch (action->type) {
160943de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
161043de7e2dSAlberto Garcia         {
161143de7e2dSAlberto Garcia             BlockdevSnapshot *s = action->u.blockdev_snapshot;
161243de7e2dSAlberto Garcia             device = s->node;
161343de7e2dSAlberto Garcia             node_name = s->node;
161443de7e2dSAlberto Garcia             new_image_file = NULL;
161543de7e2dSAlberto Garcia             snapshot_ref = s->overlay;
1616e2a31e87SWenchao Xia         }
161743de7e2dSAlberto Garcia         break;
161843de7e2dSAlberto Garcia     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
161943de7e2dSAlberto Garcia         {
162043de7e2dSAlberto Garcia             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
162143de7e2dSAlberto Garcia             device = s->has_device ? s->device : NULL;
162243de7e2dSAlberto Garcia             node_name = s->has_node_name ? s->node_name : NULL;
162343de7e2dSAlberto Garcia             new_image_file = s->snapshot_file;
162443de7e2dSAlberto Garcia             snapshot_ref = NULL;
162543de7e2dSAlberto Garcia         }
162643de7e2dSAlberto Garcia         break;
162743de7e2dSAlberto Garcia     default:
162843de7e2dSAlberto Garcia         g_assert_not_reached();
1629e2a31e87SWenchao Xia     }
1630e2a31e87SWenchao Xia 
1631e2a31e87SWenchao Xia     /* start processing */
163294d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
163394d16a64SJohn Snow         return;
163494d16a64SJohn Snow     }
163594d16a64SJohn Snow 
163643de7e2dSAlberto Garcia     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
163743de7e2dSAlberto Garcia     if (!state->old_bs) {
16389b9877eeSWenchao Xia         return;
16399b9877eeSWenchao Xia     }
16409b9877eeSWenchao Xia 
16415d6e96efSStefan Hajnoczi     /* Acquire AioContext now so any threads operating on old_bs stop */
16425d6e96efSStefan Hajnoczi     state->aio_context = bdrv_get_aio_context(state->old_bs);
16435d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
1644da763e83SFam Zheng     bdrv_drained_begin(state->old_bs);
16455d6e96efSStefan Hajnoczi 
1646ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_inserted(state->old_bs)) {
1647c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
16489b9877eeSWenchao Xia         return;
16499b9877eeSWenchao Xia     }
16509b9877eeSWenchao Xia 
16513718d8abSFam Zheng     if (bdrv_op_is_blocked(state->old_bs,
16523718d8abSFam Zheng                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
16539b9877eeSWenchao Xia         return;
16549b9877eeSWenchao Xia     }
16559b9877eeSWenchao Xia 
1656ba5d6ab6SStefan Hajnoczi     if (!bdrv_is_read_only(state->old_bs)) {
1657ba5d6ab6SStefan Hajnoczi         if (bdrv_flush(state->old_bs)) {
1658c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_IO_ERROR);
16599b9877eeSWenchao Xia             return;
16609b9877eeSWenchao Xia         }
16619b9877eeSWenchao Xia     }
16629b9877eeSWenchao Xia 
1663212a5a8fSBenoît Canet     if (!bdrv_is_first_non_filter(state->old_bs)) {
1664c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1665f6186f49SBenoît Canet         return;
1666f6186f49SBenoît Canet     }
1667f6186f49SBenoît Canet 
166843de7e2dSAlberto Garcia     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
166943de7e2dSAlberto Garcia         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
167043de7e2dSAlberto Garcia         const char *format = s->has_format ? s->format : "qcow2";
167143de7e2dSAlberto Garcia         enum NewImageMode mode;
167243de7e2dSAlberto Garcia         const char *snapshot_node_name =
167343de7e2dSAlberto Garcia             s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
167443de7e2dSAlberto Garcia 
167543de7e2dSAlberto Garcia         if (node_name && !snapshot_node_name) {
167643de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name missing");
167743de7e2dSAlberto Garcia             return;
167843de7e2dSAlberto Garcia         }
167943de7e2dSAlberto Garcia 
168043de7e2dSAlberto Garcia         if (snapshot_node_name &&
168143de7e2dSAlberto Garcia             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
168243de7e2dSAlberto Garcia             error_setg(errp, "New snapshot node name already in use");
168343de7e2dSAlberto Garcia             return;
168443de7e2dSAlberto Garcia         }
168543de7e2dSAlberto Garcia 
1686ba5d6ab6SStefan Hajnoczi         flags = state->old_bs->open_flags;
16879b9877eeSWenchao Xia 
16889b9877eeSWenchao Xia         /* create new image w/backing file */
168943de7e2dSAlberto Garcia         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
16909b9877eeSWenchao Xia         if (mode != NEW_IMAGE_MODE_EXISTING) {
16919b9877eeSWenchao Xia             bdrv_img_create(new_image_file, format,
1692ba5d6ab6SStefan Hajnoczi                             state->old_bs->filename,
1693ba5d6ab6SStefan Hajnoczi                             state->old_bs->drv->format_name,
16949b9877eeSWenchao Xia                             NULL, -1, flags, &local_err, false);
169584d18f06SMarkus Armbruster             if (local_err) {
16969b9877eeSWenchao Xia                 error_propagate(errp, local_err);
16979b9877eeSWenchao Xia                 return;
16989b9877eeSWenchao Xia             }
16999b9877eeSWenchao Xia         }
17009b9877eeSWenchao Xia 
17010901f67eSBenoît Canet         options = qdict_new();
170243de7e2dSAlberto Garcia         if (s->has_snapshot_node_name) {
17030901f67eSBenoît Canet             qdict_put(options, "node-name",
17040901f67eSBenoît Canet                       qstring_from_str(snapshot_node_name));
17050901f67eSBenoît Canet         }
1706e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
17070901f67eSBenoît Canet 
170843de7e2dSAlberto Garcia         flags |= BDRV_O_NO_BACKING;
170943de7e2dSAlberto Garcia     }
171043de7e2dSAlberto Garcia 
1711f67503e5SMax Reitz     assert(state->new_bs == NULL);
171243de7e2dSAlberto Garcia     ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
171343de7e2dSAlberto Garcia                     flags, errp);
1714f67503e5SMax Reitz     /* We will manually add the backing_hd field to the bs later */
17159b9877eeSWenchao Xia     if (ret != 0) {
171643de7e2dSAlberto Garcia         return;
171743de7e2dSAlberto Garcia     }
171843de7e2dSAlberto Garcia 
171943de7e2dSAlberto Garcia     if (state->new_bs->blk != NULL) {
172043de7e2dSAlberto Garcia         error_setg(errp, "The snapshot is already in use by %s",
172143de7e2dSAlberto Garcia                    blk_name(state->new_bs->blk));
172243de7e2dSAlberto Garcia         return;
172343de7e2dSAlberto Garcia     }
172443de7e2dSAlberto Garcia 
172543de7e2dSAlberto Garcia     if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
172643de7e2dSAlberto Garcia                            errp)) {
172743de7e2dSAlberto Garcia         return;
172843de7e2dSAlberto Garcia     }
172943de7e2dSAlberto Garcia 
173043de7e2dSAlberto Garcia     if (state->new_bs->backing != NULL) {
173143de7e2dSAlberto Garcia         error_setg(errp, "The snapshot already has a backing image");
173208b24cfeSAlberto Garcia         return;
173308b24cfeSAlberto Garcia     }
173408b24cfeSAlberto Garcia 
173508b24cfeSAlberto Garcia     if (!state->new_bs->drv->supports_backing) {
173608b24cfeSAlberto Garcia         error_setg(errp, "The snapshot does not support backing images");
17379b9877eeSWenchao Xia     }
17389b9877eeSWenchao Xia }
17399b9877eeSWenchao Xia 
174050f43f0fSJohn Snow static void external_snapshot_commit(BlkActionState *common)
17413b0047e8SWenchao Xia {
1742ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1743ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1744ba0c86a3SWenchao Xia 
17455d6e96efSStefan Hajnoczi     bdrv_set_aio_context(state->new_bs, state->aio_context);
17465d6e96efSStefan Hajnoczi 
1747ba5d6ab6SStefan Hajnoczi     /* This removes our old bs and adds the new bs */
1748ba5d6ab6SStefan Hajnoczi     bdrv_append(state->new_bs, state->old_bs);
17493b0047e8SWenchao Xia     /* We don't need (or want) to use the transactional
17503b0047e8SWenchao Xia      * bdrv_reopen_multiple() across all the entries at once, because we
17513b0047e8SWenchao Xia      * don't want to abort all of them if one of them fails the reopen */
1752dd62f1caSKevin Wolf     bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
17533b0047e8SWenchao Xia                 NULL);
17543b0047e8SWenchao Xia }
17553b0047e8SWenchao Xia 
175650f43f0fSJohn Snow static void external_snapshot_abort(BlkActionState *common)
175796b86bf7SWenchao Xia {
1758ba5d6ab6SStefan Hajnoczi     ExternalSnapshotState *state =
1759ba5d6ab6SStefan Hajnoczi                              DO_UPCAST(ExternalSnapshotState, common, common);
1760ba5d6ab6SStefan Hajnoczi     if (state->new_bs) {
17614f6fd349SFam Zheng         bdrv_unref(state->new_bs);
176296b86bf7SWenchao Xia     }
1763da763e83SFam Zheng }
1764da763e83SFam Zheng 
176550f43f0fSJohn Snow static void external_snapshot_clean(BlkActionState *common)
1766da763e83SFam Zheng {
1767da763e83SFam Zheng     ExternalSnapshotState *state =
1768da763e83SFam Zheng                              DO_UPCAST(ExternalSnapshotState, common, common);
17695d6e96efSStefan Hajnoczi     if (state->aio_context) {
1770da763e83SFam Zheng         bdrv_drained_end(state->old_bs);
17715d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
17725d6e96efSStefan Hajnoczi     }
177396b86bf7SWenchao Xia }
177496b86bf7SWenchao Xia 
17753037f364SStefan Hajnoczi typedef struct DriveBackupState {
177650f43f0fSJohn Snow     BlkActionState common;
17773037f364SStefan Hajnoczi     BlockDriverState *bs;
17785d6e96efSStefan Hajnoczi     AioContext *aio_context;
17793037f364SStefan Hajnoczi     BlockJob *job;
17803037f364SStefan Hajnoczi } DriveBackupState;
17813037f364SStefan Hajnoczi 
178278f51fdeSJohn Snow static void do_drive_backup(const char *device, const char *target,
178378f51fdeSJohn Snow                             bool has_format, const char *format,
178478f51fdeSJohn Snow                             enum MirrorSyncMode sync,
178578f51fdeSJohn Snow                             bool has_mode, enum NewImageMode mode,
178678f51fdeSJohn Snow                             bool has_speed, int64_t speed,
178778f51fdeSJohn Snow                             bool has_bitmap, const char *bitmap,
178878f51fdeSJohn Snow                             bool has_on_source_error,
178978f51fdeSJohn Snow                             BlockdevOnError on_source_error,
179078f51fdeSJohn Snow                             bool has_on_target_error,
179178f51fdeSJohn Snow                             BlockdevOnError on_target_error,
179278f51fdeSJohn Snow                             BlockJobTxn *txn, Error **errp);
179378f51fdeSJohn Snow 
179450f43f0fSJohn Snow static void drive_backup_prepare(BlkActionState *common, Error **errp)
17953037f364SStefan Hajnoczi {
17963037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1797a0e8544cSFam Zheng     BlockBackend *blk;
17983037f364SStefan Hajnoczi     DriveBackup *backup;
17993037f364SStefan Hajnoczi     Error *local_err = NULL;
18003037f364SStefan Hajnoczi 
18016a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
18026a8f9661SEric Blake     backup = common->action->u.drive_backup;
18033037f364SStefan Hajnoczi 
1804a0e8544cSFam Zheng     blk = blk_by_name(backup->device);
1805a0e8544cSFam Zheng     if (!blk) {
180675158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
180775158ebbSMarkus Armbruster                   "Device '%s' not found", backup->device);
18085d6e96efSStefan Hajnoczi         return;
18095d6e96efSStefan Hajnoczi     }
18105d6e96efSStefan Hajnoczi 
18111fdd4b7bSFam Zheng     if (!blk_is_available(blk)) {
18121fdd4b7bSFam Zheng         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
18131fdd4b7bSFam Zheng         return;
18141fdd4b7bSFam Zheng     }
18151fdd4b7bSFam Zheng 
18165d6e96efSStefan Hajnoczi     /* AioContext is released in .clean() */
18175433c24fSMax Reitz     state->aio_context = blk_get_aio_context(blk);
18185d6e96efSStefan Hajnoczi     aio_context_acquire(state->aio_context);
18191fdd4b7bSFam Zheng     bdrv_drained_begin(blk_bs(blk));
18201fdd4b7bSFam Zheng     state->bs = blk_bs(blk);
18215d6e96efSStefan Hajnoczi 
182278f51fdeSJohn Snow     do_drive_backup(backup->device, backup->target,
18233037f364SStefan Hajnoczi                     backup->has_format, backup->format,
1824b53169eaSStefan Hajnoczi                     backup->sync,
18253037f364SStefan Hajnoczi                     backup->has_mode, backup->mode,
18263037f364SStefan Hajnoczi                     backup->has_speed, backup->speed,
1827d58d8453SJohn Snow                     backup->has_bitmap, backup->bitmap,
18283037f364SStefan Hajnoczi                     backup->has_on_source_error, backup->on_source_error,
18293037f364SStefan Hajnoczi                     backup->has_on_target_error, backup->on_target_error,
183094d16a64SJohn Snow                     common->block_job_txn, &local_err);
183184d18f06SMarkus Armbruster     if (local_err) {
18323037f364SStefan Hajnoczi         error_propagate(errp, local_err);
18333037f364SStefan Hajnoczi         return;
18343037f364SStefan Hajnoczi     }
18353037f364SStefan Hajnoczi 
18363037f364SStefan Hajnoczi     state->job = state->bs->job;
18373037f364SStefan Hajnoczi }
18383037f364SStefan Hajnoczi 
183950f43f0fSJohn Snow static void drive_backup_abort(BlkActionState *common)
18403037f364SStefan Hajnoczi {
18413037f364SStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
18423037f364SStefan Hajnoczi     BlockDriverState *bs = state->bs;
18433037f364SStefan Hajnoczi 
18443037f364SStefan Hajnoczi     /* Only cancel if it's the job we started */
18453037f364SStefan Hajnoczi     if (bs && bs->job && bs->job == state->job) {
18463037f364SStefan Hajnoczi         block_job_cancel_sync(bs->job);
18473037f364SStefan Hajnoczi     }
18483037f364SStefan Hajnoczi }
18493037f364SStefan Hajnoczi 
185050f43f0fSJohn Snow static void drive_backup_clean(BlkActionState *common)
18515d6e96efSStefan Hajnoczi {
18525d6e96efSStefan Hajnoczi     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
18535d6e96efSStefan Hajnoczi 
18545d6e96efSStefan Hajnoczi     if (state->aio_context) {
18551fdd4b7bSFam Zheng         bdrv_drained_end(state->bs);
18565d6e96efSStefan Hajnoczi         aio_context_release(state->aio_context);
18575d6e96efSStefan Hajnoczi     }
18585d6e96efSStefan Hajnoczi }
18595d6e96efSStefan Hajnoczi 
1860bd8baecdSFam Zheng typedef struct BlockdevBackupState {
186150f43f0fSJohn Snow     BlkActionState common;
1862bd8baecdSFam Zheng     BlockDriverState *bs;
1863bd8baecdSFam Zheng     BlockJob *job;
1864bd8baecdSFam Zheng     AioContext *aio_context;
1865bd8baecdSFam Zheng } BlockdevBackupState;
1866bd8baecdSFam Zheng 
186778f51fdeSJohn Snow static void do_blockdev_backup(const char *device, const char *target,
186878f51fdeSJohn Snow                                enum MirrorSyncMode sync,
186978f51fdeSJohn Snow                                bool has_speed, int64_t speed,
187078f51fdeSJohn Snow                                bool has_on_source_error,
187178f51fdeSJohn Snow                                BlockdevOnError on_source_error,
187278f51fdeSJohn Snow                                bool has_on_target_error,
187378f51fdeSJohn Snow                                BlockdevOnError on_target_error,
187478f51fdeSJohn Snow                                BlockJobTxn *txn, Error **errp);
187578f51fdeSJohn Snow 
187650f43f0fSJohn Snow static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1877bd8baecdSFam Zheng {
1878bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1879bd8baecdSFam Zheng     BlockdevBackup *backup;
18805433c24fSMax Reitz     BlockBackend *blk, *target;
1881bd8baecdSFam Zheng     Error *local_err = NULL;
1882bd8baecdSFam Zheng 
18836a8f9661SEric Blake     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
18846a8f9661SEric Blake     backup = common->action->u.blockdev_backup;
1885bd8baecdSFam Zheng 
1886a0e8544cSFam Zheng     blk = blk_by_name(backup->device);
1887a0e8544cSFam Zheng     if (!blk) {
18885b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", backup->device);
1889bd8baecdSFam Zheng         return;
1890bd8baecdSFam Zheng     }
1891bd8baecdSFam Zheng 
1892ff52bf36SFam Zheng     if (!blk_is_available(blk)) {
1893ff52bf36SFam Zheng         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1894ff52bf36SFam Zheng         return;
1895ff52bf36SFam Zheng     }
1896ff52bf36SFam Zheng 
18975433c24fSMax Reitz     target = blk_by_name(backup->target);
18985433c24fSMax Reitz     if (!target) {
18995b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", backup->target);
1900bd8baecdSFam Zheng         return;
1901bd8baecdSFam Zheng     }
1902bd8baecdSFam Zheng 
1903bd8baecdSFam Zheng     /* AioContext is released in .clean() */
19045433c24fSMax Reitz     state->aio_context = blk_get_aio_context(blk);
19055433c24fSMax Reitz     if (state->aio_context != blk_get_aio_context(target)) {
1906bd8baecdSFam Zheng         state->aio_context = NULL;
1907bd8baecdSFam Zheng         error_setg(errp, "Backup between two IO threads is not implemented");
1908bd8baecdSFam Zheng         return;
1909bd8baecdSFam Zheng     }
1910bd8baecdSFam Zheng     aio_context_acquire(state->aio_context);
1911ff52bf36SFam Zheng     state->bs = blk_bs(blk);
1912ff52bf36SFam Zheng     bdrv_drained_begin(state->bs);
1913bd8baecdSFam Zheng 
191478f51fdeSJohn Snow     do_blockdev_backup(backup->device, backup->target,
1915bd8baecdSFam Zheng                        backup->sync,
1916bd8baecdSFam Zheng                        backup->has_speed, backup->speed,
1917bd8baecdSFam Zheng                        backup->has_on_source_error, backup->on_source_error,
1918bd8baecdSFam Zheng                        backup->has_on_target_error, backup->on_target_error,
191994d16a64SJohn Snow                        common->block_job_txn, &local_err);
1920bd8baecdSFam Zheng     if (local_err) {
1921bd8baecdSFam Zheng         error_propagate(errp, local_err);
1922bd8baecdSFam Zheng         return;
1923bd8baecdSFam Zheng     }
1924bd8baecdSFam Zheng 
1925bd8baecdSFam Zheng     state->job = state->bs->job;
1926bd8baecdSFam Zheng }
1927bd8baecdSFam Zheng 
192850f43f0fSJohn Snow static void blockdev_backup_abort(BlkActionState *common)
1929bd8baecdSFam Zheng {
1930bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1931bd8baecdSFam Zheng     BlockDriverState *bs = state->bs;
1932bd8baecdSFam Zheng 
1933bd8baecdSFam Zheng     /* Only cancel if it's the job we started */
1934bd8baecdSFam Zheng     if (bs && bs->job && bs->job == state->job) {
1935bd8baecdSFam Zheng         block_job_cancel_sync(bs->job);
1936bd8baecdSFam Zheng     }
1937bd8baecdSFam Zheng }
1938bd8baecdSFam Zheng 
193950f43f0fSJohn Snow static void blockdev_backup_clean(BlkActionState *common)
1940bd8baecdSFam Zheng {
1941bd8baecdSFam Zheng     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1942bd8baecdSFam Zheng 
1943bd8baecdSFam Zheng     if (state->aio_context) {
1944ff52bf36SFam Zheng         bdrv_drained_end(state->bs);
1945bd8baecdSFam Zheng         aio_context_release(state->aio_context);
1946bd8baecdSFam Zheng     }
1947bd8baecdSFam Zheng }
1948bd8baecdSFam Zheng 
1949df9a681dSFam Zheng typedef struct BlockDirtyBitmapState {
195050f43f0fSJohn Snow     BlkActionState common;
1951df9a681dSFam Zheng     BdrvDirtyBitmap *bitmap;
1952df9a681dSFam Zheng     BlockDriverState *bs;
1953df9a681dSFam Zheng     AioContext *aio_context;
1954df9a681dSFam Zheng     HBitmap *backup;
1955df9a681dSFam Zheng     bool prepared;
1956df9a681dSFam Zheng } BlockDirtyBitmapState;
1957df9a681dSFam Zheng 
195850f43f0fSJohn Snow static void block_dirty_bitmap_add_prepare(BlkActionState *common,
1959df9a681dSFam Zheng                                            Error **errp)
1960df9a681dSFam Zheng {
1961df9a681dSFam Zheng     Error *local_err = NULL;
1962df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
1963df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1964df9a681dSFam Zheng                                              common, common);
1965df9a681dSFam Zheng 
196694d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
196794d16a64SJohn Snow         return;
196894d16a64SJohn Snow     }
196994d16a64SJohn Snow 
197050f43f0fSJohn Snow     action = common->action->u.block_dirty_bitmap_add;
1971df9a681dSFam Zheng     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1972df9a681dSFam Zheng     qmp_block_dirty_bitmap_add(action->node, action->name,
1973df9a681dSFam Zheng                                action->has_granularity, action->granularity,
1974df9a681dSFam Zheng                                &local_err);
1975df9a681dSFam Zheng 
1976df9a681dSFam Zheng     if (!local_err) {
1977df9a681dSFam Zheng         state->prepared = true;
1978df9a681dSFam Zheng     } else {
1979df9a681dSFam Zheng         error_propagate(errp, local_err);
1980df9a681dSFam Zheng     }
1981df9a681dSFam Zheng }
1982df9a681dSFam Zheng 
198350f43f0fSJohn Snow static void block_dirty_bitmap_add_abort(BlkActionState *common)
1984df9a681dSFam Zheng {
1985df9a681dSFam Zheng     BlockDirtyBitmapAdd *action;
1986df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1987df9a681dSFam Zheng                                              common, common);
1988df9a681dSFam Zheng 
198950f43f0fSJohn Snow     action = common->action->u.block_dirty_bitmap_add;
1990df9a681dSFam Zheng     /* Should not be able to fail: IF the bitmap was added via .prepare(),
1991df9a681dSFam Zheng      * then the node reference and bitmap name must have been valid.
1992df9a681dSFam Zheng      */
1993df9a681dSFam Zheng     if (state->prepared) {
1994df9a681dSFam Zheng         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
1995df9a681dSFam Zheng     }
1996df9a681dSFam Zheng }
1997df9a681dSFam Zheng 
199850f43f0fSJohn Snow static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
1999df9a681dSFam Zheng                                              Error **errp)
2000df9a681dSFam Zheng {
2001df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2002df9a681dSFam Zheng                                              common, common);
2003df9a681dSFam Zheng     BlockDirtyBitmap *action;
2004df9a681dSFam Zheng 
200594d16a64SJohn Snow     if (action_check_completion_mode(common, errp) < 0) {
200694d16a64SJohn Snow         return;
200794d16a64SJohn Snow     }
200894d16a64SJohn Snow 
200950f43f0fSJohn Snow     action = common->action->u.block_dirty_bitmap_clear;
2010df9a681dSFam Zheng     state->bitmap = block_dirty_bitmap_lookup(action->node,
2011df9a681dSFam Zheng                                               action->name,
2012df9a681dSFam Zheng                                               &state->bs,
2013df9a681dSFam Zheng                                               &state->aio_context,
2014df9a681dSFam Zheng                                               errp);
2015df9a681dSFam Zheng     if (!state->bitmap) {
2016df9a681dSFam Zheng         return;
2017df9a681dSFam Zheng     }
2018df9a681dSFam Zheng 
2019df9a681dSFam Zheng     if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2020df9a681dSFam Zheng         error_setg(errp, "Cannot modify a frozen bitmap");
2021df9a681dSFam Zheng         return;
2022df9a681dSFam Zheng     } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2023df9a681dSFam Zheng         error_setg(errp, "Cannot clear a disabled bitmap");
2024df9a681dSFam Zheng         return;
2025df9a681dSFam Zheng     }
2026df9a681dSFam Zheng 
2027df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2028df9a681dSFam Zheng     /* AioContext is released in .clean() */
2029df9a681dSFam Zheng }
2030df9a681dSFam Zheng 
203150f43f0fSJohn Snow static void block_dirty_bitmap_clear_abort(BlkActionState *common)
2032df9a681dSFam Zheng {
2033df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2034df9a681dSFam Zheng                                              common, common);
2035df9a681dSFam Zheng 
2036df9a681dSFam Zheng     bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2037df9a681dSFam Zheng }
2038df9a681dSFam Zheng 
203950f43f0fSJohn Snow static void block_dirty_bitmap_clear_commit(BlkActionState *common)
2040df9a681dSFam Zheng {
2041df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2042df9a681dSFam Zheng                                              common, common);
2043df9a681dSFam Zheng 
2044df9a681dSFam Zheng     hbitmap_free(state->backup);
2045df9a681dSFam Zheng }
2046df9a681dSFam Zheng 
204750f43f0fSJohn Snow static void block_dirty_bitmap_clear_clean(BlkActionState *common)
2048df9a681dSFam Zheng {
2049df9a681dSFam Zheng     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2050df9a681dSFam Zheng                                              common, common);
2051df9a681dSFam Zheng 
2052df9a681dSFam Zheng     if (state->aio_context) {
2053df9a681dSFam Zheng         aio_context_release(state->aio_context);
2054df9a681dSFam Zheng     }
2055df9a681dSFam Zheng }
2056df9a681dSFam Zheng 
205750f43f0fSJohn Snow static void abort_prepare(BlkActionState *common, Error **errp)
205878b18b78SStefan Hajnoczi {
205978b18b78SStefan Hajnoczi     error_setg(errp, "Transaction aborted using Abort action");
206078b18b78SStefan Hajnoczi }
206178b18b78SStefan Hajnoczi 
206250f43f0fSJohn Snow static void abort_commit(BlkActionState *common)
206378b18b78SStefan Hajnoczi {
2064dfc6f865SStefan Weil     g_assert_not_reached(); /* this action never succeeds */
206578b18b78SStefan Hajnoczi }
206678b18b78SStefan Hajnoczi 
206750f43f0fSJohn Snow static const BlkActionOps actions[] = {
206843de7e2dSAlberto Garcia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
206943de7e2dSAlberto Garcia         .instance_size = sizeof(ExternalSnapshotState),
207043de7e2dSAlberto Garcia         .prepare  = external_snapshot_prepare,
207143de7e2dSAlberto Garcia         .commit   = external_snapshot_commit,
207243de7e2dSAlberto Garcia         .abort = external_snapshot_abort,
207343de7e2dSAlberto Garcia     },
2074c8a83e85SKevin Wolf     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2075ba5d6ab6SStefan Hajnoczi         .instance_size = sizeof(ExternalSnapshotState),
2076ba0c86a3SWenchao Xia         .prepare  = external_snapshot_prepare,
2077ba0c86a3SWenchao Xia         .commit   = external_snapshot_commit,
2078ba0c86a3SWenchao Xia         .abort = external_snapshot_abort,
2079da763e83SFam Zheng         .clean = external_snapshot_clean,
2080ba0c86a3SWenchao Xia     },
20813037f364SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
20823037f364SStefan Hajnoczi         .instance_size = sizeof(DriveBackupState),
20833037f364SStefan Hajnoczi         .prepare = drive_backup_prepare,
20843037f364SStefan Hajnoczi         .abort = drive_backup_abort,
20855d6e96efSStefan Hajnoczi         .clean = drive_backup_clean,
20863037f364SStefan Hajnoczi     },
2087bd8baecdSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2088bd8baecdSFam Zheng         .instance_size = sizeof(BlockdevBackupState),
2089bd8baecdSFam Zheng         .prepare = blockdev_backup_prepare,
2090bd8baecdSFam Zheng         .abort = blockdev_backup_abort,
2091bd8baecdSFam Zheng         .clean = blockdev_backup_clean,
2092bd8baecdSFam Zheng     },
209378b18b78SStefan Hajnoczi     [TRANSACTION_ACTION_KIND_ABORT] = {
209450f43f0fSJohn Snow         .instance_size = sizeof(BlkActionState),
209578b18b78SStefan Hajnoczi         .prepare = abort_prepare,
209678b18b78SStefan Hajnoczi         .commit = abort_commit,
209778b18b78SStefan Hajnoczi     },
2098bbe86010SWenchao Xia     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2099bbe86010SWenchao Xia         .instance_size = sizeof(InternalSnapshotState),
2100bbe86010SWenchao Xia         .prepare  = internal_snapshot_prepare,
2101bbe86010SWenchao Xia         .abort = internal_snapshot_abort,
21025d6e96efSStefan Hajnoczi         .clean = internal_snapshot_clean,
2103bbe86010SWenchao Xia     },
2104df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2105df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2106df9a681dSFam Zheng         .prepare = block_dirty_bitmap_add_prepare,
2107df9a681dSFam Zheng         .abort = block_dirty_bitmap_add_abort,
2108df9a681dSFam Zheng     },
2109df9a681dSFam Zheng     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2110df9a681dSFam Zheng         .instance_size = sizeof(BlockDirtyBitmapState),
2111df9a681dSFam Zheng         .prepare = block_dirty_bitmap_clear_prepare,
2112df9a681dSFam Zheng         .commit = block_dirty_bitmap_clear_commit,
2113df9a681dSFam Zheng         .abort = block_dirty_bitmap_clear_abort,
2114df9a681dSFam Zheng         .clean = block_dirty_bitmap_clear_clean,
2115df9a681dSFam Zheng     }
2116ba0c86a3SWenchao Xia };
2117ba0c86a3SWenchao Xia 
211894d16a64SJohn Snow /**
211994d16a64SJohn Snow  * Allocate a TransactionProperties structure if necessary, and fill
212094d16a64SJohn Snow  * that structure with desired defaults if they are unset.
212194d16a64SJohn Snow  */
212294d16a64SJohn Snow static TransactionProperties *get_transaction_properties(
212394d16a64SJohn Snow     TransactionProperties *props)
212494d16a64SJohn Snow {
212594d16a64SJohn Snow     if (!props) {
212694d16a64SJohn Snow         props = g_new0(TransactionProperties, 1);
212794d16a64SJohn Snow     }
212894d16a64SJohn Snow 
212994d16a64SJohn Snow     if (!props->has_completion_mode) {
213094d16a64SJohn Snow         props->has_completion_mode = true;
213194d16a64SJohn Snow         props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
213294d16a64SJohn Snow     }
213394d16a64SJohn Snow 
213494d16a64SJohn Snow     return props;
213594d16a64SJohn Snow }
213694d16a64SJohn Snow 
21378802d1fdSJeff Cody /*
2138b756b9ceSStefan Hajnoczi  * 'Atomic' group operations.  The operations are performed as a set, and if
2139b756b9ceSStefan Hajnoczi  * any fail then we roll back all operations in the group.
21408802d1fdSJeff Cody  */
214194d16a64SJohn Snow void qmp_transaction(TransactionActionList *dev_list,
214294d16a64SJohn Snow                      bool has_props,
214394d16a64SJohn Snow                      struct TransactionProperties *props,
214494d16a64SJohn Snow                      Error **errp)
21458802d1fdSJeff Cody {
2146c8a83e85SKevin Wolf     TransactionActionList *dev_entry = dev_list;
214794d16a64SJohn Snow     BlockJobTxn *block_job_txn = NULL;
214850f43f0fSJohn Snow     BlkActionState *state, *next;
214943e17041SLuiz Capitulino     Error *local_err = NULL;
21508802d1fdSJeff Cody 
215150f43f0fSJohn Snow     QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
21528802d1fdSJeff Cody     QSIMPLEQ_INIT(&snap_bdrv_states);
21538802d1fdSJeff Cody 
215494d16a64SJohn Snow     /* Does this transaction get canceled as a group on failure?
215594d16a64SJohn Snow      * If not, we don't really need to make a BlockJobTxn.
215694d16a64SJohn Snow      */
215794d16a64SJohn Snow     props = get_transaction_properties(props);
215894d16a64SJohn Snow     if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
215994d16a64SJohn Snow         block_job_txn = block_job_txn_new();
216094d16a64SJohn Snow     }
216194d16a64SJohn Snow 
2162b756b9ceSStefan Hajnoczi     /* drain all i/o before any operations */
21638802d1fdSJeff Cody     bdrv_drain_all();
21648802d1fdSJeff Cody 
2165b756b9ceSStefan Hajnoczi     /* We don't do anything in this loop that commits us to the operations */
21668802d1fdSJeff Cody     while (NULL != dev_entry) {
2167c8a83e85SKevin Wolf         TransactionAction *dev_info = NULL;
216850f43f0fSJohn Snow         const BlkActionOps *ops;
216952e7c241SPaolo Bonzini 
21708802d1fdSJeff Cody         dev_info = dev_entry->value;
21718802d1fdSJeff Cody         dev_entry = dev_entry->next;
21728802d1fdSJeff Cody 
21736a8f9661SEric Blake         assert(dev_info->type < ARRAY_SIZE(actions));
2174ba0c86a3SWenchao Xia 
21756a8f9661SEric Blake         ops = &actions[dev_info->type];
2176aa3fe714SMax Reitz         assert(ops->instance_size > 0);
2177aa3fe714SMax Reitz 
2178ba5d6ab6SStefan Hajnoczi         state = g_malloc0(ops->instance_size);
2179ba5d6ab6SStefan Hajnoczi         state->ops = ops;
2180ba5d6ab6SStefan Hajnoczi         state->action = dev_info;
218194d16a64SJohn Snow         state->block_job_txn = block_job_txn;
218294d16a64SJohn Snow         state->txn_props = props;
2183ba5d6ab6SStefan Hajnoczi         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
21848802d1fdSJeff Cody 
2185ba5d6ab6SStefan Hajnoczi         state->ops->prepare(state, &local_err);
218684d18f06SMarkus Armbruster         if (local_err) {
21879b9877eeSWenchao Xia             error_propagate(errp, local_err);
21889b9877eeSWenchao Xia             goto delete_and_fail;
21899b9877eeSWenchao Xia         }
219052e7c241SPaolo Bonzini     }
21918802d1fdSJeff Cody 
2192ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2193f9ea81e8SStefan Hajnoczi         if (state->ops->commit) {
2194ba5d6ab6SStefan Hajnoczi             state->ops->commit(state);
21958802d1fdSJeff Cody         }
2196f9ea81e8SStefan Hajnoczi     }
21978802d1fdSJeff Cody 
21988802d1fdSJeff Cody     /* success */
21998802d1fdSJeff Cody     goto exit;
22008802d1fdSJeff Cody 
22018802d1fdSJeff Cody delete_and_fail:
2202b756b9ceSStefan Hajnoczi     /* failure, and it is all-or-none; roll back all operations */
2203ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2204ba5d6ab6SStefan Hajnoczi         if (state->ops->abort) {
2205ba5d6ab6SStefan Hajnoczi             state->ops->abort(state);
2206ba0c86a3SWenchao Xia         }
22078802d1fdSJeff Cody     }
22088802d1fdSJeff Cody exit:
2209ba5d6ab6SStefan Hajnoczi     QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2210ba5d6ab6SStefan Hajnoczi         if (state->ops->clean) {
2211ba5d6ab6SStefan Hajnoczi             state->ops->clean(state);
2212ba0c86a3SWenchao Xia         }
2213ba5d6ab6SStefan Hajnoczi         g_free(state);
22148802d1fdSJeff Cody     }
221594d16a64SJohn Snow     if (!has_props) {
221694d16a64SJohn Snow         qapi_free_TransactionProperties(props);
221794d16a64SJohn Snow     }
221894d16a64SJohn Snow     block_job_txn_unref(block_job_txn);
22198802d1fdSJeff Cody }
22208802d1fdSJeff Cody 
2221c245b6a3SLuiz Capitulino void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2222666daa68SMarkus Armbruster {
222338f54bd1SMax Reitz     Error *local_err = NULL;
2224666daa68SMarkus Armbruster 
222538f54bd1SMax Reitz     qmp_blockdev_open_tray(device, has_force, force, &local_err);
222638f54bd1SMax Reitz     if (local_err) {
222738f54bd1SMax Reitz         error_propagate(errp, local_err);
2228c245b6a3SLuiz Capitulino         return;
2229666daa68SMarkus Armbruster     }
223092d48558SLuiz Capitulino 
223138f54bd1SMax Reitz     qmp_blockdev_remove_medium(device, errp);
2232666daa68SMarkus Armbruster }
2233666daa68SMarkus Armbruster 
223412d3ba82SBenoît Canet void qmp_block_passwd(bool has_device, const char *device,
223512d3ba82SBenoît Canet                       bool has_node_name, const char *node_name,
223612d3ba82SBenoît Canet                       const char *password, Error **errp)
2237666daa68SMarkus Armbruster {
223812d3ba82SBenoît Canet     Error *local_err = NULL;
2239666daa68SMarkus Armbruster     BlockDriverState *bs;
2240e3442099SStefan Hajnoczi     AioContext *aio_context;
2241666daa68SMarkus Armbruster 
224212d3ba82SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
224312d3ba82SBenoît Canet                         has_node_name ? node_name : NULL,
224412d3ba82SBenoît Canet                         &local_err);
224584d18f06SMarkus Armbruster     if (local_err) {
224612d3ba82SBenoît Canet         error_propagate(errp, local_err);
2247a4dea8a9SLuiz Capitulino         return;
2248666daa68SMarkus Armbruster     }
2249666daa68SMarkus Armbruster 
2250e3442099SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
2251e3442099SStefan Hajnoczi     aio_context_acquire(aio_context);
2252e3442099SStefan Hajnoczi 
22534d2855a3SMarkus Armbruster     bdrv_add_key(bs, password, errp);
2254666daa68SMarkus Armbruster 
2255e3442099SStefan Hajnoczi     aio_context_release(aio_context);
2256e3442099SStefan Hajnoczi }
2257e3442099SStefan Hajnoczi 
22587d8a9f71SMax Reitz void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
22597d8a9f71SMax Reitz                             Error **errp)
22607d8a9f71SMax Reitz {
22617d8a9f71SMax Reitz     BlockBackend *blk;
22627d8a9f71SMax Reitz     bool locked;
22637d8a9f71SMax Reitz 
22647d8a9f71SMax Reitz     if (!has_force) {
22657d8a9f71SMax Reitz         force = false;
22667d8a9f71SMax Reitz     }
22677d8a9f71SMax Reitz 
22687d8a9f71SMax Reitz     blk = blk_by_name(device);
22697d8a9f71SMax Reitz     if (!blk) {
22707d8a9f71SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
22717d8a9f71SMax Reitz                   "Device '%s' not found", device);
22727d8a9f71SMax Reitz         return;
22737d8a9f71SMax Reitz     }
22747d8a9f71SMax Reitz 
22757d8a9f71SMax Reitz     if (!blk_dev_has_removable_media(blk)) {
22767d8a9f71SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
22777d8a9f71SMax Reitz         return;
22787d8a9f71SMax Reitz     }
22797d8a9f71SMax Reitz 
22807d8a9f71SMax Reitz     if (blk_dev_is_tray_open(blk)) {
22817d8a9f71SMax Reitz         return;
22827d8a9f71SMax Reitz     }
22837d8a9f71SMax Reitz 
22847d8a9f71SMax Reitz     locked = blk_dev_is_medium_locked(blk);
22857d8a9f71SMax Reitz     if (locked) {
22867d8a9f71SMax Reitz         blk_dev_eject_request(blk, force);
22877d8a9f71SMax Reitz     }
22887d8a9f71SMax Reitz 
22897d8a9f71SMax Reitz     if (!locked || force) {
22907d8a9f71SMax Reitz         blk_dev_change_media_cb(blk, false);
22917d8a9f71SMax Reitz     }
22927d8a9f71SMax Reitz }
22937d8a9f71SMax Reitz 
2294abaaf59dSMax Reitz void qmp_blockdev_close_tray(const char *device, Error **errp)
2295abaaf59dSMax Reitz {
2296abaaf59dSMax Reitz     BlockBackend *blk;
2297abaaf59dSMax Reitz 
2298abaaf59dSMax Reitz     blk = blk_by_name(device);
2299abaaf59dSMax Reitz     if (!blk) {
2300abaaf59dSMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2301abaaf59dSMax Reitz                   "Device '%s' not found", device);
2302abaaf59dSMax Reitz         return;
2303abaaf59dSMax Reitz     }
2304abaaf59dSMax Reitz 
2305abaaf59dSMax Reitz     if (!blk_dev_has_removable_media(blk)) {
2306abaaf59dSMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
2307abaaf59dSMax Reitz         return;
2308abaaf59dSMax Reitz     }
2309abaaf59dSMax Reitz 
2310abaaf59dSMax Reitz     if (!blk_dev_is_tray_open(blk)) {
2311abaaf59dSMax Reitz         return;
2312abaaf59dSMax Reitz     }
2313abaaf59dSMax Reitz 
2314abaaf59dSMax Reitz     blk_dev_change_media_cb(blk, true);
2315abaaf59dSMax Reitz }
2316abaaf59dSMax Reitz 
23172814f672SMax Reitz void qmp_blockdev_remove_medium(const char *device, Error **errp)
23182814f672SMax Reitz {
23192814f672SMax Reitz     BlockBackend *blk;
23202814f672SMax Reitz     BlockDriverState *bs;
23212814f672SMax Reitz     AioContext *aio_context;
23222814f672SMax Reitz     bool has_device;
23232814f672SMax Reitz 
23242814f672SMax Reitz     blk = blk_by_name(device);
23252814f672SMax Reitz     if (!blk) {
23262814f672SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
23272814f672SMax Reitz                   "Device '%s' not found", device);
23282814f672SMax Reitz         return;
23292814f672SMax Reitz     }
23302814f672SMax Reitz 
23312814f672SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
23322814f672SMax Reitz     has_device = blk_get_attached_dev(blk);
23332814f672SMax Reitz 
23342814f672SMax Reitz     if (has_device && !blk_dev_has_removable_media(blk)) {
23352814f672SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
23362814f672SMax Reitz         return;
23372814f672SMax Reitz     }
23382814f672SMax Reitz 
23392814f672SMax Reitz     if (has_device && !blk_dev_is_tray_open(blk)) {
23402814f672SMax Reitz         error_setg(errp, "Tray of device '%s' is not open", device);
23412814f672SMax Reitz         return;
23422814f672SMax Reitz     }
23432814f672SMax Reitz 
23442814f672SMax Reitz     bs = blk_bs(blk);
23452814f672SMax Reitz     if (!bs) {
23462814f672SMax Reitz         return;
23472814f672SMax Reitz     }
23482814f672SMax Reitz 
23492814f672SMax Reitz     aio_context = bdrv_get_aio_context(bs);
23502814f672SMax Reitz     aio_context_acquire(aio_context);
23512814f672SMax Reitz 
23522814f672SMax Reitz     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
23532814f672SMax Reitz         goto out;
23542814f672SMax Reitz     }
23552814f672SMax Reitz 
23562814f672SMax Reitz     /* This follows the convention established by bdrv_make_anon() */
23572814f672SMax Reitz     if (bs->device_list.tqe_prev) {
23582814f672SMax Reitz         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
23592814f672SMax Reitz         bs->device_list.tqe_prev = NULL;
23602814f672SMax Reitz     }
23612814f672SMax Reitz 
23622814f672SMax Reitz     blk_remove_bs(blk);
23632814f672SMax Reitz 
23642814f672SMax Reitz out:
23652814f672SMax Reitz     aio_context_release(aio_context);
23662814f672SMax Reitz }
23672814f672SMax Reitz 
2368d1299882SMax Reitz static void qmp_blockdev_insert_anon_medium(const char *device,
2369d1299882SMax Reitz                                             BlockDriverState *bs, Error **errp)
2370d1299882SMax Reitz {
2371d1299882SMax Reitz     BlockBackend *blk;
2372d1299882SMax Reitz     bool has_device;
2373d1299882SMax Reitz 
2374d1299882SMax Reitz     blk = blk_by_name(device);
2375d1299882SMax Reitz     if (!blk) {
2376d1299882SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2377d1299882SMax Reitz                   "Device '%s' not found", device);
2378d1299882SMax Reitz         return;
2379d1299882SMax Reitz     }
2380d1299882SMax Reitz 
2381d1299882SMax Reitz     /* For BBs without a device, we can exchange the BDS tree at will */
2382d1299882SMax Reitz     has_device = blk_get_attached_dev(blk);
2383d1299882SMax Reitz 
2384d1299882SMax Reitz     if (has_device && !blk_dev_has_removable_media(blk)) {
2385d1299882SMax Reitz         error_setg(errp, "Device '%s' is not removable", device);
2386d1299882SMax Reitz         return;
2387d1299882SMax Reitz     }
2388d1299882SMax Reitz 
2389d1299882SMax Reitz     if (has_device && !blk_dev_is_tray_open(blk)) {
2390d1299882SMax Reitz         error_setg(errp, "Tray of device '%s' is not open", device);
2391d1299882SMax Reitz         return;
2392d1299882SMax Reitz     }
2393d1299882SMax Reitz 
2394d1299882SMax Reitz     if (blk_bs(blk)) {
2395d1299882SMax Reitz         error_setg(errp, "There already is a medium in device '%s'", device);
2396d1299882SMax Reitz         return;
2397d1299882SMax Reitz     }
2398d1299882SMax Reitz 
2399d1299882SMax Reitz     blk_insert_bs(blk, bs);
2400d1299882SMax Reitz 
2401d1299882SMax Reitz     QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
2402d1299882SMax Reitz }
2403d1299882SMax Reitz 
2404d1299882SMax Reitz void qmp_blockdev_insert_medium(const char *device, const char *node_name,
2405d1299882SMax Reitz                                 Error **errp)
2406d1299882SMax Reitz {
2407d1299882SMax Reitz     BlockDriverState *bs;
2408d1299882SMax Reitz 
2409d1299882SMax Reitz     bs = bdrv_find_node(node_name);
2410d1299882SMax Reitz     if (!bs) {
2411d1299882SMax Reitz         error_setg(errp, "Node '%s' not found", node_name);
2412d1299882SMax Reitz         return;
2413d1299882SMax Reitz     }
2414d1299882SMax Reitz 
2415d1299882SMax Reitz     if (bs->blk) {
2416d1299882SMax Reitz         error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2417d1299882SMax Reitz                    blk_name(bs->blk));
2418d1299882SMax Reitz         return;
2419d1299882SMax Reitz     }
2420d1299882SMax Reitz 
2421d1299882SMax Reitz     qmp_blockdev_insert_anon_medium(device, bs, errp);
2422d1299882SMax Reitz }
2423d1299882SMax Reitz 
242424fb4133SMax Reitz void qmp_blockdev_change_medium(const char *device, const char *filename,
242524fb4133SMax Reitz                                 bool has_format, const char *format,
242639ff43d9SMax Reitz                                 bool has_read_only,
242739ff43d9SMax Reitz                                 BlockdevChangeReadOnlyMode read_only,
242824fb4133SMax Reitz                                 Error **errp)
2429de2c6c05SMax Reitz {
2430de2c6c05SMax Reitz     BlockBackend *blk;
2431de2c6c05SMax Reitz     BlockDriverState *medium_bs = NULL;
2432de2c6c05SMax Reitz     int bdrv_flags, ret;
2433de2c6c05SMax Reitz     QDict *options = NULL;
2434de2c6c05SMax Reitz     Error *err = NULL;
2435de2c6c05SMax Reitz 
2436de2c6c05SMax Reitz     blk = blk_by_name(device);
2437de2c6c05SMax Reitz     if (!blk) {
2438de2c6c05SMax Reitz         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2439de2c6c05SMax Reitz                   "Device '%s' not found", device);
2440de2c6c05SMax Reitz         goto fail;
2441de2c6c05SMax Reitz     }
2442de2c6c05SMax Reitz 
2443de2c6c05SMax Reitz     if (blk_bs(blk)) {
2444de2c6c05SMax Reitz         blk_update_root_state(blk);
2445de2c6c05SMax Reitz     }
2446de2c6c05SMax Reitz 
2447de2c6c05SMax Reitz     bdrv_flags = blk_get_open_flags_from_root_state(blk);
2448de2c6c05SMax Reitz 
244939ff43d9SMax Reitz     if (!has_read_only) {
245039ff43d9SMax Reitz         read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
245139ff43d9SMax Reitz     }
245239ff43d9SMax Reitz 
245339ff43d9SMax Reitz     switch (read_only) {
245439ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
245539ff43d9SMax Reitz         break;
245639ff43d9SMax Reitz 
245739ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
245839ff43d9SMax Reitz         bdrv_flags &= ~BDRV_O_RDWR;
245939ff43d9SMax Reitz         break;
246039ff43d9SMax Reitz 
246139ff43d9SMax Reitz     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
246239ff43d9SMax Reitz         bdrv_flags |= BDRV_O_RDWR;
246339ff43d9SMax Reitz         break;
246439ff43d9SMax Reitz 
246539ff43d9SMax Reitz     default:
246639ff43d9SMax Reitz         abort();
246739ff43d9SMax Reitz     }
246839ff43d9SMax Reitz 
246924fb4133SMax Reitz     if (has_format) {
2470de2c6c05SMax Reitz         options = qdict_new();
2471de2c6c05SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
2472de2c6c05SMax Reitz     }
2473de2c6c05SMax Reitz 
2474de2c6c05SMax Reitz     assert(!medium_bs);
2475de2c6c05SMax Reitz     ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2476de2c6c05SMax Reitz     if (ret < 0) {
2477de2c6c05SMax Reitz         goto fail;
2478de2c6c05SMax Reitz     }
2479de2c6c05SMax Reitz 
2480de2c6c05SMax Reitz     blk_apply_root_state(blk, medium_bs);
2481de2c6c05SMax Reitz 
2482de2c6c05SMax Reitz     bdrv_add_key(medium_bs, NULL, &err);
2483de2c6c05SMax Reitz     if (err) {
2484de2c6c05SMax Reitz         error_propagate(errp, err);
2485de2c6c05SMax Reitz         goto fail;
2486de2c6c05SMax Reitz     }
2487de2c6c05SMax Reitz 
2488de2c6c05SMax Reitz     qmp_blockdev_open_tray(device, false, false, &err);
2489de2c6c05SMax Reitz     if (err) {
2490de2c6c05SMax Reitz         error_propagate(errp, err);
2491de2c6c05SMax Reitz         goto fail;
2492de2c6c05SMax Reitz     }
2493de2c6c05SMax Reitz 
2494de2c6c05SMax Reitz     qmp_blockdev_remove_medium(device, &err);
2495de2c6c05SMax Reitz     if (err) {
2496de2c6c05SMax Reitz         error_propagate(errp, err);
2497de2c6c05SMax Reitz         goto fail;
2498de2c6c05SMax Reitz     }
2499de2c6c05SMax Reitz 
2500de2c6c05SMax Reitz     qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2501de2c6c05SMax Reitz     if (err) {
2502de2c6c05SMax Reitz         error_propagate(errp, err);
2503de2c6c05SMax Reitz         goto fail;
2504de2c6c05SMax Reitz     }
2505de2c6c05SMax Reitz 
2506de2c6c05SMax Reitz     qmp_blockdev_close_tray(device, errp);
2507de2c6c05SMax Reitz 
2508de2c6c05SMax Reitz fail:
2509de2c6c05SMax Reitz     /* If the medium has been inserted, the device has its own reference, so
2510de2c6c05SMax Reitz      * ours must be relinquished; and if it has not been inserted successfully,
2511de2c6c05SMax Reitz      * the reference must be relinquished anyway */
2512de2c6c05SMax Reitz     bdrv_unref(medium_bs);
2513de2c6c05SMax Reitz }
2514de2c6c05SMax Reitz 
2515727f005eSZhi Yong Wu /* throttling disk I/O limits */
251680047da5SLuiz Capitulino void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
25173e9fab69SBenoît Canet                                int64_t bps_wr,
25183e9fab69SBenoît Canet                                int64_t iops,
25193e9fab69SBenoît Canet                                int64_t iops_rd,
25203e9fab69SBenoît Canet                                int64_t iops_wr,
25213e9fab69SBenoît Canet                                bool has_bps_max,
25223e9fab69SBenoît Canet                                int64_t bps_max,
25233e9fab69SBenoît Canet                                bool has_bps_rd_max,
25243e9fab69SBenoît Canet                                int64_t bps_rd_max,
25253e9fab69SBenoît Canet                                bool has_bps_wr_max,
25263e9fab69SBenoît Canet                                int64_t bps_wr_max,
25273e9fab69SBenoît Canet                                bool has_iops_max,
25283e9fab69SBenoît Canet                                int64_t iops_max,
25293e9fab69SBenoît Canet                                bool has_iops_rd_max,
25303e9fab69SBenoît Canet                                int64_t iops_rd_max,
25313e9fab69SBenoît Canet                                bool has_iops_wr_max,
25322024c1dfSBenoît Canet                                int64_t iops_wr_max,
25332024c1dfSBenoît Canet                                bool has_iops_size,
253476f4afb4SAlberto Garcia                                int64_t iops_size,
253576f4afb4SAlberto Garcia                                bool has_group,
253676f4afb4SAlberto Garcia                                const char *group, Error **errp)
2537727f005eSZhi Yong Wu {
2538cc0681c4SBenoît Canet     ThrottleConfig cfg;
2539727f005eSZhi Yong Wu     BlockDriverState *bs;
2540a0e8544cSFam Zheng     BlockBackend *blk;
2541b15446fdSStefan Hajnoczi     AioContext *aio_context;
2542727f005eSZhi Yong Wu 
2543a0e8544cSFam Zheng     blk = blk_by_name(device);
2544a0e8544cSFam Zheng     if (!blk) {
254575158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
254675158ebbSMarkus Armbruster                   "Device '%s' not found", device);
254780047da5SLuiz Capitulino         return;
2548727f005eSZhi Yong Wu     }
25495433c24fSMax Reitz 
25505433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
25515433c24fSMax Reitz     aio_context_acquire(aio_context);
25525433c24fSMax Reitz 
2553a0e8544cSFam Zheng     bs = blk_bs(blk);
25545433c24fSMax Reitz     if (!bs) {
25555433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
25565433c24fSMax Reitz         goto out;
25575433c24fSMax Reitz     }
2558727f005eSZhi Yong Wu 
2559cc0681c4SBenoît Canet     memset(&cfg, 0, sizeof(cfg));
2560cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2561cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;
2562cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2563727f005eSZhi Yong Wu 
2564cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2565cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;
2566cc0681c4SBenoît Canet     cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2567cc0681c4SBenoît Canet 
25683e9fab69SBenoît Canet     if (has_bps_max) {
25693e9fab69SBenoît Canet         cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
25703e9fab69SBenoît Canet     }
25713e9fab69SBenoît Canet     if (has_bps_rd_max) {
25723e9fab69SBenoît Canet         cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
25733e9fab69SBenoît Canet     }
25743e9fab69SBenoît Canet     if (has_bps_wr_max) {
25753e9fab69SBenoît Canet         cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
25763e9fab69SBenoît Canet     }
25773e9fab69SBenoît Canet     if (has_iops_max) {
25783e9fab69SBenoît Canet         cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
25793e9fab69SBenoît Canet     }
25803e9fab69SBenoît Canet     if (has_iops_rd_max) {
25813e9fab69SBenoît Canet         cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
25823e9fab69SBenoît Canet     }
25833e9fab69SBenoît Canet     if (has_iops_wr_max) {
25843e9fab69SBenoît Canet         cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
25853e9fab69SBenoît Canet     }
2586cc0681c4SBenoît Canet 
25872024c1dfSBenoît Canet     if (has_iops_size) {
25882024c1dfSBenoît Canet         cfg.op_size = iops_size;
25892024c1dfSBenoît Canet     }
2590cc0681c4SBenoît Canet 
2591cc0681c4SBenoît Canet     if (!check_throttle_config(&cfg, errp)) {
25925433c24fSMax Reitz         goto out;
2593727f005eSZhi Yong Wu     }
2594727f005eSZhi Yong Wu 
259576f4afb4SAlberto Garcia     if (throttle_enabled(&cfg)) {
259676f4afb4SAlberto Garcia         /* Enable I/O limits if they're not enabled yet, otherwise
259776f4afb4SAlberto Garcia          * just update the throttling group. */
2598a0d64a61SAlberto Garcia         if (!bs->throttle_state) {
259976f4afb4SAlberto Garcia             bdrv_io_limits_enable(bs, has_group ? group : device);
260076f4afb4SAlberto Garcia         } else if (has_group) {
260176f4afb4SAlberto Garcia             bdrv_io_limits_update_group(bs, group);
2602727f005eSZhi Yong Wu         }
260376f4afb4SAlberto Garcia         /* Set the new throttling configuration */
2604cc0681c4SBenoît Canet         bdrv_set_io_limits(bs, &cfg);
2605a0d64a61SAlberto Garcia     } else if (bs->throttle_state) {
260676f4afb4SAlberto Garcia         /* If all throttling settings are set to 0, disable I/O limits */
260776f4afb4SAlberto Garcia         bdrv_io_limits_disable(bs);
2608727f005eSZhi Yong Wu     }
2609b15446fdSStefan Hajnoczi 
26105433c24fSMax Reitz out:
2611b15446fdSStefan Hajnoczi     aio_context_release(aio_context);
2612727f005eSZhi Yong Wu }
2613727f005eSZhi Yong Wu 
2614341ebc2fSJohn Snow void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2615341ebc2fSJohn Snow                                 bool has_granularity, uint32_t granularity,
2616341ebc2fSJohn Snow                                 Error **errp)
2617341ebc2fSJohn Snow {
2618341ebc2fSJohn Snow     AioContext *aio_context;
2619341ebc2fSJohn Snow     BlockDriverState *bs;
2620341ebc2fSJohn Snow 
2621341ebc2fSJohn Snow     if (!name || name[0] == '\0') {
2622341ebc2fSJohn Snow         error_setg(errp, "Bitmap name cannot be empty");
2623341ebc2fSJohn Snow         return;
2624341ebc2fSJohn Snow     }
2625341ebc2fSJohn Snow 
2626341ebc2fSJohn Snow     bs = bdrv_lookup_bs(node, node, errp);
2627341ebc2fSJohn Snow     if (!bs) {
2628341ebc2fSJohn Snow         return;
2629341ebc2fSJohn Snow     }
2630341ebc2fSJohn Snow 
2631341ebc2fSJohn Snow     aio_context = bdrv_get_aio_context(bs);
2632341ebc2fSJohn Snow     aio_context_acquire(aio_context);
2633341ebc2fSJohn Snow 
2634341ebc2fSJohn Snow     if (has_granularity) {
2635341ebc2fSJohn Snow         if (granularity < 512 || !is_power_of_2(granularity)) {
2636341ebc2fSJohn Snow             error_setg(errp, "Granularity must be power of 2 "
2637341ebc2fSJohn Snow                              "and at least 512");
2638341ebc2fSJohn Snow             goto out;
2639341ebc2fSJohn Snow         }
2640341ebc2fSJohn Snow     } else {
2641341ebc2fSJohn Snow         /* Default to cluster size, if available: */
2642341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(bs);
2643341ebc2fSJohn Snow     }
2644341ebc2fSJohn Snow 
2645341ebc2fSJohn Snow     bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2646341ebc2fSJohn Snow 
2647341ebc2fSJohn Snow  out:
2648341ebc2fSJohn Snow     aio_context_release(aio_context);
2649341ebc2fSJohn Snow }
2650341ebc2fSJohn Snow 
2651341ebc2fSJohn Snow void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2652341ebc2fSJohn Snow                                    Error **errp)
2653341ebc2fSJohn Snow {
2654341ebc2fSJohn Snow     AioContext *aio_context;
2655341ebc2fSJohn Snow     BlockDriverState *bs;
2656341ebc2fSJohn Snow     BdrvDirtyBitmap *bitmap;
2657341ebc2fSJohn Snow 
2658341ebc2fSJohn Snow     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2659341ebc2fSJohn Snow     if (!bitmap || !bs) {
2660341ebc2fSJohn Snow         return;
2661341ebc2fSJohn Snow     }
2662341ebc2fSJohn Snow 
26639bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
26649bd2b08fSJohn Snow         error_setg(errp,
26659bd2b08fSJohn Snow                    "Bitmap '%s' is currently frozen and cannot be removed",
26669bd2b08fSJohn Snow                    name);
26679bd2b08fSJohn Snow         goto out;
26689bd2b08fSJohn Snow     }
266920dca810SJohn Snow     bdrv_dirty_bitmap_make_anon(bitmap);
2670341ebc2fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
2671341ebc2fSJohn Snow 
26729bd2b08fSJohn Snow  out:
2673341ebc2fSJohn Snow     aio_context_release(aio_context);
2674341ebc2fSJohn Snow }
2675341ebc2fSJohn Snow 
2676e74e6b78SJohn Snow /**
2677e74e6b78SJohn Snow  * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2678e74e6b78SJohn Snow  * immediately after a full backup operation.
2679e74e6b78SJohn Snow  */
2680e74e6b78SJohn Snow void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2681e74e6b78SJohn Snow                                   Error **errp)
2682e74e6b78SJohn Snow {
2683e74e6b78SJohn Snow     AioContext *aio_context;
2684e74e6b78SJohn Snow     BdrvDirtyBitmap *bitmap;
2685e74e6b78SJohn Snow     BlockDriverState *bs;
2686e74e6b78SJohn Snow 
2687e74e6b78SJohn Snow     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2688e74e6b78SJohn Snow     if (!bitmap || !bs) {
2689e74e6b78SJohn Snow         return;
2690e74e6b78SJohn Snow     }
2691e74e6b78SJohn Snow 
2692e74e6b78SJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2693e74e6b78SJohn Snow         error_setg(errp,
2694e74e6b78SJohn Snow                    "Bitmap '%s' is currently frozen and cannot be modified",
2695e74e6b78SJohn Snow                    name);
2696e74e6b78SJohn Snow         goto out;
2697e74e6b78SJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2698e74e6b78SJohn Snow         error_setg(errp,
2699e74e6b78SJohn Snow                    "Bitmap '%s' is currently disabled and cannot be cleared",
2700e74e6b78SJohn Snow                    name);
2701e74e6b78SJohn Snow         goto out;
2702e74e6b78SJohn Snow     }
2703e74e6b78SJohn Snow 
2704df9a681dSFam Zheng     bdrv_clear_dirty_bitmap(bitmap, NULL);
2705e74e6b78SJohn Snow 
2706e74e6b78SJohn Snow  out:
2707e74e6b78SJohn Snow     aio_context_release(aio_context);
2708e74e6b78SJohn Snow }
2709e74e6b78SJohn Snow 
2710072ebe6bSMarkus Armbruster void hmp_drive_del(Monitor *mon, const QDict *qdict)
27119063f814SRyan Harper {
27129063f814SRyan Harper     const char *id = qdict_get_str(qdict, "id");
27137e7d56d9SMarkus Armbruster     BlockBackend *blk;
27149063f814SRyan Harper     BlockDriverState *bs;
27158ad4202bSStefan Hajnoczi     AioContext *aio_context;
27163718d8abSFam Zheng     Error *local_err = NULL;
27179063f814SRyan Harper 
27187e7d56d9SMarkus Armbruster     blk = blk_by_name(id);
27197e7d56d9SMarkus Armbruster     if (!blk) {
2720b1422f20SMarkus Armbruster         error_report("Device '%s' not found", id);
2721072ebe6bSMarkus Armbruster         return;
27229063f814SRyan Harper     }
27238ad4202bSStefan Hajnoczi 
272426f8b3a8SMarkus Armbruster     if (!blk_legacy_dinfo(blk)) {
272548f364ddSMarkus Armbruster         error_report("Deleting device added with blockdev-add"
272648f364ddSMarkus Armbruster                      " is not supported");
2727072ebe6bSMarkus Armbruster         return;
272848f364ddSMarkus Armbruster     }
272948f364ddSMarkus Armbruster 
27305433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
27318ad4202bSStefan Hajnoczi     aio_context_acquire(aio_context);
27328ad4202bSStefan Hajnoczi 
27335433c24fSMax Reitz     bs = blk_bs(blk);
27345433c24fSMax Reitz     if (bs) {
27353718d8abSFam Zheng         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2736565f65d2SMarkus Armbruster             error_report_err(local_err);
27378ad4202bSStefan Hajnoczi             aio_context_release(aio_context);
2738072ebe6bSMarkus Armbruster             return;
27398591675fSMarcelo Tosatti         }
27409063f814SRyan Harper 
27419063f814SRyan Harper         bdrv_close(bs);
27425433c24fSMax Reitz     }
27439063f814SRyan Harper 
2744fa879d62SMarkus Armbruster     /* if we have a device attached to this BlockDriverState
2745d22b2f41SRyan Harper      * then we need to make the drive anonymous until the device
2746d22b2f41SRyan Harper      * can be removed.  If this is a drive with no device backing
2747d22b2f41SRyan Harper      * then we can just get rid of the block driver state right here.
2748d22b2f41SRyan Harper      */
2749a7f53e26SMarkus Armbruster     if (blk_get_attached_dev(blk)) {
27503e5a50d6SMarkus Armbruster         blk_hide_on_behalf_of_hmp_drive_del(blk);
2751293c51a6SStefan Hajnoczi         /* Further I/O must not pause the guest */
2752373340b2SMax Reitz         blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2753293c51a6SStefan Hajnoczi                          BLOCKDEV_ON_ERROR_REPORT);
2754d22b2f41SRyan Harper     } else {
2755b9fe8a7aSMarkus Armbruster         blk_unref(blk);
2756d22b2f41SRyan Harper     }
27579063f814SRyan Harper 
27588ad4202bSStefan Hajnoczi     aio_context_release(aio_context);
27599063f814SRyan Harper }
27606d4a2b3aSChristoph Hellwig 
27613b1dbd11SBenoît Canet void qmp_block_resize(bool has_device, const char *device,
27623b1dbd11SBenoît Canet                       bool has_node_name, const char *node_name,
27633b1dbd11SBenoît Canet                       int64_t size, Error **errp)
27646d4a2b3aSChristoph Hellwig {
27653b1dbd11SBenoît Canet     Error *local_err = NULL;
27666d4a2b3aSChristoph Hellwig     BlockDriverState *bs;
2767927e0e76SStefan Hajnoczi     AioContext *aio_context;
27688732901eSKevin Wolf     int ret;
27696d4a2b3aSChristoph Hellwig 
27703b1dbd11SBenoît Canet     bs = bdrv_lookup_bs(has_device ? device : NULL,
27713b1dbd11SBenoît Canet                         has_node_name ? node_name : NULL,
27723b1dbd11SBenoît Canet                         &local_err);
277384d18f06SMarkus Armbruster     if (local_err) {
27743b1dbd11SBenoît Canet         error_propagate(errp, local_err);
27753b1dbd11SBenoît Canet         return;
27763b1dbd11SBenoît Canet     }
27773b1dbd11SBenoît Canet 
2778927e0e76SStefan Hajnoczi     aio_context = bdrv_get_aio_context(bs);
2779927e0e76SStefan Hajnoczi     aio_context_acquire(aio_context);
2780927e0e76SStefan Hajnoczi 
27813b1dbd11SBenoît Canet     if (!bdrv_is_first_non_filter(bs)) {
2782c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2783927e0e76SStefan Hajnoczi         goto out;
27846d4a2b3aSChristoph Hellwig     }
27856d4a2b3aSChristoph Hellwig 
27866d4a2b3aSChristoph Hellwig     if (size < 0) {
2787c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2788927e0e76SStefan Hajnoczi         goto out;
27896d4a2b3aSChristoph Hellwig     }
27906d4a2b3aSChristoph Hellwig 
27919c75e168SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2792c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2793927e0e76SStefan Hajnoczi         goto out;
27949c75e168SJeff Cody     }
27959c75e168SJeff Cody 
279692b7a08dSPeter Lieven     /* complete all in-flight operations before resizing the device */
279792b7a08dSPeter Lieven     bdrv_drain_all();
279892b7a08dSPeter Lieven 
27998732901eSKevin Wolf     ret = bdrv_truncate(bs, size);
28008732901eSKevin Wolf     switch (ret) {
2801939a1cc3SStefan Hajnoczi     case 0:
2802939a1cc3SStefan Hajnoczi         break;
2803939a1cc3SStefan Hajnoczi     case -ENOMEDIUM:
2804c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2805939a1cc3SStefan Hajnoczi         break;
2806939a1cc3SStefan Hajnoczi     case -ENOTSUP:
2807c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_UNSUPPORTED);
2808939a1cc3SStefan Hajnoczi         break;
2809939a1cc3SStefan Hajnoczi     case -EACCES:
281081e5f78aSAlberto Garcia         error_setg(errp, "Device '%s' is read only", device);
2811939a1cc3SStefan Hajnoczi         break;
2812939a1cc3SStefan Hajnoczi     case -EBUSY:
2813c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_IN_USE, device);
2814939a1cc3SStefan Hajnoczi         break;
2815939a1cc3SStefan Hajnoczi     default:
28168732901eSKevin Wolf         error_setg_errno(errp, -ret, "Could not resize");
2817939a1cc3SStefan Hajnoczi         break;
28186d4a2b3aSChristoph Hellwig     }
2819927e0e76SStefan Hajnoczi 
2820927e0e76SStefan Hajnoczi out:
2821927e0e76SStefan Hajnoczi     aio_context_release(aio_context);
28226d4a2b3aSChristoph Hellwig }
282312bd451fSStefan Hajnoczi 
28249abf2dbaSJeff Cody static void block_job_cb(void *opaque, int ret)
282512bd451fSStefan Hajnoczi {
2826723c5d93SStefan Hajnoczi     /* Note that this function may be executed from another AioContext besides
2827723c5d93SStefan Hajnoczi      * the QEMU main loop.  If you need to access anything that assumes the
2828723c5d93SStefan Hajnoczi      * QEMU global mutex, use a BH or introduce a mutex.
2829723c5d93SStefan Hajnoczi      */
2830723c5d93SStefan Hajnoczi 
283112bd451fSStefan Hajnoczi     BlockDriverState *bs = opaque;
2832bcada37bSWenchao Xia     const char *msg = NULL;
283312bd451fSStefan Hajnoczi 
28349abf2dbaSJeff Cody     trace_block_job_cb(bs, bs->job, ret);
283512bd451fSStefan Hajnoczi 
283612bd451fSStefan Hajnoczi     assert(bs->job);
2837bcada37bSWenchao Xia 
283812bd451fSStefan Hajnoczi     if (ret < 0) {
2839bcada37bSWenchao Xia         msg = strerror(-ret);
284012bd451fSStefan Hajnoczi     }
284112bd451fSStefan Hajnoczi 
2842370521a1SStefan Hajnoczi     if (block_job_is_cancelled(bs->job)) {
2843bcada37bSWenchao Xia         block_job_event_cancelled(bs->job);
2844370521a1SStefan Hajnoczi     } else {
2845bcada37bSWenchao Xia         block_job_event_completed(bs->job, msg);
2846370521a1SStefan Hajnoczi     }
284712bd451fSStefan Hajnoczi }
284812bd451fSStefan Hajnoczi 
284913d8cc51SJeff Cody void qmp_block_stream(const char *device,
285013d8cc51SJeff Cody                       bool has_base, const char *base,
285113d8cc51SJeff Cody                       bool has_backing_file, const char *backing_file,
285213d8cc51SJeff Cody                       bool has_speed, int64_t speed,
28531d809098SPaolo Bonzini                       bool has_on_error, BlockdevOnError on_error,
28541d809098SPaolo Bonzini                       Error **errp)
285512bd451fSStefan Hajnoczi {
2856a0e8544cSFam Zheng     BlockBackend *blk;
285712bd451fSStefan Hajnoczi     BlockDriverState *bs;
2858c8c3080fSMarcelo Tosatti     BlockDriverState *base_bs = NULL;
2859f3e69bebSStefan Hajnoczi     AioContext *aio_context;
2860fd7f8c65SStefan Hajnoczi     Error *local_err = NULL;
286113d8cc51SJeff Cody     const char *base_name = NULL;
286212bd451fSStefan Hajnoczi 
28631d809098SPaolo Bonzini     if (!has_on_error) {
28641d809098SPaolo Bonzini         on_error = BLOCKDEV_ON_ERROR_REPORT;
28651d809098SPaolo Bonzini     }
28661d809098SPaolo Bonzini 
2867a0e8544cSFam Zheng     blk = blk_by_name(device);
2868a0e8544cSFam Zheng     if (!blk) {
286975158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
287075158ebbSMarkus Armbruster                   "Device '%s' not found", device);
287112bd451fSStefan Hajnoczi         return;
287212bd451fSStefan Hajnoczi     }
287312bd451fSStefan Hajnoczi 
28745433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
2875f3e69bebSStefan Hajnoczi     aio_context_acquire(aio_context);
2876f3e69bebSStefan Hajnoczi 
28775433c24fSMax Reitz     if (!blk_is_available(blk)) {
28785433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
28795433c24fSMax Reitz         goto out;
28805433c24fSMax Reitz     }
28815433c24fSMax Reitz     bs = blk_bs(blk);
28825433c24fSMax Reitz 
2883628ff683SFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2884f3e69bebSStefan Hajnoczi         goto out;
2885628ff683SFam Zheng     }
2886628ff683SFam Zheng 
288713d8cc51SJeff Cody     if (has_base) {
2888c8c3080fSMarcelo Tosatti         base_bs = bdrv_find_backing_image(bs, base);
2889c8c3080fSMarcelo Tosatti         if (base_bs == NULL) {
2890c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_BASE_NOT_FOUND, base);
2891f3e69bebSStefan Hajnoczi             goto out;
289212bd451fSStefan Hajnoczi         }
2893f3e69bebSStefan Hajnoczi         assert(bdrv_get_aio_context(base_bs) == aio_context);
289413d8cc51SJeff Cody         base_name = base;
2895c8c3080fSMarcelo Tosatti     }
289612bd451fSStefan Hajnoczi 
289713d8cc51SJeff Cody     /* if we are streaming the entire chain, the result will have no backing
289813d8cc51SJeff Cody      * file, and specifying one is therefore an error */
289913d8cc51SJeff Cody     if (base_bs == NULL && has_backing_file) {
290013d8cc51SJeff Cody         error_setg(errp, "backing file specified, but streaming the "
290113d8cc51SJeff Cody                          "entire chain");
2902f3e69bebSStefan Hajnoczi         goto out;
290313d8cc51SJeff Cody     }
290413d8cc51SJeff Cody 
290513d8cc51SJeff Cody     /* backing_file string overrides base bs filename */
290613d8cc51SJeff Cody     base_name = has_backing_file ? backing_file : base_name;
290713d8cc51SJeff Cody 
290813d8cc51SJeff Cody     stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
29091d809098SPaolo Bonzini                  on_error, block_job_cb, bs, &local_err);
291084d18f06SMarkus Armbruster     if (local_err) {
2911fd7f8c65SStefan Hajnoczi         error_propagate(errp, local_err);
2912f3e69bebSStefan Hajnoczi         goto out;
291312bd451fSStefan Hajnoczi     }
291412bd451fSStefan Hajnoczi 
291512bd451fSStefan Hajnoczi     trace_qmp_block_stream(bs, bs->job);
2916f3e69bebSStefan Hajnoczi 
2917f3e69bebSStefan Hajnoczi out:
2918f3e69bebSStefan Hajnoczi     aio_context_release(aio_context);
291912bd451fSStefan Hajnoczi }
29202d47c6e9SStefan Hajnoczi 
2921ed61fc10SJeff Cody void qmp_block_commit(const char *device,
29227676e2c5SJeff Cody                       bool has_base, const char *base,
29237676e2c5SJeff Cody                       bool has_top, const char *top,
292454e26900SJeff Cody                       bool has_backing_file, const char *backing_file,
2925ed61fc10SJeff Cody                       bool has_speed, int64_t speed,
2926ed61fc10SJeff Cody                       Error **errp)
2927ed61fc10SJeff Cody {
2928a0e8544cSFam Zheng     BlockBackend *blk;
2929ed61fc10SJeff Cody     BlockDriverState *bs;
2930ed61fc10SJeff Cody     BlockDriverState *base_bs, *top_bs;
29319e85cd5cSStefan Hajnoczi     AioContext *aio_context;
2932ed61fc10SJeff Cody     Error *local_err = NULL;
2933ed61fc10SJeff Cody     /* This will be part of the QMP command, if/when the
2934ed61fc10SJeff Cody      * BlockdevOnError change for blkmirror makes it in
2935ed61fc10SJeff Cody      */
293692aa5c6dSPaolo Bonzini     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2937ed61fc10SJeff Cody 
293854504663SMax Reitz     if (!has_speed) {
293954504663SMax Reitz         speed = 0;
294054504663SMax Reitz     }
294154504663SMax Reitz 
29427676e2c5SJeff Cody     /* Important Note:
29437676e2c5SJeff Cody      *  libvirt relies on the DeviceNotFound error class in order to probe for
29447676e2c5SJeff Cody      *  live commit feature versions; for this to work, we must make sure to
29457676e2c5SJeff Cody      *  perform the device lookup before any generic errors that may occur in a
29467676e2c5SJeff Cody      *  scenario in which all optional arguments are omitted. */
2947a0e8544cSFam Zheng     blk = blk_by_name(device);
2948a0e8544cSFam Zheng     if (!blk) {
294975158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
295075158ebbSMarkus Armbruster                   "Device '%s' not found", device);
2951ed61fc10SJeff Cody         return;
2952ed61fc10SJeff Cody     }
2953ed61fc10SJeff Cody 
29545433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
29559e85cd5cSStefan Hajnoczi     aio_context_acquire(aio_context);
29569e85cd5cSStefan Hajnoczi 
29575433c24fSMax Reitz     if (!blk_is_available(blk)) {
29585433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
29595433c24fSMax Reitz         goto out;
29605433c24fSMax Reitz     }
29615433c24fSMax Reitz     bs = blk_bs(blk);
29625433c24fSMax Reitz 
2963bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
29649e85cd5cSStefan Hajnoczi         goto out;
2965628ff683SFam Zheng     }
2966628ff683SFam Zheng 
2967ed61fc10SJeff Cody     /* default top_bs is the active layer */
2968ed61fc10SJeff Cody     top_bs = bs;
2969ed61fc10SJeff Cody 
29707676e2c5SJeff Cody     if (has_top && top) {
2971ed61fc10SJeff Cody         if (strcmp(bs->filename, top) != 0) {
2972ed61fc10SJeff Cody             top_bs = bdrv_find_backing_image(bs, top);
2973ed61fc10SJeff Cody         }
2974ed61fc10SJeff Cody     }
2975ed61fc10SJeff Cody 
2976ed61fc10SJeff Cody     if (top_bs == NULL) {
2977ed61fc10SJeff Cody         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
29789e85cd5cSStefan Hajnoczi         goto out;
2979ed61fc10SJeff Cody     }
2980ed61fc10SJeff Cody 
29819e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(top_bs) == aio_context);
29829e85cd5cSStefan Hajnoczi 
2983d5208c45SJeff Cody     if (has_base && base) {
2984d5208c45SJeff Cody         base_bs = bdrv_find_backing_image(top_bs, base);
2985d5208c45SJeff Cody     } else {
2986d5208c45SJeff Cody         base_bs = bdrv_find_base(top_bs);
2987d5208c45SJeff Cody     }
2988d5208c45SJeff Cody 
2989d5208c45SJeff Cody     if (base_bs == NULL) {
2990c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
29919e85cd5cSStefan Hajnoczi         goto out;
2992d5208c45SJeff Cody     }
2993d5208c45SJeff Cody 
29949e85cd5cSStefan Hajnoczi     assert(bdrv_get_aio_context(base_bs) == aio_context);
29959e85cd5cSStefan Hajnoczi 
2996bb00021dSFam Zheng     if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2997bb00021dSFam Zheng         goto out;
2998bb00021dSFam Zheng     }
2999bb00021dSFam Zheng 
30007676e2c5SJeff Cody     /* Do not allow attempts to commit an image into itself */
30017676e2c5SJeff Cody     if (top_bs == base_bs) {
30027676e2c5SJeff Cody         error_setg(errp, "cannot commit an image into itself");
30039e85cd5cSStefan Hajnoczi         goto out;
30047676e2c5SJeff Cody     }
30057676e2c5SJeff Cody 
300620a63d2cSFam Zheng     if (top_bs == bs) {
300754e26900SJeff Cody         if (has_backing_file) {
300854e26900SJeff Cody             error_setg(errp, "'backing-file' specified,"
300954e26900SJeff Cody                              " but 'top' is the active layer");
30109e85cd5cSStefan Hajnoczi             goto out;
301154e26900SJeff Cody         }
301220a63d2cSFam Zheng         commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
301320a63d2cSFam Zheng                             bs, &local_err);
301420a63d2cSFam Zheng     } else {
3015ed61fc10SJeff Cody         commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
301654e26900SJeff Cody                      has_backing_file ? backing_file : NULL, &local_err);
301720a63d2cSFam Zheng     }
3018ed61fc10SJeff Cody     if (local_err != NULL) {
3019ed61fc10SJeff Cody         error_propagate(errp, local_err);
30209e85cd5cSStefan Hajnoczi         goto out;
3021ed61fc10SJeff Cody     }
30229e85cd5cSStefan Hajnoczi 
30239e85cd5cSStefan Hajnoczi out:
30249e85cd5cSStefan Hajnoczi     aio_context_release(aio_context);
3025ed61fc10SJeff Cody }
3026ed61fc10SJeff Cody 
302778f51fdeSJohn Snow static void do_drive_backup(const char *device, const char *target,
302899a9addfSStefan Hajnoczi                             bool has_format, const char *format,
3029b53169eaSStefan Hajnoczi                             enum MirrorSyncMode sync,
303099a9addfSStefan Hajnoczi                             bool has_mode, enum NewImageMode mode,
303199a9addfSStefan Hajnoczi                             bool has_speed, int64_t speed,
3032d58d8453SJohn Snow                             bool has_bitmap, const char *bitmap,
303378f51fdeSJohn Snow                             bool has_on_source_error,
303478f51fdeSJohn Snow                             BlockdevOnError on_source_error,
303578f51fdeSJohn Snow                             bool has_on_target_error,
303678f51fdeSJohn Snow                             BlockdevOnError on_target_error,
303778f51fdeSJohn Snow                             BlockJobTxn *txn, Error **errp)
303899a9addfSStefan Hajnoczi {
3039a0e8544cSFam Zheng     BlockBackend *blk;
304099a9addfSStefan Hajnoczi     BlockDriverState *bs;
304199a9addfSStefan Hajnoczi     BlockDriverState *target_bs;
3042fc5d3f84SIan Main     BlockDriverState *source = NULL;
3043d58d8453SJohn Snow     BdrvDirtyBitmap *bmap = NULL;
3044761731b1SStefan Hajnoczi     AioContext *aio_context;
3045e6641719SMax Reitz     QDict *options = NULL;
304699a9addfSStefan Hajnoczi     Error *local_err = NULL;
304799a9addfSStefan Hajnoczi     int flags;
304899a9addfSStefan Hajnoczi     int64_t size;
304999a9addfSStefan Hajnoczi     int ret;
305099a9addfSStefan Hajnoczi 
305199a9addfSStefan Hajnoczi     if (!has_speed) {
305299a9addfSStefan Hajnoczi         speed = 0;
305399a9addfSStefan Hajnoczi     }
305499a9addfSStefan Hajnoczi     if (!has_on_source_error) {
305599a9addfSStefan Hajnoczi         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
305699a9addfSStefan Hajnoczi     }
305799a9addfSStefan Hajnoczi     if (!has_on_target_error) {
305899a9addfSStefan Hajnoczi         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
305999a9addfSStefan Hajnoczi     }
306099a9addfSStefan Hajnoczi     if (!has_mode) {
306199a9addfSStefan Hajnoczi         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
306299a9addfSStefan Hajnoczi     }
306399a9addfSStefan Hajnoczi 
3064a0e8544cSFam Zheng     blk = blk_by_name(device);
3065a0e8544cSFam Zheng     if (!blk) {
306675158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
306775158ebbSMarkus Armbruster                   "Device '%s' not found", device);
306899a9addfSStefan Hajnoczi         return;
306999a9addfSStefan Hajnoczi     }
307099a9addfSStefan Hajnoczi 
30715433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3072761731b1SStefan Hajnoczi     aio_context_acquire(aio_context);
3073761731b1SStefan Hajnoczi 
3074c29c1dd3SFam Zheng     /* Although backup_run has this check too, we need to use bs->drv below, so
3075c29c1dd3SFam Zheng      * do an early check redundantly. */
30765433c24fSMax Reitz     if (!blk_is_available(blk)) {
3077c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3078761731b1SStefan Hajnoczi         goto out;
307999a9addfSStefan Hajnoczi     }
30805433c24fSMax Reitz     bs = blk_bs(blk);
308199a9addfSStefan Hajnoczi 
308299a9addfSStefan Hajnoczi     if (!has_format) {
308399a9addfSStefan Hajnoczi         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
308499a9addfSStefan Hajnoczi     }
308599a9addfSStefan Hajnoczi 
3086c29c1dd3SFam Zheng     /* Early check to avoid creating target */
30873718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
3088761731b1SStefan Hajnoczi         goto out;
308999a9addfSStefan Hajnoczi     }
309099a9addfSStefan Hajnoczi 
309199a9addfSStefan Hajnoczi     flags = bs->open_flags | BDRV_O_RDWR;
309299a9addfSStefan Hajnoczi 
3093fc5d3f84SIan Main     /* See if we have a backing HD we can use to create our new image
3094fc5d3f84SIan Main      * on top of. */
3095fc5d3f84SIan Main     if (sync == MIRROR_SYNC_MODE_TOP) {
3096760e0063SKevin Wolf         source = backing_bs(bs);
3097fc5d3f84SIan Main         if (!source) {
3098fc5d3f84SIan Main             sync = MIRROR_SYNC_MODE_FULL;
3099fc5d3f84SIan Main         }
3100fc5d3f84SIan Main     }
3101fc5d3f84SIan Main     if (sync == MIRROR_SYNC_MODE_NONE) {
3102fc5d3f84SIan Main         source = bs;
3103fc5d3f84SIan Main     }
3104fc5d3f84SIan Main 
310599a9addfSStefan Hajnoczi     size = bdrv_getlength(bs);
310699a9addfSStefan Hajnoczi     if (size < 0) {
310799a9addfSStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
3108761731b1SStefan Hajnoczi         goto out;
310999a9addfSStefan Hajnoczi     }
311099a9addfSStefan Hajnoczi 
311199a9addfSStefan Hajnoczi     if (mode != NEW_IMAGE_MODE_EXISTING) {
3112e6641719SMax Reitz         assert(format);
3113fc5d3f84SIan Main         if (source) {
3114fc5d3f84SIan Main             bdrv_img_create(target, format, source->filename,
3115fc5d3f84SIan Main                             source->drv->format_name, NULL,
3116fc5d3f84SIan Main                             size, flags, &local_err, false);
3117fc5d3f84SIan Main         } else {
3118fc5d3f84SIan Main             bdrv_img_create(target, format, NULL, NULL, NULL,
3119fc5d3f84SIan Main                             size, flags, &local_err, false);
3120fc5d3f84SIan Main         }
312199a9addfSStefan Hajnoczi     }
312299a9addfSStefan Hajnoczi 
312384d18f06SMarkus Armbruster     if (local_err) {
312499a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3125761731b1SStefan Hajnoczi         goto out;
312699a9addfSStefan Hajnoczi     }
312799a9addfSStefan Hajnoczi 
3128e6641719SMax Reitz     if (format) {
3129e6641719SMax Reitz         options = qdict_new();
3130e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
3131e6641719SMax Reitz     }
3132e6641719SMax Reitz 
3133f67503e5SMax Reitz     target_bs = NULL;
31346ebf9aa2SMax Reitz     ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
313599a9addfSStefan Hajnoczi     if (ret < 0) {
313634b5d2c6SMax Reitz         error_propagate(errp, local_err);
3137761731b1SStefan Hajnoczi         goto out;
313899a9addfSStefan Hajnoczi     }
313999a9addfSStefan Hajnoczi 
3140761731b1SStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
3141761731b1SStefan Hajnoczi 
3142d58d8453SJohn Snow     if (has_bitmap) {
3143d58d8453SJohn Snow         bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3144d58d8453SJohn Snow         if (!bmap) {
3145d58d8453SJohn Snow             error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3146d58d8453SJohn Snow             goto out;
3147d58d8453SJohn Snow         }
3148d58d8453SJohn Snow     }
3149d58d8453SJohn Snow 
3150d58d8453SJohn Snow     backup_start(bs, target_bs, speed, sync, bmap,
3151d58d8453SJohn Snow                  on_source_error, on_target_error,
315278f51fdeSJohn Snow                  block_job_cb, bs, txn, &local_err);
315399a9addfSStefan Hajnoczi     if (local_err != NULL) {
31544f6fd349SFam Zheng         bdrv_unref(target_bs);
315599a9addfSStefan Hajnoczi         error_propagate(errp, local_err);
3156761731b1SStefan Hajnoczi         goto out;
315799a9addfSStefan Hajnoczi     }
3158761731b1SStefan Hajnoczi 
3159761731b1SStefan Hajnoczi out:
3160761731b1SStefan Hajnoczi     aio_context_release(aio_context);
316199a9addfSStefan Hajnoczi }
316299a9addfSStefan Hajnoczi 
316378f51fdeSJohn Snow void qmp_drive_backup(const char *device, const char *target,
316478f51fdeSJohn Snow                       bool has_format, const char *format,
316578f51fdeSJohn Snow                       enum MirrorSyncMode sync,
316678f51fdeSJohn Snow                       bool has_mode, enum NewImageMode mode,
316778f51fdeSJohn Snow                       bool has_speed, int64_t speed,
316878f51fdeSJohn Snow                       bool has_bitmap, const char *bitmap,
316978f51fdeSJohn Snow                       bool has_on_source_error, BlockdevOnError on_source_error,
317078f51fdeSJohn Snow                       bool has_on_target_error, BlockdevOnError on_target_error,
317178f51fdeSJohn Snow                       Error **errp)
317278f51fdeSJohn Snow {
317378f51fdeSJohn Snow     return do_drive_backup(device, target, has_format, format, sync,
317478f51fdeSJohn Snow                            has_mode, mode, has_speed, speed,
317578f51fdeSJohn Snow                            has_bitmap, bitmap,
317678f51fdeSJohn Snow                            has_on_source_error, on_source_error,
317778f51fdeSJohn Snow                            has_on_target_error, on_target_error,
317878f51fdeSJohn Snow                            NULL, errp);
317978f51fdeSJohn Snow }
318078f51fdeSJohn Snow 
3181c13163fbSBenoît Canet BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3182c13163fbSBenoît Canet {
3183d5a8ee60SAlberto Garcia     return bdrv_named_nodes_list(errp);
3184c13163fbSBenoît Canet }
3185c13163fbSBenoît Canet 
318678f51fdeSJohn Snow void do_blockdev_backup(const char *device, const char *target,
3187c29c1dd3SFam Zheng                          enum MirrorSyncMode sync,
3188c29c1dd3SFam Zheng                          bool has_speed, int64_t speed,
3189c29c1dd3SFam Zheng                          bool has_on_source_error,
3190c29c1dd3SFam Zheng                          BlockdevOnError on_source_error,
3191c29c1dd3SFam Zheng                          bool has_on_target_error,
3192c29c1dd3SFam Zheng                          BlockdevOnError on_target_error,
319378f51fdeSJohn Snow                          BlockJobTxn *txn, Error **errp)
3194c29c1dd3SFam Zheng {
31955433c24fSMax Reitz     BlockBackend *blk, *target_blk;
3196c29c1dd3SFam Zheng     BlockDriverState *bs;
3197c29c1dd3SFam Zheng     BlockDriverState *target_bs;
3198c29c1dd3SFam Zheng     Error *local_err = NULL;
3199c29c1dd3SFam Zheng     AioContext *aio_context;
3200c29c1dd3SFam Zheng 
3201c29c1dd3SFam Zheng     if (!has_speed) {
3202c29c1dd3SFam Zheng         speed = 0;
3203c29c1dd3SFam Zheng     }
3204c29c1dd3SFam Zheng     if (!has_on_source_error) {
3205c29c1dd3SFam Zheng         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3206c29c1dd3SFam Zheng     }
3207c29c1dd3SFam Zheng     if (!has_on_target_error) {
3208c29c1dd3SFam Zheng         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3209c29c1dd3SFam Zheng     }
3210c29c1dd3SFam Zheng 
3211a0e8544cSFam Zheng     blk = blk_by_name(device);
3212a0e8544cSFam Zheng     if (!blk) {
32135b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", device);
3214c29c1dd3SFam Zheng         return;
3215c29c1dd3SFam Zheng     }
3216c29c1dd3SFam Zheng 
32175433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3218c29c1dd3SFam Zheng     aio_context_acquire(aio_context);
3219c29c1dd3SFam Zheng 
32205433c24fSMax Reitz     if (!blk_is_available(blk)) {
32215433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
32225433c24fSMax Reitz         goto out;
32235433c24fSMax Reitz     }
32245433c24fSMax Reitz     bs = blk_bs(blk);
32255433c24fSMax Reitz 
32265433c24fSMax Reitz     target_blk = blk_by_name(target);
32275433c24fSMax Reitz     if (!target_blk) {
32285b347c54SMarkus Armbruster         error_setg(errp, "Device '%s' not found", target);
3229c29c1dd3SFam Zheng         goto out;
3230c29c1dd3SFam Zheng     }
32315433c24fSMax Reitz 
32325433c24fSMax Reitz     if (!blk_is_available(target_blk)) {
32335433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", target);
32345433c24fSMax Reitz         goto out;
32355433c24fSMax Reitz     }
32365433c24fSMax Reitz     target_bs = blk_bs(target_blk);
3237c29c1dd3SFam Zheng 
3238c29c1dd3SFam Zheng     bdrv_ref(target_bs);
3239c29c1dd3SFam Zheng     bdrv_set_aio_context(target_bs, aio_context);
3240d58d8453SJohn Snow     backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
324178f51fdeSJohn Snow                  on_target_error, block_job_cb, bs, txn, &local_err);
3242c29c1dd3SFam Zheng     if (local_err != NULL) {
3243c29c1dd3SFam Zheng         bdrv_unref(target_bs);
3244c29c1dd3SFam Zheng         error_propagate(errp, local_err);
3245c29c1dd3SFam Zheng     }
3246c29c1dd3SFam Zheng out:
3247c29c1dd3SFam Zheng     aio_context_release(aio_context);
3248c29c1dd3SFam Zheng }
3249c29c1dd3SFam Zheng 
325078f51fdeSJohn Snow void qmp_blockdev_backup(const char *device, const char *target,
325178f51fdeSJohn Snow                          enum MirrorSyncMode sync,
325278f51fdeSJohn Snow                          bool has_speed, int64_t speed,
325378f51fdeSJohn Snow                          bool has_on_source_error,
325478f51fdeSJohn Snow                          BlockdevOnError on_source_error,
325578f51fdeSJohn Snow                          bool has_on_target_error,
325678f51fdeSJohn Snow                          BlockdevOnError on_target_error,
325778f51fdeSJohn Snow                          Error **errp)
325878f51fdeSJohn Snow {
325978f51fdeSJohn Snow     do_blockdev_backup(device, target, sync, has_speed, speed,
326078f51fdeSJohn Snow                        has_on_source_error, on_source_error,
326178f51fdeSJohn Snow                        has_on_target_error, on_target_error,
326278f51fdeSJohn Snow                        NULL, errp);
326378f51fdeSJohn Snow }
326478f51fdeSJohn Snow 
3265d9b902dbSPaolo Bonzini void qmp_drive_mirror(const char *device, const char *target,
3266d9b902dbSPaolo Bonzini                       bool has_format, const char *format,
32674c828dc6SBenoît Canet                       bool has_node_name, const char *node_name,
326809158f00SBenoît Canet                       bool has_replaces, const char *replaces,
3269d9b902dbSPaolo Bonzini                       enum MirrorSyncMode sync,
3270d9b902dbSPaolo Bonzini                       bool has_mode, enum NewImageMode mode,
3271b952b558SPaolo Bonzini                       bool has_speed, int64_t speed,
3272eee13dfeSPaolo Bonzini                       bool has_granularity, uint32_t granularity,
327308e4ed6cSPaolo Bonzini                       bool has_buf_size, int64_t buf_size,
3274b952b558SPaolo Bonzini                       bool has_on_source_error, BlockdevOnError on_source_error,
3275b952b558SPaolo Bonzini                       bool has_on_target_error, BlockdevOnError on_target_error,
32760fc9f8eaSFam Zheng                       bool has_unmap, bool unmap,
3277b952b558SPaolo Bonzini                       Error **errp)
3278d9b902dbSPaolo Bonzini {
3279a0e8544cSFam Zheng     BlockBackend *blk;
3280d9b902dbSPaolo Bonzini     BlockDriverState *bs;
3281d9b902dbSPaolo Bonzini     BlockDriverState *source, *target_bs;
32825a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
3283d9b902dbSPaolo Bonzini     Error *local_err = NULL;
3284e6641719SMax Reitz     QDict *options;
3285d9b902dbSPaolo Bonzini     int flags;
3286ac3c5d83SStefan Hajnoczi     int64_t size;
3287d9b902dbSPaolo Bonzini     int ret;
3288d9b902dbSPaolo Bonzini 
3289d9b902dbSPaolo Bonzini     if (!has_speed) {
3290d9b902dbSPaolo Bonzini         speed = 0;
3291d9b902dbSPaolo Bonzini     }
3292b952b558SPaolo Bonzini     if (!has_on_source_error) {
3293b952b558SPaolo Bonzini         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3294b952b558SPaolo Bonzini     }
3295b952b558SPaolo Bonzini     if (!has_on_target_error) {
3296b952b558SPaolo Bonzini         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3297b952b558SPaolo Bonzini     }
3298d9b902dbSPaolo Bonzini     if (!has_mode) {
3299d9b902dbSPaolo Bonzini         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3300d9b902dbSPaolo Bonzini     }
3301eee13dfeSPaolo Bonzini     if (!has_granularity) {
3302eee13dfeSPaolo Bonzini         granularity = 0;
3303eee13dfeSPaolo Bonzini     }
330408e4ed6cSPaolo Bonzini     if (!has_buf_size) {
330548ac0a4dSWen Congyang         buf_size = 0;
330608e4ed6cSPaolo Bonzini     }
33070fc9f8eaSFam Zheng     if (!has_unmap) {
33080fc9f8eaSFam Zheng         unmap = true;
33090fc9f8eaSFam Zheng     }
331008e4ed6cSPaolo Bonzini 
3311eee13dfeSPaolo Bonzini     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3312c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
33133cbbe9fdSStefan Hajnoczi                    "a value in range [512B, 64MB]");
3314eee13dfeSPaolo Bonzini         return;
3315eee13dfeSPaolo Bonzini     }
3316eee13dfeSPaolo Bonzini     if (granularity & (granularity - 1)) {
3317c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3318c6bd8c70SMarkus Armbruster                    "power of 2");
3319eee13dfeSPaolo Bonzini         return;
3320eee13dfeSPaolo Bonzini     }
3321d9b902dbSPaolo Bonzini 
3322a0e8544cSFam Zheng     blk = blk_by_name(device);
3323a0e8544cSFam Zheng     if (!blk) {
332475158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
332575158ebbSMarkus Armbruster                   "Device '%s' not found", device);
3326d9b902dbSPaolo Bonzini         return;
3327d9b902dbSPaolo Bonzini     }
3328d9b902dbSPaolo Bonzini 
33295433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
33305a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
33315a7e7a0bSStefan Hajnoczi 
33325433c24fSMax Reitz     if (!blk_is_available(blk)) {
3333c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
33345a7e7a0bSStefan Hajnoczi         goto out;
3335d9b902dbSPaolo Bonzini     }
33365433c24fSMax Reitz     bs = blk_bs(blk);
3337d9b902dbSPaolo Bonzini 
3338d9b902dbSPaolo Bonzini     if (!has_format) {
3339d9b902dbSPaolo Bonzini         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3340d9b902dbSPaolo Bonzini     }
3341d9b902dbSPaolo Bonzini 
33423718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
33435a7e7a0bSStefan Hajnoczi         goto out;
3344d9b902dbSPaolo Bonzini     }
3345d9b902dbSPaolo Bonzini 
3346d9b902dbSPaolo Bonzini     flags = bs->open_flags | BDRV_O_RDWR;
3347760e0063SKevin Wolf     source = backing_bs(bs);
3348d9b902dbSPaolo Bonzini     if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3349d9b902dbSPaolo Bonzini         sync = MIRROR_SYNC_MODE_FULL;
3350d9b902dbSPaolo Bonzini     }
3351117e0c82SMax Reitz     if (sync == MIRROR_SYNC_MODE_NONE) {
3352117e0c82SMax Reitz         source = bs;
3353117e0c82SMax Reitz     }
3354d9b902dbSPaolo Bonzini 
3355ac3c5d83SStefan Hajnoczi     size = bdrv_getlength(bs);
3356ac3c5d83SStefan Hajnoczi     if (size < 0) {
3357ac3c5d83SStefan Hajnoczi         error_setg_errno(errp, -size, "bdrv_getlength failed");
33585a7e7a0bSStefan Hajnoczi         goto out;
3359ac3c5d83SStefan Hajnoczi     }
3360ac3c5d83SStefan Hajnoczi 
336109158f00SBenoît Canet     if (has_replaces) {
336209158f00SBenoît Canet         BlockDriverState *to_replace_bs;
33635a7e7a0bSStefan Hajnoczi         AioContext *replace_aio_context;
33645a7e7a0bSStefan Hajnoczi         int64_t replace_size;
336509158f00SBenoît Canet 
336609158f00SBenoît Canet         if (!has_node_name) {
336709158f00SBenoît Canet             error_setg(errp, "a node-name must be provided when replacing a"
336809158f00SBenoît Canet                              " named node of the graph");
33695a7e7a0bSStefan Hajnoczi             goto out;
337009158f00SBenoît Canet         }
337109158f00SBenoît Canet 
3372e12f3784SWen Congyang         to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
337309158f00SBenoît Canet 
337409158f00SBenoît Canet         if (!to_replace_bs) {
337509158f00SBenoît Canet             error_propagate(errp, local_err);
33765a7e7a0bSStefan Hajnoczi             goto out;
337709158f00SBenoît Canet         }
337809158f00SBenoît Canet 
33795a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
33805a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
33815a7e7a0bSStefan Hajnoczi         replace_size = bdrv_getlength(to_replace_bs);
33825a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
33835a7e7a0bSStefan Hajnoczi 
33845a7e7a0bSStefan Hajnoczi         if (size != replace_size) {
338509158f00SBenoît Canet             error_setg(errp, "cannot replace image with a mirror image of "
338609158f00SBenoît Canet                              "different size");
33875a7e7a0bSStefan Hajnoczi             goto out;
338809158f00SBenoît Canet         }
338909158f00SBenoît Canet     }
339009158f00SBenoît Canet 
339114526864SMax Reitz     if ((sync == MIRROR_SYNC_MODE_FULL || !source)
339214526864SMax Reitz         && mode != NEW_IMAGE_MODE_EXISTING)
339314526864SMax Reitz     {
3394d9b902dbSPaolo Bonzini         /* create new image w/o backing file */
3395e6641719SMax Reitz         assert(format);
3396cf8f2426SLuiz Capitulino         bdrv_img_create(target, format,
3397f382d43aSMiroslav Rezanina                         NULL, NULL, NULL, size, flags, &local_err, false);
3398d9b902dbSPaolo Bonzini     } else {
3399d9b902dbSPaolo Bonzini         switch (mode) {
3400d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_EXISTING:
3401d9b902dbSPaolo Bonzini             break;
3402d9b902dbSPaolo Bonzini         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3403d9b902dbSPaolo Bonzini             /* create new image with backing file */
3404cf8f2426SLuiz Capitulino             bdrv_img_create(target, format,
3405d9b902dbSPaolo Bonzini                             source->filename,
3406d9b902dbSPaolo Bonzini                             source->drv->format_name,
3407f382d43aSMiroslav Rezanina                             NULL, size, flags, &local_err, false);
3408d9b902dbSPaolo Bonzini             break;
3409d9b902dbSPaolo Bonzini         default:
3410d9b902dbSPaolo Bonzini             abort();
3411d9b902dbSPaolo Bonzini         }
3412d9b902dbSPaolo Bonzini     }
3413d9b902dbSPaolo Bonzini 
341484d18f06SMarkus Armbruster     if (local_err) {
3415cf8f2426SLuiz Capitulino         error_propagate(errp, local_err);
34165a7e7a0bSStefan Hajnoczi         goto out;
3417d9b902dbSPaolo Bonzini     }
3418d9b902dbSPaolo Bonzini 
34194c828dc6SBenoît Canet     options = qdict_new();
3420e6641719SMax Reitz     if (has_node_name) {
34214c828dc6SBenoît Canet         qdict_put(options, "node-name", qstring_from_str(node_name));
34224c828dc6SBenoît Canet     }
3423e6641719SMax Reitz     if (format) {
3424e6641719SMax Reitz         qdict_put(options, "driver", qstring_from_str(format));
3425e6641719SMax Reitz     }
34264c828dc6SBenoît Canet 
3427b812f671SPaolo Bonzini     /* Mirroring takes care of copy-on-write using the source's backing
3428b812f671SPaolo Bonzini      * file.
3429b812f671SPaolo Bonzini      */
3430f67503e5SMax Reitz     target_bs = NULL;
34314c828dc6SBenoît Canet     ret = bdrv_open(&target_bs, target, NULL, options,
34326ebf9aa2SMax Reitz                     flags | BDRV_O_NO_BACKING, &local_err);
3433d9b902dbSPaolo Bonzini     if (ret < 0) {
343434b5d2c6SMax Reitz         error_propagate(errp, local_err);
34355a7e7a0bSStefan Hajnoczi         goto out;
3436d9b902dbSPaolo Bonzini     }
3437d9b902dbSPaolo Bonzini 
34385a7e7a0bSStefan Hajnoczi     bdrv_set_aio_context(target_bs, aio_context);
34395a7e7a0bSStefan Hajnoczi 
344009158f00SBenoît Canet     /* pass the node name to replace to mirror start since it's loose coupling
344109158f00SBenoît Canet      * and will allow to check whether the node still exist at mirror completion
344209158f00SBenoît Canet      */
344309158f00SBenoît Canet     mirror_start(bs, target_bs,
344409158f00SBenoît Canet                  has_replaces ? replaces : NULL,
344509158f00SBenoît Canet                  speed, granularity, buf_size, sync,
3446eee13dfeSPaolo Bonzini                  on_source_error, on_target_error,
34470fc9f8eaSFam Zheng                  unmap,
3448b952b558SPaolo Bonzini                  block_job_cb, bs, &local_err);
3449d9b902dbSPaolo Bonzini     if (local_err != NULL) {
34504f6fd349SFam Zheng         bdrv_unref(target_bs);
3451d9b902dbSPaolo Bonzini         error_propagate(errp, local_err);
34525a7e7a0bSStefan Hajnoczi         goto out;
3453d9b902dbSPaolo Bonzini     }
34545a7e7a0bSStefan Hajnoczi 
34555a7e7a0bSStefan Hajnoczi out:
34565a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
3457d9b902dbSPaolo Bonzini }
3458d9b902dbSPaolo Bonzini 
34593d948cdfSStefan Hajnoczi /* Get the block job for a given device name and acquire its AioContext */
346024d6bffeSMarkus Armbruster static BlockJob *find_block_job(const char *device, AioContext **aio_context,
346124d6bffeSMarkus Armbruster                                 Error **errp)
34622d47c6e9SStefan Hajnoczi {
3463a0e8544cSFam Zheng     BlockBackend *blk;
34642d47c6e9SStefan Hajnoczi     BlockDriverState *bs;
34652d47c6e9SStefan Hajnoczi 
34665433c24fSMax Reitz     *aio_context = NULL;
34675433c24fSMax Reitz 
3468a0e8544cSFam Zheng     blk = blk_by_name(device);
3469a0e8544cSFam Zheng     if (!blk) {
34703d948cdfSStefan Hajnoczi         goto notfound;
34712d47c6e9SStefan Hajnoczi     }
34723d948cdfSStefan Hajnoczi 
34735433c24fSMax Reitz     *aio_context = blk_get_aio_context(blk);
34743d948cdfSStefan Hajnoczi     aio_context_acquire(*aio_context);
34753d948cdfSStefan Hajnoczi 
34765433c24fSMax Reitz     if (!blk_is_available(blk)) {
34775433c24fSMax Reitz         goto notfound;
34785433c24fSMax Reitz     }
34795433c24fSMax Reitz     bs = blk_bs(blk);
34805433c24fSMax Reitz 
34813d948cdfSStefan Hajnoczi     if (!bs->job) {
34823d948cdfSStefan Hajnoczi         goto notfound;
34833d948cdfSStefan Hajnoczi     }
34843d948cdfSStefan Hajnoczi 
34852d47c6e9SStefan Hajnoczi     return bs->job;
34863d948cdfSStefan Hajnoczi 
34873d948cdfSStefan Hajnoczi notfound:
34882e3a0266SMarkus Armbruster     error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
34892e3a0266SMarkus Armbruster               "No active block job on device '%s'", device);
34905433c24fSMax Reitz     if (*aio_context) {
34915433c24fSMax Reitz         aio_context_release(*aio_context);
34923d948cdfSStefan Hajnoczi         *aio_context = NULL;
34935433c24fSMax Reitz     }
34943d948cdfSStefan Hajnoczi     return NULL;
34952d47c6e9SStefan Hajnoczi }
34962d47c6e9SStefan Hajnoczi 
3497882ec7ceSStefan Hajnoczi void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
34982d47c6e9SStefan Hajnoczi {
34993d948cdfSStefan Hajnoczi     AioContext *aio_context;
350024d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
35012d47c6e9SStefan Hajnoczi 
35022d47c6e9SStefan Hajnoczi     if (!job) {
35032d47c6e9SStefan Hajnoczi         return;
35042d47c6e9SStefan Hajnoczi     }
35052d47c6e9SStefan Hajnoczi 
3506882ec7ceSStefan Hajnoczi     block_job_set_speed(job, speed, errp);
35073d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
35082d47c6e9SStefan Hajnoczi }
3509370521a1SStefan Hajnoczi 
35106e37fb81SPaolo Bonzini void qmp_block_job_cancel(const char *device,
35116e37fb81SPaolo Bonzini                           bool has_force, bool force, Error **errp)
35126e37fb81SPaolo Bonzini {
35133d948cdfSStefan Hajnoczi     AioContext *aio_context;
351424d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
35156e37fb81SPaolo Bonzini 
35166e37fb81SPaolo Bonzini     if (!job) {
35176e37fb81SPaolo Bonzini         return;
35186e37fb81SPaolo Bonzini     }
35193d948cdfSStefan Hajnoczi 
35203d948cdfSStefan Hajnoczi     if (!has_force) {
35213d948cdfSStefan Hajnoczi         force = false;
35223d948cdfSStefan Hajnoczi     }
35233d948cdfSStefan Hajnoczi 
3524751ebd76SFam Zheng     if (job->user_paused && !force) {
3525f231b88dSCole Robinson         error_setg(errp, "The block job for device '%s' is currently paused",
3526f231b88dSCole Robinson                    device);
35273d948cdfSStefan Hajnoczi         goto out;
35286e37fb81SPaolo Bonzini     }
35296e37fb81SPaolo Bonzini 
35306e37fb81SPaolo Bonzini     trace_qmp_block_job_cancel(job);
35316e37fb81SPaolo Bonzini     block_job_cancel(job);
35323d948cdfSStefan Hajnoczi out:
35333d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
35346e37fb81SPaolo Bonzini }
35356e37fb81SPaolo Bonzini 
35366e37fb81SPaolo Bonzini void qmp_block_job_pause(const char *device, Error **errp)
3537370521a1SStefan Hajnoczi {
35383d948cdfSStefan Hajnoczi     AioContext *aio_context;
353924d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3540370521a1SStefan Hajnoczi 
3541751ebd76SFam Zheng     if (!job || job->user_paused) {
3542370521a1SStefan Hajnoczi         return;
3543370521a1SStefan Hajnoczi     }
35446e37fb81SPaolo Bonzini 
3545751ebd76SFam Zheng     job->user_paused = true;
35466e37fb81SPaolo Bonzini     trace_qmp_block_job_pause(job);
35476e37fb81SPaolo Bonzini     block_job_pause(job);
35483d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
35496e37fb81SPaolo Bonzini }
35506e37fb81SPaolo Bonzini 
35516e37fb81SPaolo Bonzini void qmp_block_job_resume(const char *device, Error **errp)
35526e37fb81SPaolo Bonzini {
35533d948cdfSStefan Hajnoczi     AioContext *aio_context;
355424d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
35556e37fb81SPaolo Bonzini 
3556751ebd76SFam Zheng     if (!job || !job->user_paused) {
35578acc72a4SPaolo Bonzini         return;
35588acc72a4SPaolo Bonzini     }
3559370521a1SStefan Hajnoczi 
3560751ebd76SFam Zheng     job->user_paused = false;
35616e37fb81SPaolo Bonzini     trace_qmp_block_job_resume(job);
35626e37fb81SPaolo Bonzini     block_job_resume(job);
35633d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3564370521a1SStefan Hajnoczi }
3565fb5458cdSStefan Hajnoczi 
3566aeae883bSPaolo Bonzini void qmp_block_job_complete(const char *device, Error **errp)
3567aeae883bSPaolo Bonzini {
35683d948cdfSStefan Hajnoczi     AioContext *aio_context;
356924d6bffeSMarkus Armbruster     BlockJob *job = find_block_job(device, &aio_context, errp);
3570aeae883bSPaolo Bonzini 
3571aeae883bSPaolo Bonzini     if (!job) {
3572aeae883bSPaolo Bonzini         return;
3573aeae883bSPaolo Bonzini     }
3574aeae883bSPaolo Bonzini 
3575aeae883bSPaolo Bonzini     trace_qmp_block_job_complete(job);
3576aeae883bSPaolo Bonzini     block_job_complete(job, errp);
35773d948cdfSStefan Hajnoczi     aio_context_release(aio_context);
3578aeae883bSPaolo Bonzini }
3579aeae883bSPaolo Bonzini 
3580fa40e656SJeff Cody void qmp_change_backing_file(const char *device,
3581fa40e656SJeff Cody                              const char *image_node_name,
3582fa40e656SJeff Cody                              const char *backing_file,
3583fa40e656SJeff Cody                              Error **errp)
3584fa40e656SJeff Cody {
3585a0e8544cSFam Zheng     BlockBackend *blk;
3586fa40e656SJeff Cody     BlockDriverState *bs = NULL;
3587729962f6SStefan Hajnoczi     AioContext *aio_context;
3588fa40e656SJeff Cody     BlockDriverState *image_bs = NULL;
3589fa40e656SJeff Cody     Error *local_err = NULL;
3590fa40e656SJeff Cody     bool ro;
3591fa40e656SJeff Cody     int open_flags;
3592fa40e656SJeff Cody     int ret;
3593fa40e656SJeff Cody 
3594a0e8544cSFam Zheng     blk = blk_by_name(device);
3595a0e8544cSFam Zheng     if (!blk) {
359675158ebbSMarkus Armbruster         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
359775158ebbSMarkus Armbruster                   "Device '%s' not found", device);
3598fa40e656SJeff Cody         return;
3599fa40e656SJeff Cody     }
3600fa40e656SJeff Cody 
36015433c24fSMax Reitz     aio_context = blk_get_aio_context(blk);
3602729962f6SStefan Hajnoczi     aio_context_acquire(aio_context);
3603729962f6SStefan Hajnoczi 
36045433c24fSMax Reitz     if (!blk_is_available(blk)) {
36055433c24fSMax Reitz         error_setg(errp, "Device '%s' has no medium", device);
36065433c24fSMax Reitz         goto out;
36075433c24fSMax Reitz     }
36085433c24fSMax Reitz     bs = blk_bs(blk);
36095433c24fSMax Reitz 
3610fa40e656SJeff Cody     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3611fa40e656SJeff Cody     if (local_err) {
3612fa40e656SJeff Cody         error_propagate(errp, local_err);
3613729962f6SStefan Hajnoczi         goto out;
3614fa40e656SJeff Cody     }
3615fa40e656SJeff Cody 
3616fa40e656SJeff Cody     if (!image_bs) {
3617fa40e656SJeff Cody         error_setg(errp, "image file not found");
3618729962f6SStefan Hajnoczi         goto out;
3619fa40e656SJeff Cody     }
3620fa40e656SJeff Cody 
3621fa40e656SJeff Cody     if (bdrv_find_base(image_bs) == image_bs) {
3622fa40e656SJeff Cody         error_setg(errp, "not allowing backing file change on an image "
3623fa40e656SJeff Cody                          "without a backing file");
3624729962f6SStefan Hajnoczi         goto out;
3625fa40e656SJeff Cody     }
3626fa40e656SJeff Cody 
3627fa40e656SJeff Cody     /* even though we are not necessarily operating on bs, we need it to
3628fa40e656SJeff Cody      * determine if block ops are currently prohibited on the chain */
3629fa40e656SJeff Cody     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3630729962f6SStefan Hajnoczi         goto out;
3631fa40e656SJeff Cody     }
3632fa40e656SJeff Cody 
3633fa40e656SJeff Cody     /* final sanity check */
3634fa40e656SJeff Cody     if (!bdrv_chain_contains(bs, image_bs)) {
3635fa40e656SJeff Cody         error_setg(errp, "'%s' and image file are not in the same chain",
3636fa40e656SJeff Cody                    device);
3637729962f6SStefan Hajnoczi         goto out;
3638fa40e656SJeff Cody     }
3639fa40e656SJeff Cody 
3640fa40e656SJeff Cody     /* if not r/w, reopen to make r/w */
3641fa40e656SJeff Cody     open_flags = image_bs->open_flags;
3642fa40e656SJeff Cody     ro = bdrv_is_read_only(image_bs);
3643fa40e656SJeff Cody 
3644fa40e656SJeff Cody     if (ro) {
3645fa40e656SJeff Cody         bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3646fa40e656SJeff Cody         if (local_err) {
3647fa40e656SJeff Cody             error_propagate(errp, local_err);
3648729962f6SStefan Hajnoczi             goto out;
3649fa40e656SJeff Cody         }
3650fa40e656SJeff Cody     }
3651fa40e656SJeff Cody 
3652fa40e656SJeff Cody     ret = bdrv_change_backing_file(image_bs, backing_file,
3653fa40e656SJeff Cody                                image_bs->drv ? image_bs->drv->format_name : "");
3654fa40e656SJeff Cody 
3655fa40e656SJeff Cody     if (ret < 0) {
3656fa40e656SJeff Cody         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3657fa40e656SJeff Cody                          backing_file);
3658fa40e656SJeff Cody         /* don't exit here, so we can try to restore open flags if
3659fa40e656SJeff Cody          * appropriate */
3660fa40e656SJeff Cody     }
3661fa40e656SJeff Cody 
3662fa40e656SJeff Cody     if (ro) {
3663fa40e656SJeff Cody         bdrv_reopen(image_bs, open_flags, &local_err);
3664fa40e656SJeff Cody         if (local_err) {
3665fa40e656SJeff Cody             error_propagate(errp, local_err); /* will preserve prior errp */
3666fa40e656SJeff Cody         }
3667fa40e656SJeff Cody     }
3668729962f6SStefan Hajnoczi 
3669729962f6SStefan Hajnoczi out:
3670729962f6SStefan Hajnoczi     aio_context_release(aio_context);
3671fa40e656SJeff Cody }
3672fa40e656SJeff Cody 
3673d26c9a15SKevin Wolf void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3674d26c9a15SKevin Wolf {
3675d26c9a15SKevin Wolf     QmpOutputVisitor *ov = qmp_output_visitor_new();
3676be4b67bcSMax Reitz     BlockDriverState *bs;
3677be4b67bcSMax Reitz     BlockBackend *blk = NULL;
3678d26c9a15SKevin Wolf     QObject *obj;
3679d26c9a15SKevin Wolf     QDict *qdict;
3680d26c9a15SKevin Wolf     Error *local_err = NULL;
3681d26c9a15SKevin Wolf 
368260e19e06SMarkus Armbruster     /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3683d26c9a15SKevin Wolf      * cache.direct=false instead of silently switching to aio=threads, except
368460e19e06SMarkus Armbruster      * when called from drive_new().
3685d26c9a15SKevin Wolf      *
3686d26c9a15SKevin Wolf      * For now, simply forbidding the combination for all drivers will do. */
3687d26c9a15SKevin Wolf     if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3688c6e0bd9bSKevin Wolf         bool direct = options->has_cache &&
3689c6e0bd9bSKevin Wolf                       options->cache->has_direct &&
3690c6e0bd9bSKevin Wolf                       options->cache->direct;
3691c6e0bd9bSKevin Wolf         if (!direct) {
3692d26c9a15SKevin Wolf             error_setg(errp, "aio=native requires cache.direct=true");
3693d26c9a15SKevin Wolf             goto fail;
3694d26c9a15SKevin Wolf         }
3695d26c9a15SKevin Wolf     }
3696d26c9a15SKevin Wolf 
3697d26c9a15SKevin Wolf     visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
3698d26c9a15SKevin Wolf                                &options, NULL, &local_err);
369984d18f06SMarkus Armbruster     if (local_err) {
3700d26c9a15SKevin Wolf         error_propagate(errp, local_err);
3701d26c9a15SKevin Wolf         goto fail;
3702d26c9a15SKevin Wolf     }
3703d26c9a15SKevin Wolf 
3704d26c9a15SKevin Wolf     obj = qmp_output_get_qobject(ov);
3705d26c9a15SKevin Wolf     qdict = qobject_to_qdict(obj);
3706d26c9a15SKevin Wolf 
3707d26c9a15SKevin Wolf     qdict_flatten(qdict);
3708d26c9a15SKevin Wolf 
3709be4b67bcSMax Reitz     if (options->has_id) {
371018e46a03SMarkus Armbruster         blk = blockdev_init(NULL, qdict, &local_err);
371184d18f06SMarkus Armbruster         if (local_err) {
3712b681072dSKevin Wolf             error_propagate(errp, local_err);
3713d26c9a15SKevin Wolf             goto fail;
3714d26c9a15SKevin Wolf         }
3715d26c9a15SKevin Wolf 
3716be4b67bcSMax Reitz         bs = blk_bs(blk);
3717be4b67bcSMax Reitz     } else {
3718be4b67bcSMax Reitz         if (!qdict_get_try_str(qdict, "node-name")) {
3719be4b67bcSMax Reitz             error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3720be4b67bcSMax Reitz                        "the root node");
3721be4b67bcSMax Reitz             goto fail;
3722be4b67bcSMax Reitz         }
3723be4b67bcSMax Reitz 
3724bd745e23SMax Reitz         bs = bds_tree_init(qdict, errp);
3725bd745e23SMax Reitz         if (!bs) {
3726be4b67bcSMax Reitz             goto fail;
3727be4b67bcSMax Reitz         }
3728be4b67bcSMax Reitz     }
3729be4b67bcSMax Reitz 
3730be4b67bcSMax Reitz     if (bs && bdrv_key_required(bs)) {
3731be4b67bcSMax Reitz         if (blk) {
373218e46a03SMarkus Armbruster             blk_unref(blk);
3733be4b67bcSMax Reitz         } else {
3734be4b67bcSMax Reitz             bdrv_unref(bs);
3735be4b67bcSMax Reitz         }
37368ae8e904SKevin Wolf         error_setg(errp, "blockdev-add doesn't support encrypted devices");
37378ae8e904SKevin Wolf         goto fail;
37388ae8e904SKevin Wolf     }
37398ae8e904SKevin Wolf 
3740d26c9a15SKevin Wolf fail:
3741d26c9a15SKevin Wolf     qmp_output_visitor_cleanup(ov);
3742d26c9a15SKevin Wolf }
3743d26c9a15SKevin Wolf 
374481b936aeSAlberto Garcia void qmp_x_blockdev_del(bool has_id, const char *id,
374581b936aeSAlberto Garcia                         bool has_node_name, const char *node_name, Error **errp)
374681b936aeSAlberto Garcia {
374781b936aeSAlberto Garcia     AioContext *aio_context;
374881b936aeSAlberto Garcia     BlockBackend *blk;
374981b936aeSAlberto Garcia     BlockDriverState *bs;
375081b936aeSAlberto Garcia 
375181b936aeSAlberto Garcia     if (has_id && has_node_name) {
375281b936aeSAlberto Garcia         error_setg(errp, "Only one of id and node-name must be specified");
375381b936aeSAlberto Garcia         return;
375481b936aeSAlberto Garcia     } else if (!has_id && !has_node_name) {
375581b936aeSAlberto Garcia         error_setg(errp, "No block device specified");
375681b936aeSAlberto Garcia         return;
375781b936aeSAlberto Garcia     }
375881b936aeSAlberto Garcia 
375981b936aeSAlberto Garcia     if (has_id) {
376081b936aeSAlberto Garcia         blk = blk_by_name(id);
376181b936aeSAlberto Garcia         if (!blk) {
376281b936aeSAlberto Garcia             error_setg(errp, "Cannot find block backend %s", id);
376381b936aeSAlberto Garcia             return;
376481b936aeSAlberto Garcia         }
376581b936aeSAlberto Garcia         if (blk_get_refcnt(blk) > 1) {
376681b936aeSAlberto Garcia             error_setg(errp, "Block backend %s is in use", id);
376781b936aeSAlberto Garcia             return;
376881b936aeSAlberto Garcia         }
376981b936aeSAlberto Garcia         bs = blk_bs(blk);
377081b936aeSAlberto Garcia         aio_context = blk_get_aio_context(blk);
377181b936aeSAlberto Garcia     } else {
377281b936aeSAlberto Garcia         bs = bdrv_find_node(node_name);
377381b936aeSAlberto Garcia         if (!bs) {
377481b936aeSAlberto Garcia             error_setg(errp, "Cannot find node %s", node_name);
377581b936aeSAlberto Garcia             return;
377681b936aeSAlberto Garcia         }
377781b936aeSAlberto Garcia         blk = bs->blk;
377881b936aeSAlberto Garcia         if (blk) {
377981b936aeSAlberto Garcia             error_setg(errp, "Node %s is in use by %s",
378081b936aeSAlberto Garcia                        node_name, blk_name(blk));
378181b936aeSAlberto Garcia             return;
378281b936aeSAlberto Garcia         }
378381b936aeSAlberto Garcia         aio_context = bdrv_get_aio_context(bs);
378481b936aeSAlberto Garcia     }
378581b936aeSAlberto Garcia 
378681b936aeSAlberto Garcia     aio_context_acquire(aio_context);
378781b936aeSAlberto Garcia 
378881b936aeSAlberto Garcia     if (bs) {
378981b936aeSAlberto Garcia         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
379081b936aeSAlberto Garcia             goto out;
379181b936aeSAlberto Garcia         }
379281b936aeSAlberto Garcia 
379381b936aeSAlberto Garcia         if (bs->refcnt > 1 || !QLIST_EMPTY(&bs->parents)) {
379481b936aeSAlberto Garcia             error_setg(errp, "Block device %s is in use",
379581b936aeSAlberto Garcia                        bdrv_get_device_or_node_name(bs));
379681b936aeSAlberto Garcia             goto out;
379781b936aeSAlberto Garcia         }
379881b936aeSAlberto Garcia     }
379981b936aeSAlberto Garcia 
380081b936aeSAlberto Garcia     if (blk) {
380181b936aeSAlberto Garcia         blk_unref(blk);
380281b936aeSAlberto Garcia     } else {
380381b936aeSAlberto Garcia         bdrv_unref(bs);
380481b936aeSAlberto Garcia     }
380581b936aeSAlberto Garcia 
380681b936aeSAlberto Garcia out:
380781b936aeSAlberto Garcia     aio_context_release(aio_context);
380881b936aeSAlberto Garcia }
380981b936aeSAlberto Garcia 
3810fb5458cdSStefan Hajnoczi BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3811fb5458cdSStefan Hajnoczi {
3812fea68bb6SMarkus Armbruster     BlockJobInfoList *head = NULL, **p_next = &head;
3813fea68bb6SMarkus Armbruster     BlockDriverState *bs;
3814fea68bb6SMarkus Armbruster 
3815fea68bb6SMarkus Armbruster     for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
381669691e72SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
381769691e72SStefan Hajnoczi 
381869691e72SStefan Hajnoczi         aio_context_acquire(aio_context);
381969691e72SStefan Hajnoczi 
3820fea68bb6SMarkus Armbruster         if (bs->job) {
3821fea68bb6SMarkus Armbruster             BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
3822fea68bb6SMarkus Armbruster             elem->value = block_job_query(bs->job);
3823fea68bb6SMarkus Armbruster             *p_next = elem;
3824fea68bb6SMarkus Armbruster             p_next = &elem->next;
3825fea68bb6SMarkus Armbruster         }
382669691e72SStefan Hajnoczi 
382769691e72SStefan Hajnoczi         aio_context_release(aio_context);
3828fea68bb6SMarkus Armbruster     }
3829fea68bb6SMarkus Armbruster 
3830fea68bb6SMarkus Armbruster     return head;
3831fb5458cdSStefan Hajnoczi }
38324d454574SPaolo Bonzini 
38330006383eSKevin Wolf QemuOptsList qemu_common_drive_opts = {
38344d454574SPaolo Bonzini     .name = "drive",
38350006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
38364d454574SPaolo Bonzini     .desc = {
38374d454574SPaolo Bonzini         {
38384d454574SPaolo Bonzini             .name = "snapshot",
38394d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
38404d454574SPaolo Bonzini             .help = "enable/disable snapshot mode",
38414d454574SPaolo Bonzini         },{
3842a9384affSPaolo Bonzini             .name = "discard",
3843a9384affSPaolo Bonzini             .type = QEMU_OPT_STRING,
3844a9384affSPaolo Bonzini             .help = "discard operation (ignore/off, unmap/on)",
3845a9384affSPaolo Bonzini         },{
384654861b92SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
384729c4e2b5SKevin Wolf             .type = QEMU_OPT_BOOL,
384829c4e2b5SKevin Wolf             .help = "enables writeback mode for any caches",
384929c4e2b5SKevin Wolf         },{
385054861b92SKevin Wolf             .name = BDRV_OPT_CACHE_DIRECT,
385129c4e2b5SKevin Wolf             .type = QEMU_OPT_BOOL,
385229c4e2b5SKevin Wolf             .help = "enables use of O_DIRECT (bypass the host page cache)",
385329c4e2b5SKevin Wolf         },{
385454861b92SKevin Wolf             .name = BDRV_OPT_CACHE_NO_FLUSH,
385529c4e2b5SKevin Wolf             .type = QEMU_OPT_BOOL,
385629c4e2b5SKevin Wolf             .help = "ignore any flush requests for the device",
38574d454574SPaolo Bonzini         },{
38584d454574SPaolo Bonzini             .name = "aio",
38594d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
38604d454574SPaolo Bonzini             .help = "host AIO implementation (threads, native)",
38614d454574SPaolo Bonzini         },{
38624d454574SPaolo Bonzini             .name = "format",
38634d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
38644d454574SPaolo Bonzini             .help = "disk format (raw, qcow2, ...)",
38654d454574SPaolo Bonzini         },{
38664d454574SPaolo Bonzini             .name = "rerror",
38674d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
38684d454574SPaolo Bonzini             .help = "read error action",
38694d454574SPaolo Bonzini         },{
38704d454574SPaolo Bonzini             .name = "werror",
38714d454574SPaolo Bonzini             .type = QEMU_OPT_STRING,
38724d454574SPaolo Bonzini             .help = "write error action",
38734d454574SPaolo Bonzini         },{
38740f227a94SKevin Wolf             .name = "read-only",
38754d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
38764d454574SPaolo Bonzini             .help = "open drive file as read-only",
38774d454574SPaolo Bonzini         },{
387857975222SKevin Wolf             .name = "throttling.iops-total",
38794d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
38804d454574SPaolo Bonzini             .help = "limit total I/O operations per second",
38814d454574SPaolo Bonzini         },{
388257975222SKevin Wolf             .name = "throttling.iops-read",
38834d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
38844d454574SPaolo Bonzini             .help = "limit read operations per second",
38854d454574SPaolo Bonzini         },{
388657975222SKevin Wolf             .name = "throttling.iops-write",
38874d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
38884d454574SPaolo Bonzini             .help = "limit write operations per second",
38894d454574SPaolo Bonzini         },{
389057975222SKevin Wolf             .name = "throttling.bps-total",
38914d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
38924d454574SPaolo Bonzini             .help = "limit total bytes per second",
38934d454574SPaolo Bonzini         },{
389457975222SKevin Wolf             .name = "throttling.bps-read",
38954d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
38964d454574SPaolo Bonzini             .help = "limit read bytes per second",
38974d454574SPaolo Bonzini         },{
389857975222SKevin Wolf             .name = "throttling.bps-write",
38994d454574SPaolo Bonzini             .type = QEMU_OPT_NUMBER,
39004d454574SPaolo Bonzini             .help = "limit write bytes per second",
39014d454574SPaolo Bonzini         },{
39023e9fab69SBenoît Canet             .name = "throttling.iops-total-max",
39033e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
39043e9fab69SBenoît Canet             .help = "I/O operations burst",
39053e9fab69SBenoît Canet         },{
39063e9fab69SBenoît Canet             .name = "throttling.iops-read-max",
39073e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
39083e9fab69SBenoît Canet             .help = "I/O operations read burst",
39093e9fab69SBenoît Canet         },{
39103e9fab69SBenoît Canet             .name = "throttling.iops-write-max",
39113e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
39123e9fab69SBenoît Canet             .help = "I/O operations write burst",
39133e9fab69SBenoît Canet         },{
39143e9fab69SBenoît Canet             .name = "throttling.bps-total-max",
39153e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
39163e9fab69SBenoît Canet             .help = "total bytes burst",
39173e9fab69SBenoît Canet         },{
39183e9fab69SBenoît Canet             .name = "throttling.bps-read-max",
39193e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
39203e9fab69SBenoît Canet             .help = "total bytes read burst",
39213e9fab69SBenoît Canet         },{
39223e9fab69SBenoît Canet             .name = "throttling.bps-write-max",
39233e9fab69SBenoît Canet             .type = QEMU_OPT_NUMBER,
39243e9fab69SBenoît Canet             .help = "total bytes write burst",
39253e9fab69SBenoît Canet         },{
39262024c1dfSBenoît Canet             .name = "throttling.iops-size",
39272024c1dfSBenoît Canet             .type = QEMU_OPT_NUMBER,
39282024c1dfSBenoît Canet             .help = "when limiting by iops max size of an I/O in bytes",
39292024c1dfSBenoît Canet         },{
393076f4afb4SAlberto Garcia             .name = "throttling.group",
393176f4afb4SAlberto Garcia             .type = QEMU_OPT_STRING,
393276f4afb4SAlberto Garcia             .help = "name of the block throttling group",
393376f4afb4SAlberto Garcia         },{
39344d454574SPaolo Bonzini             .name = "copy-on-read",
39354d454574SPaolo Bonzini             .type = QEMU_OPT_BOOL,
39364d454574SPaolo Bonzini             .help = "copy read data from backing file into image file",
3937465bee1dSPeter Lieven         },{
3938465bee1dSPeter Lieven             .name = "detect-zeroes",
3939465bee1dSPeter Lieven             .type = QEMU_OPT_STRING,
3940465bee1dSPeter Lieven             .help = "try to optimize zero writes (off, on, unmap)",
3941362e9299SAlberto Garcia         },{
3942362e9299SAlberto Garcia             .name = "stats-account-invalid",
3943362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
3944362e9299SAlberto Garcia             .help = "whether to account for invalid I/O operations "
3945362e9299SAlberto Garcia                     "in the statistics",
3946362e9299SAlberto Garcia         },{
3947362e9299SAlberto Garcia             .name = "stats-account-failed",
3948362e9299SAlberto Garcia             .type = QEMU_OPT_BOOL,
3949362e9299SAlberto Garcia             .help = "whether to account for failed I/O operations "
3950362e9299SAlberto Garcia                     "in the statistics",
3951*2be5506fSAlberto Garcia         },{
3952*2be5506fSAlberto Garcia             .name = "stats-intervals",
3953*2be5506fSAlberto Garcia             .type = QEMU_OPT_STRING,
3954*2be5506fSAlberto Garcia             .help = "colon-separated list of intervals "
3955*2be5506fSAlberto Garcia                     "for collecting I/O statistics, in seconds",
39564d454574SPaolo Bonzini         },
39574d454574SPaolo Bonzini         { /* end of list */ }
39584d454574SPaolo Bonzini     },
39594d454574SPaolo Bonzini };
39600006383eSKevin Wolf 
3961bd745e23SMax Reitz static QemuOptsList qemu_root_bds_opts = {
3962bd745e23SMax Reitz     .name = "root-bds",
3963bd745e23SMax Reitz     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3964bd745e23SMax Reitz     .desc = {
3965bd745e23SMax Reitz         {
3966bd745e23SMax Reitz             .name = "discard",
3967bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
3968bd745e23SMax Reitz             .help = "discard operation (ignore/off, unmap/on)",
3969bd745e23SMax Reitz         },{
3970bd745e23SMax Reitz             .name = "cache.writeback",
3971bd745e23SMax Reitz             .type = QEMU_OPT_BOOL,
3972bd745e23SMax Reitz             .help = "enables writeback mode for any caches",
3973bd745e23SMax Reitz         },{
3974bd745e23SMax Reitz             .name = "cache.direct",
3975bd745e23SMax Reitz             .type = QEMU_OPT_BOOL,
3976bd745e23SMax Reitz             .help = "enables use of O_DIRECT (bypass the host page cache)",
3977bd745e23SMax Reitz         },{
3978bd745e23SMax Reitz             .name = "cache.no-flush",
3979bd745e23SMax Reitz             .type = QEMU_OPT_BOOL,
3980bd745e23SMax Reitz             .help = "ignore any flush requests for the device",
3981bd745e23SMax Reitz         },{
3982bd745e23SMax Reitz             .name = "aio",
3983bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
3984bd745e23SMax Reitz             .help = "host AIO implementation (threads, native)",
3985bd745e23SMax Reitz         },{
3986bd745e23SMax Reitz             .name = "read-only",
3987bd745e23SMax Reitz             .type = QEMU_OPT_BOOL,
3988bd745e23SMax Reitz             .help = "open drive file as read-only",
3989bd745e23SMax Reitz         },{
3990bd745e23SMax Reitz             .name = "copy-on-read",
3991bd745e23SMax Reitz             .type = QEMU_OPT_BOOL,
3992bd745e23SMax Reitz             .help = "copy read data from backing file into image file",
3993bd745e23SMax Reitz         },{
3994bd745e23SMax Reitz             .name = "detect-zeroes",
3995bd745e23SMax Reitz             .type = QEMU_OPT_STRING,
3996bd745e23SMax Reitz             .help = "try to optimize zero writes (off, on, unmap)",
3997bd745e23SMax Reitz         },
3998bd745e23SMax Reitz         { /* end of list */ }
3999bd745e23SMax Reitz     },
4000bd745e23SMax Reitz };
4001bd745e23SMax Reitz 
40020006383eSKevin Wolf QemuOptsList qemu_drive_opts = {
40030006383eSKevin Wolf     .name = "drive",
40040006383eSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
40050006383eSKevin Wolf     .desc = {
4006492fdc6fSKevin Wolf         /*
4007492fdc6fSKevin Wolf          * no elements => accept any params
4008492fdc6fSKevin Wolf          * validation will happen later
4009492fdc6fSKevin Wolf          */
40100006383eSKevin Wolf         { /* end of list */ }
40110006383eSKevin Wolf     },
40120006383eSKevin Wolf };
4013