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