[PATCH] x86/tsc: export tsc_khz to sysfs

From: Redha Gouicem
Date: Thu Dec 31 2020 - 07:29:30 EST


Export the frequency of the tsc clock to user space. This is particularly
useful for benchmarking purposes because it allows to convert tsc cycles
into time. The value is available at:
/sys/devices/system/cpu/tsc_khz

Signed-off-by: Redha Gouicem <redha.gouicem@xxxxxxxxx>
---
arch/x86/kernel/tsc.c | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)

diff --git a/arch/x86/kernel/tsc.c b/arch/x86/kernel/tsc.c
index 49d925043171..6ea991516d08 100644
--- a/arch/x86/kernel/tsc.c
+++ b/arch/x86/kernel/tsc.c
@@ -14,6 +14,7 @@
#include <linux/percpu.h>
#include <linux/timex.h>
#include <linux/static_key.h>
+#include <linux/cpu.h>

#include <asm/hpet.h>
#include <asm/timer.h>
@@ -1412,6 +1413,15 @@ static int __init init_tsc_clocksource(void)
*/
device_initcall(init_tsc_clocksource);

+/* sysfs file to export tsc_khz */
+static ssize_t tsc_khz_show(struct kobject *kobj,
+ struct kobj_attribute *attr, char *buf)
+{
+ return sprintf(buf, "%u\n", tsc_khz);
+}
+
+struct kobj_attribute tsc_khz_attr = __ATTR_RO(tsc_khz);
+
static bool __init determine_cpu_tsc_frequencies(bool early)
{
/* Make sure that cpu and tsc are not already calibrated */
@@ -1530,6 +1540,19 @@ void __init tsc_init(void)
detect_art();
}

+static int __init tsc_khz_sysfs_init(void)
+{
+ int ret = sysfs_create_file(&cpu_subsys.dev_root->kobj, &tsc_khz_attr.attr);
+
+ if (!ret)
+ pr_info("tsc_khz exported in sysfs\n");
+ else
+ pr_warn("tsc_khz failed to be exported in sysfs\n");
+
+ return ret;
+}
+late_initcall(tsc_khz_sysfs_init);
+
#ifdef CONFIG_SMP
/*
* If we have a constant TSC and are using the TSC for the delay loop,
--
2.30.0