sync with latest
[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
10 #include "blockdev.h"
11 #include "hw/block-common.h"
12 #include "monitor.h"
13 #include "qerror.h"
14 #include "qemu-option.h"
15 #include "qemu-config.h"
16 #include "qemu-objects.h"
17 #include "sysemu.h"
18 #include "block_int.h"
19 #include "qmp-commands.h"
20 #include "trace.h"
21 #include "arch_init.h"
22
23 static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
24
25 static const char *const if_name[IF_COUNT] = {
26     [IF_NONE] = "none",
27     [IF_IDE] = "ide",
28     [IF_SCSI] = "scsi",
29     [IF_FLOPPY] = "floppy",
30     [IF_PFLASH] = "pflash",
31     [IF_MTD] = "mtd",
32     [IF_SD] = "sd",
33     [IF_VIRTIO] = "virtio",
34     [IF_XEN] = "xen",
35 };
36
37 static const int if_max_devs[IF_COUNT] = {
38     /*
39      * Do not change these numbers!  They govern how drive option
40      * index maps to unit and bus.  That mapping is ABI.
41      *
42      * All controllers used to imlement if=T drives need to support
43      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
44      * Otherwise, some index values map to "impossible" bus, unit
45      * values.
46      *
47      * For instance, if you change [IF_SCSI] to 255, -drive
48      * if=scsi,index=12 no longer means bus=1,unit=5, but
49      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
50      * the drive can't be set up.  Regression.
51      */
52     [IF_IDE] = 2,
53     [IF_SCSI] = 7,
54 };
55
56 /*
57  * We automatically delete the drive when a device using it gets
58  * unplugged.  Questionable feature, but we can't just drop it.
59  * Device models call blockdev_mark_auto_del() to schedule the
60  * automatic deletion, and generic qdev code calls blockdev_auto_del()
61  * when deletion is actually safe.
62  */
63 void blockdev_mark_auto_del(BlockDriverState *bs)
64 {
65     DriveInfo *dinfo = drive_get_by_blockdev(bs);
66
67     if (bs->job) {
68         block_job_cancel(bs->job);
69     }
70     if (dinfo) {
71         dinfo->auto_del = 1;
72     }
73 }
74
75 void blockdev_auto_del(BlockDriverState *bs)
76 {
77     DriveInfo *dinfo = drive_get_by_blockdev(bs);
78
79     if (dinfo && dinfo->auto_del) {
80         drive_put_ref(dinfo);
81     }
82 }
83
84 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
85 {
86     int max_devs = if_max_devs[type];
87     return max_devs ? index / max_devs : 0;
88 }
89
90 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
91 {
92     int max_devs = if_max_devs[type];
93     return max_devs ? index % max_devs : index;
94 }
95
96 QemuOpts *drive_def(const char *optstr)
97 {
98     return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
99 }
100
101 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
102                     const char *optstr)
103 {
104     QemuOpts *opts;
105     char buf[32];
106
107     opts = drive_def(optstr);
108     if (!opts) {
109         return NULL;
110     }
111     if (type != IF_DEFAULT) {
112         qemu_opt_set(opts, "if", if_name[type]);
113     }
114     if (index >= 0) {
115         snprintf(buf, sizeof(buf), "%d", index);
116         qemu_opt_set(opts, "index", buf);
117     }
118     if (file)
119         qemu_opt_set(opts, "file", file);
120     return opts;
121 }
122
123 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
124 {
125     DriveInfo *dinfo;
126
127     /* seek interface, bus and unit */
128
129     QTAILQ_FOREACH(dinfo, &drives, next) {
130         if (dinfo->type == type &&
131             dinfo->bus == bus &&
132             dinfo->unit == unit)
133             return dinfo;
134     }
135
136     return NULL;
137 }
138
139 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
140 {
141     return drive_get(type,
142                      drive_index_to_bus_id(type, index),
143                      drive_index_to_unit_id(type, index));
144 }
145
146 int drive_get_max_bus(BlockInterfaceType type)
147 {
148     int max_bus;
149     DriveInfo *dinfo;
150
151     max_bus = -1;
152     QTAILQ_FOREACH(dinfo, &drives, next) {
153         if(dinfo->type == type &&
154            dinfo->bus > max_bus)
155             max_bus = dinfo->bus;
156     }
157     return max_bus;
158 }
159
160 /* Get a block device.  This should only be used for single-drive devices
161    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
162    appropriate bus.  */
163 DriveInfo *drive_get_next(BlockInterfaceType type)
164 {
165     static int next_block_unit[IF_COUNT];
166
167     return drive_get(type, 0, next_block_unit[type]++);
168 }
169
170 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
171 {
172     DriveInfo *dinfo;
173
174     QTAILQ_FOREACH(dinfo, &drives, next) {
175         if (dinfo->bdrv == bs) {
176             return dinfo;
177         }
178     }
179     return NULL;
180 }
181
182 static void bdrv_format_print(void *opaque, const char *name)
183 {
184     error_printf(" %s", name);
185 }
186
187 static void drive_uninit(DriveInfo *dinfo)
188 {
189     qemu_opts_del(dinfo->opts);
190     bdrv_delete(dinfo->bdrv);
191     g_free(dinfo->id);
192     QTAILQ_REMOVE(&drives, dinfo, next);
193     g_free(dinfo);
194 }
195
196 void drive_put_ref(DriveInfo *dinfo)
197 {
198     assert(dinfo->refcount);
199     if (--dinfo->refcount == 0) {
200         drive_uninit(dinfo);
201     }
202 }
203
204 void drive_get_ref(DriveInfo *dinfo)
205 {
206     dinfo->refcount++;
207 }
208
209 typedef struct {
210     QEMUBH *bh;
211     DriveInfo *dinfo;
212 } DrivePutRefBH;
213
214 static void drive_put_ref_bh(void *opaque)
215 {
216     DrivePutRefBH *s = opaque;
217
218     drive_put_ref(s->dinfo);
219     qemu_bh_delete(s->bh);
220     g_free(s);
221 }
222
223 /*
224  * Release a drive reference in a BH
225  *
226  * It is not possible to use drive_put_ref() from a callback function when the
227  * callers still need the drive.  In such cases we schedule a BH to release the
228  * reference.
229  */
230 static void drive_put_ref_bh_schedule(DriveInfo *dinfo)
231 {
232     DrivePutRefBH *s;
233
234     s = g_new(DrivePutRefBH, 1);
235     s->bh = qemu_bh_new(drive_put_ref_bh, s);
236     s->dinfo = dinfo;
237     qemu_bh_schedule(s->bh);
238 }
239
240 static int parse_block_error_action(const char *buf, int is_read)
241 {
242     if (!strcmp(buf, "ignore")) {
243         return BLOCK_ERR_IGNORE;
244     } else if (!is_read && !strcmp(buf, "enospc")) {
245         return BLOCK_ERR_STOP_ENOSPC;
246     } else if (!strcmp(buf, "stop")) {
247         return BLOCK_ERR_STOP_ANY;
248     } else if (!strcmp(buf, "report")) {
249         return BLOCK_ERR_REPORT;
250     } else {
251         error_report("'%s' invalid %s error action",
252                      buf, is_read ? "read" : "write");
253         return -1;
254     }
255 }
256
257 #ifdef CONFIG_MARU
258 extern int start_simple_client(char* msg);
259 extern char* maru_convert_path(char* msg, const char *path);
260 #endif
261
262 static bool do_check_io_limits(BlockIOLimit *io_limits)
263 {
264     bool bps_flag;
265     bool iops_flag;
266
267     assert(io_limits);
268
269     bps_flag  = (io_limits->bps[BLOCK_IO_LIMIT_TOTAL] != 0)
270                  && ((io_limits->bps[BLOCK_IO_LIMIT_READ] != 0)
271                  || (io_limits->bps[BLOCK_IO_LIMIT_WRITE] != 0));
272     iops_flag = (io_limits->iops[BLOCK_IO_LIMIT_TOTAL] != 0)
273                  && ((io_limits->iops[BLOCK_IO_LIMIT_READ] != 0)
274                  || (io_limits->iops[BLOCK_IO_LIMIT_WRITE] != 0));
275     if (bps_flag || iops_flag) {
276         return false;
277     }
278
279     return true;
280 }
281
282 DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)
283 {
284     const char *buf;
285     const char *file = NULL;
286     const char *serial;
287     const char *mediastr = "";
288     BlockInterfaceType type;
289     enum { MEDIA_DISK, MEDIA_CDROM } media;
290     int bus_id, unit_id;
291     int cyls, heads, secs, translation;
292     BlockDriver *drv = NULL;
293     int max_devs;
294     int index;
295     int ro = 0;
296     int bdrv_flags = 0;
297     int on_read_error, on_write_error;
298     const char *devaddr;
299     DriveInfo *dinfo;
300     BlockIOLimit io_limits;
301     int snapshot = 0;
302     bool copy_on_read;
303     int ret;
304
305     translation = BIOS_ATA_TRANSLATION_AUTO;
306     media = MEDIA_DISK;
307
308     /* extract parameters */
309     bus_id  = qemu_opt_get_number(opts, "bus", 0);
310     unit_id = qemu_opt_get_number(opts, "unit", -1);
311     index   = qemu_opt_get_number(opts, "index", -1);
312
313     cyls  = qemu_opt_get_number(opts, "cyls", 0);
314     heads = qemu_opt_get_number(opts, "heads", 0);
315     secs  = qemu_opt_get_number(opts, "secs", 0);
316
317     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
318     ro = qemu_opt_get_bool(opts, "readonly", 0);
319     copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
320
321     file = qemu_opt_get(opts, "file");
322     serial = qemu_opt_get(opts, "serial");
323
324     if ((buf = qemu_opt_get(opts, "if")) != NULL) {
325         for (type = 0; type < IF_COUNT && strcmp(buf, if_name[type]); type++)
326             ;
327         if (type == IF_COUNT) {
328             error_report("unsupported bus type '%s'", buf);
329             return NULL;
330         }
331     } else {
332         type = default_to_scsi ? IF_SCSI : IF_IDE;
333     }
334
335     max_devs = if_max_devs[type];
336
337     if (cyls || heads || secs) {
338         if (cyls < 1) {
339             error_report("invalid physical cyls number");
340             return NULL;
341         }
342         if (heads < 1) {
343             error_report("invalid physical heads number");
344             return NULL;
345         }
346         if (secs < 1) {
347             error_report("invalid physical secs number");
348             return NULL;
349         }
350     }
351
352     if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
353         if (!cyls) {
354             error_report("'%s' trans must be used with cyls, heads and secs",
355                          buf);
356             return NULL;
357         }
358         if (!strcmp(buf, "none"))
359             translation = BIOS_ATA_TRANSLATION_NONE;
360         else if (!strcmp(buf, "lba"))
361             translation = BIOS_ATA_TRANSLATION_LBA;
362         else if (!strcmp(buf, "auto"))
363             translation = BIOS_ATA_TRANSLATION_AUTO;
364         else {
365             error_report("'%s' invalid translation type", buf);
366             return NULL;
367         }
368     }
369
370     if ((buf = qemu_opt_get(opts, "media")) != NULL) {
371         if (!strcmp(buf, "disk")) {
372             media = MEDIA_DISK;
373         } else if (!strcmp(buf, "cdrom")) {
374             if (cyls || secs || heads) {
375                 error_report("CHS can't be set with media=%s", buf);
376                 return NULL;
377             }
378             media = MEDIA_CDROM;
379         } else {
380             error_report("'%s' invalid media", buf);
381             return NULL;
382         }
383     }
384
385     bdrv_flags |= BDRV_O_CACHE_WB;
386     if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
387         if (bdrv_parse_cache_flags(buf, &bdrv_flags) != 0) {
388             error_report("invalid cache option");
389             return NULL;
390         }
391     }
392
393 #ifdef CONFIG_LINUX_AIO
394     if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
395         if (!strcmp(buf, "native")) {
396             bdrv_flags |= BDRV_O_NATIVE_AIO;
397         } else if (!strcmp(buf, "threads")) {
398             /* this is the default */
399         } else {
400            error_report("invalid aio option");
401            return NULL;
402         }
403     }
404 #endif
405
406     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
407         if (is_help_option(buf)) {
408             error_printf("Supported formats:");
409             bdrv_iterate_format(bdrv_format_print, NULL);
410             error_printf("\n");
411             return NULL;
412         }
413         drv = bdrv_find_whitelisted_format(buf);
414         if (!drv) {
415             error_report("'%s' invalid format", buf);
416             return NULL;
417         }
418     }
419
420     /* disk I/O throttling */
421     io_limits.bps[BLOCK_IO_LIMIT_TOTAL]  =
422                            qemu_opt_get_number(opts, "bps", 0);
423     io_limits.bps[BLOCK_IO_LIMIT_READ]   =
424                            qemu_opt_get_number(opts, "bps_rd", 0);
425     io_limits.bps[BLOCK_IO_LIMIT_WRITE]  =
426                            qemu_opt_get_number(opts, "bps_wr", 0);
427     io_limits.iops[BLOCK_IO_LIMIT_TOTAL] =
428                            qemu_opt_get_number(opts, "iops", 0);
429     io_limits.iops[BLOCK_IO_LIMIT_READ]  =
430                            qemu_opt_get_number(opts, "iops_rd", 0);
431     io_limits.iops[BLOCK_IO_LIMIT_WRITE] =
432                            qemu_opt_get_number(opts, "iops_wr", 0);
433
434     if (!do_check_io_limits(&io_limits)) {
435         error_report("bps(iops) and bps_rd/bps_wr(iops_rd/iops_wr) "
436                      "cannot be used at the same time");
437         return NULL;
438     }
439
440     on_write_error = BLOCK_ERR_STOP_ENOSPC;
441     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
442         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {
443             error_report("werror is not supported by this bus type");
444             return NULL;
445         }
446
447         on_write_error = parse_block_error_action(buf, 0);
448         if (on_write_error < 0) {
449             return NULL;
450         }
451     }
452
453     on_read_error = BLOCK_ERR_REPORT;
454     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
455         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {
456             error_report("rerror is not supported by this bus type");
457             return NULL;
458         }
459
460         on_read_error = parse_block_error_action(buf, 1);
461         if (on_read_error < 0) {
462             return NULL;
463         }
464     }
465
466     if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
467         if (type != IF_VIRTIO) {
468             error_report("addr is not supported by this bus type");
469             return NULL;
470         }
471     }
472
473     /* compute bus and unit according index */
474
475     if (index != -1) {
476         if (bus_id != 0 || unit_id != -1) {
477             error_report("index cannot be used with bus and unit");
478             return NULL;
479         }
480         bus_id = drive_index_to_bus_id(type, index);
481         unit_id = drive_index_to_unit_id(type, index);
482     }
483
484     /* if user doesn't specify a unit_id,
485      * try to find the first free
486      */
487
488     if (unit_id == -1) {
489        unit_id = 0;
490        while (drive_get(type, bus_id, unit_id) != NULL) {
491            unit_id++;
492            if (max_devs && unit_id >= max_devs) {
493                unit_id -= max_devs;
494                bus_id++;
495            }
496        }
497     }
498
499     /* check unit id */
500
501     if (max_devs && unit_id >= max_devs) {
502         error_report("unit %d too big (max is %d)",
503                      unit_id, max_devs - 1);
504         return NULL;
505     }
506
507     /*
508      * catch multiple definitions
509      */
510
511     if (drive_get(type, bus_id, unit_id) != NULL) {
512         error_report("drive with bus=%d, unit=%d (index=%d) exists",
513                      bus_id, unit_id, index);
514         return NULL;
515     }
516
517     /* init */
518
519     dinfo = g_malloc0(sizeof(*dinfo));
520     if ((buf = qemu_opts_id(opts)) != NULL) {
521         dinfo->id = g_strdup(buf);
522     } else {
523         /* no id supplied -> create one */
524         dinfo->id = g_malloc0(32);
525         if (type == IF_IDE || type == IF_SCSI)
526             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
527         if (max_devs)
528             snprintf(dinfo->id, 32, "%s%i%s%i",
529                      if_name[type], bus_id, mediastr, unit_id);
530         else
531             snprintf(dinfo->id, 32, "%s%s%i",
532                      if_name[type], mediastr, unit_id);
533     }
534     dinfo->bdrv = bdrv_new(dinfo->id);
535     dinfo->devaddr = devaddr;
536     dinfo->type = type;
537     dinfo->bus = bus_id;
538     dinfo->unit = unit_id;
539     dinfo->cyls = cyls;
540     dinfo->heads = heads;
541     dinfo->secs = secs;
542     dinfo->trans = translation;
543     dinfo->opts = opts;
544     dinfo->refcount = 1;
545     dinfo->serial = serial;
546     QTAILQ_INSERT_TAIL(&drives, dinfo, next);
547
548     bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
549
550     /* disk I/O throttling */
551     bdrv_set_io_limits(dinfo->bdrv, &io_limits);
552
553     switch(type) {
554     case IF_IDE:
555     case IF_SCSI:
556     case IF_XEN:
557     case IF_NONE:
558         dinfo->media_cd = media == MEDIA_CDROM;
559         break;
560     case IF_SD:
561     case IF_FLOPPY:
562     case IF_PFLASH:
563     case IF_MTD:
564         break;
565     case IF_VIRTIO:
566         /* add virtio block device */
567         opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0, NULL);
568         if (arch_type == QEMU_ARCH_S390X) {
569             qemu_opt_set(opts, "driver", "virtio-blk-s390");
570         } else {
571             qemu_opt_set(opts, "driver", "virtio-blk-pci");
572         }
573         qemu_opt_set(opts, "drive", dinfo->id);
574         if (devaddr)
575             qemu_opt_set(opts, "addr", devaddr);
576         break;
577     default:
578         abort();
579     }
580     if (!file || !*file) {
581         return dinfo;
582     }
583     if (snapshot) {
584         /* always use cache=unsafe with snapshot */
585         bdrv_flags &= ~BDRV_O_CACHE_MASK;
586         bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
587     }
588
589     if (copy_on_read) {
590         bdrv_flags |= BDRV_O_COPY_ON_READ;
591     }
592
593     if (runstate_check(RUN_STATE_INMIGRATE)) {
594         bdrv_flags |= BDRV_O_INCOMING;
595     }
596
597     if (media == MEDIA_CDROM) {
598         /* CDROM is fine for any interface, don't check.  */
599         ro = 1;
600     } else if (ro == 1) {
601         if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY &&
602             type != IF_NONE && type != IF_PFLASH) {
603             error_report("readonly not supported by this bus type");
604             goto err;
605         }
606     }
607
608     bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
609
610     if (ro && copy_on_read) {
611         error_report("warning: disabling copy_on_read on readonly drive");
612     }
613
614     ret = bdrv_open(dinfo->bdrv, file, bdrv_flags, drv);
615     if (ret < 0) {
616         error_report("could not open disk image %s: %s",
617                      file, strerror(-ret));
618
619 #ifdef CONFIG_MARU
620         const char _msg[] = "Failed to load disk file from the following path. Check if the file is corrupted or missing.\n\n";
621             char* err_msg = NULL;
622         err_msg = maru_convert_path((char*)_msg, file);
623         start_simple_client(err_msg);
624         if (err_msg) {
625             g_free(err_msg);
626         }
627 #endif
628
629         goto err;
630     }
631
632     if (bdrv_key_required(dinfo->bdrv))
633         autostart = 0;
634     return dinfo;
635
636 err:
637     bdrv_delete(dinfo->bdrv);
638     g_free(dinfo->id);
639     QTAILQ_REMOVE(&drives, dinfo, next);
640     g_free(dinfo);
641     return NULL;
642 }
643
644 void do_commit(Monitor *mon, const QDict *qdict)
645 {
646     const char *device = qdict_get_str(qdict, "device");
647     BlockDriverState *bs;
648     int ret;
649
650     if (!strcmp(device, "all")) {
651         ret = bdrv_commit_all();
652         if (ret == -EBUSY) {
653             qerror_report(QERR_DEVICE_IN_USE, device);
654             return;
655         }
656     } else {
657         bs = bdrv_find(device);
658         if (!bs) {
659             qerror_report(QERR_DEVICE_NOT_FOUND, device);
660             return;
661         }
662         ret = bdrv_commit(bs);
663         if (ret == -EBUSY) {
664             qerror_report(QERR_DEVICE_IN_USE, device);
665             return;
666         }
667     }
668 }
669
670 static void blockdev_do_action(int kind, void *data, Error **errp)
671 {
672     BlockdevAction action;
673     BlockdevActionList list;
674
675     action.kind = kind;
676     action.data = data;
677     list.value = &action;
678     list.next = NULL;
679     qmp_transaction(&list, errp);
680 }
681
682 void qmp_blockdev_snapshot_sync(const char *device, const char *snapshot_file,
683                                 bool has_format, const char *format,
684                                 bool has_mode, enum NewImageMode mode,
685                                 Error **errp)
686 {
687     BlockdevSnapshot snapshot = {
688         .device = (char *) device,
689         .snapshot_file = (char *) snapshot_file,
690         .has_format = has_format,
691         .format = (char *) format,
692         .has_mode = has_mode,
693         .mode = mode,
694     };
695     blockdev_do_action(BLOCKDEV_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC, &snapshot,
696                        errp);
697 }
698
699
700 /* New and old BlockDriverState structs for group snapshots */
701 typedef struct BlkTransactionStates {
702     BlockDriverState *old_bs;
703     BlockDriverState *new_bs;
704     QSIMPLEQ_ENTRY(BlkTransactionStates) entry;
705 } BlkTransactionStates;
706
707 /*
708  * 'Atomic' group snapshots.  The snapshots are taken as a set, and if any fail
709  *  then we do not pivot any of the devices in the group, and abandon the
710  *  snapshots
711  */
712 void qmp_transaction(BlockdevActionList *dev_list, Error **errp)
713 {
714     int ret = 0;
715     BlockdevActionList *dev_entry = dev_list;
716     BlkTransactionStates *states, *next;
717
718     QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionStates) snap_bdrv_states;
719     QSIMPLEQ_INIT(&snap_bdrv_states);
720
721     /* drain all i/o before any snapshots */
722     bdrv_drain_all();
723
724     /* We don't do anything in this loop that commits us to the snapshot */
725     while (NULL != dev_entry) {
726         BlockdevAction *dev_info = NULL;
727         BlockDriver *proto_drv;
728         BlockDriver *drv;
729         int flags;
730         enum NewImageMode mode;
731         const char *new_image_file;
732         const char *device;
733         const char *format = "qcow2";
734
735         dev_info = dev_entry->value;
736         dev_entry = dev_entry->next;
737
738         states = g_malloc0(sizeof(BlkTransactionStates));
739         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, states, entry);
740
741         switch (dev_info->kind) {
742         case BLOCKDEV_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
743             device = dev_info->blockdev_snapshot_sync->device;
744             if (!dev_info->blockdev_snapshot_sync->has_mode) {
745                 dev_info->blockdev_snapshot_sync->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
746             }
747             new_image_file = dev_info->blockdev_snapshot_sync->snapshot_file;
748             if (dev_info->blockdev_snapshot_sync->has_format) {
749                 format = dev_info->blockdev_snapshot_sync->format;
750             }
751             mode = dev_info->blockdev_snapshot_sync->mode;
752             break;
753         default:
754             abort();
755         }
756
757         drv = bdrv_find_format(format);
758         if (!drv) {
759             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
760             goto delete_and_fail;
761         }
762
763         states->old_bs = bdrv_find(device);
764         if (!states->old_bs) {
765             error_set(errp, QERR_DEVICE_NOT_FOUND, device);
766             goto delete_and_fail;
767         }
768
769         if (!bdrv_is_inserted(states->old_bs)) {
770             error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
771             goto delete_and_fail;
772         }
773
774         if (bdrv_in_use(states->old_bs)) {
775             error_set(errp, QERR_DEVICE_IN_USE, device);
776             goto delete_and_fail;
777         }
778
779         if (!bdrv_is_read_only(states->old_bs)) {
780             if (bdrv_flush(states->old_bs)) {
781                 error_set(errp, QERR_IO_ERROR);
782                 goto delete_and_fail;
783             }
784         }
785
786         flags = states->old_bs->open_flags;
787
788         proto_drv = bdrv_find_protocol(new_image_file);
789         if (!proto_drv) {
790             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
791             goto delete_and_fail;
792         }
793
794         /* create new image w/backing file */
795         if (mode != NEW_IMAGE_MODE_EXISTING) {
796             ret = bdrv_img_create(new_image_file, format,
797                                   states->old_bs->filename,
798                                   states->old_bs->drv->format_name,
799                                   NULL, -1, flags);
800             if (ret) {
801                 error_set(errp, QERR_OPEN_FILE_FAILED, new_image_file);
802                 goto delete_and_fail;
803             }
804         }
805
806         /* We will manually add the backing_hd field to the bs later */
807         states->new_bs = bdrv_new("");
808         ret = bdrv_open(states->new_bs, new_image_file,
809                         flags | BDRV_O_NO_BACKING, drv);
810         if (ret != 0) {
811             error_set(errp, QERR_OPEN_FILE_FAILED, new_image_file);
812             goto delete_and_fail;
813         }
814     }
815
816
817     /* Now we are going to do the actual pivot.  Everything up to this point
818      * is reversible, but we are committed at this point */
819     QSIMPLEQ_FOREACH(states, &snap_bdrv_states, entry) {
820         /* This removes our old bs from the bdrv_states, and adds the new bs */
821         bdrv_append(states->new_bs, states->old_bs);
822     }
823
824     /* success */
825     goto exit;
826
827 delete_and_fail:
828     /*
829     * failure, and it is all-or-none; abandon each new bs, and keep using
830     * the original bs for all images
831     */
832     QSIMPLEQ_FOREACH(states, &snap_bdrv_states, entry) {
833         if (states->new_bs) {
834              bdrv_delete(states->new_bs);
835         }
836     }
837 exit:
838     QSIMPLEQ_FOREACH_SAFE(states, &snap_bdrv_states, entry, next) {
839         g_free(states);
840     }
841     return;
842 }
843
844
845 static void eject_device(BlockDriverState *bs, int force, Error **errp)
846 {
847     if (bdrv_in_use(bs)) {
848         error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
849         return;
850     }
851     if (!bdrv_dev_has_removable_media(bs)) {
852         error_set(errp, QERR_DEVICE_NOT_REMOVABLE, bdrv_get_device_name(bs));
853         return;
854     }
855
856     if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
857         bdrv_dev_eject_request(bs, force);
858         if (!force) {
859             error_set(errp, QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
860             return;
861         }
862     }
863
864     bdrv_close(bs);
865 }
866
867 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
868 {
869     BlockDriverState *bs;
870
871     bs = bdrv_find(device);
872     if (!bs) {
873         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
874         return;
875     }
876
877     eject_device(bs, force, errp);
878 }
879
880 void qmp_block_passwd(const char *device, const char *password, Error **errp)
881 {
882     BlockDriverState *bs;
883     int err;
884
885     bs = bdrv_find(device);
886     if (!bs) {
887         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
888         return;
889     }
890
891     err = bdrv_set_key(bs, password);
892     if (err == -EINVAL) {
893         error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
894         return;
895     } else if (err < 0) {
896         error_set(errp, QERR_INVALID_PASSWORD);
897         return;
898     }
899 }
900
901 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
902                                     int bdrv_flags, BlockDriver *drv,
903                                     const char *password, Error **errp)
904 {
905     if (bdrv_open(bs, filename, bdrv_flags, drv) < 0) {
906         error_set(errp, QERR_OPEN_FILE_FAILED, filename);
907         return;
908     }
909
910     if (bdrv_key_required(bs)) {
911         if (password) {
912             if (bdrv_set_key(bs, password) < 0) {
913                 error_set(errp, QERR_INVALID_PASSWORD);
914             }
915         } else {
916             error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
917                       bdrv_get_encrypted_filename(bs));
918         }
919     } else if (password) {
920         error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
921     }
922 }
923
924 void qmp_change_blockdev(const char *device, const char *filename,
925                          bool has_format, const char *format, Error **errp)
926 {
927     BlockDriverState *bs;
928     BlockDriver *drv = NULL;
929     int bdrv_flags;
930     Error *err = NULL;
931
932     bs = bdrv_find(device);
933     if (!bs) {
934         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
935         return;
936     }
937
938     if (format) {
939         drv = bdrv_find_whitelisted_format(format);
940         if (!drv) {
941             error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
942             return;
943         }
944     }
945
946     eject_device(bs, 0, &err);
947     if (error_is_set(&err)) {
948         error_propagate(errp, err);
949         return;
950     }
951
952     bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
953     bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
954
955     qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
956 }
957
958 /* throttling disk I/O limits */
959 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
960                                int64_t bps_wr, int64_t iops, int64_t iops_rd,
961                                int64_t iops_wr, Error **errp)
962 {
963     BlockIOLimit io_limits;
964     BlockDriverState *bs;
965
966     bs = bdrv_find(device);
967     if (!bs) {
968         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
969         return;
970     }
971
972     io_limits.bps[BLOCK_IO_LIMIT_TOTAL] = bps;
973     io_limits.bps[BLOCK_IO_LIMIT_READ]  = bps_rd;
974     io_limits.bps[BLOCK_IO_LIMIT_WRITE] = bps_wr;
975     io_limits.iops[BLOCK_IO_LIMIT_TOTAL]= iops;
976     io_limits.iops[BLOCK_IO_LIMIT_READ] = iops_rd;
977     io_limits.iops[BLOCK_IO_LIMIT_WRITE]= iops_wr;
978
979     if (!do_check_io_limits(&io_limits)) {
980         error_set(errp, QERR_INVALID_PARAMETER_COMBINATION);
981         return;
982     }
983
984     bs->io_limits = io_limits;
985     bs->slice_time = BLOCK_IO_SLICE_TIME;
986
987     if (!bs->io_limits_enabled && bdrv_io_limits_enabled(bs)) {
988         bdrv_io_limits_enable(bs);
989     } else if (bs->io_limits_enabled && !bdrv_io_limits_enabled(bs)) {
990         bdrv_io_limits_disable(bs);
991     } else {
992         if (bs->block_timer) {
993             qemu_mod_timer(bs->block_timer, qemu_get_clock_ns(vm_clock));
994         }
995     }
996 }
997
998 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
999 {
1000     const char *id = qdict_get_str(qdict, "id");
1001     BlockDriverState *bs;
1002
1003     bs = bdrv_find(id);
1004     if (!bs) {
1005         qerror_report(QERR_DEVICE_NOT_FOUND, id);
1006         return -1;
1007     }
1008     if (bdrv_in_use(bs)) {
1009         qerror_report(QERR_DEVICE_IN_USE, id);
1010         return -1;
1011     }
1012
1013     /* quiesce block driver; prevent further io */
1014     bdrv_drain_all();
1015     bdrv_flush(bs);
1016     bdrv_close(bs);
1017
1018     /* if we have a device attached to this BlockDriverState
1019      * then we need to make the drive anonymous until the device
1020      * can be removed.  If this is a drive with no device backing
1021      * then we can just get rid of the block driver state right here.
1022      */
1023     if (bdrv_get_attached_dev(bs)) {
1024         bdrv_make_anon(bs);
1025     } else {
1026         drive_uninit(drive_get_by_blockdev(bs));
1027     }
1028
1029     return 0;
1030 }
1031
1032 void qmp_block_resize(const char *device, int64_t size, Error **errp)
1033 {
1034     BlockDriverState *bs;
1035
1036     bs = bdrv_find(device);
1037     if (!bs) {
1038         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1039         return;
1040     }
1041
1042     if (size < 0) {
1043         error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1044         return;
1045     }
1046
1047     switch (bdrv_truncate(bs, size)) {
1048     case 0:
1049         break;
1050     case -ENOMEDIUM:
1051         error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1052         break;
1053     case -ENOTSUP:
1054         error_set(errp, QERR_UNSUPPORTED);
1055         break;
1056     case -EACCES:
1057         error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1058         break;
1059     case -EBUSY:
1060         error_set(errp, QERR_DEVICE_IN_USE, device);
1061         break;
1062     default:
1063         error_set(errp, QERR_UNDEFINED_ERROR);
1064         break;
1065     }
1066 }
1067
1068 static QObject *qobject_from_block_job(BlockJob *job)
1069 {
1070     return qobject_from_jsonf("{ 'type': %s,"
1071                               "'device': %s,"
1072                               "'len': %" PRId64 ","
1073                               "'offset': %" PRId64 ","
1074                               "'speed': %" PRId64 " }",
1075                               job->job_type->job_type,
1076                               bdrv_get_device_name(job->bs),
1077                               job->len,
1078                               job->offset,
1079                               job->speed);
1080 }
1081
1082 static void block_stream_cb(void *opaque, int ret)
1083 {
1084     BlockDriverState *bs = opaque;
1085     QObject *obj;
1086
1087     trace_block_stream_cb(bs, bs->job, ret);
1088
1089     assert(bs->job);
1090     obj = qobject_from_block_job(bs->job);
1091     if (ret < 0) {
1092         QDict *dict = qobject_to_qdict(obj);
1093         qdict_put(dict, "error", qstring_from_str(strerror(-ret)));
1094     }
1095
1096     if (block_job_is_cancelled(bs->job)) {
1097         monitor_protocol_event(QEVENT_BLOCK_JOB_CANCELLED, obj);
1098     } else {
1099         monitor_protocol_event(QEVENT_BLOCK_JOB_COMPLETED, obj);
1100     }
1101     qobject_decref(obj);
1102
1103     drive_put_ref_bh_schedule(drive_get_by_blockdev(bs));
1104 }
1105
1106 void qmp_block_stream(const char *device, bool has_base,
1107                       const char *base, bool has_speed,
1108                       int64_t speed, Error **errp)
1109 {
1110     BlockDriverState *bs;
1111     BlockDriverState *base_bs = NULL;
1112     Error *local_err = NULL;
1113
1114     bs = bdrv_find(device);
1115     if (!bs) {
1116         error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1117         return;
1118     }
1119
1120     if (base) {
1121         base_bs = bdrv_find_backing_image(bs, base);
1122         if (base_bs == NULL) {
1123             error_set(errp, QERR_BASE_NOT_FOUND, base);
1124             return;
1125         }
1126     }
1127
1128     stream_start(bs, base_bs, base, has_speed ? speed : 0,
1129                  block_stream_cb, bs, &local_err);
1130     if (error_is_set(&local_err)) {
1131         error_propagate(errp, local_err);
1132         return;
1133     }
1134
1135     /* Grab a reference so hotplug does not delete the BlockDriverState from
1136      * underneath us.
1137      */
1138     drive_get_ref(drive_get_by_blockdev(bs));
1139
1140     trace_qmp_block_stream(bs, bs->job);
1141 }
1142
1143 static BlockJob *find_block_job(const char *device)
1144 {
1145     BlockDriverState *bs;
1146
1147     bs = bdrv_find(device);
1148     if (!bs || !bs->job) {
1149         return NULL;
1150     }
1151     return bs->job;
1152 }
1153
1154 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
1155 {
1156     BlockJob *job = find_block_job(device);
1157
1158     if (!job) {
1159         error_set(errp, QERR_DEVICE_NOT_ACTIVE, device);
1160         return;
1161     }
1162
1163     block_job_set_speed(job, speed, errp);
1164 }
1165
1166 void qmp_block_job_cancel(const char *device, Error **errp)
1167 {
1168     BlockJob *job = find_block_job(device);
1169
1170     if (!job) {
1171         error_set(errp, QERR_DEVICE_NOT_ACTIVE, device);
1172         return;
1173     }
1174
1175     trace_qmp_block_job_cancel(job);
1176     block_job_cancel(job);
1177 }
1178
1179 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
1180 {
1181     BlockJobInfoList **prev = opaque;
1182     BlockJob *job = bs->job;
1183
1184     if (job) {
1185         BlockJobInfoList *elem;
1186         BlockJobInfo *info = g_new(BlockJobInfo, 1);
1187         *info = (BlockJobInfo){
1188             .type   = g_strdup(job->job_type->job_type),
1189             .device = g_strdup(bdrv_get_device_name(bs)),
1190             .len    = job->len,
1191             .offset = job->offset,
1192             .speed  = job->speed,
1193         };
1194
1195         elem = g_new0(BlockJobInfoList, 1);
1196         elem->value = info;
1197
1198         (*prev)->next = elem;
1199         *prev = elem;
1200     }
1201 }
1202
1203 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
1204 {
1205     /* Dummy is a fake list element for holding the head pointer */
1206     BlockJobInfoList dummy = {};
1207     BlockJobInfoList *prev = &dummy;
1208     bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
1209     return dummy.next;
1210 }