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