Skip to content

Instantly share code, notes, and snippets.

@wenjianhn
Created October 23, 2020 02:04
Show Gist options
  • Save wenjianhn/c7a471983f7927c92d3dd453c4da1e2f to your computer and use it in GitHub Desktop.
Save wenjianhn/c7a471983f7927c92d3dd453c4da1e2f to your computer and use it in GitHub Desktop.
Bench mark the cost of doing kmalloc() then kfree()
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/slab.h>
static u64 read_tsc(void)
{
return (u64)rdtsc_ordered();
}
static void bench_kmalloc(void)
{
unsigned long long now;
unsigned long long delta;
void *p;
p = kmalloc(8, GFP_KERNEL);
/* The next kmalloc is expected to use the fast path */
kfree(p);
/* Check if the CPU is in performance mode. */
// $ cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
local_irq_disable();
now = read_tsc();
p = kmalloc(8, GFP_KERNEL);
kfree(p);
delta = read_tsc() - now;
local_irq_enable();
pr_info("Doing kmalloc() then kfree() costs %llu clock cycles\n", delta);
now = read_tsc();
delta = read_tsc() - now;
pr_info("The cost of read_tsc() is %llu ticks\n", delta);
now = read_tsc();
WRITE_ONCE(p, NULL);
delta = read_tsc() - now - delta;
/* Got a negative value? Need to understand how a CPU works to
* answer this question. */
pr_info("The cost of setting p to NULL is %llu ticks\n", delta);
}
static int __init uaf_init(void)
{
bench_kmalloc();
return 0;
}
static void __exit uaf_exit(void)
{
}
module_init(uaf_init)
module_exit(uaf_exit)
MODULE_LICENSE("GPL");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment