From nobody Sat Feb 7 20:39:22 2026 Received: from mail-pg1-f172.google.com (mail-pg1-f172.google.com [209.85.215.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 74CB661FE1 for ; Wed, 3 Jul 2024 07:30:47 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991849; cv=none; b=DwhrbTjWjwfFfx547xPeSo61ws43GHqeLiBHTXe7lgcNhrzK4mih/5hC3rqyOVrvSWrCr+IOzxiN432HPdBKQCEdAMuPJTHSKJXuKSOgqHfnTT0XSTlPb9NaD/LCMaUMyyg/sEWr9zNbkQlPBVcs3PBxQquZtuSRIiUmdrLBACw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991849; c=relaxed/simple; bh=GK2g/4QhvhMTx4QYRZDVe7tqIhXsVJ2LLJpMAfTNCdw=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version:Content-Type; b=aSW+K0arVpxykO+U2GhkFGg5EMdAoO+5tf+zgl3ZZWQRY17BiMW+0M5KAktwvyIiw+ik5z/k7Ive/tcyuiFdZRrDu7X4j75UYKDU19qTEweaS5ptRp5Wsabm7BZct301+fk240TsoPpk7J+arzsckbmd1qxexJafVBTT08ZYMgs= 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=mOv0Rz9b; arc=none smtp.client-ip=209.85.215.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="mOv0Rz9b" Received: by mail-pg1-f172.google.com with SMTP id 41be03b00d2f7-725a7b0fc55so3093955a12.3 for ; Wed, 03 Jul 2024 00:30:47 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1719991847; x=1720596647; 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=LmIqXvmGNOMRdgx5QTBNAc1d2UsMur4Ln/Lj5x2EkKQ=; b=mOv0Rz9bS4fwcOXiFCtfO38Q/lfPlOXTTJUOeaggRJZ1RVhW5f3KnMwQig4Hybs7if 48/WUCrLhy5/9UGFrd8idvM9mhltEujw//Cv3I+fmE7jGsKIDG6JA3mKDsifjgfT33YE kq0wlLc57trDhrTCknxA8WUjUMJqV/lZIbcpdoFfhWgQnD5yW/YLyyyj8r2Xq2bKduLc g9idxUwbsmSPpJfnv1H036P9/ezbeVX8H07NG1YoWNTzh8iSX7bJ03vCwaBc7sSqyBkG /0+TYmzMDjXdScsqgypJXjVIv0GCTtGzy4pS6RaUQF8JNci56G72tnQ8SkxB2sA2QInT xfTQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719991847; x=1720596647; 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=LmIqXvmGNOMRdgx5QTBNAc1d2UsMur4Ln/Lj5x2EkKQ=; b=KgZsIwdg+kO9BJ2H0K4RhgovjemopS2jlT/qtNUQe9TzCPg8bSFyTC80KH9gZugFkj xFjwBSoNeZvh7mD5F0ehoWFvYRt5iY/7UjLulORSUWv3+Mc3trZbLAPT28vygm0O3tho slCbTMDSoiSmqnU6NmHjJf+SNfJfOZ7Xdd5ZV7lFgqxntMsnwlwxBZrIi2dzQ5m74zVy 92BdS9C+2Y6fukJEhm/jsTHapGCYBeEPDmMBdeCQLj4dKmb9U9u641MVcjuGvvrIgYUR fGljqHgT7HH7/jwiNHV1fKc7Zze6uP0SRF8voIAQAiDc9HRjf3LhJZRbYZIXvfsUw+Fb P1SA== X-Forwarded-Encrypted: i=1; AJvYcCUztIHIOJqJnfQYvWLIXV7vsPqydqgIb78S8AxA1TAikwsT/c6QLY+KOLuemabGhXTU1GtUu/JG/5p6Um9quqInb8eXNtRtsVID0BpC X-Gm-Message-State: AOJu0YwZXddYJyQC6He+XObN8K45CzraDor2AMZ8G7IFK/6uL9n5W7vD mCPNM7Ziq/HPGIEJSidA3nYbV07p8+ir/ascwkcaTSa+0KdyUtYGuuW5BcWshrk= X-Google-Smtp-Source: AGHT+IE+NygpQCuADLF9esQ+aGRiDiKaDEVs/1KtnrCfBn2nuONTakqGy5ihyncFzkVA+na251+Xrw== X-Received: by 2002:a05:6a20:3948:b0:1be:cdce:9fb7 with SMTP id adf61e73a8af0-1bef613f429mr11746387637.19.1719991846646; Wed, 03 Jul 2024 00:30:46 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1fac10d1fb1sm95810335ad.36.2024.07.03.00.30.45 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 03 Jul 2024 00:30:46 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V3 1/8] rust: Add initial bindings for OPP framework Date: Wed, 3 Jul 2024 12:44:26 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This commit adds initial Rust bindings for the Operating performance points (OPP) core. This adds bindings for `struct dev_pm_opp` and `struct dev_pm_opp_data` to begin with. Reviewed-by: Manos Pitsidianakis Signed-off-by: Viresh Kumar --- rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 2 + rust/kernel/opp.rs | 182 ++++++++++++++++++++++++++++++++ 3 files changed, 185 insertions(+) create mode 100644 rust/kernel/opp.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index d8b54b9fa4d0..1bf8e053c8f4 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 3bf1089b87a3..e309d7774cbd 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -45,6 +45,8 @@ #[cfg(CONFIG_NET)] pub mod net; pub mod of; +#[cfg(CONFIG_PM_OPP)] +pub mod opp; pub mod platform; pub mod prelude; pub mod print; diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs new file mode 100644 index 000000000000..b26e39a74635 --- /dev/null +++ b/rust/kernel/opp.rs @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Operating performance points. +//! +//! This module provides bindings for interacting with the OPP subsystem. +//! +//! C header: [`include/linux/pm_opp.h`](srctree/include/linux/pm_opp.h) + +use crate::{ + bindings, + device::Device, + error::{code::*, to_result, Result}, + types::{ARef, AlwaysRefCounted, Opaque}, +}; + +use core::ptr; + +/// Dynamically created Operating performance point (OPP). +pub struct Token { + dev: ARef, + freq: u64, +} + +impl Token { + /// Adds an OPP dynamically. + pub fn new(dev: &ARef, mut data: Data) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` 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 `Dev= ice` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_remove(self.dev.as_raw(), self.freq)= }; + } +} + +/// Equivalent to `struct dev_pm_opp_data` in the C Code. +#[repr(transparent)] +pub struct Data(bindings::dev_pm_opp_data); + +impl Data { + /// Creates new instance of [`Data`]. + pub fn new(freq: u64, u_volt: u64, level: u32, turbo: bool) -> Self { + Self(bindings::dev_pm_opp_data { + turbo, + freq, + u_volt, + level, + }) + } + + /// Adds an OPP dynamically. The OPP is freed once the [`Token`] gets = freed. + pub fn add_opp(self, dev: &ARef) -> Result { + Token::new(dev, self) + } + + fn freq(&self) -> u64 { + self.0.freq + } +} + +/// Operating performance point (OPP). +/// +/// # Invariants +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of= the ARef instance. In +/// particular, the ARef instance owns an increment on underlying object= =E2=80=99s reference count. +#[repr(transparent)] +pub struct OPP(Opaque); + +// SAFETY: `OPP` only holds a pointer to a C OPP, which is safe to be used= from any thread. +unsafe impl Send for OPP {} + +// SAFETY: `OPP` only holds a pointer to a C OPP, references to which are = safe to be used from any +// thread. +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 refc= ount 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 a reference to a [`OPP`] from a valid pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for t= he lifetime of the + /// returned [`OPP`] reference. + pub unsafe fn from_raw_opp_owned<'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() }) + } + + /// Creates a reference to a [`OPP`] from a valid pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for t= he lifetime of the + /// returned [`OPP`] reference. + pub unsafe fn from_raw_opp<'a>(ptr: *mut bindings::dev_pm_opp) -> Resu= lt<&'a Self> { + let opp =3D unsafe { Self::from_raw_opp_owned(ptr) }?; + + // Take an extra reference to the OPP since the caller didn't take= it. + opp.inc_ref(); + Ok(opp) + } + + #[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) -> u64 { + let index =3D index.unwrap_or(0); + + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_freq_indexed(self.as_raw(), inde= x) } + } + + /// Returns the voltage of an OPP. + pub fn voltage(&self) -> u64 { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_voltage(self.as_raw()) } + } + + /// Returns the level of an OPP. + pub fn level(&self) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_level(self.as_raw()) } + } + + /// Returns the power of an OPP. + pub fn power(&self) -> u64 { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_power(self.as_raw()) } + } + + /// Returns the required pstate of an OPP. + pub fn required_pstate(&self, index: u32) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_required_pstate(self.as_raw(), i= ndex) } + } + + /// Returns true if the OPP is turbo. + pub fn is_turbo(&self) -> bool { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_is_turbo(self.as_raw()) } + } +} + +impl Drop for OPP { + fn drop(&mut self) { + // SAFETY: The safety requirements guarantee that the refcount is = nonzero. + unsafe { bindings::dev_pm_opp_put(self.as_raw()) } + } +} --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 20:39:22 2026 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 2C92B139CE3 for ; Wed, 3 Jul 2024 07:30:50 +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=1719991853; cv=none; b=EWtlG42+MhCZeJZ0nIfplgug6IJjuGJ12k7XYKg6AGW9fUBUDyei8NmyXW338yWSFfWYQvur2WxCkzUnwvxmhbbtHUzw0Nl5uaXHY/Ui3hbAgAi3NCcEWLyH6eNRkuVo6AbokUy7Am6vcoFciJAPGZ5UDQGaZip2XHtPnPYgChI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991853; c=relaxed/simple; bh=Ry5ibUlGOjuRP6QvsldHpSuFq0kMZRtgp6jIb3SypxM=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version:Content-Type; b=jKe+Td4zxw9JjodzZ3+SA4+DFWyUi+6mJPElH62uIms/UG3iw1ld9hA4rkZhkZKMBvS0iVfyzXI00lrOgVvaT7J2Gnt3qqVYThCcq4jODBY/v00agYE32p0fv16Y+XlOk1RBGb3Ke/cv6rGsPoUWBg7hM+GjjvZPRwgqMuQiQFk= 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=xfKnOTO5; 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="xfKnOTO5" Received: by mail-pl1-f177.google.com with SMTP id d9443c01a7336-1f480624d10so37487205ad.1 for ; Wed, 03 Jul 2024 00:30:50 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1719991850; x=1720596650; 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=UHpIISlSVfTAjLcZ1fNW1LpaL0AQTAK7185sDuskwgc=; b=xfKnOTO5Q96/7bMDGYmgaDTueWCZhVVJro0UAKEyVAuV5/OWUQXmBohwz7+Qw3irwi kfXX5Q8ilbvFaa15EBKZIfZFUHgdLyaCo2+x9tF0zAAgSakCTYtxAgmi4udNdFNY0paH ss2pDq1mM3LsLDQe4G+BUz/gJTA5JipYLWh4lCqJK6y6ZhFS7QiL7lt37k11z5oSOjJg bBw7XyHamE49nxGmpaa+D/E7VuPRVSKG6SIFrUSNfZcPrK5N3IYX59Ub++M7fg1H52UE tGx+hBvmcq3lD1p2GqNsYmf+XXgXuwrnMZbKEX8yYu+EO//RlGmL+dm8QOfqNJNgEeBb MUsQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719991850; x=1720596650; 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=UHpIISlSVfTAjLcZ1fNW1LpaL0AQTAK7185sDuskwgc=; b=gc2oxGZ30kHZZ3ju/AFfnBWqY+kjn35QSTAOxccnnm1V8IKbr3nznlJqiFRjF4Zd6R TRTBGBilZkNfbM7jcY5ws9RAqlVLwo9IgV+i/iWuPIPD0nf7KP7epT1exqy9jsUjf9dO Qip+Yd6luTGshvAO5ms6PXvQr/feRkUV3cY/PFakiAEeO/NVJrF/8K3IoDqj3UNwoQLf TIEHRW39ADhtEsATLtVWZ6beCYrTTNymYGbdVmPDEyUI5bLBujCuJeEKfPukbdUAoJAi Uyo7AS07JAjhCZ5iYgrhahjh8YaIAGmpOW+BaGzy8/1XbKLGta8PeMat2dUzA7S4vBl1 UVpg== X-Forwarded-Encrypted: i=1; AJvYcCV9rn9EGj00+AuWG1AssyZB2uTmZ6OlZk0sI1M3Psu7RvU5WeB94xN8V9bSEs/r+be2lVmRUE/Bu1YaCzFzDbo05tn1LMnuu4DmjV3K X-Gm-Message-State: AOJu0YxX7cH0W4DSEN+S0GvNDPybspbGGAm2wOMk7VXP4SFGq8k4LlX9 gCELDgR9Vi7Lt9Ak0hLG3eWwI65qlF0KXmjDuQgkAefQIIuBWI4BXlEoX2C/Qik= X-Google-Smtp-Source: AGHT+IGgFDNGeL0cDxsT3fOJ+hMGBICA7Mlv8WciKFBlOfUyYdFL7iziAbowRvxDLSQdjALbjEhhYQ== X-Received: by 2002:a17:903:41cd:b0:1fa:fc69:7a81 with SMTP id d9443c01a7336-1fafc697b4fmr26521665ad.29.1719991850337; Wed, 03 Jul 2024 00:30:50 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1fac1537688sm96145705ad.141.2024.07.03.00.30.49 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 03 Jul 2024 00:30:49 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V3 2/8] rust: Extend OPP bindings for the OPP table Date: Wed, 3 Jul 2024 12:44:27 +0530 Message-Id: <1cc9665b614b7de2fbe9b5ab9689b43e5c99bae5.1719990273.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-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This extends OPP bindings with the bindings for the `struct opp_table`. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 382 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 381 insertions(+), 1 deletion(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index b26e39a74635..4b31f99acc67 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -8,8 +8,9 @@ =20 use crate::{ bindings, + cpumask::Cpumask, device::Device, - error::{code::*, to_result, Result}, + error::{code::*, from_err_ptr, to_result, Error, Result}, types::{ARef, AlwaysRefCounted, Opaque}, }; =20 @@ -67,6 +68,385 @@ fn freq(&self) -> u64 { } } =20 +/// OPP search types. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum SearchType { + /// Search for exact value. + Exact, + /// Search for highest value less than equal to value. + Floor, + /// Search for lowest value greater than equal to value. + Ceil, +} + +/// Operating performance point (OPP) table. +/// +/// # Invariants +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of= the ARef instance. In +/// particular, the ARef instance owns an increment on underlying object= =E2=80=99s reference count. +pub struct Table { + ptr: *mut bindings::opp_table, + dev: ARef, + em: bool, + of: bool, + cpumask: Option, +} + +// SAFETY: The fields of `Table` are safe to be used from any thread. +unsafe impl Send for Table {} + +// SAFETY: The fields of `Table` are safe to be referenced from any thread. +unsafe impl Sync for Table {} + +impl Table { + /// Creates a new OPP table instance from raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null. + unsafe fn from_raw_table(ptr: *mut bindings::opp_table, dev: &ARef) -> Self { + // SAFETY: By the safety requirements, ptr is valid and its refcou= nt will be incremented. + unsafe { bindings::dev_pm_opp_get_opp_table_ref(ptr) }; + + Self { + ptr, + dev: dev.clone(), + em: false, + of: false, + cpumask: None, + } + } + + /// Find OPP table from device. + pub fn from_dev(dev: &ARef) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. Refcount of the OPP table is incremented as well. + let ptr =3D from_err_ptr(unsafe { bindings::dev_pm_opp_get_opp_tab= le(dev.as_raw()) })?; + + Ok(Self { + ptr, + dev: dev.clone(), + em: false, + of: false, + cpumask: None, + }) + } + + /// Add device tree based OPP table for the device. + #[cfg(CONFIG_OF)] + pub fn from_of(dev: &ARef, index: i32) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. Refcount of the OPP table is incremented as well. + to_result(unsafe { bindings::dev_pm_opp_of_add_table_indexed(dev.a= s_raw(), index) })?; + + // Fetch the newly created table. + let mut table =3D Self::from_dev(dev)?; + table.of =3D true; + + Ok(table) + } + + // Remove device tree based OPP table for the device. + #[cfg(CONFIG_OF)] + fn remove_of(&self) { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. We took the reference from `from_of` earlier, it = is safe to drop the same + // now. + unsafe { bindings::dev_pm_opp_of_remove_table(self.dev.as_raw()) }; + } + + /// Add device tree based OPP table for CPU devices. + #[cfg(CONFIG_OF)] + pub fn from_of_cpumask(dev: &ARef, cpumask: &Cpumask) -> Resul= t { + // SAFETY: The cpumask is valid and the returned ptr will be owned= by the [`Table`] instance. + to_result(unsafe { bindings::dev_pm_opp_of_cpumask_add_table(cpuma= sk.as_ptr()) })?; + + // Fetch the newly created table. + let mut table =3D Self::from_dev(dev)?; + + let mut mask =3D Cpumask::new()?; + cpumask.copy(&mut mask); + table.cpumask =3D Some(mask); + + Ok(table) + } + + // Remove device tree based OPP table for CPU devices. + #[cfg(CONFIG_OF)] + fn remove_of_cpumask(&self, cpumask: Cpumask) { + // SAFETY: The cpumask is valid and we took the reference from `fr= om_of_cpumask` earlier, + // it is safe to drop the same now. + unsafe { bindings::dev_pm_opp_of_cpumask_remove_table(cpumask.as_p= tr()) }; + } + + /// Returns the number of OPPs in the table. + pub fn opp_count(&self) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + let ret =3D unsafe { bindings::dev_pm_opp_get_opp_count(self.dev.a= s_raw()) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ret as u32) + } + } + + /// Returns max clock latency of the OPPs in the table. + pub fn max_clock_latency(&self) -> u64 { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_clock_latency(self.dev.as_ra= w()) } + } + + /// Returns max volt latency of the OPPs in the table. + pub fn max_volt_latency(&self) -> u64 { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_volt_latency(self.dev.as_raw= ()) } + } + + /// Returns max transition latency of the OPPs in the table. + pub fn max_transition_latency(&self) -> u64 { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_transition_latency(self.dev.= as_raw()) } + } + + /// Returns the suspend OPP. + pub fn suspend_freq(&self) -> u64 { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_suspend_opp_freq(self.dev.as_raw= ()) } + } + + /// Synchronizes regulators used by the OPP table. + pub fn sync_regulators(&self) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_sync_regulators(self.dev.a= s_raw()) }) + } + + /// Gets sharing CPUs. + pub fn sharing_cpus(dev: &Device, cpumask: &mut Cpumask) -> Result<()>= { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_get_sharing_cpus(dev.as_raw(), cpumask.as= _mut_ptr()) + }) + } + + /// Sets sharing CPUs. + pub fn set_sharing_cpus(&mut self, cpumask: &Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_set_sharing_cpus(self.dev.as_raw(), cpuma= sk.as_ptr()) + })?; + + if let Some(mask) =3D self.cpumask.as_mut() { + // Update the cpumask as this will be used while removing the = table. + cpumask.copy(mask); + } + + Ok(()) + } + + /// Gets sharing CPUs from Device tree. + #[cfg(CONFIG_OF)] + pub fn of_sharing_cpus(dev: &Device, cpumask: &mut Cpumask) -> Result<= ()> { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_of_get_sharing_cpus(dev.as_raw(), cpumask= .as_mut_ptr()) + }) + } + + /// Updates the voltage value for an OPP. + pub fn adjust_voltage( + &self, + freq: u64, + u_volt: u64, + u_volt_min: u64, + u_volt_max: u64, + ) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_adjust_voltage( + self.dev.as_raw(), + freq, + u_volt, + u_volt_min, + u_volt_max, + ) + }) + } + + /// Sets a matching OPP based on frequency. + pub fn set_rate(&self, freq: u64) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_set_rate(self.dev.as_raw()= , freq) }) + } + + /// Sets exact OPP. + pub fn set_opp(&self, opp: &OPP) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_set_opp(self.dev.as_raw(),= opp.as_raw()) }) + } + + /// Finds OPP based on frequency. + pub fn opp_from_freq( + &self, + mut freq: u64, + available: Option, + index: Option, + stype: SearchType, + ) -> Result> { + let rdev =3D self.dev.as_raw(); + let index =3D index.unwrap_or(0); + + let ptr =3D from_err_ptr(match stype { + SearchType::Exact =3D> { + if let Some(available) =3D available { + // SAFETY: The requirements are satisfied by the exist= ence of `Device` and + // its safety requirements. The returned ptr will be o= wned by the new [`OPP`] + // instance. + unsafe { + bindings::dev_pm_opp_find_freq_exact_indexed(rdev,= freq, index, available) + } + } else { + return Err(EINVAL); + } + } + + // SAFETY: The requirements are satisfied by the existence of = `Device` and its + // safety requirements. The returned ptr will be owned by the = new [`OPP`] instance. + SearchType::Ceil =3D> unsafe { + bindings::dev_pm_opp_find_freq_ceil_indexed(rdev, &mut fre= q as *mut u64, index) + }, + + // SAFETY: The requirements are satisfied by the existence of = `Device` and its + // safety requirements. The returned ptr will be owned by the = new [`OPP`] instance. + SearchType::Floor =3D> unsafe { + bindings::dev_pm_opp_find_freq_floor_indexed(rdev, &mut fr= eq as *mut u64, index) + }, + })?; + + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + Ok(unsafe { OPP::from_raw_opp_owned(ptr)?.into() }) + } + + /// Finds OPP based on level. + pub fn opp_from_level(&self, mut level: u32, stype: SearchType) -> Res= ult> { + let rdev =3D self.dev.as_raw(); + + let ptr =3D from_err_ptr(match stype { + // SAFETY: The requirements are satisfied by the existence of = `Device` and its + // safety requirements. The returned ptr will be owned by the = new [`OPP`] instance. + SearchType::Exact =3D> unsafe { bindings::dev_pm_opp_find_leve= l_exact(rdev, level) }, + + // SAFETY: The requirements are satisfied by the existence of = `Device` and its + // safety requirements. The returned ptr will be owned by the = new [`OPP`] instance. + SearchType::Ceil =3D> unsafe { + bindings::dev_pm_opp_find_level_ceil(rdev, &mut level as *= mut u32) + }, + + // SAFETY: The requirements are satisfied by the existence of = `Device` and its + // safety requirements. The returned ptr will be owned by the = new [`OPP`] instance. + SearchType::Floor =3D> unsafe { + bindings::dev_pm_opp_find_level_floor(rdev, &mut level as = *mut u32) + }, + })?; + + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + Ok(unsafe { OPP::from_raw_opp_owned(ptr)?.into() }) + } + + /// Finds OPP based on bandwidth. + pub fn opp_from_bw(&self, mut bw: u32, index: i32, stype: SearchType) = -> Result> { + let rdev =3D self.dev.as_raw(); + + let ptr =3D from_err_ptr(match stype { + // The OPP core doesn't support this yet. + SearchType::Exact =3D> return Err(EINVAL), + + // SAFETY: The requirements are satisfied by the existence of = `Device` and its + // safety requirements. The returned ptr will be owned by the = new [`OPP`] instance. + SearchType::Ceil =3D> unsafe { + bindings::dev_pm_opp_find_bw_ceil(rdev, &mut bw as *mut u3= 2, index) + }, + + // SAFETY: The requirements are satisfied by the existence of = `Device` and its + // safety requirements. The returned ptr will be owned by the = new [`OPP`] instance. + SearchType::Floor =3D> unsafe { + bindings::dev_pm_opp_find_bw_floor(rdev, &mut bw as *mut u= 32, index) + }, + })?; + + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + Ok(unsafe { OPP::from_raw_opp_owned(ptr)?.into() }) + } + + /// Enable the OPP. + pub fn enable_opp(&self, freq: u64) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_enable(self.dev.as_raw(), = freq) }) + } + + /// Disable the OPP. + pub fn disable_opp(&self, freq: u64) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_disable(self.dev.as_raw(),= freq) }) + } + + /// Registers with Energy model. + #[cfg(CONFIG_OF)] + pub fn of_register_em(&mut self, cpumask: &mut Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_of_register_em(self.dev.as_raw(), cpumask= .as_mut_ptr()) + })?; + + self.em =3D true; + Ok(()) + } + + // Unregisters with Energy model. + #[cfg(CONFIG_OF)] + fn of_unregister_em(&self) { + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. We registered with the EM framework earlier, it i= s safe to unregister now. + unsafe { bindings::em_dev_unregister_perf_domain(self.dev.as_raw()= ) }; + } +} + +impl Drop for Table { + fn drop(&mut self) { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe + // to relinquish it now. + unsafe { bindings::dev_pm_opp_put_opp_table(self.ptr) }; + + #[cfg(CONFIG_OF)] + { + if self.em { + self.of_unregister_em(); + } + + if self.of { + self.remove_of(); + } else if let Some(cpumask) =3D self.cpumask.take() { + self.remove_of_cpumask(cpumask); + } + } + } +} + /// Operating performance point (OPP). /// /// # Invariants --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 20:39:22 2026 Received: from mail-pj1-f53.google.com (mail-pj1-f53.google.com [209.85.216.53]) (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 9166313A40B for ; Wed, 3 Jul 2024 07:30:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.53 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991856; cv=none; b=e5RZecoit8CaillOtiUrPgj10pdCIAv4DiSlIvaqQzQAl893iLrnGCbqUEMaVRDNOA7u/XWTbgjKtdKUu3gpmnUoiBoQSPSI66M0/rXzUkyWR40+21iTe9rdK1EZBU7Ras24D26OmgkB0K8IsUDk+1rgPa3vC9PmKi1yySSC3dE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991856; c=relaxed/simple; bh=8rKxfdhj2/cDz+NvbHcA+b60mFYU5yYmAW2A0FnPtFg=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=J04t+2Xob9E5DctOflRyND3BrWaIh9Vq0v6qu8Wn5GOjhhT0DWkCGLXP45ltmeaUY8njXqOK/0tRr8iiCgxM5aAfMYUAiLsi/pWZGXPNxoNjjRuMxnbrcw5ElXoCJbi3Ijh+L+2Z1KAYu/6c2hyyDb5pTdrrkLcLsF8+97YdoQ8= 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=PkFRXeya; arc=none smtp.client-ip=209.85.216.53 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="PkFRXeya" Received: by mail-pj1-f53.google.com with SMTP id 98e67ed59e1d1-2c8e422c40cso3031181a91.2 for ; Wed, 03 Jul 2024 00:30:54 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1719991854; x=1720596654; 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=7dnxB1ID3RzLihjx0TJWMC1pRyz4W9Zi6Ac1xEfORdw=; b=PkFRXeyaxmtputHHliJjqFOepVcyHcIOV6mvH0ZYdK/2LPDc6DtvXLR95vWDax1s3q seML9IGOP3d606tX8LJcW4ud7XAKUShepuESsgpoACJMTZbQynheMxoL25wAGKgGWOKt owDIkyQdR1/k/k/UHFtFJZpA1wej+f8JVnbIXYBvrp1ZlEdnKjPTXY8LsuPBe2LfHh9E E3qermC4CfBql6Nq++B/X4cbHrGVv030P7WjnbZkgj3E35If4vF8bsm6W294mof6Ca0I F3qMzWRqZTro3iA2C+1S1QHIkmRb4XFHRnGCnYnHO8tPbg4mN96cpCj006Oaf1O6Xyur rOmg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719991854; x=1720596654; 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=7dnxB1ID3RzLihjx0TJWMC1pRyz4W9Zi6Ac1xEfORdw=; b=vWfA6GrvN7lzeWNsOPXzBboSlsy6CHO5oc0SMTMUuWfmZHkawJYW6nu6Fw3TV5q3b0 mgBWVrzFuALbMsrQ43tr2y75dDVSQxtJh0x80bV7QOLLbaJddijhITKMBCm9XcFsyVRH fXG018U1kA5g76/w+gTWPenBsLV5JGoEmYEelakt2o4Ye1pqJ0PpdEkvJWCD/RFb15H3 9R005U1OjdJp3erhg86Yv5uI72GgXFHBhjetOOiA2IvYBqrUc054sRuNOwfhxYpHlFct KL6aRYzO6edNLOyZLCWge9m2UAP5m+GPFsUW8nC7McyrHkSSSv2n0X9KxloU+D9E0GSg t/9w== X-Forwarded-Encrypted: i=1; AJvYcCXCjHXJ8zNSZERLXCKsPodJInKEECkH/bCZ7wri1ubBCs6hmo9iX94odH/4PeMdYzJdSRbdOtxtbxsZRmGI7tKJaEWZy5wHRjZcmqZH X-Gm-Message-State: AOJu0YyorJugd34efIZ1PWBGlykT40BLmFSpCzfijgNx59CU0eSj0dSe 68qitiyqSaS+ov+pVDbi2StQvo+ZclwRC5l47nuqy/3EYfkFkDLL88MEh1IkSA0= X-Google-Smtp-Source: AGHT+IFIOsjyEUEF/RZPTCJR4PG07s8g9pOwwqICGOCwBxXrz1H55FWE1J7LN7fCleAqT7oQXyQ+eg== X-Received: by 2002:a17:90b:10b:b0:2c7:b164:3ce6 with SMTP id 98e67ed59e1d1-2c93d71f43amr6766963a91.28.1719991853845; Wed, 03 Jul 2024 00:30:53 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-2c91ce17a77sm10088469a91.6.2024.07.03.00.30.52 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 03 Jul 2024 00:30:53 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V3 3/8] rust: Extend OPP bindings for the configuration options Date: Wed, 3 Jul 2024 12:44:28 +0530 Message-Id: <6d2d8f98dbed555167b6134202ae2e6d121f7c78.1719990273.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-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This extends OPP bindings with the bindings for the OPP core configuration options. Reviewed-by: Manos Pitsidianakis Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 301 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 299 insertions(+), 2 deletions(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 4b31f99acc67..92c4ac6cb89c 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -10,11 +10,28 @@ bindings, cpumask::Cpumask, 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}, + prelude::*, + str::CString, types::{ARef, AlwaysRefCounted, Opaque}, }; =20 -use core::ptr; +use core::{ffi::c_char, marker::PhantomData, ptr}; + +use macros::vtable; + +// Creates a null-terminated slice of pointers to Cstrings. +fn to_c_str_array(names: &[CString]) -> Result> { + // Allocated a null-terminated vector of pointers. + let mut list =3D Vec::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) +} =20 /// Dynamically created Operating performance point (OPP). pub struct Token { @@ -79,6 +96,286 @@ pub enum SearchType { Ceil, } =20 +/// Implement this trait to provide OPP Configuration callbacks. +#[vtable] +pub trait ConfigOps { + /// Called by the OPP core to configure OPP clks. + fn config_clks(_dev: &Device, _table: &Table, _opp: &OPP, _scaling_dow= n: bool) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Called by the OPP core to configure OPP regulators. + fn config_regulators( + _dev: &Device, + _opp_old: &OPP, + _opp_new: &OPP, + _data: *mut *mut bindings::regulator, + _count: u32, + ) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } +} + +/// Config token returned by the C code. +pub struct ConfigToken(i32); + +impl Drop for ConfigToken { + fn drop(&mut self) { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe + // to relinquish it now. + unsafe { bindings::dev_pm_opp_clear_config(self.0) }; + } +} + +/// Equivalent to `struct dev_pm_opp_config` in the C Code. +#[derive(Default)] +pub struct Config { + clk_names: Option>, + prop_name: Option, + regulator_names: Option>, + genpd_names: Option>, + supported_hw: Option>, + required_devs: Option>>, + _data: PhantomData, +} + +impl Config { + /// Creates a new instance of [`Config`]. + pub fn new() -> Self { + Self { + clk_names: None, + prop_name: None, + regulator_names: None, + genpd_names: None, + supported_hw: None, + required_devs: None, + _data: PhantomData, + } + } + + /// Initializes clock names. + pub fn set_clk_names(mut self, names: Vec) -> Result { + // Already configured. + if self.clk_names.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.clk_names =3D Some(names); + Ok(self) + } + + /// Initializes property name. + pub fn set_prop_name(mut self, name: CString) -> Result { + // Already configured. + if self.prop_name.is_some() { + return Err(EBUSY); + } + + self.prop_name =3D Some(name); + Ok(self) + } + + /// Initializes regulator names. + pub fn set_regulator_names(mut self, names: Vec) -> Result { + // Already configured. + if self.regulator_names.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.regulator_names =3D Some(names); + + Ok(self) + } + + /// Initializes genpd names. + pub fn set_genpd_names(mut self, names: Vec) -> Result { + // Already configured. Only one of genpd or required devs can be c= onfigured. + if self.genpd_names.is_some() || self.required_devs.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.genpd_names =3D Some(names); + Ok(self) + } + + /// Initializes required devices. + pub fn set_required_devs(mut self, devs: Vec>) -> Result<= Self> { + // Already configured. Only one of genpd or required devs can be c= onfigured. + if self.genpd_names.is_some() || self.required_devs.is_some() { + return Err(EBUSY); + } + + if devs.is_empty() { + return Err(EINVAL); + } + + self.required_devs =3D Some(devs); + Ok(self) + } + + /// Initializes supported hardware. + pub fn set_supported_hw(mut self, hw: Vec) -> Result { + // Already configured. + if self.supported_hw.is_some() { + return Err(EBUSY); + } + + if hw.is_empty() { + return Err(EINVAL); + } + + self.supported_hw =3D Some(hw); + Ok(self) + } + + /// Sets the configuration with the OPP core. + pub fn set(self, dev: &Device) -> Result { + let (_clk_list, clk_names) =3D match &self.clk_names { + Some(x) =3D> { + let list =3D to_c_str_array(x)?; + let ptr =3D list.as_ptr(); + (Some(list), ptr) + } + None =3D> (None, ptr::null()), + }; + + let (_regulator_list, regulator_names) =3D match &self.regulator_n= ames { + Some(x) =3D> { + let list =3D to_c_str_array(x)?; + let ptr =3D list.as_ptr(); + (Some(list), ptr) + } + None =3D> (None, ptr::null()), + }; + + let (_genpd_list, genpd_names) =3D match &self.genpd_names { + Some(x) =3D> { + let list =3D to_c_str_array(x)?; + let ptr =3D list.as_ptr(); + (Some(list), ptr) + } + None =3D> (None, ptr::null()), + }; + + let prop_name =3D match &self.prop_name { + Some(x) =3D> x.as_char_ptr(), + None =3D> ptr::null(), + }; + + let (supported_hw, supported_hw_count) =3D match &self.supported_h= w { + Some(x) =3D> (x.as_ptr(), x.len() as u32), + None =3D> (ptr::null(), 0), + }; + + let (_required_devs_list, required_devs) =3D match &self.required_= devs { + Some(x) =3D> { + // Create a non-NULL-terminated vectorof pointers. + let mut list =3D Vec::with_capacity(x.len(), GFP_KERNEL)?; + + for dev in x.iter() { + list.push(dev.as_raw(), GFP_KERNEL)?; + } + + let ptr =3D list.as_mut_ptr(); + (Some(list), ptr) + } + None =3D> (None, ptr::null_mut()), + }; + + let mut config =3D 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 + }, + genpd_names, + supported_hw, + supported_hw_count, + + // Don't need to support virt_devs for now. + virt_devs: ptr::null_mut(), + required_devs, + }; + + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. The OPP core guarantees to not use fields of `con= fig`, after this call has + // returned and so we don't need to save a copy of them for future= use + let ret =3D 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 config_clks callback. + extern "C" fn config_clks( + dev: *mut bindings::device, + opp_table: *mut bindings::opp_table, + opp: *mut bindings::dev_pm_opp, + _data: *mut core::ffi::c_void, + scaling_down: bool, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: 'dev' is guaranteed by the C code to be valid. + let dev =3D unsafe { Device::from_raw(dev) }; + T::config_clks( + &dev, + // SAFETY: 'opp_table' is guaranteed by the C code to be v= alid. + &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 config_regulators callback. + 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: core::ffi::c_uint, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: 'dev' is guaranteed by the C code to be valid. + let dev =3D unsafe { Device::from_raw(dev) }; + T::config_regulators( + &dev, + // SAFETY: 'old_opp' is guaranteed by the C code to be val= id. + unsafe { OPP::from_raw_opp(old_opp)? }, + // SAFETY: 'new_opp' is guaranteed by the C code to be val= id. + unsafe { OPP::from_raw_opp(new_opp)? }, + regulators, + count, + ) + .map(|_| 0) + }) + } +} + /// Operating performance point (OPP) table. /// /// # Invariants --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 20:39:22 2026 Received: from mail-pg1-f171.google.com (mail-pg1-f171.google.com [209.85.215.171]) (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 B491F13B59C for ; Wed, 3 Jul 2024 07:30:58 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991861; cv=none; b=Nx2B6rc2u5IiVO6SaEy9o7DIeejIli9tW73LZwa+jm7Aefishxxw+tY2N1oL4kYwG6EgTuRdC0Icds/PsGUctVpQwvSPSMaRV4y9kS10A1f5G0+SBSDYbCdWplpdwJeNZrUfJdsR0+mZJBhazbBHiTWhjtcjNU9YlMmP9ErPS4g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991861; c=relaxed/simple; bh=sEPrVIxsQv+nPLQj+utb0LbIls8GsCFzDWZXPzsyT2A=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=AQA1ypvbPD3AtEAM8dfx0C0JT1M3/UKJ5d4+zXE5XguhDdO/UKXQtzjUlLTtKQnNOz37bGWlRMs6RHKw9NqGh7th/e4PAUIB/u7UXxclsgvOteu/2dW76XX3NHpGhtW3BaUevBGIiA/Zda4iEy2HYf7wY8TX/TEDbCYYKXGmroE= 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=o5FpYQjy; arc=none smtp.client-ip=209.85.215.171 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="o5FpYQjy" Received: by mail-pg1-f171.google.com with SMTP id 41be03b00d2f7-707040e3018so3656185a12.1 for ; Wed, 03 Jul 2024 00:30:58 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1719991858; x=1720596658; 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=d4EKiOxmWoqhLcIs2aUpate87V7NdPQkU4EW5fOiOk0=; b=o5FpYQjyTcgPPPsGImRnIqYqfUin07HRqCtcj71sit/3IILLxU06TiGSDN+E/e1Dua m/Yi1Bvli8HdgzOniu/ucL7tWX0mW2ux3uy5LZoWfDV4poFWlJWjI6bzOMe+IbPLAjEa nfUVUK0dSNLhB8Uexfuobw42yLTixbQ8ILtLaw+JJTRLLi232LKXMdYRaUvoWX8y6lrv Rz1qTInzlJWWZFbangKWKM9CUWbFJsmiQAFFxiIJUhFi43qe47vpBL6yAhDTCxO7fJ8K QYc/6Agk7/XZjrfbRY1w/7ZaSM8FXbCo/rJoeLywnXnAyvM0Ar3pMtWldsa42By9Utgk P3rg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719991858; x=1720596658; 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=d4EKiOxmWoqhLcIs2aUpate87V7NdPQkU4EW5fOiOk0=; b=hlPkZ21YY0KPTyi9r4h5g0IntDK9foWkrpaafErz2FV2DXtk5PNgx1s/H41XWzQnVk TuCZE0FhfqALd3tJ+TLIZjeBm/2KY23KMX+6H9EWIuBjSS1G72id7FucEqT2QwNFe9kA sOcpCWXsmiS4knA86tIi5FlJ7T9ac3KEDr+HDKYthm55pJjsQ7jEWqOZYCStwNerK0zh GfIc+e2ru2dMVCoDFFXRPfA1bVGOjqOHYi5QknaJ05dbtvWaxTX9TgYXgEQNpL8mgMOC KwJ59hWZjqUpMIWmsXPEGEg1pKvLOMlX/aKiGz1l6u0hitNBZXX8gec1Xb+RxuP77VaC 0kUA== X-Forwarded-Encrypted: i=1; AJvYcCUMQ6nntkxuM3+SpaC6bhEzXAwNFsWev4wU/VfzajGDsS13ImI2LcRH+4Sry+AXiJNWQGqbLoVtheQenfHiV1w1rjgePWfDOGNwNCZR X-Gm-Message-State: AOJu0YxfRTFkdJbslirJXAqxwpog5TcEjrJlZL1xb81ZTDjWlpwmNEVe pvcROOhNQB6h8JfXpV2sOzKsw8rwuBKQ1o8f/VqZOuV4DAdlvI5U5IQ9Ylz0bgI= X-Google-Smtp-Source: AGHT+IGvwlqxT0lkoaWXgznkLpgL2bByCTmCBI/4tNDAPoYtQy2Z5mFBhr+I+/kd20baDi4MxRe2qQ== X-Received: by 2002:a05:6a20:a988:b0:1bd:27fd:ff56 with SMTP id adf61e73a8af0-1bef6243146mr11337288637.58.1719991857881; Wed, 03 Jul 2024 00:30:57 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1fac10d153bsm95963355ad.40.2024.07.03.00.30.56 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 03 Jul 2024 00:30:57 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V3 4/8] rust: Add initial bindings for cpufreq framework Date: Wed, 3 Jul 2024 12:44:29 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This commit adds initial Rust bindings for the cpufreq core. This adds basic bindings for cpufreq flags, relations and cpufreq table. Reviewed-by: Manos Pitsidianakis Signed-off-by: Viresh Kumar --- rust/bindings/bindings_helper.h | 1 + rust/helpers.c | 15 ++ rust/kernel/cpufreq.rs | 254 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 4 files changed, 272 insertions(+) create mode 100644 rust/kernel/cpufreq.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 1bf8e053c8f4..bee2b6013690 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -7,6 +7,7 @@ */ =20 #include +#include #include #include #include diff --git a/rust/helpers.c b/rust/helpers.c index a1b52378867c..e1e37d57ef7d 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -349,6 +350,20 @@ bool rust_helper_zalloc_cpumask_var(cpumask_var_t *mas= k, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_zalloc_cpumask_var); =20 +#ifdef CONFIG_CPU_FREQ +unsigned int rust_helper_cpufreq_table_len(struct cpufreq_frequency_table = *freq_table) +{ + return cpufreq_table_len(freq_table); +} +EXPORT_SYMBOL_GPL(rust_helper_cpufreq_table_len); + +void rust_helper_cpufreq_register_em_with_opp(struct cpufreq_policy *polic= y) +{ + cpufreq_register_em_with_opp(policy); +} +EXPORT_SYMBOL_GPL(rust_helper_cpufreq_register_em_with_opp); +#endif + #ifndef CONFIG_OF_DYNAMIC struct device_node *rust_helper_of_node_get(struct device_node *node) { diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs new file mode 100644 index 000000000000..3f3ffd9abaa2 --- /dev/null +++ b/rust/kernel/cpufreq.rs @@ -0,0 +1,254 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU frequency scaling. +//! +//! This module provides bindings for interacting with the cpufreq subsyst= em. +//! +//! C header: [`include/linux/cpufreq.h`](srctree/include/linux/cpufreq.h) + +use crate::{ + bindings, + error::{code::*, to_result, Result}, + prelude::*, +}; + +use core::{ + pin::Pin, +}; + +/// Default transition latency value. +pub const ETERNAL_LATENCY: u32 =3D bindings::CPUFREQ_ETERNAL as u32; + +/// Container for cpufreq driver flags. +pub mod flags { + use crate::bindings; + + /// Set by drivers that need to update internal upper and lower bounda= ries along with the + /// target frequency and so the core and governors should also invoke = the driver if the target + /// frequency does not change, but the policy min or max may have chan= ged. + pub const NEED_UPDATE_LIMITS: u16 =3D bindings::CPUFREQ_NEED_UPDATE_LI= MITS as _; + + /// Set by drivers for platforms where loops_per_jiffy or other kernel= "constants" aren't + /// affected by frequency transitions. + pub const CONST_LOOPS: u16 =3D bindings::CPUFREQ_CONST_LOOPS as _; + + /// Set by drivers that want the core to automatically register the cp= ufreq driver as a thermal + /// cooling device. + pub const IS_COOLING_DEV: u16 =3D bindings::CPUFREQ_IS_COOLING_DEV as = _; + + /// Set by drivers for platforms that have multiple clock-domains, i.e= . supporting multiple + /// policies. With this sysfs directories of governor would be created= in cpu/cpuN/cpufreq/ + /// directory and so they can use the same governor with different tun= ables for different + /// clusters. + pub const HAVE_GOVERNOR_PER_POLICY: u16 =3D bindings::CPUFREQ_HAVE_GOV= ERNOR_PER_POLICY as _; + + /// Set by drivers which do POSTCHANGE notifications from outside of t= heir ->target() routine. + pub const ASYNC_NOTIFICATION: u16 =3D bindings::CPUFREQ_ASYNC_NOTIFICA= TION as _; + + /// Set by drivers that want cpufreq core to check if CPU is running a= t a frequency present in + /// freq-table exposed by the driver. For these drivers if CPU is foun= d running at an out of + /// table freq, the cpufreq core will try to change the frequency to a= value from the table. + /// And if that fails, it will stop further boot process by issuing a = BUG_ON(). + pub const NEED_INITIAL_FREQ_CHECK: u16 =3D bindings::CPUFREQ_NEED_INIT= IAL_FREQ_CHECK as _; + + /// Set by drivers to disallow use of governors with "dynamic_switchin= g" flag set. + pub const NO_AUTO_DYNAMIC_SWITCHING: u16 =3D bindings::CPUFREQ_NO_AUTO= _DYNAMIC_SWITCHING as _; +} + +/// CPU frequency selection relations. Each value contains a `bool` argume= nt which corresponds to +/// the Relation being efficient. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Relation { + /// Select the lowest frequency at or above target. + Low(bool), + /// Select the highest frequency below or at target. + High(bool), + /// Select the closest frequency to the target. + Close(bool), +} + +impl Relation { + // Converts from a value compatible with the C code. + fn new(val: u32) -> Result { + let efficient =3D val & bindings::CPUFREQ_RELATION_E !=3D 0; + + Ok(match val & !bindings::CPUFREQ_RELATION_E { + bindings::CPUFREQ_RELATION_L =3D> Self::Low(efficient), + bindings::CPUFREQ_RELATION_H =3D> Self::High(efficient), + bindings::CPUFREQ_RELATION_C =3D> Self::Close(efficient), + _ =3D> return Err(EINVAL), + }) + } + + /// Converts to a value compatible with the C code. + pub fn val(&self) -> u32 { + let (mut val, e) =3D match self { + Self::Low(e) =3D> (bindings::CPUFREQ_RELATION_L, e), + Self::High(e) =3D> (bindings::CPUFREQ_RELATION_H, e), + Self::Close(e) =3D> (bindings::CPUFREQ_RELATION_C, e), + }; + + if *e { + val |=3D bindings::CPUFREQ_RELATION_E; + } + + val + } +} + +/// Equivalent to `struct cpufreq_policy_data` in the C code. +#[repr(transparent)] +pub struct PolicyData(*mut bindings::cpufreq_policy_data); + +impl PolicyData { + /// Creates new instance of [`PolicyData`]. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null. + pub unsafe fn from_raw_policy_data(ptr: *mut bindings::cpufreq_policy_= data) -> Self { + Self(ptr) + } + + /// Returns the raw pointer to the C structure. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_policy_data { + self.0 + } + + /// Provides a wrapper to the generic verify routine. + pub fn generic_verify(&self) -> Result<()> { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it now. + to_result(unsafe { bindings::cpufreq_generic_frequency_table_verif= y(self.as_raw()) }) + } +} + +/// Builder for the `struct cpufreq_frequency_table` in the C code. +#[repr(transparent)] +#[derive(Default)] +pub struct TableBuilder { + entries: Vec, +} + +impl TableBuilder { + /// Creates new instance of [`TableBuilder`]. + pub fn new() -> Self { + Self { + entries: Vec::new(), + } + } + + /// Adds a new entry to the table. + pub fn add(&mut self, frequency: u32, flags: u32, driver_data: u32) ->= Result<()> { + // Adds new entry to the end of the vector. + Ok(self.entries.push( + bindings::cpufreq_frequency_table { + flags, + driver_data, + frequency, + }, + GFP_KERNEL, + )?) + } + + /// Creates [`Table`] from [`TableBuilder`]. + pub fn into_table(mut self) -> Result { + // Add last entry to the table. + self.add(bindings::CPUFREQ_TABLE_END as u32, 0, 0)?; + Table::from_builder(self.entries) + } +} + +/// A simple implementation of the cpufreq table, equivalent to the `struct +/// cpufreq_frequency_table` in the C code. +pub struct Table { + #[allow(dead_code)] + // Dynamically created table. + entries: Option>>, + + // Pointer to the statically or dynamically created table. + ptr: *mut bindings::cpufreq_frequency_table, + + // Number of entries in the table. + len: usize, +} + +impl Table { + /// Creates new instance of [`Table`] from [`TableBuilder`]. + fn from_builder(entries: Vec) -> Re= sult { + let len =3D entries.len(); + if len =3D=3D 0 { + return Err(EINVAL); + } + + // Pin the entries to memory, since we are passing its pointer to = the C code. + let mut entries =3D Pin::new(entries); + + // The pointer is valid until the table gets dropped. + let ptr =3D entries.as_mut_ptr(); + + Ok(Self { + entries: Some(entries), + ptr, + // The last entry in table is reserved for `CPUFREQ_TABLE_END`. + len: len - 1, + }) + } + + /// Creates new instance of [`Table`] from raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null for the lifet= ime of the [`Table`]. + pub unsafe fn from_raw(ptr: *mut bindings::cpufreq_frequency_table) ->= Self { + Self { + entries: None, + ptr, + // SAFETY: The pointer is guaranteed to be valid for the lifet= ime of `Self`. + len: unsafe { bindings::cpufreq_table_len(ptr) } as usize, + } + } + + // Validate the index. + fn validate(&self, index: usize) -> Result<()> { + if index >=3D self.len { + Err(EINVAL) + } else { + Ok(()) + } + } + + /// Returns raw pointer to the `struct cpufreq_frequency_table` compat= ible with the C code. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_frequency_table { + self.ptr + } + + /// Returns `frequency` at index in the [`Table`]. + pub fn freq(&self, index: usize) -> Result { + self.validate(index)?; + + // SAFETY: The pointer is guaranteed to be valid for the lifetime = of `self` and `index` is + // also validated before this and is guaranteed to be within limit= s of the frequency table. + Ok(unsafe { (*self.ptr.add(index)).frequency }) + } + + /// Returns `flags` at index in the [`Table`]. + pub fn flags(&self, index: usize) -> Result { + self.validate(index)?; + + // SAFETY: The pointer is guaranteed to be valid for the lifetime = of `self` and `index` is + // also validated before this and is guaranteed to be within limit= s of the frequency table. + Ok(unsafe { (*self.ptr.add(index)).flags }) + } + + /// Returns `data` at index in the [`Table`]. + pub fn data(&self, index: usize) -> Result { + self.validate(index)?; + + // SAFETY: The pointer is guaranteed to be valid for the lifetime = of `self` and `index` is + // also validated before this and is guaranteed to be within limit= s of the frequency table. + Ok(unsafe { (*self.ptr.add(index)).driver_data }) + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index e309d7774cbd..77348fc33803 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -30,6 +30,8 @@ pub mod alloc; mod build_assert; pub mod clk; +#[cfg(CONFIG_CPU_FREQ)] +pub mod cpufreq; pub mod cpumask; pub mod device; pub mod device_id; --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 20:39:22 2026 Received: from mail-pf1-f178.google.com (mail-pf1-f178.google.com [209.85.210.178]) (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 550D213BC1E for ; Wed, 3 Jul 2024 07:31:02 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.178 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991864; cv=none; b=QxGosaFZ66MmXMga4UL8ySNq6v7EaC3YnHYKCXSKh4S52ZZf3qyn/AIcN24mRbJA8SrjryZPghA4wElunn1nF7WtGQlSIdMxG9AkU3lV17uXce34bIn481qNucK1NQho+u6GT3LQXWrFdaQ1B3yrKItwsdDxQIP+Aa0uxzMJr1Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991864; c=relaxed/simple; bh=9j6qyBbBg4q3edkEKPtiVlsYISdwynVBnSqtRMX1olk=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=t0my0EbCXQG5tdM9++n/xanVghLyr4o42Jt644o1xTpcvKujctp3JVvszDwZrkH7UyFNjnVAU0VFdIeC45d8srcLc9Xp3Ylplt85POcgjtFQig9rVqRfP3qFGTf473raKbj/2vXxACMgntL0dtfVhmwzXfIfWHhHSH/EbENYF5s= 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=z8368owL; arc=none smtp.client-ip=209.85.210.178 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="z8368owL" Received: by mail-pf1-f178.google.com with SMTP id d2e1a72fcca58-70aec66c936so201213b3a.0 for ; Wed, 03 Jul 2024 00:31:02 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1719991862; x=1720596662; 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=9OsbF0HbJd2DBfMBpHyv3X2gZOLpqgGdaCkDAOW/FBw=; b=z8368owLZPMWL4ht5bFWEwLTjtcrr8I5Vvy4GOZ4KReXfYe+dNlhW/h4snsABVhIQn /eIIgJRSwgad00fO5vrAXfAr+v74Ty3fO+iOcwuVilGLCkMZmaPDy824McTRZasqt1gD OgLfPVZNxOL3YpmBfi3/931INNCHR4qngIn/LBvgHyAmd5+nJKy3huePbUtdGBnFlVix qEilHJpOB0UfiNRD4ZRbkzqYNejrASvBYXBK9G7aZSkZ0TKp1bsjzf0cv5UOsjt9K6hz sREjsqq9DQlTkDY7VzC+AnM03byKsum1CpnGRJyCjYcYip0PsBDqEY3jCEwGUwrYb00Q MREQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719991862; x=1720596662; 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=9OsbF0HbJd2DBfMBpHyv3X2gZOLpqgGdaCkDAOW/FBw=; b=Mebza55bDB2hzEgYDCsbFerp7OK5eYFmuZ2rF1cb5bgYuVtKhnPMIaENOBJ8HA6ey1 wS7asHX+N+MdFSsjPPKmCREah3T/fnJ9KqS3spMQw2X9TSoyG4tcLJBxbVkmOZTFAKlM iGXsGT0kGwFUW/yuHI+Q00Dzn3iOTEoDd8kOQaLocr6kMiu+iwarzLq2UNZAgC0Hcu0S UNRBTz7z5TaZlRTOfpzq94/aI/T7YJaEnDWo3T6o2MY+rQPq3Bz6jnQxRuMzI5t89DBJ 3r6jfajpGnc2nVg5GJv9UUsYmBss0y7wt30xNoQuQ7Qs3f53bH7V9nk5Zz8D8840GbAb luUQ== X-Forwarded-Encrypted: i=1; AJvYcCUebo++oju+ogkSQ8xE5AFbCudTMlVFGBw6NTtDyTPTgD2LOhyh/IC32m60n8MGUZY1FzoOvTOA9RQ8WU+cjk9nl6DuzyqIMW9NOX81 X-Gm-Message-State: AOJu0Yz7kbFm4aXEm90ZsCUB8UcwMb1CTQ4YnhaZn+tINiAGehz1eQ2P FB+zLpCXmKmRwnBVTlZ3LGjBp/tMnt2onyB0ULJ5y7pBcwV6gYouEvefabzV/bw= X-Google-Smtp-Source: AGHT+IFcvXpYnimq4bLKY1nGsUOONMSn0uH2w4uPRhv4O5vb8htXNiKHO9NmL2IlDWBCVmvstR0KHg== X-Received: by 2002:a05:6a00:1909:b0:704:31ae:4fe5 with SMTP id d2e1a72fcca58-70aaaf25245mr10383163b3a.25.1719991861412; Wed, 03 Jul 2024 00:31:01 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id 41be03b00d2f7-72c6afb8f6asm7636982a12.42.2024.07.03.00.31.00 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 03 Jul 2024 00:31:00 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V3 5/8] rust: Extend cpufreq bindings for policy and driver ops Date: Wed, 3 Jul 2024 12:44:30 +0530 Message-Id: <1edf90cbde4588c7d71cdbcdf853640cf64a71d3.1719990273.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-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This extends the cpufreq bindings with bindings for cpufreq policy and driver operations. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 315 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 313 insertions(+), 2 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 3f3ffd9abaa2..6f9d34ebbcb0 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -7,15 +7,20 @@ //! C header: [`include/linux/cpufreq.h`](srctree/include/linux/cpufreq.h) =20 use crate::{ - bindings, - error::{code::*, to_result, Result}, + bindings, clk, cpumask, + device::Device, + error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR= }, prelude::*, + types::{ARef, ForeignOwnable}, }; =20 use core::{ pin::Pin, + ptr::self, }; =20 +use macros::vtable; + /// Default transition latency value. pub const ETERNAL_LATENCY: u32 =3D bindings::CPUFREQ_ETERNAL as u32; =20 @@ -252,3 +257,309 @@ pub fn data(&self, index: usize) -> Result { Ok(unsafe { (*self.ptr.add(index)).driver_data }) } } + +/// Equivalent to `struct cpufreq_policy` in the C code. +pub struct Policy { + ptr: *mut bindings::cpufreq_policy, + put_cpu: bool, + cpumask: cpumask::Cpumask, +} + +impl Policy { + /// Creates a new instance of [`Policy`]. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null. + pub unsafe fn from_raw_policy(ptr: *mut bindings::cpufreq_policy) -> S= elf { + Self { + ptr, + put_cpu: false, + // SAFETY: The pointer is guaranteed to be valid for the lifet= ime of `Self`. The `cpus` + // pointer is guaranteed to be valid by the C code. + cpumask: unsafe { cpumask::Cpumask::from_raw((*ptr).cpus) }, + } + } + + fn from_cpu(cpu: u32) -> Result { + // SAFETY: It is safe to call `cpufreq_cpu_get()` for any CPU. + let ptr =3D from_err_ptr(unsafe { bindings::cpufreq_cpu_get(cpu) }= )?; + + // SAFETY: The pointer is guaranteed to be valid by the C code. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + policy.put_cpu =3D true; + Ok(policy) + } + + /// Raw pointer to the underlying cpufreq policy. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_policy { + self.ptr + } + + fn as_ref(&self) -> &bindings::cpufreq_policy { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence to the pointer. + unsafe { &(*self.ptr) } + } + fn as_mut_ref(&mut self) -> &mut bindings::cpufreq_policy { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence to the pointer. + unsafe { &mut (*self.ptr) } + } + + /// Returns the primary CPU for a cpufreq policy. + pub fn cpu(&self) -> u32 { + self.as_ref().cpu + } + + /// Returns the minimum frequency for a cpufreq policy. + pub fn min(&self) -> u32 { + self.as_ref().min + } + + /// Returns the maximum frequency for a cpufreq policy. + pub fn max(&self) -> u32 { + self.as_ref().max + } + + /// Returns the current frequency for a cpufreq policy. + pub fn cur(&self) -> u32 { + self.as_ref().cur + } + + /// Sets the suspend frequency for a cpufreq policy. + pub fn set_suspend_freq(&mut self, freq: u32) -> &mut Self { + self.as_mut_ref().suspend_freq =3D freq; + self + } + + /// Returns the suspend frequency for a cpufreq policy. + pub fn suspend_freq(&self) -> u32 { + self.as_ref().suspend_freq + } + + /// Provides a wrapper to the generic suspend routine. + pub fn generic_suspend(&self) -> Result<()> { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it now. + to_result(unsafe { bindings::cpufreq_generic_suspend(self.as_raw()= ) }) + } + + /// Provides a wrapper to the generic get routine. + pub fn generic_get(&self) -> Result { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it now. + Ok(unsafe { bindings::cpufreq_generic_get(self.cpu()) }) + } + + /// Provides a wrapper to the register em with OPP routine. + pub fn register_em_opp(&self) { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it now. + unsafe { bindings::cpufreq_register_em_with_opp(self.as_raw()) }; + } + + /// Gets raw pointer to cpufreq policy's CPUs mask. + pub fn cpus(&mut self) -> &mut cpumask::Cpumask { + &mut self.cpumask + } + + /// Sets clock for a cpufreq policy. + pub fn set_clk(&mut self, dev: &Device, name: Option<&CStr>) -> Result= { + let clk =3D clk::Clk::new(dev, name)?; + self.as_mut_ref().clk =3D clk.as_raw(); + Ok(clk) + } + + /// Allows frequency switching code to run on any CPU. + pub fn set_dvfs_possible_from_any_cpu(&mut self) -> &mut Self { + self.as_mut_ref().dvfs_possible_from_any_cpu =3D true; + self + } + + /// Sets transition latency for a cpufreq policy. + pub fn set_transition_latency(&mut self, latency: u32) -> &mut Self { + self.as_mut_ref().cpuinfo.transition_latency =3D latency; + self + } + + /// Returns the cpufreq table for a cpufreq policy. The cpufreq table = is recreated in a + /// light-weight manner from the raw pointer. The table in C code is n= ot freed once this table + /// is dropped. + pub fn freq_table(&self) -> Result
{ + if self.as_ref().freq_table.is_null() { + return Err(EINVAL); + } + + // SAFETY: The `freq_table` is guaranteed to be valid. + Ok(unsafe { Table::from_raw(self.as_ref().freq_table) }) + } + + /// Sets the cpufreq table for a cpufreq policy. + /// + /// The cpufreq driver must guarantee that the frequency table does no= t get freed while it is + /// still being used by the C code. + pub fn set_freq_table(&mut self, table: &Table) -> &mut Self { + self.as_mut_ref().freq_table =3D table.as_raw(); + self + } + + /// Returns the data for a cpufreq policy. + pub fn data(&mut self) -> Option<::Borrowed<'_>>= { + if self.as_ref().driver_data.is_null() { + None + } else { + // SAFETY: The data is earlier set by us from [`set_data()`]. + Some(unsafe { T::borrow(self.as_ref().driver_data) }) + } + } + + // Sets the data for a cpufreq policy. + fn set_data(&mut self, data: T) -> Result<()> { + if self.as_ref().driver_data.is_null() { + // Pass the ownership of the data to the foreign interface. + self.as_mut_ref().driver_data =3D ::into_= foreign(data) as _; + Ok(()) + } else { + Err(EBUSY) + } + } + + // Returns the data for a cpufreq policy. + fn clear_data(&mut self) -> Option { + if self.as_ref().driver_data.is_null() { + None + } else { + // 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. + let data =3D + Some(unsafe { ::from_foreign(self.as_= ref().driver_data) }); + self.as_mut_ref().driver_data =3D ptr::null_mut(); + data + } + } +} + +impl Drop for Policy { + fn drop(&mut self) { + if self.put_cpu { + // SAFETY: By the type invariants, we know that `self` owns a = reference, so it is safe to + // relinquish it now. + unsafe { bindings::cpufreq_cpu_put(self.as_raw()) }; + } + } +} + +/// Operations to be implemented by a cpufreq driver. +#[vtable] +pub trait Driver { + /// Driver specific data. + /// + /// Corresponds to the data retrieved via the kernel's + /// `cpufreq_get_driver_data()` function. + /// + /// Require that `Data` implements `ForeignOwnable`. We guarantee to + /// never move the underlying wrapped data structure. + type Data: ForeignOwnable; + + /// Policy specific data. + /// + /// Require that `PData` implements `ForeignOwnable`. We guarantee to + /// never move the underlying wrapped data structure. + type PData: ForeignOwnable; + + /// Policy's init callback. + fn init(policy: &mut Policy) -> Result; + + /// Policy's exit callback. + fn exit(_policy: &mut Policy, _data: Option) -> Result<()= > { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's online callback. + fn online(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's offline callback. + fn offline(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's suspend callback. + fn suspend(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's resume callback. + fn resume(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's ready callback. + fn ready(_policy: &mut Policy) { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's verify callback. + fn verify(data: &mut PolicyData) -> Result<()>; + + /// Policy's setpolicy callback. + fn setpolicy(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's target callback. + fn target(_policy: &mut Policy, _target_freq: u32, _relation: Relation= ) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's target_index callback. + fn target_index(_policy: &mut Policy, _index: u32) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's fast_switch callback. + fn fast_switch(_policy: &mut Policy, _target_freq: u32) -> u32 { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's adjust_perf callback. + fn adjust_perf(_policy: &mut Policy, _min_perf: u64, _target_perf: u64= , _capacity: u64) { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's get_intermediate callback. + fn get_intermediate(_policy: &mut Policy, _index: u32) -> u32 { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's target_intermediate callback. + fn target_intermediate(_policy: &mut Policy, _index: u32) -> Result<()= > { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's get callback. + fn get(_policy: &mut Policy) -> Result { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's update_limits callback. + fn update_limits(_policy: &mut Policy) { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's bios_limit callback. + fn bios_limit(_policy: &mut Policy, _limit: &mut u32) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's set_boost callback. + fn set_boost(_policy: &mut Policy, _state: i32) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's register_em callback. + fn register_em(_policy: &mut Policy) { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } +} --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 20:39:22 2026 Received: from mail-pg1-f180.google.com (mail-pg1-f180.google.com [209.85.215.180]) (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 459CC13D24E for ; Wed, 3 Jul 2024 07:31:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.180 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991868; cv=none; b=ZjBWkwJ5/f2ZwJYL5UMV7PlPA5QvWVtKy20KgR4CmAkVgAAWd3BOjR1Pc2sj9YI8V3Wff1kFYhs7bFuLWc997ujUTHYr8rISeW7wV2468b2dA7RNJmxxn96jwV/E9F07fc0lEaIVG+uPGGqO48GZfH1w1hiI530yfRyOyGREmXo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991868; c=relaxed/simple; bh=8wlLeu6FPEBR+f6boNjajzd77+L+3m6rrk/nGWv/Ndg=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=DP2ECqmv16SF5G1SihHi2ckvxis0T6L/+mkYTcJ8BtuvMmbK46EJ7eCTAA2PeqCEaZ5nLl5JtCdjWx7uqhnI5es87cn6MOMjbSC4K/v7Qtl5uNvpbf89ILpI8JNNboDEVh9z3iNGux1mxEXGdShZsXTa81swYQFU9fjBlk/QJWU= 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=Gm5WCZJm; arc=none smtp.client-ip=209.85.215.180 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="Gm5WCZJm" Received: by mail-pg1-f180.google.com with SMTP id 41be03b00d2f7-656d8b346d2so3032186a12.2 for ; Wed, 03 Jul 2024 00:31:06 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1719991865; x=1720596665; 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=6J41cO3j0pbW38EUHEZCscL5LBP2nEdGZsajp2yJSaI=; b=Gm5WCZJmwXF7YEpocj2wIRYhH2DgXl2UOsl5ldaRlvweaP9DtAa7geEyiOc3gKkUE/ YesRn1+/vUiw3cNufVGRkxAxMRWFym8AgfiShYfIUoSYQCMOVI6RyG+yRDj4dhKt9BrR JrU+rysvwU7zOHumg6iLhbmnHrQ5s2mDSc9LOwFhm/qOAnRBZ4padPNAq01yuGMcQI+8 5sr/L2l5xR6/ClVp9hfnzbR20UPrrul8vymM3AHY6pfH9FZQBtHKlFeURRAsQHttJmcN D6kl6U4sBG02Xia0Fe8RGIPlxgaAfXq+wAtTuoRv+Iho6E6jbXyioMfl/Nk/BuTQKTfO Fv8g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719991865; x=1720596665; 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=6J41cO3j0pbW38EUHEZCscL5LBP2nEdGZsajp2yJSaI=; b=pFsHiJcsOIPRwvPM81uTf2p1wbMEPro+2+g4v/RLo+D6BybTNgv6CvmO5rk+q9QhH6 hb1hvmOcD9hTbS8WFCDdSFonBrK+NzAsRqDghZDjkFC7FC0IewjEDVO5pSERNZDQQaEB 4i0u0RrXYe918P7Pl8P3vN+2qoN1QQBn/NmztDR158AQ8Vr/wcD/YY4dWpqpB+QJPtR/ shkqzs5aNVXlnJ9s5DJyPHHF0r/q/NRRhqfstiG9rNZmEkrsEqB1trJSADuLAYQhrpCZ MuoHSw0+qn/mUmqDAuZp6/2CBpLCRwo1bRP6fXMCshVnJ1e+2aZ3vC6qzYQzYndjwFQA AquQ== X-Forwarded-Encrypted: i=1; AJvYcCWbpelC8VriU5Rj8mPCNIFfV7teMPkhp39FmovPP8A7kNzr04EKvX1q0v2oXWul4oMQyN1Su6sx3KFwF9YUxwgkIwS+yRX3YeeycQJq X-Gm-Message-State: AOJu0Ywcoiou1Yc4XIGV18ENai4mbqIctXkHTDUwGlF1OYyN0wkPt0tq lfG+O9ONg/9lslXeB4hrdBk5LdX2azj5wZDFw1lxLLMPtC3hOd/5hjvGQvY+vyo= X-Google-Smtp-Source: AGHT+IExSxxMPZAe6Fkohoqw7UoRrYcUz/MbgPnzADrNH7BveL8/ODLe07UhGmWIjaRz8S2+CdoniQ== X-Received: by 2002:a05:6a21:1807:b0:1bf:cbe:4760 with SMTP id adf61e73a8af0-1bf0cbe496cmr7790289637.40.1719991865393; Wed, 03 Jul 2024 00:31:05 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-70801e53b2csm9742039b3a.39.2024.07.03.00.31.04 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 03 Jul 2024 00:31:04 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V3 6/8] rust: Extend cpufreq bindings for driver registration Date: Wed, 3 Jul 2024 12:44:31 +0530 Message-Id: <0f8618610dde586284d8c9971b8bdf215eef0456.1719990273.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-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This extends the cpufreq bindings with bindings for registering a driver. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 482 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 479 insertions(+), 3 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 6f9d34ebbcb0..66dad18f4ab6 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -9,14 +9,16 @@ use crate::{ bindings, clk, cpumask, device::Device, - error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR= }, + error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_= DEFAULT_ERROR}, prelude::*, - types::{ARef, ForeignOwnable}, + types::ForeignOwnable, }; =20 use core::{ + cell::UnsafeCell, + marker::PhantomData, pin::Pin, - ptr::self, + ptr::{self, addr_of_mut}, }; =20 use macros::vtable; @@ -563,3 +565,477 @@ fn register_em(_policy: &mut Policy) { kernel::build_error(VTABLE_DEFAULT_ERROR) } } + +/// Registration of a cpufreq driver. +pub struct Registration { + registered: bool, + drv: UnsafeCell, + _p: PhantomData, +} + +// SAFETY: `Registration` doesn't offer any methods or access to fields wh= en shared between threads +// or CPUs, so it is safe to share it. +unsafe impl Sync for Registration {} + +// SAFETY: Registration with and unregistration from the cpufreq subsystem= can happen from any thread. +// Additionally, `T::Data` (which is dropped during unregistration) is `Se= nd`, so it is okay to move +// `Registration` to different threads. +#[allow(clippy::non_send_fields_in_send_ty)] +unsafe impl Send for Registration {} + +impl Registration { + /// Creates new [`Registration`] but does not register it yet. + /// + /// It is allowed to move. + fn new() -> Result> { + Ok(Box::new( + Self { + registered: false, + drv: UnsafeCell::new(bindings::cpufreq_driver::default()), + _p: PhantomData, + }, + GFP_KERNEL, + )?) + } + + /// Registers a cpufreq driver with the rest of the kernel. + pub fn register( + name: &'static CStr, + data: T::Data, + flags: u16, + boost: bool, + ) -> Result> { + let mut reg =3D Self::new()?; + let drv =3D reg.drv.get_mut(); + + // Account for the trailing null character. + let len =3D name.len() + 1; + if len > drv.name.len() { + return Err(EINVAL); + }; + + // SAFETY: `name` is a valid Cstr, and we are copying it to an arr= ay of equal or larger + // size. + let name =3D unsafe { &*(name.as_bytes_with_nul() as *const [u8] a= s *const [i8]) }; + drv.name[..len].copy_from_slice(name); + + drv.boost_enabled =3D boost; + drv.flags =3D flags; + + // Allocate an array of 3 pointers to be passed to the C code. + let mut attr =3D Box::new([ptr::null_mut(); 3], GFP_KERNEL)?; + let mut next =3D 0; + + // SAFETY: The C code returns a valid pointer here, which is again= passed to the C code in + // an array. + attr[next] =3D + unsafe { addr_of_mut!(bindings::cpufreq_freq_attr_scaling_avai= lable_freqs) as *mut _ }; + next +=3D 1; + + if boost { + // SAFETY: The C code returns a valid pointer here, which is a= gain passed to the C code + // in an array. + attr[next] =3D + unsafe { addr_of_mut!(bindings::cpufreq_freq_attr_scaling_= boost_freqs) as *mut _ }; + next +=3D 1; + } + attr[next] =3D ptr::null_mut(); + + // Pass the ownership of the memory block to the C code. This will= be freed when + // the [`Registration`] object goes out of scope. + drv.attr =3D Box::leak(attr) as *mut _; + + // Initialize mandatory callbacks. + drv.init =3D Some(Self::init_callback); + drv.verify =3D Some(Self::verify_callback); + + // Initialize optional callbacks. + drv.setpolicy =3D if T::HAS_SETPOLICY { + Some(Self::setpolicy_callback) + } else { + None + }; + drv.target =3D if T::HAS_TARGET { + Some(Self::target_callback) + } else { + None + }; + drv.target_index =3D if T::HAS_TARGET_INDEX { + Some(Self::target_index_callback) + } else { + None + }; + drv.fast_switch =3D if T::HAS_FAST_SWITCH { + Some(Self::fast_switch_callback) + } else { + None + }; + drv.adjust_perf =3D if T::HAS_ADJUST_PERF { + Some(Self::adjust_perf_callback) + } else { + None + }; + drv.get_intermediate =3D if T::HAS_GET_INTERMEDIATE { + Some(Self::get_intermediate_callback) + } else { + None + }; + drv.target_intermediate =3D if T::HAS_TARGET_INTERMEDIATE { + Some(Self::target_intermediate_callback) + } else { + None + }; + drv.get =3D if T::HAS_GET { + Some(Self::get_callback) + } else { + None + }; + drv.update_limits =3D if T::HAS_UPDATE_LIMITS { + Some(Self::update_limits_callback) + } else { + None + }; + drv.bios_limit =3D if T::HAS_BIOS_LIMIT { + Some(Self::bios_limit_callback) + } else { + None + }; + drv.online =3D if T::HAS_ONLINE { + Some(Self::online_callback) + } else { + None + }; + drv.offline =3D if T::HAS_OFFLINE { + Some(Self::offline_callback) + } else { + None + }; + drv.exit =3D if T::HAS_EXIT { + Some(Self::exit_callback) + } else { + None + }; + drv.suspend =3D if T::HAS_SUSPEND { + Some(Self::suspend_callback) + } else { + None + }; + drv.resume =3D if T::HAS_RESUME { + Some(Self::resume_callback) + } else { + None + }; + drv.ready =3D if T::HAS_READY { + Some(Self::ready_callback) + } else { + None + }; + drv.set_boost =3D if T::HAS_SET_BOOST { + Some(Self::set_boost_callback) + } else { + None + }; + drv.register_em =3D if T::HAS_REGISTER_EM { + Some(Self::register_em_callback) + } else { + None + }; + + // Set driver data before registering the driver, as the cpufreq c= ore may call few + // callbacks before `cpufreq_register_driver()` returns. + reg.set_data(data)?; + + // SAFETY: It is safe to register the driver with the cpufreq core= in the C code. + to_result(unsafe { bindings::cpufreq_register_driver(reg.drv.get()= ) })?; + reg.registered =3D true; + Ok(reg) + } + + /// Returns the previous set data for a cpufreq driver. + pub fn data() -> Option<::Borrowed<'static>> { + // SAFETY: The driver data is earlier set by us from [`set_data()`= ]. + let data =3D unsafe { bindings::cpufreq_get_driver_data() }; + if data.is_null() { + None + } else { + // SAFETY: The driver data is earlier set by us from [`set_dat= a()`]. + Some(unsafe { D::borrow(data) }) + } + } + + // Sets the data for a cpufreq driver. + fn set_data(&mut self, data: T::Data) -> Result<()> { + let drv =3D self.drv.get_mut(); + + if drv.driver_data.is_null() { + // Pass the ownership of the data to the foreign interface. + drv.driver_data =3D ::into_foreign(= data) as _; + Ok(()) + } else { + Err(EBUSY) + } + } + + // Clears and returns the data for a cpufreq driver. + fn clear_data(&mut self) -> Option { + let drv =3D self.drv.get_mut(); + + if drv.driver_data.is_null() { + None + } else { + // SAFETY: By the type invariants, we know that `self` owns a = reference, so it is safe to + // relinquish it now. + let data =3D Some(unsafe { ::from_f= oreign(drv.driver_data) }); + drv.driver_data =3D ptr::null_mut(); + data + } + } +} + +// cpufreq driver callbacks. +impl Registration { + // Policy's init callback. + extern "C" fn init_callback(ptr: *mut bindings::cpufreq_policy) -> cor= e::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + + let data =3D T::init(&mut policy)?; + policy.set_data(data)?; + Ok(0) + }) + } + + // Policy's exit callback. + extern "C" fn exit_callback(ptr: *mut bindings::cpufreq_policy) -> cor= e::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + + let data =3D policy.clear_data(); + T::exit(&mut policy, data).map(|_| 0) + }) + } + + // Policy's online callback. + extern "C" fn online_callback(ptr: *mut bindings::cpufreq_policy) -> c= ore::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::online(&mut policy).map(|_| 0) + }) + } + + // Policy's offline callback. + extern "C" fn offline_callback(ptr: *mut bindings::cpufreq_policy) -> = core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::offline(&mut policy).map(|_| 0) + }) + } + + // Policy's suspend callback. + extern "C" fn suspend_callback(ptr: *mut bindings::cpufreq_policy) -> = core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::suspend(&mut policy).map(|_| 0) + }) + } + + // Policy's resume callback. + extern "C" fn resume_callback(ptr: *mut bindings::cpufreq_policy) -> c= ore::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::resume(&mut policy).map(|_| 0) + }) + } + + // Policy's ready callback. + extern "C" fn ready_callback(ptr: *mut bindings::cpufreq_policy) { + // SAFETY: `ptr` is valid by the contract with the C code. `policy= ` is alive only for the + // duration of this call, so it is guaranteed to remain alive for = the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::ready(&mut policy); + } + + // Policy's verify callback. + extern "C" fn verify_callback(ptr: *mut bindings::cpufreq_policy_data)= -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut data =3D unsafe { PolicyData::from_raw_policy_data(ptr= ) }; + T::verify(&mut data).map(|_| 0) + }) + } + + // Policy's setpolicy callback. + extern "C" fn setpolicy_callback(ptr: *mut bindings::cpufreq_policy) -= > core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::setpolicy(&mut policy).map(|_| 0) + }) + } + + // Policy's target callback. + extern "C" fn target_callback( + ptr: *mut bindings::cpufreq_policy, + target_freq: u32, + relation: u32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::target(&mut policy, target_freq, Relation::new(relation)?).= map(|_| 0) + }) + } + + // Policy's target_index callback. + extern "C" fn target_index_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::target_index(&mut policy, index).map(|_| 0) + }) + } + + // Policy's fast_switch callback. + extern "C" fn fast_switch_callback( + ptr: *mut bindings::cpufreq_policy, + target_freq: u32, + ) -> core::ffi::c_uint { + // SAFETY: `ptr` is valid by the contract with the C code. `policy= ` is alive only for the + // duration of this call, so it is guaranteed to remain alive for = the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::fast_switch(&mut policy, target_freq) + } + + // Policy's adjust_perf callback. + extern "C" fn adjust_perf_callback(cpu: u32, min_perf: u64, target_per= f: u64, capacity: u64) { + if let Ok(mut policy) =3D Policy::from_cpu(cpu) { + T::adjust_perf(&mut policy, min_perf, target_perf, capacity); + } + } + + // Policy's get_intermediate callback. + extern "C" fn get_intermediate_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> core::ffi::c_uint { + // SAFETY: `ptr` is valid by the contract with the C code. `policy= ` is alive only for the + // duration of this call, so it is guaranteed to remain alive for = the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::get_intermediate(&mut policy, index) + } + + // Policy's target_intermediate callback. + extern "C" fn target_intermediate_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::target_intermediate(&mut policy, index).map(|_| 0) + }) + } + + // Policy's get callback. + extern "C" fn get_callback(cpu: u32) -> core::ffi::c_uint { + // SAFETY: Get the policy for a CPU. + Policy::from_cpu(cpu).map_or(0, |mut policy| T::get(&mut policy).m= ap_or(0, |f| f)) + } + + // Policy's update_limit callback. + extern "C" fn update_limits_callback(cpu: u32) { + // SAFETY: Get the policy for a CPU. + if let Ok(mut policy) =3D Policy::from_cpu(cpu) { + T::update_limits(&mut policy); + } + } + + // Policy's bios_limit callback. + extern "C" fn bios_limit_callback(cpu: i32, limit: *mut u32) -> core::= ffi::c_int { + from_result(|| { + let mut policy =3D Policy::from_cpu(cpu as u32)?; + + // SAFETY: The pointer is guaranteed by the C code to be valid. + T::bios_limit(&mut policy, &mut (unsafe { *limit })).map(|_| 0) + }) + } + + // Policy's set_boost callback. + extern "C" fn set_boost_callback( + ptr: *mut bindings::cpufreq_policy, + state: i32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `po= licy` is alive only for the + // duration of this call, so it is guaranteed to remain alive = for the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::set_boost(&mut policy, state).map(|_| 0) + }) + } + + // Policy's register_em callback. + extern "C" fn register_em_callback(ptr: *mut bindings::cpufreq_policy)= { + // SAFETY: `ptr` is valid by the contract with the C code. `policy= ` is alive only for the + // duration of this call, so it is guaranteed to remain alive for = the lifetime of + // `ptr`. + let mut policy =3D unsafe { Policy::from_raw_policy(ptr) }; + T::register_em(&mut policy); + } +} + +impl Drop for Registration { + // Removes the registration from the kernel if it has completed succes= sfully before. + fn drop(&mut self) { + pr_info!("Registration dropped\n"); + let drv =3D self.drv.get_mut(); + + if self.registered { + // SAFETY: The driver was earlier registered from `register()`. + unsafe { bindings::cpufreq_unregister_driver(drv) }; + } + + // Free the previously leaked memory to the C code. + if !drv.attr.is_null() { + // SAFETY: The pointer was earlier initialized from the result= of `Box::leak`. + unsafe { drop(Box::from_raw(drv.attr)) }; + } + + // Free data + drop(self.clear_data()); + } +} --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 20:39:22 2026 Received: from mail-pj1-f49.google.com (mail-pj1-f49.google.com [209.85.216.49]) (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 3E90913D600 for ; Wed, 3 Jul 2024 07:31:09 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.49 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991871; cv=none; b=tI4V5rNSowV6vncSULFzkh50kRbuEMcjcOQNlFM5kAgxUZbIsI70nW38FvZ39L5A79rf1uHymW4Q01FazFPFuc7ewoGOyr++E7YTa6CSb9CxnJV9lgp7cj2+IHf83AuwlByd6htz8pBEIZkhunUhhMB8qE2X/hu8ys7cUlDtACY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991871; c=relaxed/simple; bh=ONhmdqsWZDFLFh6FZ0fs7s5ZNKCwSTqTca5vpftOr4Y=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=R6P9xk1V+g5lWySvHb7ybPUYT01jms8qn3I6EEFW+mUGPI6d6jbyTxrdHkalYHRcIwo05StpQhH5Y2ArozA79Ca6DV6I0bCQUq18VM/VW1Hee8f/VOg51P4XnIuPwO/Njwy/dwJ7J9oPMcx7mjoT/cBkT6EnOypXtJLSh/+3cZ8= 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=W4ZU1lDX; arc=none smtp.client-ip=209.85.216.49 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="W4ZU1lDX" Received: by mail-pj1-f49.google.com with SMTP id 98e67ed59e1d1-2c97ff39453so91168a91.0 for ; Wed, 03 Jul 2024 00:31:09 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1719991869; x=1720596669; 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=eGmDSlgxeRxM9Y7lSVn8pZpU6fzV4VP8wkEHpyGM1hk=; b=W4ZU1lDXSzZmSt5bWEcJBTm9pjPTJmcoberXVHYQWus63osTQh+1ACwR+iKRJm4wR9 vRz+Mns34CkXtbrGc7hOZLOOP1MlmNpmtrvOO4fI7i1sdryoP+gyOiqOx4ZokAZ1MYet PDMUF6vynMBrdUfmLwXDrhDxOQb9E5YikYuxUTwkBKl+rxbpyg+cf8X39opxzUbWUfQ7 6D8iiQVfIXhHrBeLYKk3OZ5t6fyxLao9IHYyIkBc+VsIwCSnnubJ5nhcN7KzqXz4hrQl yxKzFOMXECxQSF3dYPgP+yNUeBGByKsNI8Oa7p+XLq9zTjxU+PhVow2/D1eREkyKfQL5 CqmA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719991869; x=1720596669; 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=eGmDSlgxeRxM9Y7lSVn8pZpU6fzV4VP8wkEHpyGM1hk=; b=Q+xZMQoJAR0qkKlezb5ZUtYGephfctj46qDFffv8YpO/eP2H2Alq9BKDY9tT1S6W4G D+tZNXBwWDCSZklabJFnDLWUbzP834NgZ5YiMMz/S/GKq5Rpzbcjyx0S6wsGlsg44sWz CBScO787DAmQOcKK+9pQMFyQ+Z0S7CfGvjIKWKB+ktINgnDkVnfHtR4kxWZCSzoPqGmo yl3ZcMJLdx8wRYjgbYvHgEgThHQLr57+rOeSJFI14B2qe1llhM4D0OqaqJ0fVC93GQKr sgcf9Kzml8zx/398ozkIe4qv92+EXCrEH6lm3/UxIpUtJISNsOF3hq/a5lrizrGYg0DU zBkA== X-Forwarded-Encrypted: i=1; AJvYcCW7XzfvEKixcBP0ts2pjkdkLQkUNanny5FMVl/DPnIrn7WPlm6kudqb6Q4b/9Odbl5ooY88UtYTwyCYPUwPz5j/H3Tjh3UidFDGSLpj X-Gm-Message-State: AOJu0YymiA8sLHOsM5F8YsMYTAa3LE3/NHludoe+jjztmdrL/jnvoL+s klSo/XG7ct/hBxgx6W9GAYiTR3Co1oGPBUBZ3b2tD69pFDeMrxEeprc4NajYl0g= X-Google-Smtp-Source: AGHT+IENXtyKbNnA1xRpxIfAeNA//qOjOvY7fcGsntZd4ck71ZV+1hEVvl03kBc6zmacmCk2AFG8yw== X-Received: by 2002:a17:90b:a48:b0:2c8:bf72:5389 with SMTP id 98e67ed59e1d1-2c93d6f1508mr9665435a91.9.1719991868718; Wed, 03 Jul 2024 00:31:08 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-2c91d3e7d7bsm10045396a91.47.2024.07.03.00.31.07 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 03 Jul 2024 00:31:08 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V3 7/8] rust: Extend OPP bindings with CPU frequency table Date: Wed, 3 Jul 2024 12:44:32 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This commit adds bindings for CPUFreq core related API. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 61 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 92c4ac6cb89c..bc16b8c407fb 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -16,7 +16,10 @@ types::{ARef, AlwaysRefCounted, Opaque}, }; =20 -use core::{ffi::c_char, marker::PhantomData, ptr}; +#[cfg(CONFIG_CPU_FREQ)] +use crate::cpufreq; + +use core::{ffi::c_char, marker::PhantomData, ops::Deref, ptr}; =20 use macros::vtable; =20 @@ -376,6 +379,56 @@ extern "C" fn config_regulators( } } =20 +/// CPU Frequency table created from OPP entries. +#[cfg(CONFIG_CPU_FREQ)] +pub struct FreqTable { + dev: ARef, + table: cpufreq::Table, +} + +#[cfg(CONFIG_CPU_FREQ)] +impl FreqTable { + /// Creates new instance of [`FreqTable`] from raw pointer. + fn new(table: &Table) -> Result { + let mut ptr: *mut bindings::cpufreq_frequency_table =3D ptr::null_= mut(); + + // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_init_cpufreq_table(table.dev.as_raw(), &m= ut ptr) + })?; + Ok(Self { + dev: table.dev.clone(), + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + table: unsafe { cpufreq::Table::from_raw(ptr) }, + }) + } + + /// Returns reference to the underlying [`cpufreq::Table`]. + pub fn table(&self) -> &cpufreq::Table { + &self.table + } +} + +#[cfg(CONFIG_CPU_FREQ)] +impl Deref for FreqTable { + type Target =3D cpufreq::Table; + + #[inline] + fn deref(&self) -> &Self::Target { + &self.table + } +} + +#[cfg(CONFIG_CPU_FREQ)] +impl Drop for FreqTable { + fn drop(&mut self) { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // relinquish it now. + unsafe { bindings::dev_pm_opp_free_cpufreq_table(self.dev.as_raw()= , &mut self.as_raw()) }; + } +} + /// Operating performance point (OPP) table. /// /// # Invariants @@ -580,6 +633,12 @@ pub fn adjust_voltage( }) } =20 + /// Create cpufreq table from OPP table. + #[cfg(CONFIG_CPU_FREQ)] + pub fn to_cpufreq_table(&mut self) -> Result { + FreqTable::new(self) + } + /// Sets a matching OPP based on frequency. pub fn set_rate(&self, freq: u64) -> Result<()> { // SAFETY: The requirements are satisfied by the existence of `Dev= ice` and its safety --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 20:39:22 2026 Received: from mail-oi1-f177.google.com (mail-oi1-f177.google.com [209.85.167.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 EB3161386B3 for ; Wed, 3 Jul 2024 07:31:13 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.177 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991875; cv=none; b=qttXItzCTofnQQdJl1AW+pO1wOPXoRLCxBIXn0I/t/cyAKSyH5nROGSEXfd38VCF+yFN93zYPqipZMDaala7otvedrl9EL4MrNk1MpblOxa0lXvjmdmKd48F/To2WN+cgjwU9xBdFemCu+Ot8mGN4r0TJ7Zr7QdPBS6P/rjq35g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1719991875; c=relaxed/simple; bh=m4XniaMihLd8qlHJenTfcjOxaFkup1FyvaUGHn+pk8M=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=h4+4Fq1TtsbRQiLH71MRhGgdEOOgX2qLPBLQknO5LLKf0+LS3z7je1F+KDsE71remOY2efrPjDj3trLyCByXulfzZjh3MWjLl7IICxb/JB5WiEMZoimq3L64MM3HN53xfaytSRB8UK5Babl2QxUO0d5rWIDU8XMp09b8I7X0nq0= 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=lO5ALY/o; arc=none smtp.client-ip=209.85.167.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="lO5ALY/o" Received: by mail-oi1-f177.google.com with SMTP id 5614622812f47-3d55c0fadd2so3180614b6e.3 for ; Wed, 03 Jul 2024 00:31:13 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1719991873; x=1720596673; 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=L48fOb2APX+YOqtqYC3BeSMU2cmish3fGmpJ70CUgSU=; b=lO5ALY/o/O58aoq6Yis5PfejMuhhSpC4/e7F23Q3GjJJv+W/Teh6OmEc8TTTuSKYxo hDQ6D+mh+zKdAOgZayPFohIYojcTxgL2cNacpDa/qnf7Xdp0lQVZ/NfC64MlZgA6z1S9 ht7eqgn6Z4QPf6gNBRsiW0asK0/iockIvVYDNez+CtoJOBojnO0Caiuvdte+wzVplwXw NPnmz6smws9VGPVu/UAwDvUz8pGVx+hIi0UYjVXKT/oUdIFaVo8LjaUvdsMCSysjk7jo cV6xLRDmV29Yw7ubtxFsMMG38HNHyuqMie93orh4X4rS9gc25jQXY/ktoquyPRBUp7jK dVCA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1719991873; x=1720596673; 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=L48fOb2APX+YOqtqYC3BeSMU2cmish3fGmpJ70CUgSU=; b=dl1O0r9yjlw5QFEguQqY3KZGaoDEeiTEcqduHhFZEuEHqINfewH66aotBw3WeFEU/1 mQscGTDO15ds3QZwf71pl2C4XsjtEBgoPGUejtZl1IDNzuQSIuzC3dMiDc8+RU1QiIOl 9zPLvcSEFbOjQzYUmjgOSFR//EPv5s/KGoNJM3n9GZ5Gdbfg5B9J+CY4Oyw/MYSMmpPW zJbzfmXdk99jEah3cXKKl3yrBhNMdLFk3bZb8ZoADHmFASSg6ZHIhJqpJOoVGeK+6Zbs 8Vlskv88dBU1bQW84S3nfLPR0NM+SW/cjoKWZg1XwUYfdrIpnovKzcK8b6+D8s9d4E0W XrQg== X-Forwarded-Encrypted: i=1; AJvYcCUNy+vu9uyk2J9Fm9UzjWhbu0VYkzgh5Ckc6IeBgsHwSNCDexI74Yypq2Decwl9ELbOte4Rlc9yMy0VxkGUvEUbvmk96hiA7PwtaStK X-Gm-Message-State: AOJu0YzibeSefWffSryq8W0wiSqX6Jwvda8IB4iaL9GocoKAwJbdCDGn eQ6M/wZ2NdSG0NMTeSKnaevC+CNFKN5Zn/uh4h6hl1Jw8GN4HRwc3TFqk4+QsWk= X-Google-Smtp-Source: AGHT+IFms6h8jZorNAQzSh3CJhe/oYnjzyhvKstmwlguqvNIql3wjHi+rQlxPQbcAx1zxn62PoX2LQ== X-Received: by 2002:a05:6808:1b2b:b0:3d2:2a62:3fdf with SMTP id 5614622812f47-3d6b4de2294mr12115665b6e.54.1719991872555; Wed, 03 Jul 2024 00:31:12 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-708043b708fsm10029525b3a.147.2024.07.03.00.31.11 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 03 Jul 2024 00:31:12 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V3 8/8] cpufreq: Add Rust based cpufreq-dt driver Date: Wed, 3 Jul 2024 12:44:33 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This commit adds a Rust based cpufreq-dt driver, which covers most of the functionality of the existing C based driver. Only a handful of things are left, like fetching platform data from cpufreq-dt-platdev.c. This is tested with the help of QEMU for now and switching of frequencies work as expected. Signed-off-by: Viresh Kumar --- drivers/cpufreq/Kconfig | 12 ++ drivers/cpufreq/Makefile | 1 + drivers/cpufreq/rcpufreq_dt.rs | 225 +++++++++++++++++++++++++++++++++ 3 files changed, 238 insertions(+) create mode 100644 drivers/cpufreq/rcpufreq_dt.rs diff --git a/drivers/cpufreq/Kconfig b/drivers/cpufreq/Kconfig index 94e55c40970a..eb9359bd3c5c 100644 --- a/drivers/cpufreq/Kconfig +++ b/drivers/cpufreq/Kconfig @@ -217,6 +217,18 @@ config CPUFREQ_DT =20 If in doubt, say N. =20 +config CPUFREQ_DT_RUST + tristate "Rust based Generic DT based cpufreq driver" + depends on HAVE_CLK && OF && RUST + select CPUFREQ_DT_PLATDEV + select PM_OPP + help + This adds a Rust based generic DT based cpufreq driver for frequency + management. It supports both uniprocessor (UP) and symmetric + multiprocessor (SMP) systems. + + If in doubt, say N. + config CPUFREQ_DT_PLATDEV tristate "Generic DT based cpufreq platdev driver" depends on OF diff --git a/drivers/cpufreq/Makefile b/drivers/cpufreq/Makefile index 8d141c71b016..4981d908b803 100644 --- a/drivers/cpufreq/Makefile +++ b/drivers/cpufreq/Makefile @@ -15,6 +15,7 @@ obj-$(CONFIG_CPU_FREQ_GOV_COMMON) +=3D cpufreq_governor.o obj-$(CONFIG_CPU_FREQ_GOV_ATTR_SET) +=3D cpufreq_governor_attr_set.o =20 obj-$(CONFIG_CPUFREQ_DT) +=3D cpufreq-dt.o +obj-$(CONFIG_CPUFREQ_DT_RUST) +=3D rcpufreq_dt.o obj-$(CONFIG_CPUFREQ_DT_PLATDEV) +=3D cpufreq-dt-platdev.o =20 # Traces diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs new file mode 100644 index 000000000000..652458e7a3b9 --- /dev/null +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust based implementation of the cpufreq-dt driver. + +use core::format_args; + +use kernel::{ + b_str, c_str, clk, cpufreq, cpumask::Cpumask, define_of_id_table, devi= ce::Device, + error::code::*, fmt, macros::vtable, module_platform_driver, of, opp, = platform, prelude::*, + str::CString, sync::Arc, +}; + +// Finds exact supply name from the OF node. +fn find_supply_name_exact(np: &of::DeviceNode, name: &str) -> Option { + let name_cstr =3D CString::try_from_fmt(fmt!("{}-supply", name)).ok()?; + + np.find_property(&name_cstr).ok()?; + CString::try_from_fmt(fmt!("{}", name)).ok() +} + +// Finds supply name for the CPU from DT. +fn find_supply_names(dev: &Device, cpu: u32) -> Option> { + let np =3D of::DeviceNode::from_dev(dev).ok()?; + + // Try "cpu0" for older DTs. + let name =3D match cpu { + 0 =3D> find_supply_name_exact(&np, "cpu0"), + _ =3D> None, + } + .or(find_supply_name_exact(&np, "cpu"))?; + + let mut list =3D Vec::with_capacity(1, GFP_KERNEL).ok()?; + list.push(name, GFP_KERNEL).ok()?; + + Some(list) +} + +// Represents the cpufreq dt device. +struct CPUFreqDTDevice { + opp_table: opp::Table, + freq_table: opp::FreqTable, + #[allow(dead_code)] + mask: Cpumask, + #[allow(dead_code)] + token: Option, + #[allow(dead_code)] + clk: clk::Clk, +} + +struct CPUFreqDTDriver; + +#[vtable] +impl opp::ConfigOps for CPUFreqDTDriver {} + +#[vtable] +impl cpufreq::Driver for CPUFreqDTDriver { + type Data =3D (); + type PData =3D Arc; + + fn init(policy: &mut cpufreq::Policy) -> Result { + let cpu =3D policy.cpu(); + let dev =3D Device::from_cpu(cpu)?; + let mut mask =3D Cpumask::new()?; + + mask.set(cpu); + + let token =3D match find_supply_names(&dev, cpu) { + Some(names) =3D> Some( + opp::Config::::new() + .set_regulator_names(names)? + .set(&dev)?, + ), + _ =3D> None, + }; + + // Get OPP-sharing information from "operating-points-v2" bindings. + let fallback =3D match opp::Table::of_sharing_cpus(&dev, &mut mask= ) { + Ok(_) =3D> false, + Err(e) =3D> { + if e !=3D ENOENT { + return Err(e); + } + + // "operating-points-v2" not supported. If the platform ha= sn't + // set sharing CPUs, fallback to all CPUs share the `Polic= y` + // for backward compatibility. + opp::Table::sharing_cpus(&dev, &mut mask).is_err() + } + }; + + // Initialize OPP tables for all policy cpus. + // + // For platforms not using "operating-points-v2" bindings, we do t= his + // before updating policy cpus. Otherwise, we will end up creating + // duplicate OPPs for the CPUs. + // + // OPPs might be populated at runtime, don't fail for error here u= nless + // it is -EPROBE_DEFER. + let mut opp_table =3D match opp::Table::from_of_cpumask(&dev, &mas= k) { + Ok(table) =3D> table, + Err(e) =3D> { + if e =3D=3D EPROBE_DEFER { + return Err(e); + } + + // The table is added dynamically ? + opp::Table::from_dev(&dev)? + } + }; + + // The OPP table must be initialized, statically or dynamically, b= y this point. + opp_table.opp_count()?; + + // Set sharing cpus for fallback scenario. + if fallback { + mask.set_all(); + opp_table.set_sharing_cpus(&mask)?; + } + + let mut transition_latency =3D opp_table.max_transition_latency() = as u32; + if transition_latency =3D=3D 0 { + transition_latency =3D cpufreq::ETERNAL_LATENCY; + } + + let freq_table =3D opp_table.to_cpufreq_table()?; + let clk =3D policy + .set_freq_table(freq_table.table()) + .set_dvfs_possible_from_any_cpu() + .set_suspend_freq((opp_table.suspend_freq() / 1000) as u32) + .set_transition_latency(transition_latency) + .set_clk(&dev, None)?; + + mask.copy(policy.cpus()); + + Ok(Arc::new( + CPUFreqDTDevice { + opp_table, + freq_table, + mask, + token, + clk, + }, + GFP_KERNEL, + )?) + } + + fn exit(_policy: &mut cpufreq::Policy, _data: Option) -> = Result<()> { + Ok(()) + } + + fn online(_policy: &mut cpufreq::Policy) -> Result<()> { + // We did light-weight tear down earlier, nothing to do here. + Ok(()) + } + + fn offline(_policy: &mut cpufreq::Policy) -> Result<()> { + // Preserve policy->data and don't free resources on light-weight + // tear down. + 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: u32) -> Result<()= > { + let data =3D match policy.data::() { + Some(data) =3D> data, + None =3D> return Err(ENOENT), + }; + + let freq =3D data.freq_table.freq(index.try_into().unwrap())? as u= 64; + data.opp_table.set_rate(freq * 1000) + } + + fn get(policy: &mut cpufreq::Policy) -> Result { + policy.generic_get() + } + + fn set_boost(_policy: &mut cpufreq::Policy, _state: i32) -> Result<()>= { + Ok(()) + } + + fn register_em(policy: &mut cpufreq::Policy) { + policy.register_em_opp() + } +} + +type DeviceData =3D Box>; + +impl platform::Driver for CPUFreqDTDriver { + type Data =3D Arc; + + define_of_id_table! {(), [ + (of::DeviceId(b_str!("operating-points-v2")), None), + ]} + + fn probe(_dev: &mut platform::Device, _id_info: Option<&Self::IdInfo>)= -> Result { + let drv =3D Arc::new( + cpufreq::Registration::::register( + c_str!("cpufreq-dt"), + (), + cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::= IS_COOLING_DEV, + true, + )?, + GFP_KERNEL, + )?; + + pr_info!("CPUFreq DT driver registered\n"); + + Ok(drv) + } +} + +module_platform_driver! { + type: CPUFreqDTDriver, + name: "cpufreq_dt", + author: "Viresh Kumar ", + description: "Generic CPUFreq DT driver", + license: "GPL v2", +} --=20 2.31.1.272.g89b43f80a514