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