All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH 0/1] rust: cpufreq: Add Send bound for Driver::PData
@ 2026-12-02  0:28 Priya Bala Govindasamy
  2026-12-02  0:28 ` [PATCH 1/1] " Priya Bala Govindasamy
  0 siblings, 1 reply; 2+ messages in thread
From: Priya Bala Govindasamy @ 2026-12-02  0:28 UTC (permalink / raw)
  To: rafael, viresh.kumar, ojeda, boqun, gary, bjorn3_gh, lossin,
	a.hindborg, aliceryhl, tmgross, dakr, daniel.almeida, tamird,
	acourbot, work, nm, sboyd
  Cc: linux-pm, rust-for-linux, ardalan, zhiyunq, dzueck, pgovind2

Dear Linux kernel maintainers,

We are developing a tool called FerroLens to detect potential unsound
behavior in Rust code in the Linux kernel. The tool internally uses an
LLM to detect bugs. We then perform manual analysis to verify these
reports. FerroLens reported the following bug in rust/kernel/cpufreq.rs:

`Driver::PData` is required to implement `ForeignOwnable`, but currently
is not required to implement `Send`.

The `Registration` type is `Send`. During registration, the `init_callback`
obtains `PData` and transfers it to the C-owned `cpufreq_policy`. While
`Registration` does not itself directly contain `PData`, moving the
`Registration` to a different thread could then allow the other thread to
run `Registration`'s `Drop` implementation. The `Drop` implementation
calls `cpufreq_unregister_driver` which may invoke Rust's `exit_callback`,
which can lead to gaining ownership of the `PData` on another thread and
passing it `Driver::exit`. Therefore, `PData`, a type which may not
implement `Send` could be accessed from a different thread and potentially
dropped there. This is unsound.

Below is a PoC kernel module that demonstrates the issue. `SampleDevice`
is not `Send`, due to the presence of the `NotThreadSafe` marker, but is
used as `Driver::PData`. This module registers a cpufreq driver and then
moves the registration to a worker thread. The worker thread then drops
the registration, which invokes the `exit_callback` and accesses the
`SampleDevice` instance from a different thread, which is unsound.

---
  use core::sync::atomic::{AtomicU32, Ordering};
  use kernel::{
      cpufreq,
      macros::vtable,
      clk::Hertz,
      sync::{Arc, Completion},
      str::CStr,
      workqueue,
      prelude::*,
      types::NotThreadSafe,
  };

  module! {
      type: CpuFreqPocModule,
      name: "cpufreq_poc",
      authors: ["Priya Govindasamy"],
      description: "PoC cpufreq driver for the Rust Driver::Pdata bug",
      license: "GPL",
  }

  struct CpuFreqPocModule {
      worker: Arc<WorkerState>,
  }

  #[pin_data]
  struct WorkerState {
      #[pin]
      started: Completion,
      #[pin]
      stop: Completion,
      #[pin]
      stopped: Completion,
  }

  struct SampleDevice{
      table: cpufreq::TableBox,
      current_freq_khz: AtomicU32,
      marker: NotThreadSafe,
  }

  impl Drop for SampleDevice {
      fn drop(&mut self) {
          pr_info!("cpufreq_poc: SampleDevice dropped on pid {}\n", kernel::current!().pid());
      }
  }

  #[derive(Default)]
  struct CpuFreqPocDriver;

  const LOW_FREQ: Hertz = Hertz::from_mhz(1000);
  const HIGH_FREQ: Hertz = Hertz::from_mhz(2000);

  #[vtable]
  impl cpufreq::Driver for CpuFreqPocDriver {
      const NAME: &'static CStr = c"cpufreq-sample";
      const FLAGS: u16 = cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV;
      const BOOST_ENABLED: bool = true;

      type PData = Arc<SampleDevice>;

      fn init(policy: &mut cpufreq::Policy) -> Result<Self::PData> {
          let mut builder = cpufreq::TableBuilder::new();
          builder.add(LOW_FREQ, 0, 0)?;
          builder.add(HIGH_FREQ, 0, 1)?;
          
          let table = builder.to_table()?;
          policy.cpus().setall();
          policy
              .set_min(LOW_FREQ)
              .set_max(HIGH_FREQ)
              .set_cpuinfo_min_freq(LOW_FREQ)
              .set_cpuinfo_max_freq(HIGH_FREQ)
              .set_suspend_freq(LOW_FREQ)
              .set_transition_latency_ns(cpufreq::DEFAULT_TRANSITION_LATENCY_NS);

          // SAFETY: The table is valid and will live until cpufreq teardown.
          unsafe { policy.set_freq_table(&table) };

          Ok(Arc::new(SampleDevice {
              table,
              current_freq_khz: AtomicU32::new(HIGH_FREQ.as_khz() as u32),
              marker: NotThreadSafe,
          }, GFP_KERNEL)?)
      }

      fn exit(_policy: &mut cpufreq::Policy, _data: Option<Self::PData>) -> Result {
          Ok(())
      }

      fn suspend(policy: &mut cpufreq::Policy) -> Result {
          policy.generic_suspend()
      }

      fn verify(data: &mut cpufreq::PolicyData) -> Result {
          data.generic_verify()
      }

      fn target_index(policy: &mut cpufreq::Policy, index: cpufreq::TableIndex) -> Result {
        let Some(data) = policy.data::<Self::PData>() else {
              return Err(ENOENT);
          };

          let table = &data.table;
          let freq = table.freq(index)?;
          let freq_khz = freq.as_khz() as u32;

          data.current_freq_khz.store(freq_khz, Ordering::Relaxed);
          Ok(())
      }

      fn get(policy: &mut cpufreq::Policy) -> Result<u32> {
          let Some(data) = policy.data::<Self::PData>() else {
              return Err(ENOENT);
          };

          let freq = data.current_freq_khz.load(Ordering::Relaxed);

          Ok(freq)
      }
  }

  impl kernel::Module for CpuFreqPocModule {
      fn init(_module: &'static ThisModule) -> Result<Self> {
          fn assert_send<T: Send>(_: &T) {}

          let driver = match cpufreq::Registration::<CpuFreqPocDriver>::new() {
              Ok(driver) => driver,
              Err(err) => {
                  pr_err!(
                      "cpufreq_poc: cpufreq driver registration failed: errno={}\n",
                      err.to_errno()
                  );
                  return Err(err);
              }
          };
          assert_send(&driver);

          let worker = Arc::pin_init(
              pin_init!(WorkerState {
                  started <- Completion::new(),
                  stop <- Completion::new(),
                  stopped <- Completion::new(),
              }),
              GFP_KERNEL,
          )?;
          let worker_task = worker.clone();

          pr_info!(
              "cpufreq_poc: moving registration from pid {} to a worker thread\n",
              kernel::current!().pid()
          );

          workqueue::system_long().try_spawn(GFP_KERNEL, move || {
              // Moving `driver` into this `Send + 'static` closure is the point of the PoC.
              // The registration remains owned by this worker until module unload.
              pr_info!(
                  "cpufreq_poc: registration is now owned by worker pid {}\n",
                  kernel::current!().pid()
              );
              worker_task.started.complete_all();
              worker_task.stop.wait_for_completion();

              drop(driver);
              pr_info!("cpufreq_poc: registration dropped by worker thread\n");
              worker_task.stopped.complete_all();
          })?;

          // Do not finish loading until the worker has actually taken ownership.
          worker.started.wait_for_completion();

          Ok(Self { worker })
      }
  }

  impl Drop for CpuFreqPocModule {
      fn drop(&mut self) {
          self.worker.stop.complete_all();
          self.worker.stopped.wait_for_completion();
          pr_info!("cpufreq_poc: unloaded\n");
      }
  }

Output:
[664276.708338] cpufreq_poc: cpufreq_poc: moving registration from pid 102668 to a worker thread
[664276.710582] cpufreq_poc: cpufreq_poc: registration is now owned by worker pid 68702
[664280.102311] cpufreq_poc: cpufreq_poc: SampleDevice dropped on pid 68702
[664280.106921] cpufreq_poc: cpufreq_poc: registration dropped by worker thread
[664280.107033] cpufreq_poc: cpufreq_poc: unloaded

Priya Bala Govindasamy (1):
  rust: cpufreq: Add Send bound for Driver::PData

 drivers/cpufreq/rcpufreq_dt.rs |  7 ++-----
 rust/kernel/cpufreq.rs         | 10 +++++++---
 rust/kernel/opp.rs             |  5 +++++
 3 files changed, 14 insertions(+), 8 deletions(-)

-- 
2.34.1


^ permalink raw reply	[flat|nested] 2+ messages in thread

* [PATCH 1/1] rust: cpufreq: Add Send bound for Driver::PData
  2026-12-02  0:28 [PATCH 0/1] rust: cpufreq: Add Send bound for Driver::PData Priya Bala Govindasamy
@ 2026-12-02  0:28 ` Priya Bala Govindasamy
  0 siblings, 0 replies; 2+ messages in thread
From: Priya Bala Govindasamy @ 2026-12-02  0:28 UTC (permalink / raw)
  To: rafael, viresh.kumar, ojeda, boqun, gary, bjorn3_gh, lossin,
	a.hindborg, aliceryhl, tmgross, dakr, daniel.almeida, tamird,
	acourbot, work, nm, sboyd
  Cc: linux-pm, rust-for-linux, ardalan, zhiyunq, dzueck, pgovind2

`Driver::PData` is required to implement `ForeignOwnable`, but
currently is not required to implement `Send`. The init callback
transfers it to the C cpufreq policy, and the exit callback later
recovers it and passes it to `Driver::exit`. These callbacks may
be executed on different threads. Therefore, `PData`, a type which
may not implement `Send` could be accessed from a different thread.

This is a soundness issue and no known failure is currently
triggered by any in-tree users.

Fix this by requiring that `Driver::PData` implement `Send`. Additionally,
for rcpufreq_dt, remove the unused `CpumaskVar`, implement `Send` for
`FreqTable`, and use `KBox<CPUFreqDTDevice>` instead of
`Arc<CPUFreqDTDevice>` for its `Driver::PData` type. `Arc<T>` is `Send`
only if `T: Send + Sync` but `KBox` requires only `T: Send`.

Fixes: 6ebdd7c93177 ("rust: cpufreq: Extend abstractions for policy and driver ops")
Reported-by: Dylan Zueck <dzueck@uci.edu>
Signed-off-by: Priya Bala Govindasamy <pgovind2@uci.edu>
---
This issue was detected by FerroLens, an LLM-assisted analysis tool.

 drivers/cpufreq/rcpufreq_dt.rs |  7 ++-----
 rust/kernel/cpufreq.rs         | 10 +++++++---
 rust/kernel/opp.rs             |  5 +++++
 3 files changed, 14 insertions(+), 8 deletions(-)

diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs
index 2b1f18b7a1e7..ae36140bff15 100644
--- a/drivers/cpufreq/rcpufreq_dt.rs
+++ b/drivers/cpufreq/rcpufreq_dt.rs
@@ -19,7 +19,6 @@
     platform, //
     prelude::*,
     str::CString,
-    sync::Arc,
 };
 
 /// Finds exact supply name from the OF node.
@@ -45,7 +44,6 @@ fn find_supply_names(dev: &Device, cpu: cpu::CpuId) -> Option<KVec<CString>> {
 struct CPUFreqDTDevice {
     opp_table: opp::Table,
     freq_table: opp::FreqTable,
-    _mask: CpumaskVar,
     _token: Option<opp::ConfigToken>,
     _clk: Clk,
 }
@@ -62,7 +60,7 @@ impl cpufreq::Driver for CPUFreqDTDriver {
     const FLAGS: u16 = cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV;
     const BOOST_ENABLED: bool = true;
 
-    type PData = Arc<CPUFreqDTDevice>;
+    type PData = KBox<CPUFreqDTDevice>;
 
     fn init(policy: &mut cpufreq::Policy) -> Result<Self::PData> {
         let cpu = policy.cpu();
@@ -142,11 +140,10 @@ fn init(policy: &mut cpufreq::Policy) -> Result<Self::PData> {
 
         mask.copy(policy.cpus());
 
-        Ok(Arc::new(
+        Ok(KBox::new(
             CPUFreqDTDevice {
                 opp_table,
                 freq_table,
-                _mask: mask,
                 _token: token,
                 _clk: clk,
             },
diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs
index f31671129c98..811dbc4ebbd8 100644
--- a/rust/kernel/cpufreq.rs
+++ b/rust/kernel/cpufreq.rs
@@ -746,9 +746,13 @@ pub trait Driver {
 
     /// Policy specific data.
     ///
-    /// Require that `PData` implements `ForeignOwnable`. We guarantee to never move the underlying
-    /// wrapped data structure.
-    type PData: ForeignOwnable;
+    /// Require that `PData` implements `ForeignOwnable` so that ownership can be transferred
+    /// to the C `cpufreq_policy`.
+    /// Require that `PData` implements `Send` because policy teardown may recover and drop
+    /// it on a different thread from the one that initialized it.
+    /// We guarantee to never move the underlying wrapped data structure while it is owned
+    /// by the C `cpufreq_policy`.
+    type PData: ForeignOwnable + Send;
 
     /// Driver's `init` callback.
     fn init(policy: &mut Policy) -> Result<Self::PData>;
diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs
index 62e44676125d..8fbdbcf857da 100644
--- a/rust/kernel/opp.rs
+++ b/rust/kernel/opp.rs
@@ -35,6 +35,11 @@ pub struct FreqTable {
         ptr: *mut bindings::cpufreq_frequency_table,
     }
 
+    // SAFETY: `FreqTable` owns the allocation referenced by `ptr`. The allocation
+    // may be freed from any thread.
+    // `dev` is an `ARef<Device>`, which is `Send`.
+    unsafe impl Send for FreqTable {}
+
     impl FreqTable {
         /// Creates a new instance of [`FreqTable`] from [`Table`].
         pub(crate) fn new(table: &Table) -> Result<Self> {
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2026-12-02  0:28 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-02  0:28 [PATCH 0/1] rust: cpufreq: Add Send bound for Driver::PData Priya Bala Govindasamy
2026-12-02  0:28 ` [PATCH 1/1] " Priya Bala Govindasamy

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.