rust: cpufreq: reject NULL from cpufreq_cpu_get()
Subsystems (2)
PATCH v2 1/1 rust: cpufreq: reject NULL from cpufreq_cpu_get()
cpufreq_cpu_get() returns either a referenced policy or NULL. PolicyCpu::from_cpu() passed its return value to from_err_ptr(), which rejects ERR_PTR values but accepts NULL.
If the lookup fails, Policy::from_raw_mut() therefore constructs a mutable reference from NULL. Dropping the resulting PolicyCpu then passes the invalid pointer to cpufreq_cpu_put(), causing an oops in kobject_put().
Reject NULL with NonNull before constructing the Policy reference. Return ENODEV instead.
A KUnit negative-control run reproduced the oops with the original conversion. The same test passed with this change. The reproducer is available on request.
---
Changes in v2:
- Format modified imports using the kernel's vertical import style.
rust/kernel/cpufreq.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-)
rust/kernel/cpufreq.rs +14 -4
@@ -14,7 +14,13 @@ cpumask, device::{Bound, Device}, devres, - error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_DEFAULT_ERROR}, + error::{ + code::*, + from_result, + to_result, + Result, + VTABLE_DEFAULT_ERROR, // + }, ffi::{c_char, c_ulong}, prelude::*, types::ForeignOwnable,
@@ -29,7 +35,10 @@ marker::PhantomData, ops::{Deref, DerefMut}, pin::Pin, - ptr, + ptr::{ + self, +NonNull ,// + }, };use macros::vtable;
@@ -687,12 +696,13 @@ fn clear_data<T: ForeignOwnable>(&mut self) -> Option<T> {impl <'a>PolicyCpu <'a> {fn from_cpu (cpu:CpuId ) ->Result <Self > {// SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU. -let ptr =from_err_ptr (unsafe { bindings::cpufreq_cpu_get (u32::from (cpu)) })?; +let ptr = +NonNull ::new (unsafe { bindings::cpufreq_cpu_get (u32::from (cpu)) }).ok_or (ENODEV )?;Ok (Self (// SAFETY: The `ptr` is guaranteed to be valid and remains valid for the lifetime of // the returned reference. -unsafe {Policy ::from_raw_mut (ptr) }, +unsafe {Policy ::from_raw_mut (ptr.as_ptr ()) }, )) } }
Signature · 1 line
2.55.0
A message that is not in the archive (sent off-list or not yet received): [email protected]
The import-formatting finding from v1 is addressed in v2. The remaining findings concern pre-existing PolicyCpu lifetime and aliasing behavior and are outside the scope of this patch. They are being investigated separately.
<[email protected]> adresine sahip kullanıcı 28 Ağu 2026 Cum, 19:32 tarihinde şunu yazdı:
Quoted 82 lines
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Pre-existing issues:
- [High] Concurrent callbacks create multiple exclusive mutable references (&mut Policy) to the same Cstruct cpufreq_policy, violating Rust's aliasing rules and causing Undefined Behavior. --commit
8885bf2914cf2fda0630183038e3d1bf9c762617
Author: Mehmet Koseoglu <[email protected]>rust: cpufreq: reject NULL from
cpufreq_cpu_get()This commit addresses a null pointer dereference issue in the cpufreq abstraction. It modifies
PolicyCpu::from_cpu()to correctly handle NULL returns fromcpufreq_cpu_get()by explicitly rejecting them usingNonNull::new()and returning ENODEV.Quoted 4 lines
rust/kernel/cpufreq.rs +0
-0[ ... ]
rust/kernel/cpufreq.rs fn clear_data<T: ForeignOwnable>(&mut self) -> Option<T> { · line 705
Quoted 13 lines
rust/kernel/cpufreq.rs +3
-2@@ -687,12 +696,13 @@ fn clear_data<T: ForeignOwnable>(&mut self) -> Option<T> { impl<'a> PolicyCpu<'a> { fn from_cpu(cpu: CpuId) -> Result<Self> { // SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU. - let ptr = from_err_ptr(unsafe { bindings::cpufreq_cpu_get(u32::from(cpu)) })?; + let ptr = + NonNull::new(unsafe { bindings::cpufreq_cpu_get(u32::from(cpu)) }).ok_or(ENODEV)?; Ok(Self( // SAFETY: The `ptr` is guaranteed to be valid and remains valid for the lifetime of // the returned reference. - unsafe { Policy::from_raw_mut(ptr) }, + unsafe { Policy::from_raw_mut(ptr.as_ptr()) },[Severity: High]
This is a pre-existing issue, but does creating a mutable reference&mut Policyfrom this pointer violate Rust's aliasing rules?Since
cpufreq_cpu_get()only increments a kobject reference count without acquiring an exclusive lock, concurrent accesses from userspace (such as reading sysfs nodes likecpuinfo_cur_freq) can executecpufreq_get()concurrently.Since it only holds a read lock (
down_read(&policy->rwsem)), this creates multiple exclusive mutable references (&mut Policy) to the same underlying Cstruct cpufreq_policyat the same time, triggering undefined behavior.This aliasing issue also seems to be present in other parts of the code that do not hold exclusive locks. For example, in
get_callback():rust/kernel/cpufreq.rs:get_callback() { ... unsafe extern "C" fn get_callback(cpu: c_uint) -> c_uint { // SAFETY: The C API guarantees that `cpu` refers to a valid CPU // number. let cpu_id = unsafe { CpuId::from_u32_unchecked(cpu) }; PolicyCpu::from_cpu(cpu_id).map_or(0, |mut policy| { T::get(&mut policy).unwrap_or(0) }) } ... }As well as in
update_limits_callback():rust/kernel/cpufreq.rs:update_limits_callback() { ... let policy = unsafe { Policy::from_raw_mut(ptr) }; ... }Could this shared access pattern miscompile due to the aliasing violation?
rust/kernel/cpufreq.rs fn clear_data<T: ForeignOwnable>(&mut self) -> Option<T> { · line 708
Quoted 3 lines
rust/kernel/cpufreq.rs +0
-0)) } }--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Onur Özkan
reviewerOn Fri, 28 Aug 2026 19:16:57 +0300
Mehmet Koseoglu <[email protected]> wrote:
Hi Mehmet,
Quoted 11 lines
cpufreq_cpu_get()returns either a referenced policy or NULL.PolicyCpu::from_cpu()passed its return value tofrom_err_ptr(), which rejectsERR_PTRvalues but accepts NULL.If the lookup fails,
Policy::from_raw_mut()therefore constructs a mutable reference from NULL. Dropping the resulting PolicyCpu then passes the invalid pointer tocpufreq_cpu_put(), causing an oops inkobject_put().Reject NULL with NonNull before constructing the Policy reference. Return ENODEV instead.
Quoted 7 lines
A KUnit negative-control run reproduced the oops with the original conversion. The same test passed with this change. The reproducer is available on request.
Fixes 6ebdd7c93177 ("rust: cpufreq: Extend abstractions for policy and driver ops")Assisted-by LLMSigned-off-by Mehmet Koseoglu <[email protected]>
This should be tagged for stable:
LGTM otherwise.
Quoted 56 lines
---
Changes in v2:
- Format modified imports using the kernel's vertical import style.rust/kernel/cpufreq.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-)rust/kernel/cpufreq.rs +14
-4@@ -14,7 +14,13 @@ cpumask, device::{Bound, Device}, devres, - error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_DEFAULT_ERROR}, + error::{ + code::*, + from_result, + to_result, + Result, + VTABLE_DEFAULT_ERROR, // + }, ffi::{c_char, c_ulong}, prelude::*, types::ForeignOwnable,@@ -29,7 +35,10 @@ marker::PhantomData, ops::{Deref, DerefMut}, pin::Pin, - ptr, + ptr::{ + self, +NonNull ,// + }, };use macros::vtable;@@ -687,12 +696,13 @@ fn clear_data<T: ForeignOwnable>(&mut self) -> Option<T> {impl <'a>PolicyCpu <'a> {fn from_cpu (cpu:CpuId ) ->Result <Self > {// SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU. -let ptr =from_err_ptr (unsafe { bindings::cpufreq_cpu_get (u32::from (cpu)) })?; +let ptr = +NonNull ::new (unsafe { bindings::cpufreq_cpu_get (u32::from (cpu)) }).ok_or (ENODEV )?;Ok (Self (// SAFETY: The `ptr` is guaranteed to be valid and remains valid for the lifetime of // the returned reference. -unsafe {Policy ::from_raw_mut (ptr) }, +unsafe {Policy ::from_raw_mut (ptr.as_ptr ()) }, )) } }Signature · 1 line
2.55.0