xref: /qemu/block/qapi.c (revision e4418354)
1 /*
2  * Block layer qmp and info dump related functions
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/cutils.h"
27 #include "block/qapi.h"
28 #include "block/block_int.h"
29 #include "block/throttle-groups.h"
30 #include "block/write-threshold.h"
31 #include "qapi/error.h"
32 #include "qapi/qapi-commands-block-core.h"
33 #include "qapi/qobject-output-visitor.h"
34 #include "qapi/qapi-visit-block-core.h"
35 #include "qapi/qmp/qbool.h"
36 #include "qapi/qmp/qdict.h"
37 #include "qapi/qmp/qlist.h"
38 #include "qapi/qmp/qnum.h"
39 #include "qapi/qmp/qstring.h"
40 #include "qemu/qemu-print.h"
41 #include "sysemu/block-backend.h"
42 #include "qemu/cutils.h"
43 
44 BlockDeviceInfo *bdrv_block_device_info(BlockBackend *blk,
45                                         BlockDriverState *bs,
46                                         bool flat,
47                                         Error **errp)
48 {
49     ImageInfo **p_image_info;
50     BlockDriverState *bs0, *backing;
51     BlockDeviceInfo *info;
52 
53     if (!bs->drv) {
54         error_setg(errp, "Block device %s is ejected", bs->node_name);
55         return NULL;
56     }
57 
58     bdrv_refresh_filename(bs);
59 
60     info = g_malloc0(sizeof(*info));
61     info->file                   = g_strdup(bs->filename);
62     info->ro                     = bdrv_is_read_only(bs);
63     info->drv                    = g_strdup(bs->drv->format_name);
64     info->encrypted              = bs->encrypted;
65 
66     info->cache = g_new(BlockdevCacheInfo, 1);
67     *info->cache = (BlockdevCacheInfo) {
68         .writeback      = blk ? blk_enable_write_cache(blk) : true,
69         .direct         = !!(bs->open_flags & BDRV_O_NOCACHE),
70         .no_flush       = !!(bs->open_flags & BDRV_O_NO_FLUSH),
71     };
72 
73     if (bs->node_name[0]) {
74         info->node_name = g_strdup(bs->node_name);
75     }
76 
77     backing = bdrv_cow_bs(bs);
78     if (backing) {
79         info->backing_file = g_strdup(backing->filename);
80     }
81 
82     if (!QLIST_EMPTY(&bs->dirty_bitmaps)) {
83         info->has_dirty_bitmaps = true;
84         info->dirty_bitmaps = bdrv_query_dirty_bitmaps(bs);
85     }
86 
87     info->detect_zeroes = bs->detect_zeroes;
88 
89     if (blk && blk_get_public(blk)->throttle_group_member.throttle_state) {
90         ThrottleConfig cfg;
91         BlockBackendPublic *blkp = blk_get_public(blk);
92 
93         throttle_group_get_config(&blkp->throttle_group_member, &cfg);
94 
95         info->bps     = cfg.buckets[THROTTLE_BPS_TOTAL].avg;
96         info->bps_rd  = cfg.buckets[THROTTLE_BPS_READ].avg;
97         info->bps_wr  = cfg.buckets[THROTTLE_BPS_WRITE].avg;
98 
99         info->iops    = cfg.buckets[THROTTLE_OPS_TOTAL].avg;
100         info->iops_rd = cfg.buckets[THROTTLE_OPS_READ].avg;
101         info->iops_wr = cfg.buckets[THROTTLE_OPS_WRITE].avg;
102 
103         info->has_bps_max     = cfg.buckets[THROTTLE_BPS_TOTAL].max;
104         info->bps_max         = cfg.buckets[THROTTLE_BPS_TOTAL].max;
105         info->has_bps_rd_max  = cfg.buckets[THROTTLE_BPS_READ].max;
106         info->bps_rd_max      = cfg.buckets[THROTTLE_BPS_READ].max;
107         info->has_bps_wr_max  = cfg.buckets[THROTTLE_BPS_WRITE].max;
108         info->bps_wr_max      = cfg.buckets[THROTTLE_BPS_WRITE].max;
109 
110         info->has_iops_max    = cfg.buckets[THROTTLE_OPS_TOTAL].max;
111         info->iops_max        = cfg.buckets[THROTTLE_OPS_TOTAL].max;
112         info->has_iops_rd_max = cfg.buckets[THROTTLE_OPS_READ].max;
113         info->iops_rd_max     = cfg.buckets[THROTTLE_OPS_READ].max;
114         info->has_iops_wr_max = cfg.buckets[THROTTLE_OPS_WRITE].max;
115         info->iops_wr_max     = cfg.buckets[THROTTLE_OPS_WRITE].max;
116 
117         info->has_bps_max_length     = info->has_bps_max;
118         info->bps_max_length         =
119             cfg.buckets[THROTTLE_BPS_TOTAL].burst_length;
120         info->has_bps_rd_max_length  = info->has_bps_rd_max;
121         info->bps_rd_max_length      =
122             cfg.buckets[THROTTLE_BPS_READ].burst_length;
123         info->has_bps_wr_max_length  = info->has_bps_wr_max;
124         info->bps_wr_max_length      =
125             cfg.buckets[THROTTLE_BPS_WRITE].burst_length;
126 
127         info->has_iops_max_length    = info->has_iops_max;
128         info->iops_max_length        =
129             cfg.buckets[THROTTLE_OPS_TOTAL].burst_length;
130         info->has_iops_rd_max_length = info->has_iops_rd_max;
131         info->iops_rd_max_length     =
132             cfg.buckets[THROTTLE_OPS_READ].burst_length;
133         info->has_iops_wr_max_length = info->has_iops_wr_max;
134         info->iops_wr_max_length     =
135             cfg.buckets[THROTTLE_OPS_WRITE].burst_length;
136 
137         info->has_iops_size = cfg.op_size;
138         info->iops_size = cfg.op_size;
139 
140         info->group =
141             g_strdup(throttle_group_get_name(&blkp->throttle_group_member));
142     }
143 
144     info->write_threshold = bdrv_write_threshold_get(bs);
145 
146     bs0 = bs;
147     p_image_info = &info->image;
148     info->backing_file_depth = 0;
149     while (1) {
150         Error *local_err = NULL;
151         bdrv_query_image_info(bs0, p_image_info, &local_err);
152         if (local_err) {
153             error_propagate(errp, local_err);
154             qapi_free_BlockDeviceInfo(info);
155             return NULL;
156         }
157 
158         /* stop gathering data for flat output */
159         if (flat) {
160             break;
161         }
162 
163         if (bs0->drv && bdrv_filter_or_cow_child(bs0)) {
164             /*
165              * Put any filtered child here (for backwards compatibility to when
166              * we put bs0->backing here, which might be any filtered child).
167              */
168             info->backing_file_depth++;
169             bs0 = bdrv_filter_or_cow_bs(bs0);
170             p_image_info = &((*p_image_info)->backing_image);
171         } else {
172             break;
173         }
174 
175         /* Skip automatically inserted nodes that the user isn't aware of for
176          * query-block (blk != NULL), but not for query-named-block-nodes */
177         if (blk) {
178             bs0 = bdrv_skip_implicit_filters(bs0);
179         }
180     }
181 
182     return info;
183 }
184 
185 /*
186  * Returns 0 on success, with *p_list either set to describe snapshot
187  * information, or NULL because there are no snapshots.  Returns -errno on
188  * error, with *p_list untouched.
189  */
190 int bdrv_query_snapshot_info_list(BlockDriverState *bs,
191                                   SnapshotInfoList **p_list,
192                                   Error **errp)
193 {
194     int i, sn_count;
195     QEMUSnapshotInfo *sn_tab = NULL;
196     SnapshotInfoList *head = NULL, **tail = &head;
197     SnapshotInfo *info;
198 
199     sn_count = bdrv_snapshot_list(bs, &sn_tab);
200     if (sn_count < 0) {
201         const char *dev = bdrv_get_device_name(bs);
202         switch (sn_count) {
203         case -ENOMEDIUM:
204             error_setg(errp, "Device '%s' is not inserted", dev);
205             break;
206         case -ENOTSUP:
207             error_setg(errp,
208                        "Device '%s' does not support internal snapshots",
209                        dev);
210             break;
211         default:
212             error_setg_errno(errp, -sn_count,
213                              "Can't list snapshots of device '%s'", dev);
214             break;
215         }
216         return sn_count;
217     }
218 
219     for (i = 0; i < sn_count; i++) {
220         info = g_new0(SnapshotInfo, 1);
221         info->id            = g_strdup(sn_tab[i].id_str);
222         info->name          = g_strdup(sn_tab[i].name);
223         info->vm_state_size = sn_tab[i].vm_state_size;
224         info->date_sec      = sn_tab[i].date_sec;
225         info->date_nsec     = sn_tab[i].date_nsec;
226         info->vm_clock_sec  = sn_tab[i].vm_clock_nsec / 1000000000;
227         info->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
228         info->icount        = sn_tab[i].icount;
229         info->has_icount    = sn_tab[i].icount != -1ULL;
230 
231         QAPI_LIST_APPEND(tail, info);
232     }
233 
234     g_free(sn_tab);
235     *p_list = head;
236     return 0;
237 }
238 
239 /**
240  * bdrv_query_image_info:
241  * @bs: block device to examine
242  * @p_info: location to store image information
243  * @errp: location to store error information
244  *
245  * Store "flat" image information in @p_info.
246  *
247  * "Flat" means it does *not* query backing image information,
248  * i.e. (*pinfo)->has_backing_image will be set to false and
249  * (*pinfo)->backing_image to NULL even when the image does in fact have
250  * a backing image.
251  *
252  * @p_info will be set only on success. On error, store error in @errp.
253  */
254 void bdrv_query_image_info(BlockDriverState *bs,
255                            ImageInfo **p_info,
256                            Error **errp)
257 {
258     int64_t size;
259     const char *backing_filename;
260     BlockDriverInfo bdi;
261     int ret;
262     Error *err = NULL;
263     ImageInfo *info;
264 
265     aio_context_acquire(bdrv_get_aio_context(bs));
266 
267     size = bdrv_getlength(bs);
268     if (size < 0) {
269         error_setg_errno(errp, -size, "Can't get image size '%s'",
270                          bs->exact_filename);
271         goto out;
272     }
273 
274     bdrv_refresh_filename(bs);
275 
276     info = g_new0(ImageInfo, 1);
277     info->filename        = g_strdup(bs->filename);
278     info->format          = g_strdup(bdrv_get_format_name(bs));
279     info->virtual_size    = size;
280     info->actual_size     = bdrv_get_allocated_file_size(bs);
281     info->has_actual_size = info->actual_size >= 0;
282     if (bs->encrypted) {
283         info->encrypted = true;
284         info->has_encrypted = true;
285     }
286     if (bdrv_get_info(bs, &bdi) >= 0) {
287         if (bdi.cluster_size != 0) {
288             info->cluster_size = bdi.cluster_size;
289             info->has_cluster_size = true;
290         }
291         info->dirty_flag = bdi.is_dirty;
292         info->has_dirty_flag = true;
293     }
294     info->format_specific = bdrv_get_specific_info(bs, &err);
295     if (err) {
296         error_propagate(errp, err);
297         qapi_free_ImageInfo(info);
298         goto out;
299     }
300     backing_filename = bs->backing_file;
301     if (backing_filename[0] != '\0') {
302         char *backing_filename2;
303 
304         info->backing_filename = g_strdup(backing_filename);
305         backing_filename2 = bdrv_get_full_backing_filename(bs, NULL);
306 
307         /* Always report the full_backing_filename if present, even if it's the
308          * same as backing_filename. That they are same is useful info. */
309         if (backing_filename2) {
310             info->full_backing_filename = g_strdup(backing_filename2);
311         }
312 
313         if (bs->backing_format[0]) {
314             info->backing_filename_format = g_strdup(bs->backing_format);
315         }
316         g_free(backing_filename2);
317     }
318 
319     ret = bdrv_query_snapshot_info_list(bs, &info->snapshots, &err);
320     switch (ret) {
321     case 0:
322         if (info->snapshots) {
323             info->has_snapshots = true;
324         }
325         break;
326     /* recoverable error */
327     case -ENOMEDIUM:
328     case -ENOTSUP:
329         error_free(err);
330         break;
331     default:
332         error_propagate(errp, err);
333         qapi_free_ImageInfo(info);
334         goto out;
335     }
336 
337     *p_info = info;
338 
339 out:
340     aio_context_release(bdrv_get_aio_context(bs));
341 }
342 
343 /* @p_info will be set only on success. */
344 static void bdrv_query_info(BlockBackend *blk, BlockInfo **p_info,
345                             Error **errp)
346 {
347     BlockInfo *info = g_malloc0(sizeof(*info));
348     BlockDriverState *bs = blk_bs(blk);
349     char *qdev;
350 
351     /* Skip automatically inserted nodes that the user isn't aware of */
352     bs = bdrv_skip_implicit_filters(bs);
353 
354     info->device = g_strdup(blk_name(blk));
355     info->type = g_strdup("unknown");
356     info->locked = blk_dev_is_medium_locked(blk);
357     info->removable = blk_dev_has_removable_media(blk);
358 
359     qdev = blk_get_attached_dev_id(blk);
360     if (qdev && *qdev) {
361         info->qdev = qdev;
362     } else {
363         g_free(qdev);
364     }
365 
366     if (blk_dev_has_tray(blk)) {
367         info->has_tray_open = true;
368         info->tray_open = blk_dev_is_tray_open(blk);
369     }
370 
371     if (blk_iostatus_is_enabled(blk)) {
372         info->has_io_status = true;
373         info->io_status = blk_iostatus(blk);
374     }
375 
376     if (bs && bs->drv) {
377         info->inserted = bdrv_block_device_info(blk, bs, false, errp);
378         if (info->inserted == NULL) {
379             goto err;
380         }
381     }
382 
383     *p_info = info;
384     return;
385 
386  err:
387     qapi_free_BlockInfo(info);
388 }
389 
390 static uint64List *uint64_list(uint64_t *list, int size)
391 {
392     int i;
393     uint64List *out_list = NULL;
394     uint64List **tail = &out_list;
395 
396     for (i = 0; i < size; i++) {
397         QAPI_LIST_APPEND(tail, list[i]);
398     }
399 
400     return out_list;
401 }
402 
403 static BlockLatencyHistogramInfo *
404 bdrv_latency_histogram_stats(BlockLatencyHistogram *hist)
405 {
406     BlockLatencyHistogramInfo *info;
407 
408     if (!hist->bins) {
409         return NULL;
410     }
411 
412     info = g_new0(BlockLatencyHistogramInfo, 1);
413     info->boundaries = uint64_list(hist->boundaries, hist->nbins - 1);
414     info->bins = uint64_list(hist->bins, hist->nbins);
415     return info;
416 }
417 
418 static void bdrv_query_blk_stats(BlockDeviceStats *ds, BlockBackend *blk)
419 {
420     BlockAcctStats *stats = blk_get_stats(blk);
421     BlockAcctTimedStats *ts = NULL;
422     BlockLatencyHistogram *hgram;
423 
424     ds->rd_bytes = stats->nr_bytes[BLOCK_ACCT_READ];
425     ds->wr_bytes = stats->nr_bytes[BLOCK_ACCT_WRITE];
426     ds->unmap_bytes = stats->nr_bytes[BLOCK_ACCT_UNMAP];
427     ds->rd_operations = stats->nr_ops[BLOCK_ACCT_READ];
428     ds->wr_operations = stats->nr_ops[BLOCK_ACCT_WRITE];
429     ds->unmap_operations = stats->nr_ops[BLOCK_ACCT_UNMAP];
430 
431     ds->failed_rd_operations = stats->failed_ops[BLOCK_ACCT_READ];
432     ds->failed_wr_operations = stats->failed_ops[BLOCK_ACCT_WRITE];
433     ds->failed_flush_operations = stats->failed_ops[BLOCK_ACCT_FLUSH];
434     ds->failed_unmap_operations = stats->failed_ops[BLOCK_ACCT_UNMAP];
435 
436     ds->invalid_rd_operations = stats->invalid_ops[BLOCK_ACCT_READ];
437     ds->invalid_wr_operations = stats->invalid_ops[BLOCK_ACCT_WRITE];
438     ds->invalid_flush_operations =
439         stats->invalid_ops[BLOCK_ACCT_FLUSH];
440     ds->invalid_unmap_operations = stats->invalid_ops[BLOCK_ACCT_UNMAP];
441 
442     ds->rd_merged = stats->merged[BLOCK_ACCT_READ];
443     ds->wr_merged = stats->merged[BLOCK_ACCT_WRITE];
444     ds->unmap_merged = stats->merged[BLOCK_ACCT_UNMAP];
445     ds->flush_operations = stats->nr_ops[BLOCK_ACCT_FLUSH];
446     ds->wr_total_time_ns = stats->total_time_ns[BLOCK_ACCT_WRITE];
447     ds->rd_total_time_ns = stats->total_time_ns[BLOCK_ACCT_READ];
448     ds->flush_total_time_ns = stats->total_time_ns[BLOCK_ACCT_FLUSH];
449     ds->unmap_total_time_ns = stats->total_time_ns[BLOCK_ACCT_UNMAP];
450 
451     ds->has_idle_time_ns = stats->last_access_time_ns > 0;
452     if (ds->has_idle_time_ns) {
453         ds->idle_time_ns = block_acct_idle_time_ns(stats);
454     }
455 
456     ds->account_invalid = stats->account_invalid;
457     ds->account_failed = stats->account_failed;
458 
459     while ((ts = block_acct_interval_next(stats, ts))) {
460         BlockDeviceTimedStats *dev_stats = g_malloc0(sizeof(*dev_stats));
461 
462         TimedAverage *rd = &ts->latency[BLOCK_ACCT_READ];
463         TimedAverage *wr = &ts->latency[BLOCK_ACCT_WRITE];
464         TimedAverage *fl = &ts->latency[BLOCK_ACCT_FLUSH];
465 
466         dev_stats->interval_length = ts->interval_length;
467 
468         dev_stats->min_rd_latency_ns = timed_average_min(rd);
469         dev_stats->max_rd_latency_ns = timed_average_max(rd);
470         dev_stats->avg_rd_latency_ns = timed_average_avg(rd);
471 
472         dev_stats->min_wr_latency_ns = timed_average_min(wr);
473         dev_stats->max_wr_latency_ns = timed_average_max(wr);
474         dev_stats->avg_wr_latency_ns = timed_average_avg(wr);
475 
476         dev_stats->min_flush_latency_ns = timed_average_min(fl);
477         dev_stats->max_flush_latency_ns = timed_average_max(fl);
478         dev_stats->avg_flush_latency_ns = timed_average_avg(fl);
479 
480         dev_stats->avg_rd_queue_depth =
481             block_acct_queue_depth(ts, BLOCK_ACCT_READ);
482         dev_stats->avg_wr_queue_depth =
483             block_acct_queue_depth(ts, BLOCK_ACCT_WRITE);
484 
485         QAPI_LIST_PREPEND(ds->timed_stats, dev_stats);
486     }
487 
488     hgram = stats->latency_histogram;
489     ds->rd_latency_histogram
490         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_READ]);
491     ds->wr_latency_histogram
492         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_WRITE]);
493     ds->flush_latency_histogram
494         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_FLUSH]);
495 }
496 
497 static BlockStats *bdrv_query_bds_stats(BlockDriverState *bs,
498                                         bool blk_level)
499 {
500     BdrvChild *parent_child;
501     BlockDriverState *filter_or_cow_bs;
502     BlockStats *s = NULL;
503 
504     s = g_malloc0(sizeof(*s));
505     s->stats = g_malloc0(sizeof(*s->stats));
506 
507     if (!bs) {
508         return s;
509     }
510 
511     /* Skip automatically inserted nodes that the user isn't aware of in
512      * a BlockBackend-level command. Stay at the exact node for a node-level
513      * command. */
514     if (blk_level) {
515         bs = bdrv_skip_implicit_filters(bs);
516     }
517 
518     if (bdrv_get_node_name(bs)[0]) {
519         s->node_name = g_strdup(bdrv_get_node_name(bs));
520     }
521 
522     s->stats->wr_highest_offset = stat64_get(&bs->wr_highest_offset);
523 
524     s->driver_specific = bdrv_get_specific_stats(bs);
525 
526     parent_child = bdrv_primary_child(bs);
527     if (!parent_child ||
528         !(parent_child->role & (BDRV_CHILD_DATA | BDRV_CHILD_FILTERED)))
529     {
530         BdrvChild *c;
531 
532         /*
533          * Look for a unique data-storing child.  We do not need to look for
534          * filtered children, as there would be only one and it would have been
535          * the primary child.
536          */
537         parent_child = NULL;
538         QLIST_FOREACH(c, &bs->children, next) {
539             if (c->role & BDRV_CHILD_DATA) {
540                 if (parent_child) {
541                     /*
542                      * There are multiple data-storing children and we cannot
543                      * choose between them.
544                      */
545                     parent_child = NULL;
546                     break;
547                 }
548                 parent_child = c;
549             }
550         }
551     }
552     if (parent_child) {
553         s->parent = bdrv_query_bds_stats(parent_child->bs, blk_level);
554     }
555 
556     filter_or_cow_bs = bdrv_filter_or_cow_bs(bs);
557     if (blk_level && filter_or_cow_bs) {
558         /*
559          * Put any filtered or COW child here (for backwards
560          * compatibility to when we put bs0->backing here, which might
561          * be either)
562          */
563         s->backing = bdrv_query_bds_stats(filter_or_cow_bs, blk_level);
564     }
565 
566     return s;
567 }
568 
569 BlockInfoList *qmp_query_block(Error **errp)
570 {
571     BlockInfoList *head = NULL, **p_next = &head;
572     BlockBackend *blk;
573     Error *local_err = NULL;
574 
575     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
576         BlockInfoList *info;
577 
578         if (!*blk_name(blk) && !blk_get_attached_dev(blk)) {
579             continue;
580         }
581 
582         info = g_malloc0(sizeof(*info));
583         bdrv_query_info(blk, &info->value, &local_err);
584         if (local_err) {
585             error_propagate(errp, local_err);
586             g_free(info);
587             qapi_free_BlockInfoList(head);
588             return NULL;
589         }
590 
591         *p_next = info;
592         p_next = &info->next;
593     }
594 
595     return head;
596 }
597 
598 BlockStatsList *qmp_query_blockstats(bool has_query_nodes,
599                                      bool query_nodes,
600                                      Error **errp)
601 {
602     BlockStatsList *head = NULL, **tail = &head;
603     BlockBackend *blk;
604     BlockDriverState *bs;
605 
606     /* Just to be safe if query_nodes is not always initialized */
607     if (has_query_nodes && query_nodes) {
608         for (bs = bdrv_next_node(NULL); bs; bs = bdrv_next_node(bs)) {
609             AioContext *ctx = bdrv_get_aio_context(bs);
610 
611             aio_context_acquire(ctx);
612             QAPI_LIST_APPEND(tail, bdrv_query_bds_stats(bs, false));
613             aio_context_release(ctx);
614         }
615     } else {
616         for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
617             AioContext *ctx = blk_get_aio_context(blk);
618             BlockStats *s;
619             char *qdev;
620 
621             if (!*blk_name(blk) && !blk_get_attached_dev(blk)) {
622                 continue;
623             }
624 
625             aio_context_acquire(ctx);
626             s = bdrv_query_bds_stats(blk_bs(blk), true);
627             s->device = g_strdup(blk_name(blk));
628 
629             qdev = blk_get_attached_dev_id(blk);
630             if (qdev && *qdev) {
631                 s->qdev = qdev;
632             } else {
633                 g_free(qdev);
634             }
635 
636             bdrv_query_blk_stats(s->stats, blk);
637             aio_context_release(ctx);
638 
639             QAPI_LIST_APPEND(tail, s);
640         }
641     }
642 
643     return head;
644 }
645 
646 void bdrv_snapshot_dump(QEMUSnapshotInfo *sn)
647 {
648     char clock_buf[128];
649     char icount_buf[128] = {0};
650     int64_t secs;
651     char *sizing = NULL;
652 
653     if (!sn) {
654         qemu_printf("%-10s%-17s%8s%20s%13s%11s",
655                     "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK", "ICOUNT");
656     } else {
657         g_autoptr(GDateTime) date = g_date_time_new_from_unix_local(sn->date_sec);
658         g_autofree char *date_buf = g_date_time_format(date, "%Y-%m-%d %H:%M:%S");
659 
660         secs = sn->vm_clock_nsec / 1000000000;
661         snprintf(clock_buf, sizeof(clock_buf),
662                  "%02d:%02d:%02d.%03d",
663                  (int)(secs / 3600),
664                  (int)((secs / 60) % 60),
665                  (int)(secs % 60),
666                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
667         sizing = size_to_str(sn->vm_state_size);
668         if (sn->icount != -1ULL) {
669             snprintf(icount_buf, sizeof(icount_buf),
670                 "%"PRId64, sn->icount);
671         }
672         qemu_printf("%-9s %-16s %8s%20s%13s%11s",
673                     sn->id_str, sn->name,
674                     sizing,
675                     date_buf,
676                     clock_buf,
677                     icount_buf);
678     }
679     g_free(sizing);
680 }
681 
682 static void dump_qdict(int indentation, QDict *dict);
683 static void dump_qlist(int indentation, QList *list);
684 
685 static void dump_qobject(int comp_indent, QObject *obj)
686 {
687     switch (qobject_type(obj)) {
688         case QTYPE_QNUM: {
689             QNum *value = qobject_to(QNum, obj);
690             char *tmp = qnum_to_string(value);
691             qemu_printf("%s", tmp);
692             g_free(tmp);
693             break;
694         }
695         case QTYPE_QSTRING: {
696             QString *value = qobject_to(QString, obj);
697             qemu_printf("%s", qstring_get_str(value));
698             break;
699         }
700         case QTYPE_QDICT: {
701             QDict *value = qobject_to(QDict, obj);
702             dump_qdict(comp_indent, value);
703             break;
704         }
705         case QTYPE_QLIST: {
706             QList *value = qobject_to(QList, obj);
707             dump_qlist(comp_indent, value);
708             break;
709         }
710         case QTYPE_QBOOL: {
711             QBool *value = qobject_to(QBool, obj);
712             qemu_printf("%s", qbool_get_bool(value) ? "true" : "false");
713             break;
714         }
715         default:
716             abort();
717     }
718 }
719 
720 static void dump_qlist(int indentation, QList *list)
721 {
722     const QListEntry *entry;
723     int i = 0;
724 
725     for (entry = qlist_first(list); entry; entry = qlist_next(entry), i++) {
726         QType type = qobject_type(entry->value);
727         bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
728         qemu_printf("%*s[%i]:%c", indentation * 4, "", i,
729                     composite ? '\n' : ' ');
730         dump_qobject(indentation + 1, entry->value);
731         if (!composite) {
732             qemu_printf("\n");
733         }
734     }
735 }
736 
737 static void dump_qdict(int indentation, QDict *dict)
738 {
739     const QDictEntry *entry;
740 
741     for (entry = qdict_first(dict); entry; entry = qdict_next(dict, entry)) {
742         QType type = qobject_type(entry->value);
743         bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
744         char *key = g_malloc(strlen(entry->key) + 1);
745         int i;
746 
747         /* replace dashes with spaces in key (variable) names */
748         for (i = 0; entry->key[i]; i++) {
749             key[i] = entry->key[i] == '-' ? ' ' : entry->key[i];
750         }
751         key[i] = 0;
752         qemu_printf("%*s%s:%c", indentation * 4, "", key,
753                     composite ? '\n' : ' ');
754         dump_qobject(indentation + 1, entry->value);
755         if (!composite) {
756             qemu_printf("\n");
757         }
758         g_free(key);
759     }
760 }
761 
762 void bdrv_image_info_specific_dump(ImageInfoSpecific *info_spec)
763 {
764     QObject *obj, *data;
765     Visitor *v = qobject_output_visitor_new(&obj);
766 
767     visit_type_ImageInfoSpecific(v, NULL, &info_spec, &error_abort);
768     visit_complete(v, &obj);
769     data = qdict_get(qobject_to(QDict, obj), "data");
770     dump_qobject(1, data);
771     qobject_unref(obj);
772     visit_free(v);
773 }
774 
775 void bdrv_image_info_dump(ImageInfo *info)
776 {
777     char *size_buf, *dsize_buf;
778     if (!info->has_actual_size) {
779         dsize_buf = g_strdup("unavailable");
780     } else {
781         dsize_buf = size_to_str(info->actual_size);
782     }
783     size_buf = size_to_str(info->virtual_size);
784     qemu_printf("image: %s\n"
785                 "file format: %s\n"
786                 "virtual size: %s (%" PRId64 " bytes)\n"
787                 "disk size: %s\n",
788                 info->filename, info->format, size_buf,
789                 info->virtual_size,
790                 dsize_buf);
791     g_free(size_buf);
792     g_free(dsize_buf);
793 
794     if (info->has_encrypted && info->encrypted) {
795         qemu_printf("encrypted: yes\n");
796     }
797 
798     if (info->has_cluster_size) {
799         qemu_printf("cluster_size: %" PRId64 "\n",
800                     info->cluster_size);
801     }
802 
803     if (info->has_dirty_flag && info->dirty_flag) {
804         qemu_printf("cleanly shut down: no\n");
805     }
806 
807     if (info->backing_filename) {
808         qemu_printf("backing file: %s", info->backing_filename);
809         if (!info->full_backing_filename) {
810             qemu_printf(" (cannot determine actual path)");
811         } else if (strcmp(info->backing_filename,
812                           info->full_backing_filename) != 0) {
813             qemu_printf(" (actual path: %s)", info->full_backing_filename);
814         }
815         qemu_printf("\n");
816         if (info->backing_filename_format) {
817             qemu_printf("backing file format: %s\n",
818                         info->backing_filename_format);
819         }
820     }
821 
822     if (info->has_snapshots) {
823         SnapshotInfoList *elem;
824 
825         qemu_printf("Snapshot list:\n");
826         bdrv_snapshot_dump(NULL);
827         qemu_printf("\n");
828 
829         /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
830          * we convert to the block layer's native QEMUSnapshotInfo for now.
831          */
832         for (elem = info->snapshots; elem; elem = elem->next) {
833             QEMUSnapshotInfo sn = {
834                 .vm_state_size = elem->value->vm_state_size,
835                 .date_sec = elem->value->date_sec,
836                 .date_nsec = elem->value->date_nsec,
837                 .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
838                                  elem->value->vm_clock_nsec,
839                 .icount = elem->value->has_icount ?
840                           elem->value->icount : -1ULL,
841             };
842 
843             pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
844             pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
845             bdrv_snapshot_dump(&sn);
846             qemu_printf("\n");
847         }
848     }
849 
850     if (info->format_specific) {
851         qemu_printf("Format specific information:\n");
852         bdrv_image_info_specific_dump(info->format_specific);
853     }
854 }
855