Refactor some hax related codes.
[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 "sysemu/sysemu.h"
42 #include "block/block_int.h"
43 #include "qmp-commands.h"
44 #include "trace.h"
45 #include "sysemu/arch_init.h"
46
47 static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
48 extern QemuOptsList qemu_common_drive_opts;
49
50 static const char *const if_name[IF_COUNT] = {
51     [IF_NONE] = "none",
52     [IF_IDE] = "ide",
53     [IF_SCSI] = "scsi",
54     [IF_FLOPPY] = "floppy",
55     [IF_PFLASH] = "pflash",
56     [IF_MTD] = "mtd",
57     [IF_SD] = "sd",
58     [IF_VIRTIO] = "virtio",
59     [IF_XEN] = "xen",
60 };
61
62 static const int if_max_devs[IF_COUNT] = {
63     /*
64      * Do not change these numbers!  They govern how drive option
65      * index maps to unit and bus.  That mapping is ABI.
66      *
67      * All controllers used to imlement if=T drives need to support
68      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
69      * Otherwise, some index values map to "impossible" bus, unit
70      * values.
71      *
72      * For instance, if you change [IF_SCSI] to 255, -drive
73      * if=scsi,index=12 no longer means bus=1,unit=5, but
74      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
75      * the drive can't be set up.  Regression.
76      */
77     [IF_IDE] = 2,
78     [IF_SCSI] = 7,
79 };
80
81 /*
82  * We automatically delete the drive when a device using it gets
83  * unplugged.  Questionable feature, but we can't just drop it.
84  * Device models call blockdev_mark_auto_del() to schedule the
85  * automatic deletion, and generic qdev code calls blockdev_auto_del()
86  * when deletion is actually safe.
87  */
88 void blockdev_mark_auto_del(BlockDriverState *bs)
89 {
90     DriveInfo *dinfo = drive_get_by_blockdev(bs);
91
92     if (bs->job) {
93         block_job_cancel(bs->job);
94     }
95     if (dinfo) {
96         dinfo->auto_del = 1;
97     }
98 }
99
100 void blockdev_auto_del(BlockDriverState *bs)
101 {
102     DriveInfo *dinfo = drive_get_by_blockdev(bs);
103
104     if (dinfo && dinfo->auto_del) {
105         drive_put_ref(dinfo);
106     }
107 }
108
109 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
110 {
111     int max_devs = if_max_devs[type];
112     return max_devs ? index / max_devs : 0;
113 }
114
115 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
116 {
117     int max_devs = if_max_devs[type];
118     return max_devs ? index % max_devs : index;
119 }
120
121 QemuOpts *drive_def(const char *optstr)
122 {
123     return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
124 }
125
126 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
127                     const char *optstr)
128 {
129     QemuOpts *opts;
130     char buf[32];
131
132     opts = drive_def(optstr);
133     if (!opts) {
134         return NULL;
135     }
136     if (type != IF_DEFAULT) {
137         qemu_opt_set(opts, "if", if_name[type]);
138     }
139     if (index >= 0) {
140         snprintf(buf, sizeof(buf), "%d", index);
141         qemu_opt_set(opts, "index", buf);
142     }
143     if (file)
144         qemu_opt_set(opts, "file", file);
145     return opts;
146 }
147
148 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
149 {
150     DriveInfo *dinfo;
151
152     /* seek interface, bus and unit */
153
154     QTAILQ_FOREACH(dinfo, &drives, next) {
155         if (dinfo->type == type &&
156             dinfo->bus == bus &&
157             dinfo->unit == unit)
158             return dinfo;
159     }
160
161     return NULL;
162 }
163
164 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
165 {
166     return drive_get(type,
167                      drive_index_to_bus_id(type, index),
168                      drive_index_to_unit_id(type, index));
169 }
170
171 int drive_get_max_bus(BlockInterfaceType type)
172 {
173     int max_bus;
174     DriveInfo *dinfo;
175
176     max_bus = -1;
177     QTAILQ_FOREACH(dinfo, &drives, next) {
178         if(dinfo->type == type &&
179            dinfo->bus > max_bus)
180             max_bus = dinfo->bus;
181     }
182     return max_bus;
183 }
184
185 /* Get a block device.  This should only be used for single-drive devices
186    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
187    appropriate bus.  */
188 DriveInfo *drive_get_next(BlockInterfaceType type)
189 {
190     static int next_block_unit[IF_COUNT];
191
192     return drive_get(type, 0, next_block_unit[type]++);
193 }
194
195 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
196 {
197     DriveInfo *dinfo;
198
199     QTAILQ_FOREACH(dinfo, &drives, next) {
200         if (dinfo->bdrv == bs) {
201             return dinfo;
202         }
203     }
204     return NULL;
205 }
206
207 static void bdrv_format_print(void *opaque, const char *name)
208 {
209     error_printf(" %s", name);
210 }
211
212 static void drive_uninit(DriveInfo *dinfo)
213 {
214     qemu_opts_del(dinfo->opts);
215     bdrv_delete(dinfo->bdrv);
216     g_free(dinfo->id);
217     QTAILQ_REMOVE(&drives, dinfo, next);
218     g_free(dinfo->serial);
219     g_free(dinfo);
220 }
221
222 void drive_put_ref(DriveInfo *dinfo)
223 {
224     assert(dinfo->refcount);
225     if (--dinfo->refcount == 0) {
226         drive_uninit(dinfo);
227     }
228 }
229
230 void drive_get_ref(DriveInfo *dinfo)
231 {
232     dinfo->refcount++;
233 }
234
235 typedef struct {
236     QEMUBH *bh;
237     DriveInfo *dinfo;
238 } DrivePutRefBH;
239
240 static void drive_put_ref_bh(void *opaque)
241 {
242     DrivePutRefBH *s = opaque;
243
244     drive_put_ref(s->dinfo);
245     qemu_bh_delete(s->bh);
246     g_free(s);
247 }
248
249 /*
250  * Release a drive reference in a BH
251  *
252  * It is not possible to use drive_put_ref() from a callback function when the
253  * callers still need the drive.  In such cases we schedule a BH to release the
254  * reference.
255  */
256 static void drive_put_ref_bh_schedule(DriveInfo *dinfo)
257 {
258     DrivePutRefBH *s;
259
260     s = g_new(DrivePutRefBH, 1);
261     s->bh = qemu_bh_new(drive_put_ref_bh, s);
262     s->dinfo = dinfo;
263     qemu_bh_schedule(s->bh);
264 }
265
266 static int parse_block_error_action(const char *buf, bool is_read)
267 {
268     if (!strcmp(buf, "ignore")) {
269         return BLOCKDEV_ON_ERROR_IGNORE;
270     } else if (!is_read && !strcmp(buf, "enospc")) {
271         return BLOCKDEV_ON_ERROR_ENOSPC;
272     } else if (!strcmp(buf, "stop")) {
273         return BLOCKDEV_ON_ERROR_STOP;
274     } else if (!strcmp(buf, "report")) {
275         return BLOCKDEV_ON_ERROR_REPORT;
276     } else {
277         error_report("'%s' invalid %s error action",
278                      buf, is_read ? "read" : "write");
279         return -1;
280     }
281 }
282
283 #ifdef CONFIG_MARU
284 extern int start_simple_client(char* msg);
285 extern char* maru_convert_path(char* msg, const char *path);
286 #endif
287
288 static bool do_check_io_limits(BlockIOLimit *io_limits, Error **errp)
289 {
290     bool bps_flag;
291     bool iops_flag;
292
293     assert(io_limits);
294
295     bps_flag  = (io_limits->bps[BLOCK_IO_LIMIT_TOTAL] != 0)
296                  && ((io_limits->bps[BLOCK_IO_LIMIT_READ] != 0)
297                  || (io_limits->bps[BLOCK_IO_LIMIT_WRITE] != 0));
298     iops_flag = (io_limits->iops[BLOCK_IO_LIMIT_TOTAL] != 0)
299                  && ((io_limits->iops[BLOCK_IO_LIMIT_READ] != 0)
300                  || (io_limits->iops[BLOCK_IO_LIMIT_WRITE] != 0));
301     if (bps_flag || iops_flag) {
302         error_setg(errp, "bps(iops) and bps_rd/bps_wr(iops_rd/iops_wr) "
303                          "cannot be used at the same time");
304         return false;
305     }
306
307     if (io_limits->bps[BLOCK_IO_LIMIT_TOTAL] < 0 ||
308         io_limits->bps[BLOCK_IO_LIMIT_WRITE] < 0 ||
309         io_limits->bps[BLOCK_IO_LIMIT_READ] < 0 ||
310         io_limits->iops[BLOCK_IO_LIMIT_TOTAL] < 0 ||
311         io_limits->iops[BLOCK_IO_LIMIT_WRITE] < 0 ||
312         io_limits->iops[BLOCK_IO_LIMIT_READ] < 0) {
313         error_setg(errp, "bps and iops values must be 0 or greater");
314         return false;
315     }
316
317     return true;
318 }
319
320 DriveInfo *drive_init(QemuOpts *all_opts, BlockInterfaceType block_default_type)
321 {
322     const char *buf;
323     const char *file = NULL;
324     const char *serial;
325     const char *mediastr = "";
326     BlockInterfaceType type;
327     enum { MEDIA_DISK, MEDIA_CDROM } media;
328     int bus_id, unit_id;
329     int cyls, heads, secs, translation;
330     BlockDriver *drv = NULL;
331     int max_devs;
332     int index;
333     int ro = 0;
334     int bdrv_flags = 0;
335     int on_read_error, on_write_error;
336     const char *devaddr;
337     DriveInfo *dinfo;
338     BlockIOLimit io_limits;
339     int snapshot = 0;
340     bool copy_on_read;
341     int ret;
342     Error *error = NULL;
343     QemuOpts *opts;
344     QDict *bs_opts;
345     const char *id;
346
347     translation = BIOS_ATA_TRANSLATION_AUTO;
348     media = MEDIA_DISK;
349
350     /* Check common options by copying from all_opts to opts, all other options
351      * are stored in bs_opts. */
352     id = qemu_opts_id(all_opts);
353     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
354     if (error_is_set(&error)) {
355         qerror_report_err(error);
356         error_free(error);
357         return NULL;
358     }
359
360     bs_opts = qdict_new();
361     qemu_opts_to_qdict(all_opts, bs_opts);
362     qemu_opts_absorb_qdict(opts, bs_opts, &error);
363     if (error_is_set(&error)) {
364         qerror_report_err(error);
365         error_free(error);
366         return NULL;
367     }
368
369     if (id) {
370         qdict_del(bs_opts, "id");
371     }
372
373     /* extract parameters */
374     bus_id  = qemu_opt_get_number(opts, "bus", 0);
375     unit_id = qemu_opt_get_number(opts, "unit", -1);
376     index   = qemu_opt_get_number(opts, "index", -1);
377
378     cyls  = qemu_opt_get_number(opts, "cyls", 0);
379     heads = qemu_opt_get_number(opts, "heads", 0);
380     secs  = qemu_opt_get_number(opts, "secs", 0);
381
382     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
383     ro = qemu_opt_get_bool(opts, "readonly", 0);
384     copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
385
386     file = qemu_opt_get(opts, "file");
387     serial = qemu_opt_get(opts, "serial");
388
389     if ((buf = qemu_opt_get(opts, "if")) != NULL) {
390         for (type = 0; type < IF_COUNT && strcmp(buf, if_name[type]); type++)
391             ;
392         if (type == IF_COUNT) {
393             error_report("unsupported bus type '%s'", buf);
394             return NULL;
395         }
396     } else {
397         type = block_default_type;
398     }
399
400     max_devs = if_max_devs[type];
401
402     if (cyls || heads || secs) {
403         if (cyls < 1) {
404             error_report("invalid physical cyls number");
405             return NULL;
406         }
407         if (heads < 1) {
408             error_report("invalid physical heads number");
409             return NULL;
410         }
411         if (secs < 1) {
412             error_report("invalid physical secs number");
413             return NULL;
414         }
415     }
416
417     if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
418         if (!cyls) {
419             error_report("'%s' trans must be used with cyls, heads and secs",
420                          buf);
421             return NULL;
422         }
423         if (!strcmp(buf, "none"))
424             translation = BIOS_ATA_TRANSLATION_NONE;
425         else if (!strcmp(buf, "lba"))
426             translation = BIOS_ATA_TRANSLATION_LBA;
427         else if (!strcmp(buf, "auto"))
428             translation = BIOS_ATA_TRANSLATION_AUTO;
429         else {
430             error_report("'%s' invalid translation type", buf);
431             return NULL;
432         }
433     }
434
435     if ((buf = qemu_opt_get(opts, "media")) != NULL) {
436         if (!strcmp(buf, "disk")) {
437             media = MEDIA_DISK;
438         } else if (!strcmp(buf, "cdrom")) {
439             if (cyls || secs || heads) {
440                 error_report("CHS can't be set with media=%s", buf);
441                 return NULL;
442             }
443             media = MEDIA_CDROM;
444         } else {
445             error_report("'%s' invalid media", buf);
446             return NULL;
447         }
448     }
449
450     if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
451         if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
452             error_report("invalid discard option");
453             return NULL;
454         }
455     }
456
457     bdrv_flags |= BDRV_O_CACHE_WB;
458     if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
459         if (bdrv_parse_cache_flags(buf, &bdrv_flags) != 0) {
460             error_report("invalid cache option");
461             return NULL;
462         }
463     }
464
465 #ifdef CONFIG_LINUX_AIO
466     if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
467         if (!strcmp(buf, "native")) {
468             bdrv_flags |= BDRV_O_NATIVE_AIO;
469         } else if (!strcmp(buf, "threads")) {
470             /* this is the default */
471         } else {
472            error_report("invalid aio option");
473            return NULL;
474         }
475     }
476 #endif
477
478     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
479         if (is_help_option(buf)) {
480             error_printf("Supported formats:");
481             bdrv_iterate_format(bdrv_format_print, NULL);
482             error_printf("\n");
483             return NULL;
484         }
485         drv = bdrv_find_whitelisted_format(buf);
486         if (!drv) {
487             error_report("'%s' invalid format", buf);
488             return NULL;
489         }
490     }
491
492     /* disk I/O throttling */
493     io_limits.bps[BLOCK_IO_LIMIT_TOTAL]  =
494                            qemu_opt_get_number(opts, "bps", 0);
495     io_limits.bps[BLOCK_IO_LIMIT_READ]   =
496                            qemu_opt_get_number(opts, "bps_rd", 0);
497     io_limits.bps[BLOCK_IO_LIMIT_WRITE]  =
498                            qemu_opt_get_number(opts, "bps_wr", 0);
499     io_limits.iops[BLOCK_IO_LIMIT_TOTAL] =
500                            qemu_opt_get_number(opts, "iops", 0);
501     io_limits.iops[BLOCK_IO_LIMIT_READ]  =
502                            qemu_opt_get_number(opts, "iops_rd", 0);
503     io_limits.iops[BLOCK_IO_LIMIT_WRITE] =
504                            qemu_opt_get_number(opts, "iops_wr", 0);
505
506     if (!do_check_io_limits(&io_limits, &error)) {
507         error_report("%s", error_get_pretty(error));
508         error_free(error);
509         return NULL;
510     }
511
512     if (qemu_opt_get(opts, "boot") != NULL) {
513         fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
514                 "ignored. Future versions will reject this parameter. Please "
515                 "update your scripts.\n");
516     }
517
518     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
519     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
520         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {
521             error_report("werror is not supported by this bus type");
522             return NULL;
523         }
524
525         on_write_error = parse_block_error_action(buf, 0);
526         if (on_write_error < 0) {
527             return NULL;
528         }
529     }
530
531     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
532     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
533         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {
534             error_report("rerror is not supported by this bus type");
535             return NULL;
536         }
537
538         on_read_error = parse_block_error_action(buf, 1);
539         if (on_read_error < 0) {
540             return NULL;
541         }
542     }
543
544     if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
545         if (type != IF_VIRTIO) {
546             error_report("addr is not supported by this bus type");
547             return NULL;
548         }
549     }
550
551     /* compute bus and unit according index */
552
553     if (index != -1) {
554         if (bus_id != 0 || unit_id != -1) {
555             error_report("index cannot be used with bus and unit");
556             return NULL;
557         }
558         bus_id = drive_index_to_bus_id(type, index);
559         unit_id = drive_index_to_unit_id(type, index);
560     }
561
562     /* if user doesn't specify a unit_id,
563      * try to find the first free
564      */
565
566     if (unit_id == -1) {
567        unit_id = 0;
568        while (drive_get(type, bus_id, unit_id) != NULL) {
569            unit_id++;
570            if (max_devs && unit_id >= max_devs) {
571                unit_id -= max_devs;
572                bus_id++;
573            }
574        }
575     }
576
577     /* check unit id */
578
579     if (max_devs && unit_id >= max_devs) {
580         error_report("unit %d too big (max is %d)",
581                      unit_id, max_devs - 1);
582         return NULL;
583     }
584
585     /*
586      * catch multiple definitions
587      */
588
589     if (drive_get(type, bus_id, unit_id) != NULL) {
590         error_report("drive with bus=%d, unit=%d (index=%d) exists",
591                      bus_id, unit_id, index);
592         return NULL;
593     }
594
595     /* init */
596
597     dinfo = g_malloc0(sizeof(*dinfo));
598     if ((buf = qemu_opts_id(opts)) != NULL) {
599         dinfo->id = g_strdup(buf);
600     } else {
601         /* no id supplied -> create one */
602         dinfo->id = g_malloc0(32);
603         if (type == IF_IDE || type == IF_SCSI)
604             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
605         if (max_devs)
606             snprintf(dinfo->id, 32, "%s%i%s%i",
607                      if_name[type], bus_id, mediastr, unit_id);
608         else
609             snprintf(dinfo->id, 32, "%s%s%i",
610                      if_name[type], mediastr, unit_id);
611     }
612     dinfo->bdrv = bdrv_new(dinfo->id);
613     dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
614     dinfo->bdrv->read_only = ro;
615     dinfo->devaddr = devaddr;
616     dinfo->type = type;
617     dinfo->bus = bus_id;
618     dinfo->unit = unit_id;
619     dinfo->cyls = cyls;
620     dinfo->heads = heads;
621     dinfo->secs = secs;
622     dinfo->trans = translation;
623     dinfo->opts = all_opts;
624     dinfo->refcount = 1;
625     if (serial != NULL) {
626         dinfo->serial = g_strdup(serial);
627     }
628     QTAILQ_INSERT_TAIL(&drives, dinfo, next);
629
630     bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
631
632     /* disk I/O throttling */
633     bdrv_set_io_limits(dinfo->bdrv, &io_limits);
634
635     switch(type) {
636     case IF_IDE:
637     case IF_SCSI:
638     case IF_XEN:
639     case IF_NONE:
640         dinfo->media_cd = media == MEDIA_CDROM;
641         break;
642     case IF_SD:
643     case IF_FLOPPY:
644     case IF_PFLASH:
645     case IF_MTD:
646         break;
647     case IF_VIRTIO:
648     {
649         /* add virtio block device */
650         QemuOpts *devopts;
651         devopts = qemu_opts_create_nofail(qemu_find_opts("device"));
652         if (arch_type == QEMU_ARCH_S390X) {
653             qemu_opt_set(devopts, "driver", "virtio-blk-s390");
654         } else {
655             qemu_opt_set(devopts, "driver", "virtio-blk-pci");
656         }
657         qemu_opt_set(devopts, "drive", dinfo->id);
658         if (devaddr)
659             qemu_opt_set(devopts, "addr", devaddr);
660         break;
661     }
662     default:
663         abort();
664     }
665     if (!file || !*file) {
666         if (qdict_size(bs_opts)) {
667             file = NULL;
668         } else {
669             return dinfo;
670         }
671     }
672     if (snapshot) {
673         /* always use cache=unsafe with snapshot */
674         bdrv_flags &= ~BDRV_O_CACHE_MASK;
675         bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
676     }
677
678     if (copy_on_read) {
679         bdrv_flags |= BDRV_O_COPY_ON_READ;
680     }
681
682     if (runstate_check(RUN_STATE_INMIGRATE)) {
683         bdrv_flags |= BDRV_O_INCOMING;
684     }
685
686     if (media == MEDIA_CDROM) {
687         /* CDROM is fine for any interface, don't check.  */
688         ro = 1;
689     } else if (ro == 1) {
690         if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY &&
691             type != IF_NONE && type != IF_PFLASH) {
692             error_report("readonly not supported by this bus type");
693             goto err;
694         }
695     }
696
697     bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
698
699     if (ro && copy_on_read) {
700         error_report("warning: disabling copy_on_read on readonly drive");
701     }
702
703     ret = bdrv_open(dinfo->bdrv, file, bs_opts, bdrv_flags, drv);
704     bs_opts = NULL;
705
706     if (ret < 0) {
707 #ifdef CONFIG_MARU
708         const char _msg[] = "Failed to load disk file from the following path. Check if the file is corrupted or missing.\n\n";
709             char* err_msg = NULL;
710         err_msg = maru_convert_path((char*)_msg, file);
711         start_simple_client(err_msg);
712         if (err_msg) {
713             g_free(err_msg);
714         }
715 #endif
716
717         if (ret == -EMEDIUMTYPE) {
718             error_report("could not open disk image %s: not in %s format",
719                          file ?: dinfo->id, drv->format_name);
720         } else {
721             error_report("could not open disk image %s: %s",
722                          file ?: dinfo->id, strerror(-ret));
723         }
724         goto err;
725     }
726
727     if (bdrv_key_required(dinfo->bdrv))
728         autostart = 0;
729
730     qemu_opts_del(opts);
731
732     return dinfo;
733
734 err:
735     qemu_opts_del(opts);
736     QDECREF(bs_opts);
737     bdrv_delete(dinfo->bdrv);
738     g_free(dinfo->id);
739     QTAILQ_REMOVE(&drives, dinfo, next);
740     g_free(dinfo);
741     return NULL;
742 }
743
744 void do_commit(Monitor *mon, const QDict *qdict)
745 {
746     const char *device = qdict_get_str(qdict, "device");
747     BlockDriverState *bs;
748     int ret;
749
750     if (!strcmp(device, "all")) {
751         ret = bdrv_commit_all();
752     } else {
753         bs = bdrv_find(device);
754         if (!bs) {
755             monitor_printf(mon, "Device '%s' not found\n", device);
756             return;
757         }
758         ret = bdrv_commit(bs);
759     }
760     if (ret < 0) {
761         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
762                        strerror(-ret));
763     }
764 }
765
766 static void blockdev_do_action(int kind, void *data, Error **errp)
767 {
768     BlockdevAction action;
769     BlockdevActionList list;
770
771     action.kind = kind;
772     action.data = data;
773     list.value = &action;
774     list.next = NULL;
775     qmp_transaction(&list, errp);
776 }
777
778 void qmp_blockdev_snapshot_sync(const char *device, const char *snapshot_file,
779                                 bool has_format, const char *format,
780                                 bool has_mode, enum NewImageMode mode,
781                                 Error **errp)
782 {
783     BlockdevSnapshot snapshot = {
784         .device = (char *) device,
785         .snapshot_file = (char *) snapshot_file,
786         .has_format = has_format,
787         .format = (char *) format,
788         .has_mode = has_mode,
789         .mode = mode,
790     };
791     blockdev_do_action(BLOCKDEV_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC, &snapshot,
792                        errp);
793 }
794
795
796 /* New and old BlockDriverState structs for group snapshots */
797 typedef struct BlkTransactionStates {
798     BlockDriverState *old_bs;
799     BlockDriverState *new_bs;
800     QSIMPLEQ_ENTRY(BlkTransactionStates) entry;
801 } BlkTransactionStates;
802
803 /*
804  * 'Atomic' group snapshots.  The snapshots are taken as a set, and if any fail
805  *  then we do not pivot any of the devices in the group, and abandon the
806  *  snapshots
807  */
808 void qmp_transaction(BlockdevActionList *dev_list, Error **errp)
809 {
810     int ret = 0;
811     BlockdevActionList *dev_entry = dev_list;
812     BlkTransactionStates *states, *next;
813     Error *local_err = NULL;
814
815     QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionStates) snap_bdrv_states;
816     QSIMPLEQ_INIT(&snap_bdrv_states);
817
818     /* drain all i/o before any snapshots */
819     bdrv_drain_all();
820
821     /* We don't do anything in this loop that commits us to the snapshot */
822     while (NULL != dev_entry) {
823         BlockdevAction *dev_info = NULL;
824         BlockDriver *proto_drv;
825         BlockDriver *drv;
826         int flags;
827         enum NewImageMode mode;
828         const char *new_image_file;
829         const char *device;
830         const char *format = "qcow2";
831
832         dev_info = dev_entry->value;
833         dev_entry = dev_entry->next;
834
835         states = g_malloc0(sizeof(BlkTransactionStates));
836         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, states, entry);
837
838         switch (dev_info->kind) {
839         case BLOCKDEV_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
840             device = dev_info->blockdev_snapshot_sync->device;
841             if (!dev_info->blockdev_snapshot_sync->has_mode) {
842                 dev_info->blockdev_snapshot_sync->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
843             }
844             new_image_file = dev_info->blockdev_snapshot_sync->snapshot_file;
845             if (dev_info->blockdev_snapshot_sync->has_format) {
846                 format = dev_info->blockdev_snapshot_sync->format;
847             }
848             mode = dev_info->blockdev_snapshot_sync->mode;
849             break;
850         default:
851             abort();
852         }
853
854         drv = bdrv_find_format(format);
855         if (!drv) {
856             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
857             goto delete_and_fail;
858         }
859
860         states->old_bs = bdrv_find(device);
861         if (!states->old_bs) {
862             error_set(errp, QERR_DEVICE_NOT_FOUND, device);
863             goto delete_and_fail;
864         }
865
866         if (!bdrv_is_inserted(states->old_bs)) {
867             error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
868             goto delete_and_fail;
869         }
870
871         if (bdrv_in_use(states->old_bs)) {
872             error_set(errp, QERR_DEVICE_IN_USE, device);
873             goto delete_and_fail;
874         }
875
876         if (!bdrv_is_read_only(states->old_bs)) {
877             if (bdrv_flush(states->old_bs)) {
878                 error_set(errp, QERR_IO_ERROR);
879                 goto delete_and_fail;
880             }
881         }
882
883         flags = states->old_bs->open_flags;
884
885         proto_drv = bdrv_find_protocol(new_image_file);
886         if (!proto_drv) {
887             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
888             goto delete_and_fail;
889         }
890
891         /* create new image w/backing file */
892         if (mode != NEW_IMAGE_MODE_EXISTING) {
893             bdrv_img_create(new_image_file, format,
894                             states->old_bs->filename,
895                             states->old_bs->drv->format_name,
896                             NULL, -1, flags, &local_err, false);
897             if (error_is_set(&local_err)) {
898                 error_propagate(errp, local_err);
899                 goto delete_and_fail;
900             }
901         }
902
903         /* We will manually add the backing_hd field to the bs later */
904         states->new_bs = bdrv_new("");
905         /* TODO Inherit bs->options or only take explicit options with an
906          * extended QMP command? */
907         ret = bdrv_open(states->new_bs, new_image_file, NULL,
908                         flags | BDRV_O_NO_BACKING, drv);
909         if (ret != 0) {
910             error_set(errp, QERR_OPEN_FILE_FAILED, new_image_file);
911             goto delete_and_fail;
912         }
913     }
914
915
916     /* Now we are going to do the actual pivot.  Everything up to this point
917      * is reversible, but we are committed at this point */
918     QSIMPLEQ_FOREACH(states, &snap_bdrv_states, entry) {
919         /* This removes our old bs from the bdrv_states, and adds the new bs */
920         bdrv_append(states->new_bs, states->old_bs);
921         /* We don't need (or want) to use the transactional
922          * bdrv_reopen_multiple() across all the entries at once, because we
923          * don't want to abort all of them if one of them fails the reopen */
924         bdrv_reopen(states->new_bs, states->new_bs->open_flags & ~BDRV_O_RDWR,
925                     NULL);
926     }
927
928     /* success */
929     goto exit;
930
931 delete_and_fail:
932     /*
933     * failure, and it is all-or-none; abandon each new bs, and keep using
934     * the original bs for all images
935     */
936     QSIMPLEQ_FOREACH(states, &snap_bdrv_states, entry) {
937         if (states->new_bs) {
938              bdrv_delete(states->new_bs);
939         }
940     }
941 exit:
942     QSIMPLEQ_FOREACH_SAFE(states, &snap_bdrv_states, entry, next) {
943         g_free(states);
944     }
945 }
946
947
948 static void eject_device(BlockDriverState *bs, int force, Error **errp)
949 {
950     if (bdrv_in_use(bs)) {
951         error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
952         return;
953     }
954     if (!bdrv_dev_has_removable_media(bs)) {
955         error_set(errp, QERR_DEVICE_NOT_REMOVABLE, bdrv_get_device_name(bs));
956         return;
957     }
958
959     if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
960         bdrv_dev_eject_request(bs, force);
961         if (!force) {
962             error_set(errp, QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
963             return;
964         }
965     }
966
967     bdrv_close(bs);
968 }
969
970 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
971 {
972     BlockDriverState *bs;
973
974     bs = bdrv_find(device);
975     if (!bs) {
976         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
977         return;
978     }
979
980     eject_device(bs, force, errp);
981 }
982
983 void qmp_block_passwd(const char *device, const char *password, Error **errp)
984 {
985     BlockDriverState *bs;
986     int err;
987
988     bs = bdrv_find(device);
989     if (!bs) {
990         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
991         return;
992     }
993
994     err = bdrv_set_key(bs, password);
995     if (err == -EINVAL) {
996         error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
997         return;
998     } else if (err < 0) {
999         error_set(errp, QERR_INVALID_PASSWORD);
1000         return;
1001     }
1002 }
1003
1004 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1005                                     int bdrv_flags, BlockDriver *drv,
1006                                     const char *password, Error **errp)
1007 {
1008     if (bdrv_open(bs, filename, NULL, bdrv_flags, drv) < 0) {
1009         error_set(errp, QERR_OPEN_FILE_FAILED, filename);
1010         return;
1011     }
1012
1013     if (bdrv_key_required(bs)) {
1014         if (password) {
1015             if (bdrv_set_key(bs, password) < 0) {
1016                 error_set(errp, QERR_INVALID_PASSWORD);
1017             }
1018         } else {
1019             error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1020                       bdrv_get_encrypted_filename(bs));
1021         }
1022     } else if (password) {
1023         error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1024     }
1025 }
1026
1027 void qmp_change_blockdev(const char *device, const char *filename,
1028                          bool has_format, const char *format, Error **errp)
1029 {
1030     BlockDriverState *bs;
1031     BlockDriver *drv = NULL;
1032     int bdrv_flags;
1033     Error *err = NULL;
1034
1035     bs = bdrv_find(device);
1036     if (!bs) {
1037         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1038         return;
1039     }
1040
1041     if (format) {
1042         drv = bdrv_find_whitelisted_format(format);
1043         if (!drv) {
1044             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1045             return;
1046         }
1047     }
1048
1049     eject_device(bs, 0, &err);
1050     if (error_is_set(&err)) {
1051         error_propagate(errp, err);
1052         return;
1053     }
1054
1055     bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1056     bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1057
1058     qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1059 }
1060
1061 /* throttling disk I/O limits */
1062 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1063                                int64_t bps_wr, int64_t iops, int64_t iops_rd,
1064                                int64_t iops_wr, Error **errp)
1065 {
1066     BlockIOLimit io_limits;
1067     BlockDriverState *bs;
1068
1069     bs = bdrv_find(device);
1070     if (!bs) {
1071         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1072         return;
1073     }
1074
1075     io_limits.bps[BLOCK_IO_LIMIT_TOTAL] = bps;
1076     io_limits.bps[BLOCK_IO_LIMIT_READ]  = bps_rd;
1077     io_limits.bps[BLOCK_IO_LIMIT_WRITE] = bps_wr;
1078     io_limits.iops[BLOCK_IO_LIMIT_TOTAL]= iops;
1079     io_limits.iops[BLOCK_IO_LIMIT_READ] = iops_rd;
1080     io_limits.iops[BLOCK_IO_LIMIT_WRITE]= iops_wr;
1081
1082     if (!do_check_io_limits(&io_limits, errp)) {
1083         return;
1084     }
1085
1086     bs->io_limits = io_limits;
1087
1088     if (!bs->io_limits_enabled && bdrv_io_limits_enabled(bs)) {
1089         bdrv_io_limits_enable(bs);
1090     } else if (bs->io_limits_enabled && !bdrv_io_limits_enabled(bs)) {
1091         bdrv_io_limits_disable(bs);
1092     } else {
1093         if (bs->block_timer) {
1094             qemu_mod_timer(bs->block_timer, qemu_get_clock_ns(vm_clock));
1095         }
1096     }
1097 }
1098
1099 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1100 {
1101     const char *id = qdict_get_str(qdict, "id");
1102     BlockDriverState *bs;
1103
1104     bs = bdrv_find(id);
1105     if (!bs) {
1106         qerror_report(QERR_DEVICE_NOT_FOUND, id);
1107         return -1;
1108     }
1109     if (bdrv_in_use(bs)) {
1110         qerror_report(QERR_DEVICE_IN_USE, id);
1111         return -1;
1112     }
1113
1114     /* quiesce block driver; prevent further io */
1115     bdrv_drain_all();
1116     bdrv_flush(bs);
1117     bdrv_close(bs);
1118
1119     /* if we have a device attached to this BlockDriverState
1120      * then we need to make the drive anonymous until the device
1121      * can be removed.  If this is a drive with no device backing
1122      * then we can just get rid of the block driver state right here.
1123      */
1124     if (bdrv_get_attached_dev(bs)) {
1125         bdrv_make_anon(bs);
1126
1127         /* Further I/O must not pause the guest */
1128         bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1129                           BLOCKDEV_ON_ERROR_REPORT);
1130     } else {
1131         drive_uninit(drive_get_by_blockdev(bs));
1132     }
1133
1134     return 0;
1135 }
1136
1137 void qmp_block_resize(const char *device, int64_t size, Error **errp)
1138 {
1139     BlockDriverState *bs;
1140     int ret;
1141
1142     bs = bdrv_find(device);
1143     if (!bs) {
1144         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1145         return;
1146     }
1147
1148     if (size < 0) {
1149         error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1150         return;
1151     }
1152
1153     /* complete all in-flight operations before resizing the device */
1154     bdrv_drain_all();
1155
1156     ret = bdrv_truncate(bs, size);
1157     switch (ret) {
1158     case 0:
1159         break;
1160     case -ENOMEDIUM:
1161         error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1162         break;
1163     case -ENOTSUP:
1164         error_set(errp, QERR_UNSUPPORTED);
1165         break;
1166     case -EACCES:
1167         error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1168         break;
1169     case -EBUSY:
1170         error_set(errp, QERR_DEVICE_IN_USE, device);
1171         break;
1172     default:
1173         error_setg_errno(errp, -ret, "Could not resize");
1174         break;
1175     }
1176 }
1177
1178 static void block_job_cb(void *opaque, int ret)
1179 {
1180     BlockDriverState *bs = opaque;
1181     QObject *obj;
1182
1183     trace_block_job_cb(bs, bs->job, ret);
1184
1185     assert(bs->job);
1186     obj = qobject_from_block_job(bs->job);
1187     if (ret < 0) {
1188         QDict *dict = qobject_to_qdict(obj);
1189         qdict_put(dict, "error", qstring_from_str(strerror(-ret)));
1190     }
1191
1192     if (block_job_is_cancelled(bs->job)) {
1193         monitor_protocol_event(QEVENT_BLOCK_JOB_CANCELLED, obj);
1194     } else {
1195         monitor_protocol_event(QEVENT_BLOCK_JOB_COMPLETED, obj);
1196     }
1197     qobject_decref(obj);
1198
1199     drive_put_ref_bh_schedule(drive_get_by_blockdev(bs));
1200 }
1201
1202 void qmp_block_stream(const char *device, bool has_base,
1203                       const char *base, bool has_speed, int64_t speed,
1204                       bool has_on_error, BlockdevOnError on_error,
1205                       Error **errp)
1206 {
1207     BlockDriverState *bs;
1208     BlockDriverState *base_bs = NULL;
1209     Error *local_err = NULL;
1210
1211     if (!has_on_error) {
1212         on_error = BLOCKDEV_ON_ERROR_REPORT;
1213     }
1214
1215     bs = bdrv_find(device);
1216     if (!bs) {
1217         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1218         return;
1219     }
1220
1221     if (base) {
1222         base_bs = bdrv_find_backing_image(bs, base);
1223         if (base_bs == NULL) {
1224             error_set(errp, QERR_BASE_NOT_FOUND, base);
1225             return;
1226         }
1227     }
1228
1229     stream_start(bs, base_bs, base, has_speed ? speed : 0,
1230                  on_error, block_job_cb, bs, &local_err);
1231     if (error_is_set(&local_err)) {
1232         error_propagate(errp, local_err);
1233         return;
1234     }
1235
1236     /* Grab a reference so hotplug does not delete the BlockDriverState from
1237      * underneath us.
1238      */
1239     drive_get_ref(drive_get_by_blockdev(bs));
1240
1241     trace_qmp_block_stream(bs, bs->job);
1242 }
1243
1244 void qmp_block_commit(const char *device,
1245                       bool has_base, const char *base, const char *top,
1246                       bool has_speed, int64_t speed,
1247                       Error **errp)
1248 {
1249     BlockDriverState *bs;
1250     BlockDriverState *base_bs, *top_bs;
1251     Error *local_err = NULL;
1252     /* This will be part of the QMP command, if/when the
1253      * BlockdevOnError change for blkmirror makes it in
1254      */
1255     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1256
1257     /* drain all i/o before commits */
1258     bdrv_drain_all();
1259
1260     bs = bdrv_find(device);
1261     if (!bs) {
1262         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1263         return;
1264     }
1265
1266     /* default top_bs is the active layer */
1267     top_bs = bs;
1268
1269     if (top) {
1270         if (strcmp(bs->filename, top) != 0) {
1271             top_bs = bdrv_find_backing_image(bs, top);
1272         }
1273     }
1274
1275     if (top_bs == NULL) {
1276         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1277         return;
1278     }
1279
1280     if (has_base && base) {
1281         base_bs = bdrv_find_backing_image(top_bs, base);
1282     } else {
1283         base_bs = bdrv_find_base(top_bs);
1284     }
1285
1286     if (base_bs == NULL) {
1287         error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1288         return;
1289     }
1290
1291     commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
1292                 &local_err);
1293     if (local_err != NULL) {
1294         error_propagate(errp, local_err);
1295         return;
1296     }
1297     /* Grab a reference so hotplug does not delete the BlockDriverState from
1298      * underneath us.
1299      */
1300     drive_get_ref(drive_get_by_blockdev(bs));
1301 }
1302
1303 #define DEFAULT_MIRROR_BUF_SIZE   (10 << 20)
1304
1305 void qmp_drive_mirror(const char *device, const char *target,
1306                       bool has_format, const char *format,
1307                       enum MirrorSyncMode sync,
1308                       bool has_mode, enum NewImageMode mode,
1309                       bool has_speed, int64_t speed,
1310                       bool has_granularity, uint32_t granularity,
1311                       bool has_buf_size, int64_t buf_size,
1312                       bool has_on_source_error, BlockdevOnError on_source_error,
1313                       bool has_on_target_error, BlockdevOnError on_target_error,
1314                       Error **errp)
1315 {
1316     BlockDriverState *bs;
1317     BlockDriverState *source, *target_bs;
1318     BlockDriver *proto_drv;
1319     BlockDriver *drv = NULL;
1320     Error *local_err = NULL;
1321     int flags;
1322     uint64_t size;
1323     int ret;
1324
1325     if (!has_speed) {
1326         speed = 0;
1327     }
1328     if (!has_on_source_error) {
1329         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1330     }
1331     if (!has_on_target_error) {
1332         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1333     }
1334     if (!has_mode) {
1335         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1336     }
1337     if (!has_granularity) {
1338         granularity = 0;
1339     }
1340     if (!has_buf_size) {
1341         buf_size = DEFAULT_MIRROR_BUF_SIZE;
1342     }
1343
1344     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
1345         error_set(errp, QERR_INVALID_PARAMETER, device);
1346         return;
1347     }
1348     if (granularity & (granularity - 1)) {
1349         error_set(errp, QERR_INVALID_PARAMETER, device);
1350         return;
1351     }
1352
1353     bs = bdrv_find(device);
1354     if (!bs) {
1355         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1356         return;
1357     }
1358
1359     if (!bdrv_is_inserted(bs)) {
1360         error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1361         return;
1362     }
1363
1364     if (!has_format) {
1365         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
1366     }
1367     if (format) {
1368         drv = bdrv_find_format(format);
1369         if (!drv) {
1370             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1371             return;
1372         }
1373     }
1374
1375     if (bdrv_in_use(bs)) {
1376         error_set(errp, QERR_DEVICE_IN_USE, device);
1377         return;
1378     }
1379
1380     flags = bs->open_flags | BDRV_O_RDWR;
1381     source = bs->backing_hd;
1382     if (!source && sync == MIRROR_SYNC_MODE_TOP) {
1383         sync = MIRROR_SYNC_MODE_FULL;
1384     }
1385
1386     proto_drv = bdrv_find_protocol(target);
1387     if (!proto_drv) {
1388         error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1389         return;
1390     }
1391
1392     bdrv_get_geometry(bs, &size);
1393     size *= 512;
1394     if (sync == MIRROR_SYNC_MODE_FULL && mode != NEW_IMAGE_MODE_EXISTING) {
1395         /* create new image w/o backing file */
1396         assert(format && drv);
1397         bdrv_img_create(target, format,
1398                         NULL, NULL, NULL, size, flags, &local_err, false);
1399     } else {
1400         switch (mode) {
1401         case NEW_IMAGE_MODE_EXISTING:
1402             ret = 0;
1403             break;
1404         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
1405             /* create new image with backing file */
1406             bdrv_img_create(target, format,
1407                             source->filename,
1408                             source->drv->format_name,
1409                             NULL, size, flags, &local_err, false);
1410             break;
1411         default:
1412             abort();
1413         }
1414     }
1415
1416     if (error_is_set(&local_err)) {
1417         error_propagate(errp, local_err);
1418         return;
1419     }
1420
1421     /* Mirroring takes care of copy-on-write using the source's backing
1422      * file.
1423      */
1424     target_bs = bdrv_new("");
1425     ret = bdrv_open(target_bs, target, NULL, flags | BDRV_O_NO_BACKING, drv);
1426
1427     if (ret < 0) {
1428         bdrv_delete(target_bs);
1429         error_set(errp, QERR_OPEN_FILE_FAILED, target);
1430         return;
1431     }
1432
1433     mirror_start(bs, target_bs, speed, granularity, buf_size, sync,
1434                  on_source_error, on_target_error,
1435                  block_job_cb, bs, &local_err);
1436     if (local_err != NULL) {
1437         bdrv_delete(target_bs);
1438         error_propagate(errp, local_err);
1439         return;
1440     }
1441
1442     /* Grab a reference so hotplug does not delete the BlockDriverState from
1443      * underneath us.
1444      */
1445     drive_get_ref(drive_get_by_blockdev(bs));
1446 }
1447
1448 static BlockJob *find_block_job(const char *device)
1449 {
1450     BlockDriverState *bs;
1451
1452     bs = bdrv_find(device);
1453     if (!bs || !bs->job) {
1454         return NULL;
1455     }
1456     return bs->job;
1457 }
1458
1459 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
1460 {
1461     BlockJob *job = find_block_job(device);
1462
1463     if (!job) {
1464         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1465         return;
1466     }
1467
1468     block_job_set_speed(job, speed, errp);
1469 }
1470
1471 void qmp_block_job_cancel(const char *device,
1472                           bool has_force, bool force, Error **errp)
1473 {
1474     BlockJob *job = find_block_job(device);
1475
1476     if (!has_force) {
1477         force = false;
1478     }
1479
1480     if (!job) {
1481         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1482         return;
1483     }
1484     if (job->paused && !force) {
1485         error_set(errp, QERR_BLOCK_JOB_PAUSED, device);
1486         return;
1487     }
1488
1489     trace_qmp_block_job_cancel(job);
1490     block_job_cancel(job);
1491 }
1492
1493 void qmp_block_job_pause(const char *device, Error **errp)
1494 {
1495     BlockJob *job = find_block_job(device);
1496
1497     if (!job) {
1498         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1499         return;
1500     }
1501
1502     trace_qmp_block_job_pause(job);
1503     block_job_pause(job);
1504 }
1505
1506 void qmp_block_job_resume(const char *device, Error **errp)
1507 {
1508     BlockJob *job = find_block_job(device);
1509
1510     if (!job) {
1511         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1512         return;
1513     }
1514
1515     trace_qmp_block_job_resume(job);
1516     block_job_resume(job);
1517 }
1518
1519 void qmp_block_job_complete(const char *device, Error **errp)
1520 {
1521     BlockJob *job = find_block_job(device);
1522
1523     if (!job) {
1524         error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1525         return;
1526     }
1527
1528     trace_qmp_block_job_complete(job);
1529     block_job_complete(job, errp);
1530 }
1531
1532 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
1533 {
1534     BlockJobInfoList **prev = opaque;
1535     BlockJob *job = bs->job;
1536
1537     if (job) {
1538         BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
1539         elem->value = block_job_query(bs->job);
1540         (*prev)->next = elem;
1541         *prev = elem;
1542     }
1543 }
1544
1545 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
1546 {
1547     /* Dummy is a fake list element for holding the head pointer */
1548     BlockJobInfoList dummy = {};
1549     BlockJobInfoList *prev = &dummy;
1550     bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
1551     return dummy.next;
1552 }
1553
1554 QemuOptsList qemu_common_drive_opts = {
1555     .name = "drive",
1556     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
1557     .desc = {
1558         {
1559             .name = "bus",
1560             .type = QEMU_OPT_NUMBER,
1561             .help = "bus number",
1562         },{
1563             .name = "unit",
1564             .type = QEMU_OPT_NUMBER,
1565             .help = "unit number (i.e. lun for scsi)",
1566         },{
1567             .name = "if",
1568             .type = QEMU_OPT_STRING,
1569             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
1570         },{
1571             .name = "index",
1572             .type = QEMU_OPT_NUMBER,
1573             .help = "index number",
1574         },{
1575             .name = "cyls",
1576             .type = QEMU_OPT_NUMBER,
1577             .help = "number of cylinders (ide disk geometry)",
1578         },{
1579             .name = "heads",
1580             .type = QEMU_OPT_NUMBER,
1581             .help = "number of heads (ide disk geometry)",
1582         },{
1583             .name = "secs",
1584             .type = QEMU_OPT_NUMBER,
1585             .help = "number of sectors (ide disk geometry)",
1586         },{
1587             .name = "trans",
1588             .type = QEMU_OPT_STRING,
1589             .help = "chs translation (auto, lba. none)",
1590         },{
1591             .name = "media",
1592             .type = QEMU_OPT_STRING,
1593             .help = "media type (disk, cdrom)",
1594         },{
1595             .name = "snapshot",
1596             .type = QEMU_OPT_BOOL,
1597             .help = "enable/disable snapshot mode",
1598         },{
1599             .name = "file",
1600             .type = QEMU_OPT_STRING,
1601             .help = "disk image",
1602         },{
1603             .name = "discard",
1604             .type = QEMU_OPT_STRING,
1605             .help = "discard operation (ignore/off, unmap/on)",
1606         },{
1607             .name = "cache",
1608             .type = QEMU_OPT_STRING,
1609             .help = "host cache usage (none, writeback, writethrough, "
1610                     "directsync, unsafe)",
1611         },{
1612             .name = "aio",
1613             .type = QEMU_OPT_STRING,
1614             .help = "host AIO implementation (threads, native)",
1615         },{
1616             .name = "format",
1617             .type = QEMU_OPT_STRING,
1618             .help = "disk format (raw, qcow2, ...)",
1619         },{
1620             .name = "serial",
1621             .type = QEMU_OPT_STRING,
1622             .help = "disk serial number",
1623         },{
1624             .name = "rerror",
1625             .type = QEMU_OPT_STRING,
1626             .help = "read error action",
1627         },{
1628             .name = "werror",
1629             .type = QEMU_OPT_STRING,
1630             .help = "write error action",
1631         },{
1632             .name = "addr",
1633             .type = QEMU_OPT_STRING,
1634             .help = "pci address (virtio only)",
1635         },{
1636             .name = "readonly",
1637             .type = QEMU_OPT_BOOL,
1638             .help = "open drive file as read-only",
1639         },{
1640             .name = "iops",
1641             .type = QEMU_OPT_NUMBER,
1642             .help = "limit total I/O operations per second",
1643         },{
1644             .name = "iops_rd",
1645             .type = QEMU_OPT_NUMBER,
1646             .help = "limit read operations per second",
1647         },{
1648             .name = "iops_wr",
1649             .type = QEMU_OPT_NUMBER,
1650             .help = "limit write operations per second",
1651         },{
1652             .name = "bps",
1653             .type = QEMU_OPT_NUMBER,
1654             .help = "limit total bytes per second",
1655         },{
1656             .name = "bps_rd",
1657             .type = QEMU_OPT_NUMBER,
1658             .help = "limit read bytes per second",
1659         },{
1660             .name = "bps_wr",
1661             .type = QEMU_OPT_NUMBER,
1662             .help = "limit write bytes per second",
1663         },{
1664             .name = "copy-on-read",
1665             .type = QEMU_OPT_BOOL,
1666             .help = "copy read data from backing file into image file",
1667         },{
1668             .name = "boot",
1669             .type = QEMU_OPT_BOOL,
1670             .help = "(deprecated, ignored)",
1671         },
1672         { /* end of list */ }
1673     },
1674 };
1675
1676 QemuOptsList qemu_drive_opts = {
1677     .name = "drive",
1678     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
1679     .desc = {
1680         {
1681             .name = "bus",
1682             .type = QEMU_OPT_NUMBER,
1683             .help = "bus number",
1684         },{
1685             .name = "unit",
1686             .type = QEMU_OPT_NUMBER,
1687             .help = "unit number (i.e. lun for scsi)",
1688         },{
1689             .name = "if",
1690             .type = QEMU_OPT_STRING,
1691             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
1692         },{
1693             .name = "index",
1694             .type = QEMU_OPT_NUMBER,
1695             .help = "index number",
1696         },{
1697             .name = "cyls",
1698             .type = QEMU_OPT_NUMBER,
1699             .help = "number of cylinders (ide disk geometry)",
1700         },{
1701             .name = "heads",
1702             .type = QEMU_OPT_NUMBER,
1703             .help = "number of heads (ide disk geometry)",
1704         },{
1705             .name = "secs",
1706             .type = QEMU_OPT_NUMBER,
1707             .help = "number of sectors (ide disk geometry)",
1708         },{
1709             .name = "trans",
1710             .type = QEMU_OPT_STRING,
1711             .help = "chs translation (auto, lba. none)",
1712         },{
1713             .name = "media",
1714             .type = QEMU_OPT_STRING,
1715             .help = "media type (disk, cdrom)",
1716         },{
1717             .name = "snapshot",
1718             .type = QEMU_OPT_BOOL,
1719             .help = "enable/disable snapshot mode",
1720         },{
1721             .name = "file",
1722             .type = QEMU_OPT_STRING,
1723             .help = "disk image",
1724         },{
1725             .name = "discard",
1726             .type = QEMU_OPT_STRING,
1727             .help = "discard operation (ignore/off, unmap/on)",
1728         },{
1729             .name = "cache",
1730             .type = QEMU_OPT_STRING,
1731             .help = "host cache usage (none, writeback, writethrough, "
1732                     "directsync, unsafe)",
1733         },{
1734             .name = "aio",
1735             .type = QEMU_OPT_STRING,
1736             .help = "host AIO implementation (threads, native)",
1737         },{
1738             .name = "format",
1739             .type = QEMU_OPT_STRING,
1740             .help = "disk format (raw, qcow2, ...)",
1741         },{
1742             .name = "serial",
1743             .type = QEMU_OPT_STRING,
1744             .help = "disk serial number",
1745         },{
1746             .name = "rerror",
1747             .type = QEMU_OPT_STRING,
1748             .help = "read error action",
1749         },{
1750             .name = "werror",
1751             .type = QEMU_OPT_STRING,
1752             .help = "write error action",
1753         },{
1754             .name = "addr",
1755             .type = QEMU_OPT_STRING,
1756             .help = "pci address (virtio only)",
1757         },{
1758             .name = "readonly",
1759             .type = QEMU_OPT_BOOL,
1760             .help = "open drive file as read-only",
1761         },{
1762             .name = "iops",
1763             .type = QEMU_OPT_NUMBER,
1764             .help = "limit total I/O operations per second",
1765         },{
1766             .name = "iops_rd",
1767             .type = QEMU_OPT_NUMBER,
1768             .help = "limit read operations per second",
1769         },{
1770             .name = "iops_wr",
1771             .type = QEMU_OPT_NUMBER,
1772             .help = "limit write operations per second",
1773         },{
1774             .name = "bps",
1775             .type = QEMU_OPT_NUMBER,
1776             .help = "limit total bytes per second",
1777         },{
1778             .name = "bps_rd",
1779             .type = QEMU_OPT_NUMBER,
1780             .help = "limit read bytes per second",
1781         },{
1782             .name = "bps_wr",
1783             .type = QEMU_OPT_NUMBER,
1784             .help = "limit write bytes per second",
1785         },{
1786             .name = "copy-on-read",
1787             .type = QEMU_OPT_BOOL,
1788             .help = "copy read data from backing file into image file",
1789         },{
1790             .name = "boot",
1791             .type = QEMU_OPT_BOOL,
1792             .help = "(deprecated, ignored)",
1793         },
1794         { /* end of list */ }
1795     },
1796 };