From patchwork Mon Apr 21 07:22:09 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 883482 Received: from mail-pl1-f172.google.com (mail-pl1-f172.google.com [209.85.214.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6A30E20F098 for ; Mon, 21 Apr 2025 07:22:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220174; cv=none; b=sFAk/V7/xp/rosilZA5Zjy0YlE3ukUZRh/ABJ5tS1/dZayrON9HYW7MZNwKVq/ZZDsPKd4U1m+ev5b0FfYP3d8kVlSR8tHHz/haiT2fsaccOj2UBzKxTGJMfwkgmnOGqrGKbmUMhlWoyTlQFu2RIvAPHIiXWMclEEySAoKQSO+c= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220174; c=relaxed/simple; bh=6bdBeyQA7PvDMni0+v4HEV40R5KCJ3SAKrl8WzzUVVY=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=utKftpz4+xws1Xjnm+WouzoWXEgUBrShSLedQnHIPxrcTGKmaq+1qK7F5T2KtHnBd8Q1cHWuaTE1E3mOTl4bN8wKuKcwDeb/HH9BtqgERUtiGRQbAhd4POAzEn+HCEW7bflgb41B1zHubgimWOGGvPA6FU+ooZNYtGuoT4gcGeg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org; spf=pass smtp.mailfrom=linaro.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b=TjHaxDtZ; arc=none smtp.client-ip=209.85.214.172 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="TjHaxDtZ" Received: by mail-pl1-f172.google.com with SMTP id d9443c01a7336-22c33e5013aso41476835ad.0 for ; Mon, 21 Apr 2025 00:22:52 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1745220172; x=1745824972; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=pYpmBeA7UxnY21oeYlIxfV+okNCfPfqyF8VN8X/0Ne0=; b=TjHaxDtZNjCA62TPnrlRd0CW6W8XZN1sD8GmimcoutNFHWLkLxG1SNJkLQRPKuSHFL o+Hw0VlhiRtBtKhWjeykn01GVlIAIDYBtRSe5eUssm35awfi7GZcnUw+rbAHIjCPmUcu SE2vxmry6dHqrrxaYpiD2yqYyid0lteShE7Ttl+MZKgia0zfIXqHODSJScueyI+i+m2n 7pH37D0b6upw6Qdbc1E+wIuoU/NhRcvayP0jUclVUE7/h8tBmrsxXOFp3X6N1PqDEjO+ NxyG2y/PePuUQ/twFwCGj3/egW1YLYC8tmYzBytkJ1zYhG5w+2lEgN+Npw1J/7ic4qnI CECg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745220172; x=1745824972; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=pYpmBeA7UxnY21oeYlIxfV+okNCfPfqyF8VN8X/0Ne0=; b=Cd3R2Pe/RFAHHBcSXEgl2BdTKDPUlr5wwbXPPSuFZwWf7axdhDTxic5O0cdS9cnEWQ GBQTUXvklgsZ7qjD7V+Udw3XukWMEVI2Mga3I2H5jZJGoXEcRMFC/Fl4eLMli8B0wNl8 GbR4268F7Y/fejBVafZ93KrGNs1b5yIRXOpV2aDAG2WTMzAwP8axmX1rE+vx5w72iMh7 b5GdUPb0FvHcAQ+xtteJQ3XIBsLM7PpNjVuNCKD1/KK2OxR2g4TOjl1whMPLg0D4KyhD E3PhHD2BXpS0yd4FF8ssURRSexxwxtqw5uWxQxHTSDkxDdOPW8gnZYHLREci8q7OYNJQ IR/w== X-Gm-Message-State: AOJu0YxkyLpfx93AxBMyGJiJGLG7yebgZHOLevsErRPK6FeFlTxzxjzz Fml+d1LyeJMnnlBXT6xY8yY2X7IJFyT0vD9wl3i04UyPR+CNCRX128GWC2oykRw= X-Gm-Gg: ASbGnctsvA17dqPdk5VtQcieLPB5wymXOxtS/ZCAS1mXhJmDmfPCSf2YPAR0UXSrjaX QMtenb3vZ0q1M596Kp5F7NQnTlgEgESD1G+i4V7Qi4RY3go0lbDP9Mg/JrCFlqLwZKL/YU6QYvx xtqvEUI+T1UAtbzEvS7/JY11ID8roNP5SA1H5RSqiQAJzSu19FvjQGCmFyTLkDqbgMxjqlqIYIL 5Chv3TkoNDDxJnZ0bDTXrl9METDzAZRF2oi2UZuNTAcJJjLU9wpHw2HztLflh3T5e9/T0mn+UcF Zvhzo3WA2vPsisibYu3G+wGJ6YAbxY1eG+CQLNnGCTGtVrXKKdMt X-Google-Smtp-Source: AGHT+IFgHdhMJfK4QGzdQrrlcnlF6l1kzsZgx4KMtOxNf9FpUUpVRDonqnuL7JYZDvqFFnKoz+ql/Q== X-Received: by 2002:a17:902:f682:b0:224:912:153 with SMTP id d9443c01a7336-22c53573d25mr174757935ad.5.1745220171548; Mon, 21 Apr 2025 00:22:51 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c50eb5349sm59226245ad.157.2025.04.21.00.22.50 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 21 Apr 2025 00:22:51 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Yury Norov , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?utf-8?q?Alex_Benn?= =?utf-8?q?=C3=A9e?= , Joakim Bech , Rob Herring , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , linux-kernel@vger.kernel.org Subject: [PATCH V11 02/15] rust: cpumask: Add initial abstractions Date: Mon, 21 Apr 2025 12:52:09 +0530 Message-Id: <4a8f23fd447897cb76ccc46d03cc30a2086a0e90.1745218975.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Add initial Rust abstractions for struct cpumask, covering a subset of its APIs. Additional APIs can be added as needed. These abstractions will be used in upcoming Rust support for cpufreq and OPP frameworks. Signed-off-by: Viresh Kumar --- rust/kernel/cpumask.rs | 330 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 2 files changed, 331 insertions(+) create mode 100644 rust/kernel/cpumask.rs diff --git a/rust/kernel/cpumask.rs b/rust/kernel/cpumask.rs new file mode 100644 index 000000000000..c90bfac9346a --- /dev/null +++ b/rust/kernel/cpumask.rs @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU Mask abstractions. +//! +//! C header: [`include/linux/cpumask.h`](srctree/include/linux/cpumask.h) + +use crate::{ + alloc::{AllocError, Flags}, + prelude::*, + types::Opaque, +}; + +#[cfg(CONFIG_CPUMASK_OFFSTACK)] +use core::ptr::{self, NonNull}; + +#[cfg(not(CONFIG_CPUMASK_OFFSTACK))] +use core::mem::MaybeUninit; + +use core::ops::{Deref, DerefMut}; + +/// A CPU Mask. +/// +/// Rust abstraction for the C `struct cpumask`. +/// +/// # Invariants +/// +/// A [`Cpumask`] instance always corresponds to a valid C `struct cpumask`. +/// +/// The callers must ensure that the `struct cpumask` is valid for access and +/// remains valid for the lifetime of the returned reference. +/// +/// ## Examples +/// +/// The following example demonstrates how to update a [`Cpumask`]. +/// +/// ``` +/// use kernel::bindings; +/// use kernel::cpumask::Cpumask; +/// +/// fn set_clear_cpu(ptr: *mut bindings::cpumask, set_cpu: u32, clear_cpu: i32) { +/// // SAFETY: The `ptr` is valid for writing and remains valid for the lifetime of the +/// // returned reference. +/// let mask = unsafe { Cpumask::as_mut_ref(ptr) }; +/// +/// mask.set(set_cpu); +/// mask.clear(clear_cpu); +/// } +/// ``` +#[repr(transparent)] +pub struct Cpumask(Opaque); + +impl Cpumask { + /// Creates a mutable reference to an existing `struct cpumask` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime + /// of the returned reference. + pub unsafe fn as_mut_ref<'a>(ptr: *mut bindings::cpumask) -> &'a mut Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the + // lifetime of the returned reference. + unsafe { &mut *ptr.cast() } + } + + /// Creates a reference to an existing `struct cpumask` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for reading and remains valid for the lifetime + /// of the returned reference. + pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask) -> &'a Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the + // lifetime of the returned reference. + unsafe { &*ptr.cast() } + } + + /// Obtain the raw `struct cpumask` pointer. + pub fn as_raw(&self) -> *mut bindings::cpumask { + let this: *const Self = self; + this.cast_mut().cast() + } + + /// Set `cpu` in the cpumask. + /// + /// ATTENTION: Contrary to C, this Rust `set()` method is non-atomic. + /// This mismatches kernel naming convention and corresponds to the C + /// function `__cpumask_set_cpu()`. + #[inline] + pub fn set(&mut self, cpu: u32) { + // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `__cpumask_set_cpu`. + unsafe { bindings::__cpumask_set_cpu(cpu, self.as_raw()) }; + } + + /// Clear `cpu` in the cpumask. + /// + /// ATTENTION: Contrary to C, this Rust `clear()` method is non-atomic. + /// This mismatches kernel naming convention and corresponds to the C + /// function `__cpumask_clear_cpu()`. + #[inline] + pub fn clear(&mut self, cpu: i32) { + // SAFETY: By the type invariant, `self.as_raw` is a valid argument to + // `__cpumask_clear_cpu`. + unsafe { bindings::__cpumask_clear_cpu(cpu, self.as_raw()) }; + } + + /// Test `cpu` in the cpumask. + /// + /// Equivalent to the kernel's `cpumask_test_cpu` API. + #[inline] + pub fn test(&self, cpu: i32) -> bool { + // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_test_cpu`. + unsafe { bindings::cpumask_test_cpu(cpu, self.as_raw()) } + } + + /// Set all CPUs in the cpumask. + /// + /// Equivalent to the kernel's `cpumask_setall` API. + #[inline] + pub fn setall(&mut self) { + // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_setall`. + unsafe { bindings::cpumask_setall(self.as_raw()) }; + } + + /// Checks if cpumask is empty. + /// + /// Equivalent to the kernel's `cpumask_empty` API. + #[inline] + pub fn empty(&self) -> bool { + // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_empty`. + unsafe { bindings::cpumask_empty(self.as_raw()) } + } + + /// Checks if cpumask is full. + /// + /// Equivalent to the kernel's `cpumask_full` API. + #[inline] + pub fn full(&self) -> bool { + // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_full`. + unsafe { bindings::cpumask_full(self.as_raw()) } + } + + /// Get weight of the cpumask. + /// + /// Equivalent to the kernel's `cpumask_weight` API. + #[inline] + pub fn weight(&self) -> u32 { + // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `cpumask_weight`. + unsafe { bindings::cpumask_weight(self.as_raw()) } + } + + /// Copy cpumask. + /// + /// Equivalent to the kernel's `cpumask_copy` API. + #[inline] + pub fn copy(&self, dstp: &mut Self) { + // SAFETY: By the type invariant, `Self::as_raw` is a valid argument to `cpumask_copy`. + unsafe { bindings::cpumask_copy(dstp.as_raw(), self.as_raw()) }; + } +} + +/// A CPU Mask pointer. +/// +/// Rust abstraction for the C `struct cpumask_var_t`. +/// +/// # Invariants +/// +/// A [`CpumaskVar`] instance always corresponds to a valid C `struct cpumask_var_t`. +/// +/// The callers must ensure that the `struct cpumask_var_t` is valid for access and remains valid +/// for the lifetime of [`CpumaskVar`]. +/// +/// ## Examples +/// +/// The following example demonstrates how to create and update a [`CpumaskVar`]. +/// +/// ``` +/// use kernel::cpumask::CpumaskVar; +/// +/// let mut mask = CpumaskVar::new_zero(GFP_KERNEL).unwrap(); +/// +/// assert!(mask.empty()); +/// mask.set(2); +/// assert!(mask.test(2)); +/// mask.set(3); +/// assert!(mask.test(3)); +/// assert_eq!(mask.weight(), 2); +/// +/// let mask2 = CpumaskVar::try_clone(&mask).unwrap(); +/// assert!(mask2.test(2)); +/// assert!(mask2.test(3)); +/// assert_eq!(mask2.weight(), 2); +/// ``` +pub struct CpumaskVar { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + ptr: NonNull, + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + mask: Cpumask, +} + +impl CpumaskVar { + /// Creates a zero-initialized instance of the [`CpumaskVar`]. + pub fn new_zero(_flags: Flags) -> Result { + Ok(Self { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + ptr: { + let mut ptr: *mut bindings::cpumask = ptr::null_mut(); + + // SAFETY: It is safe to call this method as the reference to `ptr` is valid. + // + // INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of + // scope. + unsafe { bindings::zalloc_cpumask_var(&mut ptr, _flags.as_raw()) }; + NonNull::new(ptr.cast()).ok_or(AllocError)? + }, + + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + // SAFETY: FFI type is valid to be zero-initialized. + // + // INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of scope. + mask: unsafe { core::mem::zeroed() }, + }) + } + + /// Creates an instance of the [`CpumaskVar`]. + /// + /// # Safety + /// + /// The caller must ensure that the returned [`CpumaskVar`] is properly initialized before + /// getting used. + pub unsafe fn new(_flags: Flags) -> Result { + Ok(Self { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + ptr: { + let mut ptr: *mut bindings::cpumask = ptr::null_mut(); + + // SAFETY: It is safe to call this method as the reference to `ptr` is valid. + // + // INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of + // scope. + unsafe { bindings::alloc_cpumask_var(&mut ptr, _flags.as_raw()) }; + NonNull::new(ptr.cast()).ok_or(AllocError)? + }, + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The associated memory is freed when the `CpumaskVar` goes out of scope. + mask: unsafe { MaybeUninit::uninit().assume_init() }, + }) + } + + /// Creates a mutable reference to an existing `struct cpumask_var_t` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime + /// of the returned reference. + pub unsafe fn as_mut_ref<'a>(ptr: *mut bindings::cpumask_var_t) -> &'a mut Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the + // lifetime of the returned reference. + unsafe { &mut *ptr.cast() } + } + + /// Creates a reference to an existing `struct cpumask_var_t` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for reading and remains valid for the lifetime + /// of the returned reference. + pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask_var_t) -> &'a Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the + // lifetime of the returned reference. + unsafe { &*ptr.cast() } + } + + /// Clones cpumask. + pub fn try_clone(cpumask: &Cpumask) -> Result { + // SAFETY: The returned cpumask_var is initialized right after this call. + let mut cpumask_var = unsafe { Self::new(GFP_KERNEL) }?; + + cpumask.copy(&mut cpumask_var); + Ok(cpumask_var) + } +} + +// Make [`CpumaskVar`] behave like a pointer to [`Cpumask`]. +impl Deref for CpumaskVar { + type Target = Cpumask; + + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + fn deref(&self) -> &Self::Target { + // SAFETY: The caller owns CpumaskVar, so it is safe to deref the cpumask. + unsafe { &*self.ptr.as_ptr() } + } + + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + fn deref(&self) -> &Self::Target { + &self.mask + } +} + +impl DerefMut for CpumaskVar { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + fn deref_mut(&mut self) -> &mut Cpumask { + // SAFETY: The caller owns CpumaskVar, so it is safe to deref the cpumask. + unsafe { self.ptr.as_mut() } + } + + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + fn deref_mut(&mut self) -> &mut Cpumask { + &mut self.mask + } +} + +impl Drop for CpumaskVar { + fn drop(&mut self) { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + // SAFETY: By the type invariant, `self.as_raw` is a valid argument to `free_cpumask_var`. + unsafe { + bindings::free_cpumask_var(self.as_raw()) + }; + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index de07aadd1ff5..75f78f6bfaa6 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -42,6 +42,7 @@ pub mod block; #[doc(hidden)] pub mod build_assert; +pub mod cpumask; pub mod cred; pub mod device; pub mod device_id; From patchwork Mon Apr 21 07:22:11 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 883481 Received: from mail-pl1-f177.google.com (mail-pl1-f177.google.com [209.85.214.177]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id AA7812135A1 for ; Mon, 21 Apr 2025 07:22:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.177 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220182; cv=none; b=Hk7sGHm/ONyvkWBWbYqjTqW3PeYbCt77RPWDvQY5Jj5QF7XNLe8CZLjWQ1rAwBWwSdWLoAsziCPFgYTNaPjHGszBrt/fQp33liBzKBrVj9QVJxaIoV8njz1T93Dh72ir3/5iHdUzbCoboQcDpxUY6OpGcvdNIG4Mfz8ML6P9CnE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220182; c=relaxed/simple; bh=4HWksdgns8ejVb++Q4NJVdKDSuHEDHdMmvi+j+YhGlo=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=GqDf5Dn7fmFtYoShI97SqNO3T6jCKmBMNjxKnvc3qhE5O8AA58I8ZzMeFE59I+q8LGcNoIYlyfLsehCloKC7SiFru/3VdJaJlZA2nG3DQq4jkm35lyPS3gB6oFs7bM6UtnX2XJyPhcBwwMWfl9Z+w2pWd+7HBlVeO1Ct93314kE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org; spf=pass smtp.mailfrom=linaro.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b=gCVK+MGo; arc=none smtp.client-ip=209.85.214.177 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="gCVK+MGo" Received: by mail-pl1-f177.google.com with SMTP id d9443c01a7336-225df540edcso47912435ad.0 for ; Mon, 21 Apr 2025 00:22:59 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1745220179; x=1745824979; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=WNsggH78Gujq22EIg5QA+ygoUlPHiqAj8S6vH5ayXvk=; b=gCVK+MGoFcq8T9M7dKRL77rn/KjhTtQugWexbw7oL6x6lHjgpoVTDBAZk5dj/yctiJ 3PU2r+3r9RIHBMC6yZFidl2woDvGCQuns5GN523MHPB3QXCfZ03zuKJWjrOUNMh0acqD CETr+G0uAEwCL1iOf17Yak4l+jutYIa4Tyd/KyBMR5A7IkJIz/nq0J7FBR6ikXC/ITYH RW4b6OSE08Yzk/6kyGFxhUVfFpaOtBCA8MCW7M0Kef0mLJc9UquPDcKLLh/cwkCbOHru pBYlpwTSI5jdeyIAdGzgipZhaimAKElli1+x0HmasukEb0FuGPMXVu7JLsCP1LULFX3g AHHQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745220179; x=1745824979; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=WNsggH78Gujq22EIg5QA+ygoUlPHiqAj8S6vH5ayXvk=; b=kl+Yt7ycwu3K6xNjR5P6OEhaC4XrPZeNSSNPJ7r6FyJfzKVk3RxHz5hidiL51TYPLj B13aOo/dTwAHbTy12vs45nRzK6RIJhYWxxW4XznPHkuBzQx1EOvGAgtSFe2Yb8CMIJk1 NWnQA2i+TuIHV/fnsd3XvDl1CjJKKNtKf2YkwjW/Ghcs9nFQTPdEmCY3w4/GKa+EKA9P D7hvz/f7KjZ2M1P6hw3XoKTM1n/FPU8NbrGP28zSSncbQaSvEC2DyWgE6+Cj0Fxp/L56 8avnveQaNz63ItVfjvBTnh9j5+tRemAMFG42k9slLN+tZ/+sMJoY8YGSxP4COfouSBKB mnAg== X-Forwarded-Encrypted: i=1; AJvYcCXIMVgPJiBDM/xbTV3Ej8XB4oVfDFgr97PvEfNAQbYjY/ijyCice4IfhyQp5wXBEIz2yRGvVuBFBA==@vger.kernel.org X-Gm-Message-State: AOJu0YxFiDxfsnUif4Qag8N8+iF4Uh485r3R8nsBclgEPAZh5ezGYzxa TPGeo7USmhMICvJvMVmYaV2fG7fiPLyuaTC9xnK+T6TgyXcPFysyDE2VYCsIirA= X-Gm-Gg: ASbGncsmnhwzS7su+zMcJR8eMntjqddQrslN3XEUBuURk6bRC3ndAnW4LRAWRb1qdw4 yq7l+TusgCAH9gleowr9mwWmBb/cjuDgL5719AO3JzWScJE4Y3rtZsm6D+r8SX17EXOyu2hAWqb vlQr2C4MF/K9Ff1s6iEcG/NSw1kBwsV3+FGnbK/AaddWXdo7XhRs66VqHxmy8rbNpORADVzUgfm 9F5dqX7QYppEeNKR89PqKl3V/H3k5aEpKBNsE+pbnnGfGceCaoxVCkQG3EAufjVHWitOk6SwLQw +1Ts6I885/LsJmXN8sonxTYE7lmxnPqw1ardVIb6xQ== X-Google-Smtp-Source: AGHT+IFmAEZmVfF2/jJIFd2AX+TRAi14+CXqAGbQyZTBUCMo9uzwZXqwwPnyIMPXsyXmqJRV3PygbA== X-Received: by 2002:a17:902:cf05:b0:21f:98fc:8414 with SMTP id d9443c01a7336-22c50d8c10fmr163080145ad.26.1745220178930; Mon, 21 Apr 2025 00:22:58 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73dbfaacf48sm6086222b3a.148.2025.04.21.00.22.58 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 21 Apr 2025 00:22:58 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Michael Turquette , Stephen Boyd Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?utf-8?q?Alex_Benn?= =?utf-8?q?=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Daniel Almeida , linux-kernel@vger.kernel.org Subject: [PATCH V11 04/15] rust: clk: Add helpers for Rust code Date: Mon, 21 Apr 2025 12:52:11 +0530 Message-Id: <97741e1c82feecbd650183c6a52d2e8bbafad79f.1745218975.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Non-trivial C macros and inlined C functions cannot be used directly in the Rust code and are used via functions ("helpers") that wrap those so that they can be called from Rust. In order to prepare for adding Rust abstractions for the clock APIs, add clock helpers required by the Rust implementation. Reviewed-by: Daniel Almeida Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers/clk.c | 66 +++++++++++++++++++++++++++++++++ rust/helpers/helpers.c | 1 + 4 files changed, 69 insertions(+) create mode 100644 rust/helpers/clk.c diff --git a/MAINTAINERS b/MAINTAINERS index bd7c54af4fd4..608689342aaf 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5883,6 +5883,7 @@ F: include/dt-bindings/clock/ F: include/linux/clk-pr* F: include/linux/clk/ F: include/linux/of_clk.h +F: rust/helpers/clk.c X: drivers/clk/clkdev.c COMMON INTERNET FILE SYSTEM CLIENT (CIFS and SMB3) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index ab37e1d35c70..f53d6e1a21f2 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers/clk.c b/rust/helpers/clk.c new file mode 100644 index 000000000000..6d04372c9f3b --- /dev/null +++ b/rust/helpers/clk.c @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +/* + * The "inline" implementation of below helpers are only available when + * CONFIG_HAVE_CLK or CONFIG_HAVE_CLK_PREPARE aren't set. + */ +#ifndef CONFIG_HAVE_CLK +struct clk *rust_helper_clk_get(struct device *dev, const char *id) +{ + return clk_get(dev, id); +} + +void rust_helper_clk_put(struct clk *clk) +{ + clk_put(clk); +} + +int rust_helper_clk_enable(struct clk *clk) +{ + return clk_enable(clk); +} + +void rust_helper_clk_disable(struct clk *clk) +{ + clk_disable(clk); +} + +unsigned long rust_helper_clk_get_rate(struct clk *clk) +{ + return clk_get_rate(clk); +} + +int rust_helper_clk_set_rate(struct clk *clk, unsigned long rate) +{ + return clk_set_rate(clk, rate); +} +#endif + +#ifndef CONFIG_HAVE_CLK_PREPARE +int rust_helper_clk_prepare(struct clk *clk) +{ + return clk_prepare(clk); +} + +void rust_helper_clk_unprepare(struct clk *clk) +{ + clk_unprepare(clk); +} +#endif + +struct clk *rust_helper_clk_get_optional(struct device *dev, const char *id) +{ + return clk_get_optional(dev, id); +} + +int rust_helper_clk_prepare_enable(struct clk *clk) +{ + return clk_prepare_enable(clk); +} + +void rust_helper_clk_disable_unprepare(struct clk *clk) +{ + clk_disable_unprepare(clk); +} diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index e1c21eba9b15..ae595c9cd91b 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -11,6 +11,7 @@ #include "bug.c" #include "build_assert.c" #include "build_bug.c" +#include "clk.c" #include "cpumask.c" #include "cred.c" #include "device.c" From patchwork Mon Apr 21 07:22:13 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 883480 Received: from mail-pl1-f177.google.com (mail-pl1-f177.google.com [209.85.214.177]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 438C0255E4C for ; Mon, 21 Apr 2025 07:23:07 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.177 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220188; cv=none; b=Qiq6RagzdQbfQtn7TGQ7rIEdaGPPN5e2PMDT964S+7YVRc3+L4KL3DrJGUobwscebUnS4KxoKoqKu/ZaVzlL6iL9O9ciO6Qqv+bh3b8/5RHrxF8cmvGDooYwRLPZEvh1oRnMkYdFVxJ7Tlbe3mMmj6EQjTXoYqOR8ZQ6X85V5uo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220188; c=relaxed/simple; bh=RPs39+G/2/WRBdJP3KwTQnQlR3Lp/kvURzUIgtDgvwA=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=cYCLMyYomVHpaJFLMxnSHthFm/cBDiwo1ScWFNOV0xgjx/GDe8Vg340S7rCStt1K83ANn4IbSU8oH2LmpGdy50HWfeVjMZnz7g2BIBscsmN6Ubz6vHmN8gvfU0Np1vH3nINKz2i6dkIz3h1cmOiEBUWiZO/DFmczcbkrAVpf7hc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org; spf=pass smtp.mailfrom=linaro.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b=XAfcsTJb; arc=none smtp.client-ip=209.85.214.177 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="XAfcsTJb" Received: by mail-pl1-f177.google.com with SMTP id d9443c01a7336-224191d92e4so36703125ad.3 for ; Mon, 21 Apr 2025 00:23:07 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1745220186; x=1745824986; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=06XWI3zWvI8xB81BSzBcpZnXhq7zBjUBfZT4cp51CDs=; b=XAfcsTJbmJL+OSKmyD0WVm243+wjfepWXYh3R7aeLQlzDMSnP/r/MQEgqe17BMucAX s5PULFCXBcEXtR026bMFAxICr1WX2ersvA3SVA1pbSNICCJMnb3vmXzuXhUT+gNbNCHl tj4mkrUbu4cLe0hIk1Z99pD5T6XtKY18X6GnCPaarqahEhRkv9HXYeuOsyzpk1nCseO3 kH/EZB2WipXcNSVzf32IVsAb1hCpDlF8oCi3pika/0lSCkYg7w4n1NmmKS+godqFojyp 9lDSl2eN/oVDnflMpxXDvM3gOdip+5cKUTjN22ka48tZjD/gOvGZweBL0BwPcXpLqwcg HZPA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745220186; x=1745824986; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=06XWI3zWvI8xB81BSzBcpZnXhq7zBjUBfZT4cp51CDs=; b=Zdxn5U9YtQHmL1rcj6QLvwkCo7p8NEff3cCdtzY27h2lzrGKt2Ko1cJcF/K5jfTC9B c6DAKr2CAjnywz7VBH2+HFsxesOy7XbjX+sQAwTtov+cFeloO8NlJ3FXacLojS2b1LqY Tjcg+e7Qe5BYym4OMqtLrlJejAwekUEBPAl4Fxtd6I0wc2Cnkn0qQEK+lgMhFkmRMO5Q pLW1K+oPbnzzWK5jzoe7m02ePBDlnvC8DCHKIIiQx0Hld+W4J6FFowLA63yOwS4+PVJy M3ENtFk1FEysHgd6esl3O0tS9Vz7raA6m9tgqDNKh2Zy8LzBukAPX6wcareE3dIPxhwW 1GDQ== X-Forwarded-Encrypted: i=1; AJvYcCWF/zs6PH3WT514uiTAwC0ZZNazP4tlgScVb1/aM+VErh1GC6MLs4irKXGMUYc3NeEfQ9vdiafVFw==@vger.kernel.org X-Gm-Message-State: AOJu0YyeeBdY/qBGmi4nrzqaqe9h82xy64rTYdNe5+j/wipTnlyz2rUw Rn9ykkXGmCf1ux+Siwp2Gf37rBJmsL+I6v3rLM5JjQdnXQZmyCtVGDffCdQhhOQ= X-Gm-Gg: ASbGnct/qd0poG8WOhJw1Dlv/U/TBM+31RlfaVNnab1blISUGHEWbF23oUXs4nBgEsn 4hES4is3e4PitygYPRNNGX0EmFe8MMjE4iyCo/uROK9yYlZs5K1muYl5hEMjA3lNzgbg23SShuI cJp5A5BHChODbuSIATC8yOgITs6ii/MNCdPlcC/L+G1NodoLzHeZw2PDauneaDmLGH/z3gvVIaM UYeXCrKOfQjfBd3NcskNcscfNZY0KlSBJ29gCVYau90a1N5P77Q/t61RbFu7urlr6UOKbZqxv7v KLvjnE/fG5xFWhlRUK7MT53pEQ0xEsAxhS6AaKuf5A== X-Google-Smtp-Source: AGHT+IHzFs+Yl0YKuPCOslDLAjE9ywj82yfkuqAwtgX61FbjT05TSlY35lL/GVySQmYtWNQHRuL2Lw== X-Received: by 2002:a17:902:dac9:b0:224:a74:28c2 with SMTP id d9443c01a7336-22c535aa4femr163703795ad.29.1745220186519; Mon, 21 Apr 2025 00:23:06 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c50bf31e7sm59281455ad.55.2025.04.21.00.23.05 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 21 Apr 2025 00:23:06 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?utf-8?q?Alex_Benn?= =?utf-8?q?=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Anisse Astier , linux-kernel@vger.kernel.org Subject: [PATCH V11 06/15] rust: macros: enable use of hyphens in module names Date: Mon, 21 Apr 2025 12:52:13 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 From: Anisse Astier Some modules might need naming that contains hyphens "-" to match the auto-probing by name in the platform devices that comes from the device tree. But rust identifiers cannot contain hyphens, so replace the module name by an underscore anywhere we'd use it as an identifier. Signed-off-by: Anisse Astier Reviewed-by: Alice Ryhl [Viresh: Replace "-" with '-', and fix line length checkpatch warnings] Signed-off-by: Viresh Kumar --- rust/macros/module.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/rust/macros/module.rs b/rust/macros/module.rs index a9418fbc9b44..27cc72d474f0 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -185,7 +185,9 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { let info = ModuleInfo::parse(&mut it); - let mut modinfo = ModInfoBuilder::new(info.name.as_ref()); + /* Rust does not allow hyphens in identifiers, use underscore instead */ + let name_identifier = info.name.replace('-', "_"); + let mut modinfo = ModInfoBuilder::new(name_identifier.as_ref()); if let Some(author) = info.author { modinfo.emit("author", &author); } @@ -310,14 +312,15 @@ mod __module_init {{ #[doc(hidden)] #[link_section = \"{initcall_section}\"] #[used] - pub static __{name}_initcall: extern \"C\" fn() -> kernel::ffi::c_int = __{name}_init; + pub static __{name_identifier}_initcall: extern \"C\" fn() -> + kernel::ffi::c_int = __{name_identifier}_init; #[cfg(not(MODULE))] #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)] core::arch::global_asm!( r#\".section \"{initcall_section}\", \"a\" - __{name}_initcall: - .long __{name}_init - . + __{name_identifier}_initcall: + .long __{name_identifier}_init - . .previous \"# ); @@ -325,7 +328,7 @@ mod __module_init {{ #[cfg(not(MODULE))] #[doc(hidden)] #[no_mangle] - pub extern \"C\" fn __{name}_init() -> kernel::ffi::c_int {{ + pub extern \"C\" fn __{name_identifier}_init() -> kernel::ffi::c_int {{ // SAFETY: This function is inaccessible to the outside due to the double // module wrapping it. It is called exactly once by the C side via its // placement above in the initcall section. @@ -335,13 +338,13 @@ mod __module_init {{ #[cfg(not(MODULE))] #[doc(hidden)] #[no_mangle] - pub extern \"C\" fn __{name}_exit() {{ + pub extern \"C\" fn __{name_identifier}_exit() {{ // SAFETY: // - This function is inaccessible to the outside due to the double // module wrapping it. It is called exactly once by the C side via its // unique name, - // - furthermore it is only called after `__{name}_init` has returned `0` - // (which delegates to `__init`). + // - furthermore it is only called after `__{name_identifier}_init` has + // returned `0` (which delegates to `__init`). unsafe {{ __exit() }} }} @@ -381,6 +384,7 @@ unsafe fn __exit() {{ ", type_ = info.type_, name = info.name, + name_identifier = name_identifier, modinfo = modinfo.buffer, initcall_section = ".initcall6.init" ) From patchwork Mon Apr 21 07:22:15 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 883479 Received: from mail-pl1-f173.google.com (mail-pl1-f173.google.com [209.85.214.173]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 994D625A2B6 for ; Mon, 21 Apr 2025 07:23:15 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.173 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220198; cv=none; b=hWdp33kY9Wg2mktinZdOp1BuvIHZWg0myzZIyB/JQGd9MH3AHpjJxKvKmW+gsZKGTcycxt6dmEgWLZztQJEPm+0erRlKbyk1NO/FBXN5HWAjQGZtHNcL0mZ7Pw60g63OKIZenul/ZRcQlvZM3Q/4ixh3yedHTh3tlzGz9jdOUpg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220198; c=relaxed/simple; bh=IgrvvDSM4MOiJ2z3dbx97A/9zxZ6OY5SnxorgwJ16t8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=LOhv75Gwt1+qDiRRmdC4FefB/b/DaWUJR3n/A+0NxxKQAz4zh/Lj7XFXEjpojD7quJfw+1Jad6a/PtpniWd6fJ3+TuJeZsBIinPYtN9ylOTXdifyjhCbGhdyRdMmxRM68INPznTmEkRd2Se3UF1Tkvnw0HcmNFPVrtaXqDGNaJI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org; spf=pass smtp.mailfrom=linaro.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b=R9u3w1kG; arc=none smtp.client-ip=209.85.214.173 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="R9u3w1kG" Received: by mail-pl1-f173.google.com with SMTP id d9443c01a7336-2243803b776so58042135ad.0 for ; Mon, 21 Apr 2025 00:23:15 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1745220195; x=1745824995; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=QXxxE+P/evV1DzV09qUbFo55+wR1rTVmeWl7/3Fr4p4=; b=R9u3w1kGMzrhF27+ZWhPAma4ysKz1Jzu3Ycp6dcdWNOiclY9nYdljv7mSbmxRoekn8 GOpbho+OZ1agqBiYHwhpPEi/vOA9kzaZoIuhOJ3DO3bZO52hiG2hYsNwwMU8U1Rd2ohu 6u04bS02Y/fZ9kWv+3VBN1kqSOkDnNySU7RpuYfk/HIDbrcC/yn/UIDU0/yImZzyM9Tk 1PCUytMjNubnjUl2Yi6OkcZwPImTXMxaBBoh0nyw465la1euwm40ErWp6H1V4FFcvmUR SFLbfO5P5ILLdqa5ciPpkep2qbQhXNSuV/ooX7o8xlqJeZj7lliWaKrrwlZLfdTdmc4/ Mn8g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745220195; x=1745824995; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=QXxxE+P/evV1DzV09qUbFo55+wR1rTVmeWl7/3Fr4p4=; b=kP/ivo+HPB0MR1kzDIPyPuFG25HiUy7bKh6To5qYc9A0Ag6Guwx2no2Al3d3j9e/cH EiwJzPkDhN2eSfOeafp7PVzY0mHqcRyc98s+M+r+hlHuG/9b3/zekyxgOFdbVuKduK5g wg1xH9LEiKpN1DIpERANwHN79H0YF8OSYPXFmU1jabUuozJL4QfDbLQ31BUdX3X+JHEe RHQ307NRbRk7E2BkE+0T1lIF+PhJPj2H8GlyHoG8aB81PVQlZNFlG0BDFH9BHKU3G5Z4 tH32KztSRlf1yc/Rw338Eqb/WcCbeFJRMDwnLPgHC/I1R2lQ1wrMWAa+1rz8rYPPjhxn +OwQ== X-Forwarded-Encrypted: i=1; AJvYcCWm5aJBsIH2I6LDkRMMOn+3Og666RXQr83kuxn+LCZmnR+7tFnxPTzabh8xQOE46Y2rasKaVQ6mBg==@vger.kernel.org X-Gm-Message-State: AOJu0Yz9pjCO2+o1qMP0QiSlEUh+Qjt0CTw1O7NkNA+IoaIMRDNlg66O GtcgBfwQEdVAb9QHoM3S/DgSMDzT/kRCBp0ov+ob9sBbgJuGhcp+3YV3S8P4dqs= X-Gm-Gg: ASbGncuvM653jkgMGoDI5YH5YC31c9sKxf+Nax6E4Z5/aB4u8L+X8kU4gq55grsQVEw nxtPhz/UPCkFyxjg679J/iyqDROzQvnL0ocCAM4n1rzDePCWerG83GEShvptwN6MpK6Zb9lxupU jIYwpyUq6vtP8inqu5WFEAqvZlUg5e2VgKCxQL+srFtJRHMBxKTI27Sd0zyFR5X3fqXyBlikpuy zf3JbyoZhfjudJNFF+kFXcSEAWmQoiG0xLLZhYWZ0HjhJljSO+S3sKvxcYpaPApsa1QQHAdbVbi MNawfqpsQFUcwErC56EgtfxbKqdpHtTjTPxhxr0n7w== X-Google-Smtp-Source: AGHT+IGjYOY8MYM3wuYTxzOki3xVQUi/ko18IW+gWlldXnS9ea9ckb/rLACdtggxTUFon7ZxxACpxg== X-Received: by 2002:a17:902:cec8:b0:215:a179:14ca with SMTP id d9443c01a7336-22c5357a118mr148720895ad.2.1745220194839; Mon, 21 Apr 2025 00:23:14 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c50eb03d2sm59270645ad.142.2025.04.21.00.23.13 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 21 Apr 2025 00:23:14 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?utf-8?q?Alex_Benn?= =?utf-8?q?=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , linux-kernel@vger.kernel.org Subject: [PATCH V11 08/15] rust: opp: Add initial abstractions for OPP framework Date: Mon, 21 Apr 2025 12:52:15 +0530 Message-Id: <7d085916e9c9548aef96ccb07ce709122a0be6cd.1745218975.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Introduce initial Rust abstractions for the Operating Performance Points (OPP) framework. This includes bindings for `struct dev_pm_opp` and `struct dev_pm_opp_data`, laying the groundwork for further OPP integration. Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 2 + rust/kernel/opp.rs | 299 ++++++++++++++++++++++++++++++++ 4 files changed, 303 insertions(+) create mode 100644 rust/kernel/opp.rs diff --git a/MAINTAINERS b/MAINTAINERS index 475abf72869c..931e418f89ed 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -18165,6 +18165,7 @@ F: Documentation/devicetree/bindings/opp/ F: Documentation/power/opp.rst F: drivers/opp/ F: include/linux/pm_opp.h +F: rust/kernel/opp.rs OPL4 DRIVER M: Clemens Ladisch diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index ac92c67d2c38..529f22891e0b 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index db372f806875..11d333c8c673 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -68,6 +68,8 @@ #[cfg(CONFIG_NET)] pub mod net; pub mod of; +#[cfg(CONFIG_PM_OPP)] +pub mod opp; pub mod page; #[cfg(CONFIG_PCI)] pub mod pci; diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs new file mode 100644 index 000000000000..8f0493a8b6e8 --- /dev/null +++ b/rust/kernel/opp.rs @@ -0,0 +1,299 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Operating performance points. +//! +//! This module provides rust abstractions for interacting with the OPP subsystem. +//! +//! C header: [`include/linux/pm_opp.h`](srctree/include/linux/pm_opp.h) +//! +//! Reference: + +use crate::{ + clk::Hertz, + device::Device, + error::{code::*, to_result, Result}, + ffi::c_ulong, + types::{ARef, AlwaysRefCounted, Opaque}, +}; + +use core::ptr; + +/// The voltage unit. +/// +/// Represents voltage in microvolts, wrapping a [`c_ulong`] value. +/// +/// ## Examples +/// +/// ``` +/// use kernel::opp::MicroVolt; +/// +/// let raw = 90500; +/// let volt = MicroVolt(raw); +/// +/// assert_eq!(usize::from(volt), raw); +/// assert_eq!(volt, MicroVolt(raw)); +/// ``` +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub struct MicroVolt(pub c_ulong); + +impl From for c_ulong { + #[inline] + fn from(volt: MicroVolt) -> Self { + volt.0 + } +} + +/// The power unit. +/// +/// Represents power in microwatts, wrapping a [`c_ulong`] value. +/// +/// ## Examples +/// +/// ``` +/// use kernel::opp::MicroWatt; +/// +/// let raw = 1000000; +/// let power = MicroWatt(raw); +/// +/// assert_eq!(usize::from(power), raw); +/// assert_eq!(power, MicroWatt(raw)); +/// ``` +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub struct MicroWatt(pub c_ulong); + +impl From for c_ulong { + #[inline] + fn from(power: MicroWatt) -> Self { + power.0 + } +} + +/// Handle for a dynamically created [`OPP`]. +/// +/// The associated [`OPP`] is automatically removed when the [`Token`] is dropped. +/// +/// ## Examples +/// +/// The following example demonstrates how to create an [`OPP`] dynamically. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::{Data, MicroVolt, Token}; +/// use kernel::types::ARef; +/// +/// fn create_opp(dev: &ARef, freq: Hertz, volt: MicroVolt, level: u32) -> Result { +/// let data = Data::new(freq, volt, level, false); +/// +/// // OPP is removed once token goes out of scope. +/// data.add_opp(dev) +/// } +/// ``` +pub struct Token { + dev: ARef, + freq: Hertz, +} + +impl Token { + /// Dynamically adds an [`OPP`] and returns a [`Token`] that removes it on drop. + fn new(dev: &ARef, mut data: Data) -> Result { + // SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_add_dynamic(dev.as_raw(), &mut data.0) })?; + Ok(Self { + dev: dev.clone(), + freq: data.freq(), + }) + } +} + +impl Drop for Token { + fn drop(&mut self) { + // SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety + // requirements. + unsafe { bindings::dev_pm_opp_remove(self.dev.as_raw(), self.freq.into()) }; + } +} + +/// OPP data. +/// +/// Rust abstraction for the C `struct dev_pm_opp_data`, used to define operating performance +/// points (OPPs) dynamically. +/// +/// ## Examples +/// +/// The following example demonstrates how to create an [`OPP`] with [`Data`]. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::{Data, MicroVolt, Token}; +/// use kernel::types::ARef; +/// +/// fn create_opp(dev: &ARef, freq: Hertz, volt: MicroVolt, level: u32) -> Result { +/// let data = Data::new(freq, volt, level, false); +/// +/// // OPP is removed once token goes out of scope. +/// data.add_opp(dev) +/// } +/// ``` +#[repr(transparent)] +pub struct Data(bindings::dev_pm_opp_data); + +impl Data { + /// Creates a new instance of [`Data`]. + /// + /// This can be used to define a dynamic OPP to be added to a device. + pub fn new(freq: Hertz, volt: MicroVolt, level: u32, turbo: bool) -> Self { + Self(bindings::dev_pm_opp_data { + turbo, + freq: freq.into(), + u_volt: volt.into(), + level, + }) + } + + /// Adds an [`OPP`] dynamically. + /// + /// Returns a [`Token`] that ensures the OPP is automatically removed + /// when it goes out of scope. + #[inline] + pub fn add_opp(self, dev: &ARef) -> Result { + Token::new(dev, self) + } + + /// Returns the frequency associated with this OPP data. + #[inline] + fn freq(&self) -> Hertz { + Hertz(self.0.freq) + } +} + +/// A reference-counted Operating performance point (OPP). +/// +/// Rust abstraction for the C `struct dev_pm_opp`. +/// +/// # Invariants +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of the [`OPP`]. +/// +/// Instances of this type are reference-counted. The reference count is incremented by the +/// `dev_pm_opp_get` function and decremented by `dev_pm_opp_put`. The Rust type `ARef` +/// represents a pointer that owns a reference count on the [`OPP`]. +/// +/// A reference to the [`OPP`], &[`OPP`], isn't refcounted by the Rust code. +#[repr(transparent)] +pub struct OPP(Opaque); + +/// SAFETY: It is okay to send the ownership of [`OPP`] across thread boundaries. +unsafe impl Send for OPP {} + +/// SAFETY: It is okay to access [`OPP`] through shared references from other threads because we're +/// either accessing properties that don't change or that are properly synchronised by C code. +unsafe impl Sync for OPP {} + +/// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted. +unsafe impl AlwaysRefCounted for OPP { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference means that the refcount is nonzero. + unsafe { bindings::dev_pm_opp_get(self.0.get()) }; + } + + unsafe fn dec_ref(obj: ptr::NonNull) { + // SAFETY: The safety requirements guarantee that the refcount is nonzero. + unsafe { bindings::dev_pm_opp_put(obj.cast().as_ptr()) } + } +} + +impl OPP { + /// Creates an owned reference to a [`OPP`] from a valid pointer. + /// + /// The refcount is incremented by the C code and will be decremented by `dec_ref` when the + /// [`ARef`] object is dropped. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and the refcount of the [`OPP`] is incremented. + /// The caller must also ensure that it doesn't explicitly drop the refcount of the [`OPP`], as + /// the returned [`ARef`] object takes over the refcount increment on the underlying object and + /// the same will be dropped along with it. + pub unsafe fn from_raw_opp_owned(ptr: *mut bindings::dev_pm_opp) -> Result> { + let ptr = ptr::NonNull::new(ptr).ok_or(ENODEV)?; + + // SAFETY: The safety requirements guarantee the validity of the pointer. + // + // INVARIANT: The reference-count is decremented when [`OPP`] goes out of scope. + Ok(unsafe { ARef::from_raw(ptr.cast()) }) + } + + /// Creates a reference to a [`OPP`] from a valid pointer. + /// + /// The refcount is not updated by the Rust API unless the returned reference is converted to + /// an [`ARef`] object. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for the duration of `'a`. + #[inline] + pub unsafe fn from_raw_opp<'a>(ptr: *mut bindings::dev_pm_opp) -> Result<&'a Self> { + // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the + // duration of 'a. The cast is okay because [`OPP`] is `repr(transparent)`. + Ok(unsafe { &*ptr.cast() }) + } + + #[inline] + fn as_raw(&self) -> *mut bindings::dev_pm_opp { + self.0.get() + } + + /// Returns the frequency of an [`OPP`]. + pub fn freq(&self, index: Option) -> Hertz { + let index = index.unwrap_or(0); + + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + Hertz(unsafe { bindings::dev_pm_opp_get_freq_indexed(self.as_raw(), index) }) + } + + /// Returns the voltage of an [`OPP`]. + #[inline] + pub fn voltage(&self) -> MicroVolt { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + MicroVolt(unsafe { bindings::dev_pm_opp_get_voltage(self.as_raw()) }) + } + + /// Returns the level of an [`OPP`]. + #[inline] + pub fn level(&self) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_level(self.as_raw()) } + } + + /// Returns the power of an [`OPP`]. + #[inline] + pub fn power(&self) -> MicroWatt { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + MicroWatt(unsafe { bindings::dev_pm_opp_get_power(self.as_raw()) }) + } + + /// Returns the required pstate of an [`OPP`]. + #[inline] + pub fn required_pstate(&self, index: u32) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_required_pstate(self.as_raw(), index) } + } + + /// Returns true if the [`OPP`] is turbo. + #[inline] + pub fn is_turbo(&self) -> bool { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_is_turbo(self.as_raw()) } + } +} From patchwork Mon Apr 21 07:22:17 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 883478 Received: from mail-pg1-f179.google.com (mail-pg1-f179.google.com [209.85.215.179]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E8FDA25A34E for ; Mon, 21 Apr 2025 07:23:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.179 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220204; cv=none; b=Nju9ILBFBQDXThptr/bDvdlqNwU8UIct3eey309l+dRPPZHhowhTikLLc4rx4Y7wQcnHMbF0tJNrwyw83ZabJo5G2UBEjZHryO+gCGEBYS1ThLEtcfhjsIselFZsmooOTSnZUpTWxPW+5rRHA9zL4Rqdei0vETnQCUgJgRv36lg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220204; c=relaxed/simple; bh=XX3U6Tw7oOsV2P/lZuKJuHf6QBrB6qmqZ43oqb9nxh0=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=qIHxkhtXGKuBJxQ+RG2n9c7dq6ZEd3/9Zcmmw9GENzRwHi+6GMlaUV12aUXRmisW1/k6RVdj15G/owbiCNno8j1eo/vm9SQx+6/NoBfjRKfWZkFKMF3JVzzA7BzKgV54B6THS2wLSg5f2o35bZdJ3PfqhPyXQkhNT81WdXVVaVo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org; spf=pass smtp.mailfrom=linaro.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b=nqya0186; arc=none smtp.client-ip=209.85.215.179 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="nqya0186" Received: by mail-pg1-f179.google.com with SMTP id 41be03b00d2f7-7fd35b301bdso4209482a12.2 for ; Mon, 21 Apr 2025 00:23:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1745220202; x=1745825002; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=XUcfURvD53WGE5bWpmH47J8MJLL7ClfsqTtjc7lNE8o=; b=nqya0186JqjskxIsDfC3ZnvvAlaU62g4q31MnEqE1L96tYTNiFy4HDdeRAiXMzLWBd +NjRErkznawJa6uOUV/VvWpnVrsJeKIHsiKIob5ZBexwPlHnJ+l4mjbF6wFrGagMtJZM wC35oKuWEHoAjQdRdc1aowtcmAIiGKhlr2zLc+STNxhCTjQZLOLbRxxyqw7G+ni+1ttM 0z/yS2ht2NeHJemYjX3Gfels4l5K9Fn0A4oqzVEZUZ744fzOCEmCaWFOVJBMwWQJ7/b1 XAGRavxOdEJnS0cBLAQ9OJX6c3B7/6VBiJiCnuxA62vFRs+C4rmnD6K02Gf0TGdLtqAn YC4A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745220202; x=1745825002; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=XUcfURvD53WGE5bWpmH47J8MJLL7ClfsqTtjc7lNE8o=; b=FiEeOpDng+KNPJ77L1u3UOJe3twqgG3yoUAsTLxC8KpQTygByi0ENdhQeDS2Z3BT7z F3aAKxmybiF8Wb58z4upTHGusr9NBbBeqSdX8U7RjfS/9ahgYBK0e43mvFxi856vAJrh UCDhjmNYzWAi4r5y5vYuCbaflxcmKO8JHFrkjl4HV3DbzqK1ZNryf4u5uGPv5Bi7NyRr WAvsU5viQFwKGc2Fo/R9gQldoYG57DwgMyZkdMncbdYFsqpwRKxahK9J6011drQFnNnW V62ei1appp2mfIjU4ny1fqfxenssR4ZOcJiD9eFRVEO7KlUWH2/9cYKnQ2Zh50L4Vcqm UOnA== X-Forwarded-Encrypted: i=1; AJvYcCWfB5BlGdNFYESpTl4jl50+vp41bDRg//hlNKqUcgBUQrkYlO75iVbFU/OGoQ6HlIplcdrklMSPwg==@vger.kernel.org X-Gm-Message-State: AOJu0YwJNipwuCUBfWtClsYqsM4cPA71A6c5QoBdcLtXGhwIXR5c6CFj Qc11WRwMYgCQIOML14UR89qy66zrOlXSZoAIzt+yDzirTobwuH1Fwop3NMg5bck= X-Gm-Gg: ASbGncvZGPmbTfD/zh7wPMLdwogvu8HWF/yogNypB/2zmRSZcJyRcRBda5yLXGAed90 vAz/m5Dyc2t9X6QJxs4MJbS1KWmvg3aAFJyxUWP3MeKYkzL3B++pvFtC6/Oj+nGJY1GZrAvAbtu Kl2QkT1E231VIF//kas+r+6VvZ9RzHv7GrpNtWTdPJQcFOUkfCtfxq92QDDoCza+wzp2Hroji2G KpttZLX8rgki57AvVqIxUpVEU0+hyL+M9EheRHHKEW2eDMomX92XEzQhLEaJ5XLD6O+95OUSowf jx/w+JESwxtV6CQLYJzAFbP82k2NYwyXXMeIH2KLCg== X-Google-Smtp-Source: AGHT+IGxPhzDWRwZnKMMdpMmqReoI1r2YjBUlr0I5yZMN4NwiAXmwekxI1KwiPI6yxVBzAfNSrnxIA== X-Received: by 2002:a17:902:db0f:b0:215:7421:262 with SMTP id d9443c01a7336-22c5357f020mr172416085ad.12.1745220202204; Mon, 21 Apr 2025 00:23:22 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c50bf5382sm59318555ad.81.2025.04.21.00.23.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 21 Apr 2025 00:23:21 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?utf-8?q?Alex_Benn?= =?utf-8?q?=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , linux-kernel@vger.kernel.org Subject: [PATCH V11 10/15] rust: opp: Add abstractions for the configuration options Date: Mon, 21 Apr 2025 12:52:17 +0530 Message-Id: <5394d62f356422c95866af129402878db453f25a.1745218976.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Introduce Rust abstractions for the OPP core configuration options, enabling safe access to various configurable aspects of the OPP framework. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 295 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 293 insertions(+), 2 deletions(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 062c2a04c52f..8b61ea8748a3 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -12,12 +12,29 @@ clk::Hertz, cpumask::{Cpumask, CpumaskVar}, device::Device, - error::{code::*, from_err_ptr, to_result, Error, Result}, + error::{code::*, from_err_ptr, from_result, to_result, Error, Result, VTABLE_DEFAULT_ERROR}, ffi::c_ulong, + prelude::*, + str::CString, types::{ARef, AlwaysRefCounted, Opaque}, }; -use core::ptr; +use core::{marker::PhantomData, ptr}; + +use macros::vtable; + +/// Creates a null-terminated slice of pointers to [`Cstring`]s. +fn to_c_str_array(names: &[CString]) -> Result> { + // Allocated a null-terminated vector of pointers. + let mut list = KVec::with_capacity(names.len() + 1, GFP_KERNEL)?; + + for name in names.iter() { + list.push(name.as_ptr() as _, GFP_KERNEL)?; + } + + list.push(ptr::null(), GFP_KERNEL)?; + Ok(list) +} /// The voltage unit. /// @@ -205,6 +222,280 @@ pub enum SearchType { Ceil, } +/// OPP configuration callbacks. +/// +/// Implement this trait to customize OPP clock and regulator setup for your device. +#[vtable] +pub trait ConfigOps { + /// This is typically used to scale clocks when transitioning between OPPs. + #[inline] + fn config_clks(_dev: &Device, _table: &Table, _opp: &OPP, _scaling_down: bool) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// This provides access to the old and new OPPs, allowing for safe regulator adjustments. + #[inline] + fn config_regulators( + _dev: &Device, + _opp_old: &OPP, + _opp_new: &OPP, + _data: *mut *mut bindings::regulator, + _count: u32, + ) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } +} + +/// OPP configuration token. +/// +/// Returned by the OPP core when configuration is applied to a [`Device`]. The associated +/// configuration is automatically cleared when the token is dropped. +pub struct ConfigToken(i32); + +impl Drop for ConfigToken { + fn drop(&mut self) { + // SAFETY: This is the same token value returned by the C code via `dev_pm_opp_set_config`. + unsafe { bindings::dev_pm_opp_clear_config(self.0) }; + } +} + +/// OPP configurations. +/// +/// Rust abstraction for the C `struct dev_pm_opp_config`. +/// +/// ## Examples +/// +/// The following example demonstrates how to set OPP property-name configuration for a [`Device`]. +/// +/// ``` +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::{Config, ConfigOps, ConfigToken}; +/// use kernel::str::CString; +/// use kernel::types::ARef; +/// use kernel::macros::vtable; +/// +/// #[derive(Default)] +/// struct Driver; +/// +/// #[vtable] +/// impl ConfigOps for Driver {} +/// +/// fn configure(dev: &ARef) -> Result { +/// let name = CString::try_from_fmt(fmt!("{}", "slow"))?; +/// +/// // The OPP configuration is cleared once the [`ConfigToken`] goes out of scope. +/// Config::::new() +/// .set_prop_name(name)? +/// .set(dev) +/// } +/// ``` +#[derive(Default)] +pub struct Config +where + T: Default, +{ + clk_names: Option>, + prop_name: Option, + regulator_names: Option>, + supported_hw: Option>, + + // Tuple containing (required device, index) + required_dev: Option<(ARef, u32)>, + _data: PhantomData, +} + +impl Config { + /// Creates a new instance of [`Config`]. + #[inline] + pub fn new() -> Self { + Self::default() + } + + /// Initializes clock names. + pub fn set_clk_names(mut self, names: KVec) -> Result { + if self.clk_names.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.clk_names = Some(names); + Ok(self) + } + + /// Initializes property name. + pub fn set_prop_name(mut self, name: CString) -> Result { + if self.prop_name.is_some() { + return Err(EBUSY); + } + + self.prop_name = Some(name); + Ok(self) + } + + /// Initializes regulator names. + pub fn set_regulator_names(mut self, names: KVec) -> Result { + if self.regulator_names.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.regulator_names = Some(names); + + Ok(self) + } + + /// Initializes required devices. + pub fn set_required_dev(mut self, dev: ARef, index: u32) -> Result { + if self.required_dev.is_some() { + return Err(EBUSY); + } + + self.required_dev = Some((dev, index)); + Ok(self) + } + + /// Initializes supported hardware. + pub fn set_supported_hw(mut self, hw: KVec) -> Result { + if self.supported_hw.is_some() { + return Err(EBUSY); + } + + if hw.is_empty() { + return Err(EINVAL); + } + + self.supported_hw = Some(hw); + Ok(self) + } + + /// Sets the configuration with the OPP core. + /// + /// The returned [`ConfigToken`] will remove the configuration when dropped. + pub fn set(self, dev: &Device) -> Result { + let (_clk_list, clk_names) = match &self.clk_names { + Some(x) => { + let list = to_c_str_array(x)?; + let ptr = list.as_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null()), + }; + + let (_regulator_list, regulator_names) = match &self.regulator_names { + Some(x) => { + let list = to_c_str_array(x)?; + let ptr = list.as_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null()), + }; + + let prop_name = self + .prop_name + .as_ref() + .map_or(ptr::null(), |p| p.as_char_ptr()); + + let (supported_hw, supported_hw_count) = self + .supported_hw + .as_ref() + .map_or((ptr::null(), 0), |hw| (hw.as_ptr(), hw.len() as u32)); + + let (required_dev, required_dev_index) = self + .required_dev + .as_ref() + .map_or((ptr::null_mut(), 0), |(dev, idx)| (dev.as_raw(), *idx)); + + let mut config = bindings::dev_pm_opp_config { + clk_names, + config_clks: if T::HAS_CONFIG_CLKS { + Some(Self::config_clks) + } else { + None + }, + prop_name, + regulator_names, + config_regulators: if T::HAS_CONFIG_REGULATORS { + Some(Self::config_regulators) + } else { + None + }, + supported_hw, + supported_hw_count, + + required_dev, + required_dev_index, + }; + + // SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety + // requirements. The OPP core guarantees not to access fields of [`Config`] after this call + // and so we don't need to save a copy of them for future use. + let ret = unsafe { bindings::dev_pm_opp_set_config(dev.as_raw(), &mut config) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ConfigToken(ret)) + } + } + + /// Config's clk callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn config_clks( + dev: *mut bindings::device, + opp_table: *mut bindings::opp_table, + opp: *mut bindings::dev_pm_opp, + _data: *mut kernel::ffi::c_void, + scaling_down: bool, + ) -> kernel::ffi::c_int { + from_result(|| { + // SAFETY: 'dev' is guaranteed by the C code to be valid. + let dev = unsafe { Device::get_device(dev) }; + T::config_clks( + &dev, + // SAFETY: 'opp_table' is guaranteed by the C code to be valid. + &unsafe { Table::from_raw_table(opp_table, &dev) }, + // SAFETY: 'opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp(opp)? }, + scaling_down, + ) + .map(|()| 0) + }) + } + + /// Config's regulator callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn config_regulators( + dev: *mut bindings::device, + old_opp: *mut bindings::dev_pm_opp, + new_opp: *mut bindings::dev_pm_opp, + regulators: *mut *mut bindings::regulator, + count: kernel::ffi::c_uint, + ) -> kernel::ffi::c_int { + from_result(|| { + // SAFETY: 'dev' is guaranteed by the C code to be valid. + let dev = unsafe { Device::get_device(dev) }; + T::config_regulators( + &dev, + // SAFETY: 'old_opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp(old_opp)? }, + // SAFETY: 'new_opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp(new_opp)? }, + regulators, + count, + ) + .map(|()| 0) + }) + } +} + /// A reference-counted OPP table. /// /// Rust abstraction for the C `struct opp_table`. From patchwork Mon Apr 21 07:22:19 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 883477 Received: from mail-pj1-f54.google.com (mail-pj1-f54.google.com [209.85.216.54]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8B78A25A656 for ; Mon, 21 Apr 2025 07:23:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.54 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220213; cv=none; b=RqMaAcuzOGrdVPOOwl5wlEflU3U97e37Hjn2tqEuJ5NOkvw4n+fcwPkoZ9Gq9nYvgZrRbzAEnRxUOuCye4HZLFSsJSKu5aQ/ssXuI6r4mogQupyKt4PcIEuI+FGOozrSYKSo2VbxoIlTQJrQxvP5u3/HTVHjcs3HhFnR7I6JLMw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220213; c=relaxed/simple; bh=c8B0zdfOKcl3kZLvMDCl9OXUOPTxNxGJhE5CEd5zVYE=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=IfHJ6b/Tys3Pe18OJDgpM1Cnr2qtYFjrwkfbU3mpZ0gETJq6Lo9wRhlCJeJyZVUDAf3Pq2a3+SrkuCuZ3uQxdn68iDEP0mmlmuRS0BAFZe5y0kGesNMJIqUPLY4r/TYipJCBPDqrOJl30YVNpOi1VsBigW+E+Yk/ZisyVXr4BIc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org; spf=pass smtp.mailfrom=linaro.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b=VvgObXlN; arc=none smtp.client-ip=209.85.216.54 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="VvgObXlN" Received: by mail-pj1-f54.google.com with SMTP id 98e67ed59e1d1-30572effb26so3366928a91.0 for ; Mon, 21 Apr 2025 00:23:31 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1745220211; x=1745825011; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=bpL6jiCJ5lYzq5wgbdxMXB6h/Nv5zlcQqf0W5EJ/Rk0=; b=VvgObXlNUf1tsV3K8RVAr+bsbrjw0hYqHLQOA2jJWEq8a2208pxGo7be9h1ZzrlFDk SJTja+7fDVdX/nxY8tdqEeZwaPPqDldhFShG2v/G9QRWJcxeiXZsC5u5E4Hfzrb2Maom YoXTD5PjTn97MAGo0SF+KKcSkU56S1EyKBAQbzCR0BFKbFTeSKkIeDQFRDK+rbRG0FHF hSzOa2o3y6tISIuqh4DGaxlmyl5o4CaPOY1quJ6Ka5GGFxfoyxvd+tM1Y0I4U5OELBI6 AQKB7CSnOegxOvc6aXFACB96imwzI63hQfBX+6jU36cOUpbrj9yXYkQzhYl0ckGvHkGB aPlg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745220211; x=1745825011; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=bpL6jiCJ5lYzq5wgbdxMXB6h/Nv5zlcQqf0W5EJ/Rk0=; b=tFeJm1hV8HY4Wut8F55DGkuxLbKMfdNMVHXt/wUH5FpfXDMu3PSbQpVud2X26VJNHq HCbevo5F94ZXZuzOMeUQE2aZwIA6CBYvdNPdtHaJHgDuLvZeR/0hMufAxmbszrXelPwF ELvnnRXW6qGKNwDzgTpwNausYAqz8GkHhgMe4LFTannGHwCAIUl1lxLyUABX2aAxcq8u mvKOKCxCgdMNF2LmOegat8LXH3vHXGdFGbqFA90uBnd0u9otIofmkDe6pp+fewz2PeRY BDO7oAWK2sM3cWtXsRyqKNVgmKysxfj98oKP7PdcWJml//aj7Pxs9ijeAWHHtyUpWC/5 1Reg== X-Gm-Message-State: AOJu0Ywk2H+ClMYnRsljL14GO1GeZgBsDe+wRympAlv0/HzvAV5yDZkm 5Om9/+24UvsIE92rLUQxg2jtJWAvkQ5ooMIorUhOgB2D4n1rQX0Lp+vcimxNHJc= X-Gm-Gg: ASbGncviKmjJdLI7L5zOXGeF9BgrJBPX44WEBr9WQTQ80RhX83Y+h8V9deyPmdqBCdf zgRiNdKxkTfvnyZGV/G2Wh4FTi+W2j+JM5ktrrkUFm7Rxx37YxZmdFgW4Qg92IdRVJ2RFSl8pmf wk4uge5R62wGEPSvWBhjVgn1qwYMG5uiQCcNRgamKG3tLMVnJHQx8Lqri5D0SCZQDP7xrqozklq 8b1JQjp1cGemz73gGCxjcB09Ufqw3F6I/5Y6sa15exvhS02k2p23MeHfr8e04W/DR+NC4x2LhUe 0Kt/i3RV3Es9v9Oc3UljycEUo7/JSCaK2lqTzLzQBohSobgZyhql X-Google-Smtp-Source: AGHT+IGMFli0VYy3euttDRfjCMAL4Q976zJoX2syJmV5AdZsjrJANhQGEqaD1LKm13BERvqoBFhSsQ== X-Received: by 2002:a17:90b:548c:b0:2ee:6d08:7936 with SMTP id 98e67ed59e1d1-3087bb64809mr15511261a91.20.1745220210690; Mon, 21 Apr 2025 00:23:30 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-3087e0febecsm5883921a91.39.2025.04.21.00.23.29 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 21 Apr 2025 00:23:30 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?utf-8?q?Alex_Benn?= =?utf-8?q?=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , linux-kernel@vger.kernel.org Subject: [PATCH V11 12/15] rust: cpufreq: Extend abstractions for policy and driver ops Date: Mon, 21 Apr 2025 12:52:19 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Extend the cpufreq abstractions to include support for policy handling and driver operations. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 457 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 456 insertions(+), 1 deletion(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 279956c6d056..5e0bfd03fd30 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -9,15 +9,24 @@ //! Reference: use crate::{ - error::{code::*, to_result, Result}, + clk::{Clk, Hertz}, + cpumask, + device::Device, + error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR}, ffi::c_ulong, prelude::*, + types::ForeignOwnable, + types::Opaque, }; use core::{ + ops::{Deref, DerefMut}, pin::Pin, + ptr, }; +use macros::vtable; + /// Default transition latency value in nanoseconds. pub const ETERNAL_LATENCY_NS: u32 = bindings::CPUFREQ_ETERNAL as u32; @@ -362,3 +371,449 @@ pub fn to_table(mut self) -> Result { TableBox::new(self.entries) } } + +/// CPU frequency policy. +/// +/// Rust abstraction for the C `struct cpufreq_policy`. +/// +/// # Invariants +/// +/// A [`Policy`] instance always corresponds to a valid C `struct cpufreq_policy`. +/// +/// The callers must ensure that the `struct cpufreq_policy` is valid for access and remains valid +/// for the lifetime of the returned reference. +/// +/// ## Examples +/// +/// The following example demonstrates how to create a CPU frequency table. +/// +/// ``` +/// use kernel::cpufreq::{ETERNAL_LATENCY_NS, Policy}; +/// +/// fn update_policy(policy: &mut Policy) { +/// policy +/// .set_dvfs_possible_from_any_cpu(true) +/// .set_fast_switch_possible(true) +/// .set_transition_latency_ns(ETERNAL_LATENCY_NS); +/// +/// pr_info!("The policy details are: {:?}\n", (policy.cpu(), policy.cur())); +/// } +/// ``` +#[repr(transparent)] +pub struct Policy(Opaque); + +impl Policy { + /// Creates a reference to an existing `struct cpufreq_policy` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for reading and remains valid for the lifetime + /// of the returned reference. + #[inline] + pub unsafe fn from_raw<'a>(ptr: *const bindings::cpufreq_policy) -> &'a Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for reading and remains valid for the + // lifetime of the returned reference. + unsafe { &*ptr.cast() } + } + + /// Creates a mutable reference to an existing `struct cpufreq_policy` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for writing and remains valid for the lifetime + /// of the returned reference. + #[inline] + pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpufreq_policy) -> &'a mut Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for writing and remains valid for the + // lifetime of the returned reference. + unsafe { &mut *ptr.cast() } + } + + /// Returns a raw mutable pointer to the C `struct cpufreq_policy`. + #[inline] + fn as_raw(&self) -> *mut bindings::cpufreq_policy { + let this: *const Self = self; + this.cast_mut().cast() + } + + #[inline] + fn as_ref(&self) -> &bindings::cpufreq_policy { + // SAFETY: By the type invariant, the pointer stored in `self` is valid. + unsafe { &*self.as_raw() } + } + + #[inline] + fn as_mut_ref(&mut self) -> &mut bindings::cpufreq_policy { + // SAFETY: By the type invariant, the pointer stored in `self` is valid. + unsafe { &mut *self.as_raw() } + } + + /// Returns the primary CPU for the [`Policy`]. + #[inline] + pub fn cpu(&self) -> u32 { + self.as_ref().cpu + } + + /// Returns the minimum frequency for the [`Policy`]. + #[inline] + pub fn min(&self) -> Hertz { + Hertz::from_khz(self.as_ref().min as usize) + } + + /// Set the minimum frequency for the [`Policy`]. + #[inline] + pub fn set_min(&mut self, min: Hertz) -> &mut Self { + self.as_mut_ref().min = min.as_khz() as u32; + self + } + + /// Returns the maximum frequency for the [`Policy`]. + #[inline] + pub fn max(&self) -> Hertz { + Hertz::from_khz(self.as_ref().max as usize) + } + + /// Set the maximum frequency for the [`Policy`]. + #[inline] + pub fn set_max(&mut self, max: Hertz) -> &mut Self { + self.as_mut_ref().max = max.as_khz() as u32; + self + } + + /// Returns the current frequency for the [`Policy`]. + #[inline] + pub fn cur(&self) -> Hertz { + Hertz::from_khz(self.as_ref().cur as usize) + } + + /// Returns the suspend frequency for the [`Policy`]. + #[inline] + pub fn suspend_freq(&self) -> Hertz { + Hertz::from_khz(self.as_ref().suspend_freq as usize) + } + + /// Sets the suspend frequency for the [`Policy`]. + #[inline] + pub fn set_suspend_freq(&mut self, freq: Hertz) -> &mut Self { + self.as_mut_ref().suspend_freq = freq.as_khz() as u32; + self + } + + /// Provides a wrapper to the generic suspend routine. + #[inline] + pub fn generic_suspend(&mut self) -> Result<()> { + // SAFETY: By the type invariant, the pointer stored in `self` is valid. + to_result(unsafe { bindings::cpufreq_generic_suspend(self.as_mut_ref()) }) + } + + /// Provides a wrapper to the generic get routine. + #[inline] + pub fn generic_get(&self) -> Result { + // SAFETY: By the type invariant, the pointer stored in `self` is valid. + Ok(unsafe { bindings::cpufreq_generic_get(self.cpu()) }) + } + + /// Provides a wrapper to the register with energy model using the OPP core. + #[cfg(CONFIG_PM_OPP)] + #[inline] + pub fn register_em_opp(&mut self) { + // SAFETY: By the type invariant, the pointer stored in `self` is valid. + unsafe { bindings::cpufreq_register_em_with_opp(self.as_mut_ref()) }; + } + + /// Gets [`cpumask::Cpumask`] for a cpufreq [`Policy`]. + #[inline] + pub fn cpus(&mut self) -> &mut cpumask::Cpumask { + // SAFETY: The pointer to `cpus` is valid for writing and remains valid for the lifetime of + // the returned reference. + unsafe { cpumask::CpumaskVar::as_mut_ref(&mut self.as_mut_ref().cpus) } + } + + /// Sets clock for the [`Policy`]. + /// + /// # Safety + /// + /// The caller must guarantee that the returned [`Clk`] is not dropped while it is getting used + /// by the C code. + pub unsafe fn set_clk(&mut self, dev: &Device, name: Option<&CStr>) -> Result { + let clk = Clk::get(dev, name)?; + self.as_mut_ref().clk = clk.as_raw(); + Ok(clk) + } + + /// Allows / disallows frequency switching code to run on any CPU. + #[inline] + pub fn set_dvfs_possible_from_any_cpu(&mut self, val: bool) -> &mut Self { + self.as_mut_ref().dvfs_possible_from_any_cpu = val; + self + } + + /// Returns if fast switching of frequencies is possible or not. + #[inline] + pub fn fast_switch_possible(&self) -> bool { + self.as_ref().fast_switch_possible + } + + /// Enables / disables fast frequency switching. + #[inline] + pub fn set_fast_switch_possible(&mut self, val: bool) -> &mut Self { + self.as_mut_ref().fast_switch_possible = val; + self + } + + /// Sets transition latency (in nanoseconds) for the [`Policy`]. + #[inline] + pub fn set_transition_latency_ns(&mut self, latency_ns: u32) -> &mut Self { + self.as_mut_ref().cpuinfo.transition_latency = latency_ns; + self + } + + /// Sets cpuinfo `min_freq`. + #[inline] + pub fn set_cpuinfo_min_freq(&mut self, min_freq: Hertz) -> &mut Self { + self.as_mut_ref().cpuinfo.min_freq = min_freq.as_khz() as u32; + self + } + + /// Sets cpuinfo `max_freq`. + #[inline] + pub fn set_cpuinfo_max_freq(&mut self, max_freq: Hertz) -> &mut Self { + self.as_mut_ref().cpuinfo.max_freq = max_freq.as_khz() as u32; + self + } + + /// Set `transition_delay_us`, i.e. the minimum time between successive frequency change + /// requests. + #[inline] + pub fn set_transition_delay_us(&mut self, transition_delay_us: u32) -> &mut Self { + self.as_mut_ref().transition_delay_us = transition_delay_us; + self + } + + /// Returns reference to the CPU frequency [`Table`] for the [`Policy`]. + pub fn freq_table(&self) -> Result<&Table> { + if self.as_ref().freq_table.is_null() { + return Err(EINVAL); + } + + // SAFETY: The `freq_table` is guaranteed to be valid for reading and remains valid for the + // lifetime of the returned reference. + Ok(unsafe { Table::from_raw(self.as_ref().freq_table) }) + } + + /// Sets the CPU frequency [`Table`] for the [`Policy`]. + /// + /// # Safety + /// + /// The caller must guarantee that the [`Table`] is not dropped while it is getting used by the + /// C code. + #[inline] + pub unsafe fn set_freq_table(&mut self, table: &Table) -> &mut Self { + self.as_mut_ref().freq_table = table.as_raw(); + self + } + + /// Returns the [`Policy`]'s private data. + pub fn data(&mut self) -> Option<::Borrowed<'_>> { + if self.as_ref().driver_data.is_null() { + None + } else { + // SAFETY: The data is earlier set from [`set_data`]. + Some(unsafe { T::borrow(self.as_ref().driver_data) }) + } + } + + /// Sets the private data of the [`Policy`] using a foreign-ownable wrapper. + /// + /// # Errors + /// + /// Returns `EBUSY` if private data is already set. + fn set_data(&mut self, data: T) -> Result<()> { + if self.as_ref().driver_data.is_null() { + // Transfer the ownership of the data to the foreign interface. + self.as_mut_ref().driver_data = ::into_foreign(data) as _; + Ok(()) + } else { + Err(EBUSY) + } + } + + /// Clears and returns ownership of the private data. + fn clear_data(&mut self) -> Option { + if self.as_ref().driver_data.is_null() { + None + } else { + let data = Some( + // SAFETY: The data is earlier set by us from [`set_data`]. It is safe to take + // back the ownership of the data from the foreign interface. + unsafe { ::from_foreign(self.as_ref().driver_data) }, + ); + self.as_mut_ref().driver_data = ptr::null_mut(); + data + } + } +} + +/// CPU frequency policy created from a CPU number. +/// +/// This struct represents the CPU frequency policy obtained for a specific CPU, providing safe +/// access to the underlying `cpufreq_policy` and ensuring proper cleanup when the `PolicyCpu` is +/// dropped. +struct PolicyCpu<'a>(&'a mut Policy); + +impl<'a> PolicyCpu<'a> { + fn from_cpu(cpu: u32) -> Result { + // SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU. + let ptr = from_err_ptr(unsafe { bindings::cpufreq_cpu_get(cpu) })?; + + 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) }, + )) + } +} + +impl<'a> Deref for PolicyCpu<'a> { + type Target = Policy; + + fn deref(&self) -> &Self::Target { + self.0 + } +} + +impl<'a> DerefMut for PolicyCpu<'a> { + fn deref_mut(&mut self) -> &mut Policy { + self.0 + } +} + +impl<'a> Drop for PolicyCpu<'a> { + fn drop(&mut self) { + // SAFETY: The underlying pointer is guaranteed to be valid for the lifetime of `self`. + unsafe { bindings::cpufreq_cpu_put(self.0.as_raw()) }; + } +} + +/// CPU frequency driver. +/// +/// Implement this trait to provide a CPU frequency driver and its callbacks. +/// +/// Reference: +#[vtable] +pub trait Driver { + /// Driver's name. + const NAME: &'static CStr; + + /// Driver's flags. + const FLAGS: u16; + + /// Boost support. + const BOOST_ENABLED: bool; + + /// Policy specific data. + /// + /// Require that `PData` implements `ForeignOwnable`. We guarantee to never move the underlying + /// wrapped data structure. + type PData: ForeignOwnable; + + /// Driver's `init` callback. + fn init(policy: &mut Policy) -> Result; + + /// Driver's `exit` callback. + fn exit(_policy: &mut Policy, _data: Option) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `online` callback. + fn online(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `offline` callback. + fn offline(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `suspend` callback. + fn suspend(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `resume` callback. + fn resume(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `ready` callback. + fn ready(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `verify` callback. + fn verify(data: &mut PolicyData) -> Result<()>; + + /// Driver's `setpolicy` callback. + fn setpolicy(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `target` callback. + fn target(_policy: &mut Policy, _target_freq: u32, _relation: Relation) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `target_index` callback. + fn target_index(_policy: &mut Policy, _index: TableIndex) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `fast_switch` callback. + fn fast_switch(_policy: &mut Policy, _target_freq: u32) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `adjust_perf` callback. + fn adjust_perf(_policy: &mut Policy, _min_perf: usize, _target_perf: usize, _capacity: usize) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `get_intermediate` callback. + fn get_intermediate(_policy: &mut Policy, _index: TableIndex) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `target_intermediate` callback. + fn target_intermediate(_policy: &mut Policy, _index: TableIndex) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `get` callback. + fn get(_policy: &mut Policy) -> Result { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `update_limits` callback. + fn update_limits(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `bios_limit` callback. + fn bios_limit(_policy: &mut Policy, _limit: &mut u32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `set_boost` callback. + fn set_boost(_policy: &mut Policy, _state: i32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `register_em` callback. + fn register_em(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } +} From patchwork Mon Apr 21 07:22:21 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 883476 Received: from mail-pg1-f173.google.com (mail-pg1-f173.google.com [209.85.215.173]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E428F21127E for ; Mon, 21 Apr 2025 07:23:38 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.173 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220220; cv=none; b=Q7bPDYyLjpMa82uaxbJzVvfpjsiLzaY2jYf5ZZ+D9QSA6glc2Hzn0do14RF2lJLT3omkENU6j1g4c319l+H1fvbwNrLaMSy/dpJ0MbsTx61932dKuE4V9ePE6yzCTjlNgTlrYzYrCYmSTD2OFmC+CpyTXRojphca7BE9kipP550= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745220220; c=relaxed/simple; bh=ZJOJWcwqtx8d8xu+lxGA8TNMktPEoGoBFWcawtAMpbY=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=j3RTiTOtDaIe/SAOm1KpkVg5RVK4XRszexPo7dqx3cHn4+qW9MTeaXk3gm9a+QmaXwja8FdaE78UPjkJiRr1/d4GllI+agmi0pe/UoxjNs0z/tUZk9O+0F32Lv5Uroo5OYZL4+TQHZhQY/sbcq6jAjd2hsfJM2V/3N5koQ+Dy9A= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org; spf=pass smtp.mailfrom=linaro.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b=dJv652ZE; arc=none smtp.client-ip=209.85.215.173 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="dJv652ZE" Received: by mail-pg1-f173.google.com with SMTP id 41be03b00d2f7-b06e9bcc986so2621321a12.0 for ; Mon, 21 Apr 2025 00:23:38 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1745220218; x=1745825018; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=H3pQlqLezjnktSQ7+5L21Axz5wFzz+Z2e/cSw6NoPQ4=; b=dJv652ZEcQfCXa0RNr34erD5xSbJOhKY/6sAwlcmAAPp4irZjFSuC2xb0cmKZT/Dyp taIpcDURihaaRWRO1K89P6ecIxFqzEfj1gqKTsPY4h1YY0lagaID2aMH+l0La1+d2Fpn FWAQnRBwjlomoU6Ai5D6iKS3rnE5T6/n4xTwcb89au3oefNDE9FJTz0Bf5X9bQXl67sN SMDcR5uOifLGcNdoziZYm2Wq7ir1a0cI1YoPwZWA9y5Ge+s7YumRRrzPkc2aQt2sNAAm WLOz9ypNIqR+PnMihvXdeLe9kjsJvikgPCfyiAi8x30omvdoULxGL8sPQO5puYPOLNmz AMfQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745220218; x=1745825018; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=H3pQlqLezjnktSQ7+5L21Axz5wFzz+Z2e/cSw6NoPQ4=; b=hLZkjvL7j8OZyjvnpgh2oe2t74hRj/C+kkUSI7OASXpDUAu8u5bZpIbugw1i5EChKF 9gJ3JHih6VS0t3psR/R/q4o96bwXXb7634AbyXsRuGVQ+dAjy8+W9vh712/wObECSiRz fd0eBdjZ4c99/qP29jjm+1SsQn8GbaKm4tA/dUI62c7z7G0fvhyrQmNcTOnonReL22pL bNe6bJ5c4xwv/ShFLwe/w5FW66fagfd5kH4medJaVmop/StY6bcOLdiZhl/erJlcytIS CkU2cdq3sXCQEhacmLlQ/Fyd/OxqYCawpTbDD2gAakPrM0NJTsNCP6dU4nU/iubMjKa3 j0NQ== X-Forwarded-Encrypted: i=1; AJvYcCUbpKqtXaf5bfG7R16GhniqPu2HqS/x8TGltZhL1FZVqCWMwefVY1XLsO09+cQw7OgV1F6Ygxdtig==@vger.kernel.org X-Gm-Message-State: AOJu0Yy5meazCl0+Fjkn7c6i7C+V7fLMu+b1Oscy2Y5C+wDi1YQt80g0 HC2jbcd+LhyRKvhkOFLx72u8ykG2x5aIzZ4RoYLCeEK/cmTgyj3VlgGOBU4ELx8= X-Gm-Gg: ASbGncvaAJNOX/FG6epgYcJpMACIG/vuECvwVc0f1BZrwONy6rNvFKK/29afeR9yjq+ TE/lwV+/Oe7WAFzlfarUBxYiH/HvBAmtYZI/3cbUIRjiNoywl2Wk+kRuyBu5DoUImQXTnGxyEV5 NZhbkJNyKiYwBZ+BvyMVuOBI7UGHXMtso+Z9nD0/iOc9TukrWDuWCYZiAn8t08qXCWKGh5XYbWM avh7nExf9SxQtZCZChndqIC3PtMYPQmV7wpA7gouxIqBDyCsZLInFu6gHagdL3jqPrdW/DBnXAZ t1KfUTmSMCUtRbzFFSwjeFVV6ZORxyJCryphA3C3bw== X-Google-Smtp-Source: AGHT+IHlVDoLLN+L2gJp3wbagUJcT5yEg2+t7LybVtpznFOf8VXDnXYsgSPRwIYaml1Cy16RF0TexQ== X-Received: by 2002:a17:902:f70d:b0:224:2175:b0cd with SMTP id d9443c01a7336-22c535a9bbemr150380835ad.26.1745220217965; Mon, 21 Apr 2025 00:23:37 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c50eb4292sm59122615ad.150.2025.04.21.00.23.37 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 21 Apr 2025 00:23:37 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?utf-8?q?Alex_Benn?= =?utf-8?q?=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , linux-kernel@vger.kernel.org Subject: [PATCH V11 14/15] rust: opp: Extend OPP abstractions with cpufreq support Date: Mon, 21 Apr 2025 12:52:21 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Extend the OPP abstractions to include support for interacting with the cpufreq core, including the ability to retrieve frequency tables from OPP table. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 8b61ea8748a3..985d90dc0671 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -19,6 +19,69 @@ types::{ARef, AlwaysRefCounted, Opaque}, }; +#[cfg(CONFIG_CPU_FREQ)] +/// Frequency table implementation. +mod freq { + use super::*; + use crate::cpufreq; + use core::ops::Deref; + + /// OPP frequency table. + /// + /// A [`cpufreq::Table`] created from [`Table`]. + pub struct FreqTable { + dev: ARef, + ptr: *mut bindings::cpufreq_frequency_table, + } + + impl FreqTable { + /// Creates a new instance of [`FreqTable`] from [`Table`]. + pub(crate) fn new(table: &Table) -> Result { + let mut ptr: *mut bindings::cpufreq_frequency_table = ptr::null_mut(); + + // SAFETY: The requirements are satisfied by the existence of [`Device`] and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_init_cpufreq_table(table.dev.as_raw(), &mut ptr) + })?; + + Ok(Self { + dev: table.dev.clone(), + ptr, + }) + } + + /// Returns a reference to the underlying [`cpufreq::Table`]. + #[inline] + fn table(&self) -> &cpufreq::Table { + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + unsafe { cpufreq::Table::from_raw(self.ptr) } + } + } + + impl Deref for FreqTable { + type Target = cpufreq::Table; + + #[inline] + fn deref(&self) -> &Self::Target { + self.table() + } + } + + impl Drop for FreqTable { + fn drop(&mut self) { + // SAFETY: The pointer was created via `dev_pm_opp_init_cpufreq_table`, and is only + // freed here. + unsafe { + bindings::dev_pm_opp_free_cpufreq_table(self.dev.as_raw(), &mut self.as_raw()) + }; + } + } +} + +#[cfg(CONFIG_CPU_FREQ)] +pub use freq::FreqTable; + use core::{marker::PhantomData, ptr}; use macros::vtable; @@ -751,6 +814,13 @@ pub fn adjust_voltage( }) } + /// Creates [`FreqTable`] from [`Table`]. + #[cfg(CONFIG_CPU_FREQ)] + #[inline] + pub fn cpufreq_table(&mut self) -> Result { + FreqTable::new(self) + } + /// Configures device with [`OPP`] matching the frequency value. #[inline] pub fn set_rate(&self, freq: Hertz) -> Result<()> {