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