]> Git Repo - qemu.git/blob - blockdev.c
qed: Implement .bdrv_drain
[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/block-backend.h"
34 #include "sysemu/blockdev.h"
35 #include "hw/block/block.h"
36 #include "block/blockjob.h"
37 #include "block/throttle-groups.h"
38 #include "monitor/monitor.h"
39 #include "qemu/error-report.h"
40 #include "qemu/option.h"
41 #include "qemu/config-file.h"
42 #include "qapi/qmp/types.h"
43 #include "qapi-visit.h"
44 #include "qapi/qmp/qerror.h"
45 #include "qapi/qmp-output-visitor.h"
46 #include "qapi/util.h"
47 #include "sysemu/sysemu.h"
48 #include "block/block_int.h"
49 #include "qmp-commands.h"
50 #include "trace.h"
51 #include "sysemu/arch_init.h"
52
53 static const char *const if_name[IF_COUNT] = {
54     [IF_NONE] = "none",
55     [IF_IDE] = "ide",
56     [IF_SCSI] = "scsi",
57     [IF_FLOPPY] = "floppy",
58     [IF_PFLASH] = "pflash",
59     [IF_MTD] = "mtd",
60     [IF_SD] = "sd",
61     [IF_VIRTIO] = "virtio",
62     [IF_XEN] = "xen",
63 };
64
65 static int if_max_devs[IF_COUNT] = {
66     /*
67      * Do not change these numbers!  They govern how drive option
68      * index maps to unit and bus.  That mapping is ABI.
69      *
70      * All controllers used to imlement if=T drives need to support
71      * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
72      * Otherwise, some index values map to "impossible" bus, unit
73      * values.
74      *
75      * For instance, if you change [IF_SCSI] to 255, -drive
76      * if=scsi,index=12 no longer means bus=1,unit=5, but
77      * bus=0,unit=12.  With an lsi53c895a controller (7 units max),
78      * the drive can't be set up.  Regression.
79      */
80     [IF_IDE] = 2,
81     [IF_SCSI] = 7,
82 };
83
84 /**
85  * Boards may call this to offer board-by-board overrides
86  * of the default, global values.
87  */
88 void override_max_devs(BlockInterfaceType type, int max_devs)
89 {
90     BlockBackend *blk;
91     DriveInfo *dinfo;
92
93     if (max_devs <= 0) {
94         return;
95     }
96
97     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
98         dinfo = blk_legacy_dinfo(blk);
99         if (dinfo->type == type) {
100             fprintf(stderr, "Cannot override units-per-bus property of"
101                     " the %s interface, because a drive of that type has"
102                     " already been added.\n", if_name[type]);
103             g_assert_not_reached();
104         }
105     }
106
107     if_max_devs[type] = max_devs;
108 }
109
110 /*
111  * We automatically delete the drive when a device using it gets
112  * unplugged.  Questionable feature, but we can't just drop it.
113  * Device models call blockdev_mark_auto_del() to schedule the
114  * automatic deletion, and generic qdev code calls blockdev_auto_del()
115  * when deletion is actually safe.
116  */
117 void blockdev_mark_auto_del(BlockBackend *blk)
118 {
119     DriveInfo *dinfo = blk_legacy_dinfo(blk);
120     BlockDriverState *bs = blk_bs(blk);
121     AioContext *aio_context;
122
123     if (!dinfo) {
124         return;
125     }
126
127     if (bs) {
128         aio_context = bdrv_get_aio_context(bs);
129         aio_context_acquire(aio_context);
130
131         if (bs->job) {
132             block_job_cancel(bs->job);
133         }
134
135         aio_context_release(aio_context);
136     }
137
138     dinfo->auto_del = 1;
139 }
140
141 void blockdev_auto_del(BlockBackend *blk)
142 {
143     DriveInfo *dinfo = blk_legacy_dinfo(blk);
144
145     if (dinfo && dinfo->auto_del) {
146         blk_unref(blk);
147     }
148 }
149
150 /**
151  * Returns the current mapping of how many units per bus
152  * a particular interface can support.
153  *
154  *  A positive integer indicates n units per bus.
155  *  0 implies the mapping has not been established.
156  * -1 indicates an invalid BlockInterfaceType was given.
157  */
158 int drive_get_max_devs(BlockInterfaceType type)
159 {
160     if (type >= IF_IDE && type < IF_COUNT) {
161         return if_max_devs[type];
162     }
163
164     return -1;
165 }
166
167 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
168 {
169     int max_devs = if_max_devs[type];
170     return max_devs ? index / max_devs : 0;
171 }
172
173 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
174 {
175     int max_devs = if_max_devs[type];
176     return max_devs ? index % max_devs : index;
177 }
178
179 QemuOpts *drive_def(const char *optstr)
180 {
181     return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
182 }
183
184 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
185                     const char *optstr)
186 {
187     QemuOpts *opts;
188
189     opts = drive_def(optstr);
190     if (!opts) {
191         return NULL;
192     }
193     if (type != IF_DEFAULT) {
194         qemu_opt_set(opts, "if", if_name[type], &error_abort);
195     }
196     if (index >= 0) {
197         qemu_opt_set_number(opts, "index", index, &error_abort);
198     }
199     if (file)
200         qemu_opt_set(opts, "file", file, &error_abort);
201     return opts;
202 }
203
204 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
205 {
206     BlockBackend *blk;
207     DriveInfo *dinfo;
208
209     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
210         dinfo = blk_legacy_dinfo(blk);
211         if (dinfo && dinfo->type == type
212             && dinfo->bus == bus && dinfo->unit == unit) {
213             return dinfo;
214         }
215     }
216
217     return NULL;
218 }
219
220 bool drive_check_orphaned(void)
221 {
222     BlockBackend *blk;
223     DriveInfo *dinfo;
224     bool rs = false;
225
226     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
227         dinfo = blk_legacy_dinfo(blk);
228         /* If dinfo->bdrv->dev is NULL, it has no device attached. */
229         /* Unless this is a default drive, this may be an oversight. */
230         if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
231             dinfo->type != IF_NONE) {
232             fprintf(stderr, "Warning: Orphaned drive without device: "
233                     "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
234                     blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
235                     if_name[dinfo->type], dinfo->bus, dinfo->unit);
236             rs = true;
237         }
238     }
239
240     return rs;
241 }
242
243 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
244 {
245     return drive_get(type,
246                      drive_index_to_bus_id(type, index),
247                      drive_index_to_unit_id(type, index));
248 }
249
250 int drive_get_max_bus(BlockInterfaceType type)
251 {
252     int max_bus;
253     BlockBackend *blk;
254     DriveInfo *dinfo;
255
256     max_bus = -1;
257     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
258         dinfo = blk_legacy_dinfo(blk);
259         if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
260             max_bus = dinfo->bus;
261         }
262     }
263     return max_bus;
264 }
265
266 /* Get a block device.  This should only be used for single-drive devices
267    (e.g. SD/Floppy/MTD).  Multi-disk devices (scsi/ide) should use the
268    appropriate bus.  */
269 DriveInfo *drive_get_next(BlockInterfaceType type)
270 {
271     static int next_block_unit[IF_COUNT];
272
273     return drive_get(type, 0, next_block_unit[type]++);
274 }
275
276 static void bdrv_format_print(void *opaque, const char *name)
277 {
278     error_printf(" %s", name);
279 }
280
281 typedef struct {
282     QEMUBH *bh;
283     BlockDriverState *bs;
284 } BDRVPutRefBH;
285
286 static void bdrv_put_ref_bh(void *opaque)
287 {
288     BDRVPutRefBH *s = opaque;
289
290     bdrv_unref(s->bs);
291     qemu_bh_delete(s->bh);
292     g_free(s);
293 }
294
295 /*
296  * Release a BDS reference in a BH
297  *
298  * It is not safe to use bdrv_unref() from a callback function when the callers
299  * still need the BlockDriverState.  In such cases we schedule a BH to release
300  * the reference.
301  */
302 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
303 {
304     BDRVPutRefBH *s;
305
306     s = g_new(BDRVPutRefBH, 1);
307     s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
308     s->bs = bs;
309     qemu_bh_schedule(s->bh);
310 }
311
312 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
313 {
314     if (!strcmp(buf, "ignore")) {
315         return BLOCKDEV_ON_ERROR_IGNORE;
316     } else if (!is_read && !strcmp(buf, "enospc")) {
317         return BLOCKDEV_ON_ERROR_ENOSPC;
318     } else if (!strcmp(buf, "stop")) {
319         return BLOCKDEV_ON_ERROR_STOP;
320     } else if (!strcmp(buf, "report")) {
321         return BLOCKDEV_ON_ERROR_REPORT;
322     } else {
323         error_setg(errp, "'%s' invalid %s error action",
324                    buf, is_read ? "read" : "write");
325         return -1;
326     }
327 }
328
329 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
330 {
331     if (throttle_conflicting(cfg)) {
332         error_setg(errp, "bps/iops/max total values and read/write values"
333                          " cannot be used at the same time");
334         return false;
335     }
336
337     if (!throttle_is_valid(cfg)) {
338         error_setg(errp, "bps/iops/maxs values must be 0 or greater");
339         return false;
340     }
341
342     if (throttle_max_is_missing_limit(cfg)) {
343         error_setg(errp, "bps_max/iops_max require corresponding"
344                          " bps/iops values");
345         return false;
346     }
347
348     return true;
349 }
350
351 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
352
353 /* All parameters but @opts are optional and may be set to NULL. */
354 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
355     const char **throttling_group, ThrottleConfig *throttle_cfg,
356     BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
357 {
358     const char *discard;
359     Error *local_error = NULL;
360     const char *aio;
361
362     if (bdrv_flags) {
363         if (!qemu_opt_get_bool(opts, "read-only", false)) {
364             *bdrv_flags |= BDRV_O_RDWR;
365         }
366         if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
367             *bdrv_flags |= BDRV_O_COPY_ON_READ;
368         }
369
370         if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
371             if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
372                 error_setg(errp, "Invalid discard option");
373                 return;
374             }
375         }
376
377         if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true)) {
378             *bdrv_flags |= BDRV_O_CACHE_WB;
379         }
380         if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
381             *bdrv_flags |= BDRV_O_NOCACHE;
382         }
383         if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
384             *bdrv_flags |= BDRV_O_NO_FLUSH;
385         }
386
387         if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
388             if (!strcmp(aio, "native")) {
389                 *bdrv_flags |= BDRV_O_NATIVE_AIO;
390             } else if (!strcmp(aio, "threads")) {
391                 /* this is the default */
392             } else {
393                error_setg(errp, "invalid aio option");
394                return;
395             }
396         }
397     }
398
399     /* disk I/O throttling */
400     if (throttling_group) {
401         *throttling_group = qemu_opt_get(opts, "throttling.group");
402     }
403
404     if (throttle_cfg) {
405         memset(throttle_cfg, 0, sizeof(*throttle_cfg));
406         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
407             qemu_opt_get_number(opts, "throttling.bps-total", 0);
408         throttle_cfg->buckets[THROTTLE_BPS_READ].avg  =
409             qemu_opt_get_number(opts, "throttling.bps-read", 0);
410         throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
411             qemu_opt_get_number(opts, "throttling.bps-write", 0);
412         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
413             qemu_opt_get_number(opts, "throttling.iops-total", 0);
414         throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
415             qemu_opt_get_number(opts, "throttling.iops-read", 0);
416         throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
417             qemu_opt_get_number(opts, "throttling.iops-write", 0);
418
419         throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
420             qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
421         throttle_cfg->buckets[THROTTLE_BPS_READ].max  =
422             qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
423         throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
424             qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
425         throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
426             qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
427         throttle_cfg->buckets[THROTTLE_OPS_READ].max =
428             qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
429         throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
430             qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
431
432         throttle_cfg->op_size =
433             qemu_opt_get_number(opts, "throttling.iops-size", 0);
434
435         if (!check_throttle_config(throttle_cfg, errp)) {
436             return;
437         }
438     }
439
440     if (detect_zeroes) {
441         *detect_zeroes =
442             qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
443                             qemu_opt_get(opts, "detect-zeroes"),
444                             BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
445                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
446                             &local_error);
447         if (local_error) {
448             error_propagate(errp, local_error);
449             return;
450         }
451
452         if (bdrv_flags &&
453             *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
454             !(*bdrv_flags & BDRV_O_UNMAP))
455         {
456             error_setg(errp, "setting detect-zeroes to unmap is not allowed "
457                              "without setting discard operation to unmap");
458             return;
459         }
460     }
461 }
462
463 /* Takes the ownership of bs_opts */
464 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
465                                    Error **errp)
466 {
467     const char *buf;
468     int bdrv_flags = 0;
469     int on_read_error, on_write_error;
470     BlockBackend *blk;
471     BlockDriverState *bs;
472     ThrottleConfig cfg;
473     int snapshot = 0;
474     Error *error = NULL;
475     QemuOpts *opts;
476     const char *id;
477     bool has_driver_specific_opts;
478     BlockdevDetectZeroesOptions detect_zeroes =
479         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
480     const char *throttling_group = NULL;
481
482     /* Check common options by copying from bs_opts to opts, all other options
483      * stay in bs_opts for processing by bdrv_open(). */
484     id = qdict_get_try_str(bs_opts, "id");
485     opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
486     if (error) {
487         error_propagate(errp, error);
488         goto err_no_opts;
489     }
490
491     qemu_opts_absorb_qdict(opts, bs_opts, &error);
492     if (error) {
493         error_propagate(errp, error);
494         goto early_err;
495     }
496
497     if (id) {
498         qdict_del(bs_opts, "id");
499     }
500
501     has_driver_specific_opts = !!qdict_size(bs_opts);
502
503     /* extract parameters */
504     snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
505
506     extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
507                                     &detect_zeroes, &error);
508     if (error) {
509         error_propagate(errp, error);
510         goto early_err;
511     }
512
513     if ((buf = qemu_opt_get(opts, "format")) != NULL) {
514         if (is_help_option(buf)) {
515             error_printf("Supported formats:");
516             bdrv_iterate_format(bdrv_format_print, NULL);
517             error_printf("\n");
518             goto early_err;
519         }
520
521         if (qdict_haskey(bs_opts, "driver")) {
522             error_setg(errp, "Cannot specify both 'driver' and 'format'");
523             goto early_err;
524         }
525         qdict_put(bs_opts, "driver", qstring_from_str(buf));
526     }
527
528     on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
529     if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
530         on_write_error = parse_block_error_action(buf, 0, &error);
531         if (error) {
532             error_propagate(errp, error);
533             goto early_err;
534         }
535     }
536
537     on_read_error = BLOCKDEV_ON_ERROR_REPORT;
538     if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
539         on_read_error = parse_block_error_action(buf, 1, &error);
540         if (error) {
541             error_propagate(errp, error);
542             goto early_err;
543         }
544     }
545
546     if (snapshot) {
547         /* always use cache=unsafe with snapshot */
548         bdrv_flags &= ~BDRV_O_CACHE_MASK;
549         bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
550     }
551
552     /* init */
553     if ((!file || !*file) && !has_driver_specific_opts) {
554         BlockBackendRootState *blk_rs;
555
556         blk = blk_new(qemu_opts_id(opts), errp);
557         if (!blk) {
558             goto early_err;
559         }
560
561         blk_rs = blk_get_root_state(blk);
562         blk_rs->open_flags    = bdrv_flags;
563         blk_rs->read_only     = !(bdrv_flags & BDRV_O_RDWR);
564         blk_rs->detect_zeroes = detect_zeroes;
565
566         if (throttle_enabled(&cfg)) {
567             if (!throttling_group) {
568                 throttling_group = blk_name(blk);
569             }
570             blk_rs->throttle_group = g_strdup(throttling_group);
571             blk_rs->throttle_state = throttle_group_incref(throttling_group);
572             blk_rs->throttle_state->cfg = cfg;
573         }
574
575         QDECREF(bs_opts);
576     } else {
577         if (file && !*file) {
578             file = NULL;
579         }
580
581         blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,
582                            errp);
583         if (!blk) {
584             goto err_no_bs_opts;
585         }
586         bs = blk_bs(blk);
587
588         bs->detect_zeroes = detect_zeroes;
589
590         /* disk I/O throttling */
591         if (throttle_enabled(&cfg)) {
592             if (!throttling_group) {
593                 throttling_group = blk_name(blk);
594             }
595             bdrv_io_limits_enable(bs, throttling_group);
596             bdrv_set_io_limits(bs, &cfg);
597         }
598
599         if (bdrv_key_required(bs)) {
600             autostart = 0;
601         }
602     }
603
604     blk_set_on_error(blk, on_read_error, on_write_error);
605
606 err_no_bs_opts:
607     qemu_opts_del(opts);
608     return blk;
609
610 early_err:
611     qemu_opts_del(opts);
612 err_no_opts:
613     QDECREF(bs_opts);
614     return NULL;
615 }
616
617 static QemuOptsList qemu_root_bds_opts;
618
619 /* Takes the ownership of bs_opts */
620 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
621 {
622     BlockDriverState *bs;
623     QemuOpts *opts;
624     Error *local_error = NULL;
625     BlockdevDetectZeroesOptions detect_zeroes;
626     int ret;
627     int bdrv_flags = 0;
628
629     opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
630     if (!opts) {
631         goto fail;
632     }
633
634     qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
635     if (local_error) {
636         error_propagate(errp, local_error);
637         goto fail;
638     }
639
640     extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
641                                     &detect_zeroes, &local_error);
642     if (local_error) {
643         error_propagate(errp, local_error);
644         goto fail;
645     }
646
647     bs = NULL;
648     ret = bdrv_open(&bs, NULL, NULL, bs_opts, bdrv_flags, errp);
649     if (ret < 0) {
650         goto fail_no_bs_opts;
651     }
652
653     bs->detect_zeroes = detect_zeroes;
654
655 fail_no_bs_opts:
656     qemu_opts_del(opts);
657     return bs;
658
659 fail:
660     qemu_opts_del(opts);
661     QDECREF(bs_opts);
662     return NULL;
663 }
664
665 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
666                             Error **errp)
667 {
668     const char *value;
669
670     value = qemu_opt_get(opts, from);
671     if (value) {
672         if (qemu_opt_find(opts, to)) {
673             error_setg(errp, "'%s' and its alias '%s' can't be used at the "
674                        "same time", to, from);
675             return;
676         }
677     }
678
679     /* rename all items in opts */
680     while ((value = qemu_opt_get(opts, from))) {
681         qemu_opt_set(opts, to, value, &error_abort);
682         qemu_opt_unset(opts, from);
683     }
684 }
685
686 QemuOptsList qemu_legacy_drive_opts = {
687     .name = "drive",
688     .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
689     .desc = {
690         {
691             .name = "bus",
692             .type = QEMU_OPT_NUMBER,
693             .help = "bus number",
694         },{
695             .name = "unit",
696             .type = QEMU_OPT_NUMBER,
697             .help = "unit number (i.e. lun for scsi)",
698         },{
699             .name = "index",
700             .type = QEMU_OPT_NUMBER,
701             .help = "index number",
702         },{
703             .name = "media",
704             .type = QEMU_OPT_STRING,
705             .help = "media type (disk, cdrom)",
706         },{
707             .name = "if",
708             .type = QEMU_OPT_STRING,
709             .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
710         },{
711             .name = "cyls",
712             .type = QEMU_OPT_NUMBER,
713             .help = "number of cylinders (ide disk geometry)",
714         },{
715             .name = "heads",
716             .type = QEMU_OPT_NUMBER,
717             .help = "number of heads (ide disk geometry)",
718         },{
719             .name = "secs",
720             .type = QEMU_OPT_NUMBER,
721             .help = "number of sectors (ide disk geometry)",
722         },{
723             .name = "trans",
724             .type = QEMU_OPT_STRING,
725             .help = "chs translation (auto, lba, none)",
726         },{
727             .name = "boot",
728             .type = QEMU_OPT_BOOL,
729             .help = "(deprecated, ignored)",
730         },{
731             .name = "addr",
732             .type = QEMU_OPT_STRING,
733             .help = "pci address (virtio only)",
734         },{
735             .name = "serial",
736             .type = QEMU_OPT_STRING,
737             .help = "disk serial number",
738         },{
739             .name = "file",
740             .type = QEMU_OPT_STRING,
741             .help = "file name",
742         },
743
744         /* Options that are passed on, but have special semantics with -drive */
745         {
746             .name = "read-only",
747             .type = QEMU_OPT_BOOL,
748             .help = "open drive file as read-only",
749         },{
750             .name = "rerror",
751             .type = QEMU_OPT_STRING,
752             .help = "read error action",
753         },{
754             .name = "werror",
755             .type = QEMU_OPT_STRING,
756             .help = "write error action",
757         },{
758             .name = "copy-on-read",
759             .type = QEMU_OPT_BOOL,
760             .help = "copy read data from backing file into image file",
761         },
762
763         { /* end of list */ }
764     },
765 };
766
767 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
768 {
769     const char *value;
770     BlockBackend *blk;
771     DriveInfo *dinfo = NULL;
772     QDict *bs_opts;
773     QemuOpts *legacy_opts;
774     DriveMediaType media = MEDIA_DISK;
775     BlockInterfaceType type;
776     int cyls, heads, secs, translation;
777     int max_devs, bus_id, unit_id, index;
778     const char *devaddr;
779     const char *werror, *rerror;
780     bool read_only = false;
781     bool copy_on_read;
782     const char *serial;
783     const char *filename;
784     Error *local_err = NULL;
785     int i;
786
787     /* Change legacy command line options into QMP ones */
788     static const struct {
789         const char *from;
790         const char *to;
791     } opt_renames[] = {
792         { "iops",           "throttling.iops-total" },
793         { "iops_rd",        "throttling.iops-read" },
794         { "iops_wr",        "throttling.iops-write" },
795
796         { "bps",            "throttling.bps-total" },
797         { "bps_rd",         "throttling.bps-read" },
798         { "bps_wr",         "throttling.bps-write" },
799
800         { "iops_max",       "throttling.iops-total-max" },
801         { "iops_rd_max",    "throttling.iops-read-max" },
802         { "iops_wr_max",    "throttling.iops-write-max" },
803
804         { "bps_max",        "throttling.bps-total-max" },
805         { "bps_rd_max",     "throttling.bps-read-max" },
806         { "bps_wr_max",     "throttling.bps-write-max" },
807
808         { "iops_size",      "throttling.iops-size" },
809
810         { "group",          "throttling.group" },
811
812         { "readonly",       "read-only" },
813     };
814
815     for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
816         qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
817                         &local_err);
818         if (local_err) {
819             error_report_err(local_err);
820             return NULL;
821         }
822     }
823
824     value = qemu_opt_get(all_opts, "cache");
825     if (value) {
826         int flags = 0;
827
828         if (bdrv_parse_cache_flags(value, &flags) != 0) {
829             error_report("invalid cache option");
830             return NULL;
831         }
832
833         /* Specific options take precedence */
834         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
835             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
836                               !!(flags & BDRV_O_CACHE_WB), &error_abort);
837         }
838         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
839             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
840                               !!(flags & BDRV_O_NOCACHE), &error_abort);
841         }
842         if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
843             qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
844                               !!(flags & BDRV_O_NO_FLUSH), &error_abort);
845         }
846         qemu_opt_unset(all_opts, "cache");
847     }
848
849     /* Get a QDict for processing the options */
850     bs_opts = qdict_new();
851     qemu_opts_to_qdict(all_opts, bs_opts);
852
853     legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
854                                    &error_abort);
855     qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
856     if (local_err) {
857         error_report_err(local_err);
858         goto fail;
859     }
860
861     /* Deprecated option boot=[on|off] */
862     if (qemu_opt_get(legacy_opts, "boot") != NULL) {
863         fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
864                 "ignored. Future versions will reject this parameter. Please "
865                 "update your scripts.\n");
866     }
867
868     /* Media type */
869     value = qemu_opt_get(legacy_opts, "media");
870     if (value) {
871         if (!strcmp(value, "disk")) {
872             media = MEDIA_DISK;
873         } else if (!strcmp(value, "cdrom")) {
874             media = MEDIA_CDROM;
875             read_only = true;
876         } else {
877             error_report("'%s' invalid media", value);
878             goto fail;
879         }
880     }
881
882     /* copy-on-read is disabled with a warning for read-only devices */
883     read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
884     copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
885
886     if (read_only && copy_on_read) {
887         error_report("warning: disabling copy-on-read on read-only drive");
888         copy_on_read = false;
889     }
890
891     qdict_put(bs_opts, "read-only",
892               qstring_from_str(read_only ? "on" : "off"));
893     qdict_put(bs_opts, "copy-on-read",
894               qstring_from_str(copy_on_read ? "on" :"off"));
895
896     /* Controller type */
897     value = qemu_opt_get(legacy_opts, "if");
898     if (value) {
899         for (type = 0;
900              type < IF_COUNT && strcmp(value, if_name[type]);
901              type++) {
902         }
903         if (type == IF_COUNT) {
904             error_report("unsupported bus type '%s'", value);
905             goto fail;
906         }
907     } else {
908         type = block_default_type;
909     }
910
911     /* Geometry */
912     cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);
913     heads = qemu_opt_get_number(legacy_opts, "heads", 0);
914     secs  = qemu_opt_get_number(legacy_opts, "secs", 0);
915
916     if (cyls || heads || secs) {
917         if (cyls < 1) {
918             error_report("invalid physical cyls number");
919             goto fail;
920         }
921         if (heads < 1) {
922             error_report("invalid physical heads number");
923             goto fail;
924         }
925         if (secs < 1) {
926             error_report("invalid physical secs number");
927             goto fail;
928         }
929     }
930
931     translation = BIOS_ATA_TRANSLATION_AUTO;
932     value = qemu_opt_get(legacy_opts, "trans");
933     if (value != NULL) {
934         if (!cyls) {
935             error_report("'%s' trans must be used with cyls, heads and secs",
936                          value);
937             goto fail;
938         }
939         if (!strcmp(value, "none")) {
940             translation = BIOS_ATA_TRANSLATION_NONE;
941         } else if (!strcmp(value, "lba")) {
942             translation = BIOS_ATA_TRANSLATION_LBA;
943         } else if (!strcmp(value, "large")) {
944             translation = BIOS_ATA_TRANSLATION_LARGE;
945         } else if (!strcmp(value, "rechs")) {
946             translation = BIOS_ATA_TRANSLATION_RECHS;
947         } else if (!strcmp(value, "auto")) {
948             translation = BIOS_ATA_TRANSLATION_AUTO;
949         } else {
950             error_report("'%s' invalid translation type", value);
951             goto fail;
952         }
953     }
954
955     if (media == MEDIA_CDROM) {
956         if (cyls || secs || heads) {
957             error_report("CHS can't be set with media=cdrom");
958             goto fail;
959         }
960     }
961
962     /* Device address specified by bus/unit or index.
963      * If none was specified, try to find the first free one. */
964     bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);
965     unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
966     index   = qemu_opt_get_number(legacy_opts, "index", -1);
967
968     max_devs = if_max_devs[type];
969
970     if (index != -1) {
971         if (bus_id != 0 || unit_id != -1) {
972             error_report("index cannot be used with bus and unit");
973             goto fail;
974         }
975         bus_id = drive_index_to_bus_id(type, index);
976         unit_id = drive_index_to_unit_id(type, index);
977     }
978
979     if (unit_id == -1) {
980        unit_id = 0;
981        while (drive_get(type, bus_id, unit_id) != NULL) {
982            unit_id++;
983            if (max_devs && unit_id >= max_devs) {
984                unit_id -= max_devs;
985                bus_id++;
986            }
987        }
988     }
989
990     if (max_devs && unit_id >= max_devs) {
991         error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
992         goto fail;
993     }
994
995     if (drive_get(type, bus_id, unit_id) != NULL) {
996         error_report("drive with bus=%d, unit=%d (index=%d) exists",
997                      bus_id, unit_id, index);
998         goto fail;
999     }
1000
1001     /* Serial number */
1002     serial = qemu_opt_get(legacy_opts, "serial");
1003
1004     /* no id supplied -> create one */
1005     if (qemu_opts_id(all_opts) == NULL) {
1006         char *new_id;
1007         const char *mediastr = "";
1008         if (type == IF_IDE || type == IF_SCSI) {
1009             mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1010         }
1011         if (max_devs) {
1012             new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1013                                      mediastr, unit_id);
1014         } else {
1015             new_id = g_strdup_printf("%s%s%i", if_name[type],
1016                                      mediastr, unit_id);
1017         }
1018         qdict_put(bs_opts, "id", qstring_from_str(new_id));
1019         g_free(new_id);
1020     }
1021
1022     /* Add virtio block device */
1023     devaddr = qemu_opt_get(legacy_opts, "addr");
1024     if (devaddr && type != IF_VIRTIO) {
1025         error_report("addr is not supported by this bus type");
1026         goto fail;
1027     }
1028
1029     if (type == IF_VIRTIO) {
1030         QemuOpts *devopts;
1031         devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1032                                    &error_abort);
1033         if (arch_type == QEMU_ARCH_S390X) {
1034             qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
1035         } else {
1036             qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
1037         }
1038         qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1039                      &error_abort);
1040         if (devaddr) {
1041             qemu_opt_set(devopts, "addr", devaddr, &error_abort);
1042         }
1043     }
1044
1045     filename = qemu_opt_get(legacy_opts, "file");
1046
1047     /* Check werror/rerror compatibility with if=... */
1048     werror = qemu_opt_get(legacy_opts, "werror");
1049     if (werror != NULL) {
1050         if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1051             type != IF_NONE) {
1052             error_report("werror is not supported by this bus type");
1053             goto fail;
1054         }
1055         qdict_put(bs_opts, "werror", qstring_from_str(werror));
1056     }
1057
1058     rerror = qemu_opt_get(legacy_opts, "rerror");
1059     if (rerror != NULL) {
1060         if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1061             type != IF_NONE) {
1062             error_report("rerror is not supported by this bus type");
1063             goto fail;
1064         }
1065         qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1066     }
1067
1068     /* Actual block device init: Functionality shared with blockdev-add */
1069     blk = blockdev_init(filename, bs_opts, &local_err);
1070     bs_opts = NULL;
1071     if (!blk) {
1072         if (local_err) {
1073             error_report_err(local_err);
1074         }
1075         goto fail;
1076     } else {
1077         assert(!local_err);
1078     }
1079
1080     /* Create legacy DriveInfo */
1081     dinfo = g_malloc0(sizeof(*dinfo));
1082     dinfo->opts = all_opts;
1083
1084     dinfo->cyls = cyls;
1085     dinfo->heads = heads;
1086     dinfo->secs = secs;
1087     dinfo->trans = translation;
1088
1089     dinfo->type = type;
1090     dinfo->bus = bus_id;
1091     dinfo->unit = unit_id;
1092     dinfo->devaddr = devaddr;
1093     dinfo->serial = g_strdup(serial);
1094
1095     blk_set_legacy_dinfo(blk, dinfo);
1096
1097     switch(type) {
1098     case IF_IDE:
1099     case IF_SCSI:
1100     case IF_XEN:
1101     case IF_NONE:
1102         dinfo->media_cd = media == MEDIA_CDROM;
1103         break;
1104     default:
1105         break;
1106     }
1107
1108 fail:
1109     qemu_opts_del(legacy_opts);
1110     QDECREF(bs_opts);
1111     return dinfo;
1112 }
1113
1114 void hmp_commit(Monitor *mon, const QDict *qdict)
1115 {
1116     const char *device = qdict_get_str(qdict, "device");
1117     BlockBackend *blk;
1118     int ret;
1119
1120     if (!strcmp(device, "all")) {
1121         ret = bdrv_commit_all();
1122     } else {
1123         BlockDriverState *bs;
1124         AioContext *aio_context;
1125
1126         blk = blk_by_name(device);
1127         if (!blk) {
1128             monitor_printf(mon, "Device '%s' not found\n", device);
1129             return;
1130         }
1131         if (!blk_is_available(blk)) {
1132             monitor_printf(mon, "Device '%s' has no medium\n", device);
1133             return;
1134         }
1135
1136         bs = blk_bs(blk);
1137         aio_context = bdrv_get_aio_context(bs);
1138         aio_context_acquire(aio_context);
1139
1140         ret = bdrv_commit(bs);
1141
1142         aio_context_release(aio_context);
1143     }
1144     if (ret < 0) {
1145         monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1146                        strerror(-ret));
1147     }
1148 }
1149
1150 static void blockdev_do_action(TransactionActionKind type, void *data,
1151                                Error **errp)
1152 {
1153     TransactionAction action;
1154     TransactionActionList list;
1155
1156     action.type = type;
1157     action.u.data = data;
1158     list.value = &action;
1159     list.next = NULL;
1160     qmp_transaction(&list, errp);
1161 }
1162
1163 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1164                                 bool has_node_name, const char *node_name,
1165                                 const char *snapshot_file,
1166                                 bool has_snapshot_node_name,
1167                                 const char *snapshot_node_name,
1168                                 bool has_format, const char *format,
1169                                 bool has_mode, NewImageMode mode, Error **errp)
1170 {
1171     BlockdevSnapshotSync snapshot = {
1172         .has_device = has_device,
1173         .device = (char *) device,
1174         .has_node_name = has_node_name,
1175         .node_name = (char *) node_name,
1176         .snapshot_file = (char *) snapshot_file,
1177         .has_snapshot_node_name = has_snapshot_node_name,
1178         .snapshot_node_name = (char *) snapshot_node_name,
1179         .has_format = has_format,
1180         .format = (char *) format,
1181         .has_mode = has_mode,
1182         .mode = mode,
1183     };
1184     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1185                        &snapshot, errp);
1186 }
1187
1188 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1189                            Error **errp)
1190 {
1191     BlockdevSnapshot snapshot_data = {
1192         .node = (char *) node,
1193         .overlay = (char *) overlay
1194     };
1195
1196     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1197                        &snapshot_data, errp);
1198 }
1199
1200 void qmp_blockdev_snapshot_internal_sync(const char *device,
1201                                          const char *name,
1202                                          Error **errp)
1203 {
1204     BlockdevSnapshotInternal snapshot = {
1205         .device = (char *) device,
1206         .name = (char *) name
1207     };
1208
1209     blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1210                        &snapshot, errp);
1211 }
1212
1213 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1214                                                          bool has_id,
1215                                                          const char *id,
1216                                                          bool has_name,
1217                                                          const char *name,
1218                                                          Error **errp)
1219 {
1220     BlockDriverState *bs;
1221     BlockBackend *blk;
1222     AioContext *aio_context;
1223     QEMUSnapshotInfo sn;
1224     Error *local_err = NULL;
1225     SnapshotInfo *info = NULL;
1226     int ret;
1227
1228     blk = blk_by_name(device);
1229     if (!blk) {
1230         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1231                   "Device '%s' not found", device);
1232         return NULL;
1233     }
1234
1235     aio_context = blk_get_aio_context(blk);
1236     aio_context_acquire(aio_context);
1237
1238     if (!has_id) {
1239         id = NULL;
1240     }
1241
1242     if (!has_name) {
1243         name = NULL;
1244     }
1245
1246     if (!id && !name) {
1247         error_setg(errp, "Name or id must be provided");
1248         goto out_aio_context;
1249     }
1250
1251     if (!blk_is_available(blk)) {
1252         error_setg(errp, "Device '%s' has no medium", device);
1253         goto out_aio_context;
1254     }
1255     bs = blk_bs(blk);
1256
1257     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1258         goto out_aio_context;
1259     }
1260
1261     ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1262     if (local_err) {
1263         error_propagate(errp, local_err);
1264         goto out_aio_context;
1265     }
1266     if (!ret) {
1267         error_setg(errp,
1268                    "Snapshot with id '%s' and name '%s' does not exist on "
1269                    "device '%s'",
1270                    STR_OR_NULL(id), STR_OR_NULL(name), device);
1271         goto out_aio_context;
1272     }
1273
1274     bdrv_snapshot_delete(bs, id, name, &local_err);
1275     if (local_err) {
1276         error_propagate(errp, local_err);
1277         goto out_aio_context;
1278     }
1279
1280     aio_context_release(aio_context);
1281
1282     info = g_new0(SnapshotInfo, 1);
1283     info->id = g_strdup(sn.id_str);
1284     info->name = g_strdup(sn.name);
1285     info->date_nsec = sn.date_nsec;
1286     info->date_sec = sn.date_sec;
1287     info->vm_state_size = sn.vm_state_size;
1288     info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1289     info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1290
1291     return info;
1292
1293 out_aio_context:
1294     aio_context_release(aio_context);
1295     return NULL;
1296 }
1297
1298 /**
1299  * block_dirty_bitmap_lookup:
1300  * Return a dirty bitmap (if present), after validating
1301  * the node reference and bitmap names.
1302  *
1303  * @node: The name of the BDS node to search for bitmaps
1304  * @name: The name of the bitmap to search for
1305  * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1306  * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1307  * @errp: Output pointer for error information. Can be NULL.
1308  *
1309  * @return: A bitmap object on success, or NULL on failure.
1310  */
1311 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1312                                                   const char *name,
1313                                                   BlockDriverState **pbs,
1314                                                   AioContext **paio,
1315                                                   Error **errp)
1316 {
1317     BlockDriverState *bs;
1318     BdrvDirtyBitmap *bitmap;
1319     AioContext *aio_context;
1320
1321     if (!node) {
1322         error_setg(errp, "Node cannot be NULL");
1323         return NULL;
1324     }
1325     if (!name) {
1326         error_setg(errp, "Bitmap name cannot be NULL");
1327         return NULL;
1328     }
1329     bs = bdrv_lookup_bs(node, node, NULL);
1330     if (!bs) {
1331         error_setg(errp, "Node '%s' not found", node);
1332         return NULL;
1333     }
1334
1335     aio_context = bdrv_get_aio_context(bs);
1336     aio_context_acquire(aio_context);
1337
1338     bitmap = bdrv_find_dirty_bitmap(bs, name);
1339     if (!bitmap) {
1340         error_setg(errp, "Dirty bitmap '%s' not found", name);
1341         goto fail;
1342     }
1343
1344     if (pbs) {
1345         *pbs = bs;
1346     }
1347     if (paio) {
1348         *paio = aio_context;
1349     } else {
1350         aio_context_release(aio_context);
1351     }
1352
1353     return bitmap;
1354
1355  fail:
1356     aio_context_release(aio_context);
1357     return NULL;
1358 }
1359
1360 /* New and old BlockDriverState structs for atomic group operations */
1361
1362 typedef struct BlkTransactionState BlkTransactionState;
1363
1364 /* Only prepare() may fail. In a single transaction, only one of commit() or
1365    abort() will be called, clean() will always be called if it present. */
1366 typedef struct BdrvActionOps {
1367     /* Size of state struct, in bytes. */
1368     size_t instance_size;
1369     /* Prepare the work, must NOT be NULL. */
1370     void (*prepare)(BlkTransactionState *common, Error **errp);
1371     /* Commit the changes, can be NULL. */
1372     void (*commit)(BlkTransactionState *common);
1373     /* Abort the changes on fail, can be NULL. */
1374     void (*abort)(BlkTransactionState *common);
1375     /* Clean up resource in the end, can be NULL. */
1376     void (*clean)(BlkTransactionState *common);
1377 } BdrvActionOps;
1378
1379 /*
1380  * This structure must be arranged as first member in child type, assuming
1381  * that compiler will also arrange it to the same address with parent instance.
1382  * Later it will be used in free().
1383  */
1384 struct BlkTransactionState {
1385     TransactionAction *action;
1386     const BdrvActionOps *ops;
1387     QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1388 };
1389
1390 /* internal snapshot private data */
1391 typedef struct InternalSnapshotState {
1392     BlkTransactionState common;
1393     BlockDriverState *bs;
1394     AioContext *aio_context;
1395     QEMUSnapshotInfo sn;
1396     bool created;
1397 } InternalSnapshotState;
1398
1399 static void internal_snapshot_prepare(BlkTransactionState *common,
1400                                       Error **errp)
1401 {
1402     Error *local_err = NULL;
1403     const char *device;
1404     const char *name;
1405     BlockBackend *blk;
1406     BlockDriverState *bs;
1407     QEMUSnapshotInfo old_sn, *sn;
1408     bool ret;
1409     qemu_timeval tv;
1410     BlockdevSnapshotInternal *internal;
1411     InternalSnapshotState *state;
1412     int ret1;
1413
1414     g_assert(common->action->type ==
1415              TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1416     internal = common->action->u.blockdev_snapshot_internal_sync;
1417     state = DO_UPCAST(InternalSnapshotState, common, common);
1418
1419     /* 1. parse input */
1420     device = internal->device;
1421     name = internal->name;
1422
1423     /* 2. check for validation */
1424     blk = blk_by_name(device);
1425     if (!blk) {
1426         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1427                   "Device '%s' not found", device);
1428         return;
1429     }
1430
1431     /* AioContext is released in .clean() */
1432     state->aio_context = blk_get_aio_context(blk);
1433     aio_context_acquire(state->aio_context);
1434
1435     if (!blk_is_available(blk)) {
1436         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1437         return;
1438     }
1439     bs = blk_bs(blk);
1440
1441     state->bs = bs;
1442     bdrv_drained_begin(bs);
1443
1444     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1445         return;
1446     }
1447
1448     if (bdrv_is_read_only(bs)) {
1449         error_setg(errp, "Device '%s' is read only", device);
1450         return;
1451     }
1452
1453     if (!bdrv_can_snapshot(bs)) {
1454         error_setg(errp, "Block format '%s' used by device '%s' "
1455                    "does not support internal snapshots",
1456                    bs->drv->format_name, device);
1457         return;
1458     }
1459
1460     if (!strlen(name)) {
1461         error_setg(errp, "Name is empty");
1462         return;
1463     }
1464
1465     /* check whether a snapshot with name exist */
1466     ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1467                                             &local_err);
1468     if (local_err) {
1469         error_propagate(errp, local_err);
1470         return;
1471     } else if (ret) {
1472         error_setg(errp,
1473                    "Snapshot with name '%s' already exists on device '%s'",
1474                    name, device);
1475         return;
1476     }
1477
1478     /* 3. take the snapshot */
1479     sn = &state->sn;
1480     pstrcpy(sn->name, sizeof(sn->name), name);
1481     qemu_gettimeofday(&tv);
1482     sn->date_sec = tv.tv_sec;
1483     sn->date_nsec = tv.tv_usec * 1000;
1484     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1485
1486     ret1 = bdrv_snapshot_create(bs, sn);
1487     if (ret1 < 0) {
1488         error_setg_errno(errp, -ret1,
1489                          "Failed to create snapshot '%s' on device '%s'",
1490                          name, device);
1491         return;
1492     }
1493
1494     /* 4. succeed, mark a snapshot is created */
1495     state->created = true;
1496 }
1497
1498 static void internal_snapshot_abort(BlkTransactionState *common)
1499 {
1500     InternalSnapshotState *state =
1501                              DO_UPCAST(InternalSnapshotState, common, common);
1502     BlockDriverState *bs = state->bs;
1503     QEMUSnapshotInfo *sn = &state->sn;
1504     Error *local_error = NULL;
1505
1506     if (!state->created) {
1507         return;
1508     }
1509
1510     if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1511         error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1512                      "device '%s' in abort: %s",
1513                      sn->id_str,
1514                      sn->name,
1515                      bdrv_get_device_name(bs),
1516                      error_get_pretty(local_error));
1517         error_free(local_error);
1518     }
1519 }
1520
1521 static void internal_snapshot_clean(BlkTransactionState *common)
1522 {
1523     InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1524                                              common, common);
1525
1526     if (state->aio_context) {
1527         if (state->bs) {
1528             bdrv_drained_end(state->bs);
1529         }
1530         aio_context_release(state->aio_context);
1531     }
1532 }
1533
1534 /* external snapshot private data */
1535 typedef struct ExternalSnapshotState {
1536     BlkTransactionState common;
1537     BlockDriverState *old_bs;
1538     BlockDriverState *new_bs;
1539     AioContext *aio_context;
1540 } ExternalSnapshotState;
1541
1542 static void external_snapshot_prepare(BlkTransactionState *common,
1543                                       Error **errp)
1544 {
1545     int flags = 0, ret;
1546     QDict *options = NULL;
1547     Error *local_err = NULL;
1548     /* Device and node name of the image to generate the snapshot from */
1549     const char *device;
1550     const char *node_name;
1551     /* Reference to the new image (for 'blockdev-snapshot') */
1552     const char *snapshot_ref;
1553     /* File name of the new image (for 'blockdev-snapshot-sync') */
1554     const char *new_image_file;
1555     ExternalSnapshotState *state =
1556                              DO_UPCAST(ExternalSnapshotState, common, common);
1557     TransactionAction *action = common->action;
1558
1559     /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1560      * purpose but a different set of parameters */
1561     switch (action->type) {
1562     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1563         {
1564             BlockdevSnapshot *s = action->u.blockdev_snapshot;
1565             device = s->node;
1566             node_name = s->node;
1567             new_image_file = NULL;
1568             snapshot_ref = s->overlay;
1569         }
1570         break;
1571     case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1572         {
1573             BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
1574             device = s->has_device ? s->device : NULL;
1575             node_name = s->has_node_name ? s->node_name : NULL;
1576             new_image_file = s->snapshot_file;
1577             snapshot_ref = NULL;
1578         }
1579         break;
1580     default:
1581         g_assert_not_reached();
1582     }
1583
1584     /* start processing */
1585     state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1586     if (!state->old_bs) {
1587         return;
1588     }
1589
1590     /* Acquire AioContext now so any threads operating on old_bs stop */
1591     state->aio_context = bdrv_get_aio_context(state->old_bs);
1592     aio_context_acquire(state->aio_context);
1593     bdrv_drained_begin(state->old_bs);
1594
1595     if (!bdrv_is_inserted(state->old_bs)) {
1596         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1597         return;
1598     }
1599
1600     if (bdrv_op_is_blocked(state->old_bs,
1601                            BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1602         return;
1603     }
1604
1605     if (!bdrv_is_read_only(state->old_bs)) {
1606         if (bdrv_flush(state->old_bs)) {
1607             error_setg(errp, QERR_IO_ERROR);
1608             return;
1609         }
1610     }
1611
1612     if (!bdrv_is_first_non_filter(state->old_bs)) {
1613         error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
1614         return;
1615     }
1616
1617     if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1618         BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync;
1619         const char *format = s->has_format ? s->format : "qcow2";
1620         enum NewImageMode mode;
1621         const char *snapshot_node_name =
1622             s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1623
1624         if (node_name && !snapshot_node_name) {
1625             error_setg(errp, "New snapshot node name missing");
1626             return;
1627         }
1628
1629         if (snapshot_node_name &&
1630             bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1631             error_setg(errp, "New snapshot node name already in use");
1632             return;
1633         }
1634
1635         flags = state->old_bs->open_flags;
1636
1637         /* create new image w/backing file */
1638         mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1639         if (mode != NEW_IMAGE_MODE_EXISTING) {
1640             bdrv_img_create(new_image_file, format,
1641                             state->old_bs->filename,
1642                             state->old_bs->drv->format_name,
1643                             NULL, -1, flags, &local_err, false);
1644             if (local_err) {
1645                 error_propagate(errp, local_err);
1646                 return;
1647             }
1648         }
1649
1650         options = qdict_new();
1651         if (s->has_snapshot_node_name) {
1652             qdict_put(options, "node-name",
1653                       qstring_from_str(snapshot_node_name));
1654         }
1655         qdict_put(options, "driver", qstring_from_str(format));
1656
1657         flags |= BDRV_O_NO_BACKING;
1658     }
1659
1660     assert(state->new_bs == NULL);
1661     ret = bdrv_open(&state->new_bs, new_image_file, snapshot_ref, options,
1662                     flags, errp);
1663     /* We will manually add the backing_hd field to the bs later */
1664     if (ret != 0) {
1665         return;
1666     }
1667
1668     if (state->new_bs->blk != NULL) {
1669         error_setg(errp, "The snapshot is already in use by %s",
1670                    blk_name(state->new_bs->blk));
1671         return;
1672     }
1673
1674     if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1675                            errp)) {
1676         return;
1677     }
1678
1679     if (state->new_bs->backing != NULL) {
1680         error_setg(errp, "The snapshot already has a backing image");
1681         return;
1682     }
1683
1684     if (!state->new_bs->drv->supports_backing) {
1685         error_setg(errp, "The snapshot does not support backing images");
1686     }
1687 }
1688
1689 static void external_snapshot_commit(BlkTransactionState *common)
1690 {
1691     ExternalSnapshotState *state =
1692                              DO_UPCAST(ExternalSnapshotState, common, common);
1693
1694     bdrv_set_aio_context(state->new_bs, state->aio_context);
1695
1696     /* This removes our old bs and adds the new bs */
1697     bdrv_append(state->new_bs, state->old_bs);
1698     /* We don't need (or want) to use the transactional
1699      * bdrv_reopen_multiple() across all the entries at once, because we
1700      * don't want to abort all of them if one of them fails the reopen */
1701     bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1702                 NULL);
1703 }
1704
1705 static void external_snapshot_abort(BlkTransactionState *common)
1706 {
1707     ExternalSnapshotState *state =
1708                              DO_UPCAST(ExternalSnapshotState, common, common);
1709     if (state->new_bs) {
1710         bdrv_unref(state->new_bs);
1711     }
1712 }
1713
1714 static void external_snapshot_clean(BlkTransactionState *common)
1715 {
1716     ExternalSnapshotState *state =
1717                              DO_UPCAST(ExternalSnapshotState, common, common);
1718     if (state->aio_context) {
1719         bdrv_drained_end(state->old_bs);
1720         aio_context_release(state->aio_context);
1721     }
1722 }
1723
1724 typedef struct DriveBackupState {
1725     BlkTransactionState common;
1726     BlockDriverState *bs;
1727     AioContext *aio_context;
1728     BlockJob *job;
1729 } DriveBackupState;
1730
1731 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1732 {
1733     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1734     BlockBackend *blk;
1735     DriveBackup *backup;
1736     Error *local_err = NULL;
1737
1738     assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1739     backup = common->action->u.drive_backup;
1740
1741     blk = blk_by_name(backup->device);
1742     if (!blk) {
1743         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1744                   "Device '%s' not found", backup->device);
1745         return;
1746     }
1747
1748     if (!blk_is_available(blk)) {
1749         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1750         return;
1751     }
1752
1753     /* AioContext is released in .clean() */
1754     state->aio_context = blk_get_aio_context(blk);
1755     aio_context_acquire(state->aio_context);
1756     bdrv_drained_begin(blk_bs(blk));
1757     state->bs = blk_bs(blk);
1758
1759     qmp_drive_backup(backup->device, backup->target,
1760                      backup->has_format, backup->format,
1761                      backup->sync,
1762                      backup->has_mode, backup->mode,
1763                      backup->has_speed, backup->speed,
1764                      backup->has_bitmap, backup->bitmap,
1765                      backup->has_on_source_error, backup->on_source_error,
1766                      backup->has_on_target_error, backup->on_target_error,
1767                      &local_err);
1768     if (local_err) {
1769         error_propagate(errp, local_err);
1770         return;
1771     }
1772
1773     state->job = state->bs->job;
1774 }
1775
1776 static void drive_backup_abort(BlkTransactionState *common)
1777 {
1778     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1779     BlockDriverState *bs = state->bs;
1780
1781     /* Only cancel if it's the job we started */
1782     if (bs && bs->job && bs->job == state->job) {
1783         block_job_cancel_sync(bs->job);
1784     }
1785 }
1786
1787 static void drive_backup_clean(BlkTransactionState *common)
1788 {
1789     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1790
1791     if (state->aio_context) {
1792         bdrv_drained_end(state->bs);
1793         aio_context_release(state->aio_context);
1794     }
1795 }
1796
1797 typedef struct BlockdevBackupState {
1798     BlkTransactionState common;
1799     BlockDriverState *bs;
1800     BlockJob *job;
1801     AioContext *aio_context;
1802 } BlockdevBackupState;
1803
1804 static void blockdev_backup_prepare(BlkTransactionState *common, Error **errp)
1805 {
1806     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1807     BlockdevBackup *backup;
1808     BlockBackend *blk, *target;
1809     Error *local_err = NULL;
1810
1811     assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1812     backup = common->action->u.blockdev_backup;
1813
1814     blk = blk_by_name(backup->device);
1815     if (!blk) {
1816         error_setg(errp, "Device '%s' not found", backup->device);
1817         return;
1818     }
1819
1820     if (!blk_is_available(blk)) {
1821         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1822         return;
1823     }
1824
1825     target = blk_by_name(backup->target);
1826     if (!target) {
1827         error_setg(errp, "Device '%s' not found", backup->target);
1828         return;
1829     }
1830
1831     /* AioContext is released in .clean() */
1832     state->aio_context = blk_get_aio_context(blk);
1833     if (state->aio_context != blk_get_aio_context(target)) {
1834         state->aio_context = NULL;
1835         error_setg(errp, "Backup between two IO threads is not implemented");
1836         return;
1837     }
1838     aio_context_acquire(state->aio_context);
1839     state->bs = blk_bs(blk);
1840     bdrv_drained_begin(state->bs);
1841
1842     qmp_blockdev_backup(backup->device, backup->target,
1843                         backup->sync,
1844                         backup->has_speed, backup->speed,
1845                         backup->has_on_source_error, backup->on_source_error,
1846                         backup->has_on_target_error, backup->on_target_error,
1847                         &local_err);
1848     if (local_err) {
1849         error_propagate(errp, local_err);
1850         return;
1851     }
1852
1853     state->job = state->bs->job;
1854 }
1855
1856 static void blockdev_backup_abort(BlkTransactionState *common)
1857 {
1858     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1859     BlockDriverState *bs = state->bs;
1860
1861     /* Only cancel if it's the job we started */
1862     if (bs && bs->job && bs->job == state->job) {
1863         block_job_cancel_sync(bs->job);
1864     }
1865 }
1866
1867 static void blockdev_backup_clean(BlkTransactionState *common)
1868 {
1869     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1870
1871     if (state->aio_context) {
1872         bdrv_drained_end(state->bs);
1873         aio_context_release(state->aio_context);
1874     }
1875 }
1876
1877 typedef struct BlockDirtyBitmapState {
1878     BlkTransactionState common;
1879     BdrvDirtyBitmap *bitmap;
1880     BlockDriverState *bs;
1881     AioContext *aio_context;
1882     HBitmap *backup;
1883     bool prepared;
1884 } BlockDirtyBitmapState;
1885
1886 static void block_dirty_bitmap_add_prepare(BlkTransactionState *common,
1887                                            Error **errp)
1888 {
1889     Error *local_err = NULL;
1890     BlockDirtyBitmapAdd *action;
1891     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1892                                              common, common);
1893
1894     action = common->action->block_dirty_bitmap_add;
1895     /* AIO context taken and released within qmp_block_dirty_bitmap_add */
1896     qmp_block_dirty_bitmap_add(action->node, action->name,
1897                                action->has_granularity, action->granularity,
1898                                &local_err);
1899
1900     if (!local_err) {
1901         state->prepared = true;
1902     } else {
1903         error_propagate(errp, local_err);
1904     }
1905 }
1906
1907 static void block_dirty_bitmap_add_abort(BlkTransactionState *common)
1908 {
1909     BlockDirtyBitmapAdd *action;
1910     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1911                                              common, common);
1912
1913     action = common->action->block_dirty_bitmap_add;
1914     /* Should not be able to fail: IF the bitmap was added via .prepare(),
1915      * then the node reference and bitmap name must have been valid.
1916      */
1917     if (state->prepared) {
1918         qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
1919     }
1920 }
1921
1922 static void block_dirty_bitmap_clear_prepare(BlkTransactionState *common,
1923                                              Error **errp)
1924 {
1925     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1926                                              common, common);
1927     BlockDirtyBitmap *action;
1928
1929     action = common->action->block_dirty_bitmap_clear;
1930     state->bitmap = block_dirty_bitmap_lookup(action->node,
1931                                               action->name,
1932                                               &state->bs,
1933                                               &state->aio_context,
1934                                               errp);
1935     if (!state->bitmap) {
1936         return;
1937     }
1938
1939     if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
1940         error_setg(errp, "Cannot modify a frozen bitmap");
1941         return;
1942     } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
1943         error_setg(errp, "Cannot clear a disabled bitmap");
1944         return;
1945     }
1946
1947     bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
1948     /* AioContext is released in .clean() */
1949 }
1950
1951 static void block_dirty_bitmap_clear_abort(BlkTransactionState *common)
1952 {
1953     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1954                                              common, common);
1955
1956     bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
1957 }
1958
1959 static void block_dirty_bitmap_clear_commit(BlkTransactionState *common)
1960 {
1961     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1962                                              common, common);
1963
1964     hbitmap_free(state->backup);
1965 }
1966
1967 static void block_dirty_bitmap_clear_clean(BlkTransactionState *common)
1968 {
1969     BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
1970                                              common, common);
1971
1972     if (state->aio_context) {
1973         aio_context_release(state->aio_context);
1974     }
1975 }
1976
1977 static void abort_prepare(BlkTransactionState *common, Error **errp)
1978 {
1979     error_setg(errp, "Transaction aborted using Abort action");
1980 }
1981
1982 static void abort_commit(BlkTransactionState *common)
1983 {
1984     g_assert_not_reached(); /* this action never succeeds */
1985 }
1986
1987 static const BdrvActionOps actions[] = {
1988     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
1989         .instance_size = sizeof(ExternalSnapshotState),
1990         .prepare  = external_snapshot_prepare,
1991         .commit   = external_snapshot_commit,
1992         .abort = external_snapshot_abort,
1993     },
1994     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1995         .instance_size = sizeof(ExternalSnapshotState),
1996         .prepare  = external_snapshot_prepare,
1997         .commit   = external_snapshot_commit,
1998         .abort = external_snapshot_abort,
1999         .clean = external_snapshot_clean,
2000     },
2001     [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2002         .instance_size = sizeof(DriveBackupState),
2003         .prepare = drive_backup_prepare,
2004         .abort = drive_backup_abort,
2005         .clean = drive_backup_clean,
2006     },
2007     [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2008         .instance_size = sizeof(BlockdevBackupState),
2009         .prepare = blockdev_backup_prepare,
2010         .abort = blockdev_backup_abort,
2011         .clean = blockdev_backup_clean,
2012     },
2013     [TRANSACTION_ACTION_KIND_ABORT] = {
2014         .instance_size = sizeof(BlkTransactionState),
2015         .prepare = abort_prepare,
2016         .commit = abort_commit,
2017     },
2018     [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2019         .instance_size = sizeof(InternalSnapshotState),
2020         .prepare  = internal_snapshot_prepare,
2021         .abort = internal_snapshot_abort,
2022         .clean = internal_snapshot_clean,
2023     },
2024     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2025         .instance_size = sizeof(BlockDirtyBitmapState),
2026         .prepare = block_dirty_bitmap_add_prepare,
2027         .abort = block_dirty_bitmap_add_abort,
2028     },
2029     [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2030         .instance_size = sizeof(BlockDirtyBitmapState),
2031         .prepare = block_dirty_bitmap_clear_prepare,
2032         .commit = block_dirty_bitmap_clear_commit,
2033         .abort = block_dirty_bitmap_clear_abort,
2034         .clean = block_dirty_bitmap_clear_clean,
2035     }
2036 };
2037
2038 /*
2039  * 'Atomic' group operations.  The operations are performed as a set, and if
2040  * any fail then we roll back all operations in the group.
2041  */
2042 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
2043 {
2044     TransactionActionList *dev_entry = dev_list;
2045     BlkTransactionState *state, *next;
2046     Error *local_err = NULL;
2047
2048     QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
2049     QSIMPLEQ_INIT(&snap_bdrv_states);
2050
2051     /* drain all i/o before any operations */
2052     bdrv_drain_all();
2053
2054     /* We don't do anything in this loop that commits us to the operations */
2055     while (NULL != dev_entry) {
2056         TransactionAction *dev_info = NULL;
2057         const BdrvActionOps *ops;
2058
2059         dev_info = dev_entry->value;
2060         dev_entry = dev_entry->next;
2061
2062         assert(dev_info->type < ARRAY_SIZE(actions));
2063
2064         ops = &actions[dev_info->type];
2065         assert(ops->instance_size > 0);
2066
2067         state = g_malloc0(ops->instance_size);
2068         state->ops = ops;
2069         state->action = dev_info;
2070         QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2071
2072         state->ops->prepare(state, &local_err);
2073         if (local_err) {
2074             error_propagate(errp, local_err);
2075             goto delete_and_fail;
2076         }
2077     }
2078
2079     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2080         if (state->ops->commit) {
2081             state->ops->commit(state);
2082         }
2083     }
2084
2085     /* success */
2086     goto exit;
2087
2088 delete_and_fail:
2089     /* failure, and it is all-or-none; roll back all operations */
2090     QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2091         if (state->ops->abort) {
2092             state->ops->abort(state);
2093         }
2094     }
2095 exit:
2096     QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2097         if (state->ops->clean) {
2098             state->ops->clean(state);
2099         }
2100         g_free(state);
2101     }
2102 }
2103
2104 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
2105 {
2106     Error *local_err = NULL;
2107
2108     qmp_blockdev_open_tray(device, has_force, force, &local_err);
2109     if (local_err) {
2110         error_propagate(errp, local_err);
2111         return;
2112     }
2113
2114     qmp_blockdev_remove_medium(device, errp);
2115 }
2116
2117 void qmp_block_passwd(bool has_device, const char *device,
2118                       bool has_node_name, const char *node_name,
2119                       const char *password, Error **errp)
2120 {
2121     Error *local_err = NULL;
2122     BlockDriverState *bs;
2123     AioContext *aio_context;
2124
2125     bs = bdrv_lookup_bs(has_device ? device : NULL,
2126                         has_node_name ? node_name : NULL,
2127                         &local_err);
2128     if (local_err) {
2129         error_propagate(errp, local_err);
2130         return;
2131     }
2132
2133     aio_context = bdrv_get_aio_context(bs);
2134     aio_context_acquire(aio_context);
2135
2136     bdrv_add_key(bs, password, errp);
2137
2138     aio_context_release(aio_context);
2139 }
2140
2141 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2142                             Error **errp)
2143 {
2144     BlockBackend *blk;
2145     bool locked;
2146
2147     if (!has_force) {
2148         force = false;
2149     }
2150
2151     blk = blk_by_name(device);
2152     if (!blk) {
2153         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2154                   "Device '%s' not found", device);
2155         return;
2156     }
2157
2158     if (!blk_dev_has_removable_media(blk)) {
2159         error_setg(errp, "Device '%s' is not removable", device);
2160         return;
2161     }
2162
2163     if (blk_dev_is_tray_open(blk)) {
2164         return;
2165     }
2166
2167     locked = blk_dev_is_medium_locked(blk);
2168     if (locked) {
2169         blk_dev_eject_request(blk, force);
2170     }
2171
2172     if (!locked || force) {
2173         blk_dev_change_media_cb(blk, false);
2174     }
2175 }
2176
2177 void qmp_blockdev_close_tray(const char *device, Error **errp)
2178 {
2179     BlockBackend *blk;
2180
2181     blk = blk_by_name(device);
2182     if (!blk) {
2183         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2184                   "Device '%s' not found", device);
2185         return;
2186     }
2187
2188     if (!blk_dev_has_removable_media(blk)) {
2189         error_setg(errp, "Device '%s' is not removable", device);
2190         return;
2191     }
2192
2193     if (!blk_dev_is_tray_open(blk)) {
2194         return;
2195     }
2196
2197     blk_dev_change_media_cb(blk, true);
2198 }
2199
2200 void qmp_blockdev_remove_medium(const char *device, Error **errp)
2201 {
2202     BlockBackend *blk;
2203     BlockDriverState *bs;
2204     AioContext *aio_context;
2205     bool has_device;
2206
2207     blk = blk_by_name(device);
2208     if (!blk) {
2209         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2210                   "Device '%s' not found", device);
2211         return;
2212     }
2213
2214     /* For BBs without a device, we can exchange the BDS tree at will */
2215     has_device = blk_get_attached_dev(blk);
2216
2217     if (has_device && !blk_dev_has_removable_media(blk)) {
2218         error_setg(errp, "Device '%s' is not removable", device);
2219         return;
2220     }
2221
2222     if (has_device && !blk_dev_is_tray_open(blk)) {
2223         error_setg(errp, "Tray of device '%s' is not open", device);
2224         return;
2225     }
2226
2227     bs = blk_bs(blk);
2228     if (!bs) {
2229         return;
2230     }
2231
2232     aio_context = bdrv_get_aio_context(bs);
2233     aio_context_acquire(aio_context);
2234
2235     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2236         goto out;
2237     }
2238
2239     /* This follows the convention established by bdrv_make_anon() */
2240     if (bs->device_list.tqe_prev) {
2241         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
2242         bs->device_list.tqe_prev = NULL;
2243     }
2244
2245     blk_remove_bs(blk);
2246
2247 out:
2248     aio_context_release(aio_context);
2249 }
2250
2251 static void qmp_blockdev_insert_anon_medium(const char *device,
2252                                             BlockDriverState *bs, Error **errp)
2253 {
2254     BlockBackend *blk;
2255     bool has_device;
2256
2257     blk = blk_by_name(device);
2258     if (!blk) {
2259         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2260                   "Device '%s' not found", device);
2261         return;
2262     }
2263
2264     /* For BBs without a device, we can exchange the BDS tree at will */
2265     has_device = blk_get_attached_dev(blk);
2266
2267     if (has_device && !blk_dev_has_removable_media(blk)) {
2268         error_setg(errp, "Device '%s' is not removable", device);
2269         return;
2270     }
2271
2272     if (has_device && !blk_dev_is_tray_open(blk)) {
2273         error_setg(errp, "Tray of device '%s' is not open", device);
2274         return;
2275     }
2276
2277     if (blk_bs(blk)) {
2278         error_setg(errp, "There already is a medium in device '%s'", device);
2279         return;
2280     }
2281
2282     blk_insert_bs(blk, bs);
2283
2284     QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
2285 }
2286
2287 void qmp_blockdev_insert_medium(const char *device, const char *node_name,
2288                                 Error **errp)
2289 {
2290     BlockDriverState *bs;
2291
2292     bs = bdrv_find_node(node_name);
2293     if (!bs) {
2294         error_setg(errp, "Node '%s' not found", node_name);
2295         return;
2296     }
2297
2298     if (bs->blk) {
2299         error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
2300                    blk_name(bs->blk));
2301         return;
2302     }
2303
2304     qmp_blockdev_insert_anon_medium(device, bs, errp);
2305 }
2306
2307 void qmp_blockdev_change_medium(const char *device, const char *filename,
2308                                 bool has_format, const char *format,
2309                                 bool has_read_only,
2310                                 BlockdevChangeReadOnlyMode read_only,
2311                                 Error **errp)
2312 {
2313     BlockBackend *blk;
2314     BlockDriverState *medium_bs = NULL;
2315     int bdrv_flags, ret;
2316     QDict *options = NULL;
2317     Error *err = NULL;
2318
2319     blk = blk_by_name(device);
2320     if (!blk) {
2321         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2322                   "Device '%s' not found", device);
2323         goto fail;
2324     }
2325
2326     if (blk_bs(blk)) {
2327         blk_update_root_state(blk);
2328     }
2329
2330     bdrv_flags = blk_get_open_flags_from_root_state(blk);
2331
2332     if (!has_read_only) {
2333         read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2334     }
2335
2336     switch (read_only) {
2337     case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2338         break;
2339
2340     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2341         bdrv_flags &= ~BDRV_O_RDWR;
2342         break;
2343
2344     case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2345         bdrv_flags |= BDRV_O_RDWR;
2346         break;
2347
2348     default:
2349         abort();
2350     }
2351
2352     if (has_format) {
2353         options = qdict_new();
2354         qdict_put(options, "driver", qstring_from_str(format));
2355     }
2356
2357     assert(!medium_bs);
2358     ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);
2359     if (ret < 0) {
2360         goto fail;
2361     }
2362
2363     blk_apply_root_state(blk, medium_bs);
2364
2365     bdrv_add_key(medium_bs, NULL, &err);
2366     if (err) {
2367         error_propagate(errp, err);
2368         goto fail;
2369     }
2370
2371     qmp_blockdev_open_tray(device, false, false, &err);
2372     if (err) {
2373         error_propagate(errp, err);
2374         goto fail;
2375     }
2376
2377     qmp_blockdev_remove_medium(device, &err);
2378     if (err) {
2379         error_propagate(errp, err);
2380         goto fail;
2381     }
2382
2383     qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2384     if (err) {
2385         error_propagate(errp, err);
2386         goto fail;
2387     }
2388
2389     qmp_blockdev_close_tray(device, errp);
2390
2391 fail:
2392     /* If the medium has been inserted, the device has its own reference, so
2393      * ours must be relinquished; and if it has not been inserted successfully,
2394      * the reference must be relinquished anyway */
2395     bdrv_unref(medium_bs);
2396 }
2397
2398 /* throttling disk I/O limits */
2399 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
2400                                int64_t bps_wr,
2401                                int64_t iops,
2402                                int64_t iops_rd,
2403                                int64_t iops_wr,
2404                                bool has_bps_max,
2405                                int64_t bps_max,
2406                                bool has_bps_rd_max,
2407                                int64_t bps_rd_max,
2408                                bool has_bps_wr_max,
2409                                int64_t bps_wr_max,
2410                                bool has_iops_max,
2411                                int64_t iops_max,
2412                                bool has_iops_rd_max,
2413                                int64_t iops_rd_max,
2414                                bool has_iops_wr_max,
2415                                int64_t iops_wr_max,
2416                                bool has_iops_size,
2417                                int64_t iops_size,
2418                                bool has_group,
2419                                const char *group, Error **errp)
2420 {
2421     ThrottleConfig cfg;
2422     BlockDriverState *bs;
2423     BlockBackend *blk;
2424     AioContext *aio_context;
2425
2426     blk = blk_by_name(device);
2427     if (!blk) {
2428         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2429                   "Device '%s' not found", device);
2430         return;
2431     }
2432
2433     aio_context = blk_get_aio_context(blk);
2434     aio_context_acquire(aio_context);
2435
2436     bs = blk_bs(blk);
2437     if (!bs) {
2438         error_setg(errp, "Device '%s' has no medium", device);
2439         goto out;
2440     }
2441
2442     memset(&cfg, 0, sizeof(cfg));
2443     cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
2444     cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;
2445     cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
2446
2447     cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
2448     cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;
2449     cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
2450
2451     if (has_bps_max) {
2452         cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
2453     }
2454     if (has_bps_rd_max) {
2455         cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
2456     }
2457     if (has_bps_wr_max) {
2458         cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
2459     }
2460     if (has_iops_max) {
2461         cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
2462     }
2463     if (has_iops_rd_max) {
2464         cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
2465     }
2466     if (has_iops_wr_max) {
2467         cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
2468     }
2469
2470     if (has_iops_size) {
2471         cfg.op_size = iops_size;
2472     }
2473
2474     if (!check_throttle_config(&cfg, errp)) {
2475         goto out;
2476     }
2477
2478     if (throttle_enabled(&cfg)) {
2479         /* Enable I/O limits if they're not enabled yet, otherwise
2480          * just update the throttling group. */
2481         if (!bs->throttle_state) {
2482             bdrv_io_limits_enable(bs, has_group ? group : device);
2483         } else if (has_group) {
2484             bdrv_io_limits_update_group(bs, group);
2485         }
2486         /* Set the new throttling configuration */
2487         bdrv_set_io_limits(bs, &cfg);
2488     } else if (bs->throttle_state) {
2489         /* If all throttling settings are set to 0, disable I/O limits */
2490         bdrv_io_limits_disable(bs);
2491     }
2492
2493 out:
2494     aio_context_release(aio_context);
2495 }
2496
2497 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2498                                 bool has_granularity, uint32_t granularity,
2499                                 Error **errp)
2500 {
2501     AioContext *aio_context;
2502     BlockDriverState *bs;
2503
2504     if (!name || name[0] == '\0') {
2505         error_setg(errp, "Bitmap name cannot be empty");
2506         return;
2507     }
2508
2509     bs = bdrv_lookup_bs(node, node, errp);
2510     if (!bs) {
2511         return;
2512     }
2513
2514     aio_context = bdrv_get_aio_context(bs);
2515     aio_context_acquire(aio_context);
2516
2517     if (has_granularity) {
2518         if (granularity < 512 || !is_power_of_2(granularity)) {
2519             error_setg(errp, "Granularity must be power of 2 "
2520                              "and at least 512");
2521             goto out;
2522         }
2523     } else {
2524         /* Default to cluster size, if available: */
2525         granularity = bdrv_get_default_bitmap_granularity(bs);
2526     }
2527
2528     bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2529
2530  out:
2531     aio_context_release(aio_context);
2532 }
2533
2534 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2535                                    Error **errp)
2536 {
2537     AioContext *aio_context;
2538     BlockDriverState *bs;
2539     BdrvDirtyBitmap *bitmap;
2540
2541     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2542     if (!bitmap || !bs) {
2543         return;
2544     }
2545
2546     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2547         error_setg(errp,
2548                    "Bitmap '%s' is currently frozen and cannot be removed",
2549                    name);
2550         goto out;
2551     }
2552     bdrv_dirty_bitmap_make_anon(bitmap);
2553     bdrv_release_dirty_bitmap(bs, bitmap);
2554
2555  out:
2556     aio_context_release(aio_context);
2557 }
2558
2559 /**
2560  * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2561  * immediately after a full backup operation.
2562  */
2563 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2564                                   Error **errp)
2565 {
2566     AioContext *aio_context;
2567     BdrvDirtyBitmap *bitmap;
2568     BlockDriverState *bs;
2569
2570     bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2571     if (!bitmap || !bs) {
2572         return;
2573     }
2574
2575     if (bdrv_dirty_bitmap_frozen(bitmap)) {
2576         error_setg(errp,
2577                    "Bitmap '%s' is currently frozen and cannot be modified",
2578                    name);
2579         goto out;
2580     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2581         error_setg(errp,
2582                    "Bitmap '%s' is currently disabled and cannot be cleared",
2583                    name);
2584         goto out;
2585     }
2586
2587     bdrv_clear_dirty_bitmap(bitmap, NULL);
2588
2589  out:
2590     aio_context_release(aio_context);
2591 }
2592
2593 void hmp_drive_del(Monitor *mon, const QDict *qdict)
2594 {
2595     const char *id = qdict_get_str(qdict, "id");
2596     BlockBackend *blk;
2597     BlockDriverState *bs;
2598     AioContext *aio_context;
2599     Error *local_err = NULL;
2600
2601     blk = blk_by_name(id);
2602     if (!blk) {
2603         error_report("Device '%s' not found", id);
2604         return;
2605     }
2606
2607     if (!blk_legacy_dinfo(blk)) {
2608         error_report("Deleting device added with blockdev-add"
2609                      " is not supported");
2610         return;
2611     }
2612
2613     aio_context = blk_get_aio_context(blk);
2614     aio_context_acquire(aio_context);
2615
2616     bs = blk_bs(blk);
2617     if (bs) {
2618         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2619             error_report_err(local_err);
2620             aio_context_release(aio_context);
2621             return;
2622         }
2623
2624         bdrv_close(bs);
2625     }
2626
2627     /* if we have a device attached to this BlockDriverState
2628      * then we need to make the drive anonymous until the device
2629      * can be removed.  If this is a drive with no device backing
2630      * then we can just get rid of the block driver state right here.
2631      */
2632     if (blk_get_attached_dev(blk)) {
2633         blk_hide_on_behalf_of_hmp_drive_del(blk);
2634         /* Further I/O must not pause the guest */
2635         blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2636                          BLOCKDEV_ON_ERROR_REPORT);
2637     } else {
2638         blk_unref(blk);
2639     }
2640
2641     aio_context_release(aio_context);
2642 }
2643
2644 void qmp_block_resize(bool has_device, const char *device,
2645                       bool has_node_name, const char *node_name,
2646                       int64_t size, Error **errp)
2647 {
2648     Error *local_err = NULL;
2649     BlockDriverState *bs;
2650     AioContext *aio_context;
2651     int ret;
2652
2653     bs = bdrv_lookup_bs(has_device ? device : NULL,
2654                         has_node_name ? node_name : NULL,
2655                         &local_err);
2656     if (local_err) {
2657         error_propagate(errp, local_err);
2658         return;
2659     }
2660
2661     aio_context = bdrv_get_aio_context(bs);
2662     aio_context_acquire(aio_context);
2663
2664     if (!bdrv_is_first_non_filter(bs)) {
2665         error_setg(errp, QERR_FEATURE_DISABLED, "resize");
2666         goto out;
2667     }
2668
2669     if (size < 0) {
2670         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
2671         goto out;
2672     }
2673
2674     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
2675         error_setg(errp, QERR_DEVICE_IN_USE, device);
2676         goto out;
2677     }
2678
2679     /* complete all in-flight operations before resizing the device */
2680     bdrv_drain_all();
2681
2682     ret = bdrv_truncate(bs, size);
2683     switch (ret) {
2684     case 0:
2685         break;
2686     case -ENOMEDIUM:
2687         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2688         break;
2689     case -ENOTSUP:
2690         error_setg(errp, QERR_UNSUPPORTED);
2691         break;
2692     case -EACCES:
2693         error_setg(errp, "Device '%s' is read only", device);
2694         break;
2695     case -EBUSY:
2696         error_setg(errp, QERR_DEVICE_IN_USE, device);
2697         break;
2698     default:
2699         error_setg_errno(errp, -ret, "Could not resize");
2700         break;
2701     }
2702
2703 out:
2704     aio_context_release(aio_context);
2705 }
2706
2707 static void block_job_cb(void *opaque, int ret)
2708 {
2709     /* Note that this function may be executed from another AioContext besides
2710      * the QEMU main loop.  If you need to access anything that assumes the
2711      * QEMU global mutex, use a BH or introduce a mutex.
2712      */
2713
2714     BlockDriverState *bs = opaque;
2715     const char *msg = NULL;
2716
2717     trace_block_job_cb(bs, bs->job, ret);
2718
2719     assert(bs->job);
2720
2721     if (ret < 0) {
2722         msg = strerror(-ret);
2723     }
2724
2725     if (block_job_is_cancelled(bs->job)) {
2726         block_job_event_cancelled(bs->job);
2727     } else {
2728         block_job_event_completed(bs->job, msg);
2729     }
2730
2731     bdrv_put_ref_bh_schedule(bs);
2732 }
2733
2734 void qmp_block_stream(const char *device,
2735                       bool has_base, const char *base,
2736                       bool has_backing_file, const char *backing_file,
2737                       bool has_speed, int64_t speed,
2738                       bool has_on_error, BlockdevOnError on_error,
2739                       Error **errp)
2740 {
2741     BlockBackend *blk;
2742     BlockDriverState *bs;
2743     BlockDriverState *base_bs = NULL;
2744     AioContext *aio_context;
2745     Error *local_err = NULL;
2746     const char *base_name = NULL;
2747
2748     if (!has_on_error) {
2749         on_error = BLOCKDEV_ON_ERROR_REPORT;
2750     }
2751
2752     blk = blk_by_name(device);
2753     if (!blk) {
2754         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2755                   "Device '%s' not found", device);
2756         return;
2757     }
2758
2759     aio_context = blk_get_aio_context(blk);
2760     aio_context_acquire(aio_context);
2761
2762     if (!blk_is_available(blk)) {
2763         error_setg(errp, "Device '%s' has no medium", device);
2764         goto out;
2765     }
2766     bs = blk_bs(blk);
2767
2768     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
2769         goto out;
2770     }
2771
2772     if (has_base) {
2773         base_bs = bdrv_find_backing_image(bs, base);
2774         if (base_bs == NULL) {
2775             error_setg(errp, QERR_BASE_NOT_FOUND, base);
2776             goto out;
2777         }
2778         assert(bdrv_get_aio_context(base_bs) == aio_context);
2779         base_name = base;
2780     }
2781
2782     /* if we are streaming the entire chain, the result will have no backing
2783      * file, and specifying one is therefore an error */
2784     if (base_bs == NULL && has_backing_file) {
2785         error_setg(errp, "backing file specified, but streaming the "
2786                          "entire chain");
2787         goto out;
2788     }
2789
2790     /* backing_file string overrides base bs filename */
2791     base_name = has_backing_file ? backing_file : base_name;
2792
2793     stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
2794                  on_error, block_job_cb, bs, &local_err);
2795     if (local_err) {
2796         error_propagate(errp, local_err);
2797         goto out;
2798     }
2799
2800     trace_qmp_block_stream(bs, bs->job);
2801
2802 out:
2803     aio_context_release(aio_context);
2804 }
2805
2806 void qmp_block_commit(const char *device,
2807                       bool has_base, const char *base,
2808                       bool has_top, const char *top,
2809                       bool has_backing_file, const char *backing_file,
2810                       bool has_speed, int64_t speed,
2811                       Error **errp)
2812 {
2813     BlockBackend *blk;
2814     BlockDriverState *bs;
2815     BlockDriverState *base_bs, *top_bs;
2816     AioContext *aio_context;
2817     Error *local_err = NULL;
2818     /* This will be part of the QMP command, if/when the
2819      * BlockdevOnError change for blkmirror makes it in
2820      */
2821     BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
2822
2823     if (!has_speed) {
2824         speed = 0;
2825     }
2826
2827     /* Important Note:
2828      *  libvirt relies on the DeviceNotFound error class in order to probe for
2829      *  live commit feature versions; for this to work, we must make sure to
2830      *  perform the device lookup before any generic errors that may occur in a
2831      *  scenario in which all optional arguments are omitted. */
2832     blk = blk_by_name(device);
2833     if (!blk) {
2834         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2835                   "Device '%s' not found", device);
2836         return;
2837     }
2838
2839     aio_context = blk_get_aio_context(blk);
2840     aio_context_acquire(aio_context);
2841
2842     if (!blk_is_available(blk)) {
2843         error_setg(errp, "Device '%s' has no medium", device);
2844         goto out;
2845     }
2846     bs = blk_bs(blk);
2847
2848     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
2849         goto out;
2850     }
2851
2852     /* default top_bs is the active layer */
2853     top_bs = bs;
2854
2855     if (has_top && top) {
2856         if (strcmp(bs->filename, top) != 0) {
2857             top_bs = bdrv_find_backing_image(bs, top);
2858         }
2859     }
2860
2861     if (top_bs == NULL) {
2862         error_setg(errp, "Top image file %s not found", top ? top : "NULL");
2863         goto out;
2864     }
2865
2866     assert(bdrv_get_aio_context(top_bs) == aio_context);
2867
2868     if (has_base && base) {
2869         base_bs = bdrv_find_backing_image(top_bs, base);
2870     } else {
2871         base_bs = bdrv_find_base(top_bs);
2872     }
2873
2874     if (base_bs == NULL) {
2875         error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
2876         goto out;
2877     }
2878
2879     assert(bdrv_get_aio_context(base_bs) == aio_context);
2880
2881     if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
2882         goto out;
2883     }
2884
2885     /* Do not allow attempts to commit an image into itself */
2886     if (top_bs == base_bs) {
2887         error_setg(errp, "cannot commit an image into itself");
2888         goto out;
2889     }
2890
2891     if (top_bs == bs) {
2892         if (has_backing_file) {
2893             error_setg(errp, "'backing-file' specified,"
2894                              " but 'top' is the active layer");
2895             goto out;
2896         }
2897         commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2898                             bs, &local_err);
2899     } else {
2900         commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2901                      has_backing_file ? backing_file : NULL, &local_err);
2902     }
2903     if (local_err != NULL) {
2904         error_propagate(errp, local_err);
2905         goto out;
2906     }
2907
2908 out:
2909     aio_context_release(aio_context);
2910 }
2911
2912 void qmp_drive_backup(const char *device, const char *target,
2913                       bool has_format, const char *format,
2914                       enum MirrorSyncMode sync,
2915                       bool has_mode, enum NewImageMode mode,
2916                       bool has_speed, int64_t speed,
2917                       bool has_bitmap, const char *bitmap,
2918                       bool has_on_source_error, BlockdevOnError on_source_error,
2919                       bool has_on_target_error, BlockdevOnError on_target_error,
2920                       Error **errp)
2921 {
2922     BlockBackend *blk;
2923     BlockDriverState *bs;
2924     BlockDriverState *target_bs;
2925     BlockDriverState *source = NULL;
2926     BdrvDirtyBitmap *bmap = NULL;
2927     AioContext *aio_context;
2928     QDict *options = NULL;
2929     Error *local_err = NULL;
2930     int flags;
2931     int64_t size;
2932     int ret;
2933
2934     if (!has_speed) {
2935         speed = 0;
2936     }
2937     if (!has_on_source_error) {
2938         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2939     }
2940     if (!has_on_target_error) {
2941         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2942     }
2943     if (!has_mode) {
2944         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2945     }
2946
2947     blk = blk_by_name(device);
2948     if (!blk) {
2949         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2950                   "Device '%s' not found", device);
2951         return;
2952     }
2953
2954     aio_context = blk_get_aio_context(blk);
2955     aio_context_acquire(aio_context);
2956
2957     /* Although backup_run has this check too, we need to use bs->drv below, so
2958      * do an early check redundantly. */
2959     if (!blk_is_available(blk)) {
2960         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2961         goto out;
2962     }
2963     bs = blk_bs(blk);
2964
2965     if (!has_format) {
2966         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2967     }
2968
2969     /* Early check to avoid creating target */
2970     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2971         goto out;
2972     }
2973
2974     flags = bs->open_flags | BDRV_O_RDWR;
2975
2976     /* See if we have a backing HD we can use to create our new image
2977      * on top of. */
2978     if (sync == MIRROR_SYNC_MODE_TOP) {
2979         source = backing_bs(bs);
2980         if (!source) {
2981             sync = MIRROR_SYNC_MODE_FULL;
2982         }
2983     }
2984     if (sync == MIRROR_SYNC_MODE_NONE) {
2985         source = bs;
2986     }
2987
2988     size = bdrv_getlength(bs);
2989     if (size < 0) {
2990         error_setg_errno(errp, -size, "bdrv_getlength failed");
2991         goto out;
2992     }
2993
2994     if (mode != NEW_IMAGE_MODE_EXISTING) {
2995         assert(format);
2996         if (source) {
2997             bdrv_img_create(target, format, source->filename,
2998                             source->drv->format_name, NULL,
2999                             size, flags, &local_err, false);
3000         } else {
3001             bdrv_img_create(target, format, NULL, NULL, NULL,
3002                             size, flags, &local_err, false);
3003         }
3004     }
3005
3006     if (local_err) {
3007         error_propagate(errp, local_err);
3008         goto out;
3009     }
3010
3011     if (format) {
3012         options = qdict_new();
3013         qdict_put(options, "driver", qstring_from_str(format));
3014     }
3015
3016     target_bs = NULL;
3017     ret = bdrv_open(&target_bs, target, NULL, options, flags, &local_err);
3018     if (ret < 0) {
3019         error_propagate(errp, local_err);
3020         goto out;
3021     }
3022
3023     bdrv_set_aio_context(target_bs, aio_context);
3024
3025     if (has_bitmap) {
3026         bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3027         if (!bmap) {
3028             error_setg(errp, "Bitmap '%s' could not be found", bitmap);
3029             goto out;
3030         }
3031     }
3032
3033     backup_start(bs, target_bs, speed, sync, bmap,
3034                  on_source_error, on_target_error,
3035                  block_job_cb, bs, &local_err);
3036     if (local_err != NULL) {
3037         bdrv_unref(target_bs);
3038         error_propagate(errp, local_err);
3039         goto out;
3040     }
3041
3042 out:
3043     aio_context_release(aio_context);
3044 }
3045
3046 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3047 {
3048     return bdrv_named_nodes_list(errp);
3049 }
3050
3051 void qmp_blockdev_backup(const char *device, const char *target,
3052                          enum MirrorSyncMode sync,
3053                          bool has_speed, int64_t speed,
3054                          bool has_on_source_error,
3055                          BlockdevOnError on_source_error,
3056                          bool has_on_target_error,
3057                          BlockdevOnError on_target_error,
3058                          Error **errp)
3059 {
3060     BlockBackend *blk, *target_blk;
3061     BlockDriverState *bs;
3062     BlockDriverState *target_bs;
3063     Error *local_err = NULL;
3064     AioContext *aio_context;
3065
3066     if (!has_speed) {
3067         speed = 0;
3068     }
3069     if (!has_on_source_error) {
3070         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3071     }
3072     if (!has_on_target_error) {
3073         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3074     }
3075
3076     blk = blk_by_name(device);
3077     if (!blk) {
3078         error_setg(errp, "Device '%s' not found", device);
3079         return;
3080     }
3081
3082     aio_context = blk_get_aio_context(blk);
3083     aio_context_acquire(aio_context);
3084
3085     if (!blk_is_available(blk)) {
3086         error_setg(errp, "Device '%s' has no medium", device);
3087         goto out;
3088     }
3089     bs = blk_bs(blk);
3090
3091     target_blk = blk_by_name(target);
3092     if (!target_blk) {
3093         error_setg(errp, "Device '%s' not found", target);
3094         goto out;
3095     }
3096
3097     if (!blk_is_available(target_blk)) {
3098         error_setg(errp, "Device '%s' has no medium", target);
3099         goto out;
3100     }
3101     target_bs = blk_bs(target_blk);
3102
3103     bdrv_ref(target_bs);
3104     bdrv_set_aio_context(target_bs, aio_context);
3105     backup_start(bs, target_bs, speed, sync, NULL, on_source_error,
3106                  on_target_error, block_job_cb, bs, &local_err);
3107     if (local_err != NULL) {
3108         bdrv_unref(target_bs);
3109         error_propagate(errp, local_err);
3110     }
3111 out:
3112     aio_context_release(aio_context);
3113 }
3114
3115 void qmp_drive_mirror(const char *device, const char *target,
3116                       bool has_format, const char *format,
3117                       bool has_node_name, const char *node_name,
3118                       bool has_replaces, const char *replaces,
3119                       enum MirrorSyncMode sync,
3120                       bool has_mode, enum NewImageMode mode,
3121                       bool has_speed, int64_t speed,
3122                       bool has_granularity, uint32_t granularity,
3123                       bool has_buf_size, int64_t buf_size,
3124                       bool has_on_source_error, BlockdevOnError on_source_error,
3125                       bool has_on_target_error, BlockdevOnError on_target_error,
3126                       bool has_unmap, bool unmap,
3127                       Error **errp)
3128 {
3129     BlockBackend *blk;
3130     BlockDriverState *bs;
3131     BlockDriverState *source, *target_bs;
3132     AioContext *aio_context;
3133     Error *local_err = NULL;
3134     QDict *options;
3135     int flags;
3136     int64_t size;
3137     int ret;
3138
3139     if (!has_speed) {
3140         speed = 0;
3141     }
3142     if (!has_on_source_error) {
3143         on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3144     }
3145     if (!has_on_target_error) {
3146         on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3147     }
3148     if (!has_mode) {
3149         mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3150     }
3151     if (!has_granularity) {
3152         granularity = 0;
3153     }
3154     if (!has_buf_size) {
3155         buf_size = 0;
3156     }
3157     if (!has_unmap) {
3158         unmap = true;
3159     }
3160
3161     if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3162         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3163                    "a value in range [512B, 64MB]");
3164         return;
3165     }
3166     if (granularity & (granularity - 1)) {
3167         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3168                    "power of 2");
3169         return;
3170     }
3171
3172     blk = blk_by_name(device);
3173     if (!blk) {
3174         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3175                   "Device '%s' not found", device);
3176         return;
3177     }
3178
3179     aio_context = blk_get_aio_context(blk);
3180     aio_context_acquire(aio_context);
3181
3182     if (!blk_is_available(blk)) {
3183         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
3184         goto out;
3185     }
3186     bs = blk_bs(blk);
3187
3188     if (!has_format) {
3189         format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3190     }
3191
3192     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
3193         goto out;
3194     }
3195
3196     flags = bs->open_flags | BDRV_O_RDWR;
3197     source = backing_bs(bs);
3198     if (!source && sync == MIRROR_SYNC_MODE_TOP) {
3199         sync = MIRROR_SYNC_MODE_FULL;
3200     }
3201     if (sync == MIRROR_SYNC_MODE_NONE) {
3202         source = bs;
3203     }
3204
3205     size = bdrv_getlength(bs);
3206     if (size < 0) {
3207         error_setg_errno(errp, -size, "bdrv_getlength failed");
3208         goto out;
3209     }
3210
3211     if (has_replaces) {
3212         BlockDriverState *to_replace_bs;
3213         AioContext *replace_aio_context;
3214         int64_t replace_size;
3215
3216         if (!has_node_name) {
3217             error_setg(errp, "a node-name must be provided when replacing a"
3218                              " named node of the graph");
3219             goto out;
3220         }
3221
3222         to_replace_bs = check_to_replace_node(bs, replaces, &local_err);
3223
3224         if (!to_replace_bs) {
3225             error_propagate(errp, local_err);
3226             goto out;
3227         }
3228
3229         replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3230         aio_context_acquire(replace_aio_context);
3231         replace_size = bdrv_getlength(to_replace_bs);
3232         aio_context_release(replace_aio_context);
3233
3234         if (size != replace_size) {
3235             error_setg(errp, "cannot replace image with a mirror image of "
3236                              "different size");
3237             goto out;
3238         }
3239     }
3240
3241     if ((sync == MIRROR_SYNC_MODE_FULL || !source)
3242         && mode != NEW_IMAGE_MODE_EXISTING)
3243     {
3244         /* create new image w/o backing file */
3245         assert(format);
3246         bdrv_img_create(target, format,
3247                         NULL, NULL, NULL, size, flags, &local_err, false);
3248     } else {
3249         switch (mode) {
3250         case NEW_IMAGE_MODE_EXISTING:
3251             break;
3252         case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3253             /* create new image with backing file */
3254             bdrv_img_create(target, format,
3255                             source->filename,
3256                             source->drv->format_name,
3257                             NULL, size, flags, &local_err, false);
3258             break;
3259         default:
3260             abort();
3261         }
3262     }
3263
3264     if (local_err) {
3265         error_propagate(errp, local_err);
3266         goto out;
3267     }
3268
3269     options = qdict_new();
3270     if (has_node_name) {
3271         qdict_put(options, "node-name", qstring_from_str(node_name));
3272     }
3273     if (format) {
3274         qdict_put(options, "driver", qstring_from_str(format));
3275     }
3276
3277     /* Mirroring takes care of copy-on-write using the source's backing
3278      * file.
3279      */
3280     target_bs = NULL;
3281     ret = bdrv_open(&target_bs, target, NULL, options,
3282                     flags | BDRV_O_NO_BACKING, &local_err);
3283     if (ret < 0) {
3284         error_propagate(errp, local_err);
3285         goto out;
3286     }
3287
3288     bdrv_set_aio_context(target_bs, aio_context);
3289
3290     /* pass the node name to replace to mirror start since it's loose coupling
3291      * and will allow to check whether the node still exist at mirror completion
3292      */
3293     mirror_start(bs, target_bs,
3294                  has_replaces ? replaces : NULL,
3295                  speed, granularity, buf_size, sync,
3296                  on_source_error, on_target_error,
3297                  unmap,
3298                  block_job_cb, bs, &local_err);
3299     if (local_err != NULL) {
3300         bdrv_unref(target_bs);
3301         error_propagate(errp, local_err);
3302         goto out;
3303     }
3304
3305 out:
3306     aio_context_release(aio_context);
3307 }
3308
3309 /* Get the block job for a given device name and acquire its AioContext */
3310 static BlockJob *find_block_job(const char *device, AioContext **aio_context,
3311                                 Error **errp)
3312 {
3313     BlockBackend *blk;
3314     BlockDriverState *bs;
3315
3316     *aio_context = NULL;
3317
3318     blk = blk_by_name(device);
3319     if (!blk) {
3320         goto notfound;
3321     }
3322
3323     *aio_context = blk_get_aio_context(blk);
3324     aio_context_acquire(*aio_context);
3325
3326     if (!blk_is_available(blk)) {
3327         goto notfound;
3328     }
3329     bs = blk_bs(blk);
3330
3331     if (!bs->job) {
3332         goto notfound;
3333     }
3334
3335     return bs->job;
3336
3337 notfound:
3338     error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3339               "No active block job on device '%s'", device);
3340     if (*aio_context) {
3341         aio_context_release(*aio_context);
3342         *aio_context = NULL;
3343     }
3344     return NULL;
3345 }
3346
3347 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
3348 {
3349     AioContext *aio_context;
3350     BlockJob *job = find_block_job(device, &aio_context, errp);
3351
3352     if (!job) {
3353         return;
3354     }
3355
3356     block_job_set_speed(job, speed, errp);
3357     aio_context_release(aio_context);
3358 }
3359
3360 void qmp_block_job_cancel(const char *device,
3361                           bool has_force, bool force, Error **errp)
3362 {
3363     AioContext *aio_context;
3364     BlockJob *job = find_block_job(device, &aio_context, errp);
3365
3366     if (!job) {
3367         return;
3368     }
3369
3370     if (!has_force) {
3371         force = false;
3372     }
3373
3374     if (job->user_paused && !force) {
3375         error_setg(errp, "The block job for device '%s' is currently paused",
3376                    device);
3377         goto out;
3378     }
3379
3380     trace_qmp_block_job_cancel(job);
3381     block_job_cancel(job);
3382 out:
3383     aio_context_release(aio_context);
3384 }
3385
3386 void qmp_block_job_pause(const char *device, Error **errp)
3387 {
3388     AioContext *aio_context;
3389     BlockJob *job = find_block_job(device, &aio_context, errp);
3390
3391     if (!job || job->user_paused) {
3392         return;
3393     }
3394
3395     job->user_paused = true;
3396     trace_qmp_block_job_pause(job);
3397     block_job_pause(job);
3398     aio_context_release(aio_context);
3399 }
3400
3401 void qmp_block_job_resume(const char *device, Error **errp)
3402 {
3403     AioContext *aio_context;
3404     BlockJob *job = find_block_job(device, &aio_context, errp);
3405
3406     if (!job || !job->user_paused) {
3407         return;
3408     }
3409
3410     job->user_paused = false;
3411     trace_qmp_block_job_resume(job);
3412     block_job_resume(job);
3413     aio_context_release(aio_context);
3414 }
3415
3416 void qmp_block_job_complete(const char *device, Error **errp)
3417 {
3418     AioContext *aio_context;
3419     BlockJob *job = find_block_job(device, &aio_context, errp);
3420
3421     if (!job) {
3422         return;
3423     }
3424
3425     trace_qmp_block_job_complete(job);
3426     block_job_complete(job, errp);
3427     aio_context_release(aio_context);
3428 }
3429
3430 void qmp_change_backing_file(const char *device,
3431                              const char *image_node_name,
3432                              const char *backing_file,
3433                              Error **errp)
3434 {
3435     BlockBackend *blk;
3436     BlockDriverState *bs = NULL;
3437     AioContext *aio_context;
3438     BlockDriverState *image_bs = NULL;
3439     Error *local_err = NULL;
3440     bool ro;
3441     int open_flags;
3442     int ret;
3443
3444     blk = blk_by_name(device);
3445     if (!blk) {
3446         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3447                   "Device '%s' not found", device);
3448         return;
3449     }
3450
3451     aio_context = blk_get_aio_context(blk);
3452     aio_context_acquire(aio_context);
3453
3454     if (!blk_is_available(blk)) {
3455         error_setg(errp, "Device '%s' has no medium", device);
3456         goto out;
3457     }
3458     bs = blk_bs(blk);
3459
3460     image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3461     if (local_err) {
3462         error_propagate(errp, local_err);
3463         goto out;
3464     }
3465
3466     if (!image_bs) {
3467         error_setg(errp, "image file not found");
3468         goto out;
3469     }
3470
3471     if (bdrv_find_base(image_bs) == image_bs) {
3472         error_setg(errp, "not allowing backing file change on an image "
3473                          "without a backing file");
3474         goto out;
3475     }
3476
3477     /* even though we are not necessarily operating on bs, we need it to
3478      * determine if block ops are currently prohibited on the chain */
3479     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
3480         goto out;
3481     }
3482
3483     /* final sanity check */
3484     if (!bdrv_chain_contains(bs, image_bs)) {
3485         error_setg(errp, "'%s' and image file are not in the same chain",
3486                    device);
3487         goto out;
3488     }
3489
3490     /* if not r/w, reopen to make r/w */
3491     open_flags = image_bs->open_flags;
3492     ro = bdrv_is_read_only(image_bs);
3493
3494     if (ro) {
3495         bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3496         if (local_err) {
3497             error_propagate(errp, local_err);
3498             goto out;
3499         }
3500     }
3501
3502     ret = bdrv_change_backing_file(image_bs, backing_file,
3503                                image_bs->drv ? image_bs->drv->format_name : "");
3504
3505     if (ret < 0) {
3506         error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3507                          backing_file);
3508         /* don't exit here, so we can try to restore open flags if
3509          * appropriate */
3510     }
3511
3512     if (ro) {
3513         bdrv_reopen(image_bs, open_flags, &local_err);
3514         if (local_err) {
3515             error_propagate(errp, local_err); /* will preserve prior errp */
3516         }
3517     }
3518
3519 out:
3520     aio_context_release(aio_context);
3521 }
3522
3523 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3524 {
3525     QmpOutputVisitor *ov = qmp_output_visitor_new();
3526     BlockDriverState *bs;
3527     BlockBackend *blk = NULL;
3528     QObject *obj;
3529     QDict *qdict;
3530     Error *local_err = NULL;
3531
3532     /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
3533      * cache.direct=false instead of silently switching to aio=threads, except
3534      * when called from drive_new().
3535      *
3536      * For now, simply forbidding the combination for all drivers will do. */
3537     if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
3538         bool direct = options->has_cache &&
3539                       options->cache->has_direct &&
3540                       options->cache->direct;
3541         if (!direct) {
3542             error_setg(errp, "aio=native requires cache.direct=true");
3543             goto fail;
3544         }
3545     }
3546
3547     visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
3548                                &options, NULL, &local_err);
3549     if (local_err) {
3550         error_propagate(errp, local_err);
3551         goto fail;
3552     }
3553
3554     obj = qmp_output_get_qobject(ov);
3555     qdict = qobject_to_qdict(obj);
3556
3557     qdict_flatten(qdict);
3558
3559     if (options->has_id) {
3560         blk = blockdev_init(NULL, qdict, &local_err);
3561         if (local_err) {
3562             error_propagate(errp, local_err);
3563             goto fail;
3564         }
3565
3566         bs = blk_bs(blk);
3567     } else {
3568         if (!qdict_get_try_str(qdict, "node-name")) {
3569             error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3570                        "the root node");
3571             goto fail;
3572         }
3573
3574         bs = bds_tree_init(qdict, errp);
3575         if (!bs) {
3576             goto fail;
3577         }
3578     }
3579
3580     if (bs && bdrv_key_required(bs)) {
3581         if (blk) {
3582             blk_unref(blk);
3583         } else {
3584             bdrv_unref(bs);
3585         }
3586         error_setg(errp, "blockdev-add doesn't support encrypted devices");
3587         goto fail;
3588     }
3589
3590 fail:
3591     qmp_output_visitor_cleanup(ov);
3592 }
3593
3594 void qmp_x_blockdev_del(bool has_id, const char *id,
3595                         bool has_node_name, const char *node_name, Error **errp)
3596 {
3597     AioContext *aio_context;
3598     BlockBackend *blk;
3599     BlockDriverState *bs;
3600
3601     if (has_id && has_node_name) {
3602         error_setg(errp, "Only one of id and node-name must be specified");
3603         return;
3604     } else if (!has_id && !has_node_name) {
3605         error_setg(errp, "No block device specified");
3606         return;
3607     }
3608
3609     if (has_id) {
3610         blk = blk_by_name(id);
3611         if (!blk) {
3612             error_setg(errp, "Cannot find block backend %s", id);
3613             return;
3614         }
3615         if (blk_get_refcnt(blk) > 1) {
3616             error_setg(errp, "Block backend %s is in use", id);
3617             return;
3618         }
3619         bs = blk_bs(blk);
3620         aio_context = blk_get_aio_context(blk);
3621     } else {
3622         bs = bdrv_find_node(node_name);
3623         if (!bs) {
3624             error_setg(errp, "Cannot find node %s", node_name);
3625             return;
3626         }
3627         blk = bs->blk;
3628         if (blk) {
3629             error_setg(errp, "Node %s is in use by %s",
3630                        node_name, blk_name(blk));
3631             return;
3632         }
3633         aio_context = bdrv_get_aio_context(bs);
3634     }
3635
3636     aio_context_acquire(aio_context);
3637
3638     if (bs) {
3639         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
3640             goto out;
3641         }
3642
3643         if (bs->refcnt > 1 || !QLIST_EMPTY(&bs->parents)) {
3644             error_setg(errp, "Block device %s is in use",
3645                        bdrv_get_device_or_node_name(bs));
3646             goto out;
3647         }
3648     }
3649
3650     if (blk) {
3651         blk_unref(blk);
3652     } else {
3653         bdrv_unref(bs);
3654     }
3655
3656 out:
3657     aio_context_release(aio_context);
3658 }
3659
3660 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
3661 {
3662     BlockJobInfoList *head = NULL, **p_next = &head;
3663     BlockDriverState *bs;
3664
3665     for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
3666         AioContext *aio_context = bdrv_get_aio_context(bs);
3667
3668         aio_context_acquire(aio_context);
3669
3670         if (bs->job) {
3671             BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
3672             elem->value = block_job_query(bs->job);
3673             *p_next = elem;
3674             p_next = &elem->next;
3675         }
3676
3677         aio_context_release(aio_context);
3678     }
3679
3680     return head;
3681 }
3682
3683 QemuOptsList qemu_common_drive_opts = {
3684     .name = "drive",
3685     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3686     .desc = {
3687         {
3688             .name = "snapshot",
3689             .type = QEMU_OPT_BOOL,
3690             .help = "enable/disable snapshot mode",
3691         },{
3692             .name = "discard",
3693             .type = QEMU_OPT_STRING,
3694             .help = "discard operation (ignore/off, unmap/on)",
3695         },{
3696             .name = BDRV_OPT_CACHE_WB,
3697             .type = QEMU_OPT_BOOL,
3698             .help = "enables writeback mode for any caches",
3699         },{
3700             .name = BDRV_OPT_CACHE_DIRECT,
3701             .type = QEMU_OPT_BOOL,
3702             .help = "enables use of O_DIRECT (bypass the host page cache)",
3703         },{
3704             .name = BDRV_OPT_CACHE_NO_FLUSH,
3705             .type = QEMU_OPT_BOOL,
3706             .help = "ignore any flush requests for the device",
3707         },{
3708             .name = "aio",
3709             .type = QEMU_OPT_STRING,
3710             .help = "host AIO implementation (threads, native)",
3711         },{
3712             .name = "format",
3713             .type = QEMU_OPT_STRING,
3714             .help = "disk format (raw, qcow2, ...)",
3715         },{
3716             .name = "rerror",
3717             .type = QEMU_OPT_STRING,
3718             .help = "read error action",
3719         },{
3720             .name = "werror",
3721             .type = QEMU_OPT_STRING,
3722             .help = "write error action",
3723         },{
3724             .name = "read-only",
3725             .type = QEMU_OPT_BOOL,
3726             .help = "open drive file as read-only",
3727         },{
3728             .name = "throttling.iops-total",
3729             .type = QEMU_OPT_NUMBER,
3730             .help = "limit total I/O operations per second",
3731         },{
3732             .name = "throttling.iops-read",
3733             .type = QEMU_OPT_NUMBER,
3734             .help = "limit read operations per second",
3735         },{
3736             .name = "throttling.iops-write",
3737             .type = QEMU_OPT_NUMBER,
3738             .help = "limit write operations per second",
3739         },{
3740             .name = "throttling.bps-total",
3741             .type = QEMU_OPT_NUMBER,
3742             .help = "limit total bytes per second",
3743         },{
3744             .name = "throttling.bps-read",
3745             .type = QEMU_OPT_NUMBER,
3746             .help = "limit read bytes per second",
3747         },{
3748             .name = "throttling.bps-write",
3749             .type = QEMU_OPT_NUMBER,
3750             .help = "limit write bytes per second",
3751         },{
3752             .name = "throttling.iops-total-max",
3753             .type = QEMU_OPT_NUMBER,
3754             .help = "I/O operations burst",
3755         },{
3756             .name = "throttling.iops-read-max",
3757             .type = QEMU_OPT_NUMBER,
3758             .help = "I/O operations read burst",
3759         },{
3760             .name = "throttling.iops-write-max",
3761             .type = QEMU_OPT_NUMBER,
3762             .help = "I/O operations write burst",
3763         },{
3764             .name = "throttling.bps-total-max",
3765             .type = QEMU_OPT_NUMBER,
3766             .help = "total bytes burst",
3767         },{
3768             .name = "throttling.bps-read-max",
3769             .type = QEMU_OPT_NUMBER,
3770             .help = "total bytes read burst",
3771         },{
3772             .name = "throttling.bps-write-max",
3773             .type = QEMU_OPT_NUMBER,
3774             .help = "total bytes write burst",
3775         },{
3776             .name = "throttling.iops-size",
3777             .type = QEMU_OPT_NUMBER,
3778             .help = "when limiting by iops max size of an I/O in bytes",
3779         },{
3780             .name = "throttling.group",
3781             .type = QEMU_OPT_STRING,
3782             .help = "name of the block throttling group",
3783         },{
3784             .name = "copy-on-read",
3785             .type = QEMU_OPT_BOOL,
3786             .help = "copy read data from backing file into image file",
3787         },{
3788             .name = "detect-zeroes",
3789             .type = QEMU_OPT_STRING,
3790             .help = "try to optimize zero writes (off, on, unmap)",
3791         },
3792         { /* end of list */ }
3793     },
3794 };
3795
3796 static QemuOptsList qemu_root_bds_opts = {
3797     .name = "root-bds",
3798     .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
3799     .desc = {
3800         {
3801             .name = "discard",
3802             .type = QEMU_OPT_STRING,
3803             .help = "discard operation (ignore/off, unmap/on)",
3804         },{
3805             .name = "cache.writeback",
3806             .type = QEMU_OPT_BOOL,
3807             .help = "enables writeback mode for any caches",
3808         },{
3809             .name = "cache.direct",
3810             .type = QEMU_OPT_BOOL,
3811             .help = "enables use of O_DIRECT (bypass the host page cache)",
3812         },{
3813             .name = "cache.no-flush",
3814             .type = QEMU_OPT_BOOL,
3815             .help = "ignore any flush requests for the device",
3816         },{
3817             .name = "aio",
3818             .type = QEMU_OPT_STRING,
3819             .help = "host AIO implementation (threads, native)",
3820         },{
3821             .name = "read-only",
3822             .type = QEMU_OPT_BOOL,
3823             .help = "open drive file as read-only",
3824         },{
3825             .name = "copy-on-read",
3826             .type = QEMU_OPT_BOOL,
3827             .help = "copy read data from backing file into image file",
3828         },{
3829             .name = "detect-zeroes",
3830             .type = QEMU_OPT_STRING,
3831             .help = "try to optimize zero writes (off, on, unmap)",
3832         },
3833         { /* end of list */ }
3834     },
3835 };
3836
3837 QemuOptsList qemu_drive_opts = {
3838     .name = "drive",
3839     .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
3840     .desc = {
3841         /*
3842          * no elements => accept any params
3843          * validation will happen later
3844          */
3845         { /* end of list */ }
3846     },
3847 };
This page took 0.228665 seconds and 4 git commands to generate.