All of lore.kernel.org
 help / color / mirror / Atom feed
From: Priya Bala Govindasamy <pgovind2@uci.edu>
To: rafael@kernel.org, viresh.kumar@linaro.org, ojeda@kernel.org,
	boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com,
	lossin@kernel.org, a.hindborg@kernel.org, aliceryhl@google.com,
	tmgross@umich.edu, dakr@kernel.org, daniel.almeida@collabora.com,
	tamird@kernel.org, acourbot@nvidia.com, work@onurozkan.dev,
	nm@ti.com, sboyd@kernel.org
Cc: linux-pm@vger.kernel.org, rust-for-linux@vger.kernel.org,
	ardalan@uci.edu, zhiyunq@cs.ucr.edu, dzueck@uci.edu,
	pgovind2@uci.edu
Subject: [PATCH 0/1] rust: cpufreq: Add Send bound for Driver::PData
Date: Wed,  2 Dec 2026 00:28:47 +0000	[thread overview]
Message-ID: <cover.1796073594.git.pgovind2@uci.edu> (raw)

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


             reply	other threads:[~2026-12-02  0:28 UTC|newest]

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-02  0:28 Priya Bala Govindasamy [this message]
2026-12-02  0:28 ` [PATCH 1/1] rust: cpufreq: Add Send bound for Driver::PData Priya Bala Govindasamy

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=cover.1796073594.git.pgovind2@uci.edu \
    --to=pgovind2@uci.edu \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=ardalan@uci.edu \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=dzueck@uci.edu \
    --cc=gary@garyguo.net \
    --cc=linux-pm@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=nm@ti.com \
    --cc=ojeda@kernel.org \
    --cc=rafael@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=sboyd@kernel.org \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=viresh.kumar@linaro.org \
    --cc=work@onurozkan.dev \
    --cc=zhiyunq@cs.ucr.edu \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
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.