Skip to contentSkip to conversation

Support fd-based KVM stats

PATCH Superseded Mark Kanda 4 participants 17 messages Jan 31, 2022 – Feb 11, 2022

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Mark Kanda

author
#0 lore raw

v3 cover Support fd-based KVM stats

v3:
- various QMP API enhancements from v2 review [1] [Daniel, Paolo, Igor]
- general cleanup

v2: [Paolo]
- generalize the interface
- add support for querying stat schema and instances
- add additional HMP semantic processing for a few exponent/unit combinations (related to seconds and bytes)

This patchset adds QEMU support for querying fd-based KVM stats. The kernel support was introduced by:

cb082bfab59a ("KVM: stats: Add fd-based API to read binary stats data")

[1] https://lore.kernel.org/all/[email protected]/

Mark Kanda (3):
qmp: Support for querying stats
hmp: Support for querying stats
kvm: Support for querying fd-based stats

 accel/kvm/kvm-all.c     | 308 ++++++++++++++++++++++++++++++++++++++++
 hmp-commands-info.hx    |  28 ++++
 include/monitor/hmp.h   |   2 +
 include/monitor/stats.h |  36 +++++
 monitor/hmp-cmds.c      | 288 +++++++++++++++++++++++++++++++++++++
 monitor/qmp-cmds.c      | 183 ++++++++++++++++++++++++
 qapi/misc.json          | 253 +++++++++++++++++++++++++++++++++
 7 files changed, 1098 insertions(+)
 create mode 100644 include/monitor/stats.h
Signature · 1 line
2.27.0
author
#13 lore raw

PATCH v3 2/3 hmp: Support for querying stats

Leverage the QMP support for querying stats. The interface supports the same arguments as the QMP interface. Wildcard char (*) is accepted for names and stats target.

Examples (with fd-based KVM stats):

- Display all stats
(qemu) info stats
vm
provider: kvm
max_mmu_page_hash_collisions (peak): 0
max_mmu_rmap_size (peak): 0
...
vcpu (qom path: /machine/unattached/device[0])
provider: kvm
guest_mode (instant): 0
directed_yield_successful (cumulative): 0
...

(qemu) info stats-schemas
vm
provider: kvm
max_mmu_page_hash_collisions (peak)
max_mmu_rmap_size (peak)
...
vcpu
provider: kvm
guest_mode (instant)
directed_yield_successful (cumulative)

- Display 'halt_wait_ns' and 'exits' for vCPUs with qom paths /machine/unattached/device[2] and /machine/unattached/device[4]:

(qemu) info stats exits,halt_wait_ns /machine/unattached/device[2], /machine/unattached/device[4]

vcpu (qom path: /machine/unattached/device[2])
provider: kvm

    exits (cumulative): 52369
    halt_wait_ns (cumulative nanoseconds): 416092704390
vcpu (qom path: /machine/unattached/device[4])
  provider: kvm
    exits (cumulative): 52550
    halt_wait_ns (cumulative nanoseconds): 419637402657

- Display all VM stats for provider KVM:

(qemu) info stats * vm kvm
vm
provider: kvm
max_mmu_page_hash_collisions (peak): 0
max_mmu_rmap_size (peak): 0
nx_lpage_splits (instant): 51
...

---
 hmp-commands-info.hx  |  28 ++++
 include/monitor/hmp.h |   2 +
 monitor/hmp-cmds.c    | 288 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 318 insertions(+)
hmp-commands-info.hx +28 -0
index e90f20a107..7365a8e002 100644
@@ -879,3 +879,31 @@ SRST
   ``info sgx``
     Show intel SGX information.
 ERST
+
+    {
+        .name       = "stats",
+        .args_type  = "names:s?,paths:s?,provider:s?",
+        .params     = "[names] [paths] [provider]",
+        .help       = "show statistics; optional comma separated names, "
+	              "vcpu qom paths, and provider",
+        .cmd        = hmp_info_stats,
+    },
+
+SRST
+  ``stats``
+    Show stats
+ERST
+
+    {
+        .name       = "stats-schemas",
+        .args_type  = "provider:s?",
+        .params     = "[provider]",
+        .help       = "show statistics schema for each provider",
+        .cmd        = hmp_info_stats_schemas,
+    },
+
+SRST
+  ``stats-schemas``
+    Show stats per schema
+ERST
+
include/monitor/hmp.h +2 -0
index 96d014826a..a748511105 100644
@@ -133,5 +133,7 @@ void hmp_info_dirty_rate(Monitor *mon, const QDict *qdict);
 void hmp_calc_dirty_rate(Monitor *mon, const QDict *qdict);
 void hmp_human_readable_text_helper(Monitor *mon,
                                     HumanReadableText *(*qmp_handler)(Error **));
+void hmp_info_stats(Monitor *mon, const QDict *qdict);
+void hmp_info_stats_schemas(Monitor *mon, const QDict *qdict);
 
 #endif
monitor/hmp-cmds.c +288 -0

291 lines not on this page · raw message

Signature · 1 line
2.27.0
author
#14 lore raw

PATCH v3 3/3 kvm: Support for querying fd-based stats

In reply to Mark Kanda

Add support for querying fd-based KVM stats - as introduced by Linux kernel commit:

cb082bfab59a ("KVM: stats: Add fd-based API to read binary stats data")

---
 accel/kvm/kvm-all.c | 308 ++++++++++++++++++++++++++++++++++++++++++++
 qapi/misc.json      |   2 +-
 2 files changed, 309 insertions(+), 1 deletion(-)
accel/kvm/kvm-all.c +308 -0
index 0e66ebb497..e43e1f1c1c 100644
@@ -47,6 +47,8 @@
 #include "kvm-cpus.h"
 
 #include "hw/boards.h"
+#include "qapi/qapi-commands-misc.h"
+#include "monitor/stats.h"
 
 /* This check must be after config-host.h is included */
 #ifdef CONFIG_EVENTFD
@@ -2309,6 +2311,9 @@ bool kvm_dirty_ring_enabled(void)
     return kvm_state->kvm_dirty_ring_size ? true : false;
 }
 
+static void query_stats_cb(StatsResults *, StatsFilter *, Error **);
+static void query_stats_schemas_cb(StatsSchemaResult *, Error **);
+
 static int kvm_init(MachineState *ms)
 {
     MachineClass *mc = MACHINE_GET_CLASS(ms);
@@ -2637,6 +2642,11 @@ static int kvm_init(MachineState *ms)
         }
     }
 
+    if (kvm_check_extension(kvm_state, KVM_CAP_BINARY_STATS_FD)) {
+        add_stats_callbacks(STATS_PROVIDER_KVM, &query_stats_cb,
+                            &query_stats_schemas_cb);
+    }
+
     return 0;
 
 err:
@@ -3696,3 +3706,301 @@ static void kvm_type_init(void)
 }
 
 type_init(kvm_type_init);
+
+typedef struct StatsArgs {
+    StatsFilter *filter;
+    bool is_schema;
+    union {
+        StatsResults *stats;
+        StatsSchemaResult *schema;
+    } result;
+    Error **errp;
+} StatsArgs;
+
+static StatsList *add_kvmstat_entry(struct kvm_stats_desc *pdesc,
+                                    uint64_t *stats_data,
+                                    StatsList *stats_list,
+                                    Error **errp)
+{
+    StatsList *stats_entry = g_malloc0(sizeof(*stats_entry));
+    Stats *stats = g_malloc0(sizeof(*stats));
+    uint64List *val_list = NULL;
+    int i;
+
+    stats->name = g_strdup(pdesc->name);
+    stats->value = g_malloc0(sizeof(*stats->value));
+
+    /* Alloc and populate data list */
+    if (pdesc->size == 1) {
+        stats->value->u.scalar = *stats_data;
+        stats->value->type = QTYPE_QNUM;
+    } else {
+        for (i = 0; i < pdesc->size; i++) {
+            uint64List *val_entry = g_malloc0(sizeof(*val_entry));
+            val_entry->value = stats_data[i];
+            val_entry->next = val_list;
+            val_list = val_entry;
+        }
+        stats->value->u.list.list = val_list;
+        stats->value->type = QTYPE_QDICT;
+    }
+
+    stats_entry->value = stats;
+    stats_entry->next = stats_list;
+
+    return stats_entry;
+}
+
+static StatsSchemaValueList *add_kvmschema_entry(struct kvm_stats_desc *pdesc,
+                                                 StatsSchemaValueList *list,
+                                                 Error **errp)
+{
+    StatsSchemaValueList *schema_entry;
+
+    schema_entry = g_malloc0(sizeof(*schema_entry));
+    schema_entry->value = g_malloc0(sizeof(*schema_entry->value));
+    schema_entry->value->name = g_strdup(pdesc->name);
+
+    switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
+    case KVM_STATS_TYPE_CUMULATIVE:
+        schema_entry->value->type = STAT_TYPE_CUMULATIVE;
+        break;
+    case KVM_STATS_TYPE_INSTANT:
+        schema_entry->value->type = STAT_TYPE_INSTANT;
+        break;
+    case KVM_STATS_TYPE_PEAK:
+        schema_entry->value->type = STAT_TYPE_PEAK;
+        break;
+    case KVM_STATS_TYPE_LINEAR_HIST:
+        schema_entry->value->type = STAT_TYPE_LINEAR_HIST;
+        break;
+    case KVM_STATS_TYPE_LOG_HIST:
+        schema_entry->value->type = STAT_TYPE_LOG_HIST;
+        break;
+    default:
+        schema_entry->value->type = STAT_TYPE_UNKNOWN;
+    }
+
+    switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
+    case KVM_STATS_UNIT_NONE:
+        schema_entry->value->unit = STAT_UNIT_NONE;
+        break;
+    case KVM_STATS_UNIT_BYTES:
+        schema_entry->value->unit = STAT_UNIT_BYTES;
+        break;
+    case KVM_STATS_UNIT_CYCLES:
+        schema_entry->value->unit = STAT_UNIT_CYCLES;
+        break;
+    case KVM_STATS_UNIT_SECONDS:
+        schema_entry->value->unit = STAT_UNIT_SECONDS;
+        break;
+    default:
+        schema_entry->value->unit = STAT_UNIT_UNKNOWN;
+    }
+
+    switch (pdesc->flags & KVM_STATS_BASE_MASK) {
+    case KVM_STATS_BASE_POW10:
+        schema_entry->value->base = STAT_BASE_POW10;
+        break;
+    case KVM_STATS_BASE_POW2:
+        schema_entry->value->base = STAT_BASE_POW2;
+        break;
+    default:
+        schema_entry->value->base = STAT_BASE_UNKNOWN;
+    }
+
+    schema_entry->value->exponent = pdesc->exponent;
+    schema_entry->next = list;
+    return schema_entry;
+}
+
+static void query_stats(StatsArgs *kvm_stat_args, int stats_fd)
+{
+    size_t size_desc, size_data;
+    struct kvm_stats_header *header;
+    struct kvm_stats_desc *stats_desc = NULL;
+    Error *local_err = NULL;
+    void *stats_list = NULL;
+    char *id = NULL;
+    ssize_t ret;
+    int i;
+
+    /* Read KVM stats header */
+    header = g_malloc(sizeof(*header));
+    ret = read(stats_fd, header, sizeof(*header));
+    if (ret != sizeof(*header)) {
+        error_setg(&local_err, "KVM stats: failed to read stats header: "
+                   "expected %zu actual %zu", sizeof(*header), ret);
+        goto exit;
+    }
+    size_desc = sizeof(*stats_desc) + header->name_size;
+
+    /* Read KVM stats id string */
+    id = g_malloc(header->name_size);
+    ret = read(stats_fd, id, header->name_size);
+    if (ret != header->name_size) {
+        error_setg(&local_err, "KVM stats: failed to read id string: "
+                   "expected %zu actual %zu", (size_t) header->name_size, ret);
+        goto exit;
+    }
+
+    /* Read KVM stats descriptors */
+    stats_desc = g_malloc0(header->num_desc * size_desc);
+    ret = pread(stats_fd, stats_desc,
+                size_desc * header->num_desc, header->desc_offset);
+
+    if (ret != size_desc * header->num_desc) {
+        error_setg(&local_err, "KVM stats: failed to read stats descriptors: "
+                   "expected %zu actual %zu",
+                   size_desc * header->num_desc, ret);
+        goto exit;
+    }
+
+    for (i = 0; i < header->num_desc; ++i) {
+        struct kvm_stats_desc *pdesc = (void *)stats_desc + i * size_desc;
+        size_data = pdesc->size * sizeof(uint64_t);
+
+        uint64_t *stats_data = g_malloc(size_data);
+
+        ret = pread(stats_fd, stats_data, size_data,
+                    header->data_offset + pdesc->offset);
+
+        if (ret != pdesc->size * sizeof(*stats_data)) {
+            error_setg(&local_err, "KVM stats: failed to read data: "
+                       "expected %zu actual %zu",
+                       pdesc->size * sizeof(*stats_data), ret);
+            g_free(stats_data);
+            goto exit;
+        }
+
+        /* Add entry to the list */
+        if (kvm_stat_args->is_schema) {
+            stats_list = add_kvmschema_entry(pdesc, (StatsSchemaValueList *)
+                                             stats_list, &local_err);
+        } else {
+            if (stat_name_filter(kvm_stat_args->filter,
+                                 kvm_stat_args->filter->target, pdesc->name)) {
+                g_free(stats_data);
+                continue;
+            }
+            stats_list = add_kvmstat_entry(pdesc, stats_data,
+                                           (StatsList *) stats_list,
+                                           &local_err);
+        }
+        g_free(stats_data);
+    }
+
+    if (!stats_list) {
+        goto exit;
+    }
+
+    if (kvm_stat_args->is_schema) {
+        StatsSchemaProvider *provider;
+        if (kvm_stat_args->filter->target == STATS_TARGET_VM) {
+            provider = add_vm_stats_schema(kvm_stat_args->result.schema,
+                                           STATS_PROVIDER_KVM);
+        } else if (kvm_stat_args->filter->target == STATS_TARGET_VCPU) {
+            provider = add_vcpu_stats_schema(kvm_stat_args->result.schema,
+                                             STATS_PROVIDER_KVM);
+        }
+        provider->stats = (StatsSchemaValueList *)stats_list;
+    } else {
+        StatsResultsEntry *results;
+        if (kvm_stat_args->filter->target == STATS_TARGET_VM) {
+            results = add_vm_stats_entry(kvm_stat_args->result.stats,
+                                         STATS_PROVIDER_KVM);
+        } else if (kvm_stat_args->filter->target == STATS_TARGET_VCPU) {
+            results =
+                add_vcpu_stats_entry(kvm_stat_args->result.stats,
+                                     STATS_PROVIDER_KVM,
+                                     current_cpu->parent_obj.canonical_path);
+        }
+        results->stats = (StatsList *)stats_list;
+    }
+exit:
+    error_propagate(kvm_stat_args->errp, local_err);
+    g_free(stats_desc);
+    g_free(id);
+    g_free(header);
+}
+
+static void query_stats_vcpu(CPUState *cpu, run_on_cpu_data data)
+{
+    StatsArgs *kvm_stats_args = (StatsArgs *) data.host_ptr;
+    int stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
+    Error *local_err = NULL;
+
+    if (stats_fd == -1) {
+        error_setg(&local_err, "KVM stats: ioctl failed");
+        error_propagate(kvm_stats_args->errp, local_err);
+        return;
+    }
+    query_stats(kvm_stats_args, stats_fd);
+    close(stats_fd);
+}
+
+static void query_stats_cb(StatsResults *stats_result, StatsFilter *filter,
+                           Error **errp)
+{
+    KVMState *s = kvm_state;
+    CPUState *cpu;
+    int stats_fd;
+    StatsArgs *stats_args = g_malloc0(sizeof(*stats_args));
+    stats_args->filter = filter;
+    stats_args->errp = errp;
+    stats_args->result.stats = stats_result;
+
+    switch (filter->target) {
+    case STATS_TARGET_VM:
+        stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
+        if (stats_fd == -1) {
+            error_setg(errp, "KVM stats: ioctl failed");
+            goto done;
+        }
+
+        query_stats(stats_args, stats_fd);
+        break;
+    case STATS_TARGET_VCPU:
+        CPU_FOREACH(cpu) {
+            if (stat_cpu_filter(filter, cpu->parent_obj.canonical_path)) {
+                continue;
+            }
+            run_on_cpu(cpu, query_stats_vcpu, RUN_ON_CPU_HOST_PTR(stats_args));
+        }
+        break;
+    default:
+        break;
+    }
+done:
+    g_free(stats_args);
+}
+
+void query_stats_schemas_cb(StatsSchemaResult *stats_result, Error **errp)
+{
+    KVMState *s = kvm_state;
+    int stats_fd;
+    StatsArgs *stats_args =  g_malloc0(sizeof(*stats_args));
+    stats_args->filter = g_malloc0(sizeof(*stats_args->filter));
+    stats_args->errp = errp;
+
+    stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
+    if (stats_fd == -1) {
+        error_setg(errp, "KVM stats: ioctl failed");
+        goto done;
+    }
+
+    stats_args->result.schema = stats_result;
+    stats_args->is_schema = true;
+
+    /* Query VM */
+    stats_args->filter->target = STATS_TARGET_VM;
+    query_stats(stats_args, stats_fd);
+
+    /* Query vCPU */
+    stats_args->filter->target = STATS_TARGET_VCPU;
+    run_on_cpu(first_cpu, query_stats_vcpu, RUN_ON_CPU_HOST_PTR(stats_args));
+done:
+    g_free(stats_args->filter);
+    g_free(stats_args);
+}
+
qapi/misc.json +1 -1
index 8d326464f0..39a7d172cb 100644
@@ -574,7 +574,7 @@
 # Since: 7.0
 ##
 { 'enum': 'StatsProvider',
-  'data': [ ] }
+  'data': [ 'kvm' ] }
 
 ##
 # @StatsTarget:
Signature · 1 line
2.27.0
author
#1 lore raw

PATCH v3 1/3 qmp: Support for querying stats

In reply to Mark Kanda

Introduce QMP support for querying stats. Provide a framework for adding new stats and support for the following commands:

- query-stats
Returns a list of all stats per target type (only VM and VCPU for now), with additional options for specifying stat names, VCPU qom paths, and stat provider.

- query-stats-schemas
Returns a list of stats included in each schema type, with an option for specifying the stat provider.

The framework provides a method to register callbacks for these QMP commands.

The first usecase will be for fd-based KVM stats (in an upcoming patch).

Examples (with fd-based KVM stats):

- Display all VM stats:

{ "execute": "query-stats", "arguments" : { "target": "vm" } }

{ "return": {
    "list": [
      { "provider": "kvm",
        "stats": [
          { "name": "max_mmu_page_hash_collisions", "value": 0 },
          { "name": "max_mmu_rmap_size", "value": 0 },
          { "name": "nx_lpage_splits", "value": 131 },
         ...
        ] }
      { "provider": "provider XYZ",
      ...
    ],
    "target": "vm"

}
}

- Display all VCPU stats:

{ "execute": "query-stats", "arguments" : { "target": "vcpu" } }

{ "return": {
    "list": [
      { "list": [
          { "provider": "kvm",
            "stats": [
              { "name": "guest_mode", "value": 0 },
              { "name": "directed_yield_successful", "value": 0  },
              { "name": "directed_yield_attempted", "value": 76 },
              ...
            ] }
	  { "provider": "provider XYZ",
	  ...
        ],
        "path": "/machine/unattached/device[0]"
      },
      { "list": [
          { "provider": "kvm",
            "stats": [
              { "name": "guest_mode", "value": 0 },
              { "name": "directed_yield_successful", "value": 0 },
              { "name": "directed_yield_attempted", "value": 51 },
              ...
      }
    ],
    "target": "vcpu"

}
}

- Display 'exits' and 'l1d_flush' KVM stats for VCPUs at '/machine/unattached/device[2]' and '/machine/unattached/device[4]':

{ "execute": "query-stats",
"arguments" : { "target": "vcpu",

                  "fields": [ "exits", "l1d_flush" ],
	          "paths": [ "/machine/unattached/device[2]",
	                      "/machine/unattached/device[4]" ]
                  "provider": "kvm" } }
{ "return": {
    "list": [
      { "list": [
          { "provider": "kvm",
            "stats": [
              { "name": "l1d_flush", "value": 14690 },
              { "name": "exits", "value": 50898 }
            ] }
        ],
        "path": "/machine/unattached/device[2]"
      },
      { "list": [
          { "provider": "kvm",
            "stats": [
              { "name": "l1d_flush", "value": 24902 },
              { "name": "exits", "value": 74374 }
            ] }
	 ],
        "path": "/machine/unattached/device[4]"
      }
    ],
    "target": "vcpu"

}
}

- Query stats schemas:

{ "execute": "query-stats-schemas" }

{ "return": {
    "vcpu": [
      { "provider": "kvm",
        "stats": [
           { "name": "guest_mode",
             "unit": "none",
             "base": 10,
             "exponent": 0,
             "type": "instant" },
	   { "name": "directed_yield_successful",
             "unit": "none",
             "base": 10,
             "exponent": 0,
             "type": "cumulative" },
             ...
	"provider": "provider XYZ",
...
   "vm": [
      { "provider": "kvm",
        "stats": [
           { "name": "max_mmu_page_hash_collisions",
             "unit": "none",
             "base": 10,
             "exponent": 0,
             "type": "peak" },
	"provider": "provider XYZ",

...

---
 include/monitor/stats.h |  36 ++++++
 monitor/qmp-cmds.c      | 183 +++++++++++++++++++++++++++++
 qapi/misc.json          | 253 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 472 insertions(+)
 create mode 100644 include/monitor/stats.h
include/monitor/stats.h new file +36 -0
new file mode 100644
index 0000000000..d4b57322eb
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2022 Oracle and/or its affiliates.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2.
+ * See the COPYING file in the top-level directory.
+ */
+
+#ifndef STATS_H
+#define STATS_H
+
+/*
+ * Add qmp stats callbacks to the stats_callbacks list.
+ *
+ * @provider: stats provider
+ *
+ * @stats_fn: routine to query stats:
+ *    void (*stats_fn)(StatsResults *results, StatsFilter *filter, Error **errp)
+ *
+ * @schema_fn: routine to query stat schemas:
+ *    void (*schemas_fn)(StatsSchemaResult *results, Error **errp)
+ */
+void add_stats_callbacks(StatsProvider provider,
+                         void (*stats_fn)(StatsResults *, StatsFilter *,
+                                          Error **),
+                         void (*schemas_fn)(StatsSchemaResult *, Error **));
+
+/* Stats helpers routines */
+StatsResultsEntry *add_vm_stats_entry(StatsResults *, StatsProvider);
+StatsResultsEntry *add_vcpu_stats_entry(StatsResults *, StatsProvider, char *);
+StatsSchemaProvider *add_vm_stats_schema(StatsSchemaResult *, StatsProvider);
+StatsSchemaProvider *add_vcpu_stats_schema(StatsSchemaResult *, StatsProvider);
+
+bool stat_name_filter(StatsFilter *, StatsTarget, char *);
+bool stat_cpu_filter(StatsFilter *, char *);
+
+#endif /* STATS_H */
monitor/qmp-cmds.c +183 -0

192 lines not on this page · raw message

qapi/misc.json +253 -0

256 lines not on this page · raw message

Signature · 1 line
2.27.0
#15 lore raw

Re: [PATCH v3 3/3] kvm: Support for querying fd-based stats

In reply to Mark Kanda
Quoted 149 lines · Mark Kanda

Add support for querying fd-based KVM stats - as introduced by Linux kernel commit:

cb082bfab59a ("KVM: stats: Add fd-based API to read binary stats data")

---
 accel/kvm/kvm-all.c | 308 ++++++++++++++++++++++++++++++++++++++++++++
 qapi/misc.json      |   2 +-
 2 files changed, 309 insertions(+), 1 deletion(-)
accel/kvm/kvm-all.c +109 -0
index 0e66ebb497..e43e1f1c1c 100644
@@ -47,6 +47,8 @@
 #include "kvm-cpus.h"
 
 #include "hw/boards.h"
+#include "qapi/qapi-commands-misc.h"
+#include "monitor/stats.h"
 
 /* This check must be after config-host.h is included */
 #ifdef CONFIG_EVENTFD
@@ -2309,6 +2311,9 @@ bool kvm_dirty_ring_enabled(void)
     return kvm_state->kvm_dirty_ring_size ? true : false;
 }
 
+static void query_stats_cb(StatsResults *, StatsFilter *, Error **);
+static void query_stats_schemas_cb(StatsSchemaResult *, Error **);
+
 static int kvm_init(MachineState *ms)
 {
     MachineClass *mc = MACHINE_GET_CLASS(ms);
@@ -2637,6 +2642,11 @@ static int kvm_init(MachineState *ms)
         }
     }
 
+    if (kvm_check_extension(kvm_state, KVM_CAP_BINARY_STATS_FD)) {
+        add_stats_callbacks(STATS_PROVIDER_KVM, &query_stats_cb,
+                            &query_stats_schemas_cb);
+    }
+
     return 0;
 
 err:
@@ -3696,3 +3706,301 @@ static void kvm_type_init(void)
 }
 
 type_init(kvm_type_init);
+
+typedef struct StatsArgs {
+    StatsFilter *filter;
+    bool is_schema;
+    union {
+        StatsResults *stats;
+        StatsSchemaResult *schema;
+    } result;
+    Error **errp;
+} StatsArgs;
+
+static StatsList *add_kvmstat_entry(struct kvm_stats_desc *pdesc,
+                                    uint64_t *stats_data,
+                                    StatsList *stats_list,
+                                    Error **errp)
+{
+    StatsList *stats_entry = g_malloc0(sizeof(*stats_entry));
+    Stats *stats = g_malloc0(sizeof(*stats));
+    uint64List *val_list = NULL;
+    int i;
+
+    stats->name = g_strdup(pdesc->name);
+    stats->value = g_malloc0(sizeof(*stats->value));
+
+    /* Alloc and populate data list */
+    if (pdesc->size == 1) {
+        stats->value->u.scalar = *stats_data;
+        stats->value->type = QTYPE_QNUM;
+    } else {
+        for (i = 0; i < pdesc->size; i++) {
+            uint64List *val_entry = g_malloc0(sizeof(*val_entry));
+            val_entry->value = stats_data[i];
+            val_entry->next = val_list;
+            val_list = val_entry;
+        }
+        stats->value->u.list.list = val_list;
+        stats->value->type = QTYPE_QDICT;
+    }
+
+    stats_entry->value = stats;
+    stats_entry->next = stats_list;
+
+    return stats_entry;
+}
+
+static StatsSchemaValueList *add_kvmschema_entry(struct kvm_stats_desc *pdesc,
+                                                 StatsSchemaValueList *list,
+                                                 Error **errp)
+{
+    StatsSchemaValueList *schema_entry;
+
+    schema_entry = g_malloc0(sizeof(*schema_entry));
+    schema_entry->value = g_malloc0(sizeof(*schema_entry->value));
+    schema_entry->value->name = g_strdup(pdesc->name);
+
+    switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
+    case KVM_STATS_TYPE_CUMULATIVE:
+        schema_entry->value->type = STAT_TYPE_CUMULATIVE;
+        break;
+    case KVM_STATS_TYPE_INSTANT:
+        schema_entry->value->type = STAT_TYPE_INSTANT;
+        break;
+    case KVM_STATS_TYPE_PEAK:
+        schema_entry->value->type = STAT_TYPE_PEAK;
+        break;
+    case KVM_STATS_TYPE_LINEAR_HIST:
+        schema_entry->value->type = STAT_TYPE_LINEAR_HIST;
+        break;
+    case KVM_STATS_TYPE_LOG_HIST:
+        schema_entry->value->type = STAT_TYPE_LOG_HIST;
+        break;
+    default:
+        schema_entry->value->type = STAT_TYPE_UNKNOWN;
+    }
+
+    switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
+    case KVM_STATS_UNIT_NONE:
+        schema_entry->value->unit = STAT_UNIT_NONE;
+        break;
+    case KVM_STATS_UNIT_BYTES:
+        schema_entry->value->unit = STAT_UNIT_BYTES;
+        break;
+    case KVM_STATS_UNIT_CYCLES:
+        schema_entry->value->unit = STAT_UNIT_CYCLES;
+        break;
+    case KVM_STATS_UNIT_SECONDS:
+        schema_entry->value->unit = STAT_UNIT_SECONDS;
+        break;
+    default:
+        schema_entry->value->unit = STAT_UNIT_UNKNOWN;
+    }
+
+    switch (pdesc->flags & KVM_STATS_BASE_MASK) {
+    case KVM_STATS_BASE_POW10:
+        schema_entry->value->base = STAT_BASE_POW10;
+        break;
+    case KVM_STATS_BASE_POW2:
+        schema_entry->value->base = STAT_BASE_POW2;
+        break;

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3817

Quoted 10 lines
accel/kvm/kvm-all.c +10 -0
+    default:
+        schema_entry->value->base = STAT_BASE_UNKNOWN;
+    }
+
+    schema_entry->value->exponent = pdesc->exponent;
+    schema_entry->next = list;
+    return schema_entry;
+}
+
+static void query_stats(StatsArgs *kvm_stat_args, int stats_fd)

Pass "Error **errp". For that matter, just pass in all fields directly - no need for 'StatsArgs' indirection here - that's only needed in the VCPU stats case due to need to pass many values via the run_on_cpu callback.

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3820

Quoted 3 lines
accel/kvm/kvm-all.c +3 -0
+{
+    size_t size_desc, size_data;
+    struct kvm_stats_header *header;
  g_autofree struct kvm_stats_header *header = NULL;

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3821

Quoted 1 line
accel/kvm/kvm-all.c +1 -0
+    struct kvm_stats_desc *stats_desc = NULL;

g_autofree

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3822

Quoted 1 line
accel/kvm/kvm-all.c +1 -0
+    Error *local_err = NULL;

Should not be required if errp is passed in

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3824

Quoted 2 lines
accel/kvm/kvm-all.c +2 -0
+    void *stats_list = NULL;
+    char *id = NULL;

g_autofree

Quoted 72 lines
accel/kvm/kvm-all.c +72 -0
+    ssize_t ret;
+    int i;
+
+    /* Read KVM stats header */
+    header = g_malloc(sizeof(*header));
+    ret = read(stats_fd, header, sizeof(*header));
+    if (ret != sizeof(*header)) {
+        error_setg(&local_err, "KVM stats: failed to read stats header: "
+                   "expected %zu actual %zu", sizeof(*header), ret);
+        goto exit;
+    }
+    size_desc = sizeof(*stats_desc) + header->name_size;
+
+    /* Read KVM stats id string */
+    id = g_malloc(header->name_size);
+    ret = read(stats_fd, id, header->name_size);
+    if (ret != header->name_size) {
+        error_setg(&local_err, "KVM stats: failed to read id string: "
+                   "expected %zu actual %zu", (size_t) header->name_size, ret);
+        goto exit;
+    }
+
+    /* Read KVM stats descriptors */
+    stats_desc = g_malloc0(header->num_desc * size_desc);
+    ret = pread(stats_fd, stats_desc,
+                size_desc * header->num_desc, header->desc_offset);
+
+    if (ret != size_desc * header->num_desc) {
+        error_setg(&local_err, "KVM stats: failed to read stats descriptors: "
+                   "expected %zu actual %zu",
+                   size_desc * header->num_desc, ret);
+        goto exit;
+    }
+
+    for (i = 0; i < header->num_desc; ++i) {
+        struct kvm_stats_desc *pdesc = (void *)stats_desc + i * size_desc;
+        size_data = pdesc->size * sizeof(uint64_t);
+
+        uint64_t *stats_data = g_malloc(size_data);
+
+        ret = pread(stats_fd, stats_data, size_data,
+                    header->data_offset + pdesc->offset);
+
+        if (ret != pdesc->size * sizeof(*stats_data)) {
+            error_setg(&local_err, "KVM stats: failed to read data: "
+                       "expected %zu actual %zu",
+                       pdesc->size * sizeof(*stats_data), ret);
+            g_free(stats_data);
+            goto exit;
+        }
+
+        /* Add entry to the list */
+        if (kvm_stat_args->is_schema) {
+            stats_list = add_kvmschema_entry(pdesc, (StatsSchemaValueList *)
+                                             stats_list, &local_err);
+        } else {
+            if (stat_name_filter(kvm_stat_args->filter,
+                                 kvm_stat_args->filter->target, pdesc->name)) {
+                g_free(stats_data);
+                continue;
+            }
+            stats_list = add_kvmstat_entry(pdesc, stats_data,
+                                           (StatsList *) stats_list,
+                                           &local_err);
+        }
+        g_free(stats_data);
+    }
+
+    if (!stats_list) {
+        goto exit;
+    }
+

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3906

Quoted 10 lines
accel/kvm/kvm-all.c +10 -0
+    if (kvm_stat_args->is_schema) {
+        StatsSchemaProvider *provider;
+        if (kvm_stat_args->filter->target == STATS_TARGET_VM) {
+            provider = add_vm_stats_schema(kvm_stat_args->result.schema,
+                                           STATS_PROVIDER_KVM);
+        } else if (kvm_stat_args->filter->target == STATS_TARGET_VCPU) {
+            provider = add_vcpu_stats_schema(kvm_stat_args->result.schema,
+                                             STATS_PROVIDER_KVM);
+        }
+        provider->stats = (StatsSchemaValueList *)stats_list;

The compiler warns about provider being used uninitialized.

This would be better as a switch

       StatsSchemaProvider *provider = NULL;
       switch (kvm_stat_args->filter->target){
         case STATS_TARGET_VM:
           provider = add_vm_stats_schema(kvm_stat_args->result.schema,
                                          STATS_PROVIDER_KVM);
           break;
         case STATS_TARGET_VCPU:
           provider = add_vcpu_stats_schema(kvm_stat_args->result.schema,
                                            STATS_PROVIDER_KVM);
           break;
	 default:
	   break;
       }
       if (provider) {
           provider->stats = (StatsSchemaValueList *)stats_list;
       }

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3918

Quoted 12 lines
accel/kvm/kvm-all.c +12 -0
+    } else {
+        StatsResultsEntry *results;
+        if (kvm_stat_args->filter->target == STATS_TARGET_VM) {
+            results = add_vm_stats_entry(kvm_stat_args->result.stats,
+                                         STATS_PROVIDER_KVM);
+        } else if (kvm_stat_args->filter->target == STATS_TARGET_VCPU) {
+            results =
+                add_vcpu_stats_entry(kvm_stat_args->result.stats,
+                                     STATS_PROVIDER_KVM,
+                                     current_cpu->parent_obj.canonical_path);
+        }
+        results->stats = (StatsList *)stats_list;

Same compiler around as previous block

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3921

Quoted 3 lines
accel/kvm/kvm-all.c +3 -0
+    }
+exit:
+    error_propagate(kvm_stat_args->errp, local_err);

Not required if we use errp from the caller directly.

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3924

Quoted 3 lines
accel/kvm/kvm-all.c +3 -0
+    g_free(stats_desc);
+    g_free(id);
+    g_free(header);

Not needed with g_autofree usage, so we don't need the 'exit:' label at all.

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3935

Quoted 11 lines
accel/kvm/kvm-all.c +11 -0
+}
+
+static void query_stats_vcpu(CPUState *cpu, run_on_cpu_data data)
+{
+    StatsArgs *kvm_stats_args = (StatsArgs *) data.host_ptr;
+    int stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
+    Error *local_err = NULL;
+
+    if (stats_fd == -1) {
+        error_setg(&local_err, "KVM stats: ioctl failed");
+        error_propagate(kvm_stats_args->errp, local_err);

Get rid of local_err and pass kvm_stat_args->errp straight to error_setg

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3938

Quoted 3 lines
accel/kvm/kvm-all.c +3 -0
+        return;
+    }
+    query_stats(kvm_stats_args, stats_fd);

Pass kvm_stats_args->errp into this.

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3948

Quoted 13 lines
accel/kvm/kvm-all.c +10 -0
+    close(stats_fd);
+}
+
+static void query_stats_cb(StatsResults *stats_result, StatsFilter *filter,
+                           Error **errp)
+{
 
 
 
+    KVMState *s = kvm_state;
+    CPUState *cpu;
+    int stats_fd;
+    StatsArgs *stats_args = g_malloc0(sizeof(*stats_args));

g_autofree

Quoted 4 lines
accel/kvm/kvm-all.c +3 -0
+    stats_args->filter = filter;
+    stats_args->errp = errp;
+    stats_args->result.stats = stats_result;
 

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3961

Quoted 10 lines
accel/kvm/kvm-all.c +10 -0
+
+    switch (filter->target) {
+    case STATS_TARGET_VM:
+        stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
+        if (stats_fd == -1) {
+            error_setg(errp, "KVM stats: ioctl failed");
+            goto done;
+        }
+
+        query_stats(stats_args, stats_fd);

Pass errp into this.

Quoted 4 lines
accel/kvm/kvm-all.c +4 -0
+        break;
+    case STATS_TARGET_VCPU:
+        CPU_FOREACH(cpu) {
+            if (stat_cpu_filter(filter, cpu->parent_obj.canonical_path)) {

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3975

Quoted 10 lines
accel/kvm/kvm-all.c +10 -0
+                continue;
+            }
+            run_on_cpu(cpu, query_stats_vcpu, RUN_ON_CPU_HOST_PTR(stats_args));
+        }
+        break;
+    default:
+        break;
+    }
+done:
+    g_free(stats_args);

No need for this label / g_free, if we use g_autofree

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3982

Quoted 7 lines
accel/kvm/kvm-all.c +7 -0
+}
+
+void query_stats_schemas_cb(StatsSchemaResult *stats_result, Error **errp)
+{
+    KVMState *s = kvm_state;
+    int stats_fd;
+    StatsArgs *stats_args =  g_malloc0(sizeof(*stats_args));

g_autofree + g_new0

Quoted 1 line

+ stats_args->filter = g_malloc0(sizeof(*stats_args->filter));

  g_autofree StatsFilter *filter = g_new(StatsFilter, 1);

  stats_args->filter = filter;
Quoted 11 lines
accel/kvm/kvm-all.c +11 -0
+    stats_args->errp = errp;
+
+    stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
+    if (stats_fd == -1) {
+        error_setg(errp, "KVM stats: ioctl failed");
+        goto done;
+    }
+
+    stats_args->result.schema = stats_result;
+    stats_args->is_schema = true;
+

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 4004

Quoted 10 lines
accel/kvm/kvm-all.c +10 -0
+    /* Query VM */
+    stats_args->filter->target = STATS_TARGET_VM;
+    query_stats(stats_args, stats_fd);
+
+    /* Query vCPU */
+    stats_args->filter->target = STATS_TARGET_VCPU;
+    run_on_cpu(first_cpu, query_stats_vcpu, RUN_ON_CPU_HOST_PTR(stats_args));
+done:
+    g_free(stats_args->filter);
+    g_free(stats_args);

The label & g_free can be removed with g_autofree usage.

Quoted 18 lines
accel/kvm/kvm-all.c +2 -0
+}
+
qapi/misc.json +1 -1
index 8d326464f0..39a7d172cb 100644
@@ -574,7 +574,7 @@
 # Since: 7.0
 ##
 { 'enum': 'StatsProvider',
-  'data': [ ] }
+  'data': [ 'kvm' ] }
 
 ##
 # @StatsTarget:
Signature · 1 line
2.27.0

Regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#16 lore raw

Re: [PATCH v3 3/3] kvm: Support for querying fd-based stats

In reply to Mark Kanda

accel/kvm/kvm-all.c static void kvm_type_init(void) · line 3866

Quoted 9 lines · Mark Kanda
accel/kvm/kvm-all.c +8 -0
+    for (i = 0; i < header->num_desc; ++i) {
+        struct kvm_stats_desc *pdesc = (void *)stats_desc + i * size_desc;
+        size_data = pdesc->size * sizeof(uint64_t);
+
+        uint64_t *stats_data = g_malloc(size_data);
+
+        ret = pread(stats_fd, stats_data, size_data,
+                    header->data_offset + pdesc->offset);

How hard would it be to cache the descriptors? Ideally, a query-stats command would do only one pread.

Paolo

#2 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

In reply to Mark Kanda
Quoted 15 lines · Mark Kanda

{ "execute": "query-stats", "arguments" : { "target": "vm" } }

{ "return": {
     "list": [
       { "provider": "kvm",
         "stats": [
           { "name": "max_mmu_page_hash_collisions", "value": 0 },
           { "name": "max_mmu_rmap_size", "value": 0 },
           { "name": "nx_lpage_splits", "value": 131 },
          ...
         ] }
       { "provider": "provider XYZ",
       ...
     ],
     "target": "vm"
Quoted 2 lines

}
}

Perhaps it's better to have a better name than "list" for clarity, like you already did with 'stats':

{ 'struct': 'VCPUResultsEntry',
'data': { 'path': 'str',

            'providers': [ 'StatsResultsEntry' ] } }

{ 'struct': 'VCPUStatsResults',
'data': { 'objects': [ 'VCPUResultsEntry' ] } }

{ 'struct': 'VMStatsResults',
'data': { 'providers' : [ 'StatsResultsEntry' ] } }

Also, here:

qapi/misc.json line 649

Quoted 3 lines
qapi/misc.json +3 -0
+{ 'alternate': 'StatsValue',
+  'data': { 'scalar': 'uint64',
+            'list': 'StatsValueArray' } }

is it possible to just do

{ 'alternate': 'StatsValue',
'data': { 'scalar': 'uint64',

            'list': ['uint64'] } }

Thanks,

Paolo

#3 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

Quoted 39 lines · Paolo Bonzini
Quoted 15 lines · Mark Kanda

{ "execute": "query-stats", "arguments" : { "target": "vm" } }

{ "return": {
     "list": [
       { "provider": "kvm",
         "stats": [
           { "name": "max_mmu_page_hash_collisions", "value": 0 },
           { "name": "max_mmu_rmap_size", "value": 0 },
           { "name": "nx_lpage_splits", "value": 131 },
          ...
         ] }
       { "provider": "provider XYZ",
       ...
     ],
     "target": "vm"
Quoted 2 lines

}
}

Perhaps it's better to have a better name than "list" for clarity, like you already did with 'stats':

{ 'struct': 'VCPUResultsEntry',
'data': { 'path': 'str',

            'providers': [ 'StatsResultsEntry' ] } }

{ 'struct': 'VCPUStatsResults',
'data': { 'objects': [ 'VCPUResultsEntry' ] } }

{ 'struct': 'VMStatsResults',
'data': { 'providers' : [ 'StatsResultsEntry' ] } }

Also, here:

qapi/misc.json line 649

Quoted 3 lines
qapi/misc.json +3 -0
+{ 'alternate': 'StatsValue',
+  'data': { 'scalar': 'uint64',
+            'list': 'StatsValueArray' } }
Quoted 5 lines

is it possible to just do

{ 'alternate': 'StatsValue',
'data': { 'scalar': 'uint64',

            'list': ['uint64'] } }

No, the QAPI generator throws its toys out of the pram.

It claims you can have any set of data types which have a distinct representation on the wire, so this is valid from that POV. Something about the parser/code generator can't cope with this inline array though - it wants a named type which means a built-in scalar, or a compound type, but not an array :-(

Regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#5 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

In reply to Mark Kanda
Quoted 33 lines · Mark Kanda

Introduce QMP support for querying stats. Provide a framework for adding new stats and support for the following commands:

- query-stats
Returns a list of all stats per target type (only VM and VCPU for now), with additional options for specifying stat names, VCPU qom paths, and stat provider.

- query-stats-schemas
Returns a list of stats included in each schema type, with an option for specifying the stat provider.

The framework provides a method to register callbacks for these QMP commands.

The first usecase will be for fd-based KVM stats (in an upcoming patch).

Examples (with fd-based KVM stats):

- Display all VM stats:

{ "execute": "query-stats", "arguments" : { "target": "vm" } }

{ "return": {
    "list": [
      { "provider": "kvm",
        "stats": [
          { "name": "max_mmu_page_hash_collisions", "value": 0 },
          { "name": "max_mmu_rmap_size", "value": 0 },
          { "name": "nx_lpage_splits", "value": 131 },
         ...
        ] }
      { "provider": "provider XYZ",
      ...
    ],
    "target": "vm"
Quoted 2 lines

}
}

I still feel like this is rather verbose, and should be simplified down to.

 { "return": {
     "vm": {
       "kvm": [ ... ]
       "provider-XYZ": [ ... ],
       ...
     }

}

While vCPU would need one extra nesting layer

 { "return": {
     "vcpus": [
       {
         "path": "/vcpu0/path"
         "kvm": [ ... ]
         "provider-XYZ": [ ... ],
         ...
       },
       {
         "path": "/vcpu1/path"
         "kvm": [ ... ]
         "provider-XYZ": [ ... ],
         ...
       },
       ...
     ],

}

The notable difference here is that we'd be adding new keys to the StatsResultEntry struct, every time we gain a new provider, so your QMP code couldn't be entirely metadata driven - you'd need new code to wire up each stats provider.

Quoted 2 lines

- Display 'exits' and 'l1d_flush' KVM stats for VCPUs at '/machine/unattached/device[2]' and '/machine/unattached/device[4]':

Shows the value of giving CPUs proper paths

https://lists.gnu.org/archive/html/qemu-devel/2022-01/msg06744.html

Quoted 7 lines

{ "execute": "query-stats",
"arguments" : { "target": "vcpu",

                  "fields": [ "exits", "l1d_flush" ],
	          "paths": [ "/machine/unattached/device[2]",
	                      "/machine/unattached/device[4]" ]
                  "provider": "kvm" } }

This design requires multiple query-stats calls to get data from multiple providers which I think is very undesirable from a performance POV.

I'd like to see us able to query fields from many providers at once

ie so we have something that looks like

{ "execute": "query-stats",
"arguments" : { "target": "vcpu",
"vcpus": [ "/machine/unattached/device[2]",
"/machine/unattached/device[4]" ]

                   "kvm": [ "exits", "l1d_flush" ],
		   "someprovider: [ "somefield" ] } }

qapi/misc.json

Quoted 70 lines
{ "return": {
    "list": [
      { "list": [
          { "provider": "kvm",
            "stats": [
              { "name": "l1d_flush", "value": 14690 },
              { "name": "exits", "value": 50898 }
            ] }
        ],
        "path": "/machine/unattached/device[2]"
      },
      { "list": [
          { "provider": "kvm",
            "stats": [
              { "name": "l1d_flush", "value": 24902 },
              { "name": "exits", "value": 74374 }
            ] }
	 ],
        "path": "/machine/unattached/device[4]"
      }
    ],
    "target": "vcpu"

}
}

- Query stats schemas:

{ "execute": "query-stats-schemas" }

{ "return": {
    "vcpu": [
      { "provider": "kvm",
        "stats": [
           { "name": "guest_mode",
             "unit": "none",
             "base": 10,
             "exponent": 0,
             "type": "instant" },
	   { "name": "directed_yield_successful",
             "unit": "none",
             "base": 10,
             "exponent": 0,
             "type": "cumulative" },
             ...
	"provider": "provider XYZ",
...
   "vm": [
      { "provider": "kvm",
        "stats": [
           { "name": "max_mmu_page_hash_collisions",
             "unit": "none",
             "base": 10,
             "exponent": 0,
             "type": "peak" },
	"provider": "provider XYZ",

...

---
 include/monitor/stats.h |  36 ++++++
 monitor/qmp-cmds.c      | 183 +++++++++++++++++++++++++++++
 qapi/misc.json          | 253 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 472 insertions(+)
 create mode 100644 include/monitor/stats.h
qapi/misc.json +0 -0
index e8054f415b..8d326464f0 100644

I'd suggest we introduce a 'stats.json' file just for this. We have quite a few data types introduced, and its good to avoid 'misc.json' becoming a dumping ground for ranom unrelated stuff.

qapi/misc.json line 532

Quoted 7 lines
qapi/misc.json +3 -0
@@ -527,3 +527,256 @@
  'data': { '*option': 'str' },
  'returns': ['CommandLineOptionInfo'],
  'allow-preconfig': true }
+
+##
+# @StatType:

There's inconsistency with naming through these changes. Can we ensure that everything uses 'Stats' (plural) as the prefix for every type.

qapi/misc.json line 537

Quoted 5 lines
qapi/misc.json +5 -0
+#
+# Enumeration of stat types
+# @cumulative: stat is cumulative; value can only increase.
+# @instant: stat is instantaneous; value can increase or decrease.
+# @peak: stat is the peak value; value can only increase.

Not documenting all members

qapi/misc.json line 543

Quoted 6 lines
qapi/misc.json +6 -0
+#
+# Since: 7.0
+##
+{ 'enum' : 'StatType',
+  'data' : [ 'cumulative', 'instant', 'peak',
+             'linear-hist', 'log-hist', 'unknown' ] }

IMHO 'unknown' shouldn't exist at all.

qapi/misc.json line 601

Quoted 11 lines
qapi/misc.json +11 -0
+##
+# @StatsVCPURequest:
+#
+# vcpu specific filter element.
+# @paths: list of qom paths.
+#
+# Since: 7.0
+##
+{ 'struct': 'StatsVCPURequest',
+  'base': 'StatsRequest',
+  'data': { '*paths': [ 'str' ] } }

Call the field 'vcpus' instead of 'paths' to make it clear that we're listing VCPU paths here.

qapi/misc.json line 614

Quoted 12 lines
qapi/misc.json +12 -0
+##
+# @StatsRequest:
+#
+# Stats filter element.
+# @provider: stat provider.
+# @fields: list of stat names.
+#
+# Since: 7.0
+##
+{ 'struct': 'StatsRequest',
+  'data': { '*provider': 'StatsProvider',
+            '*fields': [ 'str' ] } }

As mentioned earlier I think we need to have aility to query from many providers at once. It'd be better to have provider name as the field name, eg

{ 'struct': 'StatsRequest',
'data': { '*kvm': ['str'],

             '*someprovider': [ 'str' ] } }
Quoted 13 lines
qapi/misc.json +13 -0
+
+##
+# @StatsFilter:
+#
+# Target specific filter.
+#
+# Since: 7.0
+##
+{ 'union': 'StatsFilter',
+  'base': { 'target': 'StatsTarget' },
+  'discriminator': 'target',
+  'data': { 'vcpu': 'StatsVCPURequest',
+            'vm': 'StatsRequest' } }

qapi/misc.json line 637

Quoted 10 lines
qapi/misc.json +9 -0
 
+##
+# @StatsValueArray:
+#
+# uint64 list for StatsValue.
+#
+# Since: 7.0
+##
+{ 'struct': 'StatsValueArray',
+  'data': { 'list' : [ 'uint64' ] } }

'values' or 'elements' rather than repeating 'list'

Quoted 67 lines
qapi/misc.json +67 -0
+
+##
+# @StatsValue:
+#
+# @scalar: stat is single uint64.
+# @list: stat is a list of uint64.
+#
+# Since: 7.0
+##
+{ 'alternate': 'StatsValue',
+  'data': { 'scalar': 'uint64',
+            'list': 'StatsValueArray' } }
+
+##
+# @Stats:
+#
+# @name: name of stat.
+# @value: stat value.
+#
+# Since: 7.0
+##
+{ 'struct': 'Stats',
+  'data': { 'name': 'str',
+            'value' : 'StatsValue' } }
+
+##
+# @StatsResultsEntry:
+#
+# @provider: stat provider.
+# @stats: list of stats.
+#
+# Since: 7.0
+##
+{ 'struct': 'StatsResultsEntry',
+  'data': { 'provider': 'StatsProvider',
+            'stats': [ 'Stats' ] } }
+
+##
+# @VCPUResultsEntry:
+#
+# @path: qom path.
+# @list: per provider @StatsResultEntry list.
+#
+# Since: 7.0
+##
+{ 'struct': 'VCPUResultsEntry',
+  'data': { 'path': 'str',
+            'list': [ 'StatsResultsEntry' ] } }
+
+##
+# @VMStatsResults:
+#
+# Since: 7.0
+##
+{ 'struct': 'VMStatsResults',
+  'data': { 'list' : [ 'StatsResultsEntry' ] } }
+
+##
+# @VCPUStatsResults:
+#
+# Since: 7.0
+##
+{ 'struct': 'VCPUStatsResults',
+  'data': { 'list': [ 'VCPUResultsEntry' ] } }
+
+##
+# @StatsResults:

qapi/misc.json line 714

Quoted 10 lines
qapi/misc.json +10 -0
+#
+# Target specific results.
+#
+# Since: 7.0
+##
+{ 'union': 'StatsResults',
+  'base': { 'target': 'StatsTarget' },
+  'discriminator': 'target',
+  'data': { 'vcpu': 'VCPUStatsResults',
+            'vm': 'VMStatsResults' } }

I feel we can simplify this all down somewhat, eliminating levels of redundant nesting

{ 'struct': 'StatsResultsEntry',
'data': { '*kvm': [ 'Stats' ] } }

{ 'struct': 'StatsResultsVCPUEntry',
'base': 'StatsResultsEntry',
'data': 'path': 'str' } }

{ 'struct': 'StatsResults',
'data': {
'*vcpus': ['StatsResultsVCPUEntry'],
'*vm': 'StatsResultsEntry'
}
}

qapi/misc.json line 727

Quoted 13 lines
qapi/misc.json +13 -0
+
+##
+# @query-stats:
+#
+# data: @StatsFilter
+# Returns: @StatsResults
+#
+# Since: 7.0
+##
+{ 'command': 'query-stats',
+  'data': 'StatsFilter',
+  'boxed': true,
+  'returns': 'StatsResults' }

Regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
author
#6 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

Thanks Daniel,

Quoted 8 lines · Daniel P. Berrangé

qapi/misc.json line 543

Quoted 6 lines
qapi/misc.json +6 -0
+#
+# Since: 7.0
+##
+{ 'enum' : 'StatType',
+  'data' : [ 'cumulative', 'instant', 'peak',
+             'linear-hist', 'log-hist', 'unknown' ] }

IMHO 'unknown' shouldn't exist at all.

I added the 'unknown' member here (and in other enums) to handle situations where QEMU is behind KVM in terms of enumerating the various stat types, units, etc. I feel this will be a semi-common scenario (old QEMU on a new kernel) and with 'unknown', QEMU can at least display the raw data.

That said, I happy skip 'unknown' entries if you think that's better.

Thanks/regards,
-Mark

author
#8 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

In reply to Daniel P. Berrangé
Quoted 17 lines · Daniel P. Berrangé
Quoted 16 lines · Mark Kanda

Thanks Daniel,

Quoted 8 lines · Daniel P. Berrangé

qapi/misc.json line 543

Quoted 6 lines
qapi/misc.json +6 -0
+#
+# Since: 7.0
+##
+{ 'enum' : 'StatType',
+  'data' : [ 'cumulative', 'instant', 'peak',
+             'linear-hist', 'log-hist', 'unknown' ] }

IMHO 'unknown' shouldn't exist at all.

I added the 'unknown' member here (and in other enums) to handle situations where QEMU is behind KVM in terms of enumerating the various stat types, units, etc. I feel this will be a semi-common scenario (old QEMU on a new kernel) and with 'unknown', QEMU can at least display the raw data.

Quoted 9 lines
Quoted 1 line

That said, I happy skip 'unknown' entries if you think that's better.

Yep, I don't think we should be including 'unknown' stuff.

An application could use this, and then we add support for the new type and the application will now break with new QEMU because it is presented in QMP in a different way.

The same for the 'unknown' base and unit too for that matter.

Sounds good. I'll implement the other changes you suggested in v4.

Thanks/regards,
-Mark

#10 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

In reply to Daniel P. Berrangé
Quoted 10 lines · Daniel P. Berrangé

I still feel like this is rather verbose, and should be simplified down to.

  { "return": {
      "vm": {
        "kvm": [ ... ]
        "provider-XYZ": [ ... ],
        ...
      }
  }

My main qualm with this is that not just QEMU, but every layer above then needs to either treat stats as a "dynamic" type unless they want to only handle providers that they know.

The main reason why I asked Mark to do all this work, was so that new stats and stats providers could be added transparently, and only new *targets* would need work all over the stack (but those are fewer, for example blockdev/netdev/iothread).

Paolo

#7 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

In reply to Mark Kanda
Quoted 12 lines · Mark Kanda

Thanks Daniel,

Quoted 8 lines · Daniel P. Berrangé

qapi/misc.json line 543

Quoted 6 lines
qapi/misc.json +6 -0
+#
+# Since: 7.0
+##
+{ 'enum' : 'StatType',
+  'data' : [ 'cumulative', 'instant', 'peak',
+             'linear-hist', 'log-hist', 'unknown' ] }

IMHO 'unknown' shouldn't exist at all.

Quoted 6 lines

I added the 'unknown' member here (and in other enums) to handle situations where QEMU is behind KVM in terms of enumerating the various stat types, units, etc. I feel this will be a semi-common scenario (old QEMU on a new kernel) and with 'unknown', QEMU can at least display the raw data.

That said, I happy skip 'unknown' entries if you think that's better.

Yep, I don't think we should be including 'unknown' stuff.

An application could use this, and then we add support for the new type and the application will now break with new QEMU because it is presented in QMP in a different way.

The same for the 'unknown' base and unit too for that matter.

Regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
author
#12 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

In reply to Daniel P. Berrangé
Quoted 22 lines · Daniel P. Berrangé

qapi/misc.json line 714

Quoted 12 lines
qapi/misc.json +12 -0
+##
+# @StatsResults:
+#
+# Target specific results.
+#
+# Since: 7.0
+##
+{ 'union': 'StatsResults',
+  'base': { 'target': 'StatsTarget' },
+  'discriminator': 'target',
+  'data': { 'vcpu': 'VCPUStatsResults',
+            'vm': 'VMStatsResults' } }

I feel we can simplify this all down somewhat, eliminating levels of redundant nesting

{ 'struct': 'StatsResultsEntry',
'data': { '*kvm': [ 'Stats' ] } }

{ 'struct': 'StatsResultsVCPUEntry',
'base': 'StatsResultsEntry',
'data': 'path': 'str' } }

Quoted 8 lines

{ 'struct': 'StatsResults',
'data': {
'*vcpus': ['StatsResultsVCPUEntry'],
'*vm': 'StatsResultsEntry'
}
}

I'm happy to make this change, but I would like Paolo to comment as he had suggested the StatsResults layout [1].

Thanks Daniel/Paolo,
-Mark

[1] https://lore.kernel.org/all/[email protected]/

#9 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

In reply to Mark Kanda
Quoted 2 lines · Mark Kanda

I added the 'unknown' member here (and in other enums) to handle situations where QEMU is behind KVM in terms of enumerating the various stat types, units, etc. I feel this will be a semi-common scenario (old QEMU on a new kernel) and with 'unknown', QEMU can at least display the raw data.

I think you can skip them, there aren't really plans for new types (the "metaschema" is based on one that has been in use for quite some time at Google).

Paolo

#11 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

In reply to Paolo Bonzini
Quoted 12 lines · Paolo Bonzini
Quoted 10 lines · Daniel P. Berrangé

I still feel like this is rather verbose, and should be simplified down to.

  { "return": {
      "vm": {
        "kvm": [ ... ]
        "provider-XYZ": [ ... ],
        ...
      }
  }
Quoted 8 lines

My main qualm with this is that not just QEMU, but every layer above then needs to either treat stats as a "dynamic" type unless they want to only handle providers that they know.

The main reason why I asked Mark to do all this work, was so that new stats and stats providers could be added transparently, and only new *targets* would need work all over the stack (but those are fewer, for example blockdev/netdev/iothread).

Hmm, yes, i see what you mean.

Regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#4 lore raw

Re: [PATCH v3 1/3] qmp: Support for querying stats

In reply to Daniel P. Berrangé
Quoted 46 lines · Daniel P. Berrangé
Quoted 39 lines · Paolo Bonzini
Quoted 15 lines · Mark Kanda

{ "execute": "query-stats", "arguments" : { "target": "vm" } }

{ "return": {
     "list": [
       { "provider": "kvm",
         "stats": [
           { "name": "max_mmu_page_hash_collisions", "value": 0 },
           { "name": "max_mmu_rmap_size", "value": 0 },
           { "name": "nx_lpage_splits", "value": 131 },
          ...
         ] }
       { "provider": "provider XYZ",
       ...
     ],
     "target": "vm"
Quoted 2 lines

}
}

Perhaps it's better to have a better name than "list" for clarity, like you already did with 'stats':

{ 'struct': 'VCPUResultsEntry',
'data': { 'path': 'str',

            'providers': [ 'StatsResultsEntry' ] } }

{ 'struct': 'VCPUStatsResults',
'data': { 'objects': [ 'VCPUResultsEntry' ] } }

{ 'struct': 'VMStatsResults',
'data': { 'providers' : [ 'StatsResultsEntry' ] } }

Also, here:

qapi/misc.json line 649

Quoted 3 lines
qapi/misc.json +3 -0
+{ 'alternate': 'StatsValue',
+  'data': { 'scalar': 'uint64',
+            'list': 'StatsValueArray' } }
Quoted 5 lines

is it possible to just do

{ 'alternate': 'StatsValue',
'data': { 'scalar': 'uint64',

            'list': ['uint64'] } }
Quoted 8 lines

No, the QAPI generator throws its toys out of the pram.

It claims you can have any set of data types which have a distinct representation on the wire, so this is valid from that POV. Something about the parser/code generator can't cope with this inline array though - it wants a named type which means a built-in scalar, or a compound type, but not an array :-(

Array is not implemented, simply because we haven't had a use for it.

Should not make you settle for an inferior schema design! Implementing array alternates shouldn't be hard.