From patchwork Tue Jul 30 10:26:58 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 815561 Received: from mail-pj1-f51.google.com (mail-pj1-f51.google.com [209.85.216.51]) (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 9C93019D8B1 for ; Tue, 30 Jul 2024 10:27:24 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.51 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335246; cv=none; b=eEUeqEkK+8eLxO2cmzAjsdZNWM/ZvDPSclQHwEg12JhdfdmH2QLSDjPdXlUTkgzYKRnBreJO55J3ksXK4S/eEYvwOc8O/yt0OIFKLthPveep1S3EWfS2duATpzjvbXo1SC8tGXMLJsY/fNdm+TziYCMv6o2DfKUucpuWB26Uxa0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335246; c=relaxed/simple; bh=ZHAaLoaHcc60AeP58pL4+JTmmO9l4+owKxpIqNbTLe8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=k1/HE2wvaBy9vhGWrF2HE3ws+vfwrFtw+kLB2NfxxIc5HwLG+A4kov74tU7h1Iv0aKmm8Skcst7KBUfT74DG0kBvx7WbeFF5rdzJ8UzgNdcMumAxezgYEKaNdG9GE05HiBKIqJGWzoWjck+4f3JDJXMSQsUpTCRpJ4c1iUy2dnM= 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=Jw42Fgmc; arc=none smtp.client-ip=209.85.216.51 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="Jw42Fgmc" Received: by mail-pj1-f51.google.com with SMTP id 98e67ed59e1d1-2cfd1b25aaaso115037a91.0 for ; Tue, 30 Jul 2024 03:27:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1722335244; x=1722940044; 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=oh4w9fMremB+/ZgxAOcXwOPCcleTD6cOMjoa5EUy0w4=; b=Jw42Fgmcps/1nM8Hl0lnigKgIVu5FzlIv3VfqiVdcEhfiPzo1S49HM58f4Fzq3KfT5 P4n4oDEld7e8nE1IO/d5FkAkSaRqawBWY7e0ZTX6nPvPWWjmlcICQDN7vJxJOGuW7rkP fGi4FePphSaiB1gs5yilZa996HFlPxuliiX50/sKQW9QIsvMT2VmU8rHkQZt1QeFCLSD cR1+G9YqhE1vRVEQ7EIKS3o76uAS+QeVMfgqErKOoVJUKzaOku9NXU9IwD/9vf7mdber b1POTsAB/sVeSCFYZF62WP9ZfPwEZ7/GkAURRWbpTB2IAa/ZXrJRjwltxEFglxxC/nIL dNCQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722335244; x=1722940044; 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=oh4w9fMremB+/ZgxAOcXwOPCcleTD6cOMjoa5EUy0w4=; b=EClt5n6xj16CNzHKi9YeOcDdASgLck0WKMW+NAVs6IMFv4k2VrbXUGAQF0DYPd8kco xpFpquPB2O24pRAuyTMAbssDKYoaFlFg2mgIHPapVJh5wiDd4fagold5M6o6pE++A23J s/UrZ73g1FXPWvStNm4N7xigLQK922j9lz1mN7W23/zlzDF7zp8NyzM9pi3TP19C4QOe oKQ8aW057GjeLtygFE0/UIVccjkI0X+4Dyk2y5Aa/dUzErZU+El2+XVu9k/+z4UEbkHa kJLbqzBuoIGS9P3GAXUGP4jRArtrUBLBO/JG1UiU+1wFjXddb0eQBHRpLhie4FoyZVK2 xJBw== X-Forwarded-Encrypted: i=1; AJvYcCU30GfpAjcZappxMQjEFpAgxVRANXKnwlGyuj50j/vyIWavbTsQds0yeg0SJn5h1KwJwHvfoRKGftudBgGksrFlxNcsALQFYus= X-Gm-Message-State: AOJu0YxpYIi1tvSfzB7OQ6H1/vLx+mpBioyBy40sDBiU6c1RW6z1vL5A MjyZmnwL5XtOuMauH05KX0QauSbh91qLqO8ml7tuCVI7yQQL72LopBjVSjpE3No= X-Google-Smtp-Source: AGHT+IFFm7hRsTQa4HhQ+xPpSFHiCso1o2VoRNNPM3Z4KPvk2H+vpA/7gdlzGAQfQoXGRZIzCBGvxg== X-Received: by 2002:a17:90a:d30a:b0:2c9:3370:56e3 with SMTP id 98e67ed59e1d1-2cf7e831e5dmr8763504a91.34.1722335243841; Tue, 30 Jul 2024 03:27:23 -0700 (PDT) Received: from localhost ([122.172.84.129]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-2cf28ca1058sm10253136a91.31.2024.07.30.03.27.22 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 30 Jul 2024 03:27:22 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , 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 , Viresh Kumar , Nishanth Menon , Stephen Boyd Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , 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: [PATCH V5 1/8] rust: Add initial bindings for OPP framework Date: Tue, 30 Jul 2024 15:56:58 +0530 Message-Id: <5f97e6fba01f85bacb15bc2a1149625760ec690a.1722334569.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 Operating performance points (OPP) core. This adds bindings for `struct dev_pm_opp` and `struct dev_pm_opp_data` to begin with. Reviewed-by: Manos Pitsidianakis Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 2 + rust/kernel/opp.rs | 189 ++++++++++++++++++++++++++++++++ 4 files changed, 193 insertions(+) create mode 100644 rust/kernel/opp.rs diff --git a/MAINTAINERS b/MAINTAINERS index d6c90161c7bf..1ffcf68b5566 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -16861,6 +16861,7 @@ F: Documentation/devicetree/bindings/opp/ F: Documentation/power/opp.rst F: drivers/opp/ F: include/linux/pm_opp.h +F: rust/kernel/opp.rs OPL4 DRIVER M: Clemens Ladisch diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index d8b54b9fa4d0..1bf8e053c8f4 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 3bf1089b87a3..e309d7774cbd 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -45,6 +45,8 @@ #[cfg(CONFIG_NET)] pub mod net; pub mod of; +#[cfg(CONFIG_PM_OPP)] +pub mod opp; pub mod platform; pub mod prelude; pub mod print; diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs new file mode 100644 index 000000000000..dec832edec9b --- /dev/null +++ b/rust/kernel/opp.rs @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Operating performance points. +//! +//! This module provides bindings for interacting with the OPP subsystem. +//! +//! C header: [`include/linux/pm_opp.h`](srctree/include/linux/pm_opp.h) + +use crate::{ + bindings, + device::Device, + error::{code::*, to_result, Result}, + types::{ARef, AlwaysRefCounted, Opaque}, +}; + +use core::ptr; + +/// Dynamically created Operating performance point (OPP). +pub struct Token { + dev: ARef, + freq: u64, +} + +impl Token { + /// Adds an OPP dynamically. + pub fn new(dev: &ARef, mut data: Data) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_add_dynamic(dev.as_raw(), &mut data.0) })?; + Ok(Self { + dev: dev.clone(), + freq: data.freq(), + }) + } +} + +impl Drop for Token { + fn drop(&mut self) { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_remove(self.dev.as_raw(), self.freq) }; + } +} + +/// Equivalent to `struct dev_pm_opp_data` in the C Code. +#[repr(transparent)] +pub struct Data(bindings::dev_pm_opp_data); + +impl Data { + /// Creates new instance of [`Data`]. + pub fn new(freq: u64, u_volt: u64, level: u32, turbo: bool) -> Self { + Self(bindings::dev_pm_opp_data { + turbo, + freq, + u_volt, + level, + }) + } + + /// Adds an OPP dynamically. The OPP is freed once the [`Token`] gets freed. + pub fn add_opp(self, dev: &ARef) -> Result { + Token::new(dev, self) + } + + fn freq(&self) -> u64 { + self.0.freq + } +} + +/// Operating performance point (OPP). +/// +/// Wraps the kernel's `struct dev_pm_opp`. +/// +/// The pointer to `struct dev_pm_opp` is non-null and valid for the lifetime of the `OPP` +/// instance. +/// +/// # Invariants +/// +/// Instances of this type are reference-counted. The reference count is incremented by the +/// `dev_pm_opp_get()` function and decremented by `dev_pm_opp_put`. The Rust type `ARef` +/// represents a pointer that owns a reference count on the OPP. +/// +/// A reference to the `OPP`, `&OPP` isn't refcounted by the Rust code. + +#[repr(transparent)] +pub struct OPP(Opaque); + +// SAFETY: It's OK to send the ownership of `OPP` across thread boundaries. +unsafe impl Send for OPP {} + +// SAFETY: It's OK to access `OPP` through shared references from other threads because we're +// either accessing properties that don't change or that are properly synchronised by C code. +unsafe impl Sync for OPP {} + +// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted. +unsafe impl AlwaysRefCounted for OPP { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference means that the refcount is nonzero. + unsafe { bindings::dev_pm_opp_get(self.0.get()) }; + } + + unsafe fn dec_ref(obj: ptr::NonNull) { + // SAFETY: The safety requirements guarantee that the refcount is nonzero. + unsafe { bindings::dev_pm_opp_put(obj.cast().as_ptr()) } + } +} + +impl OPP { + /// Creates an owned reference to a [`OPP`] from a valid pointer. + /// + /// The refcount is incremented by the C code and will be decremented by `dec_ref()` when the + /// ARef object is dropped. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and the OPP's refcount is incremented. The + /// caller must also ensure that it doesn't explicitly drop the refcount of the OPP, as the + /// returned ARef object takes over the refcount increment on the underlying object and the + /// same will be dropped along with it. + pub unsafe fn from_raw_opp_owned(ptr: *mut bindings::dev_pm_opp) -> Result> { + let ptr = ptr::NonNull::new(ptr).ok_or(ENODEV)?; + + // SAFETY: The safety requirements guarantee the validity of the pointer. + Ok(unsafe { ARef::from_raw(ptr.cast()) }) + } + + /// Creates a reference to a [`OPP`] from a valid pointer. + /// + /// The refcount is not updated by the Rust API unless the returned reference is converted to + /// an ARef object. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for the duration of 'a. + pub unsafe fn from_raw_opp<'a>(ptr: *mut bindings::dev_pm_opp) -> Result<&'a Self> { + // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the + // duration of 'a. The cast is okay because `OPP` is `repr(transparent)`. + Ok(unsafe { &*ptr.cast() }) + } + + #[inline] + fn as_raw(&self) -> *mut bindings::dev_pm_opp { + self.0.get() + } + + /// Returns the frequency of an OPP. + pub fn freq(&self, index: Option) -> 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_raw(), 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_raw()) } + } + + /// 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_raw()) } + } + + /// 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_raw()) } + } + + /// Returns the required pstate of an OPP. + pub fn required_pstate(&self, index: u32) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_required_pstate(self.as_raw(), index) } + } + + /// Returns true if the OPP is turbo. + pub fn is_turbo(&self) -> bool { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_is_turbo(self.as_raw()) } + } +} From patchwork Tue Jul 30 10:26:59 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 815914 Received: from mail-pj1-f50.google.com (mail-pj1-f50.google.com [209.85.216.50]) (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 8233719DF98 for ; Tue, 30 Jul 2024 10:27:28 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.50 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335251; cv=none; b=RfeOS+EvlCqSY4gmZSirrIyPtTifTrkwqaBE1S6FI2Zbn8fUuB/uFkvqMFycReJwZRBUFnifjn20COm9cGb1UUOxPdf3e4a6cw67r4I1F5PFJ3Brk1vMGmZ3G7sC2/8fWvmiPQ6KebWnyIxg5kCOBMsQNXPQuYSgcR5RRXWPz7E= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335251; c=relaxed/simple; bh=YjNq75QgFeA7Yus4IxCVFfuEQI50uhXJwK9Os0w9Dag=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=RREAfW7y4VEx6gq4MCT4j+htaz8U4iF4eZQnXpKbpK1GPooTcaq2X8gVcybEu2bLexyyx9vfkTMHfa32JNaKqYWmkgjo0nmSmgv7PLmGmVFjGKwjYOQk0ov1H/DakM7gCfzZn+fiuVDc11wffUJCcj7fwmXipygEl+Ao4klsWbk= 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=BciqrHr9; arc=none smtp.client-ip=209.85.216.50 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="BciqrHr9" Received: by mail-pj1-f50.google.com with SMTP id 98e67ed59e1d1-2cb56c2c30eso2849471a91.1 for ; Tue, 30 Jul 2024 03:27:28 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1722335248; x=1722940048; 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=bwz/REpE+iNc1GUN5OnD3+R/RJ6eiupzXXvcQ/qHpdo=; b=BciqrHr91lRzL2/pJNfdjqRGRHN3JC5rmBCu+A7Fx5ozrMn8LGgr8k+0hzbLJH6WyJ dR+EBe/VTQxxaG1iy6N065ETVOcWE3m1I/6GQ7CllkayUjkySFUP5fqzJ1Om/XNicaNL y3IEcV43c/poIUZeO2vhGI1R0uz4XmJTaDfS0QE0/90xZnLSxGsCdsY5TF3kMrmsobeQ UI4YcwLyc8kI6N5kWo+PLH1aFtCEXIjnI9INWCW0g6A32/X3+1j7MXIRBQrk6Jr+R/9C ZVtBnL7kTSnu2HyHgvxBAq4W1EHVMQbAjzvXWBsEHi4KL3lcxJPveK7khRCt/t8a7o3I Vpew== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722335248; x=1722940048; 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=bwz/REpE+iNc1GUN5OnD3+R/RJ6eiupzXXvcQ/qHpdo=; b=jXzKByWOySXDR7kNlZJwkFyyN/lUT+65QPW+uux1lNBqcJHjxbi9b81XjJppRa9Lk7 NaZDF49nmVnUNmDj4MdbQL/jpXJg2Qf0TlY3z07q5evarCLmRSUSFILtpEzdBBWD2172 1yqE7/X0jsh1Mb7A/zKt99smaIE+vd6TjNNoToqb3NuM9sTexDy/V2HzEwgfafsXCjIs tS8E7BXijIJTpQociZxcOEW1tYflYlgFNl0w4wA4xrOk9NJnk2+uecTJuxjOMzkaNd0G OsXVLUimQXpyp86O2PHzF4U5saYDUfxl7lCPLp7oUV4hJljgzbmIMXkbQJrvoL9dnHfQ TJCA== X-Forwarded-Encrypted: i=1; AJvYcCVUI8kXxT58SSwj2n6vF+CQMiiFHYiXn4kKKi6bjI0UNfkgLPkk5GZtBPK4f/ZtX/zruXzvwGpH4SH+b62MM0BdsHvataAbzvQ= X-Gm-Message-State: AOJu0YxTyaDxtQwbHfjjITLfFjssy3HGgb2en9qqQG0st8HM3Uq/QLaB pNE7L3mcdONAtJAF0pArj+zCfFPP1tutDgxVvHmBmKlR5VVyfwonk15Wrj9mxS4= X-Google-Smtp-Source: AGHT+IGHg8nZg75/O6cvErBFY7boVJ447cvylF1yQqdO3h+yR6dx+9LQr6FsTewmDGh7fUQICJviYQ== X-Received: by 2002:a17:90a:4e4c:b0:2c8:2cd1:881b with SMTP id 98e67ed59e1d1-2cfcabb451cmr2495856a91.20.1722335247705; Tue, 30 Jul 2024 03:27:27 -0700 (PDT) Received: from localhost ([122.172.84.129]) by smtp.gmail.com with ESMTPSA id 41be03b00d2f7-7a9f9ec7acdsm8543002a12.66.2024.07.30.03.27.26 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 30 Jul 2024 03:27:27 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd , 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 , 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: [PATCH V5 2/8] rust: Extend OPP bindings for the OPP table Date: Tue, 30 Jul 2024 15:56:59 +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 | 382 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 381 insertions(+), 1 deletion(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index dec832edec9b..c3433b0d8221 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -8,8 +8,9 @@ use crate::{ bindings, + cpumask::Cpumask, device::Device, - error::{code::*, to_result, Result}, + error::{code::*, from_err_ptr, to_result, Error, Result}, types::{ARef, AlwaysRefCounted, Opaque}, }; @@ -67,6 +68,385 @@ fn freq(&self) -> u64 { } } +/// 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. +/// +/// Wraps the kernel's `struct opp_table`. +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of the `Table`. +pub struct Table { + ptr: *mut bindings::opp_table, + dev: ARef, + em: bool, + of: bool, + cpumask: Option, +} + +// SAFETY: It is okay to send ownership of `Table` across thread boundaries. +unsafe impl Send for Table {} + +// SAFETY: It's OK to access `Table` through shared references from other threads because we're +// either accessing properties that don't change or that are properly synchronised by C code. +unsafe impl Sync for Table {} + +impl Table { + /// Creates a new OPP table instance from raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null. + unsafe fn from_raw_table(ptr: *mut bindings::opp_table, dev: &ARef) -> Self { + // SAFETY: By the safety requirements, ptr is valid and its refcount will be incremented. + unsafe { bindings::dev_pm_opp_get_opp_table_ref(ptr) }; + + Self { + ptr, + dev: dev.clone(), + em: false, + of: false, + cpumask: None, + } + } + + /// Find OPP table from device. + pub fn from_dev(dev: &ARef) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. Refcount of the OPP table is incremented by the C code. + 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 by the C code. + 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 earlier from `from_of` earlier, it is safe to drop + // the same now. + unsafe { bindings::dev_pm_opp_of_remove_table(self.dev.as_raw()) }; + } + + /// Add device tree based OPP table for CPU devices. + #[cfg(CONFIG_OF)] + pub fn from_of_cpumask(dev: &ARef, cpumask: &Cpumask) -> 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)?; + + let mut mask = Cpumask::new()?; + cpumask.copy(&mut mask); + table.cpumask = Some(mask); + + Ok(table) + } + + // Remove device tree based OPP table for CPU devices. + #[cfg(CONFIG_OF)] + fn remove_of_cpumask(&self, cpumask: Cpumask) { + // SAFETY: The cpumask is valid and we took the reference from `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: &Device, cpumask: &mut 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(&mut self, 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()) + })?; + + if let Some(mask) = self.cpumask.as_mut() { + // Update the cpumask as this will be used while removing the table. + cpumask.copy(mask); + } + + Ok(()) + } + + /// Gets sharing CPUs from Device tree. + #[cfg(CONFIG_OF)] + pub fn of_sharing_cpus(dev: &Device, cpumask: &mut Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `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: &OPP) -> 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_raw()) }) + } + + /// 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_raw_opp_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_raw_opp_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_raw_opp_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) -> 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.take() { + self.remove_of_cpumask(cpumask); + } + } + } +} + /// Operating performance point (OPP). /// /// Wraps the kernel's `struct dev_pm_opp`. From patchwork Tue Jul 30 10:27:00 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 815560 Received: from mail-pl1-f176.google.com (mail-pl1-f176.google.com [209.85.214.176]) (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 EF6B419E806 for ; Tue, 30 Jul 2024 10:27:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.176 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335254; cv=none; b=EevSdGWV0EbCYrGwC3BT//GUVxRrxiTaGaLs4VsZvQ+7GSYJje1ZisAVq94b6e5O5RzrKdqGlqGSXYO4cJ/g4sAVdyFUmfA8tKtqp0huGaJ90Jui7boCp/xTUpLNUeYQSbyQ5eM6PudlOtMwDjelU3fFDcAjn9DoFbUzJqg6NKM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335254; c=relaxed/simple; bh=OzPunyqGE/5TW6uLHohmOvJN9eUza1Duw/uCRtbeQoQ=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=g876X16/zGaXPPhFG34DANycEC8fk6K2C5EPBuPGpA5ggTioRU4ipAGpZOqfxQMHLdmX9l6WOb3Q6Ua5v7NMDyWxUxOIbtTMZVFnQoTu9w477Hgt2MD4hbF4GFJqZHZl6ELsOHmnzDpj6lYJ+EMg33sGKYTHwlsBvkkYVJNxxag= 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=eT4TvYap; arc=none smtp.client-ip=209.85.214.176 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="eT4TvYap" Received: by mail-pl1-f176.google.com with SMTP id d9443c01a7336-1fd70ba6a15so28713665ad.0 for ; Tue, 30 Jul 2024 03:27:32 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1722335252; x=1722940052; 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=CeU9Cta51JYSW0ONrM7wbRe9y3vgozaJuy5zKjtbdGM=; b=eT4TvYapOoNF9J+4pb3lx387E27teVIcvVRd00TNs1Tsg6YhEjVAVBXs6qNuW/En+5 UOajhe5XTxNXweThFHbTBRIrJx6te4GMJg3Hq0aYcgeYrtt5wyEdmG3b/itmtvZMHbZP Vu4JL01X6Jmmw3uuyt4r3L4tdGOYaaBMiXaOmL4HtI2o6t3AHi0melZsxzMadxRoKotQ fD9Vk1PEgJuXbO7zvWYYYtV/ax/2+kMIPeBm2UAfbpd86NOc5F6fqSkmLkZaveWI6tpD YGxGhgP880TnMb/FeYo12TxfONtMC+Z24/QZBMmD+xciwyCY/Lb9Hi0YrsA7jXMEGdmf pbQQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722335252; x=1722940052; 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=CeU9Cta51JYSW0ONrM7wbRe9y3vgozaJuy5zKjtbdGM=; b=sOUPMysF3LjqgpgQHdhOS3UlUzjombN/SuL+Z85rSjgYu0gI2EIpKAnlc/Hr5N8mcU m74oSH6s7vAJWNt0vXoAQQm8jGZQFtJAbshTug6lfGgtFqLJDfMs2z+zmITSggc+jfPk 3IlXwWDGRtnt+c+7ouPm5DJN01aMv7H1d5X59boI1IIqIxKXDV/ZdZHNGp9eiQoMpT6G KzuTIyuhQ6Z5kEsTeYlkaEYq9Masul3w+gHsAmAFfI5N4u2kMcvfTd9sG+ZmBRs9rwIj Ttl85DDE3xz3wng/0SUpItg2IeTyt2fOPTcXoqgoxujEsKYtD2zUQAudYIdZXjo+tz1J TdKg== X-Forwarded-Encrypted: i=1; AJvYcCWhcwmCkmUJB7tk417bLOPK1jcXCakGoyxIXNft9DuF04564Ifsfp32JDXgmjgJjYLsV0jTeNV3uu/uxgB4Ntd0OkNBLkXfcyI= X-Gm-Message-State: AOJu0YxULz9E/o6Isd10GEHGXvCttlhIWgqzGr8mK1BcghaotJtByBJM IZHUaLOtSN9cy241z09K2y2RRcukr/jd8HnoUFY3FL2Tpmbqkw3i6ybtnjoTVGk= X-Google-Smtp-Source: AGHT+IHwAyVe6AgJ9Pe0S6EytajK8Bli6aq5tXPwFgiIY0LpnOjDuZ6s1Rr/Syjch7+m5c9f/vtN0w== X-Received: by 2002:a17:903:1245:b0:1fd:70c4:8389 with SMTP id d9443c01a7336-1ff047eaea7mr110395435ad.7.1722335252007; Tue, 30 Jul 2024 03:27:32 -0700 (PDT) Received: from localhost ([122.172.84.129]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1fed7ee115dsm98284695ad.143.2024.07.30.03.27.30 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 30 Jul 2024 03:27:31 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd , 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 , 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: [PATCH V5 3/8] rust: Extend OPP bindings for the configuration options Date: Tue, 30 Jul 2024 15:57:00 +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 OPP core configuration options. Reviewed-by: Manos Pitsidianakis Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 301 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 299 insertions(+), 2 deletions(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index c3433b0d8221..113652448056 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -10,11 +10,28 @@ bindings, cpumask::Cpumask, device::Device, - error::{code::*, from_err_ptr, to_result, Error, Result}, + error::{code::*, from_err_ptr, from_result, to_result, Error, Result, VTABLE_DEFAULT_ERROR}, + prelude::*, + str::CString, types::{ARef, AlwaysRefCounted, Opaque}, }; -use core::ptr; +use core::{ffi::c_char, marker::PhantomData, ptr}; + +use macros::vtable; + +// Creates a null-terminated slice of pointers to Cstrings. +fn to_c_str_array(names: &[CString]) -> Result> { + // Allocated a null-terminated vector of pointers. + let mut list = 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) +} /// Dynamically created Operating performance point (OPP). pub struct Token { @@ -79,6 +96,286 @@ 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: &Device, _table: &Table, _opp: &OPP, _scaling_down: bool) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Called by the OPP core to configure OPP regulators. + fn config_regulators( + _dev: &Device, + _opp_old: &OPP, + _opp_new: &OPP, + _data: *mut *mut bindings::regulator, + _count: u32, + ) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } +} + +/// Config token returned by the C code. +pub struct ConfigToken(i32); + +impl Drop for ConfigToken { + fn drop(&mut self) { + // SAFETY: Its safe to return the configuration token number previously received from the C + // code. + unsafe { bindings::dev_pm_opp_clear_config(self.0) }; + } +} + +/// Equivalent to `struct dev_pm_opp_config` in the C Code. +#[derive(Default)] +pub struct Config { + clk_names: Option>, + prop_name: Option, + regulator_names: Option>, + genpd_names: Option>, + supported_hw: Option>, + required_devs: Option>>, + _data: PhantomData, +} + +impl Config { + /// Creates a new instance of [`Config`]. + pub fn new() -> Self { + Self { + clk_names: None, + prop_name: None, + regulator_names: None, + genpd_names: None, + supported_hw: None, + required_devs: None, + _data: PhantomData, + } + } + + /// Initializes clock names. + pub fn set_clk_names(mut self, names: Vec) -> Result { + // Already configured. + if self.clk_names.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.clk_names = 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: &Device) -> Result { + let (_clk_list, clk_names) = match &self.clk_names { + Some(x) => { + let list = to_c_str_array(x)?; + let ptr = list.as_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null()), + }; + + let (_regulator_list, regulator_names) = match &self.regulator_names { + Some(x) => { + let list = to_c_str_array(x)?; + let ptr = list.as_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null()), + }; + + let (_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, + // SAFETY: 'opp_table' is guaranteed by the C code to be valid. + &unsafe { Table::from_raw_table(opp_table, &dev) }, + // SAFETY: 'opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp(opp)? }, + scaling_down, + ) + .map(|_| 0) + }) + } + + // Config's 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_raw_opp(old_opp)? }, + // SAFETY: 'new_opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp(new_opp)? }, + regulators, + count, + ) + .map(|_| 0) + }) + } +} + /// Operating performance point (OPP) table. /// /// Wraps the kernel's `struct opp_table`. From patchwork Tue Jul 30 10:27:01 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 815913 Received: from mail-pl1-f171.google.com (mail-pl1-f171.google.com [209.85.214.171]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 82D1F19EEAE for ; Tue, 30 Jul 2024 10:27:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335259; cv=none; b=Ait56F6dmXMxHNPphOoGv9WkAFoD/6x6Sr1/msOO2STZENEYgru4l2muOVi/m48pqKLE0Qy4qvhtSYHCa5WUH0jO4Jl9l7QG4HJdv2DGfescNkd9ongCRGk+TcKDiotyyL5zAYqHnFR/Ip1//Gwynf4arCn7cYKv0nCQSu/e71k= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335259; c=relaxed/simple; bh=i43nnzkO6YM/OZibPUqU5csESWwD7dclh97iNrzDtkY=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=ZvHAP8TDY2xCs1xWG51NddrBpCtugq3TWFrky1yNjWa/2osNiI8p+mJl4Wy0dkY+DEbbUCo9XqfpdjCp77BIRvt1JoKQHpNr4E8NFzDjaQciKgww7EMKNB1gK6+8BaxBxTnAomsc9/SNXjjKE9htAaT8r4O8ZbZ9Nn6kUAytk0k= 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=cDz5phVO; arc=none smtp.client-ip=209.85.214.171 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="cDz5phVO" Received: by mail-pl1-f171.google.com with SMTP id d9443c01a7336-1fc47abc040so25647925ad.0 for ; Tue, 30 Jul 2024 03:27:37 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1722335257; x=1722940057; 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=XUgOwF4VOfSZwujecU4b6ilYD3YLuL6K5yX18+fiv0c=; b=cDz5phVOYmDGv7Xj4HQ7OsXA3ZQjps7uyr4HGlysu0PxyXFLy5j5SJS0hVZEw7qEMW fpkarA4iKdjOsXkG6FxH675swHIvkYJwfjDI67jXA17zbc0D8xqhy7FqoacHALIGIiQn 7povoLgq3dhSvcnVSYO5mCdSSC0XDO4S+dAkXpvLfZTCGVXOT36ZfeSEetybFO+Lc4gf 27/3x7apaqYENmE+6Z7S7c4JnM3eJglXj4GQi+w7Qm9LzRXjPEHDXvQ9ZTSYZRQH3l/t g7duZEXYuZx2EQ3dIhIkpNW+YCV1ll2EXOiBf0rH805o3QRgRn6O+hpfuo24dMcs+l8M byYw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722335257; x=1722940057; 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=XUgOwF4VOfSZwujecU4b6ilYD3YLuL6K5yX18+fiv0c=; b=bIzsqmEaQ3nMXiok1UTStkzXvd+N8R7FQNIUEHBoX0VNG9wZsJ2VEsxv+G0m7IbiCf QXbQDukUk0wHwmxFpGsaRF0VyBC67fcaQJRSK+5sOwwJmdYWunfQgGOruMl/aW9+ABtl 6czwS4l+I7C0ok3Peg9ujBNiHwXxWFNyT6VpdkwRpWV8N8+Qp33ksHeo97wOXOkBOkqJ QJiBfD0DzkUCuvst9ZbOAG2jUYOMDXeR+xBRWo3bsbTGsHcpAiHjOFIYxWksdrCBk/v4 e0OY0yp7Qb1Yt72PAxp7eMjMC055Zj6OatGj9CSd+q/6kPZwMzqz8nFoBKQ3FIADFK3g e7EQ== X-Gm-Message-State: AOJu0YwxfRKjauBoyAhPGC/0pE5nidsuKU0NYzoc4M5hFZHllYtjwGSK Su3LMcq3LfJlWpKwEImFc1XvwSins4wAA/nEIz7nCAqxRckvwIU27szwfMWI7Nw= X-Google-Smtp-Source: AGHT+IGyeCkI/vw09RSM/jqgLi6A8Tm2DaqJkfOD/75KWCmJVQt8yEo+MOtfYNMOulG7wxDLrNtnVA== X-Received: by 2002:a17:903:1cf:b0:1fa:128c:4315 with SMTP id d9443c01a7336-1ff04842046mr90590795ad.44.1722335256714; Tue, 30 Jul 2024 03:27:36 -0700 (PDT) Received: from localhost ([122.172.84.129]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-1fed7ee6a1esm98638455ad.164.2024.07.30.03.27.35 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 30 Jul 2024 03:27:36 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , 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 , Viresh Kumar 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: [PATCH V5 4/8] rust: Add initial bindings for cpufreq framework Date: Tue, 30 Jul 2024 15:57:01 +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 cpufreq core. This adds basic bindings for cpufreq flags, relations and cpufreq table. Reviewed-by: Manos Pitsidianakis Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers.c | 15 ++ rust/kernel/cpufreq.rs | 254 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 5 files changed, 273 insertions(+) create mode 100644 rust/kernel/cpufreq.rs diff --git a/MAINTAINERS b/MAINTAINERS index 1ffcf68b5566..22cbbb792dcf 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5657,6 +5657,7 @@ F: drivers/cpufreq/ F: include/linux/cpufreq.h F: include/linux/sched/cpufreq.h F: kernel/sched/cpufreq*.c +F: rust/kernel/cpufreq.rs F: tools/testing/selftests/cpufreq/ CPU HOTPLUG diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 1bf8e053c8f4..bee2b6013690 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 7a15d0ebe49b..3b2850a11859 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -357,6 +358,20 @@ void rust_helper_free_cpumask_var(cpumask_var_t mask) EXPORT_SYMBOL_GPL(rust_helper_free_cpumask_var); #endif +#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..0751ad9459e2 --- /dev/null +++ b/rust/kernel/cpufreq.rs @@ -0,0 +1,254 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU frequency scaling. +//! +//! This module provides bindings for interacting with the cpufreq subsystem. +//! +//! C header: [`include/linux/cpufreq.h`](srctree/include/linux/cpufreq.h) + +use crate::{ + bindings, + error::{code::*, to_result, Result}, + prelude::*, +}; + +use core::{ + pin::Pin, +}; + +/// Default transition latency value. +pub const ETERNAL_LATENCY: u32 = 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_raw_policy_data(ptr: *mut bindings::cpufreq_policy_data) -> Self { + Self(ptr) + } + + /// Returns the raw pointer to the C structure. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_policy_data { + self.0 + } + + /// Provides a wrapper to the generic verify routine. + pub fn generic_verify(&self) -> Result<()> { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it now. + to_result(unsafe { bindings::cpufreq_generic_frequency_table_verify(self.as_raw()) }) + } +} + +/// Builder for the `struct cpufreq_frequency_table` in the C code. +#[repr(transparent)] +#[derive(Default)] +pub struct TableBuilder { + entries: Vec, +} + +impl TableBuilder { + /// Creates new instance of [`TableBuilder`]. + pub fn new() -> Self { + Self { + entries: Vec::new(), + } + } + + /// Adds a new entry to the table. + pub fn add(&mut self, frequency: u32, flags: u32, driver_data: u32) -> Result<()> { + // Adds new entry to the end of the vector. + Ok(self.entries.push( + bindings::cpufreq_frequency_table { + flags, + driver_data, + frequency, + }, + GFP_KERNEL, + )?) + } + + /// Creates [`Table`] from [`TableBuilder`]. + pub fn into_table(mut self) -> Result { + // Add last entry to the table. + self.add(bindings::CPUFREQ_TABLE_END as u32, 0, 0)?; + Table::from_builder(self.entries) + } +} + +/// A simple implementation of the cpufreq table, equivalent to the `struct +/// cpufreq_frequency_table` in the C code. +pub struct Table { + #[allow(dead_code)] + // Dynamically created table. + entries: Option>>, + + // Pointer to the statically or dynamically created table. + ptr: *mut bindings::cpufreq_frequency_table, + + // Number of entries in the table. + len: usize, +} + +impl Table { + /// Creates new instance of [`Table`] from [`TableBuilder`]. + fn from_builder(entries: Vec) -> 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. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_frequency_table { + self.ptr + } + + /// Returns `frequency` at index in the [`Table`]. + pub fn freq(&self, index: usize) -> Result { + self.validate(index)?; + + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `self` and `index` is + // also validated before this and is guaranteed to be within 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 e309d7774cbd..77348fc33803 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -30,6 +30,8 @@ pub mod alloc; mod build_assert; pub mod clk; +#[cfg(CONFIG_CPU_FREQ)] +pub mod cpufreq; pub mod cpumask; pub mod device; pub mod device_id; From patchwork Tue Jul 30 10:27:02 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 815559 Received: from mail-oa1-f46.google.com (mail-oa1-f46.google.com [209.85.160.46]) (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 9212D19F466 for ; Tue, 30 Jul 2024 10:27:41 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.46 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335263; cv=none; b=ZFrcpJWlLCV33NGeCVpZDHEVUUSkCq1a9jk1lSEqlVfRttNRObuMjn9oQfEKCAfVfCWF5ueK5gPBRNNP4KcM72Xe5azYz+ZMndFQYRgiPOW8C4BGB7l4An7cH5CXu+vR3bofJG/ygHSqEdEgblWEhuyB7Uepla6HvTuKXn43fww= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335263; c=relaxed/simple; bh=JrIqdLXOKsgLnmkFZ98ZZ7V7b3MO61ztZBHVJHMyFBk=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=XzDlFH+fgUMGH+NGe0UtUN2ByBEIzHBXZrJfvq5O8SnVnQJAldQa8EZvoaqeYrybMQlTSjnlhgOJTI3ZpqzGozY8VfaqjmzAzqRRYwxbhgFd7+jykbR9YnX/6HWomyqVaAscH1gOHGDyKxwEEgavoqKt/EHgmk/wYSArKAkVdp0= 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=nu9+uRbJ; arc=none smtp.client-ip=209.85.160.46 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="nu9+uRbJ" Received: by mail-oa1-f46.google.com with SMTP id 586e51a60fabf-2611da054fbso2798886fac.1 for ; Tue, 30 Jul 2024 03:27:41 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1722335260; x=1722940060; 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=ZiAYeNUaYtfs4MtrCjwt6UV709MtWKglHtY8sLRknhk=; b=nu9+uRbJU/iEDp+elVp+63dY+es9Lz7K+1JoifApQwoy2YX1EjRtYPKa9Uyr5pPjzx aPZIeDa1gB/3HEVzYpKUxYXV4WgJ+VGN5p7nentnw9LmXiYTbsBvlaPZgzuSyTa6lje2 zTLrhBHtTPAdSm2l7tbP0PJUkl4OFQq2rZQZniBMmvTipldeI0AB8A8Wh9jhuCLemysz x63nKuBV8GuaarNQdM6EIgkYE6OrmMPesb1CXaPdOXsF40tdj5DQL4HCNjDMid1W5OJT 2HgotLfSenotKx/mF1bgI5+RkRxRbCK4yoUoQUi7IVBr/FawXoaQ9rkixKzDitI9aEu5 /y1g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722335260; x=1722940060; 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=ZiAYeNUaYtfs4MtrCjwt6UV709MtWKglHtY8sLRknhk=; b=AoBKAJkHlyIyXH1vwT0I7big/Sd+cywnfRuDPMPDqzC3mwBKIGu5S7r+XT4HrDirW9 6hgBj0/xJKggWpO1y/JDpLwet4Sltds6nIQvyduxsiVDll3LiOC0EGKIQsNYSCB36t7L P5d0Ai8lx+vgFsOOTquUBuEI8uy/jQJ8F41rj/Tfx746xkXhXcNZSe/CiIFJR8NDaGjL Djj1v+UN7GpC0UiVpg0ZcymCMbqNJDpCZPfCg9PUM/VylA6TeMH8ABDp+0/lMTnX5lN5 8HoKz5L0J3Ws9IarA9V6BfZSGrw985gleZniFGzGBX6ou9hIOaMuZeIaC+S+xolQC4+6 EOww== X-Gm-Message-State: AOJu0YyWIgQPuDTHlxxFyL+z7nw8Xh/6yIsK/zxLmEgdRRAeurHz36qX ntcL2AiJQgNsG++EIa0pKtTLLGJrmKDBwwrVKhOc3GZSHYcAnyooIb/kjky7ND4= X-Google-Smtp-Source: AGHT+IFMUUfWshqb98OirQmMVR3VDQ0gY4mGjIcFohc4LBShIVNWKoOjK2OgKRj/KiUFGee5tkh4kw== X-Received: by 2002:a05:6870:1494:b0:261:9fc:16b9 with SMTP id 586e51a60fabf-267d4f03468mr14789604fac.33.1722335260506; Tue, 30 Jul 2024 03:27:40 -0700 (PDT) Received: from localhost ([122.172.84.129]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-70ead8225f4sm8408044b3a.98.2024.07.30.03.27.39 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 30 Jul 2024 03:27:40 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , 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: [PATCH V5 5/8] rust: Extend cpufreq bindings for policy and driver ops Date: Tue, 30 Jul 2024 15:57:02 +0530 Message-Id: <62c46a0853511f6606003e44e6692acac525a63a.1722334569.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 the cpufreq bindings with bindings for cpufreq policy and driver operations. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 315 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 313 insertions(+), 2 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 0751ad9459e2..d58bb0bbaad4 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -7,15 +7,20 @@ //! C header: [`include/linux/cpufreq.h`](srctree/include/linux/cpufreq.h) 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::ForeignOwnable, }; use core::{ pin::Pin, + ptr::self, }; +use macros::vtable; + /// Default transition latency value. pub const ETERNAL_LATENCY: u32 = bindings::CPUFREQ_ETERNAL as u32; @@ -252,3 +257,309 @@ pub fn data(&self, index: usize) -> Result { Ok(unsafe { (*self.ptr.add(index)).driver_data }) } } + +/// Equivalent to `struct cpufreq_policy` in the C code. +pub struct Policy { + ptr: *mut bindings::cpufreq_policy, + put_cpu: bool, + cpumask: cpumask::Cpumask, +} + +impl Policy { + /// Creates a new instance of [`Policy`]. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null. + pub unsafe fn from_raw_policy(ptr: *mut bindings::cpufreq_policy) -> 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::from_raw((*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_raw_policy(ptr) }; + policy.put_cpu = true; + Ok(policy) + } + + /// Raw pointer to the underlying cpufreq policy. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_policy { + self.ptr + } + + fn as_ref(&self) -> &bindings::cpufreq_policy { + // SAFETY: By the type invariants, we know that `self` owns a 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_raw()) }) + } + + /// Provides a wrapper to the generic get routine. + pub fn generic_get(&self) -> Result { + // SAFETY: By the type invariants, we know that `self` owns a 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_raw()) }; + } + + /// Gets raw pointer to cpufreq policy's CPUs mask. + pub fn cpus(&mut self) -> &mut cpumask::Cpumask { + &mut self.cpumask + } + + /// Sets clock for a cpufreq policy. + pub fn set_clk(&mut self, dev: &Device, name: Option<&CStr>) -> Result { + let clk = clk::Clk::new(dev, name)?; + self.as_mut_ref().clk = clk.as_raw(); + Ok(clk) + } + + /// Allows frequency switching code to run on any CPU. + pub fn set_dvfs_possible_from_any_cpu(&mut self) -> &mut Self { + self.as_mut_ref().dvfs_possible_from_any_cpu = 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.is_null() { + return Err(EINVAL); + } + + // SAFETY: The `freq_table` is guaranteed to be valid. + Ok(unsafe { Table::from_raw(self.as_ref().freq_table) }) + } + + /// Sets the cpufreq table for a cpufreq policy. + /// + /// The cpufreq driver must guarantee that the frequency table does 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_raw(); + self + } + + /// Returns the data for a cpufreq policy. + pub fn data(&mut self) -> Option<::Borrowed<'_>> { + if self.as_ref().driver_data.is_null() { + None + } else { + // SAFETY: The data is earlier set by us from [`set_data()`]. + Some(unsafe { T::borrow(self.as_ref().driver_data) }) + } + } + + // Sets the data for a cpufreq policy. + fn set_data(&mut self, data: T) -> Result<()> { + if self.as_ref().driver_data.is_null() { + // Pass the ownership of the data to the foreign interface. + self.as_mut_ref().driver_data = ::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_raw()) }; + } + } +} + +/// Operations to be implemented by a cpufreq driver. +#[vtable] +pub trait Driver { + /// Driver specific data. + /// + /// Corresponds to the data retrieved via the kernel's + /// `cpufreq_get_driver_data()` function. + /// + /// Require that `Data` implements `ForeignOwnable`. We guarantee to + /// never move the underlying wrapped data structure. + type Data: ForeignOwnable; + + /// Policy specific data. + /// + /// Require that `PData` implements `ForeignOwnable`. We guarantee to + /// never move the underlying wrapped data structure. + type PData: ForeignOwnable; + + /// Policy's init callback. + fn init(policy: &mut Policy) -> Result; + + /// Policy's exit callback. + fn exit(_policy: &mut Policy, _data: Option) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's online callback. + fn online(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's offline callback. + fn offline(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's suspend callback. + fn suspend(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's resume callback. + fn resume(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's ready callback. + fn ready(_policy: &mut Policy) { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's verify callback. + fn verify(data: &mut PolicyData) -> Result<()>; + + /// Policy's setpolicy callback. + fn setpolicy(_policy: &mut Policy) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's target callback. + fn target(_policy: &mut Policy, _target_freq: u32, _relation: Relation) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's target_index callback. + fn target_index(_policy: &mut Policy, _index: u32) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's fast_switch callback. + fn fast_switch(_policy: &mut Policy, _target_freq: u32) -> u32 { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's adjust_perf callback. + fn adjust_perf(_policy: &mut Policy, _min_perf: u64, _target_perf: u64, _capacity: u64) { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's get_intermediate callback. + fn get_intermediate(_policy: &mut Policy, _index: u32) -> u32 { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's target_intermediate callback. + fn target_intermediate(_policy: &mut Policy, _index: u32) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's get callback. + fn get(_policy: &mut Policy) -> Result { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's update_limits callback. + fn update_limits(_policy: &mut Policy) { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's bios_limit callback. + fn bios_limit(_policy: &mut Policy, _limit: &mut u32) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's set_boost callback. + fn set_boost(_policy: &mut Policy, _state: i32) -> Result<()> { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } + + /// Policy's register_em callback. + fn register_em(_policy: &mut Policy) { + kernel::build_error(VTABLE_DEFAULT_ERROR) + } +} From patchwork Tue Jul 30 10:27:03 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 815912 Received: from mail-oa1-f44.google.com (mail-oa1-f44.google.com [209.85.160.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 472FB19F478 for ; Tue, 30 Jul 2024 10:27:45 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.44 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335267; cv=none; b=fAu9RtKiGdx+XcdLmVwliwCq+GCl9s4zkWLtRHH28ZabW5mlmyeaRHFnpQ8ROZG52fvXJOBRNtk5/647ptSpOPopo6+vPuv9m9V5MZ9X/vyqE/VEWJ9tIA1VGHeysiDaDSD02M5ofTsOz8H4ddQqACp4bkvIUooIOaMsZhBzQjg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335267; c=relaxed/simple; bh=pqzUQ4KlxrmXUdyCt1wox4qdv+yuWpCugEOGVv0bSrM=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=LQ7jkj0a3l5sWcbCDeWvLCx0abdrb34afwpupGTQ5StK7Z8fHnjBTEw/7PPSDgN4zQykNqNg79UQNC+eKT9gT7Y0feAfbgVOYXrOwOMmrrLwRJJghPDMqHGzOvfJrkAOYDXWN5kbrGhm4OHSMLgNaFefuoY2ZRS2yga4CuKtmYs= 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=PUkN/fWT; arc=none smtp.client-ip=209.85.160.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="PUkN/fWT" Received: by mail-oa1-f44.google.com with SMTP id 586e51a60fabf-260e8c98cc2so2331596fac.0 for ; Tue, 30 Jul 2024 03:27:45 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1722335264; x=1722940064; 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=qKlvoMf1SdBmhghmZ6bpOYzYm0BMCKbY7iERXGuPOjs=; b=PUkN/fWTjf/zbkyncusc+GfUM3xKbBKOx5Al7ZsTlZEpv+hh8APfByFuqTo+gm4rhp vQeSHpys7WiRDONN7ktdPkVW4goq5lx26biBWIpLUgQ60ERh41i0sRPBNCiZMiEQV2XJ Znlmia5XfSRFv6aJyhFL4+cBECIa9YlODPYpO8QyE7+zLALXGkUQ/rAE3PmtaA/M/Rl4 TQ6W0SOtRK2suTrt9J40i+cgpaJ/XQTwIddp3rn/bn5AreRGB71D0mokwZF0d35G51II pDo1+suHNPTLGCT0YiCvYiTquUNNezYBEcMBbx1eKhsSWmxouY/xOHpu50bcg3U/KWRr 27pg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722335264; x=1722940064; 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=qKlvoMf1SdBmhghmZ6bpOYzYm0BMCKbY7iERXGuPOjs=; b=eWFma3LJTx8MI4cv8ZjzWIe7SeEsEkjkzZYDOSL9STJ82R4wEzu5mYQgk9PgSTaDd5 72yn+H4ufjOJU1ChepV9ibo0EzP002FsmgVQq3cOkaZVgQVHymcX3gqRCaMbBuMTbsg5 Dpk3TpQhtgwDRo5mKOC2/sBKTpXTOzhKGpb36d8wGCfEHXXhNl9vnNJEb2j1dW3O5dbg t+p6nHSCNz3td8jVOcBLVJX4pODaG2ZQhz2bwqd1YZmdkv9L3yKjlcdVBfHYubdWtTsD fkX9rC2AlapYDFtYdudwNO769cbG62gjIH9ae6oT2MSz2D0L/rFH/UjScL5egNmEZpmW AZOQ== X-Gm-Message-State: AOJu0YxunV1C/vSage4gS5S5oWF8wZbau99YXvoD5cM0OZOP8aTT9HFV ZZX4ZPlv7C6wy4iMIYRszLsb1LNP/O1OjRxraQ7IrdMhKj1y8tYNnxtHzk6fKh8= X-Google-Smtp-Source: AGHT+IHoh92BnX3JWnSzudZPGbfx1ehTt5SHjTni4XZCOVLOg4mQPUnafBpOwOLsW6xKFibmHOSXXw== X-Received: by 2002:a05:6870:501:b0:261:9fc:b8fb with SMTP id 586e51a60fabf-267d4f59727mr13608575fac.46.1722335264324; Tue, 30 Jul 2024 03:27:44 -0700 (PDT) Received: from localhost ([122.172.84.129]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-70ead8a5ffasm8126664b3a.216.2024.07.30.03.27.43 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 30 Jul 2024 03:27:43 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , 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: [PATCH V5 6/8] rust: Extend cpufreq bindings for driver registration Date: Tue, 30 Jul 2024 15:57:03 +0530 Message-Id: <9eb75ce148b8fead5b66c1927cff2355325ae621.1722334569.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 the cpufreq bindings with bindings for registering a driver. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 478 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 476 insertions(+), 2 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index d58bb0bbaad4..2631dbb4865f 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -9,14 +9,17 @@ use crate::{ bindings, clk, cpumask, device::Device, - error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR}, + devres::Devres, + error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_DEFAULT_ERROR}, prelude::*, types::ForeignOwnable, }; use core::{ + cell::UnsafeCell, + marker::PhantomData, pin::Pin, - ptr::self, + ptr::{self, addr_of_mut}, }; use macros::vtable; @@ -563,3 +566,474 @@ fn register_em(_policy: &mut Policy) { kernel::build_error(VTABLE_DEFAULT_ERROR) } } + +/// Registration of a cpufreq driver. +pub struct Registration { + drv: Box>, + _p: PhantomData, +} + +// 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 Registration { + /// Registers a cpufreq driver with the rest of the kernel. + pub fn new(name: &'static CStr, data: T::Data, flags: u16, boost: bool) -> Result { + let mut drv = Box::new( + UnsafeCell::new(bindings::cpufreq_driver::default()), + GFP_KERNEL, + )?; + let drv_ref = drv.get_mut(); + + // Account for the trailing null character. + let len = name.len() + 1; + if len > drv_ref.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_ref.name[..len].copy_from_slice(name); + + drv_ref.boost_enabled = boost; + drv_ref.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_ref.attr = Box::leak(attr) as *mut _; + + // Initialize mandatory callbacks. + drv_ref.init = Some(Self::init_callback); + drv_ref.verify = Some(Self::verify_callback); + + // Initialize optional callbacks. + drv_ref.setpolicy = if T::HAS_SETPOLICY { + Some(Self::setpolicy_callback) + } else { + None + }; + drv_ref.target = if T::HAS_TARGET { + Some(Self::target_callback) + } else { + None + }; + drv_ref.target_index = if T::HAS_TARGET_INDEX { + Some(Self::target_index_callback) + } else { + None + }; + drv_ref.fast_switch = if T::HAS_FAST_SWITCH { + Some(Self::fast_switch_callback) + } else { + None + }; + drv_ref.adjust_perf = if T::HAS_ADJUST_PERF { + Some(Self::adjust_perf_callback) + } else { + None + }; + drv_ref.get_intermediate = if T::HAS_GET_INTERMEDIATE { + Some(Self::get_intermediate_callback) + } else { + None + }; + drv_ref.target_intermediate = if T::HAS_TARGET_INTERMEDIATE { + Some(Self::target_intermediate_callback) + } else { + None + }; + drv_ref.get = if T::HAS_GET { + Some(Self::get_callback) + } else { + None + }; + drv_ref.update_limits = if T::HAS_UPDATE_LIMITS { + Some(Self::update_limits_callback) + } else { + None + }; + drv_ref.bios_limit = if T::HAS_BIOS_LIMIT { + Some(Self::bios_limit_callback) + } else { + None + }; + drv_ref.online = if T::HAS_ONLINE { + Some(Self::online_callback) + } else { + None + }; + drv_ref.offline = if T::HAS_OFFLINE { + Some(Self::offline_callback) + } else { + None + }; + drv_ref.exit = if T::HAS_EXIT { + Some(Self::exit_callback) + } else { + None + }; + drv_ref.suspend = if T::HAS_SUSPEND { + Some(Self::suspend_callback) + } else { + None + }; + drv_ref.resume = if T::HAS_RESUME { + Some(Self::resume_callback) + } else { + None + }; + drv_ref.ready = if T::HAS_READY { + Some(Self::ready_callback) + } else { + None + }; + drv_ref.set_boost = if T::HAS_SET_BOOST { + Some(Self::set_boost_callback) + } else { + None + }; + drv_ref.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. + Self::set_data(drv_ref, data)?; + + // SAFETY: It is safe to register the driver with the cpufreq core in the C code. + to_result(unsafe { bindings::cpufreq_register_driver(drv_ref) })?; + + Ok(Self { + drv, + _p: PhantomData, + }) + } + + /// Same as [Registration::new`], but does not return a `Registration` instance. + /// Instead the `Registration` is owned by devres and will be revoked / dropped, once the + /// device is detached. + pub fn new_foreign_owned( + dev: &Device, + name: &'static CStr, + data: T::Data, + flags: u16, + boost: bool, + ) -> Result<()> { + let reg = Self::new(name, data, flags, boost)?; + Devres::new_foreign_owned(dev, reg, GFP_KERNEL)?; + Ok(()) + } + + // Sets the data for a cpufreq driver. + fn set_data(drv: &mut bindings::cpufreq_driver, data: T::Data) -> Result<()> { + 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) + } + } + + /// Returns the previous set data for a cpufreq driver. + pub fn data(&mut self) -> Option<::Borrowed<'static>> { + let drv = self.drv.get_mut(); + + if drv.driver_data.is_null() { + None + } else { + // SAFETY: The data is earlier set by us from [`set_data()`]. + Some(unsafe { ::borrow(drv.driver_data) }) + } + } + + // 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_raw_policy(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_raw_policy(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_raw_policy(ptr) }; + T::online(&mut policy).map(|_| 0) + }) + } + + // Policy's offline callback. + extern "C" fn offline_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `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_raw_policy(ptr) }; + T::offline(&mut policy).map(|_| 0) + }) + } + + // Policy's suspend callback. + extern "C" fn suspend_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `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_raw_policy(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_raw_policy(ptr) }; + T::resume(&mut policy).map(|_| 0) + }) + } + + // Policy's ready callback. + extern "C" fn ready_callback(ptr: *mut bindings::cpufreq_policy) { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::ready(&mut policy); + } + + // Policy's verify callback. + extern "C" fn verify_callback(ptr: *mut bindings::cpufreq_policy_data) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `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_raw_policy_data(ptr) }; + T::verify(&mut data).map(|_| 0) + }) + } + + // Policy's setpolicy callback. + extern "C" fn setpolicy_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `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_raw_policy(ptr) }; + T::setpolicy(&mut policy).map(|_| 0) + }) + } + + // Policy's target callback. + extern "C" fn target_callback( + ptr: *mut bindings::cpufreq_policy, + target_freq: u32, + relation: u32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `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_raw_policy(ptr) }; + T::target(&mut policy, target_freq, Relation::new(relation)?).map(|_| 0) + }) + } + + // Policy's target_index callback. + extern "C" fn target_index_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `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_raw_policy(ptr) }; + T::target_index(&mut policy, index).map(|_| 0) + }) + } + + // Policy's fast_switch callback. + extern "C" fn fast_switch_callback( + ptr: *mut bindings::cpufreq_policy, + target_freq: u32, + ) -> core::ffi::c_uint { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::fast_switch(&mut policy, target_freq) + } + + // Policy's adjust_perf callback. + extern "C" fn adjust_perf_callback(cpu: u32, min_perf: u64, target_perf: u64, capacity: u64) { + if let Ok(mut policy) = Policy::from_cpu(cpu) { + T::adjust_perf(&mut policy, min_perf, target_perf, capacity); + } + } + + // Policy's get_intermediate callback. + extern "C" fn get_intermediate_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> core::ffi::c_uint { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::get_intermediate(&mut policy, index) + } + + // Policy's target_intermediate callback. + extern "C" fn target_intermediate_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `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_raw_policy(ptr) }; + T::target_intermediate(&mut policy, index).map(|_| 0) + }) + } + + // Policy's get callback. + extern "C" fn get_callback(cpu: u32) -> core::ffi::c_uint { + // SAFETY: Get the policy for a CPU. + Policy::from_cpu(cpu).map_or(0, |mut policy| T::get(&mut policy).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 Ok(mut policy) = Policy::from_cpu(cpu) { + T::update_limits(&mut policy); + } + } + + // Policy's bios_limit callback. + extern "C" fn bios_limit_callback(cpu: i32, limit: *mut u32) -> core::ffi::c_int { + from_result(|| { + let mut policy = 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_raw_policy(ptr) }; + T::set_boost(&mut policy, state).map(|_| 0) + }) + } + + // Policy's register_em callback. + extern "C" fn register_em_callback(ptr: *mut bindings::cpufreq_policy) { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::register_em(&mut policy); + } +} + +impl Drop for Registration { + // Removes the registration from the kernel if it has completed successfully before. + fn drop(&mut self) { + pr_info!("Registration dropped\n"); + let drv = self.drv.get_mut(); + + // SAFETY: The driver was earlier registered from `new()`. + 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 Tue Jul 30 10:27:04 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 815558 Received: from mail-pf1-f173.google.com (mail-pf1-f173.google.com [209.85.210.173]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6CA9B19FA61 for ; Tue, 30 Jul 2024 10:27:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.173 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335269; cv=none; b=eivHmSrfOXALe2ItmItC63ACH9JZGkBVjZMhbHZNiEyxAjU51TGLtpACYKDgD3ORB4yB4tw3+Aj5tpq/GkVr6wEOiGifc9l64l2twl8LgewAyiMOa/TtS2o94fp6kI5FWxEi5yoaZCpzZT+x+rT29O/LWf+10K0nomXfUz+UmLA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335269; c=relaxed/simple; bh=dO0CWc/xKDTHkuWPDNFu1TEYJonQR+X8T3Udl4DMBu8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=VgSEUh/4sUMaK6ESVupaleAehmxI6WAoAeri/SFjNZEU7jmr8g8MN/bGOBdf748zuOO5NajbDyExJg2GIAnsM3mebkhq3ALmSKhIsqbGx8j/fVNgzAqZjj2/AHX8Xv+bE9cgmwGlaZmjWCa9grZqc8pWmCavMTpKlmMgiU/YUbw= 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=RcuWV5+B; arc=none smtp.client-ip=209.85.210.173 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="RcuWV5+B" Received: by mail-pf1-f173.google.com with SMTP id d2e1a72fcca58-70d18d4b94cso3081200b3a.2 for ; Tue, 30 Jul 2024 03:27:48 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1722335268; x=1722940068; 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=uGcVVh6shkk/cP1y6RKWzcHFgRZvU/7gGba22DNsHXQ=; b=RcuWV5+BeoZYWqU4ujqXpdUswRDHWB/avZhFUl0N3VCoRhVb5iFyVdK+N6E3UtkwSx 1118Cxr7lRRbISDh7Vj21Ps6fmLFI2fFdzzSN7JkM/iMC3uZiwiHU+gunBzMfUVb1K6b ysOe7ZTkl0BzrqNm45hSe2KKgfZK6RzKLgmFwXWM2+xEVv1uHrLWqlGiVCtSGV8vnlX9 +AA4WodPynk7ATgVQjOeAyAbNKl6P1XV+tlXa04082iHCYtSDmIrJH4jK6kP6qnFHdCd nIm+ymsW3I80enl/P0TqAXt5UBq08amgq0HnSLvKKMeYBFG1wi8Bp/CUaUGdoTjUCCKN WC7A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722335268; x=1722940068; 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=uGcVVh6shkk/cP1y6RKWzcHFgRZvU/7gGba22DNsHXQ=; b=qX6y39ipWoCaGrqdIjk+pkKfYN6Qx2kHd17gV2b3uMnnd7aseOpUc+aADAd0+UN2a6 YwGY5EkD4wEgfqdzJzjRDCy9H5u2AjALdiq4wDAtZdKMGLdXdF+DAaQFRe81CvQuQ+t5 0MOfxhvrziHpR9ap0PRwLSMP0tstygYUp3ITyYWQo4PWpEKCMm14QLqdvBWxtebwESjJ 4Z7+dd7o2w3ioIMZe2UaoQcr0+d4W1grdul04sUqq+Oq/eNprZEPbgOVNkCtOLzkpEoJ E51k41+IcYy9SRW1kJmcc9vYAEkt+W9oXqWeY00J8hU82GFMjvA3o6QxmVDkTTsHTHLo hfVQ== X-Forwarded-Encrypted: i=1; AJvYcCU5s0syyi00QGKQxjpN8dLS9zCFQWBxeEnNbaCzSoKBLGaGpCGdLIDKsBBm9K1WZ4uaEHBtZv60qNfdvfzjQ0+s9921cA6OE+E= X-Gm-Message-State: AOJu0YxnxZvNetBJSaTcQsqwtW2dy9e/YcCO6HatBdIoKNfWBxEWiAdZ GujJ4TpighHW1gkMOmqRiEcZaMaprIMZeuJxverBkw62gitH3C7VxahWTK5Ui24= X-Google-Smtp-Source: AGHT+IGh5k77jhw4qnCpk6Wyl01TvyBbrQE0VQxUroorUPZ3Pe+onjAYfUxT64noXwHfpihD+swzFQ== X-Received: by 2002:a05:6a20:a11a:b0:1c4:8da5:219a with SMTP id adf61e73a8af0-1c4a1299d97mr10019110637.8.1722335267630; Tue, 30 Jul 2024 03:27:47 -0700 (PDT) Received: from localhost ([122.172.84.129]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-70ead72ba2csm8424835b3a.93.2024.07.30.03.27.46 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 30 Jul 2024 03:27:47 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd , 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 , 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: [PATCH V5 7/8] rust: Extend OPP bindings with CPU frequency table Date: Tue, 30 Jul 2024 15:57:04 +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 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 113652448056..7317a5e922cc 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -16,7 +16,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; @@ -376,6 +379,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: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_free_cpufreq_table(self.dev.as_raw(), &mut self.as_raw()) }; + } +} + /// Operating performance point (OPP) table. /// /// Wraps the kernel's `struct opp_table`. @@ -580,6 +633,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 Tue Jul 30 10:27:05 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 815911 Received: from mail-pf1-f180.google.com (mail-pf1-f180.google.com [209.85.210.180]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 7325C1A2548 for ; Tue, 30 Jul 2024 10:27:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.180 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335274; cv=none; b=M5WZ7+tfMBk8l1RbIO7qiJ+zqkMBl2XnblrfbTjybqWLL8pTNtZMRd7LdPPVgqrWPQlYThCCdUsJl3NXTZsmdAEYii0gHOnbNxUz+w/6YA8Ek6oc+VrRyo24RaH2G0XSScIRfRUTyP0Mo8DRwMJBxYo/PaDfmnc/+p6VAToQr3w= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722335274; c=relaxed/simple; bh=OipYs2jGMIG55RSvY0g+EruEK6I4jZr0y4xBIO3mgRI=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=tDec9KOLj1BPWoJt2l5QEik7wsYX8Ia7bnQ69ESOjMMVGKkhVOomyaii9MR0riFAnZFh+aBhJsK0wqs0Vd0zFjPxrzhF0tTP67v9GUproQ1mE8KLyt7XZI1eFDozAcQbjx8s2EVINYrSjg/0iSeAzXTBBf6OYxykJnvRzY09H60= 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=iOhtQyD3; arc=none smtp.client-ip=209.85.210.180 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="iOhtQyD3" Received: by mail-pf1-f180.google.com with SMTP id d2e1a72fcca58-70d1a74a43bso2929877b3a.1 for ; Tue, 30 Jul 2024 03:27:52 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1722335272; x=1722940072; 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=64NJu5WzFt3zlYqH/AI7f9SrXiYNa9Z4nnnRivkqC2g=; b=iOhtQyD3iQVZh7IoAm9It4wrvPbDNYM06vLkE4/Nwa1eDwrw5hOxAA4Ni8j+fzQLxO ugCOfhnlTFo4x3vzVKF6KtBiiuEaghhx8/eq7h6el9tQFUseGOdx5q7fHhbSHGJZYkV0 RCg8pAY7IuAivzuE654YebVrwN4PR9BI0Bx7OnjU+cz0XaYbc1G66w09l9UIX4jvwqSf RfWsRn7YFLMFmhc7jY8w565+5PPnb319oV1mh8P0wHf9FT/9BcydzD4W+9wY7gidGMR5 pAF5k0aZs3btFtznx/TgYK/2liGT6uMt18SomqC4v7fMcEBbq8j1N0+0YPdQ1SnJThKA xKPw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722335272; x=1722940072; 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=64NJu5WzFt3zlYqH/AI7f9SrXiYNa9Z4nnnRivkqC2g=; b=VhJFzxKZApn+n6FuNw4vBiFUKQ1evf97liArYaZEYiPDjBuXZbru/Eqc6kZzzaKV9G 9DxtOPGY/Rtvqk012um44f96PHbrLJY8o7te2KUm4BpEuoQTPw1Q9rwONDlI/NFY3uMw UeZmw7WgzHy82tWI5fdKm/dzMZK69gQH41XCRm6wy8Mpjjn8TAfBu2jiZURkNE9HWPfF DWCW+gAIVItLNJh9OpCYr/Lzv3/9Mhn6TOrof/AmkvUlCYfxBfgb6XN7XB1v44dBZHoE Nw79JdnRAzRPjmxam1ln6v6czuNlcPwWS6VjsxYypn+7pHJyPy78ixwBvn3Uq8NU8hjY SwSg== X-Gm-Message-State: AOJu0YzKzQWnjPMX/YCbImUfr0IoRMwMe+5+Cunjm3rwRWORL7I0tA+B bzoQYXSu5ZPV1LjnxAHnpP1zOnBlsU5vgpTMrlaNM78ycR2oQds8QzU4QJFYank= X-Google-Smtp-Source: AGHT+IHeSyE+opvB09AXIAZzJ5TeSwrPJ0ppFzLEZUPZ0AUFm3maJU+k0UCjKh8k7BQgMp3X1sfBuw== X-Received: by 2002:a05:6a00:1250:b0:705:c029:c993 with SMTP id d2e1a72fcca58-70ecea2ee9dmr8635105b3a.14.1722335271655; Tue, 30 Jul 2024 03:27:51 -0700 (PDT) Received: from localhost ([122.172.84.129]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-70ead882b2esm8435874b3a.179.2024.07.30.03.27.50 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 30 Jul 2024 03:27:51 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , 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: [PATCH V5 8/8] cpufreq: Add Rust based cpufreq-dt driver Date: Tue, 30 Jul 2024 15:57:05 +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 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 | 221 +++++++++++++++++++++++++++++++++ 3 files changed, 234 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..9204d92d3eec --- /dev/null +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust based implementation of the cpufreq-dt driver. + +use core::format_args; + +use kernel::{ + b_str, c_str, clk, cpufreq, cpumask::Cpumask, define_of_id_table, device::Device, + error::code::*, fmt, macros::vtable, module_platform_driver, of, opp, platform, prelude::*, + str::CString, sync::Arc, +}; + +// Finds exact supply name from the OF node. +fn find_supply_name_exact(np: &of::DeviceNode, name: &str) -> Option { + let name_cstr = CString::try_from_fmt(fmt!("{}-supply", name)).ok()?; + + np.find_property(&name_cstr).ok()?; + CString::try_from_fmt(fmt!("{}", name)).ok() +} + +// Finds supply name for the CPU from DT. +fn find_supply_names(dev: &Device, cpu: u32) -> Option> { + let np = 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)] + mask: Cpumask, + #[allow(dead_code)] + token: Option, + #[allow(dead_code)] + clk: clk::Clk, +} + +struct CPUFreqDTDriver; + +#[vtable] +impl opp::ConfigOps for CPUFreqDTDriver {} + +#[vtable] +impl cpufreq::Driver for CPUFreqDTDriver { + type Data = (); + type PData = Arc; + + fn init(policy: &mut cpufreq::Policy) -> Result { + let cpu = policy.cpu(); + let dev = Device::from_cpu(cpu)?; + let mut mask = Cpumask::new()?; + + mask.set(cpu); + + let token = match find_supply_names(&dev, cpu) { + Some(names) => Some( + opp::Config::::new() + .set_regulator_names(names)? + .set(&dev)?, + ), + _ => None, + }; + + // Get OPP-sharing information from "operating-points-v2" bindings. + let fallback = match opp::Table::of_sharing_cpus(&dev, &mut mask) { + 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, &mut mask).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, &mask) { + Ok(table) => table, + Err(e) => { + if e == EPROBE_DEFER { + return Err(e); + } + + // The table is added dynamically ? + opp::Table::from_dev(&dev)? + } + }; + + // The OPP table must be initialized, statically or dynamically, by this point. + opp_table.opp_count()?; + + // Set sharing cpus for fallback scenario. + if fallback { + mask.set_all(); + opp_table.set_sharing_cpus(&mask)?; + } + + let mut transition_latency = 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)?; + + mask.copy(policy.cpus()); + + Ok(Arc::new( + CPUFreqDTDevice { + opp_table, + freq_table, + mask, + token, + clk, + }, + GFP_KERNEL, + )?) + } + + fn exit(_policy: &mut cpufreq::Policy, _data: Option) -> Result<()> { + Ok(()) + } + + fn online(_policy: &mut cpufreq::Policy) -> Result<()> { + // We did light-weight tear down earlier, nothing to do here. + Ok(()) + } + + fn offline(_policy: &mut cpufreq::Policy) -> Result<()> { + // Preserve policy->data and don't free resources on light-weight + // tear down. + Ok(()) + } + + fn suspend(policy: &mut cpufreq::Policy) -> Result<()> { + policy.generic_suspend() + } + + fn verify(data: &mut cpufreq::PolicyData) -> Result<()> { + data.generic_verify() + } + + fn target_index(policy: &mut cpufreq::Policy, index: u32) -> Result<()> { + let data = 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() + } +} + +impl platform::Driver for CPUFreqDTDriver { + type Data = (); + + define_of_id_table! {(), [ + (of::DeviceId(b_str!("operating-points-v2")), None), + ]} + + fn probe(dev: &mut platform::Device, _id_info: Option<&Self::IdInfo>) -> Result { + cpufreq::Registration::::new_foreign_owned( + dev.as_ref(), + c_str!("cpufreq-dt"), + (), + cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV, + true, + )?; + + pr_info!("CPUFreq DT driver registered\n"); + + Ok(()) + } +} + +module_platform_driver! { + type: CPUFreqDTDriver, + name: "cpufreq_dt", + author: "Viresh Kumar ", + description: "Generic CPUFreq DT driver", + license: "GPL v2", +}