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