xref: /openbmc/qemu/block/qapi.c (revision d6032e06)
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 "block/qapi.h"
26 #include "block/block_int.h"
27 #include "qmp-commands.h"
28 #include "qapi-visit.h"
29 #include "qapi/qmp-output-visitor.h"
30 #include "qapi/qmp/types.h"
31 
32 BlockDeviceInfo *bdrv_block_device_info(BlockDriverState *bs)
33 {
34     BlockDeviceInfo *info = g_malloc0(sizeof(*info));
35 
36     info->file                   = g_strdup(bs->filename);
37     info->ro                     = bs->read_only;
38     info->drv                    = g_strdup(bs->drv->format_name);
39     info->encrypted              = bs->encrypted;
40     info->encryption_key_missing = bdrv_key_required(bs);
41 
42     if (bs->node_name[0]) {
43         info->has_node_name = true;
44         info->node_name = g_strdup(bs->node_name);
45     }
46 
47     if (bs->backing_file[0]) {
48         info->has_backing_file = true;
49         info->backing_file = g_strdup(bs->backing_file);
50     }
51 
52     info->backing_file_depth = bdrv_get_backing_file_depth(bs);
53 
54     if (bs->io_limits_enabled) {
55         ThrottleConfig cfg;
56         throttle_get_config(&bs->throttle_state, &cfg);
57         info->bps     = cfg.buckets[THROTTLE_BPS_TOTAL].avg;
58         info->bps_rd  = cfg.buckets[THROTTLE_BPS_READ].avg;
59         info->bps_wr  = cfg.buckets[THROTTLE_BPS_WRITE].avg;
60 
61         info->iops    = cfg.buckets[THROTTLE_OPS_TOTAL].avg;
62         info->iops_rd = cfg.buckets[THROTTLE_OPS_READ].avg;
63         info->iops_wr = cfg.buckets[THROTTLE_OPS_WRITE].avg;
64 
65         info->has_bps_max     = cfg.buckets[THROTTLE_BPS_TOTAL].max;
66         info->bps_max         = cfg.buckets[THROTTLE_BPS_TOTAL].max;
67         info->has_bps_rd_max  = cfg.buckets[THROTTLE_BPS_READ].max;
68         info->bps_rd_max      = cfg.buckets[THROTTLE_BPS_READ].max;
69         info->has_bps_wr_max  = cfg.buckets[THROTTLE_BPS_WRITE].max;
70         info->bps_wr_max      = cfg.buckets[THROTTLE_BPS_WRITE].max;
71 
72         info->has_iops_max    = cfg.buckets[THROTTLE_OPS_TOTAL].max;
73         info->iops_max        = cfg.buckets[THROTTLE_OPS_TOTAL].max;
74         info->has_iops_rd_max = cfg.buckets[THROTTLE_OPS_READ].max;
75         info->iops_rd_max     = cfg.buckets[THROTTLE_OPS_READ].max;
76         info->has_iops_wr_max = cfg.buckets[THROTTLE_OPS_WRITE].max;
77         info->iops_wr_max     = cfg.buckets[THROTTLE_OPS_WRITE].max;
78 
79         info->has_iops_size = cfg.op_size;
80         info->iops_size = cfg.op_size;
81     }
82 
83     return info;
84 }
85 
86 /*
87  * Returns 0 on success, with *p_list either set to describe snapshot
88  * information, or NULL because there are no snapshots.  Returns -errno on
89  * error, with *p_list untouched.
90  */
91 int bdrv_query_snapshot_info_list(BlockDriverState *bs,
92                                   SnapshotInfoList **p_list,
93                                   Error **errp)
94 {
95     int i, sn_count;
96     QEMUSnapshotInfo *sn_tab = NULL;
97     SnapshotInfoList *info_list, *cur_item = NULL, *head = NULL;
98     SnapshotInfo *info;
99 
100     sn_count = bdrv_snapshot_list(bs, &sn_tab);
101     if (sn_count < 0) {
102         const char *dev = bdrv_get_device_name(bs);
103         switch (sn_count) {
104         case -ENOMEDIUM:
105             error_setg(errp, "Device '%s' is not inserted", dev);
106             break;
107         case -ENOTSUP:
108             error_setg(errp,
109                        "Device '%s' does not support internal snapshots",
110                        dev);
111             break;
112         default:
113             error_setg_errno(errp, -sn_count,
114                              "Can't list snapshots of device '%s'", dev);
115             break;
116         }
117         return sn_count;
118     }
119 
120     for (i = 0; i < sn_count; i++) {
121         info = g_new0(SnapshotInfo, 1);
122         info->id            = g_strdup(sn_tab[i].id_str);
123         info->name          = g_strdup(sn_tab[i].name);
124         info->vm_state_size = sn_tab[i].vm_state_size;
125         info->date_sec      = sn_tab[i].date_sec;
126         info->date_nsec     = sn_tab[i].date_nsec;
127         info->vm_clock_sec  = sn_tab[i].vm_clock_nsec / 1000000000;
128         info->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
129 
130         info_list = g_new0(SnapshotInfoList, 1);
131         info_list->value = info;
132 
133         /* XXX: waiting for the qapi to support qemu-queue.h types */
134         if (!cur_item) {
135             head = cur_item = info_list;
136         } else {
137             cur_item->next = info_list;
138             cur_item = info_list;
139         }
140 
141     }
142 
143     g_free(sn_tab);
144     *p_list = head;
145     return 0;
146 }
147 
148 /**
149  * bdrv_query_image_info:
150  * @bs: block device to examine
151  * @p_info: location to store image information
152  * @errp: location to store error information
153  *
154  * Store "flat" image information in @p_info.
155  *
156  * "Flat" means it does *not* query backing image information,
157  * i.e. (*pinfo)->has_backing_image will be set to false and
158  * (*pinfo)->backing_image to NULL even when the image does in fact have
159  * a backing image.
160  *
161  * @p_info will be set only on success. On error, store error in @errp.
162  */
163 void bdrv_query_image_info(BlockDriverState *bs,
164                            ImageInfo **p_info,
165                            Error **errp)
166 {
167     uint64_t total_sectors;
168     const char *backing_filename;
169     char backing_filename2[1024];
170     BlockDriverInfo bdi;
171     int ret;
172     Error *err = NULL;
173     ImageInfo *info = g_new0(ImageInfo, 1);
174 
175     bdrv_get_geometry(bs, &total_sectors);
176 
177     info->filename        = g_strdup(bs->filename);
178     info->format          = g_strdup(bdrv_get_format_name(bs));
179     info->virtual_size    = total_sectors * 512;
180     info->actual_size     = bdrv_get_allocated_file_size(bs);
181     info->has_actual_size = info->actual_size >= 0;
182     if (bdrv_is_encrypted(bs)) {
183         info->encrypted = true;
184         info->has_encrypted = true;
185     }
186     if (bdrv_get_info(bs, &bdi) >= 0) {
187         if (bdi.cluster_size != 0) {
188             info->cluster_size = bdi.cluster_size;
189             info->has_cluster_size = true;
190         }
191         info->dirty_flag = bdi.is_dirty;
192         info->has_dirty_flag = true;
193     }
194     info->format_specific     = bdrv_get_specific_info(bs);
195     info->has_format_specific = info->format_specific != NULL;
196 
197     backing_filename = bs->backing_file;
198     if (backing_filename[0] != '\0') {
199         info->backing_filename = g_strdup(backing_filename);
200         info->has_backing_filename = true;
201         bdrv_get_full_backing_filename(bs, backing_filename2,
202                                        sizeof(backing_filename2));
203 
204         if (strcmp(backing_filename, backing_filename2) != 0) {
205             info->full_backing_filename =
206                         g_strdup(backing_filename2);
207             info->has_full_backing_filename = true;
208         }
209 
210         if (bs->backing_format[0]) {
211             info->backing_filename_format = g_strdup(bs->backing_format);
212             info->has_backing_filename_format = true;
213         }
214     }
215 
216     ret = bdrv_query_snapshot_info_list(bs, &info->snapshots, &err);
217     switch (ret) {
218     case 0:
219         if (info->snapshots) {
220             info->has_snapshots = true;
221         }
222         break;
223     /* recoverable error */
224     case -ENOMEDIUM:
225     case -ENOTSUP:
226         error_free(err);
227         break;
228     default:
229         error_propagate(errp, err);
230         qapi_free_ImageInfo(info);
231         return;
232     }
233 
234     *p_info = info;
235 }
236 
237 /* @p_info will be set only on success. */
238 void bdrv_query_info(BlockDriverState *bs,
239                      BlockInfo **p_info,
240                      Error **errp)
241 {
242     BlockInfo *info = g_malloc0(sizeof(*info));
243     BlockDriverState *bs0;
244     ImageInfo **p_image_info;
245     Error *local_err = NULL;
246     info->device = g_strdup(bs->device_name);
247     info->type = g_strdup("unknown");
248     info->locked = bdrv_dev_is_medium_locked(bs);
249     info->removable = bdrv_dev_has_removable_media(bs);
250 
251     if (bdrv_dev_has_removable_media(bs)) {
252         info->has_tray_open = true;
253         info->tray_open = bdrv_dev_is_tray_open(bs);
254     }
255 
256     if (bdrv_iostatus_is_enabled(bs)) {
257         info->has_io_status = true;
258         info->io_status = bs->iostatus;
259     }
260 
261     if (!QLIST_EMPTY(&bs->dirty_bitmaps)) {
262         info->has_dirty_bitmaps = true;
263         info->dirty_bitmaps = bdrv_query_dirty_bitmaps(bs);
264     }
265 
266     if (bs->drv) {
267         info->has_inserted = true;
268         info->inserted = bdrv_block_device_info(bs);
269 
270         bs0 = bs;
271         p_image_info = &info->inserted->image;
272         while (1) {
273             bdrv_query_image_info(bs0, p_image_info, &local_err);
274             if (local_err) {
275                 error_propagate(errp, local_err);
276                 goto err;
277             }
278             if (bs0->drv && bs0->backing_hd) {
279                 bs0 = bs0->backing_hd;
280                 (*p_image_info)->has_backing_image = true;
281                 p_image_info = &((*p_image_info)->backing_image);
282             } else {
283                 break;
284             }
285         }
286     }
287 
288     *p_info = info;
289     return;
290 
291  err:
292     qapi_free_BlockInfo(info);
293 }
294 
295 BlockStats *bdrv_query_stats(const BlockDriverState *bs)
296 {
297     BlockStats *s;
298 
299     s = g_malloc0(sizeof(*s));
300 
301     if (bs->device_name[0]) {
302         s->has_device = true;
303         s->device = g_strdup(bs->device_name);
304     }
305 
306     s->stats = g_malloc0(sizeof(*s->stats));
307     s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
308     s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
309     s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
310     s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
311     s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
312     s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
313     s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
314     s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
315     s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
316 
317     if (bs->file) {
318         s->has_parent = true;
319         s->parent = bdrv_query_stats(bs->file);
320     }
321 
322     if (bs->backing_hd) {
323         s->has_backing = true;
324         s->backing = bdrv_query_stats(bs->backing_hd);
325     }
326 
327     return s;
328 }
329 
330 BlockInfoList *qmp_query_block(Error **errp)
331 {
332     BlockInfoList *head = NULL, **p_next = &head;
333     BlockDriverState *bs = NULL;
334     Error *local_err = NULL;
335 
336      while ((bs = bdrv_next(bs))) {
337         BlockInfoList *info = g_malloc0(sizeof(*info));
338         bdrv_query_info(bs, &info->value, &local_err);
339         if (local_err) {
340             error_propagate(errp, local_err);
341             goto err;
342         }
343 
344         *p_next = info;
345         p_next = &info->next;
346     }
347 
348     return head;
349 
350  err:
351     qapi_free_BlockInfoList(head);
352     return NULL;
353 }
354 
355 BlockStatsList *qmp_query_blockstats(Error **errp)
356 {
357     BlockStatsList *head = NULL, **p_next = &head;
358     BlockDriverState *bs = NULL;
359 
360      while ((bs = bdrv_next(bs))) {
361         BlockStatsList *info = g_malloc0(sizeof(*info));
362         info->value = bdrv_query_stats(bs);
363 
364         *p_next = info;
365         p_next = &info->next;
366     }
367 
368     return head;
369 }
370 
371 #define NB_SUFFIXES 4
372 
373 static char *get_human_readable_size(char *buf, int buf_size, int64_t size)
374 {
375     static const char suffixes[NB_SUFFIXES] = "KMGT";
376     int64_t base;
377     int i;
378 
379     if (size <= 999) {
380         snprintf(buf, buf_size, "%" PRId64, size);
381     } else {
382         base = 1024;
383         for (i = 0; i < NB_SUFFIXES; i++) {
384             if (size < (10 * base)) {
385                 snprintf(buf, buf_size, "%0.1f%c",
386                          (double)size / base,
387                          suffixes[i]);
388                 break;
389             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
390                 snprintf(buf, buf_size, "%" PRId64 "%c",
391                          ((size + (base >> 1)) / base),
392                          suffixes[i]);
393                 break;
394             }
395             base = base * 1024;
396         }
397     }
398     return buf;
399 }
400 
401 void bdrv_snapshot_dump(fprintf_function func_fprintf, void *f,
402                         QEMUSnapshotInfo *sn)
403 {
404     char buf1[128], date_buf[128], clock_buf[128];
405     struct tm tm;
406     time_t ti;
407     int64_t secs;
408 
409     if (!sn) {
410         func_fprintf(f,
411                      "%-10s%-20s%7s%20s%15s",
412                      "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
413     } else {
414         ti = sn->date_sec;
415         localtime_r(&ti, &tm);
416         strftime(date_buf, sizeof(date_buf),
417                  "%Y-%m-%d %H:%M:%S", &tm);
418         secs = sn->vm_clock_nsec / 1000000000;
419         snprintf(clock_buf, sizeof(clock_buf),
420                  "%02d:%02d:%02d.%03d",
421                  (int)(secs / 3600),
422                  (int)((secs / 60) % 60),
423                  (int)(secs % 60),
424                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
425         func_fprintf(f,
426                      "%-10s%-20s%7s%20s%15s",
427                      sn->id_str, sn->name,
428                      get_human_readable_size(buf1, sizeof(buf1),
429                                              sn->vm_state_size),
430                      date_buf,
431                      clock_buf);
432     }
433 }
434 
435 static void dump_qdict(fprintf_function func_fprintf, void *f, int indentation,
436                        QDict *dict);
437 static void dump_qlist(fprintf_function func_fprintf, void *f, int indentation,
438                        QList *list);
439 
440 static void dump_qobject(fprintf_function func_fprintf, void *f,
441                          int comp_indent, QObject *obj)
442 {
443     switch (qobject_type(obj)) {
444         case QTYPE_QINT: {
445             QInt *value = qobject_to_qint(obj);
446             func_fprintf(f, "%" PRId64, qint_get_int(value));
447             break;
448         }
449         case QTYPE_QSTRING: {
450             QString *value = qobject_to_qstring(obj);
451             func_fprintf(f, "%s", qstring_get_str(value));
452             break;
453         }
454         case QTYPE_QDICT: {
455             QDict *value = qobject_to_qdict(obj);
456             dump_qdict(func_fprintf, f, comp_indent, value);
457             break;
458         }
459         case QTYPE_QLIST: {
460             QList *value = qobject_to_qlist(obj);
461             dump_qlist(func_fprintf, f, comp_indent, value);
462             break;
463         }
464         case QTYPE_QFLOAT: {
465             QFloat *value = qobject_to_qfloat(obj);
466             func_fprintf(f, "%g", qfloat_get_double(value));
467             break;
468         }
469         case QTYPE_QBOOL: {
470             QBool *value = qobject_to_qbool(obj);
471             func_fprintf(f, "%s", qbool_get_int(value) ? "true" : "false");
472             break;
473         }
474         case QTYPE_QERROR: {
475             QString *value = qerror_human((QError *)obj);
476             func_fprintf(f, "%s", qstring_get_str(value));
477             break;
478         }
479         case QTYPE_NONE:
480             break;
481         case QTYPE_MAX:
482         default:
483             abort();
484     }
485 }
486 
487 static void dump_qlist(fprintf_function func_fprintf, void *f, int indentation,
488                        QList *list)
489 {
490     const QListEntry *entry;
491     int i = 0;
492 
493     for (entry = qlist_first(list); entry; entry = qlist_next(entry), i++) {
494         qtype_code type = qobject_type(entry->value);
495         bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
496         const char *format = composite ? "%*s[%i]:\n" : "%*s[%i]: ";
497 
498         func_fprintf(f, format, indentation * 4, "", i);
499         dump_qobject(func_fprintf, f, indentation + 1, entry->value);
500         if (!composite) {
501             func_fprintf(f, "\n");
502         }
503     }
504 }
505 
506 static void dump_qdict(fprintf_function func_fprintf, void *f, int indentation,
507                        QDict *dict)
508 {
509     const QDictEntry *entry;
510 
511     for (entry = qdict_first(dict); entry; entry = qdict_next(dict, entry)) {
512         qtype_code type = qobject_type(entry->value);
513         bool composite = (type == QTYPE_QDICT || type == QTYPE_QLIST);
514         const char *format = composite ? "%*s%s:\n" : "%*s%s: ";
515         char key[strlen(entry->key) + 1];
516         int i;
517 
518         /* replace dashes with spaces in key (variable) names */
519         for (i = 0; entry->key[i]; i++) {
520             key[i] = entry->key[i] == '-' ? ' ' : entry->key[i];
521         }
522         key[i] = 0;
523 
524         func_fprintf(f, format, indentation * 4, "", key);
525         dump_qobject(func_fprintf, f, indentation + 1, entry->value);
526         if (!composite) {
527             func_fprintf(f, "\n");
528         }
529     }
530 }
531 
532 void bdrv_image_info_specific_dump(fprintf_function func_fprintf, void *f,
533                                    ImageInfoSpecific *info_spec)
534 {
535     Error *local_err = NULL;
536     QmpOutputVisitor *ov = qmp_output_visitor_new();
537     QObject *obj, *data;
538 
539     visit_type_ImageInfoSpecific(qmp_output_get_visitor(ov), &info_spec, NULL,
540                                  &local_err);
541     obj = qmp_output_get_qobject(ov);
542     assert(qobject_type(obj) == QTYPE_QDICT);
543     data = qdict_get(qobject_to_qdict(obj), "data");
544     dump_qobject(func_fprintf, f, 1, data);
545     qmp_output_visitor_cleanup(ov);
546 }
547 
548 void bdrv_image_info_dump(fprintf_function func_fprintf, void *f,
549                           ImageInfo *info)
550 {
551     char size_buf[128], dsize_buf[128];
552     if (!info->has_actual_size) {
553         snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
554     } else {
555         get_human_readable_size(dsize_buf, sizeof(dsize_buf),
556                                 info->actual_size);
557     }
558     get_human_readable_size(size_buf, sizeof(size_buf), info->virtual_size);
559     func_fprintf(f,
560                  "image: %s\n"
561                  "file format: %s\n"
562                  "virtual size: %s (%" PRId64 " bytes)\n"
563                  "disk size: %s\n",
564                  info->filename, info->format, size_buf,
565                  info->virtual_size,
566                  dsize_buf);
567 
568     if (info->has_encrypted && info->encrypted) {
569         func_fprintf(f, "encrypted: yes\n");
570     }
571 
572     if (info->has_cluster_size) {
573         func_fprintf(f, "cluster_size: %" PRId64 "\n",
574                        info->cluster_size);
575     }
576 
577     if (info->has_dirty_flag && info->dirty_flag) {
578         func_fprintf(f, "cleanly shut down: no\n");
579     }
580 
581     if (info->has_backing_filename) {
582         func_fprintf(f, "backing file: %s", info->backing_filename);
583         if (info->has_full_backing_filename) {
584             func_fprintf(f, " (actual path: %s)", info->full_backing_filename);
585         }
586         func_fprintf(f, "\n");
587         if (info->has_backing_filename_format) {
588             func_fprintf(f, "backing file format: %s\n",
589                          info->backing_filename_format);
590         }
591     }
592 
593     if (info->has_snapshots) {
594         SnapshotInfoList *elem;
595 
596         func_fprintf(f, "Snapshot list:\n");
597         bdrv_snapshot_dump(func_fprintf, f, NULL);
598         func_fprintf(f, "\n");
599 
600         /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
601          * we convert to the block layer's native QEMUSnapshotInfo for now.
602          */
603         for (elem = info->snapshots; elem; elem = elem->next) {
604             QEMUSnapshotInfo sn = {
605                 .vm_state_size = elem->value->vm_state_size,
606                 .date_sec = elem->value->date_sec,
607                 .date_nsec = elem->value->date_nsec,
608                 .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
609                                  elem->value->vm_clock_nsec,
610             };
611 
612             pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
613             pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
614             bdrv_snapshot_dump(func_fprintf, f, &sn);
615             func_fprintf(f, "\n");
616         }
617     }
618 
619     if (info->has_format_specific) {
620         func_fprintf(f, "Format specific information:\n");
621         bdrv_image_info_specific_dump(func_fprintf, f, info->format_specific);
622     }
623 }
624