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