xref: /qemu/block/qapi.c (revision 5e6f3db2)
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/dirty-bitmap.h"
30 #include "block/throttle-groups.h"
31 #include "block/write-threshold.h"
32 #include "qapi/error.h"
33 #include "qapi/qapi-commands-block-core.h"
34 #include "qapi/qobject-output-visitor.h"
35 #include "qapi/qapi-visit-block-core.h"
36 #include "qapi/qmp/qbool.h"
37 #include "qapi/qmp/qdict.h"
38 #include "qapi/qmp/qlist.h"
39 #include "qapi/qmp/qnum.h"
40 #include "qapi/qmp/qstring.h"
41 #include "qemu/qemu-print.h"
42 #include "sysemu/block-backend.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     ImageInfo *backing_info;
51     BlockDriverState *backing;
52     BlockDeviceInfo *info;
53     ERRP_GUARD();
54 
55     if (!bs->drv) {
56         error_setg(errp, "Block device %s is ejected", bs->node_name);
57         return NULL;
58     }
59 
60     bdrv_refresh_filename(bs);
61 
62     info = g_malloc0(sizeof(*info));
63     info->file                   = g_strdup(bs->filename);
64     info->ro                     = bdrv_is_read_only(bs);
65     info->drv                    = g_strdup(bs->drv->format_name);
66     info->encrypted              = bs->encrypted;
67 
68     info->cache = g_new(BlockdevCacheInfo, 1);
69     *info->cache = (BlockdevCacheInfo) {
70         .writeback      = blk ? blk_enable_write_cache(blk) : true,
71         .direct         = !!(bs->open_flags & BDRV_O_NOCACHE),
72         .no_flush       = !!(bs->open_flags & BDRV_O_NO_FLUSH),
73     };
74 
75     if (bs->node_name[0]) {
76         info->node_name = g_strdup(bs->node_name);
77     }
78 
79     backing = bdrv_cow_bs(bs);
80     if (backing) {
81         info->backing_file = g_strdup(backing->filename);
82     }
83 
84     if (!QLIST_EMPTY(&bs->dirty_bitmaps)) {
85         info->has_dirty_bitmaps = true;
86         info->dirty_bitmaps = bdrv_query_dirty_bitmaps(bs);
87     }
88 
89     info->detect_zeroes = bs->detect_zeroes;
90 
91     if (blk && blk_get_public(blk)->throttle_group_member.throttle_state) {
92         ThrottleConfig cfg;
93         BlockBackendPublic *blkp = blk_get_public(blk);
94 
95         throttle_group_get_config(&blkp->throttle_group_member, &cfg);
96 
97         info->bps     = cfg.buckets[THROTTLE_BPS_TOTAL].avg;
98         info->bps_rd  = cfg.buckets[THROTTLE_BPS_READ].avg;
99         info->bps_wr  = cfg.buckets[THROTTLE_BPS_WRITE].avg;
100 
101         info->iops    = cfg.buckets[THROTTLE_OPS_TOTAL].avg;
102         info->iops_rd = cfg.buckets[THROTTLE_OPS_READ].avg;
103         info->iops_wr = cfg.buckets[THROTTLE_OPS_WRITE].avg;
104 
105         info->has_bps_max     = cfg.buckets[THROTTLE_BPS_TOTAL].max;
106         info->bps_max         = cfg.buckets[THROTTLE_BPS_TOTAL].max;
107         info->has_bps_rd_max  = cfg.buckets[THROTTLE_BPS_READ].max;
108         info->bps_rd_max      = cfg.buckets[THROTTLE_BPS_READ].max;
109         info->has_bps_wr_max  = cfg.buckets[THROTTLE_BPS_WRITE].max;
110         info->bps_wr_max      = cfg.buckets[THROTTLE_BPS_WRITE].max;
111 
112         info->has_iops_max    = cfg.buckets[THROTTLE_OPS_TOTAL].max;
113         info->iops_max        = cfg.buckets[THROTTLE_OPS_TOTAL].max;
114         info->has_iops_rd_max = cfg.buckets[THROTTLE_OPS_READ].max;
115         info->iops_rd_max     = cfg.buckets[THROTTLE_OPS_READ].max;
116         info->has_iops_wr_max = cfg.buckets[THROTTLE_OPS_WRITE].max;
117         info->iops_wr_max     = cfg.buckets[THROTTLE_OPS_WRITE].max;
118 
119         info->has_bps_max_length     = info->has_bps_max;
120         info->bps_max_length         =
121             cfg.buckets[THROTTLE_BPS_TOTAL].burst_length;
122         info->has_bps_rd_max_length  = info->has_bps_rd_max;
123         info->bps_rd_max_length      =
124             cfg.buckets[THROTTLE_BPS_READ].burst_length;
125         info->has_bps_wr_max_length  = info->has_bps_wr_max;
126         info->bps_wr_max_length      =
127             cfg.buckets[THROTTLE_BPS_WRITE].burst_length;
128 
129         info->has_iops_max_length    = info->has_iops_max;
130         info->iops_max_length        =
131             cfg.buckets[THROTTLE_OPS_TOTAL].burst_length;
132         info->has_iops_rd_max_length = info->has_iops_rd_max;
133         info->iops_rd_max_length     =
134             cfg.buckets[THROTTLE_OPS_READ].burst_length;
135         info->has_iops_wr_max_length = info->has_iops_wr_max;
136         info->iops_wr_max_length     =
137             cfg.buckets[THROTTLE_OPS_WRITE].burst_length;
138 
139         info->has_iops_size = cfg.op_size;
140         info->iops_size = cfg.op_size;
141 
142         info->group =
143             g_strdup(throttle_group_get_name(&blkp->throttle_group_member));
144     }
145 
146     info->write_threshold = bdrv_write_threshold_get(bs);
147 
148     p_image_info = &info->image;
149     info->backing_file_depth = 0;
150 
151     /*
152      * Skip automatically inserted nodes that the user isn't aware of for
153      * query-block (blk != NULL), but not for query-named-block-nodes
154      */
155     bdrv_query_image_info(bs, p_image_info, flat, blk != NULL, errp);
156     if (*errp) {
157         qapi_free_BlockDeviceInfo(info);
158         return NULL;
159     }
160 
161     backing_info = info->image->backing_image;
162     while (backing_info) {
163         info->backing_file_depth++;
164         backing_info = backing_info->backing_image;
165     }
166 
167     return info;
168 }
169 
170 /*
171  * Returns 0 on success, with *p_list either set to describe snapshot
172  * information, or NULL because there are no snapshots.  Returns -errno on
173  * error, with *p_list untouched.
174  */
175 int bdrv_query_snapshot_info_list(BlockDriverState *bs,
176                                   SnapshotInfoList **p_list,
177                                   Error **errp)
178 {
179     int i, sn_count;
180     QEMUSnapshotInfo *sn_tab = NULL;
181     SnapshotInfoList *head = NULL, **tail = &head;
182     SnapshotInfo *info;
183 
184     sn_count = bdrv_snapshot_list(bs, &sn_tab);
185     if (sn_count < 0) {
186         const char *dev = bdrv_get_device_name(bs);
187         switch (sn_count) {
188         case -ENOMEDIUM:
189             error_setg(errp, "Device '%s' is not inserted", dev);
190             break;
191         case -ENOTSUP:
192             error_setg(errp,
193                        "Device '%s' does not support internal snapshots",
194                        dev);
195             break;
196         default:
197             error_setg_errno(errp, -sn_count,
198                              "Can't list snapshots of device '%s'", dev);
199             break;
200         }
201         return sn_count;
202     }
203 
204     for (i = 0; i < sn_count; i++) {
205         info = g_new0(SnapshotInfo, 1);
206         info->id            = g_strdup(sn_tab[i].id_str);
207         info->name          = g_strdup(sn_tab[i].name);
208         info->vm_state_size = sn_tab[i].vm_state_size;
209         info->date_sec      = sn_tab[i].date_sec;
210         info->date_nsec     = sn_tab[i].date_nsec;
211         info->vm_clock_sec  = sn_tab[i].vm_clock_nsec / 1000000000;
212         info->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
213         info->icount        = sn_tab[i].icount;
214         info->has_icount    = sn_tab[i].icount != -1ULL;
215 
216         QAPI_LIST_APPEND(tail, info);
217     }
218 
219     g_free(sn_tab);
220     *p_list = head;
221     return 0;
222 }
223 
224 /**
225  * Helper function for other query info functions.  Store information about @bs
226  * in @info, setting @errp on error.
227  */
228 static void bdrv_do_query_node_info(BlockDriverState *bs,
229                                     BlockNodeInfo *info,
230                                     Error **errp)
231 {
232     int64_t size;
233     const char *backing_filename;
234     BlockDriverInfo bdi;
235     int ret;
236     Error *err = NULL;
237 
238     aio_context_acquire(bdrv_get_aio_context(bs));
239 
240     size = bdrv_getlength(bs);
241     if (size < 0) {
242         error_setg_errno(errp, -size, "Can't get image size '%s'",
243                          bs->exact_filename);
244         goto out;
245     }
246 
247     bdrv_refresh_filename(bs);
248 
249     info->filename        = g_strdup(bs->filename);
250     info->format          = g_strdup(bdrv_get_format_name(bs));
251     info->virtual_size    = size;
252     info->actual_size     = bdrv_get_allocated_file_size(bs);
253     info->has_actual_size = info->actual_size >= 0;
254     if (bs->encrypted) {
255         info->encrypted = true;
256         info->has_encrypted = true;
257     }
258     if (bdrv_get_info(bs, &bdi) >= 0) {
259         if (bdi.cluster_size != 0) {
260             info->cluster_size = bdi.cluster_size;
261             info->has_cluster_size = true;
262         }
263         info->dirty_flag = bdi.is_dirty;
264         info->has_dirty_flag = true;
265     }
266     info->format_specific = bdrv_get_specific_info(bs, &err);
267     if (err) {
268         error_propagate(errp, err);
269         goto out;
270     }
271     backing_filename = bs->backing_file;
272     if (backing_filename[0] != '\0') {
273         char *backing_filename2;
274 
275         info->backing_filename = g_strdup(backing_filename);
276         backing_filename2 = bdrv_get_full_backing_filename(bs, NULL);
277 
278         /* Always report the full_backing_filename if present, even if it's the
279          * same as backing_filename. That they are same is useful info. */
280         if (backing_filename2) {
281             info->full_backing_filename = g_strdup(backing_filename2);
282         }
283 
284         if (bs->backing_format[0]) {
285             info->backing_filename_format = g_strdup(bs->backing_format);
286         }
287         g_free(backing_filename2);
288     }
289 
290     ret = bdrv_query_snapshot_info_list(bs, &info->snapshots, &err);
291     switch (ret) {
292     case 0:
293         if (info->snapshots) {
294             info->has_snapshots = true;
295         }
296         break;
297     /* recoverable error */
298     case -ENOMEDIUM:
299     case -ENOTSUP:
300         error_free(err);
301         break;
302     default:
303         error_propagate(errp, err);
304         goto out;
305     }
306 
307 out:
308     aio_context_release(bdrv_get_aio_context(bs));
309 }
310 
311 /**
312  * bdrv_query_image_info:
313  * @bs: block node to examine
314  * @p_info: location to store image information
315  * @flat: skip backing node information
316  * @skip_implicit_filters: skip implicit filters in the backing chain
317  * @errp: location to store error information
318  *
319  * Store image information in @p_info, potentially recursively covering the
320  * backing chain.
321  *
322  * If @flat is true, do not query backing image information, i.e.
323  * (*p_info)->has_backing_image will be set to false and
324  * (*p_info)->backing_image to NULL even when the image does in fact have a
325  * backing image.
326  *
327  * If @skip_implicit_filters is true, implicit filter nodes in the backing chain
328  * will be skipped when querying backing image information.
329  * (@skip_implicit_filters is ignored when @flat is true.)
330  *
331  * @p_info will be set only on success. On error, store error in @errp.
332  */
333 void bdrv_query_image_info(BlockDriverState *bs,
334                            ImageInfo **p_info,
335                            bool flat,
336                            bool skip_implicit_filters,
337                            Error **errp)
338 {
339     ImageInfo *info;
340     ERRP_GUARD();
341 
342     info = g_new0(ImageInfo, 1);
343     bdrv_do_query_node_info(bs, qapi_ImageInfo_base(info), errp);
344     if (*errp) {
345         goto fail;
346     }
347 
348     if (!flat) {
349         BlockDriverState *backing;
350 
351         /*
352          * Use any filtered child here (for backwards compatibility to when
353          * we always took bs->backing, which might be any filtered child).
354          */
355         backing = bdrv_filter_or_cow_bs(bs);
356         if (skip_implicit_filters) {
357             backing = bdrv_skip_implicit_filters(backing);
358         }
359 
360         if (backing) {
361             bdrv_query_image_info(backing, &info->backing_image, false,
362                                   skip_implicit_filters, errp);
363             if (*errp) {
364                 goto fail;
365             }
366         }
367     }
368 
369     *p_info = info;
370     return;
371 
372 fail:
373     assert(*errp);
374     qapi_free_ImageInfo(info);
375 }
376 
377 /**
378  * bdrv_query_block_graph_info:
379  * @bs: root node to start from
380  * @p_info: location to store image information
381  * @errp: location to store error information
382  *
383  * Store image information about the graph starting from @bs in @p_info.
384  *
385  * @p_info will be set only on success. On error, store error in @errp.
386  */
387 void bdrv_query_block_graph_info(BlockDriverState *bs,
388                                  BlockGraphInfo **p_info,
389                                  Error **errp)
390 {
391     BlockGraphInfo *info;
392     BlockChildInfoList **children_list_tail;
393     BdrvChild *c;
394     ERRP_GUARD();
395 
396     info = g_new0(BlockGraphInfo, 1);
397     bdrv_do_query_node_info(bs, qapi_BlockGraphInfo_base(info), errp);
398     if (*errp) {
399         goto fail;
400     }
401 
402     children_list_tail = &info->children;
403 
404     QLIST_FOREACH(c, &bs->children, next) {
405         BlockChildInfo *c_info;
406 
407         c_info = g_new0(BlockChildInfo, 1);
408         QAPI_LIST_APPEND(children_list_tail, c_info);
409 
410         c_info->name = g_strdup(c->name);
411         bdrv_query_block_graph_info(c->bs, &c_info->info, errp);
412         if (*errp) {
413             goto fail;
414         }
415     }
416 
417     *p_info = info;
418     return;
419 
420 fail:
421     assert(*errp != NULL);
422     qapi_free_BlockGraphInfo(info);
423 }
424 
425 /* @p_info will be set only on success. */
426 static void bdrv_query_info(BlockBackend *blk, BlockInfo **p_info,
427                             Error **errp)
428 {
429     BlockInfo *info = g_malloc0(sizeof(*info));
430     BlockDriverState *bs = blk_bs(blk);
431     char *qdev;
432 
433     /* Skip automatically inserted nodes that the user isn't aware of */
434     bs = bdrv_skip_implicit_filters(bs);
435 
436     info->device = g_strdup(blk_name(blk));
437     info->type = g_strdup("unknown");
438     info->locked = blk_dev_is_medium_locked(blk);
439     info->removable = blk_dev_has_removable_media(blk);
440 
441     qdev = blk_get_attached_dev_id(blk);
442     if (qdev && *qdev) {
443         info->qdev = qdev;
444     } else {
445         g_free(qdev);
446     }
447 
448     if (blk_dev_has_tray(blk)) {
449         info->has_tray_open = true;
450         info->tray_open = blk_dev_is_tray_open(blk);
451     }
452 
453     if (blk_iostatus_is_enabled(blk)) {
454         info->has_io_status = true;
455         info->io_status = blk_iostatus(blk);
456     }
457 
458     if (bs && bs->drv) {
459         info->inserted = bdrv_block_device_info(blk, bs, false, errp);
460         if (info->inserted == NULL) {
461             goto err;
462         }
463     }
464 
465     *p_info = info;
466     return;
467 
468  err:
469     qapi_free_BlockInfo(info);
470 }
471 
472 static uint64List *uint64_list(uint64_t *list, int size)
473 {
474     int i;
475     uint64List *out_list = NULL;
476     uint64List **tail = &out_list;
477 
478     for (i = 0; i < size; i++) {
479         QAPI_LIST_APPEND(tail, list[i]);
480     }
481 
482     return out_list;
483 }
484 
485 static BlockLatencyHistogramInfo *
486 bdrv_latency_histogram_stats(BlockLatencyHistogram *hist)
487 {
488     BlockLatencyHistogramInfo *info;
489 
490     if (!hist->bins) {
491         return NULL;
492     }
493 
494     info = g_new0(BlockLatencyHistogramInfo, 1);
495     info->boundaries = uint64_list(hist->boundaries, hist->nbins - 1);
496     info->bins = uint64_list(hist->bins, hist->nbins);
497     return info;
498 }
499 
500 static void bdrv_query_blk_stats(BlockDeviceStats *ds, BlockBackend *blk)
501 {
502     BlockAcctStats *stats = blk_get_stats(blk);
503     BlockAcctTimedStats *ts = NULL;
504     BlockLatencyHistogram *hgram;
505 
506     ds->rd_bytes = stats->nr_bytes[BLOCK_ACCT_READ];
507     ds->wr_bytes = stats->nr_bytes[BLOCK_ACCT_WRITE];
508     ds->zone_append_bytes = stats->nr_bytes[BLOCK_ACCT_ZONE_APPEND];
509     ds->unmap_bytes = stats->nr_bytes[BLOCK_ACCT_UNMAP];
510     ds->rd_operations = stats->nr_ops[BLOCK_ACCT_READ];
511     ds->wr_operations = stats->nr_ops[BLOCK_ACCT_WRITE];
512     ds->zone_append_operations = stats->nr_ops[BLOCK_ACCT_ZONE_APPEND];
513     ds->unmap_operations = stats->nr_ops[BLOCK_ACCT_UNMAP];
514 
515     ds->failed_rd_operations = stats->failed_ops[BLOCK_ACCT_READ];
516     ds->failed_wr_operations = stats->failed_ops[BLOCK_ACCT_WRITE];
517     ds->failed_zone_append_operations =
518         stats->failed_ops[BLOCK_ACCT_ZONE_APPEND];
519     ds->failed_flush_operations = stats->failed_ops[BLOCK_ACCT_FLUSH];
520     ds->failed_unmap_operations = stats->failed_ops[BLOCK_ACCT_UNMAP];
521 
522     ds->invalid_rd_operations = stats->invalid_ops[BLOCK_ACCT_READ];
523     ds->invalid_wr_operations = stats->invalid_ops[BLOCK_ACCT_WRITE];
524     ds->invalid_zone_append_operations =
525         stats->invalid_ops[BLOCK_ACCT_ZONE_APPEND];
526     ds->invalid_flush_operations =
527         stats->invalid_ops[BLOCK_ACCT_FLUSH];
528     ds->invalid_unmap_operations = stats->invalid_ops[BLOCK_ACCT_UNMAP];
529 
530     ds->rd_merged = stats->merged[BLOCK_ACCT_READ];
531     ds->wr_merged = stats->merged[BLOCK_ACCT_WRITE];
532     ds->zone_append_merged = stats->merged[BLOCK_ACCT_ZONE_APPEND];
533     ds->unmap_merged = stats->merged[BLOCK_ACCT_UNMAP];
534     ds->flush_operations = stats->nr_ops[BLOCK_ACCT_FLUSH];
535     ds->wr_total_time_ns = stats->total_time_ns[BLOCK_ACCT_WRITE];
536     ds->zone_append_total_time_ns =
537         stats->total_time_ns[BLOCK_ACCT_ZONE_APPEND];
538     ds->rd_total_time_ns = stats->total_time_ns[BLOCK_ACCT_READ];
539     ds->flush_total_time_ns = stats->total_time_ns[BLOCK_ACCT_FLUSH];
540     ds->unmap_total_time_ns = stats->total_time_ns[BLOCK_ACCT_UNMAP];
541 
542     ds->has_idle_time_ns = stats->last_access_time_ns > 0;
543     if (ds->has_idle_time_ns) {
544         ds->idle_time_ns = block_acct_idle_time_ns(stats);
545     }
546 
547     ds->account_invalid = stats->account_invalid;
548     ds->account_failed = stats->account_failed;
549 
550     while ((ts = block_acct_interval_next(stats, ts))) {
551         BlockDeviceTimedStats *dev_stats = g_malloc0(sizeof(*dev_stats));
552 
553         TimedAverage *rd = &ts->latency[BLOCK_ACCT_READ];
554         TimedAverage *wr = &ts->latency[BLOCK_ACCT_WRITE];
555         TimedAverage *zap = &ts->latency[BLOCK_ACCT_ZONE_APPEND];
556         TimedAverage *fl = &ts->latency[BLOCK_ACCT_FLUSH];
557 
558         dev_stats->interval_length = ts->interval_length;
559 
560         dev_stats->min_rd_latency_ns = timed_average_min(rd);
561         dev_stats->max_rd_latency_ns = timed_average_max(rd);
562         dev_stats->avg_rd_latency_ns = timed_average_avg(rd);
563 
564         dev_stats->min_wr_latency_ns = timed_average_min(wr);
565         dev_stats->max_wr_latency_ns = timed_average_max(wr);
566         dev_stats->avg_wr_latency_ns = timed_average_avg(wr);
567 
568         dev_stats->min_zone_append_latency_ns = timed_average_min(zap);
569         dev_stats->max_zone_append_latency_ns = timed_average_max(zap);
570         dev_stats->avg_zone_append_latency_ns = timed_average_avg(zap);
571 
572         dev_stats->min_flush_latency_ns = timed_average_min(fl);
573         dev_stats->max_flush_latency_ns = timed_average_max(fl);
574         dev_stats->avg_flush_latency_ns = timed_average_avg(fl);
575 
576         dev_stats->avg_rd_queue_depth =
577             block_acct_queue_depth(ts, BLOCK_ACCT_READ);
578         dev_stats->avg_wr_queue_depth =
579             block_acct_queue_depth(ts, BLOCK_ACCT_WRITE);
580         dev_stats->avg_zone_append_queue_depth =
581             block_acct_queue_depth(ts, BLOCK_ACCT_ZONE_APPEND);
582 
583         QAPI_LIST_PREPEND(ds->timed_stats, dev_stats);
584     }
585 
586     hgram = stats->latency_histogram;
587     ds->rd_latency_histogram
588         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_READ]);
589     ds->wr_latency_histogram
590         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_WRITE]);
591     ds->zone_append_latency_histogram
592         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_ZONE_APPEND]);
593     ds->flush_latency_histogram
594         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_FLUSH]);
595 }
596 
597 static BlockStats * GRAPH_RDLOCK
598 bdrv_query_bds_stats(BlockDriverState *bs, bool blk_level)
599 {
600     BdrvChild *parent_child;
601     BlockDriverState *filter_or_cow_bs;
602     BlockStats *s = NULL;
603 
604     s = g_malloc0(sizeof(*s));
605     s->stats = g_malloc0(sizeof(*s->stats));
606 
607     if (!bs) {
608         return s;
609     }
610 
611     /* Skip automatically inserted nodes that the user isn't aware of in
612      * a BlockBackend-level command. Stay at the exact node for a node-level
613      * command. */
614     if (blk_level) {
615         bs = bdrv_skip_implicit_filters(bs);
616     }
617 
618     if (bdrv_get_node_name(bs)[0]) {
619         s->node_name = g_strdup(bdrv_get_node_name(bs));
620     }
621 
622     s->stats->wr_highest_offset = stat64_get(&bs->wr_highest_offset);
623 
624     s->driver_specific = bdrv_get_specific_stats(bs);
625 
626     parent_child = bdrv_primary_child(bs);
627     if (!parent_child ||
628         !(parent_child->role & (BDRV_CHILD_DATA | BDRV_CHILD_FILTERED)))
629     {
630         BdrvChild *c;
631 
632         /*
633          * Look for a unique data-storing child.  We do not need to look for
634          * filtered children, as there would be only one and it would have been
635          * the primary child.
636          */
637         parent_child = NULL;
638         QLIST_FOREACH(c, &bs->children, next) {
639             if (c->role & BDRV_CHILD_DATA) {
640                 if (parent_child) {
641                     /*
642                      * There are multiple data-storing children and we cannot
643                      * choose between them.
644                      */
645                     parent_child = NULL;
646                     break;
647                 }
648                 parent_child = c;
649             }
650         }
651     }
652     if (parent_child) {
653         s->parent = bdrv_query_bds_stats(parent_child->bs, blk_level);
654     }
655 
656     filter_or_cow_bs = bdrv_filter_or_cow_bs(bs);
657     if (blk_level && filter_or_cow_bs) {
658         /*
659          * Put any filtered or COW child here (for backwards
660          * compatibility to when we put bs0->backing here, which might
661          * be either)
662          */
663         s->backing = bdrv_query_bds_stats(filter_or_cow_bs, blk_level);
664     }
665 
666     return s;
667 }
668 
669 BlockInfoList *qmp_query_block(Error **errp)
670 {
671     BlockInfoList *head = NULL, **p_next = &head;
672     BlockBackend *blk;
673     Error *local_err = NULL;
674 
675     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
676         BlockInfoList *info;
677 
678         if (!*blk_name(blk) && !blk_get_attached_dev(blk)) {
679             continue;
680         }
681 
682         info = g_malloc0(sizeof(*info));
683         bdrv_query_info(blk, &info->value, &local_err);
684         if (local_err) {
685             error_propagate(errp, local_err);
686             g_free(info);
687             qapi_free_BlockInfoList(head);
688             return NULL;
689         }
690 
691         *p_next = info;
692         p_next = &info->next;
693     }
694 
695     return head;
696 }
697 
698 BlockStatsList *qmp_query_blockstats(bool has_query_nodes,
699                                      bool query_nodes,
700                                      Error **errp)
701 {
702     BlockStatsList *head = NULL, **tail = &head;
703     BlockBackend *blk;
704     BlockDriverState *bs;
705 
706     GRAPH_RDLOCK_GUARD_MAINLOOP();
707 
708     /* Just to be safe if query_nodes is not always initialized */
709     if (has_query_nodes && query_nodes) {
710         for (bs = bdrv_next_node(NULL); bs; bs = bdrv_next_node(bs)) {
711             AioContext *ctx = bdrv_get_aio_context(bs);
712 
713             aio_context_acquire(ctx);
714             QAPI_LIST_APPEND(tail, bdrv_query_bds_stats(bs, false));
715             aio_context_release(ctx);
716         }
717     } else {
718         for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
719             AioContext *ctx = blk_get_aio_context(blk);
720             BlockStats *s;
721             char *qdev;
722 
723             if (!*blk_name(blk) && !blk_get_attached_dev(blk)) {
724                 continue;
725             }
726 
727             aio_context_acquire(ctx);
728             s = bdrv_query_bds_stats(blk_bs(blk), true);
729             s->device = g_strdup(blk_name(blk));
730 
731             qdev = blk_get_attached_dev_id(blk);
732             if (qdev && *qdev) {
733                 s->qdev = qdev;
734             } else {
735                 g_free(qdev);
736             }
737 
738             bdrv_query_blk_stats(s->stats, blk);
739             aio_context_release(ctx);
740 
741             QAPI_LIST_APPEND(tail, s);
742         }
743     }
744 
745     return head;
746 }
747 
748 void bdrv_snapshot_dump(QEMUSnapshotInfo *sn)
749 {
750     char clock_buf[128];
751     char icount_buf[128] = {0};
752     int64_t secs;
753     char *sizing = NULL;
754 
755     if (!sn) {
756         qemu_printf("%-10s%-17s%8s%20s%13s%11s",
757                     "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK", "ICOUNT");
758     } else {
759         g_autoptr(GDateTime) date = g_date_time_new_from_unix_local(sn->date_sec);
760         g_autofree char *date_buf = g_date_time_format(date, "%Y-%m-%d %H:%M:%S");
761 
762         secs = sn->vm_clock_nsec / 1000000000;
763         snprintf(clock_buf, sizeof(clock_buf),
764                  "%02d:%02d:%02d.%03d",
765                  (int)(secs / 3600),
766                  (int)((secs / 60) % 60),
767                  (int)(secs % 60),
768                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
769         sizing = size_to_str(sn->vm_state_size);
770         if (sn->icount != -1ULL) {
771             snprintf(icount_buf, sizeof(icount_buf),
772                 "%"PRId64, sn->icount);
773         }
774         qemu_printf("%-9s %-16s %8s%20s%13s%11s",
775                     sn->id_str, sn->name,
776                     sizing,
777                     date_buf,
778                     clock_buf,
779                     icount_buf);
780     }
781     g_free(sizing);
782 }
783 
784 static void dump_qdict(int indentation, QDict *dict);
785 static void dump_qlist(int indentation, QList *list);
786 
787 static void dump_qobject(int comp_indent, QObject *obj)
788 {
789     switch (qobject_type(obj)) {
790         case QTYPE_QNUM: {
791             QNum *value = qobject_to(QNum, obj);
792             char *tmp = qnum_to_string(value);
793             qemu_printf("%s", tmp);
794             g_free(tmp);
795             break;
796         }
797         case QTYPE_QSTRING: {
798             QString *value = qobject_to(QString, obj);
799             qemu_printf("%s", qstring_get_str(value));
800             break;
801         }
802         case QTYPE_QDICT: {
803             QDict *value = qobject_to(QDict, obj);
804             dump_qdict(comp_indent, value);
805             break;
806         }
807         case QTYPE_QLIST: {
808             QList *value = qobject_to(QList, obj);
809             dump_qlist(comp_indent, value);
810             break;
811         }
812         case QTYPE_QBOOL: {
813             QBool *value = qobject_to(QBool, obj);
814             qemu_printf("%s", qbool_get_bool(value) ? "true" : "false");
815             break;
816         }
817         default:
818             abort();
819     }
820 }
821 
822 static void dump_qlist(int indentation, QList *list)
823 {
824     const QListEntry *entry;
825     int i = 0;
826 
827     for (entry = qlist_first(list); entry; entry = qlist_next(entry), i++) {
828         QType type = qobject_type(entry->value);
829         bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
830         qemu_printf("%*s[%i]:%c", indentation * 4, "", i,
831                     composite ? '\n' : ' ');
832         dump_qobject(indentation + 1, entry->value);
833         if (!composite) {
834             qemu_printf("\n");
835         }
836     }
837 }
838 
839 static void dump_qdict(int indentation, QDict *dict)
840 {
841     const QDictEntry *entry;
842 
843     for (entry = qdict_first(dict); entry; entry = qdict_next(dict, entry)) {
844         QType type = qobject_type(entry->value);
845         bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
846         char *key = g_malloc(strlen(entry->key) + 1);
847         int i;
848 
849         /* replace dashes with spaces in key (variable) names */
850         for (i = 0; entry->key[i]; i++) {
851             key[i] = entry->key[i] == '-' ? ' ' : entry->key[i];
852         }
853         key[i] = 0;
854         qemu_printf("%*s%s:%c", indentation * 4, "", key,
855                     composite ? '\n' : ' ');
856         dump_qobject(indentation + 1, entry->value);
857         if (!composite) {
858             qemu_printf("\n");
859         }
860         g_free(key);
861     }
862 }
863 
864 /*
865  * Return whether dumping the given QObject with dump_qobject() would
866  * yield an empty dump, i.e. not print anything.
867  */
868 static bool qobject_is_empty_dump(const QObject *obj)
869 {
870     switch (qobject_type(obj)) {
871     case QTYPE_QNUM:
872     case QTYPE_QSTRING:
873     case QTYPE_QBOOL:
874         return false;
875 
876     case QTYPE_QDICT:
877         return qdict_size(qobject_to(QDict, obj)) == 0;
878 
879     case QTYPE_QLIST:
880         return qlist_empty(qobject_to(QList, obj));
881 
882     default:
883         abort();
884     }
885 }
886 
887 /**
888  * Dumps the given ImageInfoSpecific object in a human-readable form,
889  * prepending an optional prefix if the dump is not empty.
890  */
891 void bdrv_image_info_specific_dump(ImageInfoSpecific *info_spec,
892                                    const char *prefix,
893                                    int indentation)
894 {
895     QObject *obj, *data;
896     Visitor *v = qobject_output_visitor_new(&obj);
897 
898     visit_type_ImageInfoSpecific(v, NULL, &info_spec, &error_abort);
899     visit_complete(v, &obj);
900     data = qdict_get(qobject_to(QDict, obj), "data");
901     if (!qobject_is_empty_dump(data)) {
902         if (prefix) {
903             qemu_printf("%*s%s", indentation * 4, "", prefix);
904         }
905         dump_qobject(indentation + 1, data);
906     }
907     qobject_unref(obj);
908     visit_free(v);
909 }
910 
911 /**
912  * Print the given @info object in human-readable form.  Every field is indented
913  * using the given @indentation (four spaces per indentation level).
914  *
915  * When using this to print a whole block graph, @protocol can be set to true to
916  * signify that the given information is associated with a protocol node, i.e.
917  * just data storage for an image, such that the data it presents is not really
918  * a full VM disk.  If so, several fields change name: For example, "virtual
919  * size" is printed as "file length".
920  * (Consider a qcow2 image, which is represented by a qcow2 node and a file
921  * node.  Printing a "virtual size" for the file node does not make sense,
922  * because without the qcow2 node, it is not really a guest disk, so it does not
923  * have a "virtual size".  Therefore, we call it "file length" instead.)
924  *
925  * @protocol is ignored when @indentation is 0, because we take that to mean
926  * that the associated node is the root node in the queried block graph, and
927  * thus is always to be interpreted as a standalone guest disk.
928  */
929 void bdrv_node_info_dump(BlockNodeInfo *info, int indentation, bool protocol)
930 {
931     char *size_buf, *dsize_buf;
932     g_autofree char *ind_s = g_strdup_printf("%*s", indentation * 4, "");
933 
934     if (indentation == 0) {
935         /* Top level, consider this a normal image */
936         protocol = false;
937     }
938 
939     if (!info->has_actual_size) {
940         dsize_buf = g_strdup("unavailable");
941     } else {
942         dsize_buf = size_to_str(info->actual_size);
943     }
944     size_buf = size_to_str(info->virtual_size);
945     qemu_printf("%s%s: %s\n"
946                 "%s%s: %s\n"
947                 "%s%s: %s (%" PRId64 " bytes)\n"
948                 "%sdisk size: %s\n",
949                 ind_s, protocol ? "filename" : "image", info->filename,
950                 ind_s, protocol ? "protocol type" : "file format",
951                 info->format,
952                 ind_s, protocol ? "file length" : "virtual size",
953                 size_buf, info->virtual_size,
954                 ind_s, dsize_buf);
955     g_free(size_buf);
956     g_free(dsize_buf);
957 
958     if (info->has_encrypted && info->encrypted) {
959         qemu_printf("%sencrypted: yes\n", ind_s);
960     }
961 
962     if (info->has_cluster_size) {
963         qemu_printf("%scluster_size: %" PRId64 "\n",
964                     ind_s, info->cluster_size);
965     }
966 
967     if (info->has_dirty_flag && info->dirty_flag) {
968         qemu_printf("%scleanly shut down: no\n", ind_s);
969     }
970 
971     if (info->backing_filename) {
972         qemu_printf("%sbacking file: %s", ind_s, info->backing_filename);
973         if (!info->full_backing_filename) {
974             qemu_printf(" (cannot determine actual path)");
975         } else if (strcmp(info->backing_filename,
976                           info->full_backing_filename) != 0) {
977             qemu_printf(" (actual path: %s)", info->full_backing_filename);
978         }
979         qemu_printf("\n");
980         if (info->backing_filename_format) {
981             qemu_printf("%sbacking file format: %s\n",
982                         ind_s, info->backing_filename_format);
983         }
984     }
985 
986     if (info->has_snapshots) {
987         SnapshotInfoList *elem;
988 
989         qemu_printf("%sSnapshot list:\n", ind_s);
990         qemu_printf("%s", ind_s);
991         bdrv_snapshot_dump(NULL);
992         qemu_printf("\n");
993 
994         /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
995          * we convert to the block layer's native QEMUSnapshotInfo for now.
996          */
997         for (elem = info->snapshots; elem; elem = elem->next) {
998             QEMUSnapshotInfo sn = {
999                 .vm_state_size = elem->value->vm_state_size,
1000                 .date_sec = elem->value->date_sec,
1001                 .date_nsec = elem->value->date_nsec,
1002                 .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
1003                                  elem->value->vm_clock_nsec,
1004                 .icount = elem->value->has_icount ?
1005                           elem->value->icount : -1ULL,
1006             };
1007 
1008             pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
1009             pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
1010             qemu_printf("%s", ind_s);
1011             bdrv_snapshot_dump(&sn);
1012             qemu_printf("\n");
1013         }
1014     }
1015 
1016     if (info->format_specific) {
1017         bdrv_image_info_specific_dump(info->format_specific,
1018                                       "Format specific information:\n",
1019                                       indentation);
1020     }
1021 }
1022