Linux Power Management development
 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

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 a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox