Skip to contentSkip to conversation

cpufreq_ext: Introduce cpufreq ext governor

RFC PATCH In review Yipeng Zou 6 participants 11 messages Sep 27, 2024 – Oct 23

Subsystems (2)
lore
Share & tools
lore

Yipeng Zou

author
#0 lore raw

cover cpufreq_ext: Introduce cpufreq ext governor

Hi everyone,

I am currently working on a patch for a CPU frequency governor based on BPF, which can use BPF to customize and implement various frequency scaling strategies.

If you have any feedback or suggestions, please do let me know.

Motivation
----------

1. Customization

Existing cpufreq governors in the kernel are designed for general scenarios, which may not always be optimal for specific or specialized workloads.

The userspace governor allows direct control over cpufreq, but users often require guidance from the kernel to achieve the desired frequency.

Cpufreq_ext aims to address this by providing a customizable framework that can be tailored to the unique needs of different systems and applications.

While cpufreq governors can be implemented within a kernel module, maintaining a ko tailored for specific scenarios can be challenging. The complexity and overhead associated with kernel modules make it difficult to quickly adapt and deploy custom frequency scaling strategies.

Cpufreq_ext leverages BPF to offer a more lightweight and flexible approach to implementing customized strategies, allowing for easier maintenance and deployment.

2. Integration with sched_ext:

sched_ext is a scheduler class whose behavior can be defined by a set of BPF programs - the BPF scheduler.

Look for more about sched_ext in [1]:

[1] https://www.kernel.org/doc/html/next/scheduler/sched-ext.html

The interaction between CPU frequency scaling and task scheduling is critical for performance.

cpufreq_ext can work with sched_ext to ensure that both scheduling decisions and frequency adjustments are made in a coordinated manner, optimizing system responsiveness and power consumption.

Overview
--------

The cpufreq ext is a BPF based cpufreq governor, we can customize cpufreq governor in BPF program.

CPUFreq ext works as common cpufreq governor with cpufreq policy.

		   --------------------------
		  |        BPF governor      |
		   --------------------------
			       |
			       v
			  BPF Register
			       |
			       v
	    --------------------------------------
	   |             CPUFreq ext              |
	    --------------------------------------
	      ^                ^               ^
	      |                |               |
	   ---------       ---------       ---------
	  | policy0 | ... | policy1 | ... | policyn |
	   ---------       ---------       ---------

We can register serval function hooks to cpufreq ext by BPF Struct OPS.

The first patch define a dbs_governor, and it's works like other governor.

The second patch gives a sample how to use it, implement one typical cpufreq governor, switch to max cpufreq when VIP task is running on target cpu.

Detail
------

The cpufreq ext use bpf_struct_ops to register serval function hooks.

	struct cpufreq_governor_ext_ops {
		...
	}

Cpufreq_governor_ext_ops defines all the functions that BPF programs can implement customly.

If you need to add a custom function, you only need to define it in this struct.

At the moment we have defined the basic functions.

1. unsigned long (*get_next_freq)(struct cpufreq_policy *policy)

Make decision how to adjust cpufreq here.
The return value represents the CPU frequency that will be updated.

2. unsigned int (*get_sampling_rate)(struct cpufreq_policy *policy)

Make decision how to adjust sampling_rate here. The return value represents the governor samplint rate that will be updated.

3. unsigned int (*init)(void)

BPF governor init callback, return 0 means success.

4. void (*exit)(void)

BPF governor exit callback.

5. char name[CPUFREQ_EXT_NAME_LEN]

BPF governor name.

The cpufreq_ext also add sysfs interface which refer to governor status.

1. ext/stat attribute:

Access to current BPF governor status.

# cat /sys/devices/system/cpu/cpufreq/ext/stat
Stat: CPUFREQ_EXT_INIT
BPF governor: performance

There are number of constraints on the cpufreq_ext:

1. Only one ext governor can be registered at a time.

2. By default, it operates as a performance governor when no BPF governor is registered.

3. The cpufreq_ext governor must be selected before loading a BPF governor; otherwise, the installation of the BPF governor will fail.

TODO
----

The current patch is a starting point, and future work will focus on expanding its capabilities.

I plan to leverage the BPF ecosystem to introduce innovative features, such as real-time adjustments and optimizations based on system-wide observations and analytics.

And I am looking forward to any insights, critiques, or suggestions you may have.

Yipeng Zou (2):
cpufreq_ext: Introduce cpufreq ext governor
cpufreq_ext: Add bpf sample

 drivers/cpufreq/Kconfig        |  23 ++
 drivers/cpufreq/Makefile       |   1 +
 drivers/cpufreq/cpufreq_ext.c  | 525 +++++++++++++++++++++++++++++++++
 samples/bpf/.gitignore         |   1 +
 samples/bpf/Makefile           |   8 +-
 samples/bpf/cpufreq_ext.bpf.c  | 113 +++++++
 samples/bpf/cpufreq_ext_user.c |  48 +++
 7 files changed, 718 insertions(+), 1 deletion(-)
 create mode 100644 drivers/cpufreq/cpufreq_ext.c
 create mode 100644 samples/bpf/cpufreq_ext.bpf.c
 create mode 100644 samples/bpf/cpufreq_ext_user.c
Signature · 1 line
2.34.1
author
#1 lore raw

RFC PATCH 1/2 cpufreq_ext: Introduce cpufreq ext governor

The cpufreq ext is a BPF based cpufreq governor, we can customize cpufreq governor in BPF program.

The cpufreq ext use bpf_struct_ops to register serval function hooks.

	struct cpufreq_governor_ext_ops {
		...
	}

Cpufreq_governor_ext_ops defines all the functions that BPF programs can implement customly.

If you need to add a custom function, you only need to define it in this struct.

At the moment we have defined the basic functions.

1. unsigned long (*get_next_freq)(struct cpufreq_policy *policy)

Make decision how to adjust cpufreq here.
The return value represents the CPU frequency that will be updated.

2. unsigned int (*get_sampling_rate)(struct cpufreq_policy *policy)

Make decision how to adjust sampling_rate here. The return value represents the governor samplint rate that will be updated.

3. unsigned int (*init)(void)

BPF governor init callback, return 0 means success.

4. void (*exit)(void)

BPF governor exit callback.

5. char name[CPUFREQ_EXT_NAME_LEN]

BPF governor name.

The cpufreq_ext also add sysfs interface which refer to governor status.

1. ext/stat attribute:

Access to current BPF governor status.

# cat /sys/devices/system/cpu/cpufreq/ext/stat
Stat: CPUFREQ_EXT_INIT
BPF governor: performance

There are number of constraints on the cpufreq_ext:

1. Only one ext governor can be registered at a time.

2. As default, it will be a performance governor when no BPF governor register.

3. Ext governor should be selected before load one BPF governor, otherwise it will fail to install BPF governor.

---
 drivers/cpufreq/Kconfig       |  23 ++
 drivers/cpufreq/Makefile      |   1 +
 drivers/cpufreq/cpufreq_ext.c | 525 ++++++++++++++++++++++++++++++++++
 3 files changed, 549 insertions(+)
 create mode 100644 drivers/cpufreq/cpufreq_ext.c
drivers/cpufreq/Kconfig +23 -0
index bc49fdfb6419..61ce6f937d3d 100644
@@ -105,6 +105,16 @@ config CPU_FREQ_DEFAULT_GOV_SCHEDUTIL
 	  have a look at the help section of that governor. The fallback
 	  governor will be 'performance'.
 
+config CPU_FREQ_DEFAULT_GOV_EXT
+	bool "ext"
+	depends on SMP
+	select CPU_FREQ_GOV_EXT
+	help
+	  Use the CPUFreq governor 'ext' as default. BPF base cpufreq
+	  governor which can customize governor in BPF program.
+	  Cpufreq_ext can provide application-specific governor, more radical
+	  strategies for dedicated scenarios.
+
 endchoice
 
 config CPU_FREQ_GOV_PERFORMANCE
@@ -203,6 +213,19 @@ config CPU_FREQ_GOV_SCHEDUTIL
 
 	  If in doubt, say N.
 
+config CPU_FREQ_GOV_EXT
+	bool "'ext' cpufreq policy governor"
+	depends on CPU_FREQ && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+	select CPU_FREQ_GOV_ATTR_SET
+	select CPU_FREQ_GOV_COMMON
+	help
+	  This governor makes decisions based on ext. BPF base cpufreq
+	  governor which can customize governor in BPF program.
+	  Cpufreq_ext can provide application-specific governor, more radical
+	  strategies for dedicated scenarios.
+
+	  If in doubt, say N.
+
 comment "CPU frequency scaling drivers"
 
 config CPUFREQ_DT
drivers/cpufreq/Makefile +1 -0
index 3dd9216a65f4..2e8038b7c3c2 100644
@@ -11,6 +11,7 @@ obj-$(CONFIG_CPU_FREQ_GOV_POWERSAVE)	+= cpufreq_powersave.o
 obj-$(CONFIG_CPU_FREQ_GOV_USERSPACE)	+= cpufreq_userspace.o
 obj-$(CONFIG_CPU_FREQ_GOV_ONDEMAND)	+= cpufreq_ondemand.o
 obj-$(CONFIG_CPU_FREQ_GOV_CONSERVATIVE)	+= cpufreq_conservative.o
+obj-$(CONFIG_CPU_FREQ_GOV_EXT)		+= cpufreq_ext.o
 obj-$(CONFIG_CPU_FREQ_GOV_COMMON)		+= cpufreq_governor.o
 obj-$(CONFIG_CPU_FREQ_GOV_ATTR_SET)	+= cpufreq_governor_attr_set.o
 
drivers/cpufreq/cpufreq_ext.c new file +525 -0

525 lines not on this page · raw message

Signature · 1 line
2.34.1
#2 lore raw

RFC PATCH 1/1 cpufreq: ext: serialize BPF registration with governor teardown

The struct_ops link can outlive the last policy using the ext governor. Switching that policy to performance releases the DBS tuners and clears ext_global_tuner. Destroying the link afterwards calls ext_disable(), which unconditionally dereferences the NULL pointer.

Serialize tuner publication and release with BPF registration and unregistration using ext_mutex, and allow unregistering after the tuners have gone away. Preserve registered BPF operations when the governor is initialized again while the link is still alive.

Take the CPU hotplug read lock before ext_mutex in the BPF callbacks and use the cpuslocked static-key helpers. Governor callbacks can run under the hotplug write lock, so acquiring the read lock inside ext_mutex would invert their lock order.

Reproduce by selecting ext, attaching the RFC sample, selecting performance, then destroying the link. This was tested on arm64 QEMU with Linux 6.12 plus the RFC and Jinghao Zhou's ext_gov_update() fix. Lifecycle, frequency-limit and original sample checks also passed with lockdep, jump labels and CPU hotplug enabled.

The 2025 fix addresses a separate policy-state lookup error. This teardown bug is present in the original, unmerged RFC as well.

---
 drivers/cpufreq/cpufreq_ext.c | 29 +++++++++++++++++++++++------
 1 file changed, 23 insertions(+), 6 deletions(-)
drivers/cpufreq/cpufreq_ext.c +23 -6
index c79068e86..20d4d3648 100644
@@ -197,8 +197,9 @@ static int ext_check_member(const struct btf_type *t,
 static void ext_disable(void)
 {
 	pr_info("%s : Unregister ext governor(%s).\n", __func__, ext_ops_global.name);
-	static_branch_disable(&ext_gov_load);
-	ext_global_tuner->ext_gov_stat = CPUFREQ_EXT_INIT;
+	static_branch_disable_cpuslocked(&ext_gov_load);
+	if (ext_global_tuner)
+		ext_global_tuner->ext_gov_stat = CPUFREQ_EXT_INIT;
 	ext_ops_global.get_next_freq = get_next_freq_nop;
 	ext_ops_global.get_sampling_rate = get_sampling_rate_nop;
 	ext_ops_global.init = init_nop;
@@ -210,6 +211,7 @@ static int ext_reg(void *kdata, struct bpf_link *link)
 {
 	struct cpufreq_governor_ext_ops *ops = (struct cpufreq_governor_ext_ops *)kdata;
 
+	cpus_read_lock();
 	mutex_lock(&ext_mutex);
 
 	/*
@@ -218,12 +220,14 @@ static int ext_reg(void *kdata, struct bpf_link *link)
 	if (ext_global_tuner == NULL) {
 		pr_err("%s : Need set ext governor first.\n", __func__);
 		mutex_unlock(&ext_mutex);
+		cpus_read_unlock();
 		return -EEXIST;
 	}
 
 	if (ext_global_tuner->ext_gov_stat != CPUFREQ_EXT_INIT) {
 		pr_err("%s : Already register.\n", __func__);
 		mutex_unlock(&ext_mutex);
+		cpus_read_unlock();
 		return -EEXIST;
 	}
 
@@ -233,17 +237,20 @@ static int ext_reg(void *kdata, struct bpf_link *link)
 	if (ext_ops_global.init && ext_ops_global.init()) {
 		ext_disable();
 		mutex_unlock(&ext_mutex);
+		cpus_read_unlock();
 		return -EINVAL;
 	}
 
-	static_branch_enable(&ext_gov_load);
+	static_branch_enable_cpuslocked(&ext_gov_load);
 	pr_info("%s: Register ext governor(%s).\n", __func__, ext_ops_global.name);
 	mutex_unlock(&ext_mutex);
+	cpus_read_unlock();
 	return 0;
 }
 
 static void ext_unreg(void *kdata, struct bpf_link *link)
 {
+	cpus_read_lock();
 	mutex_lock(&ext_mutex);
 
 	if (ext_ops_global.exit)
@@ -251,6 +258,7 @@ static void ext_unreg(void *kdata, struct bpf_link *link)
 
 	ext_disable();
 	mutex_unlock(&ext_mutex);
+	cpus_read_unlock();
 }
 
 static int ext_init(struct btf *btf)
@@ -470,9 +478,13 @@ static int ext_gov_init(struct dbs_data *dbs_data)
 	dbs_data->ignore_nice_load = 0;
 	dbs_data->tuners = tuner;
 	dbs_data->up_threshold = DEAFULT_FREQUENCY_UP_THRESHOLD;
+
+	mutex_lock(&ext_mutex);
 	ext_global_tuner = tuner;
-	/* Disable ext_gov_load as default */
-	static_branch_disable(&ext_gov_load);
+	if (static_branch_unlikely(&ext_gov_load)) {
+		tuner->ext_gov_stat = CPUFREQ_EXT_LOADED;
+		goto unlock;
+	}
 
 	/* As default, set ext_ops_global to nop function */
 	ext_ops_global.get_next_freq = get_next_freq_nop;
@@ -480,6 +492,8 @@ static int ext_gov_init(struct dbs_data *dbs_data)
 	ext_ops_global.init = init_nop;
 	ext_ops_global.exit = exit_nop;
 	strscpy(ext_ops_global.name, CPUFREQ_EXT_DEFAULT_NAME, strlen(CPUFREQ_EXT_DEFAULT_NAME));
+unlock:
+	mutex_unlock(&ext_mutex);
 	return 0;
 }
 
@@ -490,11 +504,14 @@ static void ext_gov_exit(struct dbs_data *dbs_data)
 	if (!dbs_data || !dbs_data->tuners)
 		return;
 
+	mutex_lock(&ext_mutex);
 	tuner = (struct ext_tuner *)dbs_data->tuners;
 	tuner->ext_gov_stat = CPUFREQ_EXT_NONE;
+	if (ext_global_tuner == tuner)
+		ext_global_tuner = NULL;
 	kfree(dbs_data->tuners);
 	dbs_data->tuners = NULL;
-	ext_global_tuner = NULL;
+	mutex_unlock(&ext_mutex);
 }
 
 static void ext_gov_start(struct cpufreq_policy *policy)
Signature · 1 line
2.43.0
#3 lore raw

Re: [RFC PATCH] cpufreq: ext: serialize BPF registration with governor teardown

Quoted 2 lines · Hungyu Lin

The 2025 fix addresses a separate policy-state lookup error. This teardown bug is present in the original, unmerged RFC as well.

Your bot is going nuts.
drivers/cpufreq/cpufreq_ext.c doesn't exist.
Stop sending slop. This is how you get blocked.

pw-bot: cr

#4 lore raw

Re: [RFC PATCH] cpufreq: ext: serialize BPF registration with governor teardown

Quoted 1 line · Alexei Starovoitov

drivers/cpufreq/cpufreq_ext.c doesn't exist.

I got the submission route wrong. This fix was based on the old, unmerged cpufreq_ext RFC, and I should have coordinated with its author before posting it to the lists.

I'm withdrawing this submission and will take it up with the RFC author directly.

Sorry for the noise.

Hungyu

#5 lore raw

Re: [RFC PATCH] cpufreq: ext: serialize BPF registration with governor teardown

Quoted 3 lines · Hungyu Lin

I'm withdrawing this submission and will take it up with the RFC author directly.

NO. Stop spaming people.

author
#6 lore raw

RFC PATCH 2/2 cpufreq_ext: Add bpf sample

In reply to Yipeng Zou

The cpufreq_ext sample implement the typical BPF governor, switch to max cpufreq when VIP task is running on target cpu.

We can enable the sample in the following step:

1. First add target VIP task PID in samples/bpf/cpufreq_ext.bpf.c, append in vip_task_pid array.

	s32 vip_task_pid[] = {
		...
		@PID
		...
	}

2. Compile the sample.

make -C samples/bpf/

3. Configure ext governor on all cpufreq policy.

echo ext > /sys/devices/system/cpu/cpufreq/policy*/scaling_governor

4. Install the sample.

./samples/bpf/cpufreq_ext

If everything works well, will have some message in kernel log.

	# dmesg
	cpufreq_ext: ext_reg: Register ext governor(VIP).

After BPF cpufreq governor loaded, we can see current BPF governor information in ext/stat attribute.

	# cat /sys/devices/system/cpu/cpufreq/ext/stat
	Stat: CPUFREQ_EXT_LOADED
	BPF governor: VIP

The "VIP" is the BPF governor name.

And we can see some log in trace file.

	# cat /sys/kernel/debug/tracing/trace
	...
	bpf_trace_printk: VIP running Set Freq(2600000) On Policy0.
	bpf_trace_printk: No VIP Set Freq(200000) On Policy0.
	...
---
 samples/bpf/.gitignore         |   1 +
 samples/bpf/Makefile           |   8 ++-
 samples/bpf/cpufreq_ext.bpf.c  | 113 +++++++++++++++++++++++++++++++++
 samples/bpf/cpufreq_ext_user.c |  48 ++++++++++++++
 4 files changed, 169 insertions(+), 1 deletion(-)
 create mode 100644 samples/bpf/cpufreq_ext.bpf.c
 create mode 100644 samples/bpf/cpufreq_ext_user.c
samples/bpf/.gitignore +1 -0
index 9f36fe5e2208..85903156e7e7 100644
@@ -1,4 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0-only
+cpufreq_ext
 cpustat
 fds_example
 hbm
samples/bpf/Makefile +7 -1
index bb4ab3a86b40..07b05d5cf748 100644
@@ -46,6 +46,7 @@ tprogs-y += xdp_fwd
 tprogs-y += task_fd_query
 tprogs-y += ibumad
 tprogs-y += hbm
+tprogs-y += cpufreq_ext
 
 # Libbpf dependencies
 LIBBPF_SRC = $(TOOLS_PATH)/lib/bpf
@@ -96,6 +97,7 @@ xdp_fwd-objs := xdp_fwd_user.o
 task_fd_query-objs := task_fd_query_user.o $(TRACE_HELPERS)
 ibumad-objs := ibumad_user.o
 hbm-objs := hbm.o $(CGROUP_HELPERS)
+cpufreq_ext-objs := cpufreq_ext_user.o
 
 xdp_router_ipv4-objs := xdp_router_ipv4_user.o $(XDP_SAMPLE)
 
@@ -149,6 +151,7 @@ always-y += task_fd_query_kern.o
 always-y += ibumad_kern.o
 always-y += hbm_out_kern.o
 always-y += hbm_edt_kern.o
+always-y += cpufreq_ext.bpf.o
 
 TPROGS_CFLAGS = $(TPROGS_USER_CFLAGS)
 TPROGS_LDFLAGS = $(TPROGS_USER_LDFLAGS)
@@ -200,6 +203,7 @@ TPROGLDLIBS_trace_output	+= -lrt
 TPROGLDLIBS_trace_power		+= -lrt
 TPROGLDLIBS_map_perf_test	+= -lrt
 TPROGLDLIBS_test_overhead	+= -lrt
+TPROGLDLIBS_cpufreq_ext		+= -lrt
 
 # Allows pointing LLC/CLANG to a LLVM backend with bpf support, redefine on cmdline:
 # make M=samples/bpf LLC=~/git/llvm-project/llvm/build/bin/llc CLANG=~/git/llvm-project/llvm/build/bin/clang
@@ -311,6 +315,7 @@ $(obj)/$(TRACE_HELPERS) $(obj)/$(CGROUP_HELPERS) $(obj)/$(XDP_SAMPLE): | libbpf_
 .PHONY: libbpf_hdrs
 
 $(obj)/xdp_router_ipv4_user.o: $(obj)/xdp_router_ipv4.skel.h
+$(obj)/cpufreq_ext_user.o: $(obj)/cpufreq_ext.skel.h
 
 $(obj)/tracex5.bpf.o: $(obj)/syscall_nrs.h
 $(obj)/hbm_out_kern.o: $(src)/hbm.h $(src)/hbm_kern.h
@@ -375,10 +380,11 @@ $(obj)/%.bpf.o: $(src)/%.bpf.c $(obj)/vmlinux.h $(src)/xdp_sample.bpf.h $(src)/x
 		-I$(LIBBPF_INCLUDE) $(CLANG_SYS_INCLUDES) \
 		-c $(filter %.bpf.c,$^) -o $@
 
-LINKED_SKELS := xdp_router_ipv4.skel.h
+LINKED_SKELS := xdp_router_ipv4.skel.h cpufreq_ext.skel.h
 clean-files += $(LINKED_SKELS)
 
 xdp_router_ipv4.skel.h-deps := xdp_router_ipv4.bpf.o xdp_sample.bpf.o
+cpufreq_ext.skel.h-deps := cpufreq_ext.bpf.o
 
 LINKED_BPF_SRCS := $(patsubst %.bpf.o,%.bpf.c,$(foreach skel,$(LINKED_SKELS),$($(skel)-deps)))
 
samples/bpf/cpufreq_ext.bpf.c new file +113 -0

113 lines not on this page · raw message

samples/bpf/cpufreq_ext_user.c new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
2.34.1
#7 lore raw
In reply to Yipeng Zou
Quoted 40 lines · Yipeng Zou

Hi everyone,

I am currently working on a patch for a CPU frequency governor based on BPF, which can use BPF to customize and implement various frequency scaling strategies.

If you have any feedback or suggestions, please do let me know.

Motivation
----------

1. Customization

Existing cpufreq governors in the kernel are designed for general scenarios, which may not always be optimal for specific or specialized workloads.

The userspace governor allows direct control over cpufreq, but users often require guidance from the kernel to achieve the desired frequency.

Cpufreq_ext aims to address this by providing a customizable framework that can be tailored to the unique needs of different systems and applications.

While cpufreq governors can be implemented within a kernel module, maintaining a ko tailored for specific scenarios can be challenging. The complexity and overhead associated with kernel modules make it difficult to quickly adapt and deploy custom frequency scaling strategies.

Cpufreq_ext leverages BPF to offer a more lightweight and flexible approach to implementing customized strategies, allowing for easier maintenance and deployment.

2. Integration with sched_ext:

sched_ext is a scheduler class whose behavior can be defined by a set of BPF programs - the BPF scheduler.

Look for more about sched_ext in [1]:

Quoted 8 lines

[1] https://www.kernel.org/doc/html/next/scheduler/sched-ext.html

The interaction between CPU frequency scaling and task scheduling is critical for performance.

cpufreq_ext can work with sched_ext to ensure that both scheduling decisions and frequency adjustments are made in a coordinated manner, optimizing system responsiveness and power consumption.

I think sched-ext already has a mechanism to influence cpufreq. How is this different ?

Pls cc sched-ext folks in the future.

Quoted 127 lines

Overview
--------

The cpufreq ext is a BPF based cpufreq governor, we can customize cpufreq governor in BPF program.

CPUFreq ext works as common cpufreq governor with cpufreq policy.

                   --------------------------
                  |        BPF governor      |
                   --------------------------
                               |
                               v
                          BPF Register
                               |
                               v
            --------------------------------------
           |             CPUFreq ext              |
            --------------------------------------
              ^                ^               ^
              |                |               |
           ---------       ---------       ---------
          | policy0 | ... | policy1 | ... | policyn |
           ---------       ---------       ---------

We can register serval function hooks to cpufreq ext by BPF Struct OPS.

The first patch define a dbs_governor, and it's works like other governor.

The second patch gives a sample how to use it, implement one typical cpufreq governor, switch to max cpufreq when VIP task is running on target cpu.

Detail
------

The cpufreq ext use bpf_struct_ops to register serval function hooks.

        struct cpufreq_governor_ext_ops {
                ...
        }

Cpufreq_governor_ext_ops defines all the functions that BPF programs can implement customly.

If you need to add a custom function, you only need to define it in this struct.

At the moment we have defined the basic functions.

1. unsigned long (*get_next_freq)(struct cpufreq_policy *policy)

Make decision how to adjust cpufreq here.
The return value represents the CPU frequency that will be updated.

2. unsigned int (*get_sampling_rate)(struct cpufreq_policy *policy)

Make decision how to adjust sampling_rate here. The return value represents the governor samplint rate that will be updated.

3. unsigned int (*init)(void)

BPF governor init callback, return 0 means success.

4. void (*exit)(void)

BPF governor exit callback.

5. char name[CPUFREQ_EXT_NAME_LEN]

BPF governor name.

The cpufreq_ext also add sysfs interface which refer to governor status.

1. ext/stat attribute:

Access to current BPF governor status.

# cat /sys/devices/system/cpu/cpufreq/ext/stat
Stat: CPUFREQ_EXT_INIT
BPF governor: performance

There are number of constraints on the cpufreq_ext:

1. Only one ext governor can be registered at a time.

2. By default, it operates as a performance governor when no BPF governor is registered.

3. The cpufreq_ext governor must be selected before loading a BPF governor; otherwise, the installation of the BPF governor will fail.

TODO
----

The current patch is a starting point, and future work will focus on expanding its capabilities.

I plan to leverage the BPF ecosystem to introduce innovative features, such as real-time adjustments and optimizations based on system-wide observations and analytics.

And I am looking forward to any insights, critiques, or suggestions you may have.

Yipeng Zou (2):
cpufreq_ext: Introduce cpufreq ext governor
cpufreq_ext: Add bpf sample

 drivers/cpufreq/Kconfig        |  23 ++
 drivers/cpufreq/Makefile       |   1 +
 drivers/cpufreq/cpufreq_ext.c  | 525 +++++++++++++++++++++++++++++++++
 samples/bpf/.gitignore         |   1 +
 samples/bpf/Makefile           |   8 +-
 samples/bpf/cpufreq_ext.bpf.c  | 113 +++++++
 samples/bpf/cpufreq_ext_user.c |  48 +++
 7 files changed, 718 insertions(+), 1 deletion(-)
 create mode 100644 drivers/cpufreq/cpufreq_ext.c
 create mode 100644 samples/bpf/cpufreq_ext.bpf.c
 create mode 100644 samples/bpf/cpufreq_ext_user.c

--
2.34.1

#8 lore raw

(cc'ing Daniel Hodges and quoting the whole body)

Quoted 46 lines · Alexei Starovoitov
Quoted 45 lines · Yipeng Zou

Hi everyone,

I am currently working on a patch for a CPU frequency governor based on BPF, which can use BPF to customize and implement various frequency scaling strategies.

If you have any feedback or suggestions, please do let me know.

Motivation
----------

1. Customization

Existing cpufreq governors in the kernel are designed for general scenarios, which may not always be optimal for specific or specialized workloads.

The userspace governor allows direct control over cpufreq, but users often require guidance from the kernel to achieve the desired frequency.

Cpufreq_ext aims to address this by providing a customizable framework that can be tailored to the unique needs of different systems and applications.

While cpufreq governors can be implemented within a kernel module, maintaining a ko tailored for specific scenarios can be challenging. The complexity and overhead associated with kernel modules make it difficult to quickly adapt and deploy custom frequency scaling strategies.

Cpufreq_ext leverages BPF to offer a more lightweight and flexible approach to implementing customized strategies, allowing for easier maintenance and deployment.

2. Integration with sched_ext:

sched_ext is a scheduler class whose behavior can be defined by a set of BPF programs - the BPF scheduler.

Look for more about sched_ext in [1]:

[1] https://www.kernel.org/doc/html/next/scheduler/sched-ext.html

The interaction between CPU frequency scaling and task scheduling is critical for performance.

Quoted 6 lines
Quoted 3 lines

cpufreq_ext can work with sched_ext to ensure that both scheduling decisions and frequency adjustments are made in a coordinated manner, optimizing system responsiveness and power consumption.

I think sched-ext already has a mechanism to influence cpufreq. How is this different ?

FWIW, sched_ext's cpufreq implementation is through the schedutil governor. All that the BPF scheduler does is providing utilization signal to the governor. This seems to work fine for sched_ext schedulers (this doesn't preclude more direct BPF governor).

Quoted 1 line

Pls cc sched-ext folks in the future.

Yeah, it'd be great if you can cc Daniel, me and [email protected].

Quoted 127 lines
Quoted 127 lines

Overview
--------

The cpufreq ext is a BPF based cpufreq governor, we can customize cpufreq governor in BPF program.

CPUFreq ext works as common cpufreq governor with cpufreq policy.

                   --------------------------
                  |        BPF governor      |
                   --------------------------
                               |
                               v
                          BPF Register
                               |
                               v
            --------------------------------------
           |             CPUFreq ext              |
            --------------------------------------
              ^                ^               ^
              |                |               |
           ---------       ---------       ---------
          | policy0 | ... | policy1 | ... | policyn |
           ---------       ---------       ---------

We can register serval function hooks to cpufreq ext by BPF Struct OPS.

The first patch define a dbs_governor, and it's works like other governor.

The second patch gives a sample how to use it, implement one typical cpufreq governor, switch to max cpufreq when VIP task is running on target cpu.

Detail
------

The cpufreq ext use bpf_struct_ops to register serval function hooks.

        struct cpufreq_governor_ext_ops {
                ...
        }

Cpufreq_governor_ext_ops defines all the functions that BPF programs can implement customly.

If you need to add a custom function, you only need to define it in this struct.

At the moment we have defined the basic functions.

1. unsigned long (*get_next_freq)(struct cpufreq_policy *policy)

Make decision how to adjust cpufreq here.
The return value represents the CPU frequency that will be updated.

2. unsigned int (*get_sampling_rate)(struct cpufreq_policy *policy)

Make decision how to adjust sampling_rate here. The return value represents the governor samplint rate that will be updated.

3. unsigned int (*init)(void)

BPF governor init callback, return 0 means success.

4. void (*exit)(void)

BPF governor exit callback.

5. char name[CPUFREQ_EXT_NAME_LEN]

BPF governor name.

The cpufreq_ext also add sysfs interface which refer to governor status.

1. ext/stat attribute:

Access to current BPF governor status.

# cat /sys/devices/system/cpu/cpufreq/ext/stat
Stat: CPUFREQ_EXT_INIT
BPF governor: performance

There are number of constraints on the cpufreq_ext:

1. Only one ext governor can be registered at a time.

2. By default, it operates as a performance governor when no BPF governor is registered.

3. The cpufreq_ext governor must be selected before loading a BPF governor; otherwise, the installation of the BPF governor will fail.

TODO
----

The current patch is a starting point, and future work will focus on expanding its capabilities.

I plan to leverage the BPF ecosystem to introduce innovative features, such as real-time adjustments and optimizations based on system-wide observations and analytics.

And I am looking forward to any insights, critiques, or suggestions you may have.

Yipeng Zou (2):
cpufreq_ext: Introduce cpufreq ext governor
cpufreq_ext: Add bpf sample

 drivers/cpufreq/Kconfig        |  23 ++
 drivers/cpufreq/Makefile       |   1 +
 drivers/cpufreq/cpufreq_ext.c  | 525 +++++++++++++++++++++++++++++++++
 samples/bpf/.gitignore         |   1 +
 samples/bpf/Makefile           |   8 +-
 samples/bpf/cpufreq_ext.bpf.c  | 113 +++++++
 samples/bpf/cpufreq_ext_user.c |  48 +++
 7 files changed, 718 insertions(+), 1 deletion(-)
 create mode 100644 drivers/cpufreq/cpufreq_ext.c
 create mode 100644 samples/bpf/cpufreq_ext.bpf.c
 create mode 100644 samples/bpf/cpufreq_ext_user.c

--
2.34.1

Signature · 1 line
tejun
#9 lore raw
In reply to Yipeng Zou
Quoted 39 lines · Yipeng Zou

Hi everyone,

I am currently working on a patch for a CPU frequency governor based on BPF, which can use BPF to customize and implement various frequency scaling strategies.

If you have any feedback or suggestions, please do let me know.

Motivation
----------

1. Customization

Existing cpufreq governors in the kernel are designed for general scenarios, which may not always be optimal for specific or specialized workloads.

The userspace governor allows direct control over cpufreq, but users often require guidance from the kernel to achieve the desired frequency.

Cpufreq_ext aims to address this by providing a customizable framework that can be tailored to the unique needs of different systems and applications.

While cpufreq governors can be implemented within a kernel module, maintaining a ko tailored for specific scenarios can be challenging. The complexity and overhead associated with kernel modules make it difficult to quickly adapt and deploy custom frequency scaling strategies.

Cpufreq_ext leverages BPF to offer a more lightweight and flexible approach to implementing customized strategies, allowing for easier maintenance and deployment.

2. Integration with sched_ext:

sched_ext is a scheduler class whose behavior can be defined by a set of BPF programs - the BPF scheduler.

Look for more about sched_ext in [1]:

Quoted 8 lines

[1] https://www.kernel.org/doc/html/next/scheduler/sched-ext.html

The interaction between CPU frequency scaling and task scheduling is critical for performance.

cpufreq_ext can work with sched_ext to ensure that both scheduling decisions and frequency adjustments are made in a coordinated manner, optimizing system responsiveness and power consumption.

Hi Yipeng, I prototyped something really similar earlier this year and the conclusion I came to was that a governor might not be the right abstraction for struct_ops. One issue is that depending on the frequency driver being used it may have it governor implmentation included (ex:
intel_pstate). For sched_ext there is already a kfunc (scx_bpf_cpuperf_set) which is a calls into cpufreq_update_util and that has been working well so far.

Quoted 57 lines

Overview
--------

The cpufreq ext is a BPF based cpufreq governor, we can customize cpufreq governor in BPF program.

CPUFreq ext works as common cpufreq governor with cpufreq policy.

		   --------------------------
		  |        BPF governor      |
		   --------------------------
			       |
			       v
			  BPF Register
			       |
			       v
	    --------------------------------------
	   |             CPUFreq ext              |
	    --------------------------------------
	      ^                ^               ^
	      |                |               |
	   ---------       ---------       ---------
	  | policy0 | ... | policy1 | ... | policyn |
	   ---------       ---------       ---------

We can register serval function hooks to cpufreq ext by BPF Struct OPS.

The first patch define a dbs_governor, and it's works like other governor.

The second patch gives a sample how to use it, implement one typical cpufreq governor, switch to max cpufreq when VIP task is running on target cpu.

Detail
------

The cpufreq ext use bpf_struct_ops to register serval function hooks.

	struct cpufreq_governor_ext_ops {
		...
	}

Cpufreq_governor_ext_ops defines all the functions that BPF programs can implement customly.

If you need to add a custom function, you only need to define it in this struct.

At the moment we have defined the basic functions.

1. unsigned long (*get_next_freq)(struct cpufreq_policy *policy)

Make decision how to adjust cpufreq here.
The return value represents the CPU frequency that will be updated.

Quoted 6 lines

2. unsigned int (*get_sampling_rate)(struct cpufreq_policy *policy)

Make decision how to adjust sampling_rate here. The return value represents the governor samplint rate that will be updated.

Why does the governor need a sampling rate? Could this be done with a bpf timer instead?

Quoted 4 lines

3. unsigned int (*init)(void)

BPF governor init callback, return 0 means success.

Quoted 8 lines

4. void (*exit)(void)

BPF governor exit callback.

5. char name[CPUFREQ_EXT_NAME_LEN]

BPF governor name.

I'm guessing it would be useful to have the governor dispatch on almost all the governor methods. IIRC I had something like:

	int	(*start)(struct cpufreq_policy *policy);
	void	(*stop)(struct cpufreq_policy *policy);
	void	(*limits)(struct cpufreq_policy *policy);
	int	(*store_setspeed)(struct cpufreq_policy *policy,
				  unsigned int freq);
Quoted 52 lines

The cpufreq_ext also add sysfs interface which refer to governor status.

1. ext/stat attribute:

Access to current BPF governor status.

# cat /sys/devices/system/cpu/cpufreq/ext/stat
Stat: CPUFREQ_EXT_INIT
BPF governor: performance

There are number of constraints on the cpufreq_ext:

1. Only one ext governor can be registered at a time.

2. By default, it operates as a performance governor when no BPF governor is registered.

3. The cpufreq_ext governor must be selected before loading a BPF governor; otherwise, the installation of the BPF governor will fail.

TODO
----

The current patch is a starting point, and future work will focus on expanding its capabilities.

I plan to leverage the BPF ecosystem to introduce innovative features, such as real-time adjustments and optimizations based on system-wide observations and analytics.

And I am looking forward to any insights, critiques, or suggestions you may have.

Yipeng Zou (2):
cpufreq_ext: Introduce cpufreq ext governor
cpufreq_ext: Add bpf sample

 drivers/cpufreq/Kconfig        |  23 ++
 drivers/cpufreq/Makefile       |   1 +
 drivers/cpufreq/cpufreq_ext.c  | 525 +++++++++++++++++++++++++++++++++
 samples/bpf/.gitignore         |   1 +
 samples/bpf/Makefile           |   8 +-
 samples/bpf/cpufreq_ext.bpf.c  | 113 +++++++
 samples/bpf/cpufreq_ext_user.c |  48 +++
 7 files changed, 718 insertions(+), 1 deletion(-)
 create mode 100644 drivers/cpufreq/cpufreq_ext.c
 create mode 100644 samples/bpf/cpufreq_ext.bpf.c
 create mode 100644 samples/bpf/cpufreq_ext_user.c
Signature · 1 line
2.34.1
#10 lore raw

PATCH 1/1 cpufreq: ext: fix NULL deref in ext_gov_update()

In reply to Yipeng Zou

Switching to the 'ext' governor can trigger a NULL pointer dereference in ext_gov_update().

Two problems were present in this function:
1) policy_dbs was derived via container_of(policy, ...), which is not a valid way to obtain CPUFreq dbs-governor per-policy state. Use policy->governor_data instead.
2) When the BPF hook returns 0 for get_sampling_rate, the code fell

     back to gov->gdbs_data->sampling_rate, which may be NULL or stale
     depending on initialization/teardown ordering. The robust pattern
     is to fetch the per-policy sampling rate from policy_dbs->dbs_data.

This patch switches ext_gov_update() to the per-policy path (policy->governor_data -> policy_dbs->dbs_data) and adds minimal NULL checks. After this change, switching to the 'ext' governor no longer panics in testing.

Observed on: Pixel 6 (oriole, arm64), Android kernel
6.12.0-mainline-g0a53f54ba5c5 (Jun 11, 2025), after applying the cpufreq_ext RFC series. Also revalidated on a PC build.

Reproducer:
for cpu in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do
echo ext > "$cpu"
done

---
 drivers/cpufreq/cpufreq_ext.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
drivers/cpufreq/cpufreq_ext.c +11 -4
index 310f13aca70a..c79068e86c27 100644
@@ -409,11 +409,18 @@ static unsigned int ext_gov_update(struct cpufreq_policy *policy)
 {
 	struct ext_policy *ext;
 	struct policy_dbs_info *policy_dbs;
+	struct dbs_data *dbs_data;
 	unsigned int update_sampling_rate = 0;
-	struct dbs_governor *gov = dbs_governor_of(policy);
 
-	/* Only need to update current policy freq */
-	policy_dbs = container_of((void *)policy, struct policy_dbs_info, policy);
+	/* Get policy_dbs_info from policy's governor_data */
+	policy_dbs = policy->governor_data;
+	if (!policy_dbs)
+		return 0;
+
+	/* Get dbs_data directly from policy_dbs for better stability */
+	dbs_data = policy_dbs->dbs_data;
+	if (!dbs_data)
+		return 0;
 
 	ext = to_ext_policy(policy_dbs);
 
@@ -431,7 +438,7 @@ static unsigned int ext_gov_update(struct cpufreq_policy *policy)
 		update_sampling_rate = ext_ops_global.get_sampling_rate(policy);
 
 	/* If get_sampling_rate return 0, means we don't modify sampling_rate any more. */
-	return update_sampling_rate == 0 ? gov->gdbs_data->sampling_rate : update_sampling_rate;
+	return update_sampling_rate == 0 ? dbs_data->sampling_rate : update_sampling_rate;
 }
 
 static struct policy_dbs_info *ext_gov_alloc(void)
Signature · 1 line
2.34.1