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