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