xref: /openbmc/qemu/block/monitor/block-hmp-cmds.c (revision e0c72452)
1 /*
2  * Blockdev HMP commands
3  *
4  *  Authors:
5  *  Anthony Liguori   <aliguori@us.ibm.com>
6  *
7  * Copyright (c) 2003-2008 Fabrice Bellard
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.
10  * See the COPYING file in the top-level directory.
11  * Contributions after 2012-01-13 are licensed under the terms of the
12  * GNU GPL, version 2 or (at your option) any later version.
13  *
14  * This file incorporates work covered by the following copyright and
15  * permission notice:
16  *
17  * Copyright (c) 2003-2008 Fabrice Bellard
18  *
19  * Permission is hereby granted, free of charge, to any person obtaining a copy
20  * of this software and associated documentation files (the "Software"), to deal
21  * in the Software without restriction, including without limitation the rights
22  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23  * copies of the Software, and to permit persons to whom the Software is
24  * furnished to do so, subject to the following conditions:
25  *
26  * The above copyright notice and this permission notice shall be included in
27  * all copies or substantial portions of the Software.
28  *
29  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
32  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35  * THE SOFTWARE.
36  */
37 
38 #include "qemu/osdep.h"
39 #include "hw/boards.h"
40 #include "sysemu/block-backend.h"
41 #include "sysemu/blockdev.h"
42 #include "qapi/qapi-commands-block.h"
43 #include "qapi/qapi-commands-block-export.h"
44 #include "qapi/qmp/qdict.h"
45 #include "qapi/error.h"
46 #include "qapi/qmp/qerror.h"
47 #include "qemu/config-file.h"
48 #include "qemu/option.h"
49 #include "qemu/sockets.h"
50 #include "qemu/cutils.h"
51 #include "qemu/error-report.h"
52 #include "sysemu/sysemu.h"
53 #include "monitor/monitor.h"
54 #include "monitor/hmp.h"
55 #include "block/nbd.h"
56 #include "block/qapi.h"
57 #include "block/block_int.h"
58 #include "block/block-hmp-cmds.h"
59 #include "qemu-io.h"
60 
61 static void hmp_drive_add_node(Monitor *mon, const char *optstr)
62 {
63     QemuOpts *opts;
64     QDict *qdict;
65     Error *local_err = NULL;
66 
67     opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
68     if (!opts) {
69         return;
70     }
71 
72     qdict = qemu_opts_to_qdict(opts, NULL);
73 
74     if (!qdict_get_try_str(qdict, "node-name")) {
75         qobject_unref(qdict);
76         error_report("'node-name' needs to be specified");
77         goto out;
78     }
79 
80     BlockDriverState *bs = bds_tree_init(qdict, &local_err);
81     if (!bs) {
82         error_report_err(local_err);
83         goto out;
84     }
85 
86     bdrv_set_monitor_owned(bs);
87 out:
88     qemu_opts_del(opts);
89 }
90 
91 void hmp_drive_add(Monitor *mon, const QDict *qdict)
92 {
93     Error *err = NULL;
94     DriveInfo *dinfo;
95     QemuOpts *opts;
96     MachineClass *mc;
97     const char *optstr = qdict_get_str(qdict, "opts");
98     bool node = qdict_get_try_bool(qdict, "node", false);
99 
100     if (node) {
101         hmp_drive_add_node(mon, optstr);
102         return;
103     }
104 
105     opts = qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
106     if (!opts)
107         return;
108 
109     mc = MACHINE_GET_CLASS(current_machine);
110     dinfo = drive_new(opts, mc->block_default_type, &err);
111     if (err) {
112         error_report_err(err);
113         qemu_opts_del(opts);
114         goto err;
115     }
116 
117     if (!dinfo) {
118         return;
119     }
120 
121     switch (dinfo->type) {
122     case IF_NONE:
123         monitor_printf(mon, "OK\n");
124         break;
125     default:
126         monitor_printf(mon, "Can't hot-add drive to type %d\n", dinfo->type);
127         goto err;
128     }
129     return;
130 
131 err:
132     if (dinfo) {
133         BlockBackend *blk = blk_by_legacy_dinfo(dinfo);
134         monitor_remove_blk(blk);
135         blk_unref(blk);
136     }
137 }
138 
139 void hmp_drive_del(Monitor *mon, const QDict *qdict)
140 {
141     const char *id = qdict_get_str(qdict, "id");
142     BlockBackend *blk;
143     BlockDriverState *bs;
144     AioContext *aio_context;
145     Error *local_err = NULL;
146 
147     GLOBAL_STATE_CODE();
148     GRAPH_RDLOCK_GUARD_MAINLOOP();
149 
150     bs = bdrv_find_node(id);
151     if (bs) {
152         qmp_blockdev_del(id, &local_err);
153         if (local_err) {
154             error_report_err(local_err);
155         }
156         return;
157     }
158 
159     blk = blk_by_name(id);
160     if (!blk) {
161         error_report("Device '%s' not found", id);
162         return;
163     }
164 
165     if (!blk_legacy_dinfo(blk)) {
166         error_report("Deleting device added with blockdev-add"
167                      " is not supported");
168         return;
169     }
170 
171     aio_context = blk_get_aio_context(blk);
172     aio_context_acquire(aio_context);
173 
174     bs = blk_bs(blk);
175     if (bs) {
176         if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
177             error_report_err(local_err);
178             aio_context_release(aio_context);
179             return;
180         }
181 
182         blk_remove_bs(blk);
183     }
184 
185     /* Make the BlockBackend and the attached BlockDriverState anonymous */
186     monitor_remove_blk(blk);
187 
188     /*
189      * If this BlockBackend has a device attached to it, its refcount will be
190      * decremented when the device is removed; otherwise we have to do so here.
191      */
192     if (blk_get_attached_dev(blk)) {
193         /* Further I/O must not pause the guest */
194         blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
195                          BLOCKDEV_ON_ERROR_REPORT);
196     } else {
197         blk_unref(blk);
198     }
199 
200     aio_context_release(aio_context);
201 }
202 
203 void hmp_commit(Monitor *mon, const QDict *qdict)
204 {
205     const char *device = qdict_get_str(qdict, "device");
206     BlockBackend *blk;
207     int ret;
208 
209     if (!strcmp(device, "all")) {
210         ret = blk_commit_all();
211     } else {
212         BlockDriverState *bs;
213         AioContext *aio_context;
214 
215         blk = blk_by_name(device);
216         if (!blk) {
217             error_report("Device '%s' not found", device);
218             return;
219         }
220 
221         bs = bdrv_skip_implicit_filters(blk_bs(blk));
222         aio_context = bdrv_get_aio_context(bs);
223         aio_context_acquire(aio_context);
224 
225         if (!blk_is_available(blk)) {
226             error_report("Device '%s' has no medium", device);
227             aio_context_release(aio_context);
228             return;
229         }
230 
231         ret = bdrv_commit(bs);
232 
233         aio_context_release(aio_context);
234     }
235     if (ret < 0) {
236         error_report("'commit' error for '%s': %s", device, strerror(-ret));
237     }
238 }
239 
240 void hmp_drive_mirror(Monitor *mon, const QDict *qdict)
241 {
242     const char *filename = qdict_get_str(qdict, "target");
243     const char *format = qdict_get_try_str(qdict, "format");
244     bool reuse = qdict_get_try_bool(qdict, "reuse", false);
245     bool full = qdict_get_try_bool(qdict, "full", false);
246     Error *err = NULL;
247     DriveMirror mirror = {
248         .device = (char *)qdict_get_str(qdict, "device"),
249         .target = (char *)filename,
250         .format = (char *)format,
251         .sync = full ? MIRROR_SYNC_MODE_FULL : MIRROR_SYNC_MODE_TOP,
252         .has_mode = true,
253         .mode = reuse ? NEW_IMAGE_MODE_EXISTING : NEW_IMAGE_MODE_ABSOLUTE_PATHS,
254         .unmap = true,
255     };
256 
257     if (!filename) {
258         error_setg(&err, QERR_MISSING_PARAMETER, "target");
259         goto end;
260     }
261     qmp_drive_mirror(&mirror, &err);
262 end:
263     hmp_handle_error(mon, err);
264 }
265 
266 void hmp_drive_backup(Monitor *mon, const QDict *qdict)
267 {
268     const char *device = qdict_get_str(qdict, "device");
269     const char *filename = qdict_get_str(qdict, "target");
270     const char *format = qdict_get_try_str(qdict, "format");
271     bool reuse = qdict_get_try_bool(qdict, "reuse", false);
272     bool full = qdict_get_try_bool(qdict, "full", false);
273     bool compress = qdict_get_try_bool(qdict, "compress", false);
274     Error *err = NULL;
275     DriveBackup backup = {
276         .device = (char *)device,
277         .target = (char *)filename,
278         .format = (char *)format,
279         .sync = full ? MIRROR_SYNC_MODE_FULL : MIRROR_SYNC_MODE_TOP,
280         .has_mode = true,
281         .mode = reuse ? NEW_IMAGE_MODE_EXISTING : NEW_IMAGE_MODE_ABSOLUTE_PATHS,
282         .has_compress = !!compress,
283         .compress = compress,
284     };
285 
286     if (!filename) {
287         error_setg(&err, QERR_MISSING_PARAMETER, "target");
288         goto end;
289     }
290 
291     qmp_drive_backup(&backup, &err);
292 end:
293     hmp_handle_error(mon, err);
294 }
295 
296 void hmp_block_job_set_speed(Monitor *mon, const QDict *qdict)
297 {
298     Error *error = NULL;
299     const char *device = qdict_get_str(qdict, "device");
300     int64_t value = qdict_get_int(qdict, "speed");
301 
302     qmp_block_job_set_speed(device, value, &error);
303 
304     hmp_handle_error(mon, error);
305 }
306 
307 void hmp_block_job_cancel(Monitor *mon, const QDict *qdict)
308 {
309     Error *error = NULL;
310     const char *device = qdict_get_str(qdict, "device");
311     bool force = qdict_get_try_bool(qdict, "force", false);
312 
313     qmp_block_job_cancel(device, true, force, &error);
314 
315     hmp_handle_error(mon, error);
316 }
317 
318 void hmp_block_job_pause(Monitor *mon, const QDict *qdict)
319 {
320     Error *error = NULL;
321     const char *device = qdict_get_str(qdict, "device");
322 
323     qmp_block_job_pause(device, &error);
324 
325     hmp_handle_error(mon, error);
326 }
327 
328 void hmp_block_job_resume(Monitor *mon, const QDict *qdict)
329 {
330     Error *error = NULL;
331     const char *device = qdict_get_str(qdict, "device");
332 
333     qmp_block_job_resume(device, &error);
334 
335     hmp_handle_error(mon, error);
336 }
337 
338 void hmp_block_job_complete(Monitor *mon, const QDict *qdict)
339 {
340     Error *error = NULL;
341     const char *device = qdict_get_str(qdict, "device");
342 
343     qmp_block_job_complete(device, &error);
344 
345     hmp_handle_error(mon, error);
346 }
347 
348 void hmp_snapshot_blkdev(Monitor *mon, const QDict *qdict)
349 {
350     const char *device = qdict_get_str(qdict, "device");
351     const char *filename = qdict_get_try_str(qdict, "snapshot-file");
352     const char *format = qdict_get_try_str(qdict, "format");
353     bool reuse = qdict_get_try_bool(qdict, "reuse", false);
354     enum NewImageMode mode;
355     Error *err = NULL;
356 
357     if (!filename) {
358         /*
359          * In the future, if 'snapshot-file' is not specified, the snapshot
360          * will be taken internally. Today it's actually required.
361          */
362         error_setg(&err, QERR_MISSING_PARAMETER, "snapshot-file");
363         goto end;
364     }
365 
366     mode = reuse ? NEW_IMAGE_MODE_EXISTING : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
367     qmp_blockdev_snapshot_sync(device, NULL, filename, NULL, format,
368                                true, mode, &err);
369 end:
370     hmp_handle_error(mon, err);
371 }
372 
373 void hmp_snapshot_blkdev_internal(Monitor *mon, const QDict *qdict)
374 {
375     const char *device = qdict_get_str(qdict, "device");
376     const char *name = qdict_get_str(qdict, "name");
377     Error *err = NULL;
378 
379     qmp_blockdev_snapshot_internal_sync(device, name, &err);
380     hmp_handle_error(mon, err);
381 }
382 
383 void hmp_snapshot_delete_blkdev_internal(Monitor *mon, const QDict *qdict)
384 {
385     const char *device = qdict_get_str(qdict, "device");
386     const char *name = qdict_get_str(qdict, "name");
387     const char *id = qdict_get_try_str(qdict, "id");
388     Error *err = NULL;
389 
390     qmp_blockdev_snapshot_delete_internal_sync(device, id, name, &err);
391     hmp_handle_error(mon, err);
392 }
393 
394 void hmp_nbd_server_start(Monitor *mon, const QDict *qdict)
395 {
396     const char *uri = qdict_get_str(qdict, "uri");
397     bool writable = qdict_get_try_bool(qdict, "writable", false);
398     bool all = qdict_get_try_bool(qdict, "all", false);
399     Error *local_err = NULL;
400     BlockInfoList *block_list, *info;
401     SocketAddress *addr;
402     NbdServerAddOptions export;
403 
404     if (writable && !all) {
405         error_setg(&local_err, "-w only valid together with -a");
406         goto exit;
407     }
408 
409     /* First check if the address is valid and start the server.  */
410     addr = socket_parse(uri, &local_err);
411     if (local_err != NULL) {
412         goto exit;
413     }
414 
415     nbd_server_start(addr, NULL, NULL, 0, &local_err);
416     qapi_free_SocketAddress(addr);
417     if (local_err != NULL) {
418         goto exit;
419     }
420 
421     if (!all) {
422         return;
423     }
424 
425     /* Then try adding all block devices.  If one fails, close all and
426      * exit.
427      */
428     block_list = qmp_query_block(NULL);
429 
430     for (info = block_list; info; info = info->next) {
431         if (!info->value->inserted) {
432             continue;
433         }
434 
435         export = (NbdServerAddOptions) {
436             .device         = info->value->device,
437             .has_writable   = true,
438             .writable       = writable,
439         };
440 
441         qmp_nbd_server_add(&export, &local_err);
442 
443         if (local_err != NULL) {
444             qmp_nbd_server_stop(NULL);
445             break;
446         }
447     }
448 
449     qapi_free_BlockInfoList(block_list);
450 
451 exit:
452     hmp_handle_error(mon, local_err);
453 }
454 
455 void hmp_nbd_server_add(Monitor *mon, const QDict *qdict)
456 {
457     const char *device = qdict_get_str(qdict, "device");
458     const char *name = qdict_get_try_str(qdict, "name");
459     bool writable = qdict_get_try_bool(qdict, "writable", false);
460     Error *local_err = NULL;
461 
462     NbdServerAddOptions export = {
463         .device         = (char *) device,
464         .name           = (char *) name,
465         .has_writable   = true,
466         .writable       = writable,
467     };
468 
469     qmp_nbd_server_add(&export, &local_err);
470     hmp_handle_error(mon, local_err);
471 }
472 
473 void hmp_nbd_server_remove(Monitor *mon, const QDict *qdict)
474 {
475     const char *name = qdict_get_str(qdict, "name");
476     bool force = qdict_get_try_bool(qdict, "force", false);
477     Error *err = NULL;
478 
479     /* Rely on BLOCK_EXPORT_REMOVE_MODE_SAFE being the default */
480     qmp_nbd_server_remove(name, force, BLOCK_EXPORT_REMOVE_MODE_HARD, &err);
481     hmp_handle_error(mon, err);
482 }
483 
484 void hmp_nbd_server_stop(Monitor *mon, const QDict *qdict)
485 {
486     Error *err = NULL;
487 
488     qmp_nbd_server_stop(&err);
489     hmp_handle_error(mon, err);
490 }
491 
492 void coroutine_fn hmp_block_resize(Monitor *mon, const QDict *qdict)
493 {
494     const char *device = qdict_get_str(qdict, "device");
495     int64_t size = qdict_get_int(qdict, "size");
496     Error *err = NULL;
497 
498     qmp_block_resize(device, NULL, size, &err);
499     hmp_handle_error(mon, err);
500 }
501 
502 void hmp_block_stream(Monitor *mon, const QDict *qdict)
503 {
504     Error *error = NULL;
505     const char *device = qdict_get_str(qdict, "device");
506     const char *base = qdict_get_try_str(qdict, "base");
507     int64_t speed = qdict_get_try_int(qdict, "speed", 0);
508 
509     qmp_block_stream(device, device, base, NULL, NULL, NULL,
510                      qdict_haskey(qdict, "speed"), speed,
511                      true, BLOCKDEV_ON_ERROR_REPORT, NULL,
512                      false, false, false, false, &error);
513 
514     hmp_handle_error(mon, error);
515 }
516 
517 void hmp_block_set_io_throttle(Monitor *mon, const QDict *qdict)
518 {
519     Error *err = NULL;
520     char *device = (char *) qdict_get_str(qdict, "device");
521     BlockIOThrottle throttle = {
522         .bps = qdict_get_int(qdict, "bps"),
523         .bps_rd = qdict_get_int(qdict, "bps_rd"),
524         .bps_wr = qdict_get_int(qdict, "bps_wr"),
525         .iops = qdict_get_int(qdict, "iops"),
526         .iops_rd = qdict_get_int(qdict, "iops_rd"),
527         .iops_wr = qdict_get_int(qdict, "iops_wr"),
528     };
529 
530     /*
531      * qmp_block_set_io_throttle has separate parameters for the
532      * (deprecated) block device name and the qdev ID but the HMP
533      * version has only one, so we must decide which one to pass.
534      */
535     if (blk_by_name(device)) {
536         throttle.device = device;
537     } else {
538         throttle.id = device;
539     }
540 
541     qmp_block_set_io_throttle(&throttle, &err);
542     hmp_handle_error(mon, err);
543 }
544 
545 void hmp_eject(Monitor *mon, const QDict *qdict)
546 {
547     bool force = qdict_get_try_bool(qdict, "force", false);
548     const char *device = qdict_get_str(qdict, "device");
549     Error *err = NULL;
550 
551     qmp_eject(device, NULL, true, force, &err);
552     hmp_handle_error(mon, err);
553 }
554 
555 void hmp_qemu_io(Monitor *mon, const QDict *qdict)
556 {
557     BlockBackend *blk = NULL;
558     BlockDriverState *bs = NULL;
559     BlockBackend *local_blk = NULL;
560     AioContext *ctx = NULL;
561     bool qdev = qdict_get_try_bool(qdict, "qdev", false);
562     const char *device = qdict_get_str(qdict, "device");
563     const char *command = qdict_get_str(qdict, "command");
564     Error *err = NULL;
565     int ret;
566 
567     if (qdev) {
568         blk = blk_by_qdev_id(device, &err);
569         if (!blk) {
570             goto fail;
571         }
572     } else {
573         blk = blk_by_name(device);
574         if (!blk) {
575             bs = bdrv_lookup_bs(NULL, device, &err);
576             if (!bs) {
577                 goto fail;
578             }
579         }
580     }
581 
582     ctx = blk ? blk_get_aio_context(blk) : bdrv_get_aio_context(bs);
583     aio_context_acquire(ctx);
584 
585     if (bs) {
586         blk = local_blk = blk_new(bdrv_get_aio_context(bs), 0, BLK_PERM_ALL);
587         ret = blk_insert_bs(blk, bs, &err);
588         if (ret < 0) {
589             goto fail;
590         }
591     }
592 
593     /*
594      * Notably absent: Proper permission management. This is sad, but it seems
595      * almost impossible to achieve without changing the semantics and thereby
596      * limiting the use cases of the qemu-io HMP command.
597      *
598      * In an ideal world we would unconditionally create a new BlockBackend for
599      * qemuio_command(), but we have commands like 'reopen' and want them to
600      * take effect on the exact BlockBackend whose name the user passed instead
601      * of just on a temporary copy of it.
602      *
603      * Another problem is that deleting the temporary BlockBackend involves
604      * draining all requests on it first, but some qemu-iotests cases want to
605      * issue multiple aio_read/write requests and expect them to complete in
606      * the background while the monitor has already returned.
607      *
608      * This is also what prevents us from saving the original permissions and
609      * restoring them later: We can't revoke permissions until all requests
610      * have completed, and we don't know when that is nor can we really let
611      * anything else run before we have revoken them to avoid race conditions.
612      *
613      * What happens now is that command() in qemu-io-cmds.c can extend the
614      * permissions if necessary for the qemu-io command. And they simply stay
615      * extended, possibly resulting in a read-only guest device keeping write
616      * permissions. Ugly, but it appears to be the lesser evil.
617      */
618     qemuio_command(blk, command);
619 
620 fail:
621     blk_unref(local_blk);
622 
623     if (ctx) {
624         aio_context_release(ctx);
625     }
626 
627     hmp_handle_error(mon, err);
628 }
629 
630 static void print_block_info(Monitor *mon, BlockInfo *info,
631                              BlockDeviceInfo *inserted, bool verbose)
632 {
633     ImageInfo *image_info;
634 
635     assert(!info || !info->inserted || info->inserted == inserted);
636 
637     if (info && *info->device) {
638         monitor_puts(mon, info->device);
639         if (inserted && inserted->node_name) {
640             monitor_printf(mon, " (%s)", inserted->node_name);
641         }
642     } else {
643         assert(info || inserted);
644         monitor_puts(mon,
645                      inserted && inserted->node_name ? inserted->node_name
646                      : info && info->qdev ? info->qdev
647                      : "<anonymous>");
648     }
649 
650     if (inserted) {
651         monitor_printf(mon, ": %s (%s%s%s)\n",
652                        inserted->file,
653                        inserted->drv,
654                        inserted->ro ? ", read-only" : "",
655                        inserted->encrypted ? ", encrypted" : "");
656     } else {
657         monitor_printf(mon, ": [not inserted]\n");
658     }
659 
660     if (info) {
661         if (info->qdev) {
662             monitor_printf(mon, "    Attached to:      %s\n", info->qdev);
663         }
664         if (info->has_io_status && info->io_status != BLOCK_DEVICE_IO_STATUS_OK) {
665             monitor_printf(mon, "    I/O status:       %s\n",
666                            BlockDeviceIoStatus_str(info->io_status));
667         }
668 
669         if (info->removable) {
670             monitor_printf(mon, "    Removable device: %slocked, tray %s\n",
671                            info->locked ? "" : "not ",
672                            info->tray_open ? "open" : "closed");
673         }
674     }
675 
676 
677     if (!inserted) {
678         return;
679     }
680 
681     monitor_printf(mon, "    Cache mode:       %s%s%s\n",
682                    inserted->cache->writeback ? "writeback" : "writethrough",
683                    inserted->cache->direct ? ", direct" : "",
684                    inserted->cache->no_flush ? ", ignore flushes" : "");
685 
686     if (inserted->backing_file) {
687         monitor_printf(mon,
688                        "    Backing file:     %s "
689                        "(chain depth: %" PRId64 ")\n",
690                        inserted->backing_file,
691                        inserted->backing_file_depth);
692     }
693 
694     if (inserted->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF) {
695         monitor_printf(mon, "    Detect zeroes:    %s\n",
696                 BlockdevDetectZeroesOptions_str(inserted->detect_zeroes));
697     }
698 
699     if (inserted->bps  || inserted->bps_rd  || inserted->bps_wr  ||
700         inserted->iops || inserted->iops_rd || inserted->iops_wr)
701     {
702         monitor_printf(mon, "    I/O throttling:   bps=%" PRId64
703                         " bps_rd=%" PRId64  " bps_wr=%" PRId64
704                         " bps_max=%" PRId64
705                         " bps_rd_max=%" PRId64
706                         " bps_wr_max=%" PRId64
707                         " iops=%" PRId64 " iops_rd=%" PRId64
708                         " iops_wr=%" PRId64
709                         " iops_max=%" PRId64
710                         " iops_rd_max=%" PRId64
711                         " iops_wr_max=%" PRId64
712                         " iops_size=%" PRId64
713                         " group=%s\n",
714                         inserted->bps,
715                         inserted->bps_rd,
716                         inserted->bps_wr,
717                         inserted->bps_max,
718                         inserted->bps_rd_max,
719                         inserted->bps_wr_max,
720                         inserted->iops,
721                         inserted->iops_rd,
722                         inserted->iops_wr,
723                         inserted->iops_max,
724                         inserted->iops_rd_max,
725                         inserted->iops_wr_max,
726                         inserted->iops_size,
727                         inserted->group);
728     }
729 
730     if (verbose) {
731         monitor_printf(mon, "\nImages:\n");
732         image_info = inserted->image;
733         while (1) {
734             bdrv_node_info_dump(qapi_ImageInfo_base(image_info), 0, false);
735             if (image_info->backing_image) {
736                 image_info = image_info->backing_image;
737             } else {
738                 break;
739             }
740         }
741     }
742 }
743 
744 void hmp_info_block(Monitor *mon, const QDict *qdict)
745 {
746     BlockInfoList *block_list, *info;
747     BlockDeviceInfoList *blockdev_list, *blockdev;
748     const char *device = qdict_get_try_str(qdict, "device");
749     bool verbose = qdict_get_try_bool(qdict, "verbose", false);
750     bool nodes = qdict_get_try_bool(qdict, "nodes", false);
751     bool printed = false;
752 
753     /* Print BlockBackend information */
754     if (!nodes) {
755         block_list = qmp_query_block(NULL);
756     } else {
757         block_list = NULL;
758     }
759 
760     for (info = block_list; info; info = info->next) {
761         if (device && strcmp(device, info->value->device)) {
762             continue;
763         }
764 
765         if (info != block_list) {
766             monitor_printf(mon, "\n");
767         }
768 
769         print_block_info(mon, info->value, info->value->inserted,
770                          verbose);
771         printed = true;
772     }
773 
774     qapi_free_BlockInfoList(block_list);
775 
776     if ((!device && !nodes) || printed) {
777         return;
778     }
779 
780     /* Print node information */
781     blockdev_list = qmp_query_named_block_nodes(false, false, NULL);
782     for (blockdev = blockdev_list; blockdev; blockdev = blockdev->next) {
783         assert(blockdev->value->node_name);
784         if (device && strcmp(device, blockdev->value->node_name)) {
785             continue;
786         }
787 
788         if (blockdev != blockdev_list) {
789             monitor_printf(mon, "\n");
790         }
791 
792         print_block_info(mon, NULL, blockdev->value, verbose);
793     }
794     qapi_free_BlockDeviceInfoList(blockdev_list);
795 }
796 
797 void hmp_info_blockstats(Monitor *mon, const QDict *qdict)
798 {
799     BlockStatsList *stats_list, *stats;
800 
801     stats_list = qmp_query_blockstats(false, false, NULL);
802 
803     for (stats = stats_list; stats; stats = stats->next) {
804         if (!stats->value->device) {
805             continue;
806         }
807 
808         monitor_printf(mon, "%s:", stats->value->device);
809         monitor_printf(mon, " rd_bytes=%" PRId64
810                        " wr_bytes=%" PRId64
811                        " rd_operations=%" PRId64
812                        " wr_operations=%" PRId64
813                        " flush_operations=%" PRId64
814                        " wr_total_time_ns=%" PRId64
815                        " rd_total_time_ns=%" PRId64
816                        " flush_total_time_ns=%" PRId64
817                        " rd_merged=%" PRId64
818                        " wr_merged=%" PRId64
819                        " idle_time_ns=%" PRId64
820                        "\n",
821                        stats->value->stats->rd_bytes,
822                        stats->value->stats->wr_bytes,
823                        stats->value->stats->rd_operations,
824                        stats->value->stats->wr_operations,
825                        stats->value->stats->flush_operations,
826                        stats->value->stats->wr_total_time_ns,
827                        stats->value->stats->rd_total_time_ns,
828                        stats->value->stats->flush_total_time_ns,
829                        stats->value->stats->rd_merged,
830                        stats->value->stats->wr_merged,
831                        stats->value->stats->idle_time_ns);
832     }
833 
834     qapi_free_BlockStatsList(stats_list);
835 }
836 
837 void hmp_info_block_jobs(Monitor *mon, const QDict *qdict)
838 {
839     BlockJobInfoList *list;
840 
841     list = qmp_query_block_jobs(&error_abort);
842 
843     if (!list) {
844         monitor_printf(mon, "No active jobs\n");
845         return;
846     }
847 
848     while (list) {
849         if (strcmp(list->value->type, "stream") == 0) {
850             monitor_printf(mon, "Streaming device %s: Completed %" PRId64
851                            " of %" PRId64 " bytes, speed limit %" PRId64
852                            " bytes/s\n",
853                            list->value->device,
854                            list->value->offset,
855                            list->value->len,
856                            list->value->speed);
857         } else {
858             monitor_printf(mon, "Type %s, device %s: Completed %" PRId64
859                            " of %" PRId64 " bytes, speed limit %" PRId64
860                            " bytes/s\n",
861                            list->value->type,
862                            list->value->device,
863                            list->value->offset,
864                            list->value->len,
865                            list->value->speed);
866         }
867         list = list->next;
868     }
869 
870     qapi_free_BlockJobInfoList(list);
871 }
872 
873 void hmp_info_snapshots(Monitor *mon, const QDict *qdict)
874 {
875     BlockDriverState *bs, *bs1;
876     BdrvNextIterator it1;
877     QEMUSnapshotInfo *sn_tab, *sn;
878     bool no_snapshot = true;
879     int nb_sns, i;
880     int total;
881     int *global_snapshots;
882     AioContext *aio_context;
883 
884     typedef struct SnapshotEntry {
885         QEMUSnapshotInfo sn;
886         QTAILQ_ENTRY(SnapshotEntry) next;
887     } SnapshotEntry;
888 
889     typedef struct ImageEntry {
890         const char *imagename;
891         QTAILQ_ENTRY(ImageEntry) next;
892         QTAILQ_HEAD(, SnapshotEntry) snapshots;
893     } ImageEntry;
894 
895     QTAILQ_HEAD(, ImageEntry) image_list =
896         QTAILQ_HEAD_INITIALIZER(image_list);
897 
898     ImageEntry *image_entry, *next_ie;
899     SnapshotEntry *snapshot_entry;
900     Error *err = NULL;
901 
902     GRAPH_RDLOCK_GUARD_MAINLOOP();
903 
904     bs = bdrv_all_find_vmstate_bs(NULL, false, NULL, &err);
905     if (!bs) {
906         error_report_err(err);
907         return;
908     }
909     aio_context = bdrv_get_aio_context(bs);
910 
911     aio_context_acquire(aio_context);
912     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
913     aio_context_release(aio_context);
914 
915     if (nb_sns < 0) {
916         monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);
917         return;
918     }
919 
920     for (bs1 = bdrv_first(&it1); bs1; bs1 = bdrv_next(&it1)) {
921         int bs1_nb_sns = 0;
922         ImageEntry *ie;
923         SnapshotEntry *se;
924         AioContext *ctx = bdrv_get_aio_context(bs1);
925 
926         aio_context_acquire(ctx);
927         if (bdrv_can_snapshot(bs1)) {
928             sn = NULL;
929             bs1_nb_sns = bdrv_snapshot_list(bs1, &sn);
930             if (bs1_nb_sns > 0) {
931                 no_snapshot = false;
932                 ie = g_new0(ImageEntry, 1);
933                 ie->imagename = bdrv_get_device_name(bs1);
934                 QTAILQ_INIT(&ie->snapshots);
935                 QTAILQ_INSERT_TAIL(&image_list, ie, next);
936                 for (i = 0; i < bs1_nb_sns; i++) {
937                     se = g_new0(SnapshotEntry, 1);
938                     se->sn = sn[i];
939                     QTAILQ_INSERT_TAIL(&ie->snapshots, se, next);
940                 }
941             }
942             g_free(sn);
943         }
944         aio_context_release(ctx);
945     }
946 
947     if (no_snapshot) {
948         monitor_printf(mon, "There is no snapshot available.\n");
949         return;
950     }
951 
952     global_snapshots = g_new0(int, nb_sns);
953     total = 0;
954     for (i = 0; i < nb_sns; i++) {
955         SnapshotEntry *next_sn;
956         if (bdrv_all_has_snapshot(sn_tab[i].name, false, NULL, NULL) == 1) {
957             global_snapshots[total] = i;
958             total++;
959             QTAILQ_FOREACH(image_entry, &image_list, next) {
960                 QTAILQ_FOREACH_SAFE(snapshot_entry, &image_entry->snapshots,
961                                     next, next_sn) {
962                     if (!strcmp(sn_tab[i].name, snapshot_entry->sn.name)) {
963                         QTAILQ_REMOVE(&image_entry->snapshots, snapshot_entry,
964                                       next);
965                         g_free(snapshot_entry);
966                     }
967                 }
968             }
969         }
970     }
971     monitor_printf(mon, "List of snapshots present on all disks:\n");
972 
973     if (total > 0) {
974         bdrv_snapshot_dump(NULL);
975         monitor_printf(mon, "\n");
976         for (i = 0; i < total; i++) {
977             sn = &sn_tab[global_snapshots[i]];
978             /*
979              * The ID is not guaranteed to be the same on all images, so
980              * overwrite it.
981              */
982             pstrcpy(sn->id_str, sizeof(sn->id_str), "--");
983             bdrv_snapshot_dump(sn);
984             monitor_printf(mon, "\n");
985         }
986     } else {
987         monitor_printf(mon, "None\n");
988     }
989 
990     QTAILQ_FOREACH(image_entry, &image_list, next) {
991         if (QTAILQ_EMPTY(&image_entry->snapshots)) {
992             continue;
993         }
994         monitor_printf(mon,
995                        "\nList of partial (non-loadable) snapshots on '%s':\n",
996                        image_entry->imagename);
997         bdrv_snapshot_dump(NULL);
998         monitor_printf(mon, "\n");
999         QTAILQ_FOREACH(snapshot_entry, &image_entry->snapshots, next) {
1000             bdrv_snapshot_dump(&snapshot_entry->sn);
1001             monitor_printf(mon, "\n");
1002         }
1003     }
1004 
1005     QTAILQ_FOREACH_SAFE(image_entry, &image_list, next, next_ie) {
1006         SnapshotEntry *next_sn;
1007         QTAILQ_FOREACH_SAFE(snapshot_entry, &image_entry->snapshots, next,
1008                             next_sn) {
1009             g_free(snapshot_entry);
1010         }
1011         g_free(image_entry);
1012     }
1013     g_free(sn_tab);
1014     g_free(global_snapshots);
1015 }
1016 
1017 void hmp_change_medium(Monitor *mon, const char *device, const char *target,
1018                        const char *arg, const char *read_only, bool force,
1019                        Error **errp)
1020 {
1021     ERRP_GUARD();
1022     BlockdevChangeReadOnlyMode read_only_mode = 0;
1023 
1024     if (read_only) {
1025         read_only_mode =
1026             qapi_enum_parse(&BlockdevChangeReadOnlyMode_lookup,
1027                             read_only,
1028                             BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN, errp);
1029         if (*errp) {
1030             return;
1031         }
1032     }
1033 
1034     qmp_blockdev_change_medium(device, NULL, target, arg, true, force,
1035                                !!read_only, read_only_mode, errp);
1036 }
1037