xref: /openbmc/qemu/monitor/hmp-cmds.c (revision ac057879f42549f130c44d5e63ac3743a3540020)
1 /*
2  * Human Monitor Interface commands
3  *
4  * Copyright IBM, Corp. 2011
5  *
6  * Authors:
7  *  Anthony Liguori   <aliguori@us.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  * Contributions after 2012-01-13 are licensed under the terms of the
13  * GNU GPL, version 2 or (at your option) any later version.
14  */
15 
16 #include "qemu/osdep.h"
17 #include "monitor/hmp.h"
18 #include "net/net.h"
19 #include "net/eth.h"
20 #include "chardev/char.h"
21 #include "sysemu/block-backend.h"
22 #include "sysemu/sysemu.h"
23 #include "qemu/config-file.h"
24 #include "qemu/option.h"
25 #include "qemu/timer.h"
26 #include "qemu/sockets.h"
27 #include "monitor/monitor-internal.h"
28 #include "monitor/qdev.h"
29 #include "qapi/error.h"
30 #include "qapi/opts-visitor.h"
31 #include "qapi/qapi-builtin-visit.h"
32 #include "qapi/qapi-commands-block.h"
33 #include "qapi/qapi-commands-char.h"
34 #include "qapi/qapi-commands-machine.h"
35 #include "qapi/qapi-commands-migration.h"
36 #include "qapi/qapi-commands-misc.h"
37 #include "qapi/qapi-commands-net.h"
38 #include "qapi/qapi-commands-qdev.h"
39 #include "qapi/qapi-commands-rocker.h"
40 #include "qapi/qapi-commands-run-state.h"
41 #include "qapi/qapi-commands-tpm.h"
42 #include "qapi/qapi-commands-ui.h"
43 #include "qapi/qmp/qdict.h"
44 #include "qapi/qmp/qerror.h"
45 #include "qapi/string-input-visitor.h"
46 #include "qapi/string-output-visitor.h"
47 #include "qom/object_interfaces.h"
48 #include "ui/console.h"
49 #include "block/nbd.h"
50 #include "block/qapi.h"
51 #include "qemu-io.h"
52 #include "qemu/cutils.h"
53 #include "qemu/error-report.h"
54 #include "exec/ramlist.h"
55 #include "hw/intc/intc.h"
56 #include "hw/rdma/rdma.h"
57 #include "migration/snapshot.h"
58 #include "migration/misc.h"
59 
60 #ifdef CONFIG_SPICE
61 #include <spice/enums.h>
62 #endif
63 
64 void hmp_handle_error(Monitor *mon, Error **errp)
65 {
66     assert(errp);
67     if (*errp) {
68         error_reportf_err(*errp, "Error: ");
69     }
70 }
71 
72 void hmp_info_name(Monitor *mon, const QDict *qdict)
73 {
74     NameInfo *info;
75 
76     info = qmp_query_name(NULL);
77     if (info->has_name) {
78         monitor_printf(mon, "%s\n", info->name);
79     }
80     qapi_free_NameInfo(info);
81 }
82 
83 void hmp_info_version(Monitor *mon, const QDict *qdict)
84 {
85     VersionInfo *info;
86 
87     info = qmp_query_version(NULL);
88 
89     monitor_printf(mon, "%" PRId64 ".%" PRId64 ".%" PRId64 "%s\n",
90                    info->qemu->major, info->qemu->minor, info->qemu->micro,
91                    info->package);
92 
93     qapi_free_VersionInfo(info);
94 }
95 
96 void hmp_info_kvm(Monitor *mon, const QDict *qdict)
97 {
98     KvmInfo *info;
99 
100     info = qmp_query_kvm(NULL);
101     monitor_printf(mon, "kvm support: ");
102     if (info->present) {
103         monitor_printf(mon, "%s\n", info->enabled ? "enabled" : "disabled");
104     } else {
105         monitor_printf(mon, "not compiled\n");
106     }
107 
108     qapi_free_KvmInfo(info);
109 }
110 
111 void hmp_info_status(Monitor *mon, const QDict *qdict)
112 {
113     StatusInfo *info;
114 
115     info = qmp_query_status(NULL);
116 
117     monitor_printf(mon, "VM status: %s%s",
118                    info->running ? "running" : "paused",
119                    info->singlestep ? " (single step mode)" : "");
120 
121     if (!info->running && info->status != RUN_STATE_PAUSED) {
122         monitor_printf(mon, " (%s)", RunState_str(info->status));
123     }
124 
125     monitor_printf(mon, "\n");
126 
127     qapi_free_StatusInfo(info);
128 }
129 
130 void hmp_info_uuid(Monitor *mon, const QDict *qdict)
131 {
132     UuidInfo *info;
133 
134     info = qmp_query_uuid(NULL);
135     monitor_printf(mon, "%s\n", info->UUID);
136     qapi_free_UuidInfo(info);
137 }
138 
139 void hmp_info_chardev(Monitor *mon, const QDict *qdict)
140 {
141     ChardevInfoList *char_info, *info;
142 
143     char_info = qmp_query_chardev(NULL);
144     for (info = char_info; info; info = info->next) {
145         monitor_printf(mon, "%s: filename=%s\n", info->value->label,
146                                                  info->value->filename);
147     }
148 
149     qapi_free_ChardevInfoList(char_info);
150 }
151 
152 void hmp_info_mice(Monitor *mon, const QDict *qdict)
153 {
154     MouseInfoList *mice_list, *mouse;
155 
156     mice_list = qmp_query_mice(NULL);
157     if (!mice_list) {
158         monitor_printf(mon, "No mouse devices connected\n");
159         return;
160     }
161 
162     for (mouse = mice_list; mouse; mouse = mouse->next) {
163         monitor_printf(mon, "%c Mouse #%" PRId64 ": %s%s\n",
164                        mouse->value->current ? '*' : ' ',
165                        mouse->value->index, mouse->value->name,
166                        mouse->value->absolute ? " (absolute)" : "");
167     }
168 
169     qapi_free_MouseInfoList(mice_list);
170 }
171 
172 static char *SocketAddress_to_str(SocketAddress *addr)
173 {
174     switch (addr->type) {
175     case SOCKET_ADDRESS_TYPE_INET:
176         return g_strdup_printf("tcp:%s:%s",
177                                addr->u.inet.host,
178                                addr->u.inet.port);
179     case SOCKET_ADDRESS_TYPE_UNIX:
180         return g_strdup_printf("unix:%s",
181                                addr->u.q_unix.path);
182     case SOCKET_ADDRESS_TYPE_FD:
183         return g_strdup_printf("fd:%s", addr->u.fd.str);
184     case SOCKET_ADDRESS_TYPE_VSOCK:
185         return g_strdup_printf("tcp:%s:%s",
186                                addr->u.vsock.cid,
187                                addr->u.vsock.port);
188     default:
189         return g_strdup("unknown address type");
190     }
191 }
192 
193 void hmp_info_migrate(Monitor *mon, const QDict *qdict)
194 {
195     MigrationInfo *info;
196     MigrationCapabilityStatusList *caps, *cap;
197 
198     info = qmp_query_migrate(NULL);
199     caps = qmp_query_migrate_capabilities(NULL);
200 
201     migration_global_dump(mon);
202 
203     /* do not display parameters during setup */
204     if (info->has_status && caps) {
205         monitor_printf(mon, "capabilities: ");
206         for (cap = caps; cap; cap = cap->next) {
207             monitor_printf(mon, "%s: %s ",
208                            MigrationCapability_str(cap->value->capability),
209                            cap->value->state ? "on" : "off");
210         }
211         monitor_printf(mon, "\n");
212     }
213 
214     if (info->has_status) {
215         monitor_printf(mon, "Migration status: %s",
216                        MigrationStatus_str(info->status));
217         if (info->status == MIGRATION_STATUS_FAILED &&
218             info->has_error_desc) {
219             monitor_printf(mon, " (%s)\n", info->error_desc);
220         } else {
221             monitor_printf(mon, "\n");
222         }
223 
224         monitor_printf(mon, "total time: %" PRIu64 " milliseconds\n",
225                        info->total_time);
226         if (info->has_expected_downtime) {
227             monitor_printf(mon, "expected downtime: %" PRIu64 " milliseconds\n",
228                            info->expected_downtime);
229         }
230         if (info->has_downtime) {
231             monitor_printf(mon, "downtime: %" PRIu64 " milliseconds\n",
232                            info->downtime);
233         }
234         if (info->has_setup_time) {
235             monitor_printf(mon, "setup: %" PRIu64 " milliseconds\n",
236                            info->setup_time);
237         }
238     }
239 
240     if (info->has_ram) {
241         monitor_printf(mon, "transferred ram: %" PRIu64 " kbytes\n",
242                        info->ram->transferred >> 10);
243         monitor_printf(mon, "throughput: %0.2f mbps\n",
244                        info->ram->mbps);
245         monitor_printf(mon, "remaining ram: %" PRIu64 " kbytes\n",
246                        info->ram->remaining >> 10);
247         monitor_printf(mon, "total ram: %" PRIu64 " kbytes\n",
248                        info->ram->total >> 10);
249         monitor_printf(mon, "duplicate: %" PRIu64 " pages\n",
250                        info->ram->duplicate);
251         monitor_printf(mon, "skipped: %" PRIu64 " pages\n",
252                        info->ram->skipped);
253         monitor_printf(mon, "normal: %" PRIu64 " pages\n",
254                        info->ram->normal);
255         monitor_printf(mon, "normal bytes: %" PRIu64 " kbytes\n",
256                        info->ram->normal_bytes >> 10);
257         monitor_printf(mon, "dirty sync count: %" PRIu64 "\n",
258                        info->ram->dirty_sync_count);
259         monitor_printf(mon, "page size: %" PRIu64 " kbytes\n",
260                        info->ram->page_size >> 10);
261         monitor_printf(mon, "multifd bytes: %" PRIu64 " kbytes\n",
262                        info->ram->multifd_bytes >> 10);
263         monitor_printf(mon, "pages-per-second: %" PRIu64 "\n",
264                        info->ram->pages_per_second);
265 
266         if (info->ram->dirty_pages_rate) {
267             monitor_printf(mon, "dirty pages rate: %" PRIu64 " pages\n",
268                            info->ram->dirty_pages_rate);
269         }
270         if (info->ram->postcopy_requests) {
271             monitor_printf(mon, "postcopy request count: %" PRIu64 "\n",
272                            info->ram->postcopy_requests);
273         }
274     }
275 
276     if (info->has_disk) {
277         monitor_printf(mon, "transferred disk: %" PRIu64 " kbytes\n",
278                        info->disk->transferred >> 10);
279         monitor_printf(mon, "remaining disk: %" PRIu64 " kbytes\n",
280                        info->disk->remaining >> 10);
281         monitor_printf(mon, "total disk: %" PRIu64 " kbytes\n",
282                        info->disk->total >> 10);
283     }
284 
285     if (info->has_xbzrle_cache) {
286         monitor_printf(mon, "cache size: %" PRIu64 " bytes\n",
287                        info->xbzrle_cache->cache_size);
288         monitor_printf(mon, "xbzrle transferred: %" PRIu64 " kbytes\n",
289                        info->xbzrle_cache->bytes >> 10);
290         monitor_printf(mon, "xbzrle pages: %" PRIu64 " pages\n",
291                        info->xbzrle_cache->pages);
292         monitor_printf(mon, "xbzrle cache miss: %" PRIu64 "\n",
293                        info->xbzrle_cache->cache_miss);
294         monitor_printf(mon, "xbzrle cache miss rate: %0.2f\n",
295                        info->xbzrle_cache->cache_miss_rate);
296         monitor_printf(mon, "xbzrle overflow : %" PRIu64 "\n",
297                        info->xbzrle_cache->overflow);
298     }
299 
300     if (info->has_compression) {
301         monitor_printf(mon, "compression pages: %" PRIu64 " pages\n",
302                        info->compression->pages);
303         monitor_printf(mon, "compression busy: %" PRIu64 "\n",
304                        info->compression->busy);
305         monitor_printf(mon, "compression busy rate: %0.2f\n",
306                        info->compression->busy_rate);
307         monitor_printf(mon, "compressed size: %" PRIu64 "\n",
308                        info->compression->compressed_size);
309         monitor_printf(mon, "compression rate: %0.2f\n",
310                        info->compression->compression_rate);
311     }
312 
313     if (info->has_cpu_throttle_percentage) {
314         monitor_printf(mon, "cpu throttle percentage: %" PRIu64 "\n",
315                        info->cpu_throttle_percentage);
316     }
317 
318     if (info->has_postcopy_blocktime) {
319         monitor_printf(mon, "postcopy blocktime: %u\n",
320                        info->postcopy_blocktime);
321     }
322 
323     if (info->has_postcopy_vcpu_blocktime) {
324         Visitor *v;
325         char *str;
326         v = string_output_visitor_new(false, &str);
327         visit_type_uint32List(v, NULL, &info->postcopy_vcpu_blocktime, NULL);
328         visit_complete(v, &str);
329         monitor_printf(mon, "postcopy vcpu blocktime: %s\n", str);
330         g_free(str);
331         visit_free(v);
332     }
333     if (info->has_socket_address) {
334         SocketAddressList *addr;
335 
336         monitor_printf(mon, "socket address: [\n");
337 
338         for (addr = info->socket_address; addr; addr = addr->next) {
339             char *s = SocketAddress_to_str(addr->value);
340             monitor_printf(mon, "\t%s\n", s);
341             g_free(s);
342         }
343         monitor_printf(mon, "]\n");
344     }
345     qapi_free_MigrationInfo(info);
346     qapi_free_MigrationCapabilityStatusList(caps);
347 }
348 
349 void hmp_info_migrate_capabilities(Monitor *mon, const QDict *qdict)
350 {
351     MigrationCapabilityStatusList *caps, *cap;
352 
353     caps = qmp_query_migrate_capabilities(NULL);
354 
355     if (caps) {
356         for (cap = caps; cap; cap = cap->next) {
357             monitor_printf(mon, "%s: %s\n",
358                            MigrationCapability_str(cap->value->capability),
359                            cap->value->state ? "on" : "off");
360         }
361     }
362 
363     qapi_free_MigrationCapabilityStatusList(caps);
364 }
365 
366 void hmp_info_migrate_parameters(Monitor *mon, const QDict *qdict)
367 {
368     MigrationParameters *params;
369 
370     params = qmp_query_migrate_parameters(NULL);
371 
372     if (params) {
373         monitor_printf(mon, "%s: %" PRIu64 " ms\n",
374             MigrationParameter_str(MIGRATION_PARAMETER_ANNOUNCE_INITIAL),
375             params->announce_initial);
376         monitor_printf(mon, "%s: %" PRIu64 " ms\n",
377             MigrationParameter_str(MIGRATION_PARAMETER_ANNOUNCE_MAX),
378             params->announce_max);
379         monitor_printf(mon, "%s: %" PRIu64 "\n",
380             MigrationParameter_str(MIGRATION_PARAMETER_ANNOUNCE_ROUNDS),
381             params->announce_rounds);
382         monitor_printf(mon, "%s: %" PRIu64 " ms\n",
383             MigrationParameter_str(MIGRATION_PARAMETER_ANNOUNCE_STEP),
384             params->announce_step);
385         assert(params->has_compress_level);
386         monitor_printf(mon, "%s: %u\n",
387             MigrationParameter_str(MIGRATION_PARAMETER_COMPRESS_LEVEL),
388             params->compress_level);
389         assert(params->has_compress_threads);
390         monitor_printf(mon, "%s: %u\n",
391             MigrationParameter_str(MIGRATION_PARAMETER_COMPRESS_THREADS),
392             params->compress_threads);
393         assert(params->has_compress_wait_thread);
394         monitor_printf(mon, "%s: %s\n",
395             MigrationParameter_str(MIGRATION_PARAMETER_COMPRESS_WAIT_THREAD),
396             params->compress_wait_thread ? "on" : "off");
397         assert(params->has_decompress_threads);
398         monitor_printf(mon, "%s: %u\n",
399             MigrationParameter_str(MIGRATION_PARAMETER_DECOMPRESS_THREADS),
400             params->decompress_threads);
401         assert(params->has_cpu_throttle_initial);
402         monitor_printf(mon, "%s: %u\n",
403             MigrationParameter_str(MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL),
404             params->cpu_throttle_initial);
405         assert(params->has_cpu_throttle_increment);
406         monitor_printf(mon, "%s: %u\n",
407             MigrationParameter_str(MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT),
408             params->cpu_throttle_increment);
409         assert(params->has_max_cpu_throttle);
410         monitor_printf(mon, "%s: %u\n",
411             MigrationParameter_str(MIGRATION_PARAMETER_MAX_CPU_THROTTLE),
412             params->max_cpu_throttle);
413         assert(params->has_tls_creds);
414         monitor_printf(mon, "%s: '%s'\n",
415             MigrationParameter_str(MIGRATION_PARAMETER_TLS_CREDS),
416             params->tls_creds);
417         assert(params->has_tls_hostname);
418         monitor_printf(mon, "%s: '%s'\n",
419             MigrationParameter_str(MIGRATION_PARAMETER_TLS_HOSTNAME),
420             params->tls_hostname);
421         assert(params->has_max_bandwidth);
422         monitor_printf(mon, "%s: %" PRIu64 " bytes/second\n",
423             MigrationParameter_str(MIGRATION_PARAMETER_MAX_BANDWIDTH),
424             params->max_bandwidth);
425         assert(params->has_downtime_limit);
426         monitor_printf(mon, "%s: %" PRIu64 " milliseconds\n",
427             MigrationParameter_str(MIGRATION_PARAMETER_DOWNTIME_LIMIT),
428             params->downtime_limit);
429         assert(params->has_x_checkpoint_delay);
430         monitor_printf(mon, "%s: %u\n",
431             MigrationParameter_str(MIGRATION_PARAMETER_X_CHECKPOINT_DELAY),
432             params->x_checkpoint_delay);
433         assert(params->has_block_incremental);
434         monitor_printf(mon, "%s: %s\n",
435             MigrationParameter_str(MIGRATION_PARAMETER_BLOCK_INCREMENTAL),
436             params->block_incremental ? "on" : "off");
437         monitor_printf(mon, "%s: %u\n",
438             MigrationParameter_str(MIGRATION_PARAMETER_MULTIFD_CHANNELS),
439             params->multifd_channels);
440         monitor_printf(mon, "%s: %" PRIu64 "\n",
441             MigrationParameter_str(MIGRATION_PARAMETER_XBZRLE_CACHE_SIZE),
442             params->xbzrle_cache_size);
443         monitor_printf(mon, "%s: %" PRIu64 "\n",
444             MigrationParameter_str(MIGRATION_PARAMETER_MAX_POSTCOPY_BANDWIDTH),
445             params->max_postcopy_bandwidth);
446         monitor_printf(mon, " %s: '%s'\n",
447             MigrationParameter_str(MIGRATION_PARAMETER_TLS_AUTHZ),
448             params->has_tls_authz ? params->tls_authz : "");
449     }
450 
451     qapi_free_MigrationParameters(params);
452 }
453 
454 void hmp_info_migrate_cache_size(Monitor *mon, const QDict *qdict)
455 {
456     monitor_printf(mon, "xbzrel cache size: %" PRId64 " kbytes\n",
457                    qmp_query_migrate_cache_size(NULL) >> 10);
458 }
459 
460 void hmp_info_cpus(Monitor *mon, const QDict *qdict)
461 {
462     CpuInfoFastList *cpu_list, *cpu;
463 
464     cpu_list = qmp_query_cpus_fast(NULL);
465 
466     for (cpu = cpu_list; cpu; cpu = cpu->next) {
467         int active = ' ';
468 
469         if (cpu->value->cpu_index == monitor_get_cpu_index()) {
470             active = '*';
471         }
472 
473         monitor_printf(mon, "%c CPU #%" PRId64 ":", active,
474                        cpu->value->cpu_index);
475         monitor_printf(mon, " thread_id=%" PRId64 "\n", cpu->value->thread_id);
476     }
477 
478     qapi_free_CpuInfoFastList(cpu_list);
479 }
480 
481 static void print_block_info(Monitor *mon, BlockInfo *info,
482                              BlockDeviceInfo *inserted, bool verbose)
483 {
484     ImageInfo *image_info;
485 
486     assert(!info || !info->has_inserted || info->inserted == inserted);
487 
488     if (info && *info->device) {
489         monitor_printf(mon, "%s", info->device);
490         if (inserted && inserted->has_node_name) {
491             monitor_printf(mon, " (%s)", inserted->node_name);
492         }
493     } else {
494         assert(info || inserted);
495         monitor_printf(mon, "%s",
496                        inserted && inserted->has_node_name ? inserted->node_name
497                        : info && info->has_qdev ? info->qdev
498                        : "<anonymous>");
499     }
500 
501     if (inserted) {
502         monitor_printf(mon, ": %s (%s%s%s)\n",
503                        inserted->file,
504                        inserted->drv,
505                        inserted->ro ? ", read-only" : "",
506                        inserted->encrypted ? ", encrypted" : "");
507     } else {
508         monitor_printf(mon, ": [not inserted]\n");
509     }
510 
511     if (info) {
512         if (info->has_qdev) {
513             monitor_printf(mon, "    Attached to:      %s\n", info->qdev);
514         }
515         if (info->has_io_status && info->io_status != BLOCK_DEVICE_IO_STATUS_OK) {
516             monitor_printf(mon, "    I/O status:       %s\n",
517                            BlockDeviceIoStatus_str(info->io_status));
518         }
519 
520         if (info->removable) {
521             monitor_printf(mon, "    Removable device: %slocked, tray %s\n",
522                            info->locked ? "" : "not ",
523                            info->tray_open ? "open" : "closed");
524         }
525     }
526 
527 
528     if (!inserted) {
529         return;
530     }
531 
532     monitor_printf(mon, "    Cache mode:       %s%s%s\n",
533                    inserted->cache->writeback ? "writeback" : "writethrough",
534                    inserted->cache->direct ? ", direct" : "",
535                    inserted->cache->no_flush ? ", ignore flushes" : "");
536 
537     if (inserted->has_backing_file) {
538         monitor_printf(mon,
539                        "    Backing file:     %s "
540                        "(chain depth: %" PRId64 ")\n",
541                        inserted->backing_file,
542                        inserted->backing_file_depth);
543     }
544 
545     if (inserted->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF) {
546         monitor_printf(mon, "    Detect zeroes:    %s\n",
547                 BlockdevDetectZeroesOptions_str(inserted->detect_zeroes));
548     }
549 
550     if (inserted->bps  || inserted->bps_rd  || inserted->bps_wr  ||
551         inserted->iops || inserted->iops_rd || inserted->iops_wr)
552     {
553         monitor_printf(mon, "    I/O throttling:   bps=%" PRId64
554                         " bps_rd=%" PRId64  " bps_wr=%" PRId64
555                         " bps_max=%" PRId64
556                         " bps_rd_max=%" PRId64
557                         " bps_wr_max=%" PRId64
558                         " iops=%" PRId64 " iops_rd=%" PRId64
559                         " iops_wr=%" PRId64
560                         " iops_max=%" PRId64
561                         " iops_rd_max=%" PRId64
562                         " iops_wr_max=%" PRId64
563                         " iops_size=%" PRId64
564                         " group=%s\n",
565                         inserted->bps,
566                         inserted->bps_rd,
567                         inserted->bps_wr,
568                         inserted->bps_max,
569                         inserted->bps_rd_max,
570                         inserted->bps_wr_max,
571                         inserted->iops,
572                         inserted->iops_rd,
573                         inserted->iops_wr,
574                         inserted->iops_max,
575                         inserted->iops_rd_max,
576                         inserted->iops_wr_max,
577                         inserted->iops_size,
578                         inserted->group);
579     }
580 
581     if (verbose) {
582         monitor_printf(mon, "\nImages:\n");
583         image_info = inserted->image;
584         while (1) {
585                 bdrv_image_info_dump(image_info);
586             if (image_info->has_backing_image) {
587                 image_info = image_info->backing_image;
588             } else {
589                 break;
590             }
591         }
592     }
593 }
594 
595 void hmp_info_block(Monitor *mon, const QDict *qdict)
596 {
597     BlockInfoList *block_list, *info;
598     BlockDeviceInfoList *blockdev_list, *blockdev;
599     const char *device = qdict_get_try_str(qdict, "device");
600     bool verbose = qdict_get_try_bool(qdict, "verbose", false);
601     bool nodes = qdict_get_try_bool(qdict, "nodes", false);
602     bool printed = false;
603 
604     /* Print BlockBackend information */
605     if (!nodes) {
606         block_list = qmp_query_block(NULL);
607     } else {
608         block_list = NULL;
609     }
610 
611     for (info = block_list; info; info = info->next) {
612         if (device && strcmp(device, info->value->device)) {
613             continue;
614         }
615 
616         if (info != block_list) {
617             monitor_printf(mon, "\n");
618         }
619 
620         print_block_info(mon, info->value, info->value->has_inserted
621                                            ? info->value->inserted : NULL,
622                          verbose);
623         printed = true;
624     }
625 
626     qapi_free_BlockInfoList(block_list);
627 
628     if ((!device && !nodes) || printed) {
629         return;
630     }
631 
632     /* Print node information */
633     blockdev_list = qmp_query_named_block_nodes(NULL);
634     for (blockdev = blockdev_list; blockdev; blockdev = blockdev->next) {
635         assert(blockdev->value->has_node_name);
636         if (device && strcmp(device, blockdev->value->node_name)) {
637             continue;
638         }
639 
640         if (blockdev != blockdev_list) {
641             monitor_printf(mon, "\n");
642         }
643 
644         print_block_info(mon, NULL, blockdev->value, verbose);
645     }
646     qapi_free_BlockDeviceInfoList(blockdev_list);
647 }
648 
649 void hmp_info_blockstats(Monitor *mon, const QDict *qdict)
650 {
651     BlockStatsList *stats_list, *stats;
652 
653     stats_list = qmp_query_blockstats(false, false, NULL);
654 
655     for (stats = stats_list; stats; stats = stats->next) {
656         if (!stats->value->has_device) {
657             continue;
658         }
659 
660         monitor_printf(mon, "%s:", stats->value->device);
661         monitor_printf(mon, " rd_bytes=%" PRId64
662                        " wr_bytes=%" PRId64
663                        " rd_operations=%" PRId64
664                        " wr_operations=%" PRId64
665                        " flush_operations=%" PRId64
666                        " wr_total_time_ns=%" PRId64
667                        " rd_total_time_ns=%" PRId64
668                        " flush_total_time_ns=%" PRId64
669                        " rd_merged=%" PRId64
670                        " wr_merged=%" PRId64
671                        " idle_time_ns=%" PRId64
672                        "\n",
673                        stats->value->stats->rd_bytes,
674                        stats->value->stats->wr_bytes,
675                        stats->value->stats->rd_operations,
676                        stats->value->stats->wr_operations,
677                        stats->value->stats->flush_operations,
678                        stats->value->stats->wr_total_time_ns,
679                        stats->value->stats->rd_total_time_ns,
680                        stats->value->stats->flush_total_time_ns,
681                        stats->value->stats->rd_merged,
682                        stats->value->stats->wr_merged,
683                        stats->value->stats->idle_time_ns);
684     }
685 
686     qapi_free_BlockStatsList(stats_list);
687 }
688 
689 #ifdef CONFIG_VNC
690 /* Helper for hmp_info_vnc_clients, _servers */
691 static void hmp_info_VncBasicInfo(Monitor *mon, VncBasicInfo *info,
692                                   const char *name)
693 {
694     monitor_printf(mon, "  %s: %s:%s (%s%s)\n",
695                    name,
696                    info->host,
697                    info->service,
698                    NetworkAddressFamily_str(info->family),
699                    info->websocket ? " (Websocket)" : "");
700 }
701 
702 /* Helper displaying and auth and crypt info */
703 static void hmp_info_vnc_authcrypt(Monitor *mon, const char *indent,
704                                    VncPrimaryAuth auth,
705                                    VncVencryptSubAuth *vencrypt)
706 {
707     monitor_printf(mon, "%sAuth: %s (Sub: %s)\n", indent,
708                    VncPrimaryAuth_str(auth),
709                    vencrypt ? VncVencryptSubAuth_str(*vencrypt) : "none");
710 }
711 
712 static void hmp_info_vnc_clients(Monitor *mon, VncClientInfoList *client)
713 {
714     while (client) {
715         VncClientInfo *cinfo = client->value;
716 
717         hmp_info_VncBasicInfo(mon, qapi_VncClientInfo_base(cinfo), "Client");
718         monitor_printf(mon, "    x509_dname: %s\n",
719                        cinfo->has_x509_dname ?
720                        cinfo->x509_dname : "none");
721         monitor_printf(mon, "    sasl_username: %s\n",
722                        cinfo->has_sasl_username ?
723                        cinfo->sasl_username : "none");
724 
725         client = client->next;
726     }
727 }
728 
729 static void hmp_info_vnc_servers(Monitor *mon, VncServerInfo2List *server)
730 {
731     while (server) {
732         VncServerInfo2 *sinfo = server->value;
733         hmp_info_VncBasicInfo(mon, qapi_VncServerInfo2_base(sinfo), "Server");
734         hmp_info_vnc_authcrypt(mon, "    ", sinfo->auth,
735                                sinfo->has_vencrypt ? &sinfo->vencrypt : NULL);
736         server = server->next;
737     }
738 }
739 
740 void hmp_info_vnc(Monitor *mon, const QDict *qdict)
741 {
742     VncInfo2List *info2l;
743     Error *err = NULL;
744 
745     info2l = qmp_query_vnc_servers(&err);
746     if (err) {
747         hmp_handle_error(mon, &err);
748         return;
749     }
750     if (!info2l) {
751         monitor_printf(mon, "None\n");
752         return;
753     }
754 
755     while (info2l) {
756         VncInfo2 *info = info2l->value;
757         monitor_printf(mon, "%s:\n", info->id);
758         hmp_info_vnc_servers(mon, info->server);
759         hmp_info_vnc_clients(mon, info->clients);
760         if (!info->server) {
761             /* The server entry displays its auth, we only
762              * need to display in the case of 'reverse' connections
763              * where there's no server.
764              */
765             hmp_info_vnc_authcrypt(mon, "  ", info->auth,
766                                info->has_vencrypt ? &info->vencrypt : NULL);
767         }
768         if (info->has_display) {
769             monitor_printf(mon, "  Display: %s\n", info->display);
770         }
771         info2l = info2l->next;
772     }
773 
774     qapi_free_VncInfo2List(info2l);
775 
776 }
777 #endif
778 
779 #ifdef CONFIG_SPICE
780 void hmp_info_spice(Monitor *mon, const QDict *qdict)
781 {
782     SpiceChannelList *chan;
783     SpiceInfo *info;
784     const char *channel_name;
785     const char * const channel_names[] = {
786         [SPICE_CHANNEL_MAIN] = "main",
787         [SPICE_CHANNEL_DISPLAY] = "display",
788         [SPICE_CHANNEL_INPUTS] = "inputs",
789         [SPICE_CHANNEL_CURSOR] = "cursor",
790         [SPICE_CHANNEL_PLAYBACK] = "playback",
791         [SPICE_CHANNEL_RECORD] = "record",
792         [SPICE_CHANNEL_TUNNEL] = "tunnel",
793         [SPICE_CHANNEL_SMARTCARD] = "smartcard",
794         [SPICE_CHANNEL_USBREDIR] = "usbredir",
795         [SPICE_CHANNEL_PORT] = "port",
796 #if 0
797         /* minimum spice-protocol is 0.12.3, webdav was added in 0.12.7,
798          * no easy way to #ifdef (SPICE_CHANNEL_* is a enum).  Disable
799          * as quick fix for build failures with older versions. */
800         [SPICE_CHANNEL_WEBDAV] = "webdav",
801 #endif
802     };
803 
804     info = qmp_query_spice(NULL);
805 
806     if (!info->enabled) {
807         monitor_printf(mon, "Server: disabled\n");
808         goto out;
809     }
810 
811     monitor_printf(mon, "Server:\n");
812     if (info->has_port) {
813         monitor_printf(mon, "     address: %s:%" PRId64 "\n",
814                        info->host, info->port);
815     }
816     if (info->has_tls_port) {
817         monitor_printf(mon, "     address: %s:%" PRId64 " [tls]\n",
818                        info->host, info->tls_port);
819     }
820     monitor_printf(mon, "    migrated: %s\n",
821                    info->migrated ? "true" : "false");
822     monitor_printf(mon, "        auth: %s\n", info->auth);
823     monitor_printf(mon, "    compiled: %s\n", info->compiled_version);
824     monitor_printf(mon, "  mouse-mode: %s\n",
825                    SpiceQueryMouseMode_str(info->mouse_mode));
826 
827     if (!info->has_channels || info->channels == NULL) {
828         monitor_printf(mon, "Channels: none\n");
829     } else {
830         for (chan = info->channels; chan; chan = chan->next) {
831             monitor_printf(mon, "Channel:\n");
832             monitor_printf(mon, "     address: %s:%s%s\n",
833                            chan->value->host, chan->value->port,
834                            chan->value->tls ? " [tls]" : "");
835             monitor_printf(mon, "     session: %" PRId64 "\n",
836                            chan->value->connection_id);
837             monitor_printf(mon, "     channel: %" PRId64 ":%" PRId64 "\n",
838                            chan->value->channel_type, chan->value->channel_id);
839 
840             channel_name = "unknown";
841             if (chan->value->channel_type > 0 &&
842                 chan->value->channel_type < ARRAY_SIZE(channel_names) &&
843                 channel_names[chan->value->channel_type]) {
844                 channel_name = channel_names[chan->value->channel_type];
845             }
846 
847             monitor_printf(mon, "     channel name: %s\n", channel_name);
848         }
849     }
850 
851 out:
852     qapi_free_SpiceInfo(info);
853 }
854 #endif
855 
856 void hmp_info_balloon(Monitor *mon, const QDict *qdict)
857 {
858     BalloonInfo *info;
859     Error *err = NULL;
860 
861     info = qmp_query_balloon(&err);
862     if (err) {
863         hmp_handle_error(mon, &err);
864         return;
865     }
866 
867     monitor_printf(mon, "balloon: actual=%" PRId64 "\n", info->actual >> 20);
868 
869     qapi_free_BalloonInfo(info);
870 }
871 
872 static void hmp_info_pci_device(Monitor *mon, const PciDeviceInfo *dev)
873 {
874     PciMemoryRegionList *region;
875 
876     monitor_printf(mon, "  Bus %2" PRId64 ", ", dev->bus);
877     monitor_printf(mon, "device %3" PRId64 ", function %" PRId64 ":\n",
878                    dev->slot, dev->function);
879     monitor_printf(mon, "    ");
880 
881     if (dev->class_info->has_desc) {
882         monitor_printf(mon, "%s", dev->class_info->desc);
883     } else {
884         monitor_printf(mon, "Class %04" PRId64, dev->class_info->q_class);
885     }
886 
887     monitor_printf(mon, ": PCI device %04" PRIx64 ":%04" PRIx64 "\n",
888                    dev->id->vendor, dev->id->device);
889     if (dev->id->has_subsystem_vendor && dev->id->has_subsystem) {
890         monitor_printf(mon, "      PCI subsystem %04" PRIx64 ":%04" PRIx64 "\n",
891                        dev->id->subsystem_vendor, dev->id->subsystem);
892     }
893 
894     if (dev->has_irq) {
895         monitor_printf(mon, "      IRQ %" PRId64 ".\n", dev->irq);
896     }
897 
898     if (dev->has_pci_bridge) {
899         monitor_printf(mon, "      BUS %" PRId64 ".\n",
900                        dev->pci_bridge->bus->number);
901         monitor_printf(mon, "      secondary bus %" PRId64 ".\n",
902                        dev->pci_bridge->bus->secondary);
903         monitor_printf(mon, "      subordinate bus %" PRId64 ".\n",
904                        dev->pci_bridge->bus->subordinate);
905 
906         monitor_printf(mon, "      IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
907                        dev->pci_bridge->bus->io_range->base,
908                        dev->pci_bridge->bus->io_range->limit);
909 
910         monitor_printf(mon,
911                        "      memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
912                        dev->pci_bridge->bus->memory_range->base,
913                        dev->pci_bridge->bus->memory_range->limit);
914 
915         monitor_printf(mon, "      prefetchable memory range "
916                        "[0x%08"PRIx64", 0x%08"PRIx64"]\n",
917                        dev->pci_bridge->bus->prefetchable_range->base,
918                        dev->pci_bridge->bus->prefetchable_range->limit);
919     }
920 
921     for (region = dev->regions; region; region = region->next) {
922         uint64_t addr, size;
923 
924         addr = region->value->address;
925         size = region->value->size;
926 
927         monitor_printf(mon, "      BAR%" PRId64 ": ", region->value->bar);
928 
929         if (!strcmp(region->value->type, "io")) {
930             monitor_printf(mon, "I/O at 0x%04" PRIx64
931                                 " [0x%04" PRIx64 "].\n",
932                            addr, addr + size - 1);
933         } else {
934             monitor_printf(mon, "%d bit%s memory at 0x%08" PRIx64
935                                " [0x%08" PRIx64 "].\n",
936                            region->value->mem_type_64 ? 64 : 32,
937                            region->value->prefetch ? " prefetchable" : "",
938                            addr, addr + size - 1);
939         }
940     }
941 
942     monitor_printf(mon, "      id \"%s\"\n", dev->qdev_id);
943 
944     if (dev->has_pci_bridge) {
945         if (dev->pci_bridge->has_devices) {
946             PciDeviceInfoList *cdev;
947             for (cdev = dev->pci_bridge->devices; cdev; cdev = cdev->next) {
948                 hmp_info_pci_device(mon, cdev->value);
949             }
950         }
951     }
952 }
953 
954 static int hmp_info_irq_foreach(Object *obj, void *opaque)
955 {
956     InterruptStatsProvider *intc;
957     InterruptStatsProviderClass *k;
958     Monitor *mon = opaque;
959 
960     if (object_dynamic_cast(obj, TYPE_INTERRUPT_STATS_PROVIDER)) {
961         intc = INTERRUPT_STATS_PROVIDER(obj);
962         k = INTERRUPT_STATS_PROVIDER_GET_CLASS(obj);
963         uint64_t *irq_counts;
964         unsigned int nb_irqs, i;
965         if (k->get_statistics &&
966             k->get_statistics(intc, &irq_counts, &nb_irqs)) {
967             if (nb_irqs > 0) {
968                 monitor_printf(mon, "IRQ statistics for %s:\n",
969                                object_get_typename(obj));
970                 for (i = 0; i < nb_irqs; i++) {
971                     if (irq_counts[i] > 0) {
972                         monitor_printf(mon, "%2d: %" PRId64 "\n", i,
973                                        irq_counts[i]);
974                     }
975                 }
976             }
977         } else {
978             monitor_printf(mon, "IRQ statistics not available for %s.\n",
979                            object_get_typename(obj));
980         }
981     }
982 
983     return 0;
984 }
985 
986 void hmp_info_irq(Monitor *mon, const QDict *qdict)
987 {
988     object_child_foreach_recursive(object_get_root(),
989                                    hmp_info_irq_foreach, mon);
990 }
991 
992 static int hmp_info_pic_foreach(Object *obj, void *opaque)
993 {
994     InterruptStatsProvider *intc;
995     InterruptStatsProviderClass *k;
996     Monitor *mon = opaque;
997 
998     if (object_dynamic_cast(obj, TYPE_INTERRUPT_STATS_PROVIDER)) {
999         intc = INTERRUPT_STATS_PROVIDER(obj);
1000         k = INTERRUPT_STATS_PROVIDER_GET_CLASS(obj);
1001         if (k->print_info) {
1002             k->print_info(intc, mon);
1003         } else {
1004             monitor_printf(mon, "Interrupt controller information not available for %s.\n",
1005                            object_get_typename(obj));
1006         }
1007     }
1008 
1009     return 0;
1010 }
1011 
1012 void hmp_info_pic(Monitor *mon, const QDict *qdict)
1013 {
1014     object_child_foreach_recursive(object_get_root(),
1015                                    hmp_info_pic_foreach, mon);
1016 }
1017 
1018 static int hmp_info_rdma_foreach(Object *obj, void *opaque)
1019 {
1020     RdmaProvider *rdma;
1021     RdmaProviderClass *k;
1022     Monitor *mon = opaque;
1023 
1024     if (object_dynamic_cast(obj, INTERFACE_RDMA_PROVIDER)) {
1025         rdma = RDMA_PROVIDER(obj);
1026         k = RDMA_PROVIDER_GET_CLASS(obj);
1027         if (k->print_statistics) {
1028             k->print_statistics(mon, rdma);
1029         } else {
1030             monitor_printf(mon, "RDMA statistics not available for %s.\n",
1031                            object_get_typename(obj));
1032         }
1033     }
1034 
1035     return 0;
1036 }
1037 
1038 void hmp_info_rdma(Monitor *mon, const QDict *qdict)
1039 {
1040     object_child_foreach_recursive(object_get_root(),
1041                                    hmp_info_rdma_foreach, mon);
1042 }
1043 
1044 void hmp_info_pci(Monitor *mon, const QDict *qdict)
1045 {
1046     PciInfoList *info_list, *info;
1047     Error *err = NULL;
1048 
1049     info_list = qmp_query_pci(&err);
1050     if (err) {
1051         monitor_printf(mon, "PCI devices not supported\n");
1052         error_free(err);
1053         return;
1054     }
1055 
1056     for (info = info_list; info; info = info->next) {
1057         PciDeviceInfoList *dev;
1058 
1059         for (dev = info->value->devices; dev; dev = dev->next) {
1060             hmp_info_pci_device(mon, dev->value);
1061         }
1062     }
1063 
1064     qapi_free_PciInfoList(info_list);
1065 }
1066 
1067 void hmp_info_block_jobs(Monitor *mon, const QDict *qdict)
1068 {
1069     BlockJobInfoList *list;
1070     Error *err = NULL;
1071 
1072     list = qmp_query_block_jobs(&err);
1073     assert(!err);
1074 
1075     if (!list) {
1076         monitor_printf(mon, "No active jobs\n");
1077         return;
1078     }
1079 
1080     while (list) {
1081         if (strcmp(list->value->type, "stream") == 0) {
1082             monitor_printf(mon, "Streaming device %s: Completed %" PRId64
1083                            " of %" PRId64 " bytes, speed limit %" PRId64
1084                            " bytes/s\n",
1085                            list->value->device,
1086                            list->value->offset,
1087                            list->value->len,
1088                            list->value->speed);
1089         } else {
1090             monitor_printf(mon, "Type %s, device %s: Completed %" PRId64
1091                            " of %" PRId64 " bytes, speed limit %" PRId64
1092                            " bytes/s\n",
1093                            list->value->type,
1094                            list->value->device,
1095                            list->value->offset,
1096                            list->value->len,
1097                            list->value->speed);
1098         }
1099         list = list->next;
1100     }
1101 
1102     qapi_free_BlockJobInfoList(list);
1103 }
1104 
1105 void hmp_info_tpm(Monitor *mon, const QDict *qdict)
1106 {
1107     TPMInfoList *info_list, *info;
1108     Error *err = NULL;
1109     unsigned int c = 0;
1110     TPMPassthroughOptions *tpo;
1111     TPMEmulatorOptions *teo;
1112 
1113     info_list = qmp_query_tpm(&err);
1114     if (err) {
1115         monitor_printf(mon, "TPM device not supported\n");
1116         error_free(err);
1117         return;
1118     }
1119 
1120     if (info_list) {
1121         monitor_printf(mon, "TPM device:\n");
1122     }
1123 
1124     for (info = info_list; info; info = info->next) {
1125         TPMInfo *ti = info->value;
1126         monitor_printf(mon, " tpm%d: model=%s\n",
1127                        c, TpmModel_str(ti->model));
1128 
1129         monitor_printf(mon, "  \\ %s: type=%s",
1130                        ti->id, TpmTypeOptionsKind_str(ti->options->type));
1131 
1132         switch (ti->options->type) {
1133         case TPM_TYPE_OPTIONS_KIND_PASSTHROUGH:
1134             tpo = ti->options->u.passthrough.data;
1135             monitor_printf(mon, "%s%s%s%s",
1136                            tpo->has_path ? ",path=" : "",
1137                            tpo->has_path ? tpo->path : "",
1138                            tpo->has_cancel_path ? ",cancel-path=" : "",
1139                            tpo->has_cancel_path ? tpo->cancel_path : "");
1140             break;
1141         case TPM_TYPE_OPTIONS_KIND_EMULATOR:
1142             teo = ti->options->u.emulator.data;
1143             monitor_printf(mon, ",chardev=%s", teo->chardev);
1144             break;
1145         case TPM_TYPE_OPTIONS_KIND__MAX:
1146             break;
1147         }
1148         monitor_printf(mon, "\n");
1149         c++;
1150     }
1151     qapi_free_TPMInfoList(info_list);
1152 }
1153 
1154 void hmp_quit(Monitor *mon, const QDict *qdict)
1155 {
1156     monitor_suspend(mon);
1157     qmp_quit(NULL);
1158 }
1159 
1160 void hmp_stop(Monitor *mon, const QDict *qdict)
1161 {
1162     qmp_stop(NULL);
1163 }
1164 
1165 void hmp_sync_profile(Monitor *mon, const QDict *qdict)
1166 {
1167     const char *op = qdict_get_try_str(qdict, "op");
1168 
1169     if (op == NULL) {
1170         bool on = qsp_is_enabled();
1171 
1172         monitor_printf(mon, "sync-profile is %s\n", on ? "on" : "off");
1173         return;
1174     }
1175     if (!strcmp(op, "on")) {
1176         qsp_enable();
1177     } else if (!strcmp(op, "off")) {
1178         qsp_disable();
1179     } else if (!strcmp(op, "reset")) {
1180         qsp_reset();
1181     } else {
1182         Error *err = NULL;
1183 
1184         error_setg(&err, QERR_INVALID_PARAMETER, op);
1185         hmp_handle_error(mon, &err);
1186     }
1187 }
1188 
1189 void hmp_system_reset(Monitor *mon, const QDict *qdict)
1190 {
1191     qmp_system_reset(NULL);
1192 }
1193 
1194 void hmp_system_powerdown(Monitor *mon, const QDict *qdict)
1195 {
1196     qmp_system_powerdown(NULL);
1197 }
1198 
1199 void hmp_exit_preconfig(Monitor *mon, const QDict *qdict)
1200 {
1201     Error *err = NULL;
1202 
1203     qmp_x_exit_preconfig(&err);
1204     hmp_handle_error(mon, &err);
1205 }
1206 
1207 void hmp_cpu(Monitor *mon, const QDict *qdict)
1208 {
1209     int64_t cpu_index;
1210 
1211     /* XXX: drop the monitor_set_cpu() usage when all HMP commands that
1212             use it are converted to the QAPI */
1213     cpu_index = qdict_get_int(qdict, "index");
1214     if (monitor_set_cpu(cpu_index) < 0) {
1215         monitor_printf(mon, "invalid CPU index\n");
1216     }
1217 }
1218 
1219 void hmp_memsave(Monitor *mon, const QDict *qdict)
1220 {
1221     uint32_t size = qdict_get_int(qdict, "size");
1222     const char *filename = qdict_get_str(qdict, "filename");
1223     uint64_t addr = qdict_get_int(qdict, "val");
1224     Error *err = NULL;
1225     int cpu_index = monitor_get_cpu_index();
1226 
1227     if (cpu_index < 0) {
1228         monitor_printf(mon, "No CPU available\n");
1229         return;
1230     }
1231 
1232     qmp_memsave(addr, size, filename, true, cpu_index, &err);
1233     hmp_handle_error(mon, &err);
1234 }
1235 
1236 void hmp_pmemsave(Monitor *mon, const QDict *qdict)
1237 {
1238     uint32_t size = qdict_get_int(qdict, "size");
1239     const char *filename = qdict_get_str(qdict, "filename");
1240     uint64_t addr = qdict_get_int(qdict, "val");
1241     Error *err = NULL;
1242 
1243     qmp_pmemsave(addr, size, filename, &err);
1244     hmp_handle_error(mon, &err);
1245 }
1246 
1247 void hmp_ringbuf_write(Monitor *mon, const QDict *qdict)
1248 {
1249     const char *chardev = qdict_get_str(qdict, "device");
1250     const char *data = qdict_get_str(qdict, "data");
1251     Error *err = NULL;
1252 
1253     qmp_ringbuf_write(chardev, data, false, 0, &err);
1254 
1255     hmp_handle_error(mon, &err);
1256 }
1257 
1258 void hmp_ringbuf_read(Monitor *mon, const QDict *qdict)
1259 {
1260     uint32_t size = qdict_get_int(qdict, "size");
1261     const char *chardev = qdict_get_str(qdict, "device");
1262     char *data;
1263     Error *err = NULL;
1264     int i;
1265 
1266     data = qmp_ringbuf_read(chardev, size, false, 0, &err);
1267     if (err) {
1268         hmp_handle_error(mon, &err);
1269         return;
1270     }
1271 
1272     for (i = 0; data[i]; i++) {
1273         unsigned char ch = data[i];
1274 
1275         if (ch == '\\') {
1276             monitor_printf(mon, "\\\\");
1277         } else if ((ch < 0x20 && ch != '\n' && ch != '\t') || ch == 0x7F) {
1278             monitor_printf(mon, "\\u%04X", ch);
1279         } else {
1280             monitor_printf(mon, "%c", ch);
1281         }
1282 
1283     }
1284     monitor_printf(mon, "\n");
1285     g_free(data);
1286 }
1287 
1288 void hmp_cont(Monitor *mon, const QDict *qdict)
1289 {
1290     Error *err = NULL;
1291 
1292     qmp_cont(&err);
1293     hmp_handle_error(mon, &err);
1294 }
1295 
1296 void hmp_system_wakeup(Monitor *mon, const QDict *qdict)
1297 {
1298     Error *err = NULL;
1299 
1300     qmp_system_wakeup(&err);
1301     hmp_handle_error(mon, &err);
1302 }
1303 
1304 void hmp_nmi(Monitor *mon, const QDict *qdict)
1305 {
1306     Error *err = NULL;
1307 
1308     qmp_inject_nmi(&err);
1309     hmp_handle_error(mon, &err);
1310 }
1311 
1312 void hmp_set_link(Monitor *mon, const QDict *qdict)
1313 {
1314     const char *name = qdict_get_str(qdict, "name");
1315     bool up = qdict_get_bool(qdict, "up");
1316     Error *err = NULL;
1317 
1318     qmp_set_link(name, up, &err);
1319     hmp_handle_error(mon, &err);
1320 }
1321 
1322 void hmp_block_passwd(Monitor *mon, const QDict *qdict)
1323 {
1324     const char *device = qdict_get_str(qdict, "device");
1325     const char *password = qdict_get_str(qdict, "password");
1326     Error *err = NULL;
1327 
1328     qmp_block_passwd(true, device, false, NULL, password, &err);
1329     hmp_handle_error(mon, &err);
1330 }
1331 
1332 void hmp_balloon(Monitor *mon, const QDict *qdict)
1333 {
1334     int64_t value = qdict_get_int(qdict, "value");
1335     Error *err = NULL;
1336 
1337     qmp_balloon(value, &err);
1338     hmp_handle_error(mon, &err);
1339 }
1340 
1341 void hmp_block_resize(Monitor *mon, const QDict *qdict)
1342 {
1343     const char *device = qdict_get_str(qdict, "device");
1344     int64_t size = qdict_get_int(qdict, "size");
1345     Error *err = NULL;
1346 
1347     qmp_block_resize(true, device, false, NULL, size, &err);
1348     hmp_handle_error(mon, &err);
1349 }
1350 
1351 void hmp_drive_mirror(Monitor *mon, const QDict *qdict)
1352 {
1353     const char *filename = qdict_get_str(qdict, "target");
1354     const char *format = qdict_get_try_str(qdict, "format");
1355     bool reuse = qdict_get_try_bool(qdict, "reuse", false);
1356     bool full = qdict_get_try_bool(qdict, "full", false);
1357     Error *err = NULL;
1358     DriveMirror mirror = {
1359         .device = (char *)qdict_get_str(qdict, "device"),
1360         .target = (char *)filename,
1361         .has_format = !!format,
1362         .format = (char *)format,
1363         .sync = full ? MIRROR_SYNC_MODE_FULL : MIRROR_SYNC_MODE_TOP,
1364         .has_mode = true,
1365         .mode = reuse ? NEW_IMAGE_MODE_EXISTING : NEW_IMAGE_MODE_ABSOLUTE_PATHS,
1366         .unmap = true,
1367     };
1368 
1369     if (!filename) {
1370         error_setg(&err, QERR_MISSING_PARAMETER, "target");
1371         hmp_handle_error(mon, &err);
1372         return;
1373     }
1374     qmp_drive_mirror(&mirror, &err);
1375     hmp_handle_error(mon, &err);
1376 }
1377 
1378 void hmp_drive_backup(Monitor *mon, const QDict *qdict)
1379 {
1380     const char *device = qdict_get_str(qdict, "device");
1381     const char *filename = qdict_get_str(qdict, "target");
1382     const char *format = qdict_get_try_str(qdict, "format");
1383     bool reuse = qdict_get_try_bool(qdict, "reuse", false);
1384     bool full = qdict_get_try_bool(qdict, "full", false);
1385     bool compress = qdict_get_try_bool(qdict, "compress", false);
1386     Error *err = NULL;
1387     DriveBackup backup = {
1388         .device = (char *)device,
1389         .target = (char *)filename,
1390         .has_format = !!format,
1391         .format = (char *)format,
1392         .sync = full ? MIRROR_SYNC_MODE_FULL : MIRROR_SYNC_MODE_TOP,
1393         .has_mode = true,
1394         .mode = reuse ? NEW_IMAGE_MODE_EXISTING : NEW_IMAGE_MODE_ABSOLUTE_PATHS,
1395         .has_compress = !!compress,
1396         .compress = compress,
1397     };
1398 
1399     if (!filename) {
1400         error_setg(&err, QERR_MISSING_PARAMETER, "target");
1401         hmp_handle_error(mon, &err);
1402         return;
1403     }
1404 
1405     qmp_drive_backup(&backup, &err);
1406     hmp_handle_error(mon, &err);
1407 }
1408 
1409 void hmp_snapshot_blkdev(Monitor *mon, const QDict *qdict)
1410 {
1411     const char *device = qdict_get_str(qdict, "device");
1412     const char *filename = qdict_get_try_str(qdict, "snapshot-file");
1413     const char *format = qdict_get_try_str(qdict, "format");
1414     bool reuse = qdict_get_try_bool(qdict, "reuse", false);
1415     enum NewImageMode mode;
1416     Error *err = NULL;
1417 
1418     if (!filename) {
1419         /* In the future, if 'snapshot-file' is not specified, the snapshot
1420            will be taken internally. Today it's actually required. */
1421         error_setg(&err, QERR_MISSING_PARAMETER, "snapshot-file");
1422         hmp_handle_error(mon, &err);
1423         return;
1424     }
1425 
1426     mode = reuse ? NEW_IMAGE_MODE_EXISTING : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1427     qmp_blockdev_snapshot_sync(true, device, false, NULL,
1428                                filename, false, NULL,
1429                                !!format, format,
1430                                true, mode, &err);
1431     hmp_handle_error(mon, &err);
1432 }
1433 
1434 void hmp_snapshot_blkdev_internal(Monitor *mon, const QDict *qdict)
1435 {
1436     const char *device = qdict_get_str(qdict, "device");
1437     const char *name = qdict_get_str(qdict, "name");
1438     Error *err = NULL;
1439 
1440     qmp_blockdev_snapshot_internal_sync(device, name, &err);
1441     hmp_handle_error(mon, &err);
1442 }
1443 
1444 void hmp_snapshot_delete_blkdev_internal(Monitor *mon, const QDict *qdict)
1445 {
1446     const char *device = qdict_get_str(qdict, "device");
1447     const char *name = qdict_get_str(qdict, "name");
1448     const char *id = qdict_get_try_str(qdict, "id");
1449     Error *err = NULL;
1450 
1451     qmp_blockdev_snapshot_delete_internal_sync(device, !!id, id,
1452                                                true, name, &err);
1453     hmp_handle_error(mon, &err);
1454 }
1455 
1456 void hmp_loadvm(Monitor *mon, const QDict *qdict)
1457 {
1458     int saved_vm_running  = runstate_is_running();
1459     const char *name = qdict_get_str(qdict, "name");
1460     Error *err = NULL;
1461 
1462     vm_stop(RUN_STATE_RESTORE_VM);
1463 
1464     if (load_snapshot(name, &err) == 0 && saved_vm_running) {
1465         vm_start();
1466     }
1467     hmp_handle_error(mon, &err);
1468 }
1469 
1470 void hmp_savevm(Monitor *mon, const QDict *qdict)
1471 {
1472     Error *err = NULL;
1473 
1474     save_snapshot(qdict_get_try_str(qdict, "name"), &err);
1475     hmp_handle_error(mon, &err);
1476 }
1477 
1478 void hmp_delvm(Monitor *mon, const QDict *qdict)
1479 {
1480     BlockDriverState *bs;
1481     Error *err = NULL;
1482     const char *name = qdict_get_str(qdict, "name");
1483 
1484     if (bdrv_all_delete_snapshot(name, &bs, &err) < 0) {
1485         error_prepend(&err,
1486                       "deleting snapshot on device '%s': ",
1487                       bdrv_get_device_name(bs));
1488     }
1489     hmp_handle_error(mon, &err);
1490 }
1491 
1492 void hmp_info_snapshots(Monitor *mon, const QDict *qdict)
1493 {
1494     BlockDriverState *bs, *bs1;
1495     BdrvNextIterator it1;
1496     QEMUSnapshotInfo *sn_tab, *sn;
1497     bool no_snapshot = true;
1498     int nb_sns, i;
1499     int total;
1500     int *global_snapshots;
1501     AioContext *aio_context;
1502 
1503     typedef struct SnapshotEntry {
1504         QEMUSnapshotInfo sn;
1505         QTAILQ_ENTRY(SnapshotEntry) next;
1506     } SnapshotEntry;
1507 
1508     typedef struct ImageEntry {
1509         const char *imagename;
1510         QTAILQ_ENTRY(ImageEntry) next;
1511         QTAILQ_HEAD(, SnapshotEntry) snapshots;
1512     } ImageEntry;
1513 
1514     QTAILQ_HEAD(, ImageEntry) image_list =
1515         QTAILQ_HEAD_INITIALIZER(image_list);
1516 
1517     ImageEntry *image_entry, *next_ie;
1518     SnapshotEntry *snapshot_entry;
1519 
1520     bs = bdrv_all_find_vmstate_bs();
1521     if (!bs) {
1522         monitor_printf(mon, "No available block device supports snapshots\n");
1523         return;
1524     }
1525     aio_context = bdrv_get_aio_context(bs);
1526 
1527     aio_context_acquire(aio_context);
1528     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1529     aio_context_release(aio_context);
1530 
1531     if (nb_sns < 0) {
1532         monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);
1533         return;
1534     }
1535 
1536     for (bs1 = bdrv_first(&it1); bs1; bs1 = bdrv_next(&it1)) {
1537         int bs1_nb_sns = 0;
1538         ImageEntry *ie;
1539         SnapshotEntry *se;
1540         AioContext *ctx = bdrv_get_aio_context(bs1);
1541 
1542         aio_context_acquire(ctx);
1543         if (bdrv_can_snapshot(bs1)) {
1544             sn = NULL;
1545             bs1_nb_sns = bdrv_snapshot_list(bs1, &sn);
1546             if (bs1_nb_sns > 0) {
1547                 no_snapshot = false;
1548                 ie = g_new0(ImageEntry, 1);
1549                 ie->imagename = bdrv_get_device_name(bs1);
1550                 QTAILQ_INIT(&ie->snapshots);
1551                 QTAILQ_INSERT_TAIL(&image_list, ie, next);
1552                 for (i = 0; i < bs1_nb_sns; i++) {
1553                     se = g_new0(SnapshotEntry, 1);
1554                     se->sn = sn[i];
1555                     QTAILQ_INSERT_TAIL(&ie->snapshots, se, next);
1556                 }
1557             }
1558             g_free(sn);
1559         }
1560         aio_context_release(ctx);
1561     }
1562 
1563     if (no_snapshot) {
1564         monitor_printf(mon, "There is no snapshot available.\n");
1565         return;
1566     }
1567 
1568     global_snapshots = g_new0(int, nb_sns);
1569     total = 0;
1570     for (i = 0; i < nb_sns; i++) {
1571         SnapshotEntry *next_sn;
1572         if (bdrv_all_find_snapshot(sn_tab[i].name, &bs1) == 0) {
1573             global_snapshots[total] = i;
1574             total++;
1575             QTAILQ_FOREACH(image_entry, &image_list, next) {
1576                 QTAILQ_FOREACH_SAFE(snapshot_entry, &image_entry->snapshots,
1577                                     next, next_sn) {
1578                     if (!strcmp(sn_tab[i].name, snapshot_entry->sn.name)) {
1579                         QTAILQ_REMOVE(&image_entry->snapshots, snapshot_entry,
1580                                       next);
1581                         g_free(snapshot_entry);
1582                     }
1583                 }
1584             }
1585         }
1586     }
1587 
1588     monitor_printf(mon, "List of snapshots present on all disks:\n");
1589 
1590     if (total > 0) {
1591         bdrv_snapshot_dump(NULL);
1592         monitor_printf(mon, "\n");
1593         for (i = 0; i < total; i++) {
1594             sn = &sn_tab[global_snapshots[i]];
1595             /* The ID is not guaranteed to be the same on all images, so
1596              * overwrite it.
1597              */
1598             pstrcpy(sn->id_str, sizeof(sn->id_str), "--");
1599             bdrv_snapshot_dump(sn);
1600             monitor_printf(mon, "\n");
1601         }
1602     } else {
1603         monitor_printf(mon, "None\n");
1604     }
1605 
1606     QTAILQ_FOREACH(image_entry, &image_list, next) {
1607         if (QTAILQ_EMPTY(&image_entry->snapshots)) {
1608             continue;
1609         }
1610         monitor_printf(mon,
1611                        "\nList of partial (non-loadable) snapshots on '%s':\n",
1612                        image_entry->imagename);
1613         bdrv_snapshot_dump(NULL);
1614         monitor_printf(mon, "\n");
1615         QTAILQ_FOREACH(snapshot_entry, &image_entry->snapshots, next) {
1616             bdrv_snapshot_dump(&snapshot_entry->sn);
1617             monitor_printf(mon, "\n");
1618         }
1619     }
1620 
1621     QTAILQ_FOREACH_SAFE(image_entry, &image_list, next, next_ie) {
1622         SnapshotEntry *next_sn;
1623         QTAILQ_FOREACH_SAFE(snapshot_entry, &image_entry->snapshots, next,
1624                             next_sn) {
1625             g_free(snapshot_entry);
1626         }
1627         g_free(image_entry);
1628     }
1629     g_free(sn_tab);
1630     g_free(global_snapshots);
1631 
1632 }
1633 
1634 void hmp_announce_self(Monitor *mon, const QDict *qdict)
1635 {
1636     qmp_announce_self(migrate_announce_params(), NULL);
1637 }
1638 
1639 void hmp_migrate_cancel(Monitor *mon, const QDict *qdict)
1640 {
1641     qmp_migrate_cancel(NULL);
1642 }
1643 
1644 void hmp_migrate_continue(Monitor *mon, const QDict *qdict)
1645 {
1646     Error *err = NULL;
1647     const char *state = qdict_get_str(qdict, "state");
1648     int val = qapi_enum_parse(&MigrationStatus_lookup, state, -1, &err);
1649 
1650     if (val >= 0) {
1651         qmp_migrate_continue(val, &err);
1652     }
1653 
1654     hmp_handle_error(mon, &err);
1655 }
1656 
1657 void hmp_migrate_incoming(Monitor *mon, const QDict *qdict)
1658 {
1659     Error *err = NULL;
1660     const char *uri = qdict_get_str(qdict, "uri");
1661 
1662     qmp_migrate_incoming(uri, &err);
1663 
1664     hmp_handle_error(mon, &err);
1665 }
1666 
1667 void hmp_migrate_recover(Monitor *mon, const QDict *qdict)
1668 {
1669     Error *err = NULL;
1670     const char *uri = qdict_get_str(qdict, "uri");
1671 
1672     qmp_migrate_recover(uri, &err);
1673 
1674     hmp_handle_error(mon, &err);
1675 }
1676 
1677 void hmp_migrate_pause(Monitor *mon, const QDict *qdict)
1678 {
1679     Error *err = NULL;
1680 
1681     qmp_migrate_pause(&err);
1682 
1683     hmp_handle_error(mon, &err);
1684 }
1685 
1686 /* Kept for backwards compatibility */
1687 void hmp_migrate_set_downtime(Monitor *mon, const QDict *qdict)
1688 {
1689     double value = qdict_get_double(qdict, "value");
1690     qmp_migrate_set_downtime(value, NULL);
1691 }
1692 
1693 void hmp_migrate_set_cache_size(Monitor *mon, const QDict *qdict)
1694 {
1695     int64_t value = qdict_get_int(qdict, "value");
1696     Error *err = NULL;
1697 
1698     qmp_migrate_set_cache_size(value, &err);
1699     hmp_handle_error(mon, &err);
1700 }
1701 
1702 /* Kept for backwards compatibility */
1703 void hmp_migrate_set_speed(Monitor *mon, const QDict *qdict)
1704 {
1705     int64_t value = qdict_get_int(qdict, "value");
1706     qmp_migrate_set_speed(value, NULL);
1707 }
1708 
1709 void hmp_migrate_set_capability(Monitor *mon, const QDict *qdict)
1710 {
1711     const char *cap = qdict_get_str(qdict, "capability");
1712     bool state = qdict_get_bool(qdict, "state");
1713     Error *err = NULL;
1714     MigrationCapabilityStatusList *caps = g_malloc0(sizeof(*caps));
1715     int val;
1716 
1717     val = qapi_enum_parse(&MigrationCapability_lookup, cap, -1, &err);
1718     if (val < 0) {
1719         goto end;
1720     }
1721 
1722     caps->value = g_malloc0(sizeof(*caps->value));
1723     caps->value->capability = val;
1724     caps->value->state = state;
1725     caps->next = NULL;
1726     qmp_migrate_set_capabilities(caps, &err);
1727 
1728 end:
1729     qapi_free_MigrationCapabilityStatusList(caps);
1730     hmp_handle_error(mon, &err);
1731 }
1732 
1733 void hmp_migrate_set_parameter(Monitor *mon, const QDict *qdict)
1734 {
1735     const char *param = qdict_get_str(qdict, "parameter");
1736     const char *valuestr = qdict_get_str(qdict, "value");
1737     Visitor *v = string_input_visitor_new(valuestr);
1738     MigrateSetParameters *p = g_new0(MigrateSetParameters, 1);
1739     uint64_t valuebw = 0;
1740     uint64_t cache_size;
1741     Error *err = NULL;
1742     int val, ret;
1743 
1744     val = qapi_enum_parse(&MigrationParameter_lookup, param, -1, &err);
1745     if (val < 0) {
1746         goto cleanup;
1747     }
1748 
1749     switch (val) {
1750     case MIGRATION_PARAMETER_COMPRESS_LEVEL:
1751         p->has_compress_level = true;
1752         visit_type_int(v, param, &p->compress_level, &err);
1753         break;
1754     case MIGRATION_PARAMETER_COMPRESS_THREADS:
1755         p->has_compress_threads = true;
1756         visit_type_int(v, param, &p->compress_threads, &err);
1757         break;
1758     case MIGRATION_PARAMETER_COMPRESS_WAIT_THREAD:
1759         p->has_compress_wait_thread = true;
1760         visit_type_bool(v, param, &p->compress_wait_thread, &err);
1761         break;
1762     case MIGRATION_PARAMETER_DECOMPRESS_THREADS:
1763         p->has_decompress_threads = true;
1764         visit_type_int(v, param, &p->decompress_threads, &err);
1765         break;
1766     case MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL:
1767         p->has_cpu_throttle_initial = true;
1768         visit_type_int(v, param, &p->cpu_throttle_initial, &err);
1769         break;
1770     case MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT:
1771         p->has_cpu_throttle_increment = true;
1772         visit_type_int(v, param, &p->cpu_throttle_increment, &err);
1773         break;
1774     case MIGRATION_PARAMETER_MAX_CPU_THROTTLE:
1775         p->has_max_cpu_throttle = true;
1776         visit_type_int(v, param, &p->max_cpu_throttle, &err);
1777         break;
1778     case MIGRATION_PARAMETER_TLS_CREDS:
1779         p->has_tls_creds = true;
1780         p->tls_creds = g_new0(StrOrNull, 1);
1781         p->tls_creds->type = QTYPE_QSTRING;
1782         visit_type_str(v, param, &p->tls_creds->u.s, &err);
1783         break;
1784     case MIGRATION_PARAMETER_TLS_HOSTNAME:
1785         p->has_tls_hostname = true;
1786         p->tls_hostname = g_new0(StrOrNull, 1);
1787         p->tls_hostname->type = QTYPE_QSTRING;
1788         visit_type_str(v, param, &p->tls_hostname->u.s, &err);
1789         break;
1790     case MIGRATION_PARAMETER_TLS_AUTHZ:
1791         p->has_tls_authz = true;
1792         p->tls_authz = g_new0(StrOrNull, 1);
1793         p->tls_authz->type = QTYPE_QSTRING;
1794         visit_type_str(v, param, &p->tls_authz->u.s, &err);
1795         break;
1796     case MIGRATION_PARAMETER_MAX_BANDWIDTH:
1797         p->has_max_bandwidth = true;
1798         /*
1799          * Can't use visit_type_size() here, because it
1800          * defaults to Bytes rather than Mebibytes.
1801          */
1802         ret = qemu_strtosz_MiB(valuestr, NULL, &valuebw);
1803         if (ret < 0 || valuebw > INT64_MAX
1804             || (size_t)valuebw != valuebw) {
1805             error_setg(&err, "Invalid size %s", valuestr);
1806             break;
1807         }
1808         p->max_bandwidth = valuebw;
1809         break;
1810     case MIGRATION_PARAMETER_DOWNTIME_LIMIT:
1811         p->has_downtime_limit = true;
1812         visit_type_int(v, param, &p->downtime_limit, &err);
1813         break;
1814     case MIGRATION_PARAMETER_X_CHECKPOINT_DELAY:
1815         p->has_x_checkpoint_delay = true;
1816         visit_type_int(v, param, &p->x_checkpoint_delay, &err);
1817         break;
1818     case MIGRATION_PARAMETER_BLOCK_INCREMENTAL:
1819         p->has_block_incremental = true;
1820         visit_type_bool(v, param, &p->block_incremental, &err);
1821         break;
1822     case MIGRATION_PARAMETER_MULTIFD_CHANNELS:
1823         p->has_multifd_channels = true;
1824         visit_type_int(v, param, &p->multifd_channels, &err);
1825         break;
1826     case MIGRATION_PARAMETER_XBZRLE_CACHE_SIZE:
1827         p->has_xbzrle_cache_size = true;
1828         visit_type_size(v, param, &cache_size, &err);
1829         if (err) {
1830             break;
1831         }
1832         if (cache_size > INT64_MAX || (size_t)cache_size != cache_size) {
1833             error_setg(&err, "Invalid size %s", valuestr);
1834             break;
1835         }
1836         p->xbzrle_cache_size = cache_size;
1837         break;
1838     case MIGRATION_PARAMETER_MAX_POSTCOPY_BANDWIDTH:
1839         p->has_max_postcopy_bandwidth = true;
1840         visit_type_size(v, param, &p->max_postcopy_bandwidth, &err);
1841         break;
1842     case MIGRATION_PARAMETER_ANNOUNCE_INITIAL:
1843         p->has_announce_initial = true;
1844         visit_type_size(v, param, &p->announce_initial, &err);
1845         break;
1846     case MIGRATION_PARAMETER_ANNOUNCE_MAX:
1847         p->has_announce_max = true;
1848         visit_type_size(v, param, &p->announce_max, &err);
1849         break;
1850     case MIGRATION_PARAMETER_ANNOUNCE_ROUNDS:
1851         p->has_announce_rounds = true;
1852         visit_type_size(v, param, &p->announce_rounds, &err);
1853         break;
1854     case MIGRATION_PARAMETER_ANNOUNCE_STEP:
1855         p->has_announce_step = true;
1856         visit_type_size(v, param, &p->announce_step, &err);
1857         break;
1858     default:
1859         assert(0);
1860     }
1861 
1862     if (err) {
1863         goto cleanup;
1864     }
1865 
1866     qmp_migrate_set_parameters(p, &err);
1867 
1868  cleanup:
1869     qapi_free_MigrateSetParameters(p);
1870     visit_free(v);
1871     hmp_handle_error(mon, &err);
1872 }
1873 
1874 void hmp_client_migrate_info(Monitor *mon, const QDict *qdict)
1875 {
1876     Error *err = NULL;
1877     const char *protocol = qdict_get_str(qdict, "protocol");
1878     const char *hostname = qdict_get_str(qdict, "hostname");
1879     bool has_port        = qdict_haskey(qdict, "port");
1880     int port             = qdict_get_try_int(qdict, "port", -1);
1881     bool has_tls_port    = qdict_haskey(qdict, "tls-port");
1882     int tls_port         = qdict_get_try_int(qdict, "tls-port", -1);
1883     const char *cert_subject = qdict_get_try_str(qdict, "cert-subject");
1884 
1885     qmp_client_migrate_info(protocol, hostname,
1886                             has_port, port, has_tls_port, tls_port,
1887                             !!cert_subject, cert_subject, &err);
1888     hmp_handle_error(mon, &err);
1889 }
1890 
1891 void hmp_migrate_start_postcopy(Monitor *mon, const QDict *qdict)
1892 {
1893     Error *err = NULL;
1894     qmp_migrate_start_postcopy(&err);
1895     hmp_handle_error(mon, &err);
1896 }
1897 
1898 void hmp_x_colo_lost_heartbeat(Monitor *mon, const QDict *qdict)
1899 {
1900     Error *err = NULL;
1901 
1902     qmp_x_colo_lost_heartbeat(&err);
1903     hmp_handle_error(mon, &err);
1904 }
1905 
1906 void hmp_set_password(Monitor *mon, const QDict *qdict)
1907 {
1908     const char *protocol  = qdict_get_str(qdict, "protocol");
1909     const char *password  = qdict_get_str(qdict, "password");
1910     const char *connected = qdict_get_try_str(qdict, "connected");
1911     Error *err = NULL;
1912 
1913     qmp_set_password(protocol, password, !!connected, connected, &err);
1914     hmp_handle_error(mon, &err);
1915 }
1916 
1917 void hmp_expire_password(Monitor *mon, const QDict *qdict)
1918 {
1919     const char *protocol  = qdict_get_str(qdict, "protocol");
1920     const char *whenstr = qdict_get_str(qdict, "time");
1921     Error *err = NULL;
1922 
1923     qmp_expire_password(protocol, whenstr, &err);
1924     hmp_handle_error(mon, &err);
1925 }
1926 
1927 void hmp_eject(Monitor *mon, const QDict *qdict)
1928 {
1929     bool force = qdict_get_try_bool(qdict, "force", false);
1930     const char *device = qdict_get_str(qdict, "device");
1931     Error *err = NULL;
1932 
1933     qmp_eject(true, device, false, NULL, true, force, &err);
1934     hmp_handle_error(mon, &err);
1935 }
1936 
1937 #ifdef CONFIG_VNC
1938 static void hmp_change_read_arg(void *opaque, const char *password,
1939                                 void *readline_opaque)
1940 {
1941     qmp_change_vnc_password(password, NULL);
1942     monitor_read_command(opaque, 1);
1943 }
1944 #endif
1945 
1946 void hmp_change(Monitor *mon, const QDict *qdict)
1947 {
1948     MonitorHMP *hmp_mon = container_of(mon, MonitorHMP, common);
1949     const char *device = qdict_get_str(qdict, "device");
1950     const char *target = qdict_get_str(qdict, "target");
1951     const char *arg = qdict_get_try_str(qdict, "arg");
1952     const char *read_only = qdict_get_try_str(qdict, "read-only-mode");
1953     BlockdevChangeReadOnlyMode read_only_mode = 0;
1954     Error *err = NULL;
1955 
1956 #ifdef CONFIG_VNC
1957     if (strcmp(device, "vnc") == 0) {
1958         if (read_only) {
1959             monitor_printf(mon,
1960                            "Parameter 'read-only-mode' is invalid for VNC\n");
1961             return;
1962         }
1963         if (strcmp(target, "passwd") == 0 ||
1964             strcmp(target, "password") == 0) {
1965             if (!arg) {
1966                 monitor_read_password(hmp_mon, hmp_change_read_arg, NULL);
1967                 return;
1968             }
1969         }
1970         qmp_change("vnc", target, !!arg, arg, &err);
1971     } else
1972 #endif
1973     {
1974         if (read_only) {
1975             read_only_mode =
1976                 qapi_enum_parse(&BlockdevChangeReadOnlyMode_lookup,
1977                                 read_only,
1978                                 BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN, &err);
1979             if (err) {
1980                 hmp_handle_error(mon, &err);
1981                 return;
1982             }
1983         }
1984 
1985         qmp_blockdev_change_medium(true, device, false, NULL, target,
1986                                    !!arg, arg, !!read_only, read_only_mode,
1987                                    &err);
1988     }
1989 
1990     hmp_handle_error(mon, &err);
1991 }
1992 
1993 void hmp_block_set_io_throttle(Monitor *mon, const QDict *qdict)
1994 {
1995     Error *err = NULL;
1996     char *device = (char *) qdict_get_str(qdict, "device");
1997     BlockIOThrottle throttle = {
1998         .bps = qdict_get_int(qdict, "bps"),
1999         .bps_rd = qdict_get_int(qdict, "bps_rd"),
2000         .bps_wr = qdict_get_int(qdict, "bps_wr"),
2001         .iops = qdict_get_int(qdict, "iops"),
2002         .iops_rd = qdict_get_int(qdict, "iops_rd"),
2003         .iops_wr = qdict_get_int(qdict, "iops_wr"),
2004     };
2005 
2006     /* qmp_block_set_io_throttle has separate parameters for the
2007      * (deprecated) block device name and the qdev ID but the HMP
2008      * version has only one, so we must decide which one to pass. */
2009     if (blk_by_name(device)) {
2010         throttle.has_device = true;
2011         throttle.device = device;
2012     } else {
2013         throttle.has_id = true;
2014         throttle.id = device;
2015     }
2016 
2017     qmp_block_set_io_throttle(&throttle, &err);
2018     hmp_handle_error(mon, &err);
2019 }
2020 
2021 void hmp_block_stream(Monitor *mon, const QDict *qdict)
2022 {
2023     Error *error = NULL;
2024     const char *device = qdict_get_str(qdict, "device");
2025     const char *base = qdict_get_try_str(qdict, "base");
2026     int64_t speed = qdict_get_try_int(qdict, "speed", 0);
2027 
2028     qmp_block_stream(true, device, device, base != NULL, base, false, NULL,
2029                      false, NULL, qdict_haskey(qdict, "speed"), speed, true,
2030                      BLOCKDEV_ON_ERROR_REPORT, false, false, false, false,
2031                      &error);
2032 
2033     hmp_handle_error(mon, &error);
2034 }
2035 
2036 void hmp_block_job_set_speed(Monitor *mon, const QDict *qdict)
2037 {
2038     Error *error = NULL;
2039     const char *device = qdict_get_str(qdict, "device");
2040     int64_t value = qdict_get_int(qdict, "speed");
2041 
2042     qmp_block_job_set_speed(device, value, &error);
2043 
2044     hmp_handle_error(mon, &error);
2045 }
2046 
2047 void hmp_block_job_cancel(Monitor *mon, const QDict *qdict)
2048 {
2049     Error *error = NULL;
2050     const char *device = qdict_get_str(qdict, "device");
2051     bool force = qdict_get_try_bool(qdict, "force", false);
2052 
2053     qmp_block_job_cancel(device, true, force, &error);
2054 
2055     hmp_handle_error(mon, &error);
2056 }
2057 
2058 void hmp_block_job_pause(Monitor *mon, const QDict *qdict)
2059 {
2060     Error *error = NULL;
2061     const char *device = qdict_get_str(qdict, "device");
2062 
2063     qmp_block_job_pause(device, &error);
2064 
2065     hmp_handle_error(mon, &error);
2066 }
2067 
2068 void hmp_block_job_resume(Monitor *mon, const QDict *qdict)
2069 {
2070     Error *error = NULL;
2071     const char *device = qdict_get_str(qdict, "device");
2072 
2073     qmp_block_job_resume(device, &error);
2074 
2075     hmp_handle_error(mon, &error);
2076 }
2077 
2078 void hmp_block_job_complete(Monitor *mon, const QDict *qdict)
2079 {
2080     Error *error = NULL;
2081     const char *device = qdict_get_str(qdict, "device");
2082 
2083     qmp_block_job_complete(device, &error);
2084 
2085     hmp_handle_error(mon, &error);
2086 }
2087 
2088 typedef struct HMPMigrationStatus
2089 {
2090     QEMUTimer *timer;
2091     Monitor *mon;
2092     bool is_block_migration;
2093 } HMPMigrationStatus;
2094 
2095 static void hmp_migrate_status_cb(void *opaque)
2096 {
2097     HMPMigrationStatus *status = opaque;
2098     MigrationInfo *info;
2099 
2100     info = qmp_query_migrate(NULL);
2101     if (!info->has_status || info->status == MIGRATION_STATUS_ACTIVE ||
2102         info->status == MIGRATION_STATUS_SETUP) {
2103         if (info->has_disk) {
2104             int progress;
2105 
2106             if (info->disk->remaining) {
2107                 progress = info->disk->transferred * 100 / info->disk->total;
2108             } else {
2109                 progress = 100;
2110             }
2111 
2112             monitor_printf(status->mon, "Completed %d %%\r", progress);
2113             monitor_flush(status->mon);
2114         }
2115 
2116         timer_mod(status->timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 1000);
2117     } else {
2118         if (status->is_block_migration) {
2119             monitor_printf(status->mon, "\n");
2120         }
2121         if (info->has_error_desc) {
2122             error_report("%s", info->error_desc);
2123         }
2124         monitor_resume(status->mon);
2125         timer_del(status->timer);
2126         timer_free(status->timer);
2127         g_free(status);
2128     }
2129 
2130     qapi_free_MigrationInfo(info);
2131 }
2132 
2133 void hmp_migrate(Monitor *mon, const QDict *qdict)
2134 {
2135     bool detach = qdict_get_try_bool(qdict, "detach", false);
2136     bool blk = qdict_get_try_bool(qdict, "blk", false);
2137     bool inc = qdict_get_try_bool(qdict, "inc", false);
2138     bool resume = qdict_get_try_bool(qdict, "resume", false);
2139     const char *uri = qdict_get_str(qdict, "uri");
2140     Error *err = NULL;
2141 
2142     qmp_migrate(uri, !!blk, blk, !!inc, inc,
2143                 false, false, true, resume, &err);
2144     if (err) {
2145         hmp_handle_error(mon, &err);
2146         return;
2147     }
2148 
2149     if (!detach) {
2150         HMPMigrationStatus *status;
2151 
2152         if (monitor_suspend(mon) < 0) {
2153             monitor_printf(mon, "terminal does not allow synchronous "
2154                            "migration, continuing detached\n");
2155             return;
2156         }
2157 
2158         status = g_malloc0(sizeof(*status));
2159         status->mon = mon;
2160         status->is_block_migration = blk || inc;
2161         status->timer = timer_new_ms(QEMU_CLOCK_REALTIME, hmp_migrate_status_cb,
2162                                           status);
2163         timer_mod(status->timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
2164     }
2165 }
2166 
2167 void hmp_device_add(Monitor *mon, const QDict *qdict)
2168 {
2169     Error *err = NULL;
2170 
2171     qmp_device_add((QDict *)qdict, NULL, &err);
2172     hmp_handle_error(mon, &err);
2173 }
2174 
2175 void hmp_device_del(Monitor *mon, const QDict *qdict)
2176 {
2177     const char *id = qdict_get_str(qdict, "id");
2178     Error *err = NULL;
2179 
2180     qmp_device_del(id, &err);
2181     hmp_handle_error(mon, &err);
2182 }
2183 
2184 void hmp_dump_guest_memory(Monitor *mon, const QDict *qdict)
2185 {
2186     Error *err = NULL;
2187     bool win_dmp = qdict_get_try_bool(qdict, "windmp", false);
2188     bool paging = qdict_get_try_bool(qdict, "paging", false);
2189     bool zlib = qdict_get_try_bool(qdict, "zlib", false);
2190     bool lzo = qdict_get_try_bool(qdict, "lzo", false);
2191     bool snappy = qdict_get_try_bool(qdict, "snappy", false);
2192     const char *file = qdict_get_str(qdict, "filename");
2193     bool has_begin = qdict_haskey(qdict, "begin");
2194     bool has_length = qdict_haskey(qdict, "length");
2195     bool has_detach = qdict_haskey(qdict, "detach");
2196     int64_t begin = 0;
2197     int64_t length = 0;
2198     bool detach = false;
2199     enum DumpGuestMemoryFormat dump_format = DUMP_GUEST_MEMORY_FORMAT_ELF;
2200     char *prot;
2201 
2202     if (zlib + lzo + snappy + win_dmp > 1) {
2203         error_setg(&err, "only one of '-z|-l|-s|-w' can be set");
2204         hmp_handle_error(mon, &err);
2205         return;
2206     }
2207 
2208     if (win_dmp) {
2209         dump_format = DUMP_GUEST_MEMORY_FORMAT_WIN_DMP;
2210     }
2211 
2212     if (zlib) {
2213         dump_format = DUMP_GUEST_MEMORY_FORMAT_KDUMP_ZLIB;
2214     }
2215 
2216     if (lzo) {
2217         dump_format = DUMP_GUEST_MEMORY_FORMAT_KDUMP_LZO;
2218     }
2219 
2220     if (snappy) {
2221         dump_format = DUMP_GUEST_MEMORY_FORMAT_KDUMP_SNAPPY;
2222     }
2223 
2224     if (has_begin) {
2225         begin = qdict_get_int(qdict, "begin");
2226     }
2227     if (has_length) {
2228         length = qdict_get_int(qdict, "length");
2229     }
2230     if (has_detach) {
2231         detach = qdict_get_bool(qdict, "detach");
2232     }
2233 
2234     prot = g_strconcat("file:", file, NULL);
2235 
2236     qmp_dump_guest_memory(paging, prot, true, detach, has_begin, begin,
2237                           has_length, length, true, dump_format, &err);
2238     hmp_handle_error(mon, &err);
2239     g_free(prot);
2240 }
2241 
2242 void hmp_netdev_add(Monitor *mon, const QDict *qdict)
2243 {
2244     Error *err = NULL;
2245     QemuOpts *opts;
2246 
2247     opts = qemu_opts_from_qdict(qemu_find_opts("netdev"), qdict, &err);
2248     if (err) {
2249         goto out;
2250     }
2251 
2252     netdev_add(opts, &err);
2253     if (err) {
2254         qemu_opts_del(opts);
2255     }
2256 
2257 out:
2258     hmp_handle_error(mon, &err);
2259 }
2260 
2261 void hmp_netdev_del(Monitor *mon, const QDict *qdict)
2262 {
2263     const char *id = qdict_get_str(qdict, "id");
2264     Error *err = NULL;
2265 
2266     qmp_netdev_del(id, &err);
2267     hmp_handle_error(mon, &err);
2268 }
2269 
2270 void hmp_object_add(Monitor *mon, const QDict *qdict)
2271 {
2272     Error *err = NULL;
2273     QemuOpts *opts;
2274     Object *obj = NULL;
2275 
2276     opts = qemu_opts_from_qdict(qemu_find_opts("object"), qdict, &err);
2277     if (err) {
2278         hmp_handle_error(mon, &err);
2279         return;
2280     }
2281 
2282     obj = user_creatable_add_opts(opts, &err);
2283     qemu_opts_del(opts);
2284 
2285     if (err) {
2286         hmp_handle_error(mon, &err);
2287     }
2288     if (obj) {
2289         object_unref(obj);
2290     }
2291 }
2292 
2293 void hmp_getfd(Monitor *mon, const QDict *qdict)
2294 {
2295     const char *fdname = qdict_get_str(qdict, "fdname");
2296     Error *err = NULL;
2297 
2298     qmp_getfd(fdname, &err);
2299     hmp_handle_error(mon, &err);
2300 }
2301 
2302 void hmp_closefd(Monitor *mon, const QDict *qdict)
2303 {
2304     const char *fdname = qdict_get_str(qdict, "fdname");
2305     Error *err = NULL;
2306 
2307     qmp_closefd(fdname, &err);
2308     hmp_handle_error(mon, &err);
2309 }
2310 
2311 void hmp_sendkey(Monitor *mon, const QDict *qdict)
2312 {
2313     const char *keys = qdict_get_str(qdict, "keys");
2314     KeyValueList *keylist, *head = NULL, *tmp = NULL;
2315     int has_hold_time = qdict_haskey(qdict, "hold-time");
2316     int hold_time = qdict_get_try_int(qdict, "hold-time", -1);
2317     Error *err = NULL;
2318     const char *separator;
2319     int keyname_len;
2320 
2321     while (1) {
2322         separator = qemu_strchrnul(keys, '-');
2323         keyname_len = separator - keys;
2324 
2325         /* Be compatible with old interface, convert user inputted "<" */
2326         if (keys[0] == '<' && keyname_len == 1) {
2327             keys = "less";
2328             keyname_len = 4;
2329         }
2330 
2331         keylist = g_malloc0(sizeof(*keylist));
2332         keylist->value = g_malloc0(sizeof(*keylist->value));
2333 
2334         if (!head) {
2335             head = keylist;
2336         }
2337         if (tmp) {
2338             tmp->next = keylist;
2339         }
2340         tmp = keylist;
2341 
2342         if (strstart(keys, "0x", NULL)) {
2343             char *endp;
2344             int value = strtoul(keys, &endp, 0);
2345             assert(endp <= keys + keyname_len);
2346             if (endp != keys + keyname_len) {
2347                 goto err_out;
2348             }
2349             keylist->value->type = KEY_VALUE_KIND_NUMBER;
2350             keylist->value->u.number.data = value;
2351         } else {
2352             int idx = index_from_key(keys, keyname_len);
2353             if (idx == Q_KEY_CODE__MAX) {
2354                 goto err_out;
2355             }
2356             keylist->value->type = KEY_VALUE_KIND_QCODE;
2357             keylist->value->u.qcode.data = idx;
2358         }
2359 
2360         if (!*separator) {
2361             break;
2362         }
2363         keys = separator + 1;
2364     }
2365 
2366     qmp_send_key(head, has_hold_time, hold_time, &err);
2367     hmp_handle_error(mon, &err);
2368 
2369 out:
2370     qapi_free_KeyValueList(head);
2371     return;
2372 
2373 err_out:
2374     monitor_printf(mon, "invalid parameter: %.*s\n", keyname_len, keys);
2375     goto out;
2376 }
2377 
2378 void hmp_screendump(Monitor *mon, const QDict *qdict)
2379 {
2380     const char *filename = qdict_get_str(qdict, "filename");
2381     const char *id = qdict_get_try_str(qdict, "device");
2382     int64_t head = qdict_get_try_int(qdict, "head", 0);
2383     Error *err = NULL;
2384 
2385     qmp_screendump(filename, id != NULL, id, id != NULL, head, &err);
2386     hmp_handle_error(mon, &err);
2387 }
2388 
2389 void hmp_nbd_server_start(Monitor *mon, const QDict *qdict)
2390 {
2391     const char *uri = qdict_get_str(qdict, "uri");
2392     bool writable = qdict_get_try_bool(qdict, "writable", false);
2393     bool all = qdict_get_try_bool(qdict, "all", false);
2394     Error *local_err = NULL;
2395     BlockInfoList *block_list, *info;
2396     SocketAddress *addr;
2397 
2398     if (writable && !all) {
2399         error_setg(&local_err, "-w only valid together with -a");
2400         goto exit;
2401     }
2402 
2403     /* First check if the address is valid and start the server.  */
2404     addr = socket_parse(uri, &local_err);
2405     if (local_err != NULL) {
2406         goto exit;
2407     }
2408 
2409     nbd_server_start(addr, NULL, NULL, &local_err);
2410     qapi_free_SocketAddress(addr);
2411     if (local_err != NULL) {
2412         goto exit;
2413     }
2414 
2415     if (!all) {
2416         return;
2417     }
2418 
2419     /* Then try adding all block devices.  If one fails, close all and
2420      * exit.
2421      */
2422     block_list = qmp_query_block(NULL);
2423 
2424     for (info = block_list; info; info = info->next) {
2425         if (!info->value->has_inserted) {
2426             continue;
2427         }
2428 
2429         qmp_nbd_server_add(info->value->device, false, NULL,
2430                            true, writable, false, NULL, &local_err);
2431 
2432         if (local_err != NULL) {
2433             qmp_nbd_server_stop(NULL);
2434             break;
2435         }
2436     }
2437 
2438     qapi_free_BlockInfoList(block_list);
2439 
2440 exit:
2441     hmp_handle_error(mon, &local_err);
2442 }
2443 
2444 void hmp_nbd_server_add(Monitor *mon, const QDict *qdict)
2445 {
2446     const char *device = qdict_get_str(qdict, "device");
2447     const char *name = qdict_get_try_str(qdict, "name");
2448     bool writable = qdict_get_try_bool(qdict, "writable", false);
2449     Error *local_err = NULL;
2450 
2451     qmp_nbd_server_add(device, !!name, name, true, writable,
2452                        false, NULL, &local_err);
2453     hmp_handle_error(mon, &local_err);
2454 }
2455 
2456 void hmp_nbd_server_remove(Monitor *mon, const QDict *qdict)
2457 {
2458     const char *name = qdict_get_str(qdict, "name");
2459     bool force = qdict_get_try_bool(qdict, "force", false);
2460     Error *err = NULL;
2461 
2462     /* Rely on NBD_SERVER_REMOVE_MODE_SAFE being the default */
2463     qmp_nbd_server_remove(name, force, NBD_SERVER_REMOVE_MODE_HARD, &err);
2464     hmp_handle_error(mon, &err);
2465 }
2466 
2467 void hmp_nbd_server_stop(Monitor *mon, const QDict *qdict)
2468 {
2469     Error *err = NULL;
2470 
2471     qmp_nbd_server_stop(&err);
2472     hmp_handle_error(mon, &err);
2473 }
2474 
2475 void hmp_cpu_add(Monitor *mon, const QDict *qdict)
2476 {
2477     int cpuid;
2478     Error *err = NULL;
2479 
2480     error_report("cpu_add is deprecated, please use device_add instead");
2481 
2482     cpuid = qdict_get_int(qdict, "id");
2483     qmp_cpu_add(cpuid, &err);
2484     hmp_handle_error(mon, &err);
2485 }
2486 
2487 void hmp_chardev_add(Monitor *mon, const QDict *qdict)
2488 {
2489     const char *args = qdict_get_str(qdict, "args");
2490     Error *err = NULL;
2491     QemuOpts *opts;
2492 
2493     opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"), args, true);
2494     if (opts == NULL) {
2495         error_setg(&err, "Parsing chardev args failed");
2496     } else {
2497         qemu_chr_new_from_opts(opts, NULL, &err);
2498         qemu_opts_del(opts);
2499     }
2500     hmp_handle_error(mon, &err);
2501 }
2502 
2503 void hmp_chardev_change(Monitor *mon, const QDict *qdict)
2504 {
2505     const char *args = qdict_get_str(qdict, "args");
2506     const char *id;
2507     Error *err = NULL;
2508     ChardevBackend *backend = NULL;
2509     ChardevReturn *ret = NULL;
2510     QemuOpts *opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"), args,
2511                                              true);
2512     if (!opts) {
2513         error_setg(&err, "Parsing chardev args failed");
2514         goto end;
2515     }
2516 
2517     id = qdict_get_str(qdict, "id");
2518     if (qemu_opts_id(opts)) {
2519         error_setg(&err, "Unexpected 'id' parameter");
2520         goto end;
2521     }
2522 
2523     backend = qemu_chr_parse_opts(opts, &err);
2524     if (!backend) {
2525         goto end;
2526     }
2527 
2528     ret = qmp_chardev_change(id, backend, &err);
2529 
2530 end:
2531     qapi_free_ChardevReturn(ret);
2532     qapi_free_ChardevBackend(backend);
2533     qemu_opts_del(opts);
2534     hmp_handle_error(mon, &err);
2535 }
2536 
2537 void hmp_chardev_remove(Monitor *mon, const QDict *qdict)
2538 {
2539     Error *local_err = NULL;
2540 
2541     qmp_chardev_remove(qdict_get_str(qdict, "id"), &local_err);
2542     hmp_handle_error(mon, &local_err);
2543 }
2544 
2545 void hmp_chardev_send_break(Monitor *mon, const QDict *qdict)
2546 {
2547     Error *local_err = NULL;
2548 
2549     qmp_chardev_send_break(qdict_get_str(qdict, "id"), &local_err);
2550     hmp_handle_error(mon, &local_err);
2551 }
2552 
2553 void hmp_qemu_io(Monitor *mon, const QDict *qdict)
2554 {
2555     BlockBackend *blk;
2556     BlockBackend *local_blk = NULL;
2557     const char* device = qdict_get_str(qdict, "device");
2558     const char* command = qdict_get_str(qdict, "command");
2559     Error *err = NULL;
2560     int ret;
2561 
2562     blk = blk_by_name(device);
2563     if (!blk) {
2564         BlockDriverState *bs = bdrv_lookup_bs(NULL, device, &err);
2565         if (bs) {
2566             blk = local_blk = blk_new(bdrv_get_aio_context(bs),
2567                                       0, BLK_PERM_ALL);
2568             ret = blk_insert_bs(blk, bs, &err);
2569             if (ret < 0) {
2570                 goto fail;
2571             }
2572         } else {
2573             goto fail;
2574         }
2575     }
2576 
2577     /*
2578      * Notably absent: Proper permission management. This is sad, but it seems
2579      * almost impossible to achieve without changing the semantics and thereby
2580      * limiting the use cases of the qemu-io HMP command.
2581      *
2582      * In an ideal world we would unconditionally create a new BlockBackend for
2583      * qemuio_command(), but we have commands like 'reopen' and want them to
2584      * take effect on the exact BlockBackend whose name the user passed instead
2585      * of just on a temporary copy of it.
2586      *
2587      * Another problem is that deleting the temporary BlockBackend involves
2588      * draining all requests on it first, but some qemu-iotests cases want to
2589      * issue multiple aio_read/write requests and expect them to complete in
2590      * the background while the monitor has already returned.
2591      *
2592      * This is also what prevents us from saving the original permissions and
2593      * restoring them later: We can't revoke permissions until all requests
2594      * have completed, and we don't know when that is nor can we really let
2595      * anything else run before we have revoken them to avoid race conditions.
2596      *
2597      * What happens now is that command() in qemu-io-cmds.c can extend the
2598      * permissions if necessary for the qemu-io command. And they simply stay
2599      * extended, possibly resulting in a read-only guest device keeping write
2600      * permissions. Ugly, but it appears to be the lesser evil.
2601      */
2602     qemuio_command(blk, command);
2603 
2604 fail:
2605     blk_unref(local_blk);
2606     hmp_handle_error(mon, &err);
2607 }
2608 
2609 void hmp_object_del(Monitor *mon, const QDict *qdict)
2610 {
2611     const char *id = qdict_get_str(qdict, "id");
2612     Error *err = NULL;
2613 
2614     user_creatable_del(id, &err);
2615     hmp_handle_error(mon, &err);
2616 }
2617 
2618 void hmp_info_memdev(Monitor *mon, const QDict *qdict)
2619 {
2620     Error *err = NULL;
2621     MemdevList *memdev_list = qmp_query_memdev(&err);
2622     MemdevList *m = memdev_list;
2623     Visitor *v;
2624     char *str;
2625 
2626     while (m) {
2627         v = string_output_visitor_new(false, &str);
2628         visit_type_uint16List(v, NULL, &m->value->host_nodes, NULL);
2629         monitor_printf(mon, "memory backend: %s\n", m->value->id);
2630         monitor_printf(mon, "  size:  %" PRId64 "\n", m->value->size);
2631         monitor_printf(mon, "  merge: %s\n",
2632                        m->value->merge ? "true" : "false");
2633         monitor_printf(mon, "  dump: %s\n",
2634                        m->value->dump ? "true" : "false");
2635         monitor_printf(mon, "  prealloc: %s\n",
2636                        m->value->prealloc ? "true" : "false");
2637         monitor_printf(mon, "  policy: %s\n",
2638                        HostMemPolicy_str(m->value->policy));
2639         visit_complete(v, &str);
2640         monitor_printf(mon, "  host nodes: %s\n", str);
2641 
2642         g_free(str);
2643         visit_free(v);
2644         m = m->next;
2645     }
2646 
2647     monitor_printf(mon, "\n");
2648 
2649     qapi_free_MemdevList(memdev_list);
2650     hmp_handle_error(mon, &err);
2651 }
2652 
2653 void hmp_info_memory_devices(Monitor *mon, const QDict *qdict)
2654 {
2655     Error *err = NULL;
2656     MemoryDeviceInfoList *info_list = qmp_query_memory_devices(&err);
2657     MemoryDeviceInfoList *info;
2658     MemoryDeviceInfo *value;
2659     PCDIMMDeviceInfo *di;
2660 
2661     for (info = info_list; info; info = info->next) {
2662         value = info->value;
2663 
2664         if (value) {
2665             switch (value->type) {
2666             case MEMORY_DEVICE_INFO_KIND_DIMM:
2667                 di = value->u.dimm.data;
2668                 break;
2669 
2670             case MEMORY_DEVICE_INFO_KIND_NVDIMM:
2671                 di = value->u.nvdimm.data;
2672                 break;
2673 
2674             default:
2675                 di = NULL;
2676                 break;
2677             }
2678 
2679             if (di) {
2680                 monitor_printf(mon, "Memory device [%s]: \"%s\"\n",
2681                                MemoryDeviceInfoKind_str(value->type),
2682                                di->id ? di->id : "");
2683                 monitor_printf(mon, "  addr: 0x%" PRIx64 "\n", di->addr);
2684                 monitor_printf(mon, "  slot: %" PRId64 "\n", di->slot);
2685                 monitor_printf(mon, "  node: %" PRId64 "\n", di->node);
2686                 monitor_printf(mon, "  size: %" PRIu64 "\n", di->size);
2687                 monitor_printf(mon, "  memdev: %s\n", di->memdev);
2688                 monitor_printf(mon, "  hotplugged: %s\n",
2689                                di->hotplugged ? "true" : "false");
2690                 monitor_printf(mon, "  hotpluggable: %s\n",
2691                                di->hotpluggable ? "true" : "false");
2692             }
2693         }
2694     }
2695 
2696     qapi_free_MemoryDeviceInfoList(info_list);
2697     hmp_handle_error(mon, &err);
2698 }
2699 
2700 void hmp_info_iothreads(Monitor *mon, const QDict *qdict)
2701 {
2702     IOThreadInfoList *info_list = qmp_query_iothreads(NULL);
2703     IOThreadInfoList *info;
2704     IOThreadInfo *value;
2705 
2706     for (info = info_list; info; info = info->next) {
2707         value = info->value;
2708         monitor_printf(mon, "%s:\n", value->id);
2709         monitor_printf(mon, "  thread_id=%" PRId64 "\n", value->thread_id);
2710         monitor_printf(mon, "  poll-max-ns=%" PRId64 "\n", value->poll_max_ns);
2711         monitor_printf(mon, "  poll-grow=%" PRId64 "\n", value->poll_grow);
2712         monitor_printf(mon, "  poll-shrink=%" PRId64 "\n", value->poll_shrink);
2713     }
2714 
2715     qapi_free_IOThreadInfoList(info_list);
2716 }
2717 
2718 void hmp_rocker(Monitor *mon, const QDict *qdict)
2719 {
2720     const char *name = qdict_get_str(qdict, "name");
2721     RockerSwitch *rocker;
2722     Error *err = NULL;
2723 
2724     rocker = qmp_query_rocker(name, &err);
2725     if (err != NULL) {
2726         hmp_handle_error(mon, &err);
2727         return;
2728     }
2729 
2730     monitor_printf(mon, "name: %s\n", rocker->name);
2731     monitor_printf(mon, "id: 0x%" PRIx64 "\n", rocker->id);
2732     monitor_printf(mon, "ports: %d\n", rocker->ports);
2733 
2734     qapi_free_RockerSwitch(rocker);
2735 }
2736 
2737 void hmp_rocker_ports(Monitor *mon, const QDict *qdict)
2738 {
2739     RockerPortList *list, *port;
2740     const char *name = qdict_get_str(qdict, "name");
2741     Error *err = NULL;
2742 
2743     list = qmp_query_rocker_ports(name, &err);
2744     if (err != NULL) {
2745         hmp_handle_error(mon, &err);
2746         return;
2747     }
2748 
2749     monitor_printf(mon, "            ena/    speed/ auto\n");
2750     monitor_printf(mon, "      port  link    duplex neg?\n");
2751 
2752     for (port = list; port; port = port->next) {
2753         monitor_printf(mon, "%10s  %-4s   %-3s  %2s  %-3s\n",
2754                        port->value->name,
2755                        port->value->enabled ? port->value->link_up ?
2756                        "up" : "down" : "!ena",
2757                        port->value->speed == 10000 ? "10G" : "??",
2758                        port->value->duplex ? "FD" : "HD",
2759                        port->value->autoneg ? "Yes" : "No");
2760     }
2761 
2762     qapi_free_RockerPortList(list);
2763 }
2764 
2765 void hmp_rocker_of_dpa_flows(Monitor *mon, const QDict *qdict)
2766 {
2767     RockerOfDpaFlowList *list, *info;
2768     const char *name = qdict_get_str(qdict, "name");
2769     uint32_t tbl_id = qdict_get_try_int(qdict, "tbl_id", -1);
2770     Error *err = NULL;
2771 
2772     list = qmp_query_rocker_of_dpa_flows(name, tbl_id != -1, tbl_id, &err);
2773     if (err != NULL) {
2774         hmp_handle_error(mon, &err);
2775         return;
2776     }
2777 
2778     monitor_printf(mon, "prio tbl hits key(mask) --> actions\n");
2779 
2780     for (info = list; info; info = info->next) {
2781         RockerOfDpaFlow *flow = info->value;
2782         RockerOfDpaFlowKey *key = flow->key;
2783         RockerOfDpaFlowMask *mask = flow->mask;
2784         RockerOfDpaFlowAction *action = flow->action;
2785 
2786         if (flow->hits) {
2787             monitor_printf(mon, "%-4d %-3d %-4" PRIu64,
2788                            key->priority, key->tbl_id, flow->hits);
2789         } else {
2790             monitor_printf(mon, "%-4d %-3d     ",
2791                            key->priority, key->tbl_id);
2792         }
2793 
2794         if (key->has_in_pport) {
2795             monitor_printf(mon, " pport %d", key->in_pport);
2796             if (mask->has_in_pport) {
2797                 monitor_printf(mon, "(0x%x)", mask->in_pport);
2798             }
2799         }
2800 
2801         if (key->has_vlan_id) {
2802             monitor_printf(mon, " vlan %d",
2803                            key->vlan_id & VLAN_VID_MASK);
2804             if (mask->has_vlan_id) {
2805                 monitor_printf(mon, "(0x%x)", mask->vlan_id);
2806             }
2807         }
2808 
2809         if (key->has_tunnel_id) {
2810             monitor_printf(mon, " tunnel %d", key->tunnel_id);
2811             if (mask->has_tunnel_id) {
2812                 monitor_printf(mon, "(0x%x)", mask->tunnel_id);
2813             }
2814         }
2815 
2816         if (key->has_eth_type) {
2817             switch (key->eth_type) {
2818             case 0x0806:
2819                 monitor_printf(mon, " ARP");
2820                 break;
2821             case 0x0800:
2822                 monitor_printf(mon, " IP");
2823                 break;
2824             case 0x86dd:
2825                 monitor_printf(mon, " IPv6");
2826                 break;
2827             case 0x8809:
2828                 monitor_printf(mon, " LACP");
2829                 break;
2830             case 0x88cc:
2831                 monitor_printf(mon, " LLDP");
2832                 break;
2833             default:
2834                 monitor_printf(mon, " eth type 0x%04x", key->eth_type);
2835                 break;
2836             }
2837         }
2838 
2839         if (key->has_eth_src) {
2840             if ((strcmp(key->eth_src, "01:00:00:00:00:00") == 0) &&
2841                 (mask->has_eth_src) &&
2842                 (strcmp(mask->eth_src, "01:00:00:00:00:00") == 0)) {
2843                 monitor_printf(mon, " src <any mcast/bcast>");
2844             } else if ((strcmp(key->eth_src, "00:00:00:00:00:00") == 0) &&
2845                 (mask->has_eth_src) &&
2846                 (strcmp(mask->eth_src, "01:00:00:00:00:00") == 0)) {
2847                 monitor_printf(mon, " src <any ucast>");
2848             } else {
2849                 monitor_printf(mon, " src %s", key->eth_src);
2850                 if (mask->has_eth_src) {
2851                     monitor_printf(mon, "(%s)", mask->eth_src);
2852                 }
2853             }
2854         }
2855 
2856         if (key->has_eth_dst) {
2857             if ((strcmp(key->eth_dst, "01:00:00:00:00:00") == 0) &&
2858                 (mask->has_eth_dst) &&
2859                 (strcmp(mask->eth_dst, "01:00:00:00:00:00") == 0)) {
2860                 monitor_printf(mon, " dst <any mcast/bcast>");
2861             } else if ((strcmp(key->eth_dst, "00:00:00:00:00:00") == 0) &&
2862                 (mask->has_eth_dst) &&
2863                 (strcmp(mask->eth_dst, "01:00:00:00:00:00") == 0)) {
2864                 monitor_printf(mon, " dst <any ucast>");
2865             } else {
2866                 monitor_printf(mon, " dst %s", key->eth_dst);
2867                 if (mask->has_eth_dst) {
2868                     monitor_printf(mon, "(%s)", mask->eth_dst);
2869                 }
2870             }
2871         }
2872 
2873         if (key->has_ip_proto) {
2874             monitor_printf(mon, " proto %d", key->ip_proto);
2875             if (mask->has_ip_proto) {
2876                 monitor_printf(mon, "(0x%x)", mask->ip_proto);
2877             }
2878         }
2879 
2880         if (key->has_ip_tos) {
2881             monitor_printf(mon, " TOS %d", key->ip_tos);
2882             if (mask->has_ip_tos) {
2883                 monitor_printf(mon, "(0x%x)", mask->ip_tos);
2884             }
2885         }
2886 
2887         if (key->has_ip_dst) {
2888             monitor_printf(mon, " dst %s", key->ip_dst);
2889         }
2890 
2891         if (action->has_goto_tbl || action->has_group_id ||
2892             action->has_new_vlan_id) {
2893             monitor_printf(mon, " -->");
2894         }
2895 
2896         if (action->has_new_vlan_id) {
2897             monitor_printf(mon, " apply new vlan %d",
2898                            ntohs(action->new_vlan_id));
2899         }
2900 
2901         if (action->has_group_id) {
2902             monitor_printf(mon, " write group 0x%08x", action->group_id);
2903         }
2904 
2905         if (action->has_goto_tbl) {
2906             monitor_printf(mon, " goto tbl %d", action->goto_tbl);
2907         }
2908 
2909         monitor_printf(mon, "\n");
2910     }
2911 
2912     qapi_free_RockerOfDpaFlowList(list);
2913 }
2914 
2915 void hmp_rocker_of_dpa_groups(Monitor *mon, const QDict *qdict)
2916 {
2917     RockerOfDpaGroupList *list, *g;
2918     const char *name = qdict_get_str(qdict, "name");
2919     uint8_t type = qdict_get_try_int(qdict, "type", 9);
2920     Error *err = NULL;
2921     bool set = false;
2922 
2923     list = qmp_query_rocker_of_dpa_groups(name, type != 9, type, &err);
2924     if (err != NULL) {
2925         hmp_handle_error(mon, &err);
2926         return;
2927     }
2928 
2929     monitor_printf(mon, "id (decode) --> buckets\n");
2930 
2931     for (g = list; g; g = g->next) {
2932         RockerOfDpaGroup *group = g->value;
2933 
2934         monitor_printf(mon, "0x%08x", group->id);
2935 
2936         monitor_printf(mon, " (type %s", group->type == 0 ? "L2 interface" :
2937                                          group->type == 1 ? "L2 rewrite" :
2938                                          group->type == 2 ? "L3 unicast" :
2939                                          group->type == 3 ? "L2 multicast" :
2940                                          group->type == 4 ? "L2 flood" :
2941                                          group->type == 5 ? "L3 interface" :
2942                                          group->type == 6 ? "L3 multicast" :
2943                                          group->type == 7 ? "L3 ECMP" :
2944                                          group->type == 8 ? "L2 overlay" :
2945                                          "unknown");
2946 
2947         if (group->has_vlan_id) {
2948             monitor_printf(mon, " vlan %d", group->vlan_id);
2949         }
2950 
2951         if (group->has_pport) {
2952             monitor_printf(mon, " pport %d", group->pport);
2953         }
2954 
2955         if (group->has_index) {
2956             monitor_printf(mon, " index %d", group->index);
2957         }
2958 
2959         monitor_printf(mon, ") -->");
2960 
2961         if (group->has_set_vlan_id && group->set_vlan_id) {
2962             set = true;
2963             monitor_printf(mon, " set vlan %d",
2964                            group->set_vlan_id & VLAN_VID_MASK);
2965         }
2966 
2967         if (group->has_set_eth_src) {
2968             if (!set) {
2969                 set = true;
2970                 monitor_printf(mon, " set");
2971             }
2972             monitor_printf(mon, " src %s", group->set_eth_src);
2973         }
2974 
2975         if (group->has_set_eth_dst) {
2976             if (!set) {
2977                 set = true;
2978                 monitor_printf(mon, " set");
2979             }
2980             monitor_printf(mon, " dst %s", group->set_eth_dst);
2981         }
2982 
2983         set = false;
2984 
2985         if (group->has_ttl_check && group->ttl_check) {
2986             monitor_printf(mon, " check TTL");
2987         }
2988 
2989         if (group->has_group_id && group->group_id) {
2990             monitor_printf(mon, " group id 0x%08x", group->group_id);
2991         }
2992 
2993         if (group->has_pop_vlan && group->pop_vlan) {
2994             monitor_printf(mon, " pop vlan");
2995         }
2996 
2997         if (group->has_out_pport) {
2998             monitor_printf(mon, " out pport %d", group->out_pport);
2999         }
3000 
3001         if (group->has_group_ids) {
3002             struct uint32List *id;
3003 
3004             monitor_printf(mon, " groups [");
3005             for (id = group->group_ids; id; id = id->next) {
3006                 monitor_printf(mon, "0x%08x", id->value);
3007                 if (id->next) {
3008                     monitor_printf(mon, ",");
3009                 }
3010             }
3011             monitor_printf(mon, "]");
3012         }
3013 
3014         monitor_printf(mon, "\n");
3015     }
3016 
3017     qapi_free_RockerOfDpaGroupList(list);
3018 }
3019 
3020 void hmp_info_dump(Monitor *mon, const QDict *qdict)
3021 {
3022     DumpQueryResult *result = qmp_query_dump(NULL);
3023 
3024     assert(result && result->status < DUMP_STATUS__MAX);
3025     monitor_printf(mon, "Status: %s\n", DumpStatus_str(result->status));
3026 
3027     if (result->status == DUMP_STATUS_ACTIVE) {
3028         float percent = 0;
3029         assert(result->total != 0);
3030         percent = 100.0 * result->completed / result->total;
3031         monitor_printf(mon, "Finished: %.2f %%\n", percent);
3032     }
3033 
3034     qapi_free_DumpQueryResult(result);
3035 }
3036 
3037 void hmp_info_ramblock(Monitor *mon, const QDict *qdict)
3038 {
3039     ram_block_dump(mon);
3040 }
3041 
3042 void hmp_hotpluggable_cpus(Monitor *mon, const QDict *qdict)
3043 {
3044     Error *err = NULL;
3045     HotpluggableCPUList *l = qmp_query_hotpluggable_cpus(&err);
3046     HotpluggableCPUList *saved = l;
3047     CpuInstanceProperties *c;
3048 
3049     if (err != NULL) {
3050         hmp_handle_error(mon, &err);
3051         return;
3052     }
3053 
3054     monitor_printf(mon, "Hotpluggable CPUs:\n");
3055     while (l) {
3056         monitor_printf(mon, "  type: \"%s\"\n", l->value->type);
3057         monitor_printf(mon, "  vcpus_count: \"%" PRIu64 "\"\n",
3058                        l->value->vcpus_count);
3059         if (l->value->has_qom_path) {
3060             monitor_printf(mon, "  qom_path: \"%s\"\n", l->value->qom_path);
3061         }
3062 
3063         c = l->value->props;
3064         monitor_printf(mon, "  CPUInstance Properties:\n");
3065         if (c->has_node_id) {
3066             monitor_printf(mon, "    node-id: \"%" PRIu64 "\"\n", c->node_id);
3067         }
3068         if (c->has_socket_id) {
3069             monitor_printf(mon, "    socket-id: \"%" PRIu64 "\"\n", c->socket_id);
3070         }
3071         if (c->has_core_id) {
3072             monitor_printf(mon, "    core-id: \"%" PRIu64 "\"\n", c->core_id);
3073         }
3074         if (c->has_thread_id) {
3075             monitor_printf(mon, "    thread-id: \"%" PRIu64 "\"\n", c->thread_id);
3076         }
3077 
3078         l = l->next;
3079     }
3080 
3081     qapi_free_HotpluggableCPUList(saved);
3082 }
3083 
3084 void hmp_info_vm_generation_id(Monitor *mon, const QDict *qdict)
3085 {
3086     Error *err = NULL;
3087     GuidInfo *info = qmp_query_vm_generation_id(&err);
3088     if (info) {
3089         monitor_printf(mon, "%s\n", info->guid);
3090     }
3091     hmp_handle_error(mon, &err);
3092     qapi_free_GuidInfo(info);
3093 }
3094 
3095 void hmp_info_memory_size_summary(Monitor *mon, const QDict *qdict)
3096 {
3097     Error *err = NULL;
3098     MemoryInfo *info = qmp_query_memory_size_summary(&err);
3099     if (info) {
3100         monitor_printf(mon, "base memory: %" PRIu64 "\n",
3101                        info->base_memory);
3102 
3103         if (info->has_plugged_memory) {
3104             monitor_printf(mon, "plugged memory: %" PRIu64 "\n",
3105                            info->plugged_memory);
3106         }
3107 
3108         qapi_free_MemoryInfo(info);
3109     }
3110     hmp_handle_error(mon, &err);
3111 }
3112