[PATCH] perf metrics: Add literal for system TSC frequency

From: Ian Rogers
Date: Wed Feb 02 2022 - 20:08:02 EST


Such a literal is useful to calculate things like the average frequency
[1]. The TSC frequency isn't exposed by sysfs although some experimental
drivers look to add it [2]. This change computes the value using the
frequency in /proc/cpuinfo which is accruate at least on Intel
processors.

[1] https://github.com/intel/perfmon-metrics/blob/5ad9ef7056f31075e8178b9f1fb732af183b2c8d/SKX/metrics/perf/skx_metric_perf.json#L11
[2] https://github.com/trailofbits/tsc_freq_khz

Signed-off-by: Ian Rogers <irogers@xxxxxxxxxx>
---
tools/perf/util/expr.c | 42 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)

diff --git a/tools/perf/util/expr.c b/tools/perf/util/expr.c
index 675f318ce7c1..7ad01ed57025 100644
--- a/tools/perf/util/expr.c
+++ b/tools/perf/util/expr.c
@@ -402,6 +402,43 @@ double expr_id_data__source_count(const struct expr_id_data *data)
return data->val.source_count;
}

+/*
+ * Derive the TSC frequency in Hz from the /proc/cpuinfo, for example:
+ * ...
+ * model name : Intel(R) Xeon(R) Gold 6154 CPU @ 3.00GHz
+ * ...
+ * will return 3000000000.
+ */
+static double system_tsc_freq(void)
+{
+ double result = NAN;
+ FILE *cpuinfo;
+ char *line = NULL;
+ size_t len = 0;
+
+ cpuinfo = fopen("/proc/cpuinfo", "r");
+ if (!cpuinfo)
+ return NAN;
+
+ while (getline(&line, &len, cpuinfo) > 0) {
+ if (!strncmp(line, "model name", 10)) {
+ char *pos = line + 11;
+
+ while (*pos != '@')
+ pos++;
+ if (sscanf(pos, " %lfGHz", &result) == 1) {
+ result *= 1000000000;
+ goto out;
+ }
+ }
+ }
+
+out:
+ free(line);
+ fclose(cpuinfo);
+ return result;
+}
+
double expr__get_literal(const char *literal)
{
static struct cpu_topology *topology;
@@ -417,6 +454,11 @@ double expr__get_literal(const char *literal)
goto out;
}

+ if (!strcasecmp("#system_tsc_freq", literal)) {
+ result = system_tsc_freq();
+ goto out;
+ }
+
/*
* Assume that topology strings are consistent, such as CPUs "0-1"
* wouldn't be listed as "0,1", and so after deduplication the number of
--
2.35.0.rc2.247.g8bbb082509-goog