qapi.c 26.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * Block layer qmp and info dump related functions
 *
 * Copyright (c) 2003-2008 Fabrice Bellard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

P
Peter Maydell 已提交
25
#include "qemu/osdep.h"
26 27
#include "block/qapi.h"
#include "block/block_int.h"
28
#include "block/throttle-groups.h"
29
#include "block/write-threshold.h"
30
#include "qmp-commands.h"
31 32 33
#include "qapi-visit.h"
#include "qapi/qmp-output-visitor.h"
#include "qapi/qmp/types.h"
34
#include "sysemu/block-backend.h"
35
#include "qemu/cutils.h"
36

37
BlockDeviceInfo *bdrv_block_device_info(BlockDriverState *bs, Error **errp)
38
{
39 40
    ImageInfo **p_image_info;
    BlockDriverState *bs0;
41 42 43 44 45 46 47 48
    BlockDeviceInfo *info = g_malloc0(sizeof(*info));

    info->file                   = g_strdup(bs->filename);
    info->ro                     = bs->read_only;
    info->drv                    = g_strdup(bs->drv->format_name);
    info->encrypted              = bs->encrypted;
    info->encryption_key_missing = bdrv_key_required(bs);

49 50 51 52 53 54 55
    info->cache = g_new(BlockdevCacheInfo, 1);
    *info->cache = (BlockdevCacheInfo) {
        .writeback      = bdrv_enable_write_cache(bs),
        .direct         = !!(bs->open_flags & BDRV_O_NOCACHE),
        .no_flush       = !!(bs->open_flags & BDRV_O_NO_FLUSH),
    };

56 57 58 59 60 61 62 63 64 65 66
    if (bs->node_name[0]) {
        info->has_node_name = true;
        info->node_name = g_strdup(bs->node_name);
    }

    if (bs->backing_file[0]) {
        info->has_backing_file = true;
        info->backing_file = g_strdup(bs->backing_file);
    }

    info->backing_file_depth = bdrv_get_backing_file_depth(bs);
67
    info->detect_zeroes = bs->detect_zeroes;
68

69
    if (bs->throttle_state) {
70
        ThrottleConfig cfg;
71 72 73

        throttle_group_get_config(bs, &cfg);

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        info->bps     = cfg.buckets[THROTTLE_BPS_TOTAL].avg;
        info->bps_rd  = cfg.buckets[THROTTLE_BPS_READ].avg;
        info->bps_wr  = cfg.buckets[THROTTLE_BPS_WRITE].avg;

        info->iops    = cfg.buckets[THROTTLE_OPS_TOTAL].avg;
        info->iops_rd = cfg.buckets[THROTTLE_OPS_READ].avg;
        info->iops_wr = cfg.buckets[THROTTLE_OPS_WRITE].avg;

        info->has_bps_max     = cfg.buckets[THROTTLE_BPS_TOTAL].max;
        info->bps_max         = cfg.buckets[THROTTLE_BPS_TOTAL].max;
        info->has_bps_rd_max  = cfg.buckets[THROTTLE_BPS_READ].max;
        info->bps_rd_max      = cfg.buckets[THROTTLE_BPS_READ].max;
        info->has_bps_wr_max  = cfg.buckets[THROTTLE_BPS_WRITE].max;
        info->bps_wr_max      = cfg.buckets[THROTTLE_BPS_WRITE].max;

        info->has_iops_max    = cfg.buckets[THROTTLE_OPS_TOTAL].max;
        info->iops_max        = cfg.buckets[THROTTLE_OPS_TOTAL].max;
        info->has_iops_rd_max = cfg.buckets[THROTTLE_OPS_READ].max;
        info->iops_rd_max     = cfg.buckets[THROTTLE_OPS_READ].max;
        info->has_iops_wr_max = cfg.buckets[THROTTLE_OPS_WRITE].max;
        info->iops_wr_max     = cfg.buckets[THROTTLE_OPS_WRITE].max;

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        info->has_bps_max_length     = info->has_bps_max;
        info->bps_max_length         =
            cfg.buckets[THROTTLE_BPS_TOTAL].burst_length;
        info->has_bps_rd_max_length  = info->has_bps_rd_max;
        info->bps_rd_max_length      =
            cfg.buckets[THROTTLE_BPS_READ].burst_length;
        info->has_bps_wr_max_length  = info->has_bps_wr_max;
        info->bps_wr_max_length      =
            cfg.buckets[THROTTLE_BPS_WRITE].burst_length;

        info->has_iops_max_length    = info->has_iops_max;
        info->iops_max_length        =
            cfg.buckets[THROTTLE_OPS_TOTAL].burst_length;
        info->has_iops_rd_max_length = info->has_iops_rd_max;
        info->iops_rd_max_length     =
            cfg.buckets[THROTTLE_OPS_READ].burst_length;
        info->has_iops_wr_max_length = info->has_iops_wr_max;
        info->iops_wr_max_length     =
            cfg.buckets[THROTTLE_OPS_WRITE].burst_length;

116 117
        info->has_iops_size = cfg.op_size;
        info->iops_size = cfg.op_size;
118 119 120

        info->has_group = true;
        info->group = g_strdup(throttle_group_get_name(bs));
121 122
    }

123 124
    info->write_threshold = bdrv_write_threshold_get(bs);

125 126 127 128 129 130 131 132 133 134
    bs0 = bs;
    p_image_info = &info->image;
    while (1) {
        Error *local_err = NULL;
        bdrv_query_image_info(bs0, p_image_info, &local_err);
        if (local_err) {
            error_propagate(errp, local_err);
            qapi_free_BlockDeviceInfo(info);
            return NULL;
        }
135 136
        if (bs0->drv && bs0->backing) {
            bs0 = bs0->backing->bs;
137 138 139 140 141 142 143
            (*p_image_info)->has_backing_image = true;
            p_image_info = &((*p_image_info)->backing_image);
        } else {
            break;
        }
    }

144 145 146
    return info;
}

147 148 149 150 151 152 153 154
/*
 * Returns 0 on success, with *p_list either set to describe snapshot
 * information, or NULL because there are no snapshots.  Returns -errno on
 * error, with *p_list untouched.
 */
int bdrv_query_snapshot_info_list(BlockDriverState *bs,
                                  SnapshotInfoList **p_list,
                                  Error **errp)
155 156 157
{
    int i, sn_count;
    QEMUSnapshotInfo *sn_tab = NULL;
158 159 160
    SnapshotInfoList *info_list, *cur_item = NULL, *head = NULL;
    SnapshotInfo *info;

161
    sn_count = bdrv_snapshot_list(bs, &sn_tab);
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    if (sn_count < 0) {
        const char *dev = bdrv_get_device_name(bs);
        switch (sn_count) {
        case -ENOMEDIUM:
            error_setg(errp, "Device '%s' is not inserted", dev);
            break;
        case -ENOTSUP:
            error_setg(errp,
                       "Device '%s' does not support internal snapshots",
                       dev);
            break;
        default:
            error_setg_errno(errp, -sn_count,
                             "Can't list snapshots of device '%s'", dev);
            break;
        }
        return sn_count;
    }
180 181

    for (i = 0; i < sn_count; i++) {
182 183 184 185 186 187 188 189
        info = g_new0(SnapshotInfo, 1);
        info->id            = g_strdup(sn_tab[i].id_str);
        info->name          = g_strdup(sn_tab[i].name);
        info->vm_state_size = sn_tab[i].vm_state_size;
        info->date_sec      = sn_tab[i].date_sec;
        info->date_nsec     = sn_tab[i].date_nsec;
        info->vm_clock_sec  = sn_tab[i].vm_clock_nsec / 1000000000;
        info->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
190

191 192
        info_list = g_new0(SnapshotInfoList, 1);
        info_list->value = info;
193 194 195

        /* XXX: waiting for the qapi to support qemu-queue.h types */
        if (!cur_item) {
196
            head = cur_item = info_list;
197 198 199 200 201 202 203 204
        } else {
            cur_item->next = info_list;
            cur_item = info_list;
        }

    }

    g_free(sn_tab);
205 206
    *p_list = head;
    return 0;
207 208
}

209 210 211 212 213 214
/**
 * bdrv_query_image_info:
 * @bs: block device to examine
 * @p_info: location to store image information
 * @errp: location to store error information
 *
215 216 217 218 219 220 221
 * Store "flat" image information in @p_info.
 *
 * "Flat" means it does *not* query backing image information,
 * i.e. (*pinfo)->has_backing_image will be set to false and
 * (*pinfo)->backing_image to NULL even when the image does in fact have
 * a backing image.
 *
222 223 224 225 226
 * @p_info will be set only on success. On error, store error in @errp.
 */
void bdrv_query_image_info(BlockDriverState *bs,
                           ImageInfo **p_info,
                           Error **errp)
227
{
228
    int64_t size;
229
    const char *backing_filename;
230
    BlockDriverInfo bdi;
231 232
    int ret;
    Error *err = NULL;
233
    ImageInfo *info;
234

235 236
    aio_context_acquire(bdrv_get_aio_context(bs));

237 238 239 240
    size = bdrv_getlength(bs);
    if (size < 0) {
        error_setg_errno(errp, -size, "Can't get size of device '%s'",
                         bdrv_get_device_name(bs));
241
        goto out;
242
    }
243

244
    info = g_new0(ImageInfo, 1);
245
    info->filename        = g_strdup(bs->filename);
246
    info->format          = g_strdup(bdrv_get_format_name(bs));
247
    info->virtual_size    = size;
248 249 250 251 252 253 254 255 256 257 258 259 260 261
    info->actual_size     = bdrv_get_allocated_file_size(bs);
    info->has_actual_size = info->actual_size >= 0;
    if (bdrv_is_encrypted(bs)) {
        info->encrypted = true;
        info->has_encrypted = true;
    }
    if (bdrv_get_info(bs, &bdi) >= 0) {
        if (bdi.cluster_size != 0) {
            info->cluster_size = bdi.cluster_size;
            info->has_cluster_size = true;
        }
        info->dirty_flag = bdi.is_dirty;
        info->has_dirty_flag = true;
    }
M
Max Reitz 已提交
262 263 264
    info->format_specific     = bdrv_get_specific_info(bs);
    info->has_format_specific = info->format_specific != NULL;

265
    backing_filename = bs->backing_file;
266
    if (backing_filename[0] != '\0') {
267
        char *backing_filename2 = g_malloc0(PATH_MAX);
268 269
        info->backing_filename = g_strdup(backing_filename);
        info->has_backing_filename = true;
270
        bdrv_get_full_backing_filename(bs, backing_filename2, PATH_MAX, &err);
271
        if (err) {
J
John Snow 已提交
272 273
            /* Can't reconstruct the full backing filename, so we must omit
             * this field and apply a Best Effort to this query. */
274
            g_free(backing_filename2);
J
John Snow 已提交
275 276
            backing_filename2 = NULL;
            error_free(err);
277
            err = NULL;
278
        }
279

280 281 282 283
        /* Always report the full_backing_filename if present, even if it's the
         * same as backing_filename. That they are same is useful info. */
        if (backing_filename2) {
            info->full_backing_filename = g_strdup(backing_filename2);
284 285 286 287 288 289 290
            info->has_full_backing_filename = true;
        }

        if (bs->backing_format[0]) {
            info->backing_filename_format = g_strdup(bs->backing_format);
            info->has_backing_filename_format = true;
        }
291
        g_free(backing_filename2);
292
    }
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

    ret = bdrv_query_snapshot_info_list(bs, &info->snapshots, &err);
    switch (ret) {
    case 0:
        if (info->snapshots) {
            info->has_snapshots = true;
        }
        break;
    /* recoverable error */
    case -ENOMEDIUM:
    case -ENOTSUP:
        error_free(err);
        break;
    default:
        error_propagate(errp, err);
        qapi_free_ImageInfo(info);
309
        goto out;
310 311 312
    }

    *p_info = info;
313 314 315

out:
    aio_context_release(bdrv_get_aio_context(bs));
316 317
}

318
/* @p_info will be set only on success. */
319 320
static void bdrv_query_info(BlockBackend *blk, BlockInfo **p_info,
                            Error **errp)
321 322
{
    BlockInfo *info = g_malloc0(sizeof(*info));
323 324
    BlockDriverState *bs = blk_bs(blk);
    info->device = g_strdup(blk_name(blk));
325
    info->type = g_strdup("unknown");
326 327
    info->locked = blk_dev_is_medium_locked(blk);
    info->removable = blk_dev_has_removable_media(blk);
328

329
    if (blk_dev_has_tray(blk)) {
330
        info->has_tray_open = true;
331
        info->tray_open = blk_dev_is_tray_open(blk);
332 333
    }

334
    if (blk_iostatus_is_enabled(blk)) {
335
        info->has_io_status = true;
336
        info->io_status = blk_iostatus(blk);
337 338
    }

M
Max Reitz 已提交
339
    if (bs && !QLIST_EMPTY(&bs->dirty_bitmaps)) {
F
Fam Zheng 已提交
340 341 342 343
        info->has_dirty_bitmaps = true;
        info->dirty_bitmaps = bdrv_query_dirty_bitmaps(bs);
    }

M
Max Reitz 已提交
344
    if (bs && bs->drv) {
345
        info->has_inserted = true;
346 347 348
        info->inserted = bdrv_block_device_info(bs, errp);
        if (info->inserted == NULL) {
            goto err;
349
        }
350
    }
351 352 353 354 355 356

    *p_info = info;
    return;

 err:
    qapi_free_BlockInfo(info);
357 358
}

359 360
static BlockStats *bdrv_query_stats(BlockBackend *blk,
                                    const BlockDriverState *bs,
361 362
                                    bool query_backing);

363
static void bdrv_query_blk_stats(BlockDeviceStats *ds, BlockBackend *blk)
364 365 366 367
{
    BlockAcctStats *stats = blk_get_stats(blk);
    BlockAcctTimedStats *ts = NULL;

368 369 370 371
    ds->rd_bytes = stats->nr_bytes[BLOCK_ACCT_READ];
    ds->wr_bytes = stats->nr_bytes[BLOCK_ACCT_WRITE];
    ds->rd_operations = stats->nr_ops[BLOCK_ACCT_READ];
    ds->wr_operations = stats->nr_ops[BLOCK_ACCT_WRITE];
372

373 374 375
    ds->failed_rd_operations = stats->failed_ops[BLOCK_ACCT_READ];
    ds->failed_wr_operations = stats->failed_ops[BLOCK_ACCT_WRITE];
    ds->failed_flush_operations = stats->failed_ops[BLOCK_ACCT_FLUSH];
376

377 378 379
    ds->invalid_rd_operations = stats->invalid_ops[BLOCK_ACCT_READ];
    ds->invalid_wr_operations = stats->invalid_ops[BLOCK_ACCT_WRITE];
    ds->invalid_flush_operations =
380 381
        stats->invalid_ops[BLOCK_ACCT_FLUSH];

382 383 384 385 386 387
    ds->rd_merged = stats->merged[BLOCK_ACCT_READ];
    ds->wr_merged = stats->merged[BLOCK_ACCT_WRITE];
    ds->flush_operations = stats->nr_ops[BLOCK_ACCT_FLUSH];
    ds->wr_total_time_ns = stats->total_time_ns[BLOCK_ACCT_WRITE];
    ds->rd_total_time_ns = stats->total_time_ns[BLOCK_ACCT_READ];
    ds->flush_total_time_ns = stats->total_time_ns[BLOCK_ACCT_FLUSH];
388

389 390 391
    ds->has_idle_time_ns = stats->last_access_time_ns > 0;
    if (ds->has_idle_time_ns) {
        ds->idle_time_ns = block_acct_idle_time_ns(stats);
392 393
    }

394 395
    ds->account_invalid = stats->account_invalid;
    ds->account_failed = stats->account_failed;
396 397 398 399 400

    while ((ts = block_acct_interval_next(stats, ts))) {
        BlockDeviceTimedStatsList *timed_stats =
            g_malloc0(sizeof(*timed_stats));
        BlockDeviceTimedStats *dev_stats = g_malloc0(sizeof(*dev_stats));
401
        timed_stats->next = ds->timed_stats;
402
        timed_stats->value = dev_stats;
403
        ds->timed_stats = timed_stats;
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

        TimedAverage *rd = &ts->latency[BLOCK_ACCT_READ];
        TimedAverage *wr = &ts->latency[BLOCK_ACCT_WRITE];
        TimedAverage *fl = &ts->latency[BLOCK_ACCT_FLUSH];

        dev_stats->interval_length = ts->interval_length;

        dev_stats->min_rd_latency_ns = timed_average_min(rd);
        dev_stats->max_rd_latency_ns = timed_average_max(rd);
        dev_stats->avg_rd_latency_ns = timed_average_avg(rd);

        dev_stats->min_wr_latency_ns = timed_average_min(wr);
        dev_stats->max_wr_latency_ns = timed_average_max(wr);
        dev_stats->avg_wr_latency_ns = timed_average_avg(wr);

        dev_stats->min_flush_latency_ns = timed_average_min(fl);
        dev_stats->max_flush_latency_ns = timed_average_max(fl);
        dev_stats->avg_flush_latency_ns = timed_average_avg(fl);

        dev_stats->avg_rd_queue_depth =
            block_acct_queue_depth(ts, BLOCK_ACCT_READ);
        dev_stats->avg_wr_queue_depth =
            block_acct_queue_depth(ts, BLOCK_ACCT_WRITE);
    }
}

430 431
static void bdrv_query_bds_stats(BlockStats *s, const BlockDriverState *bs,
                                 bool query_backing)
432
{
433 434 435 436 437
    if (bdrv_get_node_name(bs)[0]) {
        s->has_node_name = true;
        s->node_name = g_strdup(bdrv_get_node_name(bs));
    }

438 439
    s->stats->wr_highest_offset = bs->wr_highest_offset;

440 441
    if (bs->file) {
        s->has_parent = true;
442
        s->parent = bdrv_query_stats(NULL, bs->file->bs, query_backing);
443 444
    }

445
    if (query_backing && bs->backing) {
F
Fam Zheng 已提交
446
        s->has_backing = true;
447
        s->backing = bdrv_query_stats(NULL, bs->backing->bs, query_backing);
F
Fam Zheng 已提交
448 449
    }

450 451
}

452 453
static BlockStats *bdrv_query_stats(BlockBackend *blk,
                                    const BlockDriverState *bs,
454 455 456 457 458 459 460
                                    bool query_backing)
{
    BlockStats *s;

    s = g_malloc0(sizeof(*s));
    s->stats = g_malloc0(sizeof(*s->stats));

461
    if (blk) {
462 463
        s->has_device = true;
        s->device = g_strdup(blk_name(blk));
464
        bdrv_query_blk_stats(s->stats, blk);
465 466 467
    }
    if (bs) {
        bdrv_query_bds_stats(s, bs, query_backing);
468 469
    }

470 471 472 473 474 475
    return s;
}

BlockInfoList *qmp_query_block(Error **errp)
{
    BlockInfoList *head = NULL, **p_next = &head;
476
    BlockBackend *blk;
477
    Error *local_err = NULL;
478

479
    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
480
        BlockInfoList *info = g_malloc0(sizeof(*info));
481
        bdrv_query_info(blk, &info->value, &local_err);
482
        if (local_err) {
483
            error_propagate(errp, local_err);
484 485 486
            g_free(info);
            qapi_free_BlockInfoList(head);
            return NULL;
487
        }
488 489 490 491 492 493 494 495

        *p_next = info;
        p_next = &info->next;
    }

    return head;
}

496 497 498 499 500 501 502 503 504 505 506 507 508 509
static bool next_query_bds(BlockBackend **blk, BlockDriverState **bs,
                           bool query_nodes)
{
    if (query_nodes) {
        *bs = bdrv_next_node(*bs);
        return !!*bs;
    }

    *blk = blk_next(*blk);
    *bs = *blk ? blk_bs(*blk) : NULL;

    return !!*blk;
}

510 511 512
BlockStatsList *qmp_query_blockstats(bool has_query_nodes,
                                     bool query_nodes,
                                     Error **errp)
513 514
{
    BlockStatsList *head = NULL, **p_next = &head;
515
    BlockBackend *blk = NULL;
516 517
    BlockDriverState *bs = NULL;

518 519 520
    /* Just to be safe if query_nodes is not always initialized */
    query_nodes = has_query_nodes && query_nodes;

521
    while (next_query_bds(&blk, &bs, query_nodes)) {
522
        BlockStatsList *info = g_malloc0(sizeof(*info));
523 524
        AioContext *ctx = blk ? blk_get_aio_context(blk)
                              : bdrv_get_aio_context(bs);
525 526

        aio_context_acquire(ctx);
527
        info->value = bdrv_query_stats(blk, bs, !query_nodes);
528
        aio_context_release(ctx);
529 530 531 532 533 534 535 536 537 538 539 540

        *p_next = info;
        p_next = &info->next;
    }

    return head;
}

#define NB_SUFFIXES 4

static char *get_human_readable_size(char *buf, int buf_size, int64_t size)
{
S
Stefan Weil 已提交
541
    static const char suffixes[NB_SUFFIXES] = {'K', 'M', 'G', 'T'};
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    int64_t base;
    int i;

    if (size <= 999) {
        snprintf(buf, buf_size, "%" PRId64, size);
    } else {
        base = 1024;
        for (i = 0; i < NB_SUFFIXES; i++) {
            if (size < (10 * base)) {
                snprintf(buf, buf_size, "%0.1f%c",
                         (double)size / base,
                         suffixes[i]);
                break;
            } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
                snprintf(buf, buf_size, "%" PRId64 "%c",
                         ((size + (base >> 1)) / base),
                         suffixes[i]);
                break;
            }
            base = base * 1024;
        }
    }
    return buf;
}

567 568
void bdrv_snapshot_dump(fprintf_function func_fprintf, void *f,
                        QEMUSnapshotInfo *sn)
569 570 571 572 573 574 575
{
    char buf1[128], date_buf[128], clock_buf[128];
    struct tm tm;
    time_t ti;
    int64_t secs;

    if (!sn) {
576 577 578
        func_fprintf(f,
                     "%-10s%-20s%7s%20s%15s",
                     "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
579 580 581 582 583 584 585 586 587 588 589 590
    } else {
        ti = sn->date_sec;
        localtime_r(&ti, &tm);
        strftime(date_buf, sizeof(date_buf),
                 "%Y-%m-%d %H:%M:%S", &tm);
        secs = sn->vm_clock_nsec / 1000000000;
        snprintf(clock_buf, sizeof(clock_buf),
                 "%02d:%02d:%02d.%03d",
                 (int)(secs / 3600),
                 (int)((secs / 60) % 60),
                 (int)(secs % 60),
                 (int)((sn->vm_clock_nsec / 1000000) % 1000));
591 592 593 594 595 596 597
        func_fprintf(f,
                     "%-10s%-20s%7s%20s%15s",
                     sn->id_str, sn->name,
                     get_human_readable_size(buf1, sizeof(buf1),
                                             sn->vm_state_size),
                     date_buf,
                     clock_buf);
598 599 600
    }
}

601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
static void dump_qdict(fprintf_function func_fprintf, void *f, int indentation,
                       QDict *dict);
static void dump_qlist(fprintf_function func_fprintf, void *f, int indentation,
                       QList *list);

static void dump_qobject(fprintf_function func_fprintf, void *f,
                         int comp_indent, QObject *obj)
{
    switch (qobject_type(obj)) {
        case QTYPE_QINT: {
            QInt *value = qobject_to_qint(obj);
            func_fprintf(f, "%" PRId64, qint_get_int(value));
            break;
        }
        case QTYPE_QSTRING: {
            QString *value = qobject_to_qstring(obj);
            func_fprintf(f, "%s", qstring_get_str(value));
            break;
        }
        case QTYPE_QDICT: {
            QDict *value = qobject_to_qdict(obj);
            dump_qdict(func_fprintf, f, comp_indent, value);
            break;
        }
        case QTYPE_QLIST: {
            QList *value = qobject_to_qlist(obj);
            dump_qlist(func_fprintf, f, comp_indent, value);
            break;
        }
        case QTYPE_QFLOAT: {
            QFloat *value = qobject_to_qfloat(obj);
            func_fprintf(f, "%g", qfloat_get_double(value));
            break;
        }
        case QTYPE_QBOOL: {
            QBool *value = qobject_to_qbool(obj);
E
Eric Blake 已提交
637
            func_fprintf(f, "%s", qbool_get_bool(value) ? "true" : "false");
638 639 640 641 642 643 644 645 646 647 648 649 650 651
            break;
        }
        default:
            abort();
    }
}

static void dump_qlist(fprintf_function func_fprintf, void *f, int indentation,
                       QList *list)
{
    const QListEntry *entry;
    int i = 0;

    for (entry = qlist_first(list); entry; entry = qlist_next(entry), i++) {
E
Eric Blake 已提交
652
        QType type = qobject_type(entry->value);
653
        bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
654 655
        func_fprintf(f, "%*s[%i]:%c", indentation * 4, "", i,
                     composite ? '\n' : ' ');
656 657 658 659 660 661 662 663 664 665 666 667 668
        dump_qobject(func_fprintf, f, indentation + 1, entry->value);
        if (!composite) {
            func_fprintf(f, "\n");
        }
    }
}

static void dump_qdict(fprintf_function func_fprintf, void *f, int indentation,
                       QDict *dict)
{
    const QDictEntry *entry;

    for (entry = qdict_first(dict); entry; entry = qdict_next(dict, entry)) {
E
Eric Blake 已提交
669
        QType type = qobject_type(entry->value);
670
        bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
671
        char *key = g_malloc(strlen(entry->key) + 1);
672 673 674 675 676 677 678
        int i;

        /* replace dashes with spaces in key (variable) names */
        for (i = 0; entry->key[i]; i++) {
            key[i] = entry->key[i] == '-' ? ' ' : entry->key[i];
        }
        key[i] = 0;
679 680
        func_fprintf(f, "%*s%s:%c", indentation * 4, "", key,
                     composite ? '\n' : ' ');
681 682 683 684
        dump_qobject(func_fprintf, f, indentation + 1, entry->value);
        if (!composite) {
            func_fprintf(f, "\n");
        }
685
        g_free(key);
686 687 688 689 690 691 692 693 694
    }
}

void bdrv_image_info_specific_dump(fprintf_function func_fprintf, void *f,
                                   ImageInfoSpecific *info_spec)
{
    QmpOutputVisitor *ov = qmp_output_visitor_new();
    QObject *obj, *data;

695
    visit_type_ImageInfoSpecific(qmp_output_get_visitor(ov), NULL, &info_spec,
696
                                 &error_abort);
697 698 699 700 701 702 703
    obj = qmp_output_get_qobject(ov);
    assert(qobject_type(obj) == QTYPE_QDICT);
    data = qdict_get(qobject_to_qdict(obj), "data");
    dump_qobject(func_fprintf, f, 1, data);
    qmp_output_visitor_cleanup(ov);
}

704 705
void bdrv_image_info_dump(fprintf_function func_fprintf, void *f,
                          ImageInfo *info)
706 707 708 709 710 711 712 713 714
{
    char size_buf[128], dsize_buf[128];
    if (!info->has_actual_size) {
        snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
    } else {
        get_human_readable_size(dsize_buf, sizeof(dsize_buf),
                                info->actual_size);
    }
    get_human_readable_size(size_buf, sizeof(size_buf), info->virtual_size);
715 716 717 718 719 720 721 722
    func_fprintf(f,
                 "image: %s\n"
                 "file format: %s\n"
                 "virtual size: %s (%" PRId64 " bytes)\n"
                 "disk size: %s\n",
                 info->filename, info->format, size_buf,
                 info->virtual_size,
                 dsize_buf);
723 724

    if (info->has_encrypted && info->encrypted) {
725
        func_fprintf(f, "encrypted: yes\n");
726 727 728
    }

    if (info->has_cluster_size) {
729 730
        func_fprintf(f, "cluster_size: %" PRId64 "\n",
                       info->cluster_size);
731 732 733
    }

    if (info->has_dirty_flag && info->dirty_flag) {
734
        func_fprintf(f, "cleanly shut down: no\n");
735 736 737
    }

    if (info->has_backing_filename) {
738
        func_fprintf(f, "backing file: %s", info->backing_filename);
739 740 741 742
        if (!info->has_full_backing_filename) {
            func_fprintf(f, " (cannot determine actual path)");
        } else if (strcmp(info->backing_filename,
                          info->full_backing_filename) != 0) {
743
            func_fprintf(f, " (actual path: %s)", info->full_backing_filename);
744
        }
745
        func_fprintf(f, "\n");
746
        if (info->has_backing_filename_format) {
747 748
            func_fprintf(f, "backing file format: %s\n",
                         info->backing_filename_format);
749 750 751 752 753 754
        }
    }

    if (info->has_snapshots) {
        SnapshotInfoList *elem;

755 756 757
        func_fprintf(f, "Snapshot list:\n");
        bdrv_snapshot_dump(func_fprintf, f, NULL);
        func_fprintf(f, "\n");
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772

        /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
         * we convert to the block layer's native QEMUSnapshotInfo for now.
         */
        for (elem = info->snapshots; elem; elem = elem->next) {
            QEMUSnapshotInfo sn = {
                .vm_state_size = elem->value->vm_state_size,
                .date_sec = elem->value->date_sec,
                .date_nsec = elem->value->date_nsec,
                .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
                                 elem->value->vm_clock_nsec,
            };

            pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
            pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
773 774
            bdrv_snapshot_dump(func_fprintf, f, &sn);
            func_fprintf(f, "\n");
775 776
        }
    }
777 778 779 780 781

    if (info->has_format_specific) {
        func_fprintf(f, "Format specific information:\n");
        bdrv_image_info_specific_dump(func_fprintf, f, info->format_specific);
    }
782
}