Merge tag 'v2.4.0' into tizen_3.0_qemu_2.4
[sdk/emulator/qemu.git] / blockdev.c
1 /*
2  * QEMU host block devices
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * This work is licensed under the terms of the GNU GPL, version 2 or
7  * later.  See the COPYING file in the top-level directory.
8  *
9  * This file incorporates work covered by the following copyright and
10  * permission notice:
11  *
12  * Copyright (c) 2003-2008 Fabrice Bellard
13  *
14  * Permission is hereby granted, free of charge, to any person obtaining a copy
15  * of this software and associated documentation files (the "Software"), to deal
16  * in the Software without restriction, including without limitation the rights
17  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18  * copies of the Software, and to permit persons to whom the Software is
19  * furnished to do so, subject to the following conditions:
20  *
21  * The above copyright notice and this permission notice shall be included in
22  * all copies or substantial portions of the Software.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30  * THE SOFTWARE.
31  */
32
33 #include "sysemu/block-backend.h"
34 #include "sysemu/blockdev.h"
35 #include "hw/block/block.h"
36 #include "block/blockjob.h"
37 #include "block/throttle-groups.h"
38 #include "monitor/monitor.h"
39 #include "qemu/error-report.h"
40 #include "qemu/option.h"
41 #include "qemu/config-file.h"
42 #include "qapi/qmp/types.h"
43 #include "qapi-visit.h"
44 #include "qapi/qmp/qerror.h"
45 #include "qapi/qmp-output-visitor.h"
46 #include "qapi/util.h"
47 #include "sysemu/sysemu.h"
48 #include "block/block_int.h"
49 #include "qmp-commands.h"
50 #include "trace.h"
51 #include "sysemu/arch_init.h"
52
53 #ifdef CONFIG_MARU
54 #include "tizen/src/util/exported_strings.h"
55 #endif
56
57 static const char *const if_name[IF_COUNT] = {
58     [IF_NONE] = "none",
59     [IF_IDE] = "ide",
60     [IF_SCSI] = "scsi",
61     [IF_FLOPPY] = "floppy",
62     [IF_PFLASH] = "pflash",
63     [IF_MTD] = "mtd",
64     [IF_SD] = "sd",
65     [IF_VIRTIO] = "virtio",
66     [IF_XEN] = "xen",
67 };
68
69 static int if_max_devs[IF_COUNT] = {
70     /*
71      * Do not change these numbers!  They govern how drive option
72      * index maps to unit and bus.  That mapping is ABI.
73      *
74      * All controllers used to imlement if=T drives need to support
75      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
76      * Otherwise, some index values map to "impossible" bus, unit
77      * values.
78      *
79      * For instance, if you change [IF_SCSI] to 255, -drive
80      * if=scsi,index=12 no longer means bus=1,unit=5, but
81      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
82      * the drive can't be set up.  Regression.
83      */
84     [IF_IDE] = 2,
85     [IF_SCSI] = 7,
86 };
87
88 /**
89  * Boards may call this to offer board-by-board overrides
90  * of the default, global values.
91  */
92 void override_max_devs(BlockInterfaceType type, int max_devs)
93 {
94     BlockBackend *blk;
95     DriveInfo *dinfo;
96
97     if (max_devs <= 0) {
98         return;
99     }
100
101     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
102         dinfo = blk_legacy_dinfo(blk);
103         if (dinfo->type == type) {
104             fprintf(stderr, "Cannot override units-per-bus property of"
105                     " the %s interface, because a drive of that type has"
106                     " already been added.\n", if_name[type]);
107             g_assert_not_reached();
108         }
109     }
110
111     if_max_devs[type] = max_devs;
112 }
113
114 /*
115  * We automatically delete the drive when a device using it gets
116  * unplugged.  Questionable feature, but we can't just drop it.
117  * Device models call blockdev_mark_auto_del() to schedule the
118  * automatic deletion, and generic qdev code calls blockdev_auto_del()
119  * when deletion is actually safe.
120  */
121 void blockdev_mark_auto_del(BlockBackend *blk)
122 {
123     DriveInfo *dinfo = blk_legacy_dinfo(blk);
124     BlockDriverState *bs = blk_bs(blk);
125     AioContext *aio_context;
126
127     if (!dinfo) {
128         return;
129     }
130
131     aio_context = bdrv_get_aio_context(bs);
132     aio_context_acquire(aio_context);
133
134     if (bs->job) {
135         block_job_cancel(bs->job);
136     }
137
138     aio_context_release(aio_context);
139
140     dinfo->auto_del = 1;
141 }
142
143 void blockdev_auto_del(BlockBackend *blk)
144 {
145     DriveInfo *dinfo = blk_legacy_dinfo(blk);
146
147     if (dinfo && dinfo->auto_del) {
148         blk_unref(blk);
149     }
150 }
151
152 /**
153  * Returns the current mapping of how many units per bus
154  * a particular interface can support.
155  *
156  *  A positive integer indicates n units per bus.
157  *  0 implies the mapping has not been established.
158  * -1 indicates an invalid BlockInterfaceType was given.
159  */
160 int drive_get_max_devs(BlockInterfaceType type)
161 {
162     if (type >= IF_IDE && type < IF_COUNT) {
163         return if_max_devs[type];
164     }
165
166     return -1;
167 }
168
169 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
170 {
171     int max_devs = if_max_devs[type];
172     return max_devs ? index / max_devs : 0;
173 }
174
175 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
176 {
177     int max_devs = if_max_devs[type];
178     return max_devs ? index % max_devs : index;
179 }
180
181 QemuOpts *drive_def(const char *optstr)
182 {
183     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
184 }
185
186 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
187                     const char *optstr)
188 {
189     QemuOpts *opts;
190
191     opts = drive_def(optstr);
192     if (!opts) {
193         return NULL;
194     }
195     if (type != IF_DEFAULT) {
196         qemu_opt_set(opts, "if", if_name[type], &error_abort);
197     }
198     if (index >= 0) {
199         qemu_opt_set_number(opts, "index", index, &error_abort);
200     }
201     if (file)
202         qemu_opt_set(opts, "file", file, &error_abort);
203     return opts;
204 }
205
206 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
207 {
208     BlockBackend *blk;
209     DriveInfo *dinfo;
210
211     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
212         dinfo = blk_legacy_dinfo(blk);
213         if (dinfo && dinfo->type == type
214             && dinfo->bus == bus && dinfo->unit == unit) {
215             return dinfo;
216         }
217     }
218
219     return NULL;
220 }
221
222 bool drive_check_orphaned(void)
223 {
224     BlockBackend *blk;
225     DriveInfo *dinfo;
226     bool rs = false;
227
228     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
229         dinfo = blk_legacy_dinfo(blk);
230         /* If dinfo->bdrv->dev is NULL, it has no device attached. */
231         /* Unless this is a default drive, this may be an oversight. */
232         if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
233             dinfo->type != IF_NONE) {
234             fprintf(stderr, "Warning: Orphaned drive without device: "
235                     "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
236                     blk_name(blk), blk_bs(blk)->filename, if_name[dinfo->type],
237                     dinfo->bus, dinfo->unit);
238             rs = true;
239         }
240     }
241
242     return rs;
243 }
244
245 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
246 {
247     return drive_get(type,
248                      drive_index_to_bus_id(type, index),
249                      drive_index_to_unit_id(type, index));
250 }
251
252 int drive_get_max_bus(BlockInterfaceType type)
253 {
254     int max_bus;
255     BlockBackend *blk;
256     DriveInfo *dinfo;
257
258     max_bus = -1;
259     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
260         dinfo = blk_legacy_dinfo(blk);
261         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
262             max_bus = dinfo->bus;
263         }
264     }
265     return max_bus;
266 }
267
268 /* Get a block device.  This should only be used for single-drive devices
269    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
270    appropriate bus.  */
271 DriveInfo *drive_get_next(BlockInterfaceType type)
272 {
273     static int next_block_unit[IF_COUNT];
274
275     return drive_get(type, 0, next_block_unit[type]++);
276 }
277
278 static void bdrv_format_print(void *opaque, const char *name)
279 {
280     error_printf(" %s", name);
281 }
282
283 typedef struct {
284     QEMUBH *bh;
285     BlockDriverState *bs;
286 } BDRVPutRefBH;
287
288 static void bdrv_put_ref_bh(void *opaque)
289 {
290     BDRVPutRefBH *s = opaque;
291
292     bdrv_unref(s->bs);
293     qemu_bh_delete(s->bh);
294     g_free(s);
295 }
296
297 /*
298  * Release a BDS reference in a BH
299  *
300  * It is not safe to use bdrv_unref() from a callback function when the callers
301  * still need the BlockDriverState.  In such cases we schedule a BH to release
302  * the reference.
303  */
304 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
305 {
306     BDRVPutRefBH *s;
307
308     s = g_new(BDRVPutRefBH, 1);
309     s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
310     s->bs = bs;
311     qemu_bh_schedule(s->bh);
312 }
313
314 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
315 {
316     if (!strcmp(buf, "ignore")) {
317         return BLOCKDEV_ON_ERROR_IGNORE;
318     } else if (!is_read && !strcmp(buf, "enospc")) {
319         return BLOCKDEV_ON_ERROR_ENOSPC;
320     } else if (!strcmp(buf, "stop")) {
321         return BLOCKDEV_ON_ERROR_STOP;
322     } else if (!strcmp(buf, "report")) {
323         return BLOCKDEV_ON_ERROR_REPORT;
324     } else {
325         error_setg(errp, "'%s' invalid %s error action",
326                    buf, is_read ? "read" : "write");
327         return -1;
328     }
329 }
330
331 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
332 {
333     if (throttle_conflicting(cfg)) {
334         error_setg(errp, "bps/iops/max total values and read/write values"
335                          " cannot be used at the same time");
336         return false;
337     }
338
339     if (!throttle_is_valid(cfg)) {
340         error_setg(errp, "bps/iops/maxs values must be 0 or greater");
341         return false;
342     }
343
344     return true;
345 }
346
347 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
348
349 /* Takes the ownership of bs_opts */
350 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
351                                    Error **errp)
352 {
353     const char *buf;
354     int ro = 0;
355     int bdrv_flags = 0;
356     int on_read_error, on_write_error;
357     BlockBackend *blk;
358     BlockDriverState *bs;
359     ThrottleConfig cfg;
360     int snapshot = 0;
361     bool copy_on_read;
362     Error *error = NULL;
363     QemuOpts *opts;
364     const char *id;
365     bool has_driver_specific_opts;
366     BlockdevDetectZeroesOptions detect_zeroes;
367     const char *throttling_group;
368
369     /* Check common options by copying from bs_opts to opts, all other options
370      * stay in bs_opts for processing by bdrv_open(). */
371     id = qdict_get_try_str(bs_opts, "id");
372     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
373     if (error) {
374         error_propagate(errp, error);
375         goto err_no_opts;
376     }
377
378     qemu_opts_absorb_qdict(opts, bs_opts, &error);
379     if (error) {
380         error_propagate(errp, error);
381         goto early_err;
382     }
383
384     if (id) {
385         qdict_del(bs_opts, "id");
386     }
387
388     has_driver_specific_opts = !!qdict_size(bs_opts);
389
390     /* extract parameters */
391     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
392     ro = qemu_opt_get_bool(opts, "read-only", 0);
393     copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
394
395     if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
396         if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
397             error_setg(errp, "invalid discard option");
398             goto early_err;
399         }
400     }
401
402     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true)) {
403         bdrv_flags |= BDRV_O_CACHE_WB;
404     }
405     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
406         bdrv_flags |= BDRV_O_NOCACHE;
407     }
408     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
409         bdrv_flags |= BDRV_O_NO_FLUSH;
410     }
411
412 #ifdef CONFIG_LINUX_AIO
413     if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
414         if (!strcmp(buf, "native")) {
415             bdrv_flags |= BDRV_O_NATIVE_AIO;
416         } else if (!strcmp(buf, "threads")) {
417             /* this is the default */
418         } else {
419            error_setg(errp, "invalid aio option");
420            goto early_err;
421         }
422     }
423 #endif
424
425     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
426         if (is_help_option(buf)) {
427             error_printf("Supported formats:");
428             bdrv_iterate_format(bdrv_format_print, NULL);
429             error_printf("\n");
430             goto early_err;
431         }
432
433         if (qdict_haskey(bs_opts, "driver")) {
434             error_setg(errp, "Cannot specify both 'driver' and 'format'");
435             goto early_err;
436         }
437         qdict_put(bs_opts, "driver", qstring_from_str(buf));
438     }
439
440     /* disk I/O throttling */
441     memset(&cfg, 0, sizeof(cfg));
442     cfg.buckets[THROTTLE_BPS_TOTAL].avg =
443         qemu_opt_get_number(opts, "throttling.bps-total", 0);
444     cfg.buckets[THROTTLE_BPS_READ].avg  =
445         qemu_opt_get_number(opts, "throttling.bps-read", 0);
446     cfg.buckets[THROTTLE_BPS_WRITE].avg =
447         qemu_opt_get_number(opts, "throttling.bps-write", 0);
448     cfg.buckets[THROTTLE_OPS_TOTAL].avg =
449         qemu_opt_get_number(opts, "throttling.iops-total", 0);
450     cfg.buckets[THROTTLE_OPS_READ].avg =
451         qemu_opt_get_number(opts, "throttling.iops-read", 0);
452     cfg.buckets[THROTTLE_OPS_WRITE].avg =
453         qemu_opt_get_number(opts, "throttling.iops-write", 0);
454
455     cfg.buckets[THROTTLE_BPS_TOTAL].max =
456         qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
457     cfg.buckets[THROTTLE_BPS_READ].max  =
458         qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
459     cfg.buckets[THROTTLE_BPS_WRITE].max =
460         qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
461     cfg.buckets[THROTTLE_OPS_TOTAL].max =
462         qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
463     cfg.buckets[THROTTLE_OPS_READ].max =
464         qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
465     cfg.buckets[THROTTLE_OPS_WRITE].max =
466         qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
467
468     cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
469
470     throttling_group = qemu_opt_get(opts, "throttling.group");
471
472     if (!check_throttle_config(&cfg, &error)) {
473         error_propagate(errp, error);
474         goto early_err;
475     }
476
477     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
478     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
479         on_write_error = parse_block_error_action(buf, 0, &error);
480         if (error) {
481             error_propagate(errp, error);
482             goto early_err;
483         }
484     }
485
486     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
487     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
488         on_read_error = parse_block_error_action(buf, 1, &error);
489         if (error) {
490             error_propagate(errp, error);
491             goto early_err;
492         }
493     }
494
495     detect_zeroes =
496         qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
497                         qemu_opt_get(opts, "detect-zeroes"),
498                         BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
499                         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
500                         &error);
501     if (error) {
502         error_propagate(errp, error);
503         goto early_err;
504     }
505
506     if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
507         !(bdrv_flags & BDRV_O_UNMAP)) {
508         error_setg(errp, "setting detect-zeroes to unmap is not allowed "
509                          "without setting discard operation to unmap");
510         goto early_err;
511     }
512
513     /* init */
514     if ((!file || !*file) && !has_driver_specific_opts) {
515         blk = blk_new_with_bs(qemu_opts_id(opts), errp);
516         if (!blk) {
517             goto early_err;
518         }
519
520         bs = blk_bs(blk);
521         bs->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
522         bs->read_only = ro;
523
524         QDECREF(bs_opts);
525     } else {
526         if (file && !*file) {
527             file = NULL;
528         }
529
530         if (snapshot) {
531             /* always use cache=unsafe with snapshot */
532             bdrv_flags &= ~BDRV_O_CACHE_MASK;
533             bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
534         }
535
536         if (copy_on_read) {
537             bdrv_flags |= BDRV_O_COPY_ON_READ;
538         }
539
540         if (runstate_check(RUN_STATE_INMIGRATE)) {
541             bdrv_flags |= BDRV_O_INCOMING;
542         }
543
544         bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
545
546         blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
547                            errp);
548         if (!blk) {
549             goto err_no_bs_opts;
550         }
551         bs = blk_bs(blk);
552     }
553
554     bs->detect_zeroes = detect_zeroes;
555
556     bdrv_set_on_error(bs, on_read_error, on_write_error);
557
558     /* disk I/O throttling */
559     if (throttle_enabled(&cfg)) {
560         if (!throttling_group) {
561             throttling_group = blk_name(blk);
562         }
563         bdrv_io_limits_enable(bs, throttling_group);
564         bdrv_set_io_limits(bs, &cfg);
565     }
566
567     if (bdrv_key_required(bs)) {
568         autostart = 0;
569     }
570
571 err_no_bs_opts:
572     qemu_opts_del(opts);
573     return blk;
574
575 early_err:
576     qemu_opts_del(opts);
577 err_no_opts:
578     QDECREF(bs_opts);
579     return NULL;
580 }
581
582 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
583                             Error **errp)
584 {
585     const char *value;
586
587     value = qemu_opt_get(opts, from);
588     if (value) {
589         if (qemu_opt_find(opts, to)) {
590             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
591                        "same time", to, from);
592             return;
593         }
594     }
595
596     /* rename all items in opts */
597     while ((value = qemu_opt_get(opts, from))) {
598         qemu_opt_set(opts, to, value, &error_abort);
599         qemu_opt_unset(opts, from);
600     }
601 }
602
603 QemuOptsList qemu_legacy_drive_opts = {
604     .name = "drive",
605     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
606     .desc = {
607         {
608             .name = "bus",
609             .type = QEMU_OPT_NUMBER,
610             .help = "bus number",
611         },{
612             .name = "unit",
613             .type = QEMU_OPT_NUMBER,
614             .help = "unit number (i.e. lun for scsi)",
615         },{
616             .name = "index",
617             .type = QEMU_OPT_NUMBER,
618             .help = "index number",
619         },{
620             .name = "media",
621             .type = QEMU_OPT_STRING,
622             .help = "media type (disk, cdrom)",
623         },{
624             .name = "if",
625             .type = QEMU_OPT_STRING,
626             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
627         },{
628             .name = "cyls",
629             .type = QEMU_OPT_NUMBER,
630             .help = "number of cylinders (ide disk geometry)",
631         },{
632             .name = "heads",
633             .type = QEMU_OPT_NUMBER,
634             .help = "number of heads (ide disk geometry)",
635         },{
636             .name = "secs",
637             .type = QEMU_OPT_NUMBER,
638             .help = "number of sectors (ide disk geometry)",
639         },{
640             .name = "trans",
641             .type = QEMU_OPT_STRING,
642             .help = "chs translation (auto, lba, none)",
643         },{
644             .name = "boot",
645             .type = QEMU_OPT_BOOL,
646             .help = "(deprecated, ignored)",
647         },{
648             .name = "addr",
649             .type = QEMU_OPT_STRING,
650             .help = "pci address (virtio only)",
651         },{
652             .name = "serial",
653             .type = QEMU_OPT_STRING,
654             .help = "disk serial number",
655         },{
656             .name = "file",
657             .type = QEMU_OPT_STRING,
658             .help = "file name",
659         },
660
661         /* Options that are passed on, but have special semantics with -drive */
662         {
663             .name = "read-only",
664             .type = QEMU_OPT_BOOL,
665             .help = "open drive file as read-only",
666         },{
667             .name = "rerror",
668             .type = QEMU_OPT_STRING,
669             .help = "read error action",
670         },{
671             .name = "werror",
672             .type = QEMU_OPT_STRING,
673             .help = "write error action",
674         },{
675             .name = "copy-on-read",
676             .type = QEMU_OPT_BOOL,
677             .help = "copy read data from backing file into image file",
678         },
679
680         { /* end of list */ }
681     },
682 };
683
684 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
685 {
686     const char *value;
687     BlockBackend *blk;
688     DriveInfo *dinfo = NULL;
689     QDict *bs_opts;
690     QemuOpts *legacy_opts;
691     DriveMediaType media = MEDIA_DISK;
692     BlockInterfaceType type;
693     int cyls, heads, secs, translation;
694     int max_devs, bus_id, unit_id, index;
695     const char *devaddr;
696     const char *werror, *rerror;
697     bool read_only = false;
698     bool copy_on_read;
699     const char *serial;
700     const char *filename;
701     Error *local_err = NULL;
702     int i;
703
704     /* Change legacy command line options into QMP ones */
705     static const struct {
706         const char *from;
707         const char *to;
708     } opt_renames[] = {
709         { "iops",           "throttling.iops-total" },
710         { "iops_rd",        "throttling.iops-read" },
711         { "iops_wr",        "throttling.iops-write" },
712
713         { "bps",            "throttling.bps-total" },
714         { "bps_rd",         "throttling.bps-read" },
715         { "bps_wr",         "throttling.bps-write" },
716
717         { "iops_max",       "throttling.iops-total-max" },
718         { "iops_rd_max",    "throttling.iops-read-max" },
719         { "iops_wr_max",    "throttling.iops-write-max" },
720
721         { "bps_max",        "throttling.bps-total-max" },
722         { "bps_rd_max",     "throttling.bps-read-max" },
723         { "bps_wr_max",     "throttling.bps-write-max" },
724
725         { "iops_size",      "throttling.iops-size" },
726
727         { "group",          "throttling.group" },
728
729         { "readonly",       "read-only" },
730     };
731
732     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
733         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
734                         &local_err);
735         if (local_err) {
736             error_report_err(local_err);
737             return NULL;
738         }
739     }
740
741     value = qemu_opt_get(all_opts, "cache");
742     if (value) {
743         int flags = 0;
744
745         if (bdrv_parse_cache_flags(value, &flags) != 0) {
746             error_report("invalid cache option");
747             return NULL;
748         }
749
750         /* Specific options take precedence */
751         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
752             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
753                               !!(flags & BDRV_O_CACHE_WB), &error_abort);
754         }
755         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
756             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
757                               !!(flags & BDRV_O_NOCACHE), &error_abort);
758         }
759         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
760             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
761                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
762         }
763         qemu_opt_unset(all_opts, "cache");
764     }
765
766     /* Get a QDict for processing the options */
767     bs_opts = qdict_new();
768     qemu_opts_to_qdict(all_opts, bs_opts);
769
770     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
771                                    &error_abort);
772     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
773     if (local_err) {
774         error_report_err(local_err);
775         goto fail;
776     }
777
778     /* Deprecated option boot=[on|off] */
779     if (qemu_opt_get(legacy_opts, "boot") != NULL) {
780         fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
781                 "ignored. Future versions will reject this parameter. Please "
782                 "update your scripts.\n");
783     }
784
785     /* Media type */
786     value = qemu_opt_get(legacy_opts, "media");
787     if (value) {
788         if (!strcmp(value, "disk")) {
789             media = MEDIA_DISK;
790         } else if (!strcmp(value, "cdrom")) {
791             media = MEDIA_CDROM;
792             read_only = true;
793         } else {
794             error_report("'%s' invalid media", value);
795             goto fail;
796         }
797     }
798
799     /* copy-on-read is disabled with a warning for read-only devices */
800     read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
801     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
802
803     if (read_only && copy_on_read) {
804         error_report("warning: disabling copy-on-read on read-only drive");
805         copy_on_read = false;
806     }
807
808     qdict_put(bs_opts, "read-only",
809               qstring_from_str(read_only ? "on" : "off"));
810     qdict_put(bs_opts, "copy-on-read",
811               qstring_from_str(copy_on_read ? "on" :"off"));
812
813     /* Controller type */
814     value = qemu_opt_get(legacy_opts, "if");
815     if (value) {
816         for (type = 0;
817              type < IF_COUNT && strcmp(value, if_name[type]);
818              type++) {
819         }
820         if (type == IF_COUNT) {
821             error_report("unsupported bus type '%s'", value);
822             goto fail;
823         }
824     } else {
825         type = block_default_type;
826     }
827
828     /* Geometry */
829     cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
830     heads = qemu_opt_get_number(legacy_opts, "heads", 0);
831     secs  = qemu_opt_get_number(legacy_opts, "secs", 0);
832
833     if (cyls || heads || secs) {
834         if (cyls < 1) {
835             error_report("invalid physical cyls number");
836             goto fail;
837         }
838         if (heads < 1) {
839             error_report("invalid physical heads number");
840             goto fail;
841         }
842         if (secs < 1) {
843             error_report("invalid physical secs number");
844             goto fail;
845         }
846     }
847
848     translation = BIOS_ATA_TRANSLATION_AUTO;
849     value = qemu_opt_get(legacy_opts, "trans");
850     if (value != NULL) {
851         if (!cyls) {
852             error_report("'%s' trans must be used with cyls, heads and secs",
853                          value);
854             goto fail;
855         }
856         if (!strcmp(value, "none")) {
857             translation = BIOS_ATA_TRANSLATION_NONE;
858         } else if (!strcmp(value, "lba")) {
859             translation = BIOS_ATA_TRANSLATION_LBA;
860         } else if (!strcmp(value, "large")) {
861             translation = BIOS_ATA_TRANSLATION_LARGE;
862         } else if (!strcmp(value, "rechs")) {
863             translation = BIOS_ATA_TRANSLATION_RECHS;
864         } else if (!strcmp(value, "auto")) {
865             translation = BIOS_ATA_TRANSLATION_AUTO;
866         } else {
867             error_report("'%s' invalid translation type", value);
868             goto fail;
869         }
870     }
871
872     if (media == MEDIA_CDROM) {
873         if (cyls || secs || heads) {
874             error_report("CHS can't be set with media=cdrom");
875             goto fail;
876         }
877     }
878
879     /* Device address specified by bus/unit or index.
880      * If none was specified, try to find the first free one. */
881     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
882     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
883     index   = qemu_opt_get_number(legacy_opts, "index", -1);
884
885     max_devs = if_max_devs[type];
886
887     if (index != -1) {
888         if (bus_id != 0 || unit_id != -1) {
889             error_report("index cannot be used with bus and unit");
890             goto fail;
891         }
892         bus_id = drive_index_to_bus_id(type, index);
893         unit_id = drive_index_to_unit_id(type, index);
894     }
895
896     if (unit_id == -1) {
897        unit_id = 0;
898        while (drive_get(type, bus_id, unit_id) != NULL) {
899            unit_id++;
900            if (max_devs && unit_id >= max_devs) {
901                unit_id -= max_devs;
902                bus_id++;
903            }
904        }
905     }
906
907     if (max_devs && unit_id >= max_devs) {
908         error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
909         goto fail;
910     }
911
912     if (drive_get(type, bus_id, unit_id) != NULL) {
913         error_report("drive with bus=%d, unit=%d (index=%d) exists",
914                      bus_id, unit_id, index);
915         goto fail;
916     }
917
918     /* Serial number */
919     serial = qemu_opt_get(legacy_opts, "serial");
920
921     /* no id supplied -> create one */
922     if (qemu_opts_id(all_opts) == NULL) {
923         char *new_id;
924         const char *mediastr = "";
925         if (type == IF_IDE || type == IF_SCSI) {
926             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
927         }
928         if (max_devs) {
929             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
930                                      mediastr, unit_id);
931         } else {
932             new_id = g_strdup_printf("%s%s%i", if_name[type],
933                                      mediastr, unit_id);
934         }
935         qdict_put(bs_opts, "id", qstring_from_str(new_id));
936         g_free(new_id);
937     }
938
939     /* Add virtio block device */
940     devaddr = qemu_opt_get(legacy_opts, "addr");
941     if (devaddr && type != IF_VIRTIO) {
942         error_report("addr is not supported by this bus type");
943         goto fail;
944     }
945
946     if (type == IF_VIRTIO) {
947         QemuOpts *devopts;
948         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
949                                    &error_abort);
950         if (arch_type == QEMU_ARCH_S390X) {
951             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
952         } else {
953             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
954         }
955         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
956                      &error_abort);
957         if (devaddr) {
958             qemu_opt_set(devopts, "addr", devaddr, &error_abort);
959         }
960     }
961
962     filename = qemu_opt_get(legacy_opts, "file");
963
964     /* Check werror/rerror compatibility with if=... */
965     werror = qemu_opt_get(legacy_opts, "werror");
966     if (werror != NULL) {
967         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
968             type != IF_NONE) {
969             error_report("werror is not supported by this bus type");
970             goto fail;
971         }
972         qdict_put(bs_opts, "werror", qstring_from_str(werror));
973     }
974
975     rerror = qemu_opt_get(legacy_opts, "rerror");
976     if (rerror != NULL) {
977         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
978             type != IF_NONE) {
979             error_report("rerror is not supported by this bus type");
980             goto fail;
981         }
982         qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
983     }
984
985     /* Actual block device init: Functionality shared with blockdev-add */
986     blk = blockdev_init(filename, bs_opts, &local_err);
987     bs_opts = NULL;
988     if (!blk) {
989         if (local_err) {
990             error_report_err(local_err);
991         }
992         goto fail;
993     } else {
994         assert(!local_err);
995     }
996
997     /* Create legacy DriveInfo */
998     dinfo = g_malloc0(sizeof(*dinfo));
999     dinfo->opts = all_opts;
1000
1001     dinfo->cyls = cyls;
1002     dinfo->heads = heads;
1003     dinfo->secs = secs;
1004     dinfo->trans = translation;
1005
1006     dinfo->type = type;
1007     dinfo->bus = bus_id;
1008     dinfo->unit = unit_id;
1009     dinfo->devaddr = devaddr;
1010     dinfo->serial = g_strdup(serial);
1011
1012     blk_set_legacy_dinfo(blk, dinfo);
1013
1014     switch(type) {
1015     case IF_IDE:
1016     case IF_SCSI:
1017     case IF_XEN:
1018     case IF_NONE:
1019         dinfo->media_cd = media == MEDIA_CDROM;
1020         break;
1021     default:
1022         break;
1023     }
1024
1025 fail:
1026     qemu_opts_del(legacy_opts);
1027     QDECREF(bs_opts);
1028     return dinfo;
1029 }
1030
1031 void hmp_commit(Monitor *mon, const QDict *qdict)
1032 {
1033     const char *device = qdict_get_str(qdict, "device");
1034     BlockBackend *blk;
1035     int ret;
1036
1037     if (!strcmp(device, "all")) {
1038         ret = bdrv_commit_all();
1039     } else {
1040         blk = blk_by_name(device);
1041         if (!blk) {
1042             monitor_printf(mon, "Device '%s' not found\n", device);
1043             return;
1044         }
1045         ret = bdrv_commit(blk_bs(blk));
1046     }
1047     if (ret < 0) {
1048         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1049                        strerror(-ret));
1050     }
1051 }
1052
1053 static void blockdev_do_action(int kind, void *data, Error **errp)
1054 {
1055     TransactionAction action;
1056     TransactionActionList list;
1057
1058     action.kind = kind;
1059     action.data = data;
1060     list.value = &action;
1061     list.next = NULL;
1062     qmp_transaction(&list, errp);
1063 }
1064
1065 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1066                                 bool has_node_name, const char *node_name,
1067                                 const char *snapshot_file,
1068                                 bool has_snapshot_node_name,
1069                                 const char *snapshot_node_name,
1070                                 bool has_format, const char *format,
1071                                 bool has_mode, NewImageMode mode, Error **errp)
1072 {
1073     BlockdevSnapshot snapshot = {
1074         .has_device = has_device,
1075         .device = (char *) device,
1076         .has_node_name = has_node_name,
1077         .node_name = (char *) node_name,
1078         .snapshot_file = (char *) snapshot_file,
1079         .has_snapshot_node_name = has_snapshot_node_name,
1080         .snapshot_node_name = (char *) snapshot_node_name,
1081         .has_format = has_format,
1082         .format = (char *) format,
1083         .has_mode = has_mode,
1084         .mode = mode,
1085     };
1086     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1087                        &snapshot, errp);
1088 }
1089
1090 void qmp_blockdev_snapshot_internal_sync(const char *device,
1091                                          const char *name,
1092                                          Error **errp)
1093 {
1094     BlockdevSnapshotInternal snapshot = {
1095         .device = (char *) device,
1096         .name = (char *) name
1097     };
1098
1099     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1100                        &snapshot, errp);
1101 }
1102
1103 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1104                                                          bool has_id,
1105                                                          const char *id,
1106                                                          bool has_name,
1107                                                          const char *name,
1108                                                          Error **errp)
1109 {
1110     BlockDriverState *bs;
1111     BlockBackend *blk;
1112     AioContext *aio_context;
1113     QEMUSnapshotInfo sn;
1114     Error *local_err = NULL;
1115     SnapshotInfo *info = NULL;
1116     int ret;
1117
1118     blk = blk_by_name(device);
1119     if (!blk) {
1120         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1121                   "Device '%s' not found", device);
1122         return NULL;
1123     }
1124     bs = blk_bs(blk);
1125
1126     if (!has_id) {
1127         id = NULL;
1128     }
1129
1130     if (!has_name) {
1131         name = NULL;
1132     }
1133
1134     if (!id && !name) {
1135         error_setg(errp, "Name or id must be provided");
1136         return NULL;
1137     }
1138
1139     aio_context = bdrv_get_aio_context(bs);
1140     aio_context_acquire(aio_context);
1141
1142     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1143         goto out_aio_context;
1144     }
1145
1146     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1147     if (local_err) {
1148         error_propagate(errp, local_err);
1149         goto out_aio_context;
1150     }
1151     if (!ret) {
1152         error_setg(errp,
1153                    "Snapshot with id '%s' and name '%s' does not exist on "
1154                    "device '%s'",
1155                    STR_OR_NULL(id), STR_OR_NULL(name), device);
1156         goto out_aio_context;
1157     }
1158
1159     bdrv_snapshot_delete(bs, id, name, &local_err);
1160     if (local_err) {
1161         error_propagate(errp, local_err);
1162         goto out_aio_context;
1163     }
1164
1165     aio_context_release(aio_context);
1166
1167     info = g_new0(SnapshotInfo, 1);
1168     info->id = g_strdup(sn.id_str);
1169     info->name = g_strdup(sn.name);
1170     info->date_nsec = sn.date_nsec;
1171     info->date_sec = sn.date_sec;
1172     info->vm_state_size = sn.vm_state_size;
1173     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1174     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1175
1176     return info;
1177
1178 out_aio_context:
1179     aio_context_release(aio_context);
1180     return NULL;
1181 }
1182
1183 /**
1184  * block_dirty_bitmap_lookup:
1185  * Return a dirty bitmap (if present), after validating
1186  * the node reference and bitmap names.
1187  *
1188  * @node: The name of the BDS node to search for bitmaps
1189  * @name: The name of the bitmap to search for
1190  * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1191  * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1192  * @errp: Output pointer for error information. Can be NULL.
1193  *
1194  * @return: A bitmap object on success, or NULL on failure.
1195  */
1196 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1197                                                   const char *name,
1198                                                   BlockDriverState **pbs,
1199                                                   AioContext **paio,
1200                                                   Error **errp)
1201 {
1202     BlockDriverState *bs;
1203     BdrvDirtyBitmap *bitmap;
1204     AioContext *aio_context;
1205
1206     if (!node) {
1207         error_setg(errp, "Node cannot be NULL");
1208         return NULL;
1209     }
1210     if (!name) {
1211         error_setg(errp, "Bitmap name cannot be NULL");
1212         return NULL;
1213     }
1214     bs = bdrv_lookup_bs(node, node, NULL);
1215     if (!bs) {
1216         error_setg(errp, "Node '%s' not found", node);
1217         return NULL;
1218     }
1219
1220     aio_context = bdrv_get_aio_context(bs);
1221     aio_context_acquire(aio_context);
1222
1223     bitmap = bdrv_find_dirty_bitmap(bs, name);
1224     if (!bitmap) {
1225         error_setg(errp, "Dirty bitmap '%s' not found", name);
1226         goto fail;
1227     }
1228
1229     if (pbs) {
1230         *pbs = bs;
1231     }
1232     if (paio) {
1233         *paio = aio_context;
1234     } else {
1235         aio_context_release(aio_context);
1236     }
1237
1238     return bitmap;
1239
1240  fail:
1241     aio_context_release(aio_context);
1242     return NULL;
1243 }
1244
1245 /* New and old BlockDriverState structs for atomic group operations */
1246
1247 typedef struct BlkTransactionState BlkTransactionState;
1248
1249 /* Only prepare() may fail. In a single transaction, only one of commit() or
1250    abort() will be called, clean() will always be called if it present. */
1251 typedef struct BdrvActionOps {
1252     /* Size of state struct, in bytes. */
1253     size_t instance_size;
1254     /* Prepare the work, must NOT be NULL. */
1255     void (*prepare)(BlkTransactionState *common, Error **errp);
1256     /* Commit the changes, can be NULL. */
1257     void (*commit)(BlkTransactionState *common);
1258     /* Abort the changes on fail, can be NULL. */
1259     void (*abort)(BlkTransactionState *common);
1260     /* Clean up resource in the end, can be NULL. */
1261     void (*clean)(BlkTransactionState *common);
1262 } BdrvActionOps;
1263
1264 /*
1265  * This structure must be arranged as first member in child type, assuming
1266  * that compiler will also arrange it to the same address with parent instance.
1267  * Later it will be used in free().
1268  */
1269 struct BlkTransactionState {
1270     TransactionAction *action;
1271     const BdrvActionOps *ops;
1272     QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1273 };
1274
1275 /* internal snapshot private data */
1276 typedef struct InternalSnapshotState {
1277     BlkTransactionState common;
1278     BlockDriverState *bs;
1279     AioContext *aio_context;
1280     QEMUSnapshotInfo sn;
1281 } InternalSnapshotState;
1282
1283 static void internal_snapshot_prepare(BlkTransactionState *common,
1284                                       Error **errp)
1285 {
1286     Error *local_err = NULL;
1287     const char *device;
1288     const char *name;
1289     BlockBackend *blk;
1290     BlockDriverState *bs;
1291     QEMUSnapshotInfo old_sn, *sn;
1292     bool ret;
1293     qemu_timeval tv;
1294     BlockdevSnapshotInternal *internal;
1295     InternalSnapshotState *state;
1296     int ret1;
1297
1298     g_assert(common->action->kind ==
1299              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1300     internal = common->action->blockdev_snapshot_internal_sync;
1301     state = DO_UPCAST(InternalSnapshotState, common, common);
1302
1303     /* 1. parse input */
1304     device = internal->device;
1305     name = internal->name;
1306
1307     /* 2. check for validation */
1308     blk = blk_by_name(device);
1309     if (!blk) {
1310         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1311                   "Device '%s' not found", device);
1312         return;
1313     }
1314     bs = blk_bs(blk);
1315
1316     /* AioContext is released in .clean() */
1317     state->aio_context = bdrv_get_aio_context(bs);
1318     aio_context_acquire(state->aio_context);
1319
1320     if (!bdrv_is_inserted(bs)) {
1321         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1322         return;
1323     }
1324
1325     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1326         return;
1327     }
1328
1329     if (bdrv_is_read_only(bs)) {
1330         error_setg(errp, "Device '%s' is read only", device);
1331         return;
1332     }
1333
1334     if (!bdrv_can_snapshot(bs)) {
1335         error_setg(errp, "Block format '%s' used by device '%s' "
1336                    "does not support internal snapshots",
1337                    bs->drv->format_name, device);
1338         return;
1339     }
1340
1341     if (!strlen(name)) {
1342         error_setg(errp, "Name is empty");
1343         return;
1344     }
1345
1346     /* check whether a snapshot with name exist */
1347     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1348                                             &local_err);
1349     if (local_err) {
1350         error_propagate(errp, local_err);
1351         return;
1352     } else if (ret) {
1353         error_setg(errp,
1354                    "Snapshot with name '%s' already exists on device '%s'",
1355                    name, device);
1356         return;
1357     }
1358
1359     /* 3. take the snapshot */
1360     sn = &state->sn;
1361     pstrcpy(sn->name, sizeof(sn->name), name);
1362     qemu_gettimeofday(&tv);
1363     sn->date_sec = tv.tv_sec;
1364     sn->date_nsec = tv.tv_usec * 1000;
1365     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1366
1367     ret1 = bdrv_snapshot_create(bs, sn);
1368     if (ret1 < 0) {
1369         error_setg_errno(errp, -ret1,
1370                          "Failed to create snapshot '%s' on device '%s'",
1371                          name, device);
1372         return;
1373     }
1374
1375     /* 4. succeed, mark a snapshot is created */
1376     state->bs = bs;
1377 }
1378
1379 static void internal_snapshot_abort(BlkTransactionState *common)
1380 {
1381     InternalSnapshotState *state =
1382                              DO_UPCAST(InternalSnapshotState, common, common);
1383     BlockDriverState *bs = state->bs;
1384     QEMUSnapshotInfo *sn = &state->sn;
1385     Error *local_error = NULL;
1386
1387     if (!bs) {
1388         return;
1389     }
1390
1391     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1392         error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1393                      "device '%s' in abort: %s",
1394                      sn->id_str,
1395                      sn->name,
1396                      bdrv_get_device_name(bs),
1397                      error_get_pretty(local_error));
1398         error_free(local_error);
1399     }
1400 }
1401
1402 static void internal_snapshot_clean(BlkTransactionState *common)
1403 {
1404     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1405                                              common, common);
1406
1407     if (state->aio_context) {
1408         aio_context_release(state->aio_context);
1409     }
1410 }
1411
1412 /* external snapshot private data */
1413 typedef struct ExternalSnapshotState {
1414     BlkTransactionState common;
1415     BlockDriverState *old_bs;
1416     BlockDriverState *new_bs;
1417     AioContext *aio_context;
1418 } ExternalSnapshotState;
1419
1420 static void external_snapshot_prepare(BlkTransactionState *common,
1421                                       Error **errp)
1422 {
1423     BlockDriver *drv;
1424     int flags, ret;
1425     QDict *options = NULL;
1426     Error *local_err = NULL;
1427     bool has_device = false;
1428     const char *device;
1429     bool has_node_name = false;
1430     const char *node_name;
1431     bool has_snapshot_node_name = false;
1432     const char *snapshot_node_name;
1433     const char *new_image_file;
1434     const char *format = "qcow2";
1435     enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1436     ExternalSnapshotState *state =
1437                              DO_UPCAST(ExternalSnapshotState, common, common);
1438     TransactionAction *action = common->action;
1439
1440     /* get parameters */
1441     g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1442
1443     has_device = action->blockdev_snapshot_sync->has_device;
1444     device = action->blockdev_snapshot_sync->device;
1445     has_node_name = action->blockdev_snapshot_sync->has_node_name;
1446     node_name = action->blockdev_snapshot_sync->node_name;
1447     has_snapshot_node_name =
1448         action->blockdev_snapshot_sync->has_snapshot_node_name;
1449     snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1450
1451     new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1452     if (action->blockdev_snapshot_sync->has_format) {
1453         format = action->blockdev_snapshot_sync->format;
1454     }
1455     if (action->blockdev_snapshot_sync->has_mode) {
1456         mode = action->blockdev_snapshot_sync->mode;
1457     }
1458
1459     /* start processing */
1460     drv = bdrv_find_format(format);
1461     if (!drv) {
1462         error_setg(errp, QERR_INVALID_BLOCK_FORMAT, format);
1463         return;
1464     }
1465
1466     state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1467                                    has_node_name ? node_name : NULL,
1468                                    &local_err);
1469     if (local_err) {
1470         error_propagate(errp, local_err);
1471         return;
1472     }
1473
1474     if (has_node_name && !has_snapshot_node_name) {
1475         error_setg(errp, "New snapshot node name missing");
1476         return;
1477     }
1478
1479     if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1480         error_setg(errp, "New snapshot node name already existing");
1481         return;
1482     }
1483
1484     /* Acquire AioContext now so any threads operating on old_bs stop */
1485     state->aio_context = bdrv_get_aio_context(state->old_bs);
1486     aio_context_acquire(state->aio_context);
1487
1488     if (!bdrv_is_inserted(state->old_bs)) {
1489         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1490         return;
1491     }
1492
1493     if (bdrv_op_is_blocked(state->old_bs,
1494                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1495         return;
1496     }
1497
1498     if (!bdrv_is_read_only(state->old_bs)) {
1499         if (bdrv_flush(state->old_bs)) {
1500             error_setg(errp, QERR_IO_ERROR);
1501             return;
1502         }
1503     }
1504
1505     if (!bdrv_is_first_non_filter(state->old_bs)) {
1506         error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1507         return;
1508     }
1509
1510     flags = state->old_bs->open_flags;
1511
1512     /* create new image w/backing file */
1513     if (mode != NEW_IMAGE_MODE_EXISTING) {
1514         bdrv_img_create(new_image_file, format,
1515                         state->old_bs->filename,
1516                         state->old_bs->drv->format_name,
1517                         NULL, -1, flags, &local_err, false);
1518         if (local_err) {
1519             error_propagate(errp, local_err);
1520             return;
1521         }
1522     }
1523
1524     if (has_snapshot_node_name) {
1525         options = qdict_new();
1526         qdict_put(options, "node-name",
1527                   qstring_from_str(snapshot_node_name));
1528     }
1529
1530     /* TODO Inherit bs->options or only take explicit options with an
1531      * extended QMP command? */
1532     assert(state->new_bs == NULL);
1533     ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1534                     flags | BDRV_O_NO_BACKING, drv, &local_err);
1535     /* We will manually add the backing_hd field to the bs later */
1536     if (ret != 0) {
1537         error_propagate(errp, local_err);
1538     }
1539 }
1540
1541 static void external_snapshot_commit(BlkTransactionState *common)
1542 {
1543     ExternalSnapshotState *state =
1544                              DO_UPCAST(ExternalSnapshotState, common, common);
1545
1546     bdrv_set_aio_context(state->new_bs, state->aio_context);
1547
1548     /* This removes our old bs and adds the new bs */
1549     bdrv_append(state->new_bs, state->old_bs);
1550     /* We don't need (or want) to use the transactional
1551      * bdrv_reopen_multiple() across all the entries at once, because we
1552      * don't want to abort all of them if one of them fails the reopen */
1553     bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1554                 NULL);
1555
1556     aio_context_release(state->aio_context);
1557 }
1558
1559 static void external_snapshot_abort(BlkTransactionState *common)
1560 {
1561     ExternalSnapshotState *state =
1562                              DO_UPCAST(ExternalSnapshotState, common, common);
1563     if (state->new_bs) {
1564         bdrv_unref(state->new_bs);
1565     }
1566     if (state->aio_context) {
1567         aio_context_release(state->aio_context);
1568     }
1569 }
1570
1571 typedef struct DriveBackupState {
1572     BlkTransactionState common;
1573     BlockDriverState *bs;
1574     AioContext *aio_context;
1575     BlockJob *job;
1576 } DriveBackupState;
1577
1578 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1579 {
1580     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1581     BlockDriverState *bs;
1582     BlockBackend *blk;
1583     DriveBackup *backup;
1584     Error *local_err = NULL;
1585
1586     assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1587     backup = common->action->drive_backup;
1588
1589     blk = blk_by_name(backup->device);
1590     if (!blk) {
1591         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1592                   "Device '%s' not found", backup->device);
1593         return;
1594     }
1595     bs = blk_bs(blk);
1596
1597     /* AioContext is released in .clean() */
1598     state->aio_context = bdrv_get_aio_context(bs);
1599     aio_context_acquire(state->aio_context);
1600
1601     qmp_drive_backup(backup->device, backup->target,
1602                      backup->has_format, backup->format,
1603                      backup->sync,
1604                      backup->has_mode, backup->mode,
1605                      backup->has_speed, backup->speed,
1606                      backup->has_bitmap, backup->bitmap,
1607                      backup->has_on_source_error, backup->on_source_error,
1608                      backup->has_on_target_error, backup->on_target_error,
1609                      &local_err);
1610     if (local_err) {
1611         error_propagate(errp, local_err);
1612         return;
1613     }
1614
1615     state->bs = bs;
1616     state->job = state->bs->job;
1617 }
1618
1619 static void drive_backup_abort(BlkTransactionState *common)
1620 {
1621     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1622     BlockDriverState *bs = state->bs;
1623
1624     /* Only cancel if it's the job we started */
1625     if (bs && bs->job && bs->job == state->job) {
1626         block_job_cancel_sync(bs->job);
1627     }
1628 }
1629
1630 static void drive_backup_clean(BlkTransactionState *common)
1631 {
1632     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1633
1634     if (state->aio_context) {
1635         aio_context_release(state->aio_context);
1636     }
1637 }
1638
1639 typedef struct BlockdevBackupState {
1640     BlkTransactionState common;
1641     BlockDriverState *bs;
1642     BlockJob *job;
1643     AioContext *aio_context;
1644 } BlockdevBackupState;
1645
1646 static void blockdev_backup_prepare(BlkTransactionState *common, Error **errp)
1647 {
1648     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1649     BlockdevBackup *backup;
1650     BlockDriverState *bs, *target;
1651     BlockBackend *blk;
1652     Error *local_err = NULL;
1653
1654     assert(common->action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1655     backup = common->action->blockdev_backup;
1656
1657     blk = blk_by_name(backup->device);
1658     if (!blk) {
1659         error_setg(errp, "Device '%s' not found", backup->device);
1660         return;
1661     }
1662     bs = blk_bs(blk);
1663
1664     blk = blk_by_name(backup->target);
1665     if (!blk) {
1666         error_setg(errp, "Device '%s' not found", backup->target);
1667         return;
1668     }
1669     target = blk_bs(blk);
1670
1671     /* AioContext is released in .clean() */
1672     state->aio_context = bdrv_get_aio_context(bs);
1673     if (state->aio_context != bdrv_get_aio_context(target)) {
1674         state->aio_context = NULL;
1675         error_setg(errp, "Backup between two IO threads is not implemented");
1676         return;
1677     }
1678     aio_context_acquire(state->aio_context);
1679
1680     qmp_blockdev_backup(backup->device, backup->target,
1681                         backup->sync,
1682                         backup->has_speed, backup->speed,
1683                         backup->has_on_source_error, backup->on_source_error,
1684                         backup->has_on_target_error, backup->on_target_error,
1685                         &local_err);
1686     if (local_err) {
1687         error_propagate(errp, local_err);
1688         return;
1689     }
1690
1691     state->bs = bs;
1692     state->job = state->bs->job;
1693 }
1694
1695 static void blockdev_backup_abort(BlkTransactionState *common)
1696 {
1697     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1698     BlockDriverState *bs = state->bs;
1699
1700     /* Only cancel if it's the job we started */
1701     if (bs && bs->job && bs->job == state->job) {
1702         block_job_cancel_sync(bs->job);
1703     }
1704 }
1705
1706 static void blockdev_backup_clean(BlkTransactionState *common)
1707 {
1708     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1709
1710     if (state->aio_context) {
1711         aio_context_release(state->aio_context);
1712     }
1713 }
1714
1715 static void abort_prepare(BlkTransactionState *common, Error **errp)
1716 {
1717     error_setg(errp, "Transaction aborted using Abort action");
1718 }
1719
1720 static void abort_commit(BlkTransactionState *common)
1721 {
1722     g_assert_not_reached(); /* this action never succeeds */
1723 }
1724
1725 static const BdrvActionOps actions[] = {
1726     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1727         .instance_size = sizeof(ExternalSnapshotState),
1728         .prepare  = external_snapshot_prepare,
1729         .commit   = external_snapshot_commit,
1730         .abort = external_snapshot_abort,
1731     },
1732     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1733         .instance_size = sizeof(DriveBackupState),
1734         .prepare = drive_backup_prepare,
1735         .abort = drive_backup_abort,
1736         .clean = drive_backup_clean,
1737     },
1738     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
1739         .instance_size = sizeof(BlockdevBackupState),
1740         .prepare = blockdev_backup_prepare,
1741         .abort = blockdev_backup_abort,
1742         .clean = blockdev_backup_clean,
1743     },
1744     [TRANSACTION_ACTION_KIND_ABORT] = {
1745         .instance_size = sizeof(BlkTransactionState),
1746         .prepare = abort_prepare,
1747         .commit = abort_commit,
1748     },
1749     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1750         .instance_size = sizeof(InternalSnapshotState),
1751         .prepare  = internal_snapshot_prepare,
1752         .abort = internal_snapshot_abort,
1753         .clean = internal_snapshot_clean,
1754     },
1755 };
1756
1757 /*
1758  * 'Atomic' group operations.  The operations are performed as a set, and if
1759  * any fail then we roll back all operations in the group.
1760  */
1761 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1762 {
1763     TransactionActionList *dev_entry = dev_list;
1764     BlkTransactionState *state, *next;
1765     Error *local_err = NULL;
1766
1767     QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1768     QSIMPLEQ_INIT(&snap_bdrv_states);
1769
1770     /* drain all i/o before any operations */
1771     bdrv_drain_all();
1772
1773     /* We don't do anything in this loop that commits us to the operations */
1774     while (NULL != dev_entry) {
1775         TransactionAction *dev_info = NULL;
1776         const BdrvActionOps *ops;
1777
1778         dev_info = dev_entry->value;
1779         dev_entry = dev_entry->next;
1780
1781         assert(dev_info->kind < ARRAY_SIZE(actions));
1782
1783         ops = &actions[dev_info->kind];
1784         assert(ops->instance_size > 0);
1785
1786         state = g_malloc0(ops->instance_size);
1787         state->ops = ops;
1788         state->action = dev_info;
1789         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1790
1791         state->ops->prepare(state, &local_err);
1792         if (local_err) {
1793             error_propagate(errp, local_err);
1794             goto delete_and_fail;
1795         }
1796     }
1797
1798     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1799         if (state->ops->commit) {
1800             state->ops->commit(state);
1801         }
1802     }
1803
1804     /* success */
1805     goto exit;
1806
1807 delete_and_fail:
1808     /* failure, and it is all-or-none; roll back all operations */
1809     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1810         if (state->ops->abort) {
1811             state->ops->abort(state);
1812         }
1813     }
1814 exit:
1815     QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1816         if (state->ops->clean) {
1817             state->ops->clean(state);
1818         }
1819         g_free(state);
1820     }
1821 }
1822
1823
1824 static void eject_device(BlockBackend *blk, int force, Error **errp)
1825 {
1826     BlockDriverState *bs = blk_bs(blk);
1827     AioContext *aio_context;
1828
1829     aio_context = bdrv_get_aio_context(bs);
1830     aio_context_acquire(aio_context);
1831
1832     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1833         goto out;
1834     }
1835     if (!blk_dev_has_removable_media(blk)) {
1836         error_setg(errp, "Device '%s' is not removable",
1837                    bdrv_get_device_name(bs));
1838         goto out;
1839     }
1840
1841     if (blk_dev_is_medium_locked(blk) && !blk_dev_is_tray_open(blk)) {
1842         blk_dev_eject_request(blk, force);
1843         if (!force) {
1844             error_setg(errp, "Device '%s' is locked",
1845                        bdrv_get_device_name(bs));
1846             goto out;
1847         }
1848     }
1849
1850     bdrv_close(bs);
1851
1852 out:
1853     aio_context_release(aio_context);
1854 }
1855
1856 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1857 {
1858     BlockBackend *blk;
1859
1860     blk = blk_by_name(device);
1861     if (!blk) {
1862         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1863                   "Device '%s' not found", device);
1864         return;
1865     }
1866
1867     eject_device(blk, force, errp);
1868 }
1869
1870 void qmp_block_passwd(bool has_device, const char *device,
1871                       bool has_node_name, const char *node_name,
1872                       const char *password, Error **errp)
1873 {
1874     Error *local_err = NULL;
1875     BlockDriverState *bs;
1876     AioContext *aio_context;
1877
1878     bs = bdrv_lookup_bs(has_device ? device : NULL,
1879                         has_node_name ? node_name : NULL,
1880                         &local_err);
1881     if (local_err) {
1882         error_propagate(errp, local_err);
1883         return;
1884     }
1885
1886     aio_context = bdrv_get_aio_context(bs);
1887     aio_context_acquire(aio_context);
1888
1889     bdrv_add_key(bs, password, errp);
1890
1891     aio_context_release(aio_context);
1892 }
1893
1894 /* Assumes AioContext is held */
1895 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1896                                     int bdrv_flags, BlockDriver *drv,
1897                                     const char *password, Error **errp)
1898 {
1899     Error *local_err = NULL;
1900     int ret;
1901
1902     ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1903     if (ret < 0) {
1904         error_propagate(errp, local_err);
1905         return;
1906     }
1907
1908     bdrv_add_key(bs, password, errp);
1909 }
1910
1911 void qmp_change_blockdev(const char *device, const char *filename,
1912                          const char *format, Error **errp)
1913 {
1914     BlockBackend *blk;
1915     BlockDriverState *bs;
1916     AioContext *aio_context;
1917     BlockDriver *drv = NULL;
1918     int bdrv_flags;
1919     Error *err = NULL;
1920
1921     blk = blk_by_name(device);
1922     if (!blk) {
1923         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1924                   "Device '%s' not found", device);
1925         return;
1926     }
1927     bs = blk_bs(blk);
1928
1929     aio_context = bdrv_get_aio_context(bs);
1930     aio_context_acquire(aio_context);
1931
1932     if (format) {
1933         drv = bdrv_find_whitelisted_format(format, bs->read_only);
1934         if (!drv) {
1935             error_setg(errp, QERR_INVALID_BLOCK_FORMAT, format);
1936             goto out;
1937         }
1938     }
1939
1940     eject_device(blk, 0, &err);
1941     if (err) {
1942         error_propagate(errp, err);
1943         goto out;
1944     }
1945
1946     bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1947     bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1948
1949     qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1950
1951 out:
1952     aio_context_release(aio_context);
1953 }
1954
1955 /* throttling disk I/O limits */
1956 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1957                                int64_t bps_wr,
1958                                int64_t iops,
1959                                int64_t iops_rd,
1960                                int64_t iops_wr,
1961                                bool has_bps_max,
1962                                int64_t bps_max,
1963                                bool has_bps_rd_max,
1964                                int64_t bps_rd_max,
1965                                bool has_bps_wr_max,
1966                                int64_t bps_wr_max,
1967                                bool has_iops_max,
1968                                int64_t iops_max,
1969                                bool has_iops_rd_max,
1970                                int64_t iops_rd_max,
1971                                bool has_iops_wr_max,
1972                                int64_t iops_wr_max,
1973                                bool has_iops_size,
1974                                int64_t iops_size,
1975                                bool has_group,
1976                                const char *group, Error **errp)
1977 {
1978     ThrottleConfig cfg;
1979     BlockDriverState *bs;
1980     BlockBackend *blk;
1981     AioContext *aio_context;
1982
1983     blk = blk_by_name(device);
1984     if (!blk) {
1985         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1986                   "Device '%s' not found", device);
1987         return;
1988     }
1989     bs = blk_bs(blk);
1990
1991     memset(&cfg, 0, sizeof(cfg));
1992     cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1993     cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;
1994     cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1995
1996     cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1997     cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;
1998     cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1999
2000     if (has_bps_max) {
2001         cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2002     }
2003     if (has_bps_rd_max) {
2004         cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2005     }
2006     if (has_bps_wr_max) {
2007         cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2008     }
2009     if (has_iops_max) {
2010         cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2011     }
2012     if (has_iops_rd_max) {
2013         cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2014     }
2015     if (has_iops_wr_max) {
2016         cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2017     }
2018
2019     if (has_iops_size) {
2020         cfg.op_size = iops_size;
2021     }
2022
2023     if (!check_throttle_config(&cfg, errp)) {
2024         return;
2025     }
2026
2027     aio_context = bdrv_get_aio_context(bs);
2028     aio_context_acquire(aio_context);
2029
2030     if (throttle_enabled(&cfg)) {
2031         /* Enable I/O limits if they're not enabled yet, otherwise
2032          * just update the throttling group. */
2033         if (!bs->io_limits_enabled) {
2034             bdrv_io_limits_enable(bs, has_group ? group : device);
2035         } else if (has_group) {
2036             bdrv_io_limits_update_group(bs, group);
2037         }
2038         /* Set the new throttling configuration */
2039         bdrv_set_io_limits(bs, &cfg);
2040     } else if (bs->io_limits_enabled) {
2041         /* If all throttling settings are set to 0, disable I/O limits */
2042         bdrv_io_limits_disable(bs);
2043     }
2044
2045     aio_context_release(aio_context);
2046 }
2047
2048 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2049                                 bool has_granularity, uint32_t granularity,
2050                                 Error **errp)
2051 {
2052     AioContext *aio_context;
2053     BlockDriverState *bs;
2054
2055     if (!name || name[0] == '\0') {
2056         error_setg(errp, "Bitmap name cannot be empty");
2057         return;
2058     }
2059
2060     bs = bdrv_lookup_bs(node, node, errp);
2061     if (!bs) {
2062         return;
2063     }
2064
2065     aio_context = bdrv_get_aio_context(bs);
2066     aio_context_acquire(aio_context);
2067
2068     if (has_granularity) {
2069         if (granularity < 512 || !is_power_of_2(granularity)) {
2070             error_setg(errp, "Granularity must be power of 2 "
2071                              "and at least 512");
2072             goto out;
2073         }
2074     } else {
2075         /* Default to cluster size, if available: */
2076         granularity = bdrv_get_default_bitmap_granularity(bs);
2077     }
2078
2079     bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2080
2081  out:
2082     aio_context_release(aio_context);
2083 }
2084
2085 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2086                                    Error **errp)
2087 {
2088     AioContext *aio_context;
2089     BlockDriverState *bs;
2090     BdrvDirtyBitmap *bitmap;
2091
2092     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2093     if (!bitmap || !bs) {
2094         return;
2095     }
2096
2097     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2098         error_setg(errp,
2099                    "Bitmap '%s' is currently frozen and cannot be removed",
2100                    name);
2101         goto out;
2102     }
2103     bdrv_dirty_bitmap_make_anon(bitmap);
2104     bdrv_release_dirty_bitmap(bs, bitmap);
2105
2106  out:
2107     aio_context_release(aio_context);
2108 }
2109
2110 /**
2111  * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2112  * immediately after a full backup operation.
2113  */
2114 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2115                                   Error **errp)
2116 {
2117     AioContext *aio_context;
2118     BdrvDirtyBitmap *bitmap;
2119     BlockDriverState *bs;
2120
2121     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2122     if (!bitmap || !bs) {
2123         return;
2124     }
2125
2126     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2127         error_setg(errp,
2128                    "Bitmap '%s' is currently frozen and cannot be modified",
2129                    name);
2130         goto out;
2131     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2132         error_setg(errp,
2133                    "Bitmap '%s' is currently disabled and cannot be cleared",
2134                    name);
2135         goto out;
2136     }
2137
2138     bdrv_clear_dirty_bitmap(bitmap);
2139
2140  out:
2141     aio_context_release(aio_context);
2142 }
2143
2144 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2145 {
2146     const char *id = qdict_get_str(qdict, "id");
2147     BlockBackend *blk;
2148     BlockDriverState *bs;
2149     AioContext *aio_context;
2150     Error *local_err = NULL;
2151
2152     blk = blk_by_name(id);
2153     if (!blk) {
2154         error_report("Device '%s' not found", id);
2155         return;
2156     }
2157     bs = blk_bs(blk);
2158
2159     if (!blk_legacy_dinfo(blk)) {
2160         error_report("Deleting device added with blockdev-add"
2161                      " is not supported");
2162         return;
2163     }
2164
2165     aio_context = bdrv_get_aio_context(bs);
2166     aio_context_acquire(aio_context);
2167
2168     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2169         error_report_err(local_err);
2170         aio_context_release(aio_context);
2171         return;
2172     }
2173
2174     bdrv_close(bs);
2175
2176     /* if we have a device attached to this BlockDriverState
2177      * then we need to make the drive anonymous until the device
2178      * can be removed.  If this is a drive with no device backing
2179      * then we can just get rid of the block driver state right here.
2180      */
2181     if (blk_get_attached_dev(blk)) {
2182         blk_hide_on_behalf_of_hmp_drive_del(blk);
2183         /* Further I/O must not pause the guest */
2184         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
2185                           BLOCKDEV_ON_ERROR_REPORT);
2186     } else {
2187         blk_unref(blk);
2188     }
2189
2190     aio_context_release(aio_context);
2191 }
2192
2193 void qmp_block_resize(bool has_device, const char *device,
2194                       bool has_node_name, const char *node_name,
2195                       int64_t size, Error **errp)
2196 {
2197     Error *local_err = NULL;
2198     BlockDriverState *bs;
2199     AioContext *aio_context;
2200     int ret;
2201
2202     bs = bdrv_lookup_bs(has_device ? device : NULL,
2203                         has_node_name ? node_name : NULL,
2204                         &local_err);
2205     if (local_err) {
2206         error_propagate(errp, local_err);
2207         return;
2208     }
2209
2210     aio_context = bdrv_get_aio_context(bs);
2211     aio_context_acquire(aio_context);
2212
2213     if (!bdrv_is_first_non_filter(bs)) {
2214         error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2215         goto out;
2216     }
2217
2218     if (size < 0) {
2219         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2220         goto out;
2221     }
2222
2223     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2224         error_setg(errp, QERR_DEVICE_IN_USE, device);
2225         goto out;
2226     }
2227
2228     /* complete all in-flight operations before resizing the device */
2229     bdrv_drain_all();
2230
2231     ret = bdrv_truncate(bs, size);
2232     switch (ret) {
2233     case 0:
2234         break;
2235     case -ENOMEDIUM:
2236         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2237         break;
2238     case -ENOTSUP:
2239         error_setg(errp, QERR_UNSUPPORTED);
2240         break;
2241     case -EACCES:
2242         error_setg(errp, "Device '%s' is read only", device);
2243         break;
2244     case -EBUSY:
2245         error_setg(errp, QERR_DEVICE_IN_USE, device);
2246         break;
2247     default:
2248         error_setg_errno(errp, -ret, "Could not resize");
2249         break;
2250     }
2251
2252 out:
2253     aio_context_release(aio_context);
2254 }
2255
2256 static void block_job_cb(void *opaque, int ret)
2257 {
2258     /* Note that this function may be executed from another AioContext besides
2259      * the QEMU main loop.  If you need to access anything that assumes the
2260      * QEMU global mutex, use a BH or introduce a mutex.
2261      */
2262
2263     BlockDriverState *bs = opaque;
2264     const char *msg = NULL;
2265
2266     trace_block_job_cb(bs, bs->job, ret);
2267
2268     assert(bs->job);
2269
2270     if (ret < 0) {
2271         msg = strerror(-ret);
2272     }
2273
2274     if (block_job_is_cancelled(bs->job)) {
2275         block_job_event_cancelled(bs->job);
2276     } else {
2277         block_job_event_completed(bs->job, msg);
2278     }
2279
2280     bdrv_put_ref_bh_schedule(bs);
2281 }
2282
2283 void qmp_block_stream(const char *device,
2284                       bool has_base, const char *base,
2285                       bool has_backing_file, const char *backing_file,
2286                       bool has_speed, int64_t speed,
2287                       bool has_on_error, BlockdevOnError on_error,
2288                       Error **errp)
2289 {
2290     BlockBackend *blk;
2291     BlockDriverState *bs;
2292     BlockDriverState *base_bs = NULL;
2293     AioContext *aio_context;
2294     Error *local_err = NULL;
2295     const char *base_name = NULL;
2296
2297     if (!has_on_error) {
2298         on_error = BLOCKDEV_ON_ERROR_REPORT;
2299     }
2300
2301     blk = blk_by_name(device);
2302     if (!blk) {
2303         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2304                   "Device '%s' not found", device);
2305         return;
2306     }
2307     bs = blk_bs(blk);
2308
2309     aio_context = bdrv_get_aio_context(bs);
2310     aio_context_acquire(aio_context);
2311
2312     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2313         goto out;
2314     }
2315
2316     if (has_base) {
2317         base_bs = bdrv_find_backing_image(bs, base);
2318         if (base_bs == NULL) {
2319             error_setg(errp, QERR_BASE_NOT_FOUND, base);
2320             goto out;
2321         }
2322         assert(bdrv_get_aio_context(base_bs) == aio_context);
2323         base_name = base;
2324     }
2325
2326     /* if we are streaming the entire chain, the result will have no backing
2327      * file, and specifying one is therefore an error */
2328     if (base_bs == NULL && has_backing_file) {
2329         error_setg(errp, "backing file specified, but streaming the "
2330                          "entire chain");
2331         goto out;
2332     }
2333
2334     /* backing_file string overrides base bs filename */
2335     base_name = has_backing_file ? backing_file : base_name;
2336
2337     stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2338                  on_error, block_job_cb, bs, &local_err);
2339     if (local_err) {
2340         error_propagate(errp, local_err);
2341         goto out;
2342     }
2343
2344     trace_qmp_block_stream(bs, bs->job);
2345
2346 out:
2347     aio_context_release(aio_context);
2348 }
2349
2350 void qmp_block_commit(const char *device,
2351                       bool has_base, const char *base,
2352                       bool has_top, const char *top,
2353                       bool has_backing_file, const char *backing_file,
2354                       bool has_speed, int64_t speed,
2355                       Error **errp)
2356 {
2357     BlockBackend *blk;
2358     BlockDriverState *bs;
2359     BlockDriverState *base_bs, *top_bs;
2360     AioContext *aio_context;
2361     Error *local_err = NULL;
2362     /* This will be part of the QMP command, if/when the
2363      * BlockdevOnError change for blkmirror makes it in
2364      */
2365     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2366
2367     if (!has_speed) {
2368         speed = 0;
2369     }
2370
2371     /* Important Note:
2372      *  libvirt relies on the DeviceNotFound error class in order to probe for
2373      *  live commit feature versions; for this to work, we must make sure to
2374      *  perform the device lookup before any generic errors that may occur in a
2375      *  scenario in which all optional arguments are omitted. */
2376     blk = blk_by_name(device);
2377     if (!blk) {
2378         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2379                   "Device '%s' not found", device);
2380         return;
2381     }
2382     bs = blk_bs(blk);
2383
2384     aio_context = bdrv_get_aio_context(bs);
2385     aio_context_acquire(aio_context);
2386
2387     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
2388         goto out;
2389     }
2390
2391     /* default top_bs is the active layer */
2392     top_bs = bs;
2393
2394     if (has_top && top) {
2395         if (strcmp(bs->filename, top) != 0) {
2396             top_bs = bdrv_find_backing_image(bs, top);
2397         }
2398     }
2399
2400     if (top_bs == NULL) {
2401         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2402         goto out;
2403     }
2404
2405     assert(bdrv_get_aio_context(top_bs) == aio_context);
2406
2407     if (has_base && base) {
2408         base_bs = bdrv_find_backing_image(top_bs, base);
2409     } else {
2410         base_bs = bdrv_find_base(top_bs);
2411     }
2412
2413     if (base_bs == NULL) {
2414         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2415         goto out;
2416     }
2417
2418     assert(bdrv_get_aio_context(base_bs) == aio_context);
2419
2420     if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2421         goto out;
2422     }
2423
2424     /* Do not allow attempts to commit an image into itself */
2425     if (top_bs == base_bs) {
2426         error_setg(errp, "cannot commit an image into itself");
2427         goto out;
2428     }
2429
2430     if (top_bs == bs) {
2431         if (has_backing_file) {
2432             error_setg(errp, "'backing-file' specified,"
2433                              " but 'top' is the active layer");
2434             goto out;
2435         }
2436         commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2437                             bs, &local_err);
2438     } else {
2439         commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2440                      has_backing_file ? backing_file : NULL, &local_err);
2441     }
2442     if (local_err != NULL) {
2443         error_propagate(errp, local_err);
2444         goto out;
2445     }
2446
2447 out:
2448     aio_context_release(aio_context);
2449 }
2450
2451 void qmp_drive_backup(const char *device, const char *target,
2452                       bool has_format, const char *format,
2453                       enum MirrorSyncMode sync,
2454                       bool has_mode, enum NewImageMode mode,
2455                       bool has_speed, int64_t speed,
2456                       bool has_bitmap, const char *bitmap,
2457                       bool has_on_source_error, BlockdevOnError on_source_error,
2458                       bool has_on_target_error, BlockdevOnError on_target_error,
2459                       Error **errp)
2460 {
2461     BlockBackend *blk;
2462     BlockDriverState *bs;
2463     BlockDriverState *target_bs;
2464     BlockDriverState *source = NULL;
2465     BdrvDirtyBitmap *bmap = NULL;
2466     AioContext *aio_context;
2467     BlockDriver *drv = NULL;
2468     Error *local_err = NULL;
2469     int flags;
2470     int64_t size;
2471     int ret;
2472
2473     if (!has_speed) {
2474         speed = 0;
2475     }
2476     if (!has_on_source_error) {
2477         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2478     }
2479     if (!has_on_target_error) {
2480         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2481     }
2482     if (!has_mode) {
2483         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2484     }
2485
2486     blk = blk_by_name(device);
2487     if (!blk) {
2488         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2489                   "Device '%s' not found", device);
2490         return;
2491     }
2492     bs = blk_bs(blk);
2493
2494     aio_context = bdrv_get_aio_context(bs);
2495     aio_context_acquire(aio_context);
2496
2497     /* Although backup_run has this check too, we need to use bs->drv below, so
2498      * do an early check redundantly. */
2499     if (!bdrv_is_inserted(bs)) {
2500         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2501         goto out;
2502     }
2503
2504     if (!has_format) {
2505         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2506     }
2507     if (format) {
2508         drv = bdrv_find_format(format);
2509         if (!drv) {
2510             error_setg(errp, QERR_INVALID_BLOCK_FORMAT, format);
2511             goto out;
2512         }
2513     }
2514
2515     /* Early check to avoid creating target */
2516     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2517         goto out;
2518     }
2519
2520     flags = bs->open_flags | BDRV_O_RDWR;
2521
2522     /* See if we have a backing HD we can use to create our new image
2523      * on top of. */
2524     if (sync == MIRROR_SYNC_MODE_TOP) {
2525         source = bs->backing_hd;
2526         if (!source) {
2527             sync = MIRROR_SYNC_MODE_FULL;
2528         }
2529     }
2530     if (sync == MIRROR_SYNC_MODE_NONE) {
2531         source = bs;
2532     }
2533
2534     size = bdrv_getlength(bs);
2535     if (size < 0) {
2536         error_setg_errno(errp, -size, "bdrv_getlength failed");
2537         goto out;
2538     }
2539
2540     if (mode != NEW_IMAGE_MODE_EXISTING) {
2541         assert(format && drv);
2542         if (source) {
2543             bdrv_img_create(target, format, source->filename,
2544                             source->drv->format_name, NULL,
2545                             size, flags, &local_err, false);
2546         } else {
2547             bdrv_img_create(target, format, NULL, NULL, NULL,
2548                             size, flags, &local_err, false);
2549         }
2550     }
2551
2552     if (local_err) {
2553         error_propagate(errp, local_err);
2554         goto out;
2555     }
2556
2557     target_bs = NULL;
2558     ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2559     if (ret < 0) {
2560         error_propagate(errp, local_err);
2561         goto out;
2562     }
2563
2564     bdrv_set_aio_context(target_bs, aio_context);
2565
2566     if (has_bitmap) {
2567         bmap = bdrv_find_dirty_bitmap(bs, bitmap);
2568         if (!bmap) {
2569             error_setg(errp, "Bitmap '%s' could not be found", bitmap);
2570             goto out;
2571         }
2572     }
2573
2574     backup_start(bs, target_bs, speed, sync, bmap,
2575                  on_source_error, on_target_error,
2576                  block_job_cb, bs, &local_err);
2577     if (local_err != NULL) {
2578         bdrv_unref(target_bs);
2579         error_propagate(errp, local_err);
2580         goto out;
2581     }
2582
2583 out:
2584     aio_context_release(aio_context);
2585 }
2586
2587 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2588 {
2589     return bdrv_named_nodes_list(errp);
2590 }
2591
2592 void qmp_blockdev_backup(const char *device, const char *target,
2593                          enum MirrorSyncMode sync,
2594                          bool has_speed, int64_t speed,
2595                          bool has_on_source_error,
2596                          BlockdevOnError on_source_error,
2597                          bool has_on_target_error,
2598                          BlockdevOnError on_target_error,
2599                          Error **errp)
2600 {
2601     BlockBackend *blk;
2602     BlockDriverState *bs;
2603     BlockDriverState *target_bs;
2604     Error *local_err = NULL;
2605     AioContext *aio_context;
2606
2607     if (!has_speed) {
2608         speed = 0;
2609     }
2610     if (!has_on_source_error) {
2611         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2612     }
2613     if (!has_on_target_error) {
2614         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2615     }
2616
2617     blk = blk_by_name(device);
2618     if (!blk) {
2619         error_setg(errp, "Device '%s' not found", device);
2620         return;
2621     }
2622     bs = blk_bs(blk);
2623
2624     aio_context = bdrv_get_aio_context(bs);
2625     aio_context_acquire(aio_context);
2626
2627     blk = blk_by_name(target);
2628     if (!blk) {
2629         error_setg(errp, "Device '%s' not found", target);
2630         goto out;
2631     }
2632     target_bs = blk_bs(blk);
2633
2634     bdrv_ref(target_bs);
2635     bdrv_set_aio_context(target_bs, aio_context);
2636     backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
2637                  on_target_error, block_job_cb, bs, &local_err);
2638     if (local_err != NULL) {
2639         bdrv_unref(target_bs);
2640         error_propagate(errp, local_err);
2641     }
2642 out:
2643     aio_context_release(aio_context);
2644 }
2645
2646 void qmp_drive_mirror(const char *device, const char *target,
2647                       bool has_format, const char *format,
2648                       bool has_node_name, const char *node_name,
2649                       bool has_replaces, const char *replaces,
2650                       enum MirrorSyncMode sync,
2651                       bool has_mode, enum NewImageMode mode,
2652                       bool has_speed, int64_t speed,
2653                       bool has_granularity, uint32_t granularity,
2654                       bool has_buf_size, int64_t buf_size,
2655                       bool has_on_source_error, BlockdevOnError on_source_error,
2656                       bool has_on_target_error, BlockdevOnError on_target_error,
2657                       bool has_unmap, bool unmap,
2658                       Error **errp)
2659 {
2660     BlockBackend *blk;
2661     BlockDriverState *bs;
2662     BlockDriverState *source, *target_bs;
2663     AioContext *aio_context;
2664     BlockDriver *drv = NULL;
2665     Error *local_err = NULL;
2666     QDict *options = NULL;
2667     int flags;
2668     int64_t size;
2669     int ret;
2670
2671     if (!has_speed) {
2672         speed = 0;
2673     }
2674     if (!has_on_source_error) {
2675         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2676     }
2677     if (!has_on_target_error) {
2678         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2679     }
2680     if (!has_mode) {
2681         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2682     }
2683     if (!has_granularity) {
2684         granularity = 0;
2685     }
2686     if (!has_buf_size) {
2687         buf_size = 0;
2688     }
2689     if (!has_unmap) {
2690         unmap = true;
2691     }
2692
2693     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2694         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2695                    "a value in range [512B, 64MB]");
2696         return;
2697     }
2698     if (granularity & (granularity - 1)) {
2699         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2700                    "power of 2");
2701         return;
2702     }
2703
2704     blk = blk_by_name(device);
2705     if (!blk) {
2706         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2707                   "Device '%s' not found", device);
2708         return;
2709     }
2710     bs = blk_bs(blk);
2711
2712     aio_context = bdrv_get_aio_context(bs);
2713     aio_context_acquire(aio_context);
2714
2715     if (!bdrv_is_inserted(bs)) {
2716         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2717         goto out;
2718     }
2719
2720     if (!has_format) {
2721         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2722     }
2723     if (format) {
2724         drv = bdrv_find_format(format);
2725         if (!drv) {
2726             error_setg(errp, QERR_INVALID_BLOCK_FORMAT, format);
2727             goto out;
2728         }
2729     }
2730
2731     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2732         goto out;
2733     }
2734
2735     flags = bs->open_flags | BDRV_O_RDWR;
2736     source = bs->backing_hd;
2737     if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2738         sync = MIRROR_SYNC_MODE_FULL;
2739     }
2740     if (sync == MIRROR_SYNC_MODE_NONE) {
2741         source = bs;
2742     }
2743
2744     size = bdrv_getlength(bs);
2745     if (size < 0) {
2746         error_setg_errno(errp, -size, "bdrv_getlength failed");
2747         goto out;
2748     }
2749
2750     if (has_replaces) {
2751         BlockDriverState *to_replace_bs;
2752         AioContext *replace_aio_context;
2753         int64_t replace_size;
2754
2755         if (!has_node_name) {
2756             error_setg(errp, "a node-name must be provided when replacing a"
2757                              " named node of the graph");
2758             goto out;
2759         }
2760
2761         to_replace_bs = check_to_replace_node(replaces, &local_err);
2762
2763         if (!to_replace_bs) {
2764             error_propagate(errp, local_err);
2765             goto out;
2766         }
2767
2768         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
2769         aio_context_acquire(replace_aio_context);
2770         replace_size = bdrv_getlength(to_replace_bs);
2771         aio_context_release(replace_aio_context);
2772
2773         if (size != replace_size) {
2774             error_setg(errp, "cannot replace image with a mirror image of "
2775                              "different size");
2776             goto out;
2777         }
2778     }
2779
2780     if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2781         && mode != NEW_IMAGE_MODE_EXISTING)
2782     {
2783         /* create new image w/o backing file */
2784         assert(format && drv);
2785         bdrv_img_create(target, format,
2786                         NULL, NULL, NULL, size, flags, &local_err, false);
2787     } else {
2788         switch (mode) {
2789         case NEW_IMAGE_MODE_EXISTING:
2790             break;
2791         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2792             /* create new image with backing file */
2793             bdrv_img_create(target, format,
2794                             source->filename,
2795                             source->drv->format_name,
2796                             NULL, size, flags, &local_err, false);
2797             break;
2798         default:
2799             abort();
2800         }
2801     }
2802
2803     if (local_err) {
2804         error_propagate(errp, local_err);
2805         goto out;
2806     }
2807
2808     if (has_node_name) {
2809         options = qdict_new();
2810         qdict_put(options, "node-name", qstring_from_str(node_name));
2811     }
2812
2813     /* Mirroring takes care of copy-on-write using the source's backing
2814      * file.
2815      */
2816     target_bs = NULL;
2817     ret = bdrv_open(&target_bs, target, NULL, options,
2818                     flags | BDRV_O_NO_BACKING, drv, &local_err);
2819     if (ret < 0) {
2820         error_propagate(errp, local_err);
2821         goto out;
2822     }
2823
2824     bdrv_set_aio_context(target_bs, aio_context);
2825
2826     /* pass the node name to replace to mirror start since it's loose coupling
2827      * and will allow to check whether the node still exist at mirror completion
2828      */
2829     mirror_start(bs, target_bs,
2830                  has_replaces ? replaces : NULL,
2831                  speed, granularity, buf_size, sync,
2832                  on_source_error, on_target_error,
2833                  unmap,
2834                  block_job_cb, bs, &local_err);
2835     if (local_err != NULL) {
2836         bdrv_unref(target_bs);
2837         error_propagate(errp, local_err);
2838         goto out;
2839     }
2840
2841 out:
2842     aio_context_release(aio_context);
2843 }
2844
2845 /* Get the block job for a given device name and acquire its AioContext */
2846 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
2847                                 Error **errp)
2848 {
2849     BlockBackend *blk;
2850     BlockDriverState *bs;
2851
2852     blk = blk_by_name(device);
2853     if (!blk) {
2854         goto notfound;
2855     }
2856     bs = blk_bs(blk);
2857
2858     *aio_context = bdrv_get_aio_context(bs);
2859     aio_context_acquire(*aio_context);
2860
2861     if (!bs->job) {
2862         aio_context_release(*aio_context);
2863         goto notfound;
2864     }
2865
2866     return bs->job;
2867
2868 notfound:
2869     error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
2870               "No active block job on device '%s'", device);
2871     *aio_context = NULL;
2872     return NULL;
2873 }
2874
2875 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2876 {
2877     AioContext *aio_context;
2878     BlockJob *job = find_block_job(device, &aio_context, errp);
2879
2880     if (!job) {
2881         return;
2882     }
2883
2884     block_job_set_speed(job, speed, errp);
2885     aio_context_release(aio_context);
2886 }
2887
2888 void qmp_block_job_cancel(const char *device,
2889                           bool has_force, bool force, Error **errp)
2890 {
2891     AioContext *aio_context;
2892     BlockJob *job = find_block_job(device, &aio_context, errp);
2893
2894     if (!job) {
2895         return;
2896     }
2897
2898     if (!has_force) {
2899         force = false;
2900     }
2901
2902     if (job->user_paused && !force) {
2903         error_setg(errp, "The block job for device '%s' is currently paused",
2904                    device);
2905         goto out;
2906     }
2907
2908     trace_qmp_block_job_cancel(job);
2909     block_job_cancel(job);
2910 out:
2911     aio_context_release(aio_context);
2912 }
2913
2914 void qmp_block_job_pause(const char *device, Error **errp)
2915 {
2916     AioContext *aio_context;
2917     BlockJob *job = find_block_job(device, &aio_context, errp);
2918
2919     if (!job || job->user_paused) {
2920         return;
2921     }
2922
2923     job->user_paused = true;
2924     trace_qmp_block_job_pause(job);
2925     block_job_pause(job);
2926     aio_context_release(aio_context);
2927 }
2928
2929 void qmp_block_job_resume(const char *device, Error **errp)
2930 {
2931     AioContext *aio_context;
2932     BlockJob *job = find_block_job(device, &aio_context, errp);
2933
2934     if (!job || !job->user_paused) {
2935         return;
2936     }
2937
2938     job->user_paused = false;
2939     trace_qmp_block_job_resume(job);
2940     block_job_resume(job);
2941     aio_context_release(aio_context);
2942 }
2943
2944 void qmp_block_job_complete(const char *device, Error **errp)
2945 {
2946     AioContext *aio_context;
2947     BlockJob *job = find_block_job(device, &aio_context, errp);
2948
2949     if (!job) {
2950         return;
2951     }
2952
2953     trace_qmp_block_job_complete(job);
2954     block_job_complete(job, errp);
2955     aio_context_release(aio_context);
2956 }
2957
2958 void qmp_change_backing_file(const char *device,
2959                              const char *image_node_name,
2960                              const char *backing_file,
2961                              Error **errp)
2962 {
2963     BlockBackend *blk;
2964     BlockDriverState *bs = NULL;
2965     AioContext *aio_context;
2966     BlockDriverState *image_bs = NULL;
2967     Error *local_err = NULL;
2968     bool ro;
2969     int open_flags;
2970     int ret;
2971
2972     blk = blk_by_name(device);
2973     if (!blk) {
2974         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2975                   "Device '%s' not found", device);
2976         return;
2977     }
2978     bs = blk_bs(blk);
2979
2980     aio_context = bdrv_get_aio_context(bs);
2981     aio_context_acquire(aio_context);
2982
2983     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2984     if (local_err) {
2985         error_propagate(errp, local_err);
2986         goto out;
2987     }
2988
2989     if (!image_bs) {
2990         error_setg(errp, "image file not found");
2991         goto out;
2992     }
2993
2994     if (bdrv_find_base(image_bs) == image_bs) {
2995         error_setg(errp, "not allowing backing file change on an image "
2996                          "without a backing file");
2997         goto out;
2998     }
2999
3000     /* even though we are not necessarily operating on bs, we need it to
3001      * determine if block ops are currently prohibited on the chain */
3002     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3003         goto out;
3004     }
3005
3006     /* final sanity check */
3007     if (!bdrv_chain_contains(bs, image_bs)) {
3008         error_setg(errp, "'%s' and image file are not in the same chain",
3009                    device);
3010         goto out;
3011     }
3012
3013     /* if not r/w, reopen to make r/w */
3014     open_flags = image_bs->open_flags;
3015     ro = bdrv_is_read_only(image_bs);
3016
3017     if (ro) {
3018         bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3019         if (local_err) {
3020             error_propagate(errp, local_err);
3021             goto out;
3022         }
3023     }
3024
3025     ret = bdrv_change_backing_file(image_bs, backing_file,
3026                                image_bs->drv ? image_bs->drv->format_name : "");
3027
3028     if (ret < 0) {
3029         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3030                          backing_file);
3031         /* don't exit here, so we can try to restore open flags if
3032          * appropriate */
3033     }
3034
3035     if (ro) {
3036         bdrv_reopen(image_bs, open_flags, &local_err);
3037         if (local_err) {
3038             error_propagate(errp, local_err); /* will preserve prior errp */
3039         }
3040     }
3041
3042 out:
3043     aio_context_release(aio_context);
3044 }
3045
3046 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3047 {
3048     QmpOutputVisitor *ov = qmp_output_visitor_new();
3049     BlockBackend *blk;
3050     QObject *obj;
3051     QDict *qdict;
3052     Error *local_err = NULL;
3053
3054     /* Require an ID in the top level */
3055     if (!options->has_id) {
3056         error_setg(errp, "Block device needs an ID");
3057         goto fail;
3058     }
3059
3060     /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3061      * cache.direct=false instead of silently switching to aio=threads, except
3062      * when called from drive_new().
3063      *
3064      * For now, simply forbidding the combination for all drivers will do. */
3065     if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3066         bool direct = options->has_cache &&
3067                       options->cache->has_direct &&
3068                       options->cache->direct;
3069         if (!direct) {
3070             error_setg(errp, "aio=native requires cache.direct=true");
3071             goto fail;
3072         }
3073     }
3074
3075     visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
3076                                &options, NULL, &local_err);
3077     if (local_err) {
3078         error_propagate(errp, local_err);
3079         goto fail;
3080     }
3081
3082     obj = qmp_output_get_qobject(ov);
3083     qdict = qobject_to_qdict(obj);
3084
3085     qdict_flatten(qdict);
3086
3087     blk = blockdev_init(NULL, qdict, &local_err);
3088     if (local_err) {
3089         error_propagate(errp, local_err);
3090         goto fail;
3091     }
3092
3093     if (bdrv_key_required(blk_bs(blk))) {
3094         blk_unref(blk);
3095         error_setg(errp, "blockdev-add doesn't support encrypted devices");
3096         goto fail;
3097     }
3098
3099 fail:
3100     qmp_output_visitor_cleanup(ov);
3101 }
3102
3103 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3104 {
3105     BlockJobInfoList *head = NULL, **p_next = &head;
3106     BlockDriverState *bs;
3107
3108     for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3109         AioContext *aio_context = bdrv_get_aio_context(bs);
3110
3111         aio_context_acquire(aio_context);
3112
3113         if (bs->job) {
3114             BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
3115             elem->value = block_job_query(bs->job);
3116             *p_next = elem;
3117             p_next = &elem->next;
3118         }
3119
3120         aio_context_release(aio_context);
3121     }
3122
3123     return head;
3124 }
3125
3126 QemuOptsList qemu_common_drive_opts = {
3127     .name = "drive",
3128     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3129     .desc = {
3130         {
3131             .name = "snapshot",
3132             .type = QEMU_OPT_BOOL,
3133             .help = "enable/disable snapshot mode",
3134         },{
3135             .name = "discard",
3136             .type = QEMU_OPT_STRING,
3137             .help = "discard operation (ignore/off, unmap/on)",
3138         },{
3139             .name = BDRV_OPT_CACHE_WB,
3140             .type = QEMU_OPT_BOOL,
3141             .help = "enables writeback mode for any caches",
3142         },{
3143             .name = BDRV_OPT_CACHE_DIRECT,
3144             .type = QEMU_OPT_BOOL,
3145             .help = "enables use of O_DIRECT (bypass the host page cache)",
3146         },{
3147             .name = BDRV_OPT_CACHE_NO_FLUSH,
3148             .type = QEMU_OPT_BOOL,
3149             .help = "ignore any flush requests for the device",
3150         },{
3151             .name = "aio",
3152             .type = QEMU_OPT_STRING,
3153             .help = "host AIO implementation (threads, native)",
3154         },{
3155             .name = "format",
3156             .type = QEMU_OPT_STRING,
3157             .help = "disk format (raw, qcow2, ...)",
3158         },{
3159             .name = "rerror",
3160             .type = QEMU_OPT_STRING,
3161             .help = "read error action",
3162         },{
3163             .name = "werror",
3164             .type = QEMU_OPT_STRING,
3165             .help = "write error action",
3166         },{
3167             .name = "read-only",
3168             .type = QEMU_OPT_BOOL,
3169             .help = "open drive file as read-only",
3170         },{
3171             .name = "throttling.iops-total",
3172             .type = QEMU_OPT_NUMBER,
3173             .help = "limit total I/O operations per second",
3174         },{
3175             .name = "throttling.iops-read",
3176             .type = QEMU_OPT_NUMBER,
3177             .help = "limit read operations per second",
3178         },{
3179             .name = "throttling.iops-write",
3180             .type = QEMU_OPT_NUMBER,
3181             .help = "limit write operations per second",
3182         },{
3183             .name = "throttling.bps-total",
3184             .type = QEMU_OPT_NUMBER,
3185             .help = "limit total bytes per second",
3186         },{
3187             .name = "throttling.bps-read",
3188             .type = QEMU_OPT_NUMBER,
3189             .help = "limit read bytes per second",
3190         },{
3191             .name = "throttling.bps-write",
3192             .type = QEMU_OPT_NUMBER,
3193             .help = "limit write bytes per second",
3194         },{
3195             .name = "throttling.iops-total-max",
3196             .type = QEMU_OPT_NUMBER,
3197             .help = "I/O operations burst",
3198         },{
3199             .name = "throttling.iops-read-max",
3200             .type = QEMU_OPT_NUMBER,
3201             .help = "I/O operations read burst",
3202         },{
3203             .name = "throttling.iops-write-max",
3204             .type = QEMU_OPT_NUMBER,
3205             .help = "I/O operations write burst",
3206         },{
3207             .name = "throttling.bps-total-max",
3208             .type = QEMU_OPT_NUMBER,
3209             .help = "total bytes burst",
3210         },{
3211             .name = "throttling.bps-read-max",
3212             .type = QEMU_OPT_NUMBER,
3213             .help = "total bytes read burst",
3214         },{
3215             .name = "throttling.bps-write-max",
3216             .type = QEMU_OPT_NUMBER,
3217             .help = "total bytes write burst",
3218         },{
3219             .name = "throttling.iops-size",
3220             .type = QEMU_OPT_NUMBER,
3221             .help = "when limiting by iops max size of an I/O in bytes",
3222         },{
3223             .name = "throttling.group",
3224             .type = QEMU_OPT_STRING,
3225             .help = "name of the block throttling group",
3226         },{
3227             .name = "copy-on-read",
3228             .type = QEMU_OPT_BOOL,
3229             .help = "copy read data from backing file into image file",
3230         },{
3231             .name = "detect-zeroes",
3232             .type = QEMU_OPT_STRING,
3233             .help = "try to optimize zero writes (off, on, unmap)",
3234         },
3235         { /* end of list */ }
3236     },
3237 };
3238
3239 QemuOptsList qemu_drive_opts = {
3240     .name = "drive",
3241     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
3242     .desc = {
3243         /*
3244          * no elements => accept any params
3245          * validation will happen later
3246          */
3247         { /* end of list */ }
3248     },
3249 };