From patchwork Fri Jun 7 09:12:16 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 802522 Received: from mail-pj1-f44.google.com (mail-pj1-f44.google.com [209.85.216.44]) (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 2285115B961 for ; Fri, 7 Jun 2024 09:12:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.44 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751562; cv=none; b=IsIVRlQXQWza/ecnuCI+4ViOt4V6Vx1DbuE8/s+gjwlc1FbNFJTPrm8feEF3Vlz4fuWHekombhAfjy+EpHZ92Gf08KOmid/sgERVNqaG0gjtq9PIo9scsw1pwVYfyiQSHeYUD8Gxy6kHhs8L3f/YMwT1BfSJ2oN5sJ+IA0E45xk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751562; c=relaxed/simple; bh=d/ZQBZeD9xk0ytQ718aCkWrWOqvnzxpaUv5bwXMwhBM=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version:Content-Type; b=I4MDilSQV4m1Fj8L0Yzx9KdtqULK3Nue7IUJgxZuA5Hpx1MPk0kwcuONRcl13NkP1BC+PuUv9/qtLiDssSL9zVU5u5qYEPNK1D/YfAO+spUqTdeGpUs0lGuX4OzTILhOIM7ibmfKzcCx4ZE/gULaH64zs7/dyUl4TnKllBAmik8= 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=ZaBX6CNc; arc=none smtp.client-ip=209.85.216.44 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="ZaBX6CNc" Received: by mail-pj1-f44.google.com with SMTP id 98e67ed59e1d1-2c2ccff8f0aso100790a91.0 for ; Fri, 07 Jun 2024 02:12:40 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1717751560; x=1718356360; 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=81AbJqMkmQOP0jsaSqrYKPdMCvuKMPB+xVHhmCmRbgI=; b=ZaBX6CNcBcY0KPhhdlN+l1/DiDGbDivJeAPrRCJUQTEu8AMTxcbOvKhbj5B4lbr/Y4 LjM/z8U44PN9waFxp/Wb0sBROpoNql9+/03DqWSAXqZr7fQAUKuMm3TB+shk8eaq2xTv aVaAHuHx1SuEmX2KqIQ5jOb82DHEbVNDYsL3F11SkfjcIrlvU3qNiigQaJDywE2nGzS0 EUQyYugYduli+QJt2O66zokDupPwCcs4wuO0IzS7y+I6IuQZeZ0rJ3qSA3VcXIMf8fGP P4SoI5/ShLbFKuFMiP8hmxnABGO1iXHnXBm1+zjZ9vxzbeOUS0vbgKDHqkk5W5hdlJM7 0qvg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717751560; x=1718356360; 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=81AbJqMkmQOP0jsaSqrYKPdMCvuKMPB+xVHhmCmRbgI=; b=lZ5VhHDY/wIiMpsHKNduxMBzkpPugQ6jMyuWZQP5ODLuXxB4IW5YJv6Id+ppRjcILI vfD5pORZqY75kXoe3zQB+z2ZXBc6nI7fKHD9esZLaQuE7zsGY10ZlB2aKzNiATtVk6Fo 3R2KqvB+Qyk3GoNBEsag26gOSLOX1JQvhVll7qnxguRzdktZuawj1j1g6NxCiBx4tRx7 ZcmuLcbKlvcsffQS3SXwixQNfhfKSi74v6RVOoA3LltZPgRpljqooZN6vsgyRePj8cgB QFNSfzPbioZ5OHSRNppu1q5iMagvmiyDUW1g28mxIktQGY/tt8++aRZrpiWdk+1OoTdK Wy1A== X-Forwarded-Encrypted: i=1; AJvYcCVYavIhQYbElI9oNf0ouX2sa9xgcKGB/eK5IIUfaUGsH9hi3OpFuoWD9cyTrjwH3CE288OM83cOz4gSTSCqYSXpmD2mwAR25VI= X-Gm-Message-State: AOJu0YxVGDfNc1FcN63klJRWZJ9Ev3RjNTNoQ0Han02NoEV9CEs+OCcm eK8dHS/GYfgN2O9qgdoMF5eKvlR59aKDMn5ZWlEaKCjRy5vDP9e/2ppRtyXBUeo= X-Google-Smtp-Source: AGHT+IGYKaptS6TuBb0EmDLduSvhUdAswh47VT1GJuTH6RZ3r7CwkR3CdDPkuPrN06B2IG4IMwaJBQ== X-Received: by 2002:a17:90b:f8c:b0:2bd:7935:a14e with SMTP id 98e67ed59e1d1-2c2bcc633e6mr1750465a91.30.1717751560035; Fri, 07 Jun 2024 02:12:40 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-2c29c494a51sm3139924a91.48.2024.06.07.02.12.39 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 07 Jun 2024 02:12:39 -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_Roy_Baron?= , 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_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V2 1/8] rust: Add initial bindings for OPP framework Date: Fri, 7 Jun 2024 14:42:16 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 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. Signed-off-by: Viresh Kumar --- rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 2 + rust/kernel/opp.rs | 156 ++++++++++++++++++++++++++++++++ 3 files changed, 159 insertions(+) create mode 100644 rust/kernel/opp.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 39853214806d..0465b03828b8 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index c5b21251ccba..82b527c76017 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -42,6 +42,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..9e5cf0412ed5 --- /dev/null +++ b/rust/kernel/opp.rs @@ -0,0 +1,156 @@ +// 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`](../../../../../../include/linux/pm_opp.h) + +use crate::{ + bindings, + device::Device, + error::{code::*, to_result, Result}, + types::{ARef, AlwaysRefCounted, Opaque}, +}; + +use core::ptr; + +/// 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, + }) + } +} + +/// 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’s 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 refcount is nonzero. + unsafe { bindings::dev_pm_opp_get(self.0.get()) }; + } + + unsafe fn dec_ref(obj: ptr::NonNull) { + // SAFETY: The safety requirements guarantee that the refcount is nonzero. + unsafe { bindings::dev_pm_opp_put(obj.cast().as_ptr()) } + } +} + +impl OPP { + /// Creates a reference to a [`OPP`] from a valid pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for the lifetime of the + /// returned [`OPP`] reference. + pub unsafe fn from_ptr_owned(ptr: *mut bindings::dev_pm_opp) -> Result> { + let ptr = ptr::NonNull::new(ptr).ok_or(ENODEV)?; + + // SAFETY: The safety requirements guarantee the validity of the pointer. + // + // INVARIANT: The refcount is already incremented by the C API that returned the pointer, + // and we pass ownership of the refcount to the new `ARef`. + Ok(unsafe { ARef::from_raw(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 the lifetime of the + /// returned [`OPP`] reference. + pub unsafe fn from_ptr(ptr: *mut bindings::dev_pm_opp) -> Result> { + let opp = unsafe { Self::from_ptr_owned(ptr) }?; + + // Take an extra reference to the OPP since the caller didn't take it. + opp.inc_ref(); + + Ok(opp) + } + + fn as_mut_ptr(&self) -> *mut bindings::dev_pm_opp { + self.0.get() + } + + /// Adds an OPP dynamically. + pub fn add(dev: ARef, mut data: Data) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_add_dynamic(dev.as_raw(), &mut data.0) }) + } + + /// Removes a dynamically added OPP. + pub fn remove(dev: ARef, freq: u64) { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_remove(dev.as_raw(), freq) }; + } + + /// Returns the frequency of an OPP. + pub fn freq(&self, index: Option) -> u64 { + let index = index.unwrap_or(0); + + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_freq_indexed(self.as_mut_ptr(), index) } + } + + /// Returns the voltage of an OPP. + pub fn voltage(&self) -> u64 { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_voltage(self.as_mut_ptr()) } + } + + /// Returns the level of an OPP. + pub fn level(&self) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_level(self.as_mut_ptr()) } + } + + /// Returns the power of an OPP. + pub fn power(&self) -> u64 { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_power(self.as_mut_ptr()) } + } + + /// 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 reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_required_pstate(self.as_mut_ptr(), index) } + } + + /// Returns true if the OPP is turbo. + pub fn is_turbo(&self) -> bool { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_is_turbo(self.as_mut_ptr()) } + } +} From patchwork Fri Jun 7 09:12:17 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 802793 Received: from mail-pl1-f181.google.com (mail-pl1-f181.google.com [209.85.214.181]) (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 A819115B992 for ; Fri, 7 Jun 2024 09:12:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.181 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751566; cv=none; b=Du94Ww7Z+vFbIjuKbY4wxLfUvofrQPtPL2nR570GvuiGGWHFwGUXamSkAXUZhDwcz4NCf0Btxb6btLEAbvVrWYti6ZmrjWXsD09Zq86jEYtsw7qRJFSn0hzi/kKqVBJ50hHx9NwiOXzvu+gSfGY3jHMiJrMRWK4p+L8ef3X6c6Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751566; c=relaxed/simple; bh=LXCum04nUhrgyANF+gOb3ucpEsRPodn6dAeooMzOn1w=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version:Content-Type; b=uTuzOBmA7C7wO8qgOMazP+R6SPM+9lHZyOuYsOW53LyaZ1NoqYBTubcOxUnAiuzhexu3JLi313eEMHtmQx14TRge377K8yM5DZx3cKisl6QVdjPcLl1yxSkzQGRiac/6bdmCkk7zlirLIFNc33VO+KOnrKuUa1mOInv2+W/lrXo= 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=H6ffCh6D; arc=none smtp.client-ip=209.85.214.181 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="H6ffCh6D" Received: by mail-pl1-f181.google.com with SMTP id d9443c01a7336-1f480624d0fso17130445ad.1 for ; Fri, 07 Jun 2024 02:12:44 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1717751564; x=1718356364; 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=S9btnKTfVMmtoCS/Jx3NLWU67XSnzWxib2jE3PLyV70=; b=H6ffCh6D0UAnTuxkMTeVcQtw8ak72iDES9e5sagr2R0k2UqMUCE21UpQgnOM2bKllW C4EIYtqTrwO31CFO61/UrNcAzRAoOTV52QhNhbuVvbRjWSlQRI/EvQDtUHsvBKnGjWDG Kzdtt/2aWF6hZiiajx0ht2QQ27K0UTMRYjdzahgz8g7OOzatfTebVr6C759V6SurepsS n5XnWU1XWqFoDMEIYhfZnzQqHESPEbpn0NUk8CezFityqI8ophVpFDPHkeYrxL7cIceM rDo7dNOqCfFDpTKVCdd99yFCpb4s2C5ufAp5VpXIc8hrnN/7eJLMMLkTe2JCzE0bRygA gASg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717751564; x=1718356364; 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=S9btnKTfVMmtoCS/Jx3NLWU67XSnzWxib2jE3PLyV70=; b=gBpum6cQARWTh4kHlHepgEGDtCbLiPIndaTCUW17nsuVYtTA96nMkhyrtsJ9uOmnHo K82d7AdpLrwPog+591vSADcoMNDDjhmG92qfAAF51RaTOdgbTw7Ird/THPVvuHMVNi31 SzV69A301S4We7dxxFId4bLQ9AdAgpyzX3x7L48IlEYXUrbjR9zU3FTYLl1zPowX9nP1 p/76jJci/xXWIoZ9m76lH5KkW12uWZKsJv2UylwgY+bz+Kgs+WKZaVsaHUWiKHcRDkrr TEN86okg1hvYkXnIbmAGpzhZNqu3k4ryqj+LFV+BKdzlmyt61FXyBNDFPOVHgZkpcWRC J5Tw== X-Forwarded-Encrypted: i=1; AJvYcCUvzyOG9rvyRrg4UHlgFD/JsawLFykW942uhplAaMoIBrbWbcI80KRRQPJdUNm8+OEh/dNl9xJDhsg6GL0bt/sJqbq4iMDQwys= X-Gm-Message-State: AOJu0Yzs5cR8kJ+S7MWyUJ/uRAiJWb1aImRwAJOi3cIgXIeocrL9Zfe4 hxpvH3ArLdNqZGeBXVxRdxKqJcT9K/CsFuH7UrtA9sOfCg2hEuPXNCwj1oBFcXo= X-Google-Smtp-Source: AGHT+IE3b0l/jD/45K8IZx1msoSy31zHFA37ziZd4QmuAXy5dOXcKcBDTiHkhFXbDie/5KX//NxijQ== X-Received: by 2002:a17:902:ecc1:b0:1f6:7e02:6ae0 with SMTP id d9443c01a7336-1f6d03a1132mr23054295ad.44.1717751563661; Fri, 07 Jun 2024 02:12:43 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1f6bd75f316sm29440845ad.47.2024.06.07.02.12.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 07 Jun 2024 02:12:43 -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_Roy_Baron?= , 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_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V2 2/8] rust: Extend OPP bindings for the OPP table Date: Fri, 7 Jun 2024 14:42:17 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This extends OPP bindings with the bindings for the `struct opp_table`. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 374 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 372 insertions(+), 2 deletions(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 9e5cf0412ed5..06f36845047f 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -7,9 +7,9 @@ //! C header: [`include/linux/pm_opp.h`](../../../../../../include/linux/pm_opp.h) use crate::{ - bindings, + bindings, cpumask, device::Device, - error::{code::*, to_result, Result}, + error::{code::*, from_err_ptr, to_result, Error, Result}, types::{ARef, AlwaysRefCounted, Opaque}, }; @@ -31,6 +31,376 @@ pub fn new(freq: u64, u_volt: u64, level: u32, turbo: bool) -> Self { } } +/// 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’s 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_ptr(ptr: *mut bindings::opp_table, dev: ARef) -> Self { + // SAFETY: By the safety requirements, ptr is valid and its refcount will be incremented. + unsafe { bindings::dev_pm_opp_get_opp_table_ref(ptr) }; + + Self { + ptr, + dev, + 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 `Device` and its safety + // requirements. Refcount of the OPP table is incremented as well. + let ptr = from_err_ptr(unsafe { bindings::dev_pm_opp_get_opp_table(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 `Device` 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.as_raw(), index) })?; + + // Fetch the newly created table. + let mut table = Self::from_dev(dev)?; + table.of = 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 `Device` 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: &mut cpumask::Cpumask) -> Result { + // 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(cpumask.as_ptr()) })?; + + // Fetch the newly created table. + let mut table = Self::from_dev(dev)?; + // SAFETY: The `cpumask` is guaranteed by the C code to be valid. + table.cpumask = Some(unsafe { cpumask::Cpumask::new(cpumask.as_mut_ptr()) }); + + Ok(table) + } + + // Remove device tree based OPP table for CPU devices. + #[cfg(CONFIG_OF)] + fn remove_of_cpumask(&self, cpumask: &cpumask::Cpumask) { + // SAFETY: The cpumask is valid and we took the reference from `from_of_cpumask` earlier, + // it is safe to drop the same now. + unsafe { bindings::dev_pm_opp_of_cpumask_remove_table(cpumask.as_ptr()) }; + } + + /// Returns the number of OPPs in the table. + pub fn opp_count(&self) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + let ret = unsafe { bindings::dev_pm_opp_get_opp_count(self.dev.as_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 `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_clock_latency(self.dev.as_raw()) } + } + + /// 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 `Device` 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 `Device` 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 `Device` 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 `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_sync_regulators(self.dev.as_raw()) }) + } + + /// Gets sharing CPUs. + pub fn sharing_cpus(dev: ARef, cpumask: &mut cpumask::Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` 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(&self, cpumask: &cpumask::Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_set_sharing_cpus(self.dev.as_raw(), cpumask.as_ptr()) + }) + } + + /// Gets sharing CPUs from Device tree. + #[cfg(CONFIG_OF)] + pub fn of_sharing_cpus(dev: ARef, cpumask: &mut cpumask::Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` 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 `Device` 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 `Device` 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: ARef) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_set_opp(self.dev.as_raw(), opp.as_mut_ptr()) }) + } + + /// Finds OPP based on frequency. + pub fn opp_from_freq( + &self, + mut freq: u64, + available: Option, + index: Option, + stype: SearchType, + ) -> Result> { + let rdev = self.dev.as_raw(); + let index = index.unwrap_or(0); + + let ptr = from_err_ptr(match stype { + SearchType::Exact => { + if let Some(available) = available { + // 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. + 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 => unsafe { + bindings::dev_pm_opp_find_freq_ceil_indexed(rdev, &mut freq 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 => unsafe { + bindings::dev_pm_opp_find_freq_floor_indexed(rdev, &mut freq as *mut u64, index) + }, + })?; + + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + unsafe { OPP::from_ptr_owned(ptr) } + } + + /// Finds OPP based on level. + pub fn opp_from_level(&self, mut level: u32, stype: SearchType) -> Result> { + let rdev = self.dev.as_raw(); + + let ptr = 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 => unsafe { bindings::dev_pm_opp_find_level_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 => 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 => 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. + unsafe { OPP::from_ptr_owned(ptr) } + } + + /// Finds OPP based on bandwidth. + pub fn opp_from_bw(&self, mut bw: u32, index: i32, stype: SearchType) -> Result> { + let rdev = self.dev.as_raw(); + + let ptr = from_err_ptr(match stype { + // The OPP core doesn't support this yet. + SearchType::Exact => 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 => unsafe { + bindings::dev_pm_opp_find_bw_ceil(rdev, &mut bw as *mut u32, 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 => unsafe { + bindings::dev_pm_opp_find_bw_floor(rdev, &mut bw as *mut u32, index) + }, + })?; + + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + unsafe { OPP::from_ptr_owned(ptr) } + } + + /// Enable the OPP. + pub fn enable_opp(&self, freq: u64) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` 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 `Device` 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::Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_of_register_em(self.dev.as_raw(), cpumask.as_mut_ptr()) + })?; + + self.em = true; + Ok(()) + } + + // Unregisters with Energy model. + #[cfg(CONFIG_OF)] + fn of_unregister_em(&self) { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. We registered with the EM framework earlier, it is 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 reference, 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) = &self.cpumask { + self.remove_of_cpumask(cpumask); + } + } + } +} + /// Operating performance point (OPP). /// /// # Invariants From patchwork Fri Jun 7 09:12:18 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 802521 Received: from mail-pl1-f175.google.com (mail-pl1-f175.google.com [209.85.214.175]) (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 4DAC915CD56 for ; Fri, 7 Jun 2024 09:12:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.175 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751571; cv=none; b=Hl/4fBlZYiB/7Ac1Kx7yWR/YlPVbL2AptKNz8f8JN0KJT1t1SKVNTQyTJidSkC5CCpNC9gsjCHGuKYXp4qkRm1/0a9F02dDrQpJ5M9s1hZ92l+U0UhL3cDbAv/uxBp7B5s2orCQoozV/gByhf8u4R0j8WzY523p2Oj1kgO9U02Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751571; c=relaxed/simple; bh=yQbu2BzvfcyL06wty0oKxJIOgxPxe0NA+Oypu+rr8gs=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=ACJ8Q1DK7A7U8LHcs70w8eyKUN9ahg0wyg0cM9wDku00x5X5S8UZ6s3P3hT15g0bT3nERcagCPFrHH/eWSabS/ec/plNv4m34Pd7891gTxIIBzbmmACV2qWjpbXjJXQFYJTNvtMeeEDXXUr7mSWddD0WQ424dXfnfWARz2GEo4c= 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=J1T8ZkTE; arc=none smtp.client-ip=209.85.214.175 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="J1T8ZkTE" Received: by mail-pl1-f175.google.com with SMTP id d9443c01a7336-1f6a837e9a3so12873865ad.1 for ; Fri, 07 Jun 2024 02:12:48 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1717751567; x=1718356367; 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=zFgEQc5AxyZLZc/ZKTPUL3s2+RpIEiR6EvwV6W5lrPI=; b=J1T8ZkTELA5SI9D4hxC0pkjO6v3bd9v7W11iG/AmMtR0EZFLwxbINxtrs+Hk8PtX0I Pdad2urIax4uaRGxOcMbZYIBCj6T7d/R39n1i3VnSbzKXN1XIpU6bEFlDdRV//nleYXH VU6Mdi39oopr/8hCqgsLxYxXQuuJWwApMalmCdT9h0HprKNl4NFvEYPkdRbnxU1patbu 0gXt08cyOu0nhe3QB55r3vJKwgei1ZVVuPV0LF4aX2j3qFxErMIEPgXT1py/K64Xnk76 sqcLcJKMY+ZiATmd6rNoqGJfrSeJfIpCAeXJ7FMsSS/pMO+92FZGsZ5ymMa2tEihrCbm fKbA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717751567; x=1718356367; 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=zFgEQc5AxyZLZc/ZKTPUL3s2+RpIEiR6EvwV6W5lrPI=; b=mOg1xnfPBcMzD28XPLSzLpLDUpzyjMuxfExF2Ey/s3ru1G9yrNFLYdNepP+DpO75oX zklZwIzaWWon+Cle74S6pyLJyMQ0Z7KJ1C2jFKblMJmc5+d+WN39hmnAhKv0jabt+qC2 oh5kMdKh4Nosv2NgZhFlY4b3+8D6c6YdMFkU4qk/+DBOdp4kRqJx0iBNUKKUhV5aJS6/ 6vg7qjcmnOaRaii98G4AUJjLE/VgmclHoyIhNYu6oheTeA+sE1KFEnhpMm0VAtP8Ua1B DmBNXr8Lt1/UWpzpsffKomknxlatSmmfYX7Ikalu9meXn/F21rgISQvCLCiTsOBUjuUX 6sIA== X-Forwarded-Encrypted: i=1; AJvYcCXFLlsfNXgMzzY5N1SH1Z7rnLpvYmTsWMM+kA8j48lwqNVp0IHT5PO5vhGVIozChmpAr4D4e3S4fBdcAHtgEB3mKvhWduE0TCE= X-Gm-Message-State: AOJu0Yx3Yng2qdKjhUHWOQHKPNBFvhnRUYApitZqa4OBKUpvoC2kBuw3 2Ey6s+b4ZQd3cKOYMCA2xBPehsZlYsjzdDalYdVuLPTIXNYcktJhqm50/ss7uDM= X-Google-Smtp-Source: AGHT+IEBd3DIoYngBelIp3hj7BJXY8CXcrTfGyQViok7B8N4sl1SBFb77/zOViK4tMx3pS79KHwrBg== X-Received: by 2002:a17:903:984:b0:1f6:8235:dbbc with SMTP id d9443c01a7336-1f6d02f4747mr24505395ad.29.1717751567374; Fri, 07 Jun 2024 02:12:47 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1f6bd7fd6cfsm29198765ad.274.2024.06.07.02.12.46 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 07 Jun 2024 02:12: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_Roy_Baron?= , 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_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V2 3/8] rust: Extend OPP bindings for the configuration options Date: Fri, 7 Jun 2024 14:42:18 +0530 Message-Id: <37bdd7ee7b74292830dd9977154b08ebcf08a138.1717750631.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This extends OPP bindings with the bindings for the OPP core configuration options. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 305 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 303 insertions(+), 2 deletions(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 06f36845047f..ebcb77b52558 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -9,11 +9,28 @@ use crate::{ bindings, 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}, }; -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: &Vec) -> Result> { + // Allocated a null-terminated vector of pointers. + let mut list = 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) +} /// Equivalent to `struct dev_pm_opp_data` in the C Code. #[repr(transparent)] @@ -42,6 +59,290 @@ pub enum SearchType { Ceil, } +/// 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: ARef, + _table: &Table, + _opp: ARef, + _scaling_down: bool, + ) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Called by the OPP core to configure OPP regulators. + fn config_regulators( + _dev: ARef, + _opp_old: ARef, + _opp_new: ARef, + _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 reference, 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. +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 = 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 = 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 = 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 configured. + if self.genpd_names.is_some() || self.required_devs.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.genpd_names = Some(names); + Ok(self) + } + + /// Initializes required devices. + pub fn set_required_devs(mut self, devs: Vec>) -> Result { + // Already configured. Only one of genpd or required devs can be configured. + if self.genpd_names.is_some() || self.required_devs.is_some() { + return Err(EBUSY); + } + + if devs.is_empty() { + return Err(EINVAL); + } + + self.required_devs = 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 = Some(hw); + Ok(self) + } + + /// Sets the configuration with the OPP core. + pub fn set(self, dev: ARef) -> Result { + let (_clk_list, clk_names) = match &self.clk_names { + Some(x) => { + let list = to_c_str_array(x)?; + let ptr = list.as_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null()), + }; + + let (_regulator_list, regulator_names) = match &self.regulator_names { + Some(x) => { + let list = to_c_str_array(x)?; + let ptr = list.as_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null()), + }; + + let (_genpd_list, genpd_names) = match &self.genpd_names { + Some(x) => { + let list = to_c_str_array(x)?; + let ptr = list.as_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null()), + }; + + let prop_name = match &self.prop_name { + Some(x) => x.as_char_ptr(), + None => ptr::null(), + }; + + let (supported_hw, supported_hw_count) = match &self.supported_hw { + Some(x) => (x.as_ptr(), x.len() as u32), + None => (ptr::null(), 0), + }; + + let (_required_devs_list, required_devs) = match &self.required_devs { + Some(x) => { + // Create a non-NULL-terminated vectorof pointers. + let mut list = Vec::with_capacity(x.len(), GFP_KERNEL)?; + + for dev in x.iter() { + list.push(dev.as_raw(), GFP_KERNEL)?; + } + + let ptr = list.as_mut_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null_mut()), + }; + + let mut config = bindings::dev_pm_opp_config { + clk_names, + config_clks: if T::HAS_CONFIG_CLKS { + Some(Self::config_clks) + } else { + None + }, + prop_name, + regulator_names, + config_regulators: if T::HAS_CONFIG_REGULATORS { + Some(Self::config_regulators) + } else { + None + }, + 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 `Device` and its safety + // requirements. The OPP core guarantees to not use fields of `config`, after this call has + // returned and so we don't need to save a copy of them for future use + let ret = unsafe { bindings::dev_pm_opp_set_config(dev.as_raw(), &mut config) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ConfigToken(ret)) + } + } + + // Config's 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 = unsafe { Device::from_raw(dev) }; + T::config_clks( + dev.clone(), + // SAFETY: 'opp_table' is guaranteed by the C code to be valid. + &unsafe { Table::from_ptr(opp_table, dev) }, + // SAFETY: 'opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_ptr(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 = unsafe { Device::from_raw(dev) }; + T::config_regulators( + dev, + // SAFETY: 'old_opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_ptr(old_opp)? }, + // SAFETY: 'new_opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_ptr(new_opp)? }, + regulators, + count, + ) + .map(|_| 0) + }) + } +} + /// Operating performance point (OPP) table. /// /// # Invariants From patchwork Fri Jun 7 09:12:19 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 802792 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 C2B7515D5AE for ; Fri, 7 Jun 2024 09:12:52 +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=1717751575; cv=none; b=J6YWeM85dlBPH3KiNIN5XeK9/a55/ACbN5LXuz3tzho/RRuBkMrBTPgSP+j1pYzkIPZqtwbduklCWVsZxvIYxddbSguPN8pd7Y0iPFTzhczrFy8HwIC37dYC0YEiJvQo3js9aaaUdrw/7gMhvM8m56RIKsJ4AhbliSgopUgMans= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751575; c=relaxed/simple; bh=3WppIDEiHtkc27oSZ5kYhcEWVyq8ODvpkSqW+McEEvk=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=JliOil9U4Mdk9vER2Kiaj5dfsBftvkI7oV3fXMEgmzWF4nEV8gQtQirUrZFROAtcIHnkFNAhJAkBpXIij5oSM3xi9zCSQwElwru8gR/mxAhHJHxNiHN7bjAPaFlx2SWhhIWyHjdmVSNliwVbtjPOphkVLUXk4VQcoJAYNUwaCTc= 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=WJ1e9WJH; 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="WJ1e9WJH" Received: by mail-pf1-f178.google.com with SMTP id d2e1a72fcca58-702342c60dfso1531806b3a.2 for ; Fri, 07 Jun 2024 02:12:52 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1717751572; x=1718356372; 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=z/xFIPejr4cmz4ji8m0mAcQhzeX5l9Sd0Ky95hRycz0=; b=WJ1e9WJHMEq28nVnUsaWAdgFi5wN5i96yzwJ7VRpblJ//ueG6zqOq+smT/RTzQMeEN DTMyUSP+i5HgaTEav0eR/KHb7aYAOqoIvC3znc58iCTzLZTZGLpryLd4+dVNX/tOBaWg dy3WMxg6blALCIq0dgtjksi+7ifNEAKDtNoAYinc0HXAokz4+2k/Rc9z3W5zPaw+ZNNy SQU995cUwWXqrzmkxOgv5cUxh/dA5Wa3flWCx0mqoO1CXlPLhJHmYae2b3y+soQS5YPE mgEKw6EqDOof2FQkc1fUJVsz9uZlWmS25AvuCA9oMiin8inn9oh6b8WTNP+PaIm8hFJ4 hdCQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717751572; x=1718356372; 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=z/xFIPejr4cmz4ji8m0mAcQhzeX5l9Sd0Ky95hRycz0=; b=uKGVOHuWq812tgxdlUuKQCooe1i0wY6BopO3itskar5sngRl8tHlHcmMD2CuyyGq/G zxOn+R1X4KbrRzIIWVd4BJcEeCjFaVx4dvNw7incV1mM+R9lcW+L1Iebm+1AITJxDiKG JSEDju3/wsS0hCuCMtVcJ88d2hLeRuGlyWpaC1p+LIytMOjMm24dyES4+kVy/vpmIllM jztFlkBazl9Jsw+LCht/iC4nlHAcedMhtbhPO8z+hnswI+ifL9uanR4PXXCuBozg98+Q 94bLotcdAS7+D2n7Uh+AKdMEDeADuD18aocUKkxFv+kWH4UOC9qY3MzmkNTpw4uQrc62 R0Fg== X-Forwarded-Encrypted: i=1; AJvYcCUTh/UtPW1Z30ttpDVzLceQNb0EXq86cJLd7YOzXVAlYE4zkjI6l86JkEHCnJK9JHC/eQMjSVn1CnrQ+04K8F4zny73CQmcTTw= X-Gm-Message-State: AOJu0YwezeQLHLA83J67hsG2UpjVx1G0AspxC4321PQESqBi9R6rCKn+ 6scvXFw6lLU8kWTa8aXAHdzquv3xOesezj+MqqG0fbVR6xAoLWcGZt3SVLU4pGY= X-Google-Smtp-Source: AGHT+IG08Pxsyb1sKknE5FGDbGy+wVdyb/51Y3SH8UCEHGGJE0lkwjQeXCVUgmSPEhYisNbBmJNkKA== X-Received: by 2002:a05:6a21:3393:b0:1a7:5e8f:8707 with SMTP id adf61e73a8af0-1b2f9a27efemr2211516637.26.1717751571615; Fri, 07 Jun 2024 02:12:51 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1f6bd7ccea9sm29508395ad.161.2024.06.07.02.12.50 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 07 Jun 2024 02:12:51 -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_Roy_Baron?= , 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_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V2 4/8] rust: Add initial bindings for cpufreq framework Date: Fri, 7 Jun 2024 14:42:19 +0530 Message-Id: <8a53d1e0bf52f02027ff4be2296bf59088bbd163.1717750631.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This commit adds initial Rust bindings for the cpufreq core. This adds basic bindings for cpufreq flags, relations and cpufreq table. Signed-off-by: Viresh Kumar Reviewed-by: Manos Pitsidianakis --- rust/bindings/bindings_helper.h | 1 + rust/helpers.c | 15 ++ rust/kernel/cpufreq.rs | 251 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 4 files changed, 269 insertions(+) create mode 100644 rust/kernel/cpufreq.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 0465b03828b8..9ae8aab41c53 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -7,6 +7,7 @@ */ #include +#include #include #include #include diff --git a/rust/helpers.c b/rust/helpers.c index 25cc8adac468..35c8b66d258f 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -230,6 +231,20 @@ void rust_helper_cpumask_setall(struct cpumask *dstp) } EXPORT_SYMBOL_GPL(rust_helper_cpumask_setall); +#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 *policy) +{ + 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..51a4a9bd8d3c --- /dev/null +++ b/rust/kernel/cpufreq.rs @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU frequency scaling. +//! +//! This module provides bindings for interacting with the cpufreq subsystem. +//! +//! C header: [`include/linux/cpufreq.h`](../../../../../../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 = 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 boundaries 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 changed. + pub const NEED_UPDATE_LIMITS: u16 = bindings::CPUFREQ_NEED_UPDATE_LIMITS 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 = bindings::CPUFREQ_CONST_LOOPS as _; + + /// Set by drivers that want the core to automatically register the cpufreq driver as a thermal + /// cooling device. + pub const IS_COOLING_DEV: u16 = 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 tunables for different + /// clusters. + pub const HAVE_GOVERNOR_PER_POLICY: u16 = bindings::CPUFREQ_HAVE_GOVERNOR_PER_POLICY as _; + + /// Set by drivers which do POSTCHANGE notifications from outside of their ->target() routine. + pub const ASYNC_NOTIFICATION: u16 = bindings::CPUFREQ_ASYNC_NOTIFICATION as _; + + /// Set by drivers that want cpufreq core to check if CPU is running at a frequency present in + /// freq-table exposed by the driver. For these drivers if CPU is found 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 = bindings::CPUFREQ_NEED_INITIAL_FREQ_CHECK as _; + + /// Set by drivers to disallow use of governors with "dynamic_switching" flag set. + pub const NO_AUTO_DYNAMIC_SWITCHING: u16 = bindings::CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING as _; +} + +/// CPU frequency selection relations. Each value contains a `bool` argument 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 = val & bindings::CPUFREQ_RELATION_E != 0; + + Ok(match val & !bindings::CPUFREQ_RELATION_E { + bindings::CPUFREQ_RELATION_L => Self::Low(efficient), + bindings::CPUFREQ_RELATION_H => Self::High(efficient), + bindings::CPUFREQ_RELATION_C => Self::Close(efficient), + _ => return Err(EINVAL), + }) + } + + /// Converts to a value compatible with the C code. + pub fn val(&self) -> u32 { + let (mut val, e) = match self { + Self::Low(e) => (bindings::CPUFREQ_RELATION_L, e), + Self::High(e) => (bindings::CPUFREQ_RELATION_H, e), + Self::Close(e) => (bindings::CPUFREQ_RELATION_C, e), + }; + + if *e { + val |= 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_ptr(ptr: *mut bindings::cpufreq_policy_data) -> Self { + Self(ptr) + } + + /// Returns the raw pointer to the C structure. + pub fn as_ptr(&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 reference, so it is safe to + // use it now. + to_result(unsafe { bindings::cpufreq_generic_frequency_table_verify(self.as_ptr()) }) + } +} + +/// Builder for the `struct cpufreq_frequency_table` in the C code. +#[repr(transparent)] +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) -> Result { + let len = entries.len(); + if len == 0 { + return Err(EINVAL); + } + + // Pin the entries to memory, since we are passing its pointer to the C code. + let mut entries = Pin::new(entries); + + // The pointer is valid until the table gets dropped. + let ptr = 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 lifetime 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 lifetime of `Self`. + len: unsafe { bindings::cpufreq_table_len(ptr) } as usize, + } + } + + // Validate the index. + fn validate(&self, index: usize) -> Result<()> { + if index >= self.len { + Err(EINVAL) + } else { + Ok(()) + } + } + + /// Returns raw pointer to the `struct cpufreq_frequency_table` compatible with the C code. + pub fn as_ptr(&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 limits 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 limits 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 limits 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 82b527c76017..7a3dcf1c3755 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 devres; From patchwork Fri Jun 7 09:12:20 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 802520 Received: from mail-pl1-f175.google.com (mail-pl1-f175.google.com [209.85.214.175]) (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 78D7515DBCE for ; Fri, 7 Jun 2024 09:12:56 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.175 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751578; cv=none; b=WXMZWFUvOtpdjCmgdDTyRW1vjun4s6w8UTwNPNBo21ECs8X5sJ/han7DEbS8KUKXAGMvuxCWTmE02wch+d0R9wnRmyD6rrYdFiO9u9utGeW4/Jx/t7AfMmeC84jzU/0nK2jd2gvF0Tz43X6WmD7bRJsJ0Hzq97aoj2LWXGhucNs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751578; c=relaxed/simple; bh=SP0zF/qQV6su2Bz7tEn1mT4rgqW43S1jdltO3YIwopc=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=MU4zWm0tWH8OX3SLSo+QTqig9b7l/v+FUBYr7Et0Oo7+UEz9+lBJ+SZ6JbdjtxWLRAESMitu9CoIw6ZAgolWiT7CYx2zyHGyyODy1jeutdWU5uOnjT2Gh1Vtv4kxNhpCNceOejrdStEiyg+oSAKdMcipCg4tJEX6tsWbGdI+HZs= 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=diG8Q5cH; arc=none smtp.client-ip=209.85.214.175 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="diG8Q5cH" Received: by mail-pl1-f175.google.com with SMTP id d9443c01a7336-1f6ab88dfaeso16772655ad.2 for ; Fri, 07 Jun 2024 02:12:56 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1717751576; x=1718356376; 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=ts4ZPCWdX1WWZnRhg2kN6M+wqUEnt4/e2UDw6VFJ03s=; b=diG8Q5cHBNOTeBiAsas9EL2SXoP2vtSUQtwxTs/e4F/F2ZXnUb+/nyIahGUGeZyZBR h+cv4eyDNNZIDgooVG8d/IV+9h0VuqMUIXyHt/tvQbHwQKYml568ctipqOJPDOeYQYT2 IhtIcBU5V42ZOGpFWy7tqGjO90okR38er68h+ckvt+KecaAzXYlXWLParP3GiYQ01cJ+ bIqM/paOl1Hvx83ghzoWuz92HXzWYxry2Z9U5kgVQOmuoOjmKLnz/BEUQc3NMp7tCCQX Wh5eTVCSE1m1OepAqDMSRlcrnDcJSbbR441DQU3430x492XUxFkFalz4cTUWCmJQJ3eH ZS3g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717751576; x=1718356376; 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=ts4ZPCWdX1WWZnRhg2kN6M+wqUEnt4/e2UDw6VFJ03s=; b=ONzvSxnD265jUnl0OljgZavpGIsMfaf/3MMLolDZFVwsxTVE1ES7vmE5GyKHrIcDYg Qn/rg6wupXF3gM4DjIjpi5F0WrWbQICXUNBZq88NrJhswji6K6XTdiDP+h3of6/JlqFN Rp+2aj/rgEHxp6tHXw+SMEzlwbxbiANBRO/f36bhfw3uzLPCTyn4KKiC+NmAtEE5xlIt zX1FkGJZpxqnRs1gzb3RXlTTtuFqPIAlBRZIKoakcU23vryd+j8DneWRvNSharR4wHB/ mDSUE7WLB/c8PjKBfl9cBcSgBrYPxgkYPb45yPv/Fectggy+14ozqo2BG0Yd0fjDjfS+ IzcQ== X-Forwarded-Encrypted: i=1; AJvYcCXale4D2ikP4f1U1FGaK1Ke4q8R2HbdRWHyPxzHxVjAi+1NyGVTfGj8PwL8ePq+BbNxQONIffxasPQ34C1xr3rpF4l1bu1+LDg= X-Gm-Message-State: AOJu0YyXbSF7hnqYLmfspGVRJNdyft59m2lGhIIkyOlmWRDaOsWw/F5G 4K2OHP7er7CaNDm9ArD+JrCLXdyjZHIeVA3+QJ+z6oD2wvmpOVdX70NQahW4sQQ= X-Google-Smtp-Source: AGHT+IHkC0n5uOshvr23SahV4wBl7RrvtZwAy1q+4IdGgmbX6iinrkTMIb0M362jY/hpVtfiJVAL4w== X-Received: by 2002:a17:902:da89:b0:1f6:7e02:7ab8 with SMTP id d9443c01a7336-1f6d03e70ddmr21788485ad.68.1717751575441; Fri, 07 Jun 2024 02:12:55 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1f6bd7603bdsm29922285ad.50.2024.06.07.02.12.54 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 07 Jun 2024 02:12:54 -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_Roy_Baron?= , 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_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V2 5/8] rust: Extend cpufreq bindings for policy and driver ops Date: Fri, 7 Jun 2024 14:42:20 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This extends the cpufreq bindings with bindings for cpufreq policy and driver operations. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 335 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 333 insertions(+), 2 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 51a4a9bd8d3c..d5679272e40b 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -7,15 +7,20 @@ //! C header: [`include/linux/cpufreq.h`](../../../../../../include/linux/cpufreq.h) 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}, }; use core::{ pin::Pin, + ptr::self, }; +use macros::vtable; + /// Default transition latency value. pub const ETERNAL_LATENCY: u32 = bindings::CPUFREQ_ETERNAL as u32; @@ -249,3 +254,329 @@ 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_ptr(ptr: *mut bindings::cpufreq_policy) -> Self { + Self { + ptr, + put_cpu: false, + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `Self`. The `cpus` + // pointer is guaranteed to be valid by the C code. + cpumask: unsafe { cpumask::Cpumask::new((*ptr).cpus) }, + } + } + + fn from_cpu(cpu: u32) -> Result { + // SAFETY: It is safe to call `cpufreq_cpu_get()` for any CPU. + let ptr = from_err_ptr(unsafe { bindings::cpufreq_cpu_get(cpu) })?; + + // SAFETY: The pointer is guaranteed to be valid by the C code. + let mut policy = unsafe { Policy::from_ptr(ptr) }; + policy.put_cpu = true; + Ok(policy) + } + + /// Raw pointer to the underlying cpufreq policy. + pub fn as_ptr(&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 reference 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 reference 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 = 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 reference, so it is safe to + // use it now. + to_result(unsafe { bindings::cpufreq_generic_suspend(self.as_ptr()) }) + } + + /// 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 reference, 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 reference, so it is safe to + // use it now. + unsafe { bindings::cpufreq_register_em_with_opp(self.as_ptr()) }; + } + + /// Gets raw pointer to cpufreq policy's CPUs mask. + pub fn cpus(&mut self) -> &mut cpumask::Cpumask { + &mut self.cpumask + } + + /// Sets CPUs mask for a cpufreq policy. + /// + /// Update the `cpus` mask with a single CPU. + pub fn set_cpus(&mut self, cpu: u32) -> &mut Self { + // SAFETY: The `cpus` pointer is guaranteed to be valid for the lifetime of `self`. And it + // is safe to call `cpumask_set_cpus()` for any CPU. + unsafe { bindings::cpumask_set_cpu(cpu, self.cpus().as_mut_ptr()) }; + self + } + + /// Sets CPUs mask for a cpufreq policy. + /// + /// Update the `cpus` mask with a single CPU if `cpu` is set to `Some(cpu)`, else sets all + /// CPUs. + pub fn set_all_cpus(&mut self) -> &mut Self { + // SAFETY: The `cpus` pointer is guaranteed to be valid for the lifetime of `self`. And it + // is safe to call `cpumask_setall()`. + unsafe { bindings::cpumask_setall(self.cpus().as_mut_ptr()) }; + self + } + + /// Sets clock for a cpufreq policy. + pub fn set_clk(&mut self, dev: ARef, name: Option<&CStr>) -> Result { + let clk = clk::Clk::new(dev, name)?; + self.as_mut_ref().clk = clk.as_ptr(); + 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 = 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 = 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 not freed once this table + /// is dropped. + pub fn freq_table(&self) -> Result
{ + if self.as_ref().freq_table == ptr::null_mut() { + 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 not 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 = table.as_ptr(); + 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 = ::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 = + Some(unsafe { ::from_foreign(self.as_ref().driver_data) }); + self.as_mut_ref().driver_data = 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_ptr()) }; + } + } +} + +/// Operations to be implemented by a cpufreq driver. +#[vtable] +pub trait DriverOps { + /// 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) + } +} From patchwork Fri Jun 7 09:12:21 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 802791 Received: from mail-pl1-f174.google.com (mail-pl1-f174.google.com [209.85.214.174]) (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 64D3C15E5C0 for ; Fri, 7 Jun 2024 09:13:00 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.174 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751582; cv=none; b=Z4Ndw78uP1tOc7dtvSisueqDzPA85deuSTe+fUhiwVbyOOwdUvMxCMcFdFUUeqzdyVljssvPbYMo11mK1eRDbZSZ1cVobBALz2au1UNWMOFStFmNmcvEG3q15J25YL/ItDu13ktbNfvrbrHnsyRAQzveieMRhfG54X7TP4LovMk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751582; c=relaxed/simple; bh=W2KMeDxS/6WMTlM2Lf4D/UsbGwQ/V2yDMEQ0Z88lCb0=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=N4NsqH9Prq6j2tTc6XqqJP7R18L0L6vN9Vxr886BqnhlJoFgT7hg90VecyWGbsPAIXoeqGEDgu26Ia4Z+Ac3cDPDyaRmqeEkQqIyF5g2NHqp6rZHMzkVpaaumUNKBLSMnaWoEXWx5McmmYzPWdxSl5YYiz0yJrtHdKDviclm3ow= 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=Gi3OhzxO; arc=none smtp.client-ip=209.85.214.174 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="Gi3OhzxO" Received: by mail-pl1-f174.google.com with SMTP id d9443c01a7336-1f6ab88dfaeso16773225ad.2 for ; Fri, 07 Jun 2024 02:13:00 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1717751580; x=1718356380; 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=+Tu8R/Slxi6hlXPEgui5zs0wCaeCyPbdxpusH+/PwXI=; b=Gi3OhzxOfNsSmNOu72xiCjYFFagClz3FVvj+sNFDbZ1PgwonuKkEhVH4g6Y2iL/ch0 ecA9EiHtqbPdzbAHWUL7cvH7mK1K0PeK79ShLobRvkWohWprWJj4zjgXfN41t9jJ6yUM mSm/kqkzFPSt/yEdwnRrMliMY7kUJ5TZG9thhXdc6GPA/6aKbT7vQay+hiIzqHmTcSC7 Owb10UElv1bmnfIAPoTrfmvoIiFeFHgRAgoekeHm4TT/TluwbCztNgfjYNvN6QZjM4dp 1oM6GV73Yi+BYJ82xnoSOCbbnluViSkgiKXmiYGOrsMZse5x2KnVTFmlPi6OSjeXUPHD zjUQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717751580; x=1718356380; 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=+Tu8R/Slxi6hlXPEgui5zs0wCaeCyPbdxpusH+/PwXI=; b=HPKcYyLGtsrj4QE+5Xk9mqcHQei9tRqCqCRUjQ0JJaFqbIq188N8vo5h/00dth/SIF GP/+wFeIWia8opw5OhY7L6ZkXxDTp/ASkjQVS/6fdCRYR2DnhSfHFe07f4oCY7sBVJ6Z DdqeeHBVdt87aSTXm+A+6tJ/bm7KnG1Utqz8qNQtTr/uXHT4xhzXuagCwA42dJyEQ5iY fkSRRZIJ2TIu9+VxIlZucgoWb+3YLAAWjnBXPf7+8a/0siQeSLoikxZ+/XnlkQjWeI1e iutu6rM0UB+lGsSzM9AqVV9lonHR8Ex7tS/suc4xEbopyUAxGEoZYnBUu3TR5VyRxUMB /JRw== X-Forwarded-Encrypted: i=1; AJvYcCX7rPp6suUUNpm1QhaJKXyn0fGuKFZNS0yvVz9HrLm2W0na9DfI3qUqzx37rEx9g7Zceu7G9zKcdTs8Plx2hxqjHm31ek5OInk= X-Gm-Message-State: AOJu0Yzd447pyOr1ZZ7ZDn/oLJJgk9dqNBGGLBRRXfdSSj4zWpxTLXKo ictH+4+Mh9L8MGa0sIi/tSRT5llh9eplJ/2mhFruDXYQv4y4i/huibYh1GJ8AOc= X-Google-Smtp-Source: AGHT+IEFCeDDBxW2kS7vIkDgT3DwtVxB5zwC8xpWpKFjFRtfPknZNd6Uts92pNL6c/BZcWFUSdI6Dg== X-Received: by 2002:a17:902:db05:b0:1f6:6ae5:1410 with SMTP id d9443c01a7336-1f6d03c8d5emr20219555ad.64.1717751579255; Fri, 07 Jun 2024 02:12:59 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1f6bd761660sm29380525ad.53.2024.06.07.02.12.58 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 07 Jun 2024 02:12:58 -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_Roy_Baron?= , 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_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V2 6/8] rust: Extend cpufreq bindings for driver registration Date: Fri, 7 Jun 2024 14:42:21 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This extends the cpufreq bindings with bindings for registering a driver. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 492 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 490 insertions(+), 2 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index d5679272e40b..76eba63b6716 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}, }; use core::{ + cell::UnsafeCell, + marker::{PhantomData, PhantomPinned}, pin::Pin, - ptr::self, + ptr::{self, addr_of_mut}, }; use macros::vtable; @@ -580,3 +582,489 @@ 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, + _pin: PhantomPinned, +} + +// SAFETY: `Registration` doesn't offer any methods or access to fields when 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 `Send`, so it is okay to move +// `Registration` to different threads. +#[allow(clippy::non_send_fields_in_send_ty)] +unsafe impl Send for Registration {} + +impl Default for Registration { + fn default() -> Self { + Self::new() + } +} + +impl Registration { + /// Creates new [`Registration`] but does not register it yet. + /// + /// It is allowed to move. + pub fn new() -> Self { + Self { + registered: false, + drv: UnsafeCell::new(bindings::cpufreq_driver::default()), + _pin: PhantomPinned, + _p: PhantomData, + } + } + + /// Registers a cpufreq driver with the rest of the kernel. + pub fn register( + self: Pin<&mut Self>, + name: &'static CStr, + data: T::Data, + flags: u16, + boost: bool, + ) -> Result { + // SAFETY: We never move out of `this`. + let this = unsafe { self.get_unchecked_mut() }; + + if this.registered { + return Err(EINVAL); + } + + let drv = this.drv.get_mut(); + + // Account for the trailing null character. + let len = name.len() + 1; + if len > drv.name.len() { + return Err(EINVAL); + }; + + // SAFETY: `name` is a valid Cstr, and we are copying it to an array of equal or larger + // size. + let name = unsafe { &*(name.as_bytes_with_nul() as *const [u8] as *const [i8]) }; + drv.name[..len].copy_from_slice(name); + + drv.boost_enabled = boost; + drv.flags = flags; + + // Allocate an array of 3 pointers to be passed to the C code. + let mut attr = Box::new([ptr::null_mut(); 3], GFP_KERNEL)?; + let mut next = 0; + + // SAFETY: The C code returns a valid pointer here, which is again passed to the C code in + // an array. + attr[next] = + unsafe { addr_of_mut!(bindings::cpufreq_freq_attr_scaling_available_freqs) as *mut _ }; + next += 1; + + if boost { + // SAFETY: The C code returns a valid pointer here, which is again passed to the C code + // in an array. + attr[next] = + unsafe { addr_of_mut!(bindings::cpufreq_freq_attr_scaling_boost_freqs) as *mut _ }; + next += 1; + } + attr[next] = 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 = Box::leak(attr) as *mut _; + + // Initialize mandatory callbacks. + drv.init = Some(Self::init_callback); + drv.verify = Some(Self::verify_callback); + + // Initialize optional callbacks. + drv.setpolicy = if T::HAS_SETPOLICY { + Some(Self::setpolicy_callback) + } else { + None + }; + drv.target = if T::HAS_TARGET { + Some(Self::target_callback) + } else { + None + }; + drv.target_index = if T::HAS_TARGET_INDEX { + Some(Self::target_index_callback) + } else { + None + }; + drv.fast_switch = if T::HAS_FAST_SWITCH { + Some(Self::fast_switch_callback) + } else { + None + }; + drv.adjust_perf = if T::HAS_ADJUST_PERF { + Some(Self::adjust_perf_callback) + } else { + None + }; + drv.get_intermediate = if T::HAS_GET_INTERMEDIATE { + Some(Self::get_intermediate_callback) + } else { + None + }; + drv.target_intermediate = if T::HAS_TARGET_INTERMEDIATE { + Some(Self::target_intermediate_callback) + } else { + None + }; + drv.get = if T::HAS_GET { + Some(Self::get_callback) + } else { + None + }; + drv.update_limits = if T::HAS_UPDATE_LIMITS { + Some(Self::update_limits_callback) + } else { + None + }; + drv.bios_limit = if T::HAS_BIOS_LIMIT { + Some(Self::bios_limit_callback) + } else { + None + }; + drv.online = if T::HAS_ONLINE { + Some(Self::online_callback) + } else { + None + }; + drv.offline = if T::HAS_OFFLINE { + Some(Self::offline_callback) + } else { + None + }; + drv.exit = if T::HAS_EXIT { + Some(Self::exit_callback) + } else { + None + }; + drv.suspend = if T::HAS_SUSPEND { + Some(Self::suspend_callback) + } else { + None + }; + drv.resume = if T::HAS_RESUME { + Some(Self::resume_callback) + } else { + None + }; + drv.ready = if T::HAS_READY { + Some(Self::ready_callback) + } else { + None + }; + drv.set_boost = if T::HAS_SET_BOOST { + Some(Self::set_boost_callback) + } else { + None + }; + drv.register_em = if T::HAS_REGISTER_EM { + Some(Self::register_em_callback) + } else { + None + }; + + // Set driver data before registering the driver, as the cpufreq core may call few + // callbacks before `cpufreq_register_driver()` returns. + this.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(this.drv.get_mut()) })?; + + this.registered = true; + Ok(()) + } + + /// 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 = unsafe { bindings::cpufreq_get_driver_data() }; + if data.is_null() { + None + } else { + // SAFETY: The driver data is earlier set by us from [`set_data()`]. + Some(unsafe { D::borrow(data) }) + } + } + + // Sets the data for a cpufreq driver. + fn set_data(&mut self, data: T::Data) -> Result<()> { + let drv = self.drv.get_mut(); + + if drv.driver_data.is_null() { + // Pass the ownership of the data to the foreign interface. + drv.driver_data = ::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 = 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 = Some(unsafe { ::from_foreign(drv.driver_data) }); + drv.driver_data = ptr::null_mut(); + data + } + } +} + +// cpufreq driver callbacks. +impl Registration { + // Policy's init callback. + extern "C" fn init_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // 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 = unsafe { Policy::from_ptr(ptr) }; + + let data = T::init(&mut policy)?; + policy.set_data(data)?; + Ok(0) + }) + } + + // Policy's exit callback. + extern "C" fn exit_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // 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 = unsafe { Policy::from_ptr(ptr) }; + + let data = policy.clear_data(); + T::exit(&mut policy, data).map(|_| 0) + }) + } + + // Policy's online callback. + extern "C" fn online_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // 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 = unsafe { Policy::from_ptr(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. `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 = unsafe { Policy::from_ptr(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. `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 = unsafe { Policy::from_ptr(ptr) }; + T::suspend(&mut policy).map(|_| 0) + }) + } + + // Policy's resume callback. + extern "C" fn resume_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // 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 = unsafe { Policy::from_ptr(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 = unsafe { Policy::from_ptr(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. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut data = unsafe { PolicyData::from_ptr(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. `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 = unsafe { Policy::from_ptr(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. `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 = unsafe { Policy::from_ptr(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. `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 = unsafe { Policy::from_ptr(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 = unsafe { Policy::from_ptr(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_perf: u64, capacity: u64) { + if let Some(mut policy) = Policy::from_cpu(cpu).ok() { + 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 = unsafe { Policy::from_ptr(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. `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 = unsafe { Policy::from_ptr(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).map_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 Some(mut policy) = Policy::from_cpu(cpu).ok() { + 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 = 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. `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 = unsafe { Policy::from_ptr(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 = unsafe { Policy::from_ptr(ptr) }; + T::register_em(&mut policy); + } +} + +impl Drop for Registration { + // Removes the registration from the kernel if it has completed successfully before. + fn drop(&mut self) { + let drv = 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()); + } +} From patchwork Fri Jun 7 09:12:22 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 802519 Received: from mail-pf1-f179.google.com (mail-pf1-f179.google.com [209.85.210.179]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9F08915ECDF for ; Fri, 7 Jun 2024 09:13:03 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.179 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751585; cv=none; b=hg3z4sxL3W6yWbIBAefhFHIcxDn7fe0YMRkAsACI6WFLgIXvSCvhtwCTcRBD/VHrPyWvr02sLka/w/LBwJvGlD7tgog/3z+JTRkCURCWLyVtlyPB13vsL15jGxiK9d1pYfIJ90o2Izq5xu2Ph0TOi9uGWzfXCLQRSRSoUN0UzVE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751585; c=relaxed/simple; bh=Y+dnDpoPgLDQbxi2D26tM1HhdBJGHB5DyqDp5BgM3qc=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=lZzlXzw/UOU3aOGRMw4+wiVbRbfJf6HoLneIKpf7J8OkOq0ZvWg4O1dLyg+d58RNb739ruAxJ7tFJvFpBYruoS1ksJwoJp80DIjpA/sGUEi82NxHgrLWBeaKFhYXB8PZ6GgGf04Sro6QIQMxJCiujWKYvhcGCcn5vu2vySe8Ab4= 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=UijrZEoU; arc=none smtp.client-ip=209.85.210.179 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="UijrZEoU" Received: by mail-pf1-f179.google.com with SMTP id d2e1a72fcca58-70249faa853so1589967b3a.3 for ; Fri, 07 Jun 2024 02:13:03 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1717751583; x=1718356383; 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=zCjoSclVWZT0iDBq8VFLkZOWwHf6tFEcHjugFV93b9U=; b=UijrZEoU5H2jKL+3r85xZOL8CZZlKZ3iHSAjm3NlzVBPUD6ODH0IVGld654yG/jER9 4a5GV7BB8q7s3UIoG0VEr+2M38kb8GM/7b4nC16r3tKdQJ+1VJ5yRoYgxfOY5VbIdkan 85RIERByXSas46utrRwy8zmPTqCSV5cwV7RAFYGbEBG3LarzmI3tdL4H5fxPWFQHubPc jJMEk4Tlfz1hVKjQ5WJNSlN+xg5m7YPQRTtzcPByC1cmyeS/3alKBa5RXQ21oW8b3Ofz oqzqBTjayUf6EQCG6nSHi/7YfiYotyOaEUv3KEY55r679jvpFpsDhQ+uM50yXMaK7uLW 8wiA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717751583; x=1718356383; 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=zCjoSclVWZT0iDBq8VFLkZOWwHf6tFEcHjugFV93b9U=; b=eeJY6Tp7lzorcyvR/eVAVKurCtBzthcDylMupV+GI0nNd/rb/+4gkUb+TRErf8ifP6 beBBTYhHAEX6No8Uoiv//geWVBzWHy8nIbGq2zuiEqev54UmiJXHwOc29U/xyNu4jC3J odj6/6FpvF/Ih4+kMyN/60NJt+LHzgOQFvZfeTMDXP27xgfN7Us9rOK8+9h70tOb+6uO mz4Xip8YfCRd8U4qvyf1PF3TZBiWwCMGPcv8etULrxHAPP5zkFgDT0QkrEpPldoF66Rt mmvffFz9EeoduPF/aa4jzpE/er6qllQ4wLumQ2QT0yhxaWr4Us8TuC18QjIHKAS/l3t0 FjLw== X-Forwarded-Encrypted: i=1; AJvYcCV+IjYSc0Too6aMWYGaFaMJaWRwUQYNTg85xwSsZJRei1CgiTpVP9wipwJhZumMIsQpbSkKxpJ4mKiUqjkKGQ9923Su5nP25PU= X-Gm-Message-State: AOJu0Yy58a+Gaaws0xNKDdJCG5jUm1raKbHzL4qh1zJITyqHk4Mf+Ae6 qzeJKKBFixDc1dzOKEI1QVNfbeAjsWmDJry9AL+xnhxqA8TBV9yMjOLi7IOjfig= X-Google-Smtp-Source: AGHT+IEynFUinI3X2Ts6k+rw9ZruxT15CQaIWnniA8Pyq/ymZo56xbDZgdazaXXsdaS1AQtNJabJEw== X-Received: by 2002:a05:6a21:19a:b0:1b4:4370:60f with SMTP id adf61e73a8af0-1b443700773mr422429637.1.1717751582668; Fri, 07 Jun 2024 02:13:02 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1f6bd7d89a0sm29256535ad.128.2024.06.07.02.13.01 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 07 Jun 2024 02:13:02 -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_Roy_Baron?= , 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_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V2 7/8] rust: Extend OPP bindings with CPU frequency table Date: Fri, 7 Jun 2024 14:42:22 +0530 Message-Id: <6e703e990bd1ce864927060c53025506568fd0b8.1717750631.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 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 ebcb77b52558..4833848f79b1 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -15,7 +15,10 @@ types::{ARef, AlwaysRefCounted, Opaque}, }; -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}; use macros::vtable; @@ -343,6 +346,56 @@ extern "C" fn config_regulators( } } +/// 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 = ptr::null_mut(); + + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_init_cpufreq_table(table.dev.as_raw(), &mut ptr) + })?; + Ok(Self { + dev: table.dev.clone(), + // 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 = 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 reference, so it is safe to + // relinquish it now. + unsafe { bindings::dev_pm_opp_free_cpufreq_table(self.dev.as_raw(), &mut self.as_ptr()) }; + } +} + /// Operating performance point (OPP) table. /// /// # Invariants @@ -538,6 +591,12 @@ pub fn adjust_voltage( }) } + /// 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 `Device` and its safety From patchwork Fri Jun 7 09:12:23 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 802790 Received: from mail-pg1-f179.google.com (mail-pg1-f179.google.com [209.85.215.179]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 99705152511 for ; Fri, 7 Jun 2024 09:13:07 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.179 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751590; cv=none; b=TY1ztJUY/l16esuR8a2C1+SpWAd+wFzcz530Uo91CBXkcEe6GAG6NqXciOhETonr6rfLByEb6EtTodY/0fjkBHWBWE6qy6c9tAzbHymPXZENABK6rPzzgF419AC1kkjxx/zo09upEjzY3zPfyv7s8HMLqyzxTuxK5iaDKzq0/yI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717751590; c=relaxed/simple; bh=PlYAE9z0g5K3iAsbL9S0/w/lr81FU4c5zUhtR8b3HfE=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=bIycGjaTf0GhITtI7cKcC8gS6XtSBX75Sn6X4BaeDQu4ujDbcvLb2Yaf2Y29rkozQ72ZBUgq3q1sarqOTNrIEqvWz2cufEshnTPQBpxOcJ8DKhZfdXNU2iwNu67ArcJN4E0LaBRJ5e/09QB1g4OC1Utegjqo9Nwlz2TEq1ToGcg= 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=P3XiygEV; arc=none smtp.client-ip=209.85.215.179 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="P3XiygEV" Received: by mail-pg1-f179.google.com with SMTP id 41be03b00d2f7-6cdf9a16229so1397994a12.3 for ; Fri, 07 Jun 2024 02:13:07 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1717751587; x=1718356387; 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=gpdjfdsu7F7InZnhYGTwKFUVSu8T2YzyZYnj5q/OC3w=; b=P3XiygEVSzpvjJFpzadjMKZWCn0y7tolzdnqeClHXN/tF7mOyozN4k2qT+psTZYBEA y51bwWGhhejCinprctUg0MCiTumDoV6Yb632JPCNvfG1tF3mIptUQHn2NoFsJXET5RXD a76kfzK7UU9Gdbn1HCfQq1xeqG2pjxhpEqWm8fRHEYZFKMACOzHKWPGLpc7Ka/Dg625Z R4j8/wqwH2DYmxekCnaMAEr/vIw2shJAJhGb0kgcKDl7A2BLobIjxUqJz+dh6aXw+MCR J5K+dTQbXInmzAXiXHb+7EGCLT7Tw3Nmbi/4KWjWr8G+enB1P6PdbYhXDpifTNjCGqLt BfYg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717751587; x=1718356387; 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=gpdjfdsu7F7InZnhYGTwKFUVSu8T2YzyZYnj5q/OC3w=; b=Kyf9UIh3MKJRkXe0IZsyUmeSOmh2ttYT8z79kJHh18RX1hXhlP6yMvCvcwuNtiLliu qHY2ZA1SlaWcP9eQRYFiiYFD3uV15/Or2MPffRYjVIuofaASS0+nIJBZvwspe6G1dTS6 uIcVZAU/j0fwTY0w8t1X+0ctX7p9V8ZhCAdwGJYf3GXSD/qE70zQaZltIO78D2Y4q9pZ 8fcjNWtgq77oZ4BWwvTMc4EztJcG6hJbFVFpb73pMjL/q43UXOxuJCDipw1VZ/TBRD8I 00TPiQzwGFZ2fLKWufUaUrrYuGuGk8Ns9H0HgZCRvsRNB9m4Unz4iqfsNT0xXer6zNTO CMig== X-Gm-Message-State: AOJu0YyVLSr0CbGUH6IlSjpHtBqUkJ8+mrVVyM72eeqf6csacPfrypzx hQvFr65WlkTxtki9OXb8HwmLErzZcYve2SIEyyWVrZ8Ee/2bJb3P3nq4IZ4uZOo= X-Google-Smtp-Source: AGHT+IGTKWVmYcNoQJyhcj1P+6/81dmOtIBoL4JNvjOpvNWJY60yKyW7M76qmcyTJfvXfVUqVxTKmw== X-Received: by 2002:a17:90a:b008:b0:2bd:d2f9:e71a with SMTP id 98e67ed59e1d1-2c2bcc0bbe9mr1875468a91.29.1717751586630; Fri, 07 Jun 2024 02:13:06 -0700 (PDT) Received: from localhost ([122.172.82.13]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-2c29c4a574bsm3069258a91.56.2024.06.07.02.13.05 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 07 Jun 2024 02:13:06 -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_Roy_Baron?= , 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_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [RFC PATCH V2 8/8] cpufreq: Add Rust based cpufreq-dt driver Date: Fri, 7 Jun 2024 14:42:23 +0530 Message-Id: <994d50cbf25a1301e4c0ffbc48eaabd8c90ab827.1717750631.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 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 | 229 +++++++++++++++++++++++++++++++++ 3 files changed, 242 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 If in doubt, say N. +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) += cpufreq_governor.o obj-$(CONFIG_CPU_FREQ_GOV_ATTR_SET) += cpufreq_governor_attr_set.o obj-$(CONFIG_CPUFREQ_DT) += cpufreq-dt.o +obj-$(CONFIG_CPUFREQ_DT_RUST) += rcpufreq_dt.o obj-$(CONFIG_CPUFREQ_DT_PLATDEV) += cpufreq-dt-platdev.o # Traces diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs new file mode 100644 index 000000000000..b016771e6180 --- /dev/null +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -0,0 +1,229 @@ +// 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, define_of_id_table, + device::{self, Device}, + error::code::*, + fmt, + macros::vtable, + module_platform_driver, of, opp, platform, + prelude::*, + str::CString, + sync::Arc, + types::ARef, +}; + +// Finds exact supply name from the OF node. +fn find_supply_name_exact(np: &ARef, name: &str) -> Option { + let name_cstr = 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: ARef, cpu: u32) -> Option> { + let np = of::DeviceNode::from_dev(dev).ok()?; + + // Try "cpu0" for older DTs. + let name = match cpu { + 0 => find_supply_name_exact(&np, "cpu0"), + _ => None, + } + .or(find_supply_name_exact(&np, "cpu"))?; + + let mut list = 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)] + token: Option, + #[allow(dead_code)] + clk: clk::Clk, +} + +#[vtable] +impl opp::ConfigOps for CPUFreqDTDevice {} + +#[vtable] +impl cpufreq::DriverOps for CPUFreqDTDevice { + type Data = (); + type PData = Arc; + + fn init(policy: &mut cpufreq::Policy) -> Result { + let cpu = policy.cpu(); + let dev = Device::from_cpu(cpu)?; + + policy.set_cpus(cpu); + + let token = match find_supply_names(dev.clone(), cpu) { + Some(names) => Some( + opp::Config::::new() + .set_regulator_names(names)? + .set(dev.clone())?, + ), + _ => None, + }; + + // Get OPP-sharing information from "operating-points-v2" bindings. + let fallback = match opp::Table::of_sharing_cpus(dev.clone(), policy.cpus()) { + Ok(_) => false, + Err(e) => { + if e != ENOENT { + return Err(e); + } + + // "operating-points-v2" not supported. If the platform hasn't + // set sharing CPUs, fallback to all CPUs share the `Policy` + // for backward compatibility. + opp::Table::sharing_cpus(dev.clone(), policy.cpus()).is_err() + } + }; + + // Initialize OPP tables for all policy cpus. + // + // For platforms not using "operating-points-v2" bindings, we do this + // 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 unless + // it is -EPROBE_DEFER. + let mut opp_table = match opp::Table::from_of_cpumask(dev.clone(), policy.cpus()) { + Ok(table) => table, + Err(e) => { + if e == EPROBE_DEFER { + return Err(e); + } + + // The table is added dynamically ? + opp::Table::from_dev(dev.clone())? + } + }; + + // The OPP table must be initialized, statically or dynamically, by this point. + opp_table.opp_count()?; + + // Set sharing cpus for fallback scenario. + if fallback { + policy.set_all_cpus(); + opp_table.set_sharing_cpus(policy.cpus())?; + } + + let mut transition_latency = opp_table.max_transition_latency() as u32; + if transition_latency == 0 { + transition_latency = cpufreq::ETERNAL_LATENCY; + } + + let freq_table = opp_table.to_cpufreq_table()?; + let clk = 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)?; + + Ok(Arc::new( + CPUFreqDTDevice { + opp_table, + token, + freq_table, + 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 = match policy.data::() { + Some(data) => data, + None => return Err(ENOENT), + }; + + let freq = data.freq_table.freq(index.try_into().unwrap())? as u64; + 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 = device::Data, ()>; + +struct CPUFreqDTDriver; + +impl platform::Driver for CPUFreqDTDriver { + type Data = 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 data = Arc::::from(kernel::new_device_data!( + cpufreq::Registration::new(), + (), + "CPUFreqDT::Registration" + )?); + let flags = cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV; + let boost = true; + + data.registrations() + .ok_or(ENXIO)? + .as_pinned_mut() + .register(c_str!("cpufreq-dt"), (), flags, boost)?; + + pr_info!("CPUFreq DT driver registered\n"); + + Ok(data) + } +} + +module_platform_driver! { + type: CPUFreqDTDriver, + name: "cpufreq_dt", + author: "Viresh Kumar ", + description: "Generic CPUFreq DT driver", + license: "GPL v2", +}