xref: /openbmc/qemu/block/qapi.c (revision 80adf54e)
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 "block/qapi.h"
27 #include "block/block_int.h"
28 #include "block/throttle-groups.h"
29 #include "block/write-threshold.h"
30 #include "qmp-commands.h"
31 #include "qapi-visit.h"
32 #include "qapi/qobject-output-visitor.h"
33 #include "qapi/qmp/types.h"
34 #include "sysemu/block-backend.h"
35 #include "qemu/cutils.h"
36 
37 BlockDeviceInfo *bdrv_block_device_info(BlockBackend *blk,
38                                         BlockDriverState *bs, Error **errp)
39 {
40     ImageInfo **p_image_info;
41     BlockDriverState *bs0;
42     BlockDeviceInfo *info = g_malloc0(sizeof(*info));
43 
44     info->file                   = g_strdup(bs->filename);
45     info->ro                     = bs->read_only;
46     info->drv                    = g_strdup(bs->drv->format_name);
47     info->encrypted              = bs->encrypted;
48     info->encryption_key_missing = false;
49 
50     info->cache = g_new(BlockdevCacheInfo, 1);
51     *info->cache = (BlockdevCacheInfo) {
52         .writeback      = blk ? blk_enable_write_cache(blk) : true,
53         .direct         = !!(bs->open_flags & BDRV_O_NOCACHE),
54         .no_flush       = !!(bs->open_flags & BDRV_O_NO_FLUSH),
55     };
56 
57     if (bs->node_name[0]) {
58         info->has_node_name = true;
59         info->node_name = g_strdup(bs->node_name);
60     }
61 
62     if (bs->backing_file[0]) {
63         info->has_backing_file = true;
64         info->backing_file = g_strdup(bs->backing_file);
65     }
66 
67     info->detect_zeroes = bs->detect_zeroes;
68 
69     if (blk && blk_get_public(blk)->throttle_state) {
70         ThrottleConfig cfg;
71 
72         throttle_group_get_config(blk, &cfg);
73 
74         info->bps     = cfg.buckets[THROTTLE_BPS_TOTAL].avg;
75         info->bps_rd  = cfg.buckets[THROTTLE_BPS_READ].avg;
76         info->bps_wr  = cfg.buckets[THROTTLE_BPS_WRITE].avg;
77 
78         info->iops    = cfg.buckets[THROTTLE_OPS_TOTAL].avg;
79         info->iops_rd = cfg.buckets[THROTTLE_OPS_READ].avg;
80         info->iops_wr = cfg.buckets[THROTTLE_OPS_WRITE].avg;
81 
82         info->has_bps_max     = cfg.buckets[THROTTLE_BPS_TOTAL].max;
83         info->bps_max         = cfg.buckets[THROTTLE_BPS_TOTAL].max;
84         info->has_bps_rd_max  = cfg.buckets[THROTTLE_BPS_READ].max;
85         info->bps_rd_max      = cfg.buckets[THROTTLE_BPS_READ].max;
86         info->has_bps_wr_max  = cfg.buckets[THROTTLE_BPS_WRITE].max;
87         info->bps_wr_max      = cfg.buckets[THROTTLE_BPS_WRITE].max;
88 
89         info->has_iops_max    = cfg.buckets[THROTTLE_OPS_TOTAL].max;
90         info->iops_max        = cfg.buckets[THROTTLE_OPS_TOTAL].max;
91         info->has_iops_rd_max = cfg.buckets[THROTTLE_OPS_READ].max;
92         info->iops_rd_max     = cfg.buckets[THROTTLE_OPS_READ].max;
93         info->has_iops_wr_max = cfg.buckets[THROTTLE_OPS_WRITE].max;
94         info->iops_wr_max     = cfg.buckets[THROTTLE_OPS_WRITE].max;
95 
96         info->has_bps_max_length     = info->has_bps_max;
97         info->bps_max_length         =
98             cfg.buckets[THROTTLE_BPS_TOTAL].burst_length;
99         info->has_bps_rd_max_length  = info->has_bps_rd_max;
100         info->bps_rd_max_length      =
101             cfg.buckets[THROTTLE_BPS_READ].burst_length;
102         info->has_bps_wr_max_length  = info->has_bps_wr_max;
103         info->bps_wr_max_length      =
104             cfg.buckets[THROTTLE_BPS_WRITE].burst_length;
105 
106         info->has_iops_max_length    = info->has_iops_max;
107         info->iops_max_length        =
108             cfg.buckets[THROTTLE_OPS_TOTAL].burst_length;
109         info->has_iops_rd_max_length = info->has_iops_rd_max;
110         info->iops_rd_max_length     =
111             cfg.buckets[THROTTLE_OPS_READ].burst_length;
112         info->has_iops_wr_max_length = info->has_iops_wr_max;
113         info->iops_wr_max_length     =
114             cfg.buckets[THROTTLE_OPS_WRITE].burst_length;
115 
116         info->has_iops_size = cfg.op_size;
117         info->iops_size = cfg.op_size;
118 
119         info->has_group = true;
120         info->group = g_strdup(throttle_group_get_name(blk));
121     }
122 
123     info->write_threshold = bdrv_write_threshold_get(bs);
124 
125     bs0 = bs;
126     p_image_info = &info->image;
127     info->backing_file_depth = 0;
128     while (1) {
129         Error *local_err = NULL;
130         bdrv_query_image_info(bs0, p_image_info, &local_err);
131         if (local_err) {
132             error_propagate(errp, local_err);
133             qapi_free_BlockDeviceInfo(info);
134             return NULL;
135         }
136 
137         if (bs0->drv && bs0->backing) {
138             info->backing_file_depth++;
139             bs0 = bs0->backing->bs;
140             (*p_image_info)->has_backing_image = true;
141             p_image_info = &((*p_image_info)->backing_image);
142         } else {
143             break;
144         }
145 
146         /* Skip automatically inserted nodes that the user isn't aware of for
147          * query-block (blk != NULL), but not for query-named-block-nodes */
148         while (blk && bs0->drv && bs0->implicit) {
149             bs0 = backing_bs(bs0);
150             assert(bs0);
151         }
152     }
153 
154     return info;
155 }
156 
157 /*
158  * Returns 0 on success, with *p_list either set to describe snapshot
159  * information, or NULL because there are no snapshots.  Returns -errno on
160  * error, with *p_list untouched.
161  */
162 int bdrv_query_snapshot_info_list(BlockDriverState *bs,
163                                   SnapshotInfoList **p_list,
164                                   Error **errp)
165 {
166     int i, sn_count;
167     QEMUSnapshotInfo *sn_tab = NULL;
168     SnapshotInfoList *info_list, *cur_item = NULL, *head = NULL;
169     SnapshotInfo *info;
170 
171     sn_count = bdrv_snapshot_list(bs, &sn_tab);
172     if (sn_count < 0) {
173         const char *dev = bdrv_get_device_name(bs);
174         switch (sn_count) {
175         case -ENOMEDIUM:
176             error_setg(errp, "Device '%s' is not inserted", dev);
177             break;
178         case -ENOTSUP:
179             error_setg(errp,
180                        "Device '%s' does not support internal snapshots",
181                        dev);
182             break;
183         default:
184             error_setg_errno(errp, -sn_count,
185                              "Can't list snapshots of device '%s'", dev);
186             break;
187         }
188         return sn_count;
189     }
190 
191     for (i = 0; i < sn_count; i++) {
192         info = g_new0(SnapshotInfo, 1);
193         info->id            = g_strdup(sn_tab[i].id_str);
194         info->name          = g_strdup(sn_tab[i].name);
195         info->vm_state_size = sn_tab[i].vm_state_size;
196         info->date_sec      = sn_tab[i].date_sec;
197         info->date_nsec     = sn_tab[i].date_nsec;
198         info->vm_clock_sec  = sn_tab[i].vm_clock_nsec / 1000000000;
199         info->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
200 
201         info_list = g_new0(SnapshotInfoList, 1);
202         info_list->value = info;
203 
204         /* XXX: waiting for the qapi to support qemu-queue.h types */
205         if (!cur_item) {
206             head = cur_item = info_list;
207         } else {
208             cur_item->next = info_list;
209             cur_item = info_list;
210         }
211 
212     }
213 
214     g_free(sn_tab);
215     *p_list = head;
216     return 0;
217 }
218 
219 /**
220  * bdrv_query_image_info:
221  * @bs: block device to examine
222  * @p_info: location to store image information
223  * @errp: location to store error information
224  *
225  * Store "flat" image information in @p_info.
226  *
227  * "Flat" means it does *not* query backing image information,
228  * i.e. (*pinfo)->has_backing_image will be set to false and
229  * (*pinfo)->backing_image to NULL even when the image does in fact have
230  * a backing image.
231  *
232  * @p_info will be set only on success. On error, store error in @errp.
233  */
234 void bdrv_query_image_info(BlockDriverState *bs,
235                            ImageInfo **p_info,
236                            Error **errp)
237 {
238     int64_t size;
239     const char *backing_filename;
240     BlockDriverInfo bdi;
241     int ret;
242     Error *err = NULL;
243     ImageInfo *info;
244 
245     aio_context_acquire(bdrv_get_aio_context(bs));
246 
247     size = bdrv_getlength(bs);
248     if (size < 0) {
249         error_setg_errno(errp, -size, "Can't get image size '%s'",
250                          bs->exact_filename);
251         goto out;
252     }
253 
254     info = g_new0(ImageInfo, 1);
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 (bdrv_is_encrypted(bs)) {
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);
273     info->has_format_specific = info->format_specific != NULL;
274 
275     backing_filename = bs->backing_file;
276     if (backing_filename[0] != '\0') {
277         char *backing_filename2 = g_malloc0(PATH_MAX);
278         info->backing_filename = g_strdup(backing_filename);
279         info->has_backing_filename = true;
280         bdrv_get_full_backing_filename(bs, backing_filename2, PATH_MAX, &err);
281         if (err) {
282             /* Can't reconstruct the full backing filename, so we must omit
283              * this field and apply a Best Effort to this query. */
284             g_free(backing_filename2);
285             backing_filename2 = NULL;
286             error_free(err);
287             err = NULL;
288         }
289 
290         /* Always report the full_backing_filename if present, even if it's the
291          * same as backing_filename. That they are same is useful info. */
292         if (backing_filename2) {
293             info->full_backing_filename = g_strdup(backing_filename2);
294             info->has_full_backing_filename = true;
295         }
296 
297         if (bs->backing_format[0]) {
298             info->backing_filename_format = g_strdup(bs->backing_format);
299             info->has_backing_filename_format = true;
300         }
301         g_free(backing_filename2);
302     }
303 
304     ret = bdrv_query_snapshot_info_list(bs, &info->snapshots, &err);
305     switch (ret) {
306     case 0:
307         if (info->snapshots) {
308             info->has_snapshots = true;
309         }
310         break;
311     /* recoverable error */
312     case -ENOMEDIUM:
313     case -ENOTSUP:
314         error_free(err);
315         break;
316     default:
317         error_propagate(errp, err);
318         qapi_free_ImageInfo(info);
319         goto out;
320     }
321 
322     *p_info = info;
323 
324 out:
325     aio_context_release(bdrv_get_aio_context(bs));
326 }
327 
328 /* @p_info will be set only on success. */
329 static void bdrv_query_info(BlockBackend *blk, BlockInfo **p_info,
330                             Error **errp)
331 {
332     BlockInfo *info = g_malloc0(sizeof(*info));
333     BlockDriverState *bs = blk_bs(blk);
334     char *qdev;
335 
336     /* Skip automatically inserted nodes that the user isn't aware of */
337     while (bs && bs->drv && bs->implicit) {
338         bs = backing_bs(bs);
339     }
340 
341     info->device = g_strdup(blk_name(blk));
342     info->type = g_strdup("unknown");
343     info->locked = blk_dev_is_medium_locked(blk);
344     info->removable = blk_dev_has_removable_media(blk);
345 
346     qdev = blk_get_attached_dev_id(blk);
347     if (qdev && *qdev) {
348         info->has_qdev = true;
349         info->qdev = qdev;
350     } else {
351         g_free(qdev);
352     }
353 
354     if (blk_dev_has_tray(blk)) {
355         info->has_tray_open = true;
356         info->tray_open = blk_dev_is_tray_open(blk);
357     }
358 
359     if (blk_iostatus_is_enabled(blk)) {
360         info->has_io_status = true;
361         info->io_status = blk_iostatus(blk);
362     }
363 
364     if (bs && !QLIST_EMPTY(&bs->dirty_bitmaps)) {
365         info->has_dirty_bitmaps = true;
366         info->dirty_bitmaps = bdrv_query_dirty_bitmaps(bs);
367     }
368 
369     if (bs && bs->drv) {
370         info->has_inserted = true;
371         info->inserted = bdrv_block_device_info(blk, bs, errp);
372         if (info->inserted == NULL) {
373             goto err;
374         }
375     }
376 
377     *p_info = info;
378     return;
379 
380  err:
381     qapi_free_BlockInfo(info);
382 }
383 
384 static void bdrv_query_blk_stats(BlockDeviceStats *ds, BlockBackend *blk)
385 {
386     BlockAcctStats *stats = blk_get_stats(blk);
387     BlockAcctTimedStats *ts = NULL;
388 
389     ds->rd_bytes = stats->nr_bytes[BLOCK_ACCT_READ];
390     ds->wr_bytes = stats->nr_bytes[BLOCK_ACCT_WRITE];
391     ds->rd_operations = stats->nr_ops[BLOCK_ACCT_READ];
392     ds->wr_operations = stats->nr_ops[BLOCK_ACCT_WRITE];
393 
394     ds->failed_rd_operations = stats->failed_ops[BLOCK_ACCT_READ];
395     ds->failed_wr_operations = stats->failed_ops[BLOCK_ACCT_WRITE];
396     ds->failed_flush_operations = stats->failed_ops[BLOCK_ACCT_FLUSH];
397 
398     ds->invalid_rd_operations = stats->invalid_ops[BLOCK_ACCT_READ];
399     ds->invalid_wr_operations = stats->invalid_ops[BLOCK_ACCT_WRITE];
400     ds->invalid_flush_operations =
401         stats->invalid_ops[BLOCK_ACCT_FLUSH];
402 
403     ds->rd_merged = stats->merged[BLOCK_ACCT_READ];
404     ds->wr_merged = stats->merged[BLOCK_ACCT_WRITE];
405     ds->flush_operations = stats->nr_ops[BLOCK_ACCT_FLUSH];
406     ds->wr_total_time_ns = stats->total_time_ns[BLOCK_ACCT_WRITE];
407     ds->rd_total_time_ns = stats->total_time_ns[BLOCK_ACCT_READ];
408     ds->flush_total_time_ns = stats->total_time_ns[BLOCK_ACCT_FLUSH];
409 
410     ds->has_idle_time_ns = stats->last_access_time_ns > 0;
411     if (ds->has_idle_time_ns) {
412         ds->idle_time_ns = block_acct_idle_time_ns(stats);
413     }
414 
415     ds->account_invalid = stats->account_invalid;
416     ds->account_failed = stats->account_failed;
417 
418     while ((ts = block_acct_interval_next(stats, ts))) {
419         BlockDeviceTimedStatsList *timed_stats =
420             g_malloc0(sizeof(*timed_stats));
421         BlockDeviceTimedStats *dev_stats = g_malloc0(sizeof(*dev_stats));
422         timed_stats->next = ds->timed_stats;
423         timed_stats->value = dev_stats;
424         ds->timed_stats = timed_stats;
425 
426         TimedAverage *rd = &ts->latency[BLOCK_ACCT_READ];
427         TimedAverage *wr = &ts->latency[BLOCK_ACCT_WRITE];
428         TimedAverage *fl = &ts->latency[BLOCK_ACCT_FLUSH];
429 
430         dev_stats->interval_length = ts->interval_length;
431 
432         dev_stats->min_rd_latency_ns = timed_average_min(rd);
433         dev_stats->max_rd_latency_ns = timed_average_max(rd);
434         dev_stats->avg_rd_latency_ns = timed_average_avg(rd);
435 
436         dev_stats->min_wr_latency_ns = timed_average_min(wr);
437         dev_stats->max_wr_latency_ns = timed_average_max(wr);
438         dev_stats->avg_wr_latency_ns = timed_average_avg(wr);
439 
440         dev_stats->min_flush_latency_ns = timed_average_min(fl);
441         dev_stats->max_flush_latency_ns = timed_average_max(fl);
442         dev_stats->avg_flush_latency_ns = timed_average_avg(fl);
443 
444         dev_stats->avg_rd_queue_depth =
445             block_acct_queue_depth(ts, BLOCK_ACCT_READ);
446         dev_stats->avg_wr_queue_depth =
447             block_acct_queue_depth(ts, BLOCK_ACCT_WRITE);
448     }
449 }
450 
451 static BlockStats *bdrv_query_bds_stats(BlockDriverState *bs,
452                                         bool blk_level)
453 {
454     BlockStats *s = NULL;
455 
456     s = g_malloc0(sizeof(*s));
457     s->stats = g_malloc0(sizeof(*s->stats));
458 
459     if (!bs) {
460         return s;
461     }
462 
463     /* Skip automatically inserted nodes that the user isn't aware of in
464      * a BlockBackend-level command. Stay at the exact node for a node-level
465      * command. */
466     while (blk_level && bs->drv && bs->implicit) {
467         bs = backing_bs(bs);
468         assert(bs);
469     }
470 
471     if (bdrv_get_node_name(bs)[0]) {
472         s->has_node_name = true;
473         s->node_name = g_strdup(bdrv_get_node_name(bs));
474     }
475 
476     s->stats->wr_highest_offset = stat64_get(&bs->wr_highest_offset);
477 
478     if (bs->file) {
479         s->has_parent = true;
480         s->parent = bdrv_query_bds_stats(bs->file->bs, blk_level);
481     }
482 
483     if (blk_level && bs->backing) {
484         s->has_backing = true;
485         s->backing = bdrv_query_bds_stats(bs->backing->bs, blk_level);
486     }
487 
488     return s;
489 }
490 
491 BlockInfoList *qmp_query_block(Error **errp)
492 {
493     BlockInfoList *head = NULL, **p_next = &head;
494     BlockBackend *blk;
495     Error *local_err = NULL;
496 
497     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
498         BlockInfoList *info;
499 
500         if (!*blk_name(blk) && !blk_get_attached_dev(blk)) {
501             continue;
502         }
503 
504         info = g_malloc0(sizeof(*info));
505         bdrv_query_info(blk, &info->value, &local_err);
506         if (local_err) {
507             error_propagate(errp, local_err);
508             g_free(info);
509             qapi_free_BlockInfoList(head);
510             return NULL;
511         }
512 
513         *p_next = info;
514         p_next = &info->next;
515     }
516 
517     return head;
518 }
519 
520 BlockStatsList *qmp_query_blockstats(bool has_query_nodes,
521                                      bool query_nodes,
522                                      Error **errp)
523 {
524     BlockStatsList *head = NULL, **p_next = &head;
525     BlockBackend *blk;
526     BlockDriverState *bs;
527 
528     /* Just to be safe if query_nodes is not always initialized */
529     if (has_query_nodes && query_nodes) {
530         for (bs = bdrv_next_node(NULL); bs; bs = bdrv_next_node(bs)) {
531             BlockStatsList *info = g_malloc0(sizeof(*info));
532             AioContext *ctx = bdrv_get_aio_context(bs);
533 
534             aio_context_acquire(ctx);
535             info->value = bdrv_query_bds_stats(bs, false);
536             aio_context_release(ctx);
537 
538             *p_next = info;
539             p_next = &info->next;
540         }
541     } else {
542         for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
543             BlockStatsList *info = g_malloc0(sizeof(*info));
544             AioContext *ctx = blk_get_aio_context(blk);
545             BlockStats *s;
546 
547             aio_context_acquire(ctx);
548             s = bdrv_query_bds_stats(blk_bs(blk), true);
549             s->has_device = true;
550             s->device = g_strdup(blk_name(blk));
551             bdrv_query_blk_stats(s->stats, blk);
552             aio_context_release(ctx);
553 
554             info->value = s;
555             *p_next = info;
556             p_next = &info->next;
557         }
558     }
559 
560     return head;
561 }
562 
563 #define NB_SUFFIXES 4
564 
565 static char *get_human_readable_size(char *buf, int buf_size, int64_t size)
566 {
567     static const char suffixes[NB_SUFFIXES] = {'K', 'M', 'G', 'T'};
568     int64_t base;
569     int i;
570 
571     if (size <= 999) {
572         snprintf(buf, buf_size, "%" PRId64, size);
573     } else {
574         base = 1024;
575         for (i = 0; i < NB_SUFFIXES; i++) {
576             if (size < (10 * base)) {
577                 snprintf(buf, buf_size, "%0.1f%c",
578                          (double)size / base,
579                          suffixes[i]);
580                 break;
581             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
582                 snprintf(buf, buf_size, "%" PRId64 "%c",
583                          ((size + (base >> 1)) / base),
584                          suffixes[i]);
585                 break;
586             }
587             base = base * 1024;
588         }
589     }
590     return buf;
591 }
592 
593 void bdrv_snapshot_dump(fprintf_function func_fprintf, void *f,
594                         QEMUSnapshotInfo *sn)
595 {
596     char buf1[128], date_buf[128], clock_buf[128];
597     struct tm tm;
598     time_t ti;
599     int64_t secs;
600 
601     if (!sn) {
602         func_fprintf(f,
603                      "%-10s%-20s%7s%20s%15s",
604                      "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
605     } else {
606         ti = sn->date_sec;
607         localtime_r(&ti, &tm);
608         strftime(date_buf, sizeof(date_buf),
609                  "%Y-%m-%d %H:%M:%S", &tm);
610         secs = sn->vm_clock_nsec / 1000000000;
611         snprintf(clock_buf, sizeof(clock_buf),
612                  "%02d:%02d:%02d.%03d",
613                  (int)(secs / 3600),
614                  (int)((secs / 60) % 60),
615                  (int)(secs % 60),
616                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
617         func_fprintf(f,
618                      "%-10s%-20s%7s%20s%15s",
619                      sn->id_str, sn->name,
620                      get_human_readable_size(buf1, sizeof(buf1),
621                                              sn->vm_state_size),
622                      date_buf,
623                      clock_buf);
624     }
625 }
626 
627 static void dump_qdict(fprintf_function func_fprintf, void *f, int indentation,
628                        QDict *dict);
629 static void dump_qlist(fprintf_function func_fprintf, void *f, int indentation,
630                        QList *list);
631 
632 static void dump_qobject(fprintf_function func_fprintf, void *f,
633                          int comp_indent, QObject *obj)
634 {
635     switch (qobject_type(obj)) {
636         case QTYPE_QNUM: {
637             QNum *value = qobject_to_qnum(obj);
638             char *tmp = qnum_to_string(value);
639             func_fprintf(f, "%s", tmp);
640             g_free(tmp);
641             break;
642         }
643         case QTYPE_QSTRING: {
644             QString *value = qobject_to_qstring(obj);
645             func_fprintf(f, "%s", qstring_get_str(value));
646             break;
647         }
648         case QTYPE_QDICT: {
649             QDict *value = qobject_to_qdict(obj);
650             dump_qdict(func_fprintf, f, comp_indent, value);
651             break;
652         }
653         case QTYPE_QLIST: {
654             QList *value = qobject_to_qlist(obj);
655             dump_qlist(func_fprintf, f, comp_indent, value);
656             break;
657         }
658         case QTYPE_QBOOL: {
659             QBool *value = qobject_to_qbool(obj);
660             func_fprintf(f, "%s", qbool_get_bool(value) ? "true" : "false");
661             break;
662         }
663         default:
664             abort();
665     }
666 }
667 
668 static void dump_qlist(fprintf_function func_fprintf, void *f, int indentation,
669                        QList *list)
670 {
671     const QListEntry *entry;
672     int i = 0;
673 
674     for (entry = qlist_first(list); entry; entry = qlist_next(entry), i++) {
675         QType type = qobject_type(entry->value);
676         bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
677         func_fprintf(f, "%*s[%i]:%c", indentation * 4, "", i,
678                      composite ? '\n' : ' ');
679         dump_qobject(func_fprintf, f, indentation + 1, entry->value);
680         if (!composite) {
681             func_fprintf(f, "\n");
682         }
683     }
684 }
685 
686 static void dump_qdict(fprintf_function func_fprintf, void *f, int indentation,
687                        QDict *dict)
688 {
689     const QDictEntry *entry;
690 
691     for (entry = qdict_first(dict); entry; entry = qdict_next(dict, entry)) {
692         QType type = qobject_type(entry->value);
693         bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
694         char *key = g_malloc(strlen(entry->key) + 1);
695         int i;
696 
697         /* replace dashes with spaces in key (variable) names */
698         for (i = 0; entry->key[i]; i++) {
699             key[i] = entry->key[i] == '-' ? ' ' : entry->key[i];
700         }
701         key[i] = 0;
702         func_fprintf(f, "%*s%s:%c", indentation * 4, "", key,
703                      composite ? '\n' : ' ');
704         dump_qobject(func_fprintf, f, indentation + 1, entry->value);
705         if (!composite) {
706             func_fprintf(f, "\n");
707         }
708         g_free(key);
709     }
710 }
711 
712 void bdrv_image_info_specific_dump(fprintf_function func_fprintf, void *f,
713                                    ImageInfoSpecific *info_spec)
714 {
715     QObject *obj, *data;
716     Visitor *v = qobject_output_visitor_new(&obj);
717 
718     visit_type_ImageInfoSpecific(v, NULL, &info_spec, &error_abort);
719     visit_complete(v, &obj);
720     data = qdict_get(qobject_to_qdict(obj), "data");
721     dump_qobject(func_fprintf, f, 1, data);
722     qobject_decref(obj);
723     visit_free(v);
724 }
725 
726 void bdrv_image_info_dump(fprintf_function func_fprintf, void *f,
727                           ImageInfo *info)
728 {
729     char size_buf[128], dsize_buf[128];
730     if (!info->has_actual_size) {
731         snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
732     } else {
733         get_human_readable_size(dsize_buf, sizeof(dsize_buf),
734                                 info->actual_size);
735     }
736     get_human_readable_size(size_buf, sizeof(size_buf), info->virtual_size);
737     func_fprintf(f,
738                  "image: %s\n"
739                  "file format: %s\n"
740                  "virtual size: %s (%" PRId64 " bytes)\n"
741                  "disk size: %s\n",
742                  info->filename, info->format, size_buf,
743                  info->virtual_size,
744                  dsize_buf);
745 
746     if (info->has_encrypted && info->encrypted) {
747         func_fprintf(f, "encrypted: yes\n");
748     }
749 
750     if (info->has_cluster_size) {
751         func_fprintf(f, "cluster_size: %" PRId64 "\n",
752                        info->cluster_size);
753     }
754 
755     if (info->has_dirty_flag && info->dirty_flag) {
756         func_fprintf(f, "cleanly shut down: no\n");
757     }
758 
759     if (info->has_backing_filename) {
760         func_fprintf(f, "backing file: %s", info->backing_filename);
761         if (!info->has_full_backing_filename) {
762             func_fprintf(f, " (cannot determine actual path)");
763         } else if (strcmp(info->backing_filename,
764                           info->full_backing_filename) != 0) {
765             func_fprintf(f, " (actual path: %s)", info->full_backing_filename);
766         }
767         func_fprintf(f, "\n");
768         if (info->has_backing_filename_format) {
769             func_fprintf(f, "backing file format: %s\n",
770                          info->backing_filename_format);
771         }
772     }
773 
774     if (info->has_snapshots) {
775         SnapshotInfoList *elem;
776 
777         func_fprintf(f, "Snapshot list:\n");
778         bdrv_snapshot_dump(func_fprintf, f, NULL);
779         func_fprintf(f, "\n");
780 
781         /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
782          * we convert to the block layer's native QEMUSnapshotInfo for now.
783          */
784         for (elem = info->snapshots; elem; elem = elem->next) {
785             QEMUSnapshotInfo sn = {
786                 .vm_state_size = elem->value->vm_state_size,
787                 .date_sec = elem->value->date_sec,
788                 .date_nsec = elem->value->date_nsec,
789                 .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
790                                  elem->value->vm_clock_nsec,
791             };
792 
793             pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
794             pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
795             bdrv_snapshot_dump(func_fprintf, f, &sn);
796             func_fprintf(f, "\n");
797         }
798     }
799 
800     if (info->has_format_specific) {
801         func_fprintf(f, "Format specific information:\n");
802         bdrv_image_info_specific_dump(func_fprintf, f, info->format_specific);
803     }
804 }
805