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