xref: /openbmc/qemu/block/qapi.c (revision 68ff2eeb299d562e437b49e9bb98f9d6f62fbf06)
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 
bdrv_block_device_info(BlockBackend * blk,BlockDriverState * bs,bool flat,Error ** errp)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  */
bdrv_query_snapshot_info_list(BlockDriverState * bs,SnapshotInfoList ** p_list,Error ** errp)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
bdrv_do_query_node_info(BlockDriverState * bs,BlockNodeInfo * info,Error ** errp)238 bdrv_do_query_node_info(BlockDriverState *bs, BlockNodeInfo *info, Error **errp)
239 {
240     int64_t size;
241     const char *backing_filename;
242     BlockDriverInfo bdi;
243     int ret;
244     Error *err = NULL;
245 
246     size = bdrv_getlength(bs);
247     if (size < 0) {
248         error_setg_errno(errp, -size, "Can't get image size '%s'",
249                          bs->exact_filename);
250         return;
251     }
252 
253     bdrv_refresh_filename(bs);
254 
255     info->filename        = g_strdup(bs->filename);
256     info->format          = g_strdup(bdrv_get_format_name(bs));
257     info->virtual_size    = size;
258     info->actual_size     = bdrv_get_allocated_file_size(bs);
259     info->has_actual_size = info->actual_size >= 0;
260     if (bs->encrypted) {
261         info->encrypted = true;
262         info->has_encrypted = true;
263     }
264     if (bdrv_get_info(bs, &bdi) >= 0) {
265         if (bdi.cluster_size != 0) {
266             info->cluster_size = bdi.cluster_size;
267             info->has_cluster_size = true;
268         }
269         info->dirty_flag = bdi.is_dirty;
270         info->has_dirty_flag = true;
271     }
272     info->format_specific = bdrv_get_specific_info(bs, &err);
273     if (err) {
274         error_propagate(errp, err);
275         return;
276     }
277     backing_filename = bs->backing_file;
278     if (backing_filename[0] != '\0') {
279         char *backing_filename2;
280 
281         info->backing_filename = g_strdup(backing_filename);
282         backing_filename2 = bdrv_get_full_backing_filename(bs, NULL);
283 
284         /* Always report the full_backing_filename if present, even if it's the
285          * same as backing_filename. That they are same is useful info. */
286         if (backing_filename2) {
287             info->full_backing_filename = g_strdup(backing_filename2);
288         }
289 
290         if (bs->backing_format[0]) {
291             info->backing_filename_format = g_strdup(bs->backing_format);
292         }
293         g_free(backing_filename2);
294     }
295 
296     ret = bdrv_query_snapshot_info_list(bs, &info->snapshots, &err);
297     switch (ret) {
298     case 0:
299         if (info->snapshots) {
300             info->has_snapshots = true;
301         }
302         break;
303     /* recoverable error */
304     case -ENOMEDIUM:
305     case -ENOTSUP:
306         error_free(err);
307         break;
308     default:
309         error_propagate(errp, err);
310         return;
311     }
312 }
313 
314 /**
315  * bdrv_query_image_info:
316  * @bs: block node to examine
317  * @p_info: location to store image information
318  * @flat: skip backing node information
319  * @skip_implicit_filters: skip implicit filters in the backing chain
320  * @errp: location to store error information
321  *
322  * Store image information in @p_info, potentially recursively covering the
323  * backing chain.
324  *
325  * If @flat is true, do not query backing image information, i.e.
326  * (*p_info)->has_backing_image will be set to false and
327  * (*p_info)->backing_image to NULL even when the image does in fact have a
328  * backing image.
329  *
330  * If @skip_implicit_filters is true, implicit filter nodes in the backing chain
331  * will be skipped when querying backing image information.
332  * (@skip_implicit_filters is ignored when @flat is true.)
333  *
334  * @p_info will be set only on success. On error, store error in @errp.
335  */
bdrv_query_image_info(BlockDriverState * bs,ImageInfo ** p_info,bool flat,bool skip_implicit_filters,Error ** errp)336 void bdrv_query_image_info(BlockDriverState *bs,
337                            ImageInfo **p_info,
338                            bool flat,
339                            bool skip_implicit_filters,
340                            Error **errp)
341 {
342     ERRP_GUARD();
343     ImageInfo *info;
344 
345     info = g_new0(ImageInfo, 1);
346     bdrv_do_query_node_info(bs, qapi_ImageInfo_base(info), errp);
347     if (*errp) {
348         goto fail;
349     }
350 
351     if (!flat) {
352         BlockDriverState *backing;
353 
354         /*
355          * Use any filtered child here (for backwards compatibility to when
356          * we always took bs->backing, which might be any filtered child).
357          */
358         backing = bdrv_filter_or_cow_bs(bs);
359         if (skip_implicit_filters) {
360             backing = bdrv_skip_implicit_filters(backing);
361         }
362 
363         if (backing) {
364             bdrv_query_image_info(backing, &info->backing_image, false,
365                                   skip_implicit_filters, errp);
366             if (*errp) {
367                 goto fail;
368             }
369         }
370     }
371 
372     *p_info = info;
373     return;
374 
375 fail:
376     assert(*errp);
377     qapi_free_ImageInfo(info);
378 }
379 
380 /**
381  * bdrv_query_block_graph_info:
382  * @bs: root node to start from
383  * @p_info: location to store image information
384  * @errp: location to store error information
385  *
386  * Store image information about the graph starting from @bs in @p_info.
387  *
388  * @p_info will be set only on success. On error, store error in @errp.
389  */
bdrv_query_block_graph_info(BlockDriverState * bs,BlockGraphInfo ** p_info,Error ** errp)390 void bdrv_query_block_graph_info(BlockDriverState *bs,
391                                  BlockGraphInfo **p_info,
392                                  Error **errp)
393 {
394     ERRP_GUARD();
395     BlockGraphInfo *info;
396     BlockChildInfoList **children_list_tail;
397     BdrvChild *c;
398 
399     info = g_new0(BlockGraphInfo, 1);
400     bdrv_do_query_node_info(bs, qapi_BlockGraphInfo_base(info), errp);
401     if (*errp) {
402         goto fail;
403     }
404 
405     children_list_tail = &info->children;
406 
407     QLIST_FOREACH(c, &bs->children, next) {
408         BlockChildInfo *c_info;
409 
410         c_info = g_new0(BlockChildInfo, 1);
411         QAPI_LIST_APPEND(children_list_tail, c_info);
412 
413         c_info->name = g_strdup(c->name);
414         bdrv_query_block_graph_info(c->bs, &c_info->info, errp);
415         if (*errp) {
416             goto fail;
417         }
418     }
419 
420     *p_info = info;
421     return;
422 
423 fail:
424     assert(*errp != NULL);
425     qapi_free_BlockGraphInfo(info);
426 }
427 
428 /* @p_info will be set only on success. */
429 static void GRAPH_RDLOCK
bdrv_query_info(BlockBackend * blk,BlockInfo ** p_info,Error ** errp)430 bdrv_query_info(BlockBackend *blk, BlockInfo **p_info, Error **errp)
431 {
432     BlockInfo *info = g_malloc0(sizeof(*info));
433     BlockDriverState *bs = blk_bs(blk);
434     char *qdev;
435 
436     /* Skip automatically inserted nodes that the user isn't aware of */
437     bs = bdrv_skip_implicit_filters(bs);
438 
439     info->device = g_strdup(blk_name(blk));
440     info->type = g_strdup("unknown");
441     info->locked = blk_dev_is_medium_locked(blk);
442     info->removable = blk_dev_has_removable_media(blk);
443 
444     qdev = blk_get_attached_dev_id(blk);
445     if (qdev && *qdev) {
446         info->qdev = qdev;
447     } else {
448         g_free(qdev);
449     }
450 
451     if (blk_dev_has_tray(blk)) {
452         info->has_tray_open = true;
453         info->tray_open = blk_dev_is_tray_open(blk);
454     }
455 
456     if (blk_iostatus_is_enabled(blk)) {
457         info->has_io_status = true;
458         info->io_status = blk_iostatus(blk);
459     }
460 
461     if (bs && bs->drv) {
462         info->inserted = bdrv_block_device_info(blk, bs, false, errp);
463         if (info->inserted == NULL) {
464             goto err;
465         }
466     }
467 
468     *p_info = info;
469     return;
470 
471  err:
472     qapi_free_BlockInfo(info);
473 }
474 
uint64_list(uint64_t * list,int size)475 static uint64List *uint64_list(uint64_t *list, int size)
476 {
477     int i;
478     uint64List *out_list = NULL;
479     uint64List **tail = &out_list;
480 
481     for (i = 0; i < size; i++) {
482         QAPI_LIST_APPEND(tail, list[i]);
483     }
484 
485     return out_list;
486 }
487 
488 static BlockLatencyHistogramInfo *
bdrv_latency_histogram_stats(BlockLatencyHistogram * hist)489 bdrv_latency_histogram_stats(BlockLatencyHistogram *hist)
490 {
491     BlockLatencyHistogramInfo *info;
492 
493     if (!hist->bins) {
494         return NULL;
495     }
496 
497     info = g_new0(BlockLatencyHistogramInfo, 1);
498     info->boundaries = uint64_list(hist->boundaries, hist->nbins - 1);
499     info->bins = uint64_list(hist->bins, hist->nbins);
500     return info;
501 }
502 
bdrv_query_blk_stats(BlockDeviceStats * ds,BlockBackend * blk)503 static void bdrv_query_blk_stats(BlockDeviceStats *ds, BlockBackend *blk)
504 {
505     BlockAcctStats *stats = blk_get_stats(blk);
506     BlockAcctTimedStats *ts = NULL;
507     BlockLatencyHistogram *hgram;
508 
509     ds->rd_bytes = stats->nr_bytes[BLOCK_ACCT_READ];
510     ds->wr_bytes = stats->nr_bytes[BLOCK_ACCT_WRITE];
511     ds->zone_append_bytes = stats->nr_bytes[BLOCK_ACCT_ZONE_APPEND];
512     ds->unmap_bytes = stats->nr_bytes[BLOCK_ACCT_UNMAP];
513     ds->rd_operations = stats->nr_ops[BLOCK_ACCT_READ];
514     ds->wr_operations = stats->nr_ops[BLOCK_ACCT_WRITE];
515     ds->zone_append_operations = stats->nr_ops[BLOCK_ACCT_ZONE_APPEND];
516     ds->unmap_operations = stats->nr_ops[BLOCK_ACCT_UNMAP];
517 
518     ds->failed_rd_operations = stats->failed_ops[BLOCK_ACCT_READ];
519     ds->failed_wr_operations = stats->failed_ops[BLOCK_ACCT_WRITE];
520     ds->failed_zone_append_operations =
521         stats->failed_ops[BLOCK_ACCT_ZONE_APPEND];
522     ds->failed_flush_operations = stats->failed_ops[BLOCK_ACCT_FLUSH];
523     ds->failed_unmap_operations = stats->failed_ops[BLOCK_ACCT_UNMAP];
524 
525     ds->invalid_rd_operations = stats->invalid_ops[BLOCK_ACCT_READ];
526     ds->invalid_wr_operations = stats->invalid_ops[BLOCK_ACCT_WRITE];
527     ds->invalid_zone_append_operations =
528         stats->invalid_ops[BLOCK_ACCT_ZONE_APPEND];
529     ds->invalid_flush_operations =
530         stats->invalid_ops[BLOCK_ACCT_FLUSH];
531     ds->invalid_unmap_operations = stats->invalid_ops[BLOCK_ACCT_UNMAP];
532 
533     ds->rd_merged = stats->merged[BLOCK_ACCT_READ];
534     ds->wr_merged = stats->merged[BLOCK_ACCT_WRITE];
535     ds->zone_append_merged = stats->merged[BLOCK_ACCT_ZONE_APPEND];
536     ds->unmap_merged = stats->merged[BLOCK_ACCT_UNMAP];
537     ds->flush_operations = stats->nr_ops[BLOCK_ACCT_FLUSH];
538     ds->wr_total_time_ns = stats->total_time_ns[BLOCK_ACCT_WRITE];
539     ds->zone_append_total_time_ns =
540         stats->total_time_ns[BLOCK_ACCT_ZONE_APPEND];
541     ds->rd_total_time_ns = stats->total_time_ns[BLOCK_ACCT_READ];
542     ds->flush_total_time_ns = stats->total_time_ns[BLOCK_ACCT_FLUSH];
543     ds->unmap_total_time_ns = stats->total_time_ns[BLOCK_ACCT_UNMAP];
544 
545     ds->has_idle_time_ns = stats->last_access_time_ns > 0;
546     if (ds->has_idle_time_ns) {
547         ds->idle_time_ns = block_acct_idle_time_ns(stats);
548     }
549 
550     ds->account_invalid = stats->account_invalid;
551     ds->account_failed = stats->account_failed;
552 
553     while ((ts = block_acct_interval_next(stats, ts))) {
554         BlockDeviceTimedStats *dev_stats = g_malloc0(sizeof(*dev_stats));
555 
556         TimedAverage *rd = &ts->latency[BLOCK_ACCT_READ];
557         TimedAverage *wr = &ts->latency[BLOCK_ACCT_WRITE];
558         TimedAverage *zap = &ts->latency[BLOCK_ACCT_ZONE_APPEND];
559         TimedAverage *fl = &ts->latency[BLOCK_ACCT_FLUSH];
560 
561         dev_stats->interval_length = ts->interval_length;
562 
563         dev_stats->min_rd_latency_ns = timed_average_min(rd);
564         dev_stats->max_rd_latency_ns = timed_average_max(rd);
565         dev_stats->avg_rd_latency_ns = timed_average_avg(rd);
566 
567         dev_stats->min_wr_latency_ns = timed_average_min(wr);
568         dev_stats->max_wr_latency_ns = timed_average_max(wr);
569         dev_stats->avg_wr_latency_ns = timed_average_avg(wr);
570 
571         dev_stats->min_zone_append_latency_ns = timed_average_min(zap);
572         dev_stats->max_zone_append_latency_ns = timed_average_max(zap);
573         dev_stats->avg_zone_append_latency_ns = timed_average_avg(zap);
574 
575         dev_stats->min_flush_latency_ns = timed_average_min(fl);
576         dev_stats->max_flush_latency_ns = timed_average_max(fl);
577         dev_stats->avg_flush_latency_ns = timed_average_avg(fl);
578 
579         dev_stats->avg_rd_queue_depth =
580             block_acct_queue_depth(ts, BLOCK_ACCT_READ);
581         dev_stats->avg_wr_queue_depth =
582             block_acct_queue_depth(ts, BLOCK_ACCT_WRITE);
583         dev_stats->avg_zone_append_queue_depth =
584             block_acct_queue_depth(ts, BLOCK_ACCT_ZONE_APPEND);
585 
586         QAPI_LIST_PREPEND(ds->timed_stats, dev_stats);
587     }
588 
589     hgram = stats->latency_histogram;
590     ds->rd_latency_histogram
591         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_READ]);
592     ds->wr_latency_histogram
593         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_WRITE]);
594     ds->zone_append_latency_histogram
595         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_ZONE_APPEND]);
596     ds->flush_latency_histogram
597         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_FLUSH]);
598 }
599 
600 static BlockStats * GRAPH_RDLOCK
bdrv_query_bds_stats(BlockDriverState * bs,bool blk_level)601 bdrv_query_bds_stats(BlockDriverState *bs, bool blk_level)
602 {
603     BdrvChild *parent_child;
604     BlockDriverState *filter_or_cow_bs;
605     BlockStats *s = NULL;
606 
607     s = g_malloc0(sizeof(*s));
608     s->stats = g_malloc0(sizeof(*s->stats));
609 
610     if (!bs) {
611         return s;
612     }
613 
614     /* Skip automatically inserted nodes that the user isn't aware of in
615      * a BlockBackend-level command. Stay at the exact node for a node-level
616      * command. */
617     if (blk_level) {
618         bs = bdrv_skip_implicit_filters(bs);
619     }
620 
621     if (bdrv_get_node_name(bs)[0]) {
622         s->node_name = g_strdup(bdrv_get_node_name(bs));
623     }
624 
625     s->stats->wr_highest_offset = stat64_get(&bs->wr_highest_offset);
626 
627     s->driver_specific = bdrv_get_specific_stats(bs);
628 
629     parent_child = bdrv_primary_child(bs);
630     if (!parent_child ||
631         !(parent_child->role & (BDRV_CHILD_DATA | BDRV_CHILD_FILTERED)))
632     {
633         BdrvChild *c;
634 
635         /*
636          * Look for a unique data-storing child.  We do not need to look for
637          * filtered children, as there would be only one and it would have been
638          * the primary child.
639          */
640         parent_child = NULL;
641         QLIST_FOREACH(c, &bs->children, next) {
642             if (c->role & BDRV_CHILD_DATA) {
643                 if (parent_child) {
644                     /*
645                      * There are multiple data-storing children and we cannot
646                      * choose between them.
647                      */
648                     parent_child = NULL;
649                     break;
650                 }
651                 parent_child = c;
652             }
653         }
654     }
655     if (parent_child) {
656         s->parent = bdrv_query_bds_stats(parent_child->bs, blk_level);
657     }
658 
659     filter_or_cow_bs = bdrv_filter_or_cow_bs(bs);
660     if (blk_level && filter_or_cow_bs) {
661         /*
662          * Put any filtered or COW child here (for backwards
663          * compatibility to when we put bs0->backing here, which might
664          * be either)
665          */
666         s->backing = bdrv_query_bds_stats(filter_or_cow_bs, blk_level);
667     }
668 
669     return s;
670 }
671 
qmp_query_block(Error ** errp)672 BlockInfoList *qmp_query_block(Error **errp)
673 {
674     BlockInfoList *head = NULL, **p_next = &head;
675     BlockBackend *blk;
676     Error *local_err = NULL;
677 
678     GRAPH_RDLOCK_GUARD_MAINLOOP();
679 
680     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
681         BlockInfoList *info;
682 
683         if (!*blk_name(blk) && !blk_get_attached_dev(blk)) {
684             continue;
685         }
686 
687         info = g_malloc0(sizeof(*info));
688         bdrv_query_info(blk, &info->value, &local_err);
689         if (local_err) {
690             error_propagate(errp, local_err);
691             g_free(info);
692             qapi_free_BlockInfoList(head);
693             return NULL;
694         }
695 
696         *p_next = info;
697         p_next = &info->next;
698     }
699 
700     return head;
701 }
702 
qmp_query_blockstats(bool has_query_nodes,bool query_nodes,Error ** errp)703 BlockStatsList *qmp_query_blockstats(bool has_query_nodes,
704                                      bool query_nodes,
705                                      Error **errp)
706 {
707     BlockStatsList *head = NULL, **tail = &head;
708     BlockBackend *blk;
709     BlockDriverState *bs;
710 
711     GRAPH_RDLOCK_GUARD_MAINLOOP();
712 
713     /* Just to be safe if query_nodes is not always initialized */
714     if (has_query_nodes && query_nodes) {
715         for (bs = bdrv_next_node(NULL); bs; bs = bdrv_next_node(bs)) {
716             QAPI_LIST_APPEND(tail, bdrv_query_bds_stats(bs, false));
717         }
718     } else {
719         for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
720             BlockStats *s;
721             char *qdev;
722 
723             if (!*blk_name(blk) && !blk_get_attached_dev(blk)) {
724                 continue;
725             }
726 
727             s = bdrv_query_bds_stats(blk_bs(blk), true);
728             s->device = g_strdup(blk_name(blk));
729 
730             qdev = blk_get_attached_dev_id(blk);
731             if (qdev && *qdev) {
732                 s->qdev = qdev;
733             } else {
734                 g_free(qdev);
735             }
736 
737             bdrv_query_blk_stats(s->stats, blk);
738 
739             QAPI_LIST_APPEND(tail, s);
740         }
741     }
742 
743     return head;
744 }
745 
bdrv_snapshot_dump(QEMUSnapshotInfo * sn)746 void bdrv_snapshot_dump(QEMUSnapshotInfo *sn)
747 {
748     char clock_buf[128];
749     char icount_buf[128] = {0};
750     int64_t secs;
751     char *sizing = NULL;
752 
753     if (!sn) {
754         qemu_printf("%-7s %-16s %8s %19s %15s %10s",
755                     "ID", "TAG", "VM_SIZE", "DATE", "VM_CLOCK", "ICOUNT");
756     } else {
757         g_autoptr(GDateTime) date = g_date_time_new_from_unix_local(sn->date_sec);
758         g_autofree char *date_buf = g_date_time_format(date, "%Y-%m-%d %H:%M:%S");
759 
760         secs = sn->vm_clock_nsec / 1000000000;
761         snprintf(clock_buf, sizeof(clock_buf),
762                  "%04d:%02d:%02d.%03d",
763                  (int)(secs / 3600),
764                  (int)((secs / 60) % 60),
765                  (int)(secs % 60),
766                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
767         sizing = size_to_str(sn->vm_state_size);
768         if (sn->icount != -1ULL) {
769             snprintf(icount_buf, sizeof(icount_buf),
770                 "%"PRId64, sn->icount);
771         } else {
772             snprintf(icount_buf, sizeof(icount_buf), "--");
773         }
774         qemu_printf("%-7s %-16s %8s %19s %15s %10s",
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 
dump_qobject(int comp_indent,QObject * obj)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 
dump_qlist(int indentation,QList * list)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 
dump_qdict(int indentation,QDict * dict)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  */
qobject_is_empty_dump(const QObject * obj)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  */
bdrv_image_info_specific_dump(ImageInfoSpecific * info_spec,const char * prefix,int indentation)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  */
bdrv_node_info_dump(BlockNodeInfo * info,int indentation,bool protocol)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