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