Skip to content

Instantly share code, notes, and snippets.

@drvink
Forked from glandium/Makefile
Created June 4, 2022 03:06
Show Gist options
  • Select an option

  • Save drvink/7fc4ff8698bd1f55c56ebe40bb20c644 to your computer and use it in GitHub Desktop.

Select an option

Save drvink/7fc4ff8698bd1f55c56ebe40bb20c644 to your computer and use it in GitHub Desktop.
Linux kernel module for Zen workaround for rr
obj-m = zen_workaround.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
#include <linux/module.h>
#include <linux/tracepoint.h>
#define MODULE_NAME "zen_workaround"
#define SPECLOCKMAP_DISABLE BIT_64(54)
u64 set_speclockmap_disable(u64 msr) {
return msr | SPECLOCKMAP_DISABLE;
}
u64 unset_speclockmap_disable(u64 msr) {
return msr & ~SPECLOCKMAP_DISABLE;
}
typedef u64 (*edit_msr_func_t)(u64);
static void edit_ls_cfg_on_cpu(void *info)
{
int cpu = get_cpu();
u64 value = 0;
if (!rdmsrl_safe(MSR_AMD64_LS_CFG, &value)) {
edit_msr_func_t edit_msr = (edit_msr_func_t) info;
u64 new_value = edit_msr(value);
if (!wrmsrl_safe(MSR_AMD64_LS_CFG, new_value)) {
pr_info("MSR_AMD64_LS_CFG for cpu %d was 0x%llx, setting to 0x%llx\n",
cpu, value, new_value);
} else {
pr_err("MSR_AMD64_LS_CFG for cpu %d was 0x%llx, setting to 0x%llx failed\n",
cpu, value, new_value);
}
}
}
static int do_zen_workaround(edit_msr_func_t edit_msr)
{
smp_call_function(edit_ls_cfg_on_cpu, edit_msr, 1);
edit_ls_cfg_on_cpu(edit_msr);
return 0;
}
void on_write_msr(void *data, unsigned int msr, u64 val, int failed) {
if (msr == MSR_AMD64_LS_CFG && !(val & SPECLOCKMAP_DISABLE)) {
native_wrmsrl(MSR_AMD64_LS_CFG, set_speclockmap_disable(val));
}
}
static int __init zen_workaround_init(void)
{
int ret;
if (!static_cpu_has(X86_FEATURE_ZEN)) {
pr_err("Cannot use the Zen workaround on a non-Zen CPU\n");
return -EINVAL;
}
ret = tracepoint_probe_register(&__tracepoint_write_msr, on_write_msr, NULL);
if (ret) {
pr_err("Registering tracepoint probe failed\n");
return ret;
}
return do_zen_workaround(set_speclockmap_disable);
}
module_init(zen_workaround_init);
static void __exit zen_workaround_exit(void)
{
do_zen_workaround(unset_speclockmap_disable);
tracepoint_probe_unregister(&__tracepoint_write_msr, on_write_msr, NULL);
}
module_exit(zen_workaround_exit);
MODULE_LICENSE("GPL");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment