Skip to contentSkip to conversation

rust: cpufreq: reject NULL from cpufreq_cpu_get()

PATCH Superseded Mehmet Koseoglu 2 participants 3 messages Aug 28 1 message not in the archive

Subsystems (2)

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

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.

Fixes 6ebdd7c93177 ("rust: cpufreq: Extend abstractions for policy and driver ops")
Assisted-by LLM

---
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
index affa2b9490ef..4b992ea9a0f0 100644
@@ -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]

#2 lore raw

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 C struct 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 from cpufreq_cpu_get() by explicitly rejecting them using NonNull::new() and returning ENODEV.

Quoted 4 lines
rust/kernel/cpufreq.rs +0 -0
index affa2b9490efc..4b992ea9a0f01 100644

[ ... ]

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 Policy from 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 like cpuinfo_cur_freq) can execute cpufreq_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 C struct cpufreq_policy at 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

reviewer
#3 lore raw
In reply to Mehmet Koseoglu

On 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 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.

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 LLM

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
index affa2b9490ef..4b992ea9a0f0 100644
@@ -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