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