From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pl1-f173.google.com (mail-pl1-f173.google.com [209.85.214.173]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3F932266B5D for ; Mon, 19 May 2025 07:07:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.173 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638471; cv=none; b=iXXoPfgtCFacI99/rVZd2GdgTg51tQtlUOghZYqmlMcdphY79GMgKubpC3+ZZ59/YJTXLTIS2TGisjd8+DhdUADqQM0r8QRnUNdZ0HsALpHE7D6Hc+8+e/BYIE7ghJ4Ftn3ZUzCm7MnurItzTbg5Qa0nqpXkwgXaugSMHhSgIIU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638471; c=relaxed/simple; bh=oF63t+ak19BpgsJzIpsjrXfi+NV5+mUyjooqlBcukIM=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=oNcW3M0JjcCMiPDoX1Fj18w8U2PKb+L3rRc9/hjTfhXlyGp3++ckXXtj5TRWBoj7XhVX5AYk8gGzGt9uoBcvyzTsSrYn7oZI9NJJtYUWzK0+ifdI10ps8Cw1t4tyxRDZfAoIxgeh1LxWYLE7batEQ4KP0/hK9d+DVpzfbrDfA08= 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=LViOgfsz; arc=none smtp.client-ip=209.85.214.173 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="LViOgfsz" Received: by mail-pl1-f173.google.com with SMTP id d9443c01a7336-231c86bffc1so39203195ad.0 for ; Mon, 19 May 2025 00:07:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638466; x=1748243266; 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=SVn0xPDTBmI2fx/iE4ainR18Kbcm4bTM4VkXhqSdQK8=; b=LViOgfszVsHYWxQmmtaKerbiCNH0mn6ezN9nrJsgSEh3wG3ww9LOV6Naclk6BXwtnw TrU8IwDJlIOm1GnFZYyQ7khCjPUQk/zj5ikiyjAVosOdv9G2W+xw61VXZUUQijLyJXIg 939WDszfodpLA++4lpRsdunEgLaKCVN6p4NoDGOkDuFcMUPFVUFUQGHU+X6GdIXBV/Nl QSxyQegCUFXZ4DcXAEEy8nOcmtbFl26R0HHp2TdzP4ntargJWoAZ0rXFMlkT9CV1AgmR RHJVmwGrxK7FswjYwu81Z49SA9Sq6M3Wq3cZiXEy64mmxblCOl54mIAwy3d/ADNdWVLl vAQA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638466; x=1748243266; 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=SVn0xPDTBmI2fx/iE4ainR18Kbcm4bTM4VkXhqSdQK8=; b=KNGZRC4SyB5re1VY7UKUPOsDAclEYR3s8SHMPu6P3LVzVJscSULhYA2sedzcyQBhGs XF7YksXGUbYOCUH+TYMhNDBFWYqEYF++FPMIRZTB9IKU4TZ0TwY4xEeYG4IyF9aLVPIX xYQybLunGTID2uv69AbNHA5Y/x3Ihv/cQ2XNZUHpl+m6bEAV0u1xL6bVJK1tSOaAjok7 tQIGo+jBivjD32Yh1LQrhbw2ggmmezB2Lr5JICUhIkK6M6/arMxycPuOPSU7Thl2yT+u PTMU60jc1qAApA7aVRACMyR/6RqHhJjJ83/OmgqYwwBFhK1KgeMlLB0i/xbV8gkD4N8h aeLA== X-Forwarded-Encrypted: i=1; AJvYcCVnVPkYV8M7S2RVHLByPXcdoCBjJ6XU1PZkQz20azFtzaLoU5dgc7j+EnbkIzaUUVuL6PZoCn3q1vSAWrI=@vger.kernel.org X-Gm-Message-State: AOJu0YxSRBuZJ7cIU6pddMzBBmzfRYb27Hx+e9ucGgFiLEbeNplhkel0 zUGPor2FEyh+YGxZKOqAnvrX2CRtEMupa53LO0vim8XntTMCI0fE7kwjwgP6R0FQzLc= X-Gm-Gg: ASbGnctmiMDTEXRXGVHb7fMFOa4EJPbwFlza+mWyKZOmq6ezBGfPReGoCQE5VPl/Qi7 WsxcWHaB5qbLjyrYl6l4pCdpkLJybFNpt6DLvWZDwKeVjG+7yYyc1dY+C7JT80RnlBZ+pRK5QTL STj4koFxQaknqby4DuMuXvS0xrp4eYKjuGrlgBjAcU5M+jEkA4fgI5u+CJh/TvPnWH+Uf6R1sSK +SSyCUTdnXhwQWvqvWFVMniDJXyUN4+l1G7/AqALGYAUiUXvpwainsj3GwKOawMaEjrt16lpqgk HGnjLRj6/c5Wshp3h5MC3L3eyzsAOWAPp91LyTIQo72kfhk50ScW X-Google-Smtp-Source: AGHT+IGvRu+V4HoqAZDkp13c8s9rr5ud0+/U0brM05Z8wTvCrpR8/as4fHNNVbCsf3eEwlXoeMdK9w== X-Received: by 2002:a17:902:ce8f:b0:224:c46:d166 with SMTP id d9443c01a7336-231de3ae584mr173011935ad.40.1747638466407; Mon, 19 May 2025 00:07:46 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-231d4ed897asm53052705ad.250.2025.05.19.00.07.45 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:07:45 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Yury Norov , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 01/15] rust: cpumask: Add few more helpers Date: Mon, 19 May 2025 12:37:06 +0530 Message-Id: <0e085055a3de84550dbe478ee95851e18b2bc5a0.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add few more cpumask helpers that are required by the Rust abstraction. Signed-off-by: Viresh Kumar Acked-by: Yury Norov [NVIDIA] --- rust/helpers/cpumask.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/rust/helpers/cpumask.c b/rust/helpers/cpumask.c index 2d380a86c34a..eb10598a0242 100644 --- a/rust/helpers/cpumask.c +++ b/rust/helpers/cpumask.c @@ -7,16 +7,41 @@ void rust_helper_cpumask_set_cpu(unsigned int cpu, struct= cpumask *dstp) cpumask_set_cpu(cpu, dstp); } =20 +void rust_helper___cpumask_set_cpu(unsigned int cpu, struct cpumask *dstp) +{ + __cpumask_set_cpu(cpu, dstp); +} + void rust_helper_cpumask_clear_cpu(int cpu, struct cpumask *dstp) { cpumask_clear_cpu(cpu, dstp); } =20 +void rust_helper___cpumask_clear_cpu(int cpu, struct cpumask *dstp) +{ + __cpumask_clear_cpu(cpu, dstp); +} + +bool rust_helper_cpumask_test_cpu(int cpu, struct cpumask *srcp) +{ + return cpumask_test_cpu(cpu, srcp); +} + void rust_helper_cpumask_setall(struct cpumask *dstp) { cpumask_setall(dstp); } =20 +bool rust_helper_cpumask_empty(struct cpumask *srcp) +{ + return cpumask_empty(srcp); +} + +bool rust_helper_cpumask_full(struct cpumask *srcp) +{ + return cpumask_full(srcp); +} + unsigned int rust_helper_cpumask_weight(struct cpumask *srcp) { return cpumask_weight(srcp); --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pl1-f169.google.com (mail-pl1-f169.google.com [209.85.214.169]) (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 7E4F32673A5 for ; Mon, 19 May 2025 07:07:51 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.169 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638474; cv=none; b=cjrX8lqYS1y+E1HV/o1RWKiWat6Y0M3MA7AilMyfyHRU3xG1gydtxR5+mnnnIAO9GpChRvvrL1ExXrwieqyeat+A2nvm1dfhQ6S9EaEw5N9Es1+VtJT7NNY1l+aJNmN6bp0kYMpITvVLmmP46AAys/HzefujL5JVpnYfz0CWBV4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638474; c=relaxed/simple; bh=mmdJGfj1J92fyXHZLWhOyf340q+M42KPjIPk+rr8ZdM=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=DHOmSfXlsB7fz0mag5zVpJUd8clYP7L+zCiB+FJJpSToKyrnxCsnzquA31fwhFNyB/Ig1eXkES9ZsRp87WulbzcwLhIu2pamZfB8bTP5uy+bXHi0PALuJNJ0wEHNCvPpumjWsWHahJ6iQCO6ZprYQH7szdFcZlfoQUAiG17rJZg= 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=r0RsFeRJ; arc=none smtp.client-ip=209.85.214.169 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="r0RsFeRJ" Received: by mail-pl1-f169.google.com with SMTP id d9443c01a7336-231bf5851b7so29481985ad.0 for ; Mon, 19 May 2025 00:07:51 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638470; x=1748243270; 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=a3/wI85QVIhlqw2UpEhcb3+sPWDU0QZqMy/18ZqpoOk=; b=r0RsFeRJ51AknYUosnfC8+1IV7KQr9rjOq9NoppZYKDbMezBhllNfVaN05YUm8xAz+ Jq5hY2lRBnMiuqiepBiX8clk+h2HU4NMVfPosgyzPR8Vrg8Bcimor052PPjEEqtIACZ9 tH6oGb1AJ/gXP+ejPbbY5kQ8XkBARpCY2TnD5Uqv9Dh2kjb83kb8pAJ5Pce4vZKlnOgW vynZcqrux6sk64u/j82MmWyWpggIZ8nybpJt8qpSh7kANL1NE2AxOGpkbB6dIRUDGp9r VNlWMZReVCzsPT+lK2bVEDjsf/kch41AecrYrTVTSB6e11sOmvNAXEDkA5fxDVL+F1pR w3Nw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638470; x=1748243270; 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=a3/wI85QVIhlqw2UpEhcb3+sPWDU0QZqMy/18ZqpoOk=; b=X4EjLe5b5P8zwCWs+0MqBcg0l0Qbrf3whZjV32PXkzyJSQGKCsh3JRfiFsKd3EmH+x SG8qDtdEawPhL8aUxPE9iqPc3+hWU3OVeh/F34pmywuBRg49UaNAoNhUaTe2HCQJ1TYy kdtSUlLspdv1lrAOYsreq5LEqZYkQJYYHb15vB1ZRhpwQ9JCO3cVzMEs5ShfMDZYFA5v Sicks2A7Sm4wZeD4r7rRE6l/nzCPkDwW8h4rBvTqqlOeNOyloX3p/LS33xTa5rTSIdGg tog3JG2r//iJdTAzEYTypgdLwX+KaoNP8Rrz83hrKgQToVyoEp0icwaX3WvCX+o2zL79 vA8w== X-Forwarded-Encrypted: i=1; AJvYcCWZTbzhmgmJ7GBf83p6RX6jK2z00KBy6lX0w3Aao6UHT/L/lZv9CU+7WKbiVAMsSUev+aAhIr1k3ARnd2A=@vger.kernel.org X-Gm-Message-State: AOJu0YzwTBpS+BcnqdWq5j0ygo2c8DcOcm+CnKkQDLYpm6kKrj3UJMs+ lMmmip7ZkFw5BGgHaI8n720dJ2JA5UKNWF22CBjTQ/uc7ZvTG/iHai7W8ueg9HZX7ak= X-Gm-Gg: ASbGncvteaiq04xkIBMKGbVzwZp8cxKgYAtLvPVCg9jMJ/j9VCcz8r+Y7G9fYV0MNzP LeYUeCCrhFvV7LXYQfbV4UR7gkq06O60z/Bb2xPsej5QHpx+EgCg5gHMiGgg48ldbLVRilRp9Fg H1xezl5iEL/rT4Ad18BrVTd1DT5WJSWFg4b96y7vzIIFi1to2Nj06+AqknVH9KM21fK/mLpiTrQ K4e0Hqm/iekuFOCBMUzjIvQtMedJoGiCVz2sharsCxjlrSpMCDN4n4BP7nqvxwyeNJuno2idZnE zGWYpJX+hrE5fjtCCJrGNG6e6LuAPpPN/M/AyYBHtBnoDc3EZcPl X-Google-Smtp-Source: AGHT+IFw7FZxkI/daEY9X+IfCeDBEfiSzb6xsNooBRE42Xq9dUAbYn7PCdnIHpUVKiHdEZ4KX8VyKA== X-Received: by 2002:a17:903:19ce:b0:224:a74:28cd with SMTP id d9443c01a7336-231d454b072mr177377655ad.31.1747638470399; Mon, 19 May 2025 00:07:50 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-231d4ed259esm52927915ad.222.2025.05.19.00.07.49 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:07:49 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Yury Norov , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 02/15] rust: cpumask: Add initial abstractions Date: Mon, 19 May 2025 12:37:07 +0530 Message-Id: <24d77314f3dc848dbe73e19aed87a69dde55ed0b.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add initial Rust abstractions for struct cpumask, covering a subset of its APIs. Additional APIs can be added as needed. These abstractions will be used in upcoming Rust support for cpufreq and OPP frameworks. Signed-off-by: Viresh Kumar Reviewed-by: Yury Norov [NVIDIA] --- rust/kernel/cpumask.rs | 330 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 2 files changed, 331 insertions(+) create mode 100644 rust/kernel/cpumask.rs diff --git a/rust/kernel/cpumask.rs b/rust/kernel/cpumask.rs new file mode 100644 index 000000000000..c90bfac9346a --- /dev/null +++ b/rust/kernel/cpumask.rs @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU Mask abstractions. +//! +//! C header: [`include/linux/cpumask.h`](srctree/include/linux/cpumask.h) + +use crate::{ + alloc::{AllocError, Flags}, + prelude::*, + types::Opaque, +}; + +#[cfg(CONFIG_CPUMASK_OFFSTACK)] +use core::ptr::{self, NonNull}; + +#[cfg(not(CONFIG_CPUMASK_OFFSTACK))] +use core::mem::MaybeUninit; + +use core::ops::{Deref, DerefMut}; + +/// A CPU Mask. +/// +/// Rust abstraction for the C `struct cpumask`. +/// +/// # Invariants +/// +/// A [`Cpumask`] instance always corresponds to a valid C `struct cpumask= `. +/// +/// The callers must ensure that the `struct cpumask` is valid for access = and +/// remains valid for the lifetime of the returned reference. +/// +/// ## Examples +/// +/// The following example demonstrates how to update a [`Cpumask`]. +/// +/// ``` +/// use kernel::bindings; +/// use kernel::cpumask::Cpumask; +/// +/// fn set_clear_cpu(ptr: *mut bindings::cpumask, set_cpu: u32, clear_cpu:= i32) { +/// // SAFETY: The `ptr` is valid for writing and remains valid for th= e lifetime of the +/// // returned reference. +/// let mask =3D unsafe { Cpumask::as_mut_ref(ptr) }; +/// +/// mask.set(set_cpu); +/// mask.clear(clear_cpu); +/// } +/// ``` +#[repr(transparent)] +pub struct Cpumask(Opaque); + +impl Cpumask { + /// Creates a mutable reference to an existing `struct cpumask` pointe= r. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for writing and remains= valid for the lifetime + /// of the returned reference. + pub unsafe fn as_mut_ref<'a>(ptr: *mut bindings::cpumask) -> &'a mut S= elf { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for writing a= nd remains valid for the + // lifetime of the returned reference. + unsafe { &mut *ptr.cast() } + } + + /// Creates a reference to an existing `struct cpumask` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for reading and remains= valid for the lifetime + /// of the returned reference. + pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask) -> &'a Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for reading a= nd remains valid for the + // lifetime of the returned reference. + unsafe { &*ptr.cast() } + } + + /// Obtain the raw `struct cpumask` pointer. + pub fn as_raw(&self) -> *mut bindings::cpumask { + let this: *const Self =3D self; + this.cast_mut().cast() + } + + /// Set `cpu` in the cpumask. + /// + /// ATTENTION: Contrary to C, this Rust `set()` method is non-atomic. + /// This mismatches kernel naming convention and corresponds to the C + /// function `__cpumask_set_cpu()`. + #[inline] + pub fn set(&mut self, cpu: u32) { + // SAFETY: By the type invariant, `self.as_raw` is a valid argumen= t to `__cpumask_set_cpu`. + unsafe { bindings::__cpumask_set_cpu(cpu, self.as_raw()) }; + } + + /// Clear `cpu` in the cpumask. + /// + /// ATTENTION: Contrary to C, this Rust `clear()` method is non-atomic. + /// This mismatches kernel naming convention and corresponds to the C + /// function `__cpumask_clear_cpu()`. + #[inline] + pub fn clear(&mut self, cpu: i32) { + // SAFETY: By the type invariant, `self.as_raw` is a valid argumen= t to + // `__cpumask_clear_cpu`. + unsafe { bindings::__cpumask_clear_cpu(cpu, self.as_raw()) }; + } + + /// Test `cpu` in the cpumask. + /// + /// Equivalent to the kernel's `cpumask_test_cpu` API. + #[inline] + pub fn test(&self, cpu: i32) -> bool { + // SAFETY: By the type invariant, `self.as_raw` is a valid argumen= t to `cpumask_test_cpu`. + unsafe { bindings::cpumask_test_cpu(cpu, self.as_raw()) } + } + + /// Set all CPUs in the cpumask. + /// + /// Equivalent to the kernel's `cpumask_setall` API. + #[inline] + pub fn setall(&mut self) { + // SAFETY: By the type invariant, `self.as_raw` is a valid argumen= t to `cpumask_setall`. + unsafe { bindings::cpumask_setall(self.as_raw()) }; + } + + /// Checks if cpumask is empty. + /// + /// Equivalent to the kernel's `cpumask_empty` API. + #[inline] + pub fn empty(&self) -> bool { + // SAFETY: By the type invariant, `self.as_raw` is a valid argumen= t to `cpumask_empty`. + unsafe { bindings::cpumask_empty(self.as_raw()) } + } + + /// Checks if cpumask is full. + /// + /// Equivalent to the kernel's `cpumask_full` API. + #[inline] + pub fn full(&self) -> bool { + // SAFETY: By the type invariant, `self.as_raw` is a valid argumen= t to `cpumask_full`. + unsafe { bindings::cpumask_full(self.as_raw()) } + } + + /// Get weight of the cpumask. + /// + /// Equivalent to the kernel's `cpumask_weight` API. + #[inline] + pub fn weight(&self) -> u32 { + // SAFETY: By the type invariant, `self.as_raw` is a valid argumen= t to `cpumask_weight`. + unsafe { bindings::cpumask_weight(self.as_raw()) } + } + + /// Copy cpumask. + /// + /// Equivalent to the kernel's `cpumask_copy` API. + #[inline] + pub fn copy(&self, dstp: &mut Self) { + // SAFETY: By the type invariant, `Self::as_raw` is a valid argume= nt to `cpumask_copy`. + unsafe { bindings::cpumask_copy(dstp.as_raw(), self.as_raw()) }; + } +} + +/// A CPU Mask pointer. +/// +/// Rust abstraction for the C `struct cpumask_var_t`. +/// +/// # Invariants +/// +/// A [`CpumaskVar`] instance always corresponds to a valid C `struct cpum= ask_var_t`. +/// +/// The callers must ensure that the `struct cpumask_var_t` is valid for a= ccess and remains valid +/// for the lifetime of [`CpumaskVar`]. +/// +/// ## Examples +/// +/// The following example demonstrates how to create and update a [`Cpumas= kVar`]. +/// +/// ``` +/// use kernel::cpumask::CpumaskVar; +/// +/// let mut mask =3D CpumaskVar::new_zero(GFP_KERNEL).unwrap(); +/// +/// assert!(mask.empty()); +/// mask.set(2); +/// assert!(mask.test(2)); +/// mask.set(3); +/// assert!(mask.test(3)); +/// assert_eq!(mask.weight(), 2); +/// +/// let mask2 =3D CpumaskVar::try_clone(&mask).unwrap(); +/// assert!(mask2.test(2)); +/// assert!(mask2.test(3)); +/// assert_eq!(mask2.weight(), 2); +/// ``` +pub struct CpumaskVar { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + ptr: NonNull, + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + mask: Cpumask, +} + +impl CpumaskVar { + /// Creates a zero-initialized instance of the [`CpumaskVar`]. + pub fn new_zero(_flags: Flags) -> Result { + Ok(Self { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + ptr: { + let mut ptr: *mut bindings::cpumask =3D ptr::null_mut(); + + // SAFETY: It is safe to call this method as the reference= to `ptr` is valid. + // + // INVARIANT: The associated memory is freed when the `Cpu= maskVar` goes out of + // scope. + unsafe { bindings::zalloc_cpumask_var(&mut ptr, _flags.as_= raw()) }; + NonNull::new(ptr.cast()).ok_or(AllocError)? + }, + + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + // SAFETY: FFI type is valid to be zero-initialized. + // + // INVARIANT: The associated memory is freed when the `Cpumask= Var` goes out of scope. + mask: unsafe { core::mem::zeroed() }, + }) + } + + /// Creates an instance of the [`CpumaskVar`]. + /// + /// # Safety + /// + /// The caller must ensure that the returned [`CpumaskVar`] is properl= y initialized before + /// getting used. + pub unsafe fn new(_flags: Flags) -> Result { + Ok(Self { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + ptr: { + let mut ptr: *mut bindings::cpumask =3D ptr::null_mut(); + + // SAFETY: It is safe to call this method as the reference= to `ptr` is valid. + // + // INVARIANT: The associated memory is freed when the `Cpu= maskVar` goes out of + // scope. + unsafe { bindings::alloc_cpumask_var(&mut ptr, _flags.as_r= aw()) }; + NonNull::new(ptr.cast()).ok_or(AllocError)? + }, + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + // SAFETY: Guaranteed by the safety requirements of the functi= on. + // + // INVARIANT: The associated memory is freed when the `Cpumask= Var` goes out of scope. + mask: unsafe { MaybeUninit::uninit().assume_init() }, + }) + } + + /// Creates a mutable reference to an existing `struct cpumask_var_t` = pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for writing and remains= valid for the lifetime + /// of the returned reference. + pub unsafe fn as_mut_ref<'a>(ptr: *mut bindings::cpumask_var_t) -> &'a= mut Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for writing a= nd remains valid for the + // lifetime of the returned reference. + unsafe { &mut *ptr.cast() } + } + + /// Creates a reference to an existing `struct cpumask_var_t` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for reading and remains= valid for the lifetime + /// of the returned reference. + pub unsafe fn as_ref<'a>(ptr: *const bindings::cpumask_var_t) -> &'a S= elf { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for reading a= nd remains valid for the + // lifetime of the returned reference. + unsafe { &*ptr.cast() } + } + + /// Clones cpumask. + pub fn try_clone(cpumask: &Cpumask) -> Result { + // SAFETY: The returned cpumask_var is initialized right after thi= s call. + let mut cpumask_var =3D unsafe { Self::new(GFP_KERNEL) }?; + + cpumask.copy(&mut cpumask_var); + Ok(cpumask_var) + } +} + +// Make [`CpumaskVar`] behave like a pointer to [`Cpumask`]. +impl Deref for CpumaskVar { + type Target =3D Cpumask; + + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + fn deref(&self) -> &Self::Target { + // SAFETY: The caller owns CpumaskVar, so it is safe to deref the = cpumask. + unsafe { &*self.ptr.as_ptr() } + } + + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + fn deref(&self) -> &Self::Target { + &self.mask + } +} + +impl DerefMut for CpumaskVar { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + fn deref_mut(&mut self) -> &mut Cpumask { + // SAFETY: The caller owns CpumaskVar, so it is safe to deref the = cpumask. + unsafe { self.ptr.as_mut() } + } + + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + fn deref_mut(&mut self) -> &mut Cpumask { + &mut self.mask + } +} + +impl Drop for CpumaskVar { + fn drop(&mut self) { + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + // SAFETY: By the type invariant, `self.as_raw` is a valid argumen= t to `free_cpumask_var`. + unsafe { + bindings::free_cpumask_var(self.as_raw()) + }; + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index de07aadd1ff5..75f78f6bfaa6 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -42,6 +42,7 @@ pub mod block; #[doc(hidden)] pub mod build_assert; +pub mod cpumask; pub mod cred; pub mod device; pub mod device_id; --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pg1-f182.google.com (mail-pg1-f182.google.com [209.85.215.182]) (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 8B983267F64 for ; Mon, 19 May 2025 07:07:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.182 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638477; cv=none; b=ekrIXKo1kNjh0XjXYO3jVm0USi4dGbM9RlytBne0VjgjH6YfdlIsK3xQObjUyCh1oXj1Uu/KvKIa7fJJrv5DRod4cX5ANfrpR12Dw7K1dr32zrP7SO3EB71UqJnjAddUMn4KCNakubEhZpJCFlG8sIVJ6UkNeqVAT66kLIIFOAo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638477; c=relaxed/simple; bh=pRm5rikPg836Cpaht6T2Bti6G/gsdEEiL/oreW2ehWs=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=kU5EXcCtqdewOiNrgruIllxEVxRLlMA17Mo/5daCH3Z4X8BNL3+O+zFBpHuEnj2i0spaSMP2OBQIPSlV/Vq/mLHTs9EbPrrJNyae/XU6hdGj5umJrK/gB5NH+3VUoBp7fz+yV04EPiIM1nA18dr1jNdDfgPNva0FfBoNs4ZG3DA= 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=l+YTjkwB; arc=none smtp.client-ip=209.85.215.182 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="l+YTjkwB" Received: by mail-pg1-f182.google.com with SMTP id 41be03b00d2f7-af548cb1f83so3719117a12.3 for ; Mon, 19 May 2025 00:07:54 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638474; x=1748243274; 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=eaMUD1BDVL417dtmG3+/1YWJeUCWl78+KVSs+NX3TJI=; b=l+YTjkwBHgTH8v1w34B5fJiYaOKFe53M9ewGKfa4UJjZ0k2lPCEBBnbIfYCSZt/FD0 SNRIYAbSqo+1wpXam+T4jvGZoAY6LhMQFHXwziespZte5KjJRGOFbOiRgZ1P0AHxh1nf m5/NqgSIqQlqKxdMxDAfsmhY8RV/JJ1DAvo5JmtLmffHUU0MD6xY51VnsI4kYsinWjiL cOqrUv3QAkIKFPP0hGlGiYvyYwSIYbgjdRZC/we3aLkAw81Z8sqEmRuyqOxBRxFlejdk 3PKeKykFAEjDNLKF+gi6/GtuG6X5Zgsdxzbh+gxXjI+YtfO5xxV/DglU/fbI+II04ShC 1Hlg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638474; x=1748243274; 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=eaMUD1BDVL417dtmG3+/1YWJeUCWl78+KVSs+NX3TJI=; b=KPDta19IHyw9Imm8nJ3dgBeW/mtU1g94ATyX/6xGC4FwWrNJbOaGLBS49eAPgMCk+z NAe49YJOqxUwYlWSbAH49MD5glr2kRQst0VkxjyQ8Lj4I0X2DcxSjJ5QdOPOUH6SjjbE BgI/J2IC61mHTxOkotws2GCxsOHL0GRY5np/ljFJPiifirTG+vRn1LpKlnSpzFk+JEO1 SAOS8+omUmjVezkahgUpSwvbwMzWY1AYspde2OTaJBzAJC1REEQ/c48oJknZ8p230ZdH dtrCTTGDrZ26M+hrh20coyH4Z01JgA/IAlJl8spUBRl6796wUCyHEDA1hzj/2UbEdw+S 7JsA== X-Forwarded-Encrypted: i=1; AJvYcCU4+9hUTJ+nCKCO8tf071sRBrZ/VI4bRps3VJ3g6X5yEbixcaNPdw1hVm4zLvGLJlhNhWByCzlLSBilKw4=@vger.kernel.org X-Gm-Message-State: AOJu0Ywikv6EhdgMNoB3QWTj898enjCBwxV9uggaWurL9SrHvt51bR74 136T4atb7hyLNP2z7V50T6EX4/WI+8viz9B6bHQHBX9nIjzWHXMbrg4wpT8pBlgmuAc= X-Gm-Gg: ASbGnctHQF5gpZrfV0uxsdq+Ag8HrmQ+RVNOAfdwNN4sJRTTg9qezgWBz5h8Vn9a2iv pJu5doI1Sx9jEK/KMBTlhxiM3eZeT7zoyznZQkv9RGMNhBYxttujRprwmn/POAw9DxGIgddFZTY LBPxBarB+qyekKHeK0fTDuzL6HYwTejWjq6m0peB969Kot+3Og1W0g4qdcqLCldMw6y3euGGI8A p5Ks5PpoacUEbdqEZ+o5nVjEjkCe/gThMEP1FKfgEAUDntQNe+/rL4ufBQvH+lu9JwpwTDoZ3T+ k+saZXOHyJWdW91vB2+vQgn8K8uBwQh1oHl8z7ZyL4uv9o52mkrM X-Google-Smtp-Source: AGHT+IF6hrADdyFBpfdMCMprB3NMgzCMsos6RN5vYSz8df1JQKxMeM5q1LLUUUmaKL61jlqJM0kYYw== X-Received: by 2002:a17:902:e808:b0:22e:3eb9:471b with SMTP id d9443c01a7336-231de36ba47mr143813725ad.23.1747638473898; Mon, 19 May 2025 00:07:53 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-231d4e988c3sm53200075ad.120.2025.05.19.00.07.52 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:07:53 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 03/15] MAINTAINERS: Add entry for Rust cpumask API Date: Mon, 19 May 2025 12:37:08 +0530 Message-Id: <0bda169b2243ea571c7dc26a3362380a4b2c7840.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Update the MAINTAINERS file to include the Rust abstractions for cpumask API. Yury has indicated that he does not wish to maintain the Rust code but would like to be listed as a reviewer. Signed-off-by: Viresh Kumar Reviewed-by: Yury Norov --- MAINTAINERS | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 96b827049501..bd7c54af4fd4 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -6237,6 +6237,12 @@ L: linux-riscv@lists.infradead.org S: Maintained F: drivers/cpuidle/cpuidle-riscv-sbi.c =20 +CPUMASK API [RUST] +M: Viresh Kumar +R: Yury Norov +S: Maintained +F: rust/kernel/cpumask.rs + CRAMFS FILESYSTEM M: Nicolas Pitre S: Maintained --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pf1-f172.google.com (mail-pf1-f172.google.com [209.85.210.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CE3B42676C9 for ; Mon, 19 May 2025 07:07:58 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638480; cv=none; b=AQ0zEq3eCvUVvA/uOFRISgv0OCq6cmqqUSvDx8LQEpXducZUt0y/qpQU5cpYoXywm1gdUhmnGdbwf2rhjyiFZZ8nYo+2ILsLCTLzMaXm4RT51J2CpUbtmnnya7DMmUKO+FAqa0q6RETfzC4Vd5TEz+KnPRZds9m+ZnY/Yx0y/rY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638480; c=relaxed/simple; bh=4HWksdgns8ejVb++Q4NJVdKDSuHEDHdMmvi+j+YhGlo=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=f8yFE7eufgklEthrbw04FuQOBLbSHvJjrI/75yyLDLGxjmxBtQcE0aV6xUXa55uNcKk99whUF09Dkmimdem8tmKVoOgNBXoFncgjzVzHsVP90EZ5Xj4oKHoFlBvoKxg4X67xKr3LmdYtuN4JJLMfT4RXUTl3MncydEIiK2zLXsY= 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=oURx1vhr; arc=none smtp.client-ip=209.85.210.172 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="oURx1vhr" Received: by mail-pf1-f172.google.com with SMTP id d2e1a72fcca58-742af848148so1687298b3a.1 for ; Mon, 19 May 2025 00:07:58 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638478; x=1748243278; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=WNsggH78Gujq22EIg5QA+ygoUlPHiqAj8S6vH5ayXvk=; b=oURx1vhrE893jp72/YQ/sUBnRtO8aTJTcAZq5IkvzRVzrRghsh/zfhBt3kO+2Ga9/G fnJkmwPOzd1K3K4/rrKi9ygZw1pfP93z2gBG8A344F1E5f7w5mN9TfgGNcvlT6Eijth2 Y2YFbybWguowNkOL5aE+oxSz7y2h+7zuZoRC0T+gxDZxj84wWzcmMcLv9Rn63M4Gbd9/ HLmVcagmqxawzKlfHBGBXrW+LhRhyTm13qBaomzswvepcjQl2Thmjm2o6R3asXRgHWbn 5HUMxLz35a+CGiV3YJJe2VzhL6cSdsEsj3ETo/AAcjtm6de/iYaX+dfhcp+i2R3ILLm2 XH4g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638478; x=1748243278; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=WNsggH78Gujq22EIg5QA+ygoUlPHiqAj8S6vH5ayXvk=; b=QCGlkAqGYtvJ09v2qZDcdov9acvYtd+I/wIeZcXjtsTZ9uhyA/P+FQO2bXVZ91JeLu N7gUY1/iTDtEWkvAAGgWxvOtx3QInCTdeDcwRncQGR5tX/AHMkGYkg1tK9v6HK9Mb3zE QbyL0nQdekebhOVt2Qs5Yp13zdO9sb8ASFJBs2FFUM9O+P40RJufXLW0DXNFFaZiGpo8 kvsrFp7HFtSiY8P/aWhQlodNWNztfZ6UpUFEMmda6av70iOgEFKYyQ5S7FF3rI9PTWB/ PNFowyEZKknFkqm1z4jGTLZalnDPUL3hRU0Kn9AxNRIuWzcA0f7VkMUVSOjOY0ncTSzc SIpQ== X-Forwarded-Encrypted: i=1; AJvYcCV3gYfhf7sKp3wmeW7WbIQjsuagSVQBdAKIWaNSMUg3WcUP4fJkXZ0ykfusWtGlA/yYb3+jFxGXZRcbenQ=@vger.kernel.org X-Gm-Message-State: AOJu0Yy8Z6IitxQyagPxL72El8uAZ6b5rwT6NsB/d5Rte7xQm1RtZ3TY Rb8csKwt8uuaZwlUnHhNAnI96y+5GwZzerqIdwA9gjDuXuk+5VRmAJ25cgAPCHmQ3sI= X-Gm-Gg: ASbGncvhKK/cUjTgQ2KR/vOksEiDEOufg15I3oPl+VkEeOmpWnfLs7kIXrbtlTkcqwV WB4ye1m6DmfKluL/4G8NluTQIZb+uGrGKgcNjm58G9UUUXDyHJ2TH2foNh8Qr/wyxa+xXzpHTpr DUIopgisGWpemneki9pyddC52zBlMDJfGabjz8eko6ls1aVtUoSQCFo+Jl6xYLIceVTz8IsZZhk gFYQRRTPzH245Z2cGLPrMwWtPx8vTBAv9f7fguOf/51n7r6oXnjjh9dfkT1mT89KnAxoPp6zdgM Tdz0J3z03UjTjQmnZFMhmRldsOhkl6XEvuHwVEG8QVW5CCZYDlP2vKJRidB8xNc= X-Google-Smtp-Source: AGHT+IHyX79iTRiEese5DXhXzl4RcrDdeFt3S9RU8Ax4nAHLTvc2jaPooDG34VMRP3xDbTxlkEsoKQ== X-Received: by 2002:a17:90b:558e:b0:30e:840a:92ed with SMTP id 98e67ed59e1d1-30e840a93d2mr16053139a91.31.1747638478085; Mon, 19 May 2025 00:07:58 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-30ef3c50c31sm1582169a91.45.2025.05.19.00.07.57 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:07:57 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Michael Turquette , Stephen Boyd Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Andrew Ballance , Daniel Almeida , linux-kernel@vger.kernel.org Subject: [PATCH V12 04/15] rust: clk: Add helpers for Rust code Date: Mon, 19 May 2025 12:37:09 +0530 Message-Id: <0ec0250c1170a8a6efb2db7a6cb49ae974d7ce05.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Non-trivial C macros and inlined C functions cannot be used directly in the Rust code and are used via functions ("helpers") that wrap those so that they can be called from Rust. In order to prepare for adding Rust abstractions for the clock APIs, add clock helpers required by the Rust implementation. Reviewed-by: Daniel Almeida Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers/clk.c | 66 +++++++++++++++++++++++++++++++++ rust/helpers/helpers.c | 1 + 4 files changed, 69 insertions(+) create mode 100644 rust/helpers/clk.c diff --git a/MAINTAINERS b/MAINTAINERS index bd7c54af4fd4..608689342aaf 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5883,6 +5883,7 @@ F: include/dt-bindings/clock/ F: include/linux/clk-pr* F: include/linux/clk/ F: include/linux/of_clk.h +F: rust/helpers/clk.c X: drivers/clk/clkdev.c =20 COMMON INTERNET FILE SYSTEM CLIENT (CIFS and SMB3) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index ab37e1d35c70..f53d6e1a21f2 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers/clk.c b/rust/helpers/clk.c new file mode 100644 index 000000000000..6d04372c9f3b --- /dev/null +++ b/rust/helpers/clk.c @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +/* + * The "inline" implementation of below helpers are only available when + * CONFIG_HAVE_CLK or CONFIG_HAVE_CLK_PREPARE aren't set. + */ +#ifndef CONFIG_HAVE_CLK +struct clk *rust_helper_clk_get(struct device *dev, const char *id) +{ + return clk_get(dev, id); +} + +void rust_helper_clk_put(struct clk *clk) +{ + clk_put(clk); +} + +int rust_helper_clk_enable(struct clk *clk) +{ + return clk_enable(clk); +} + +void rust_helper_clk_disable(struct clk *clk) +{ + clk_disable(clk); +} + +unsigned long rust_helper_clk_get_rate(struct clk *clk) +{ + return clk_get_rate(clk); +} + +int rust_helper_clk_set_rate(struct clk *clk, unsigned long rate) +{ + return clk_set_rate(clk, rate); +} +#endif + +#ifndef CONFIG_HAVE_CLK_PREPARE +int rust_helper_clk_prepare(struct clk *clk) +{ + return clk_prepare(clk); +} + +void rust_helper_clk_unprepare(struct clk *clk) +{ + clk_unprepare(clk); +} +#endif + +struct clk *rust_helper_clk_get_optional(struct device *dev, const char *i= d) +{ + return clk_get_optional(dev, id); +} + +int rust_helper_clk_prepare_enable(struct clk *clk) +{ + return clk_prepare_enable(clk); +} + +void rust_helper_clk_disable_unprepare(struct clk *clk) +{ + clk_disable_unprepare(clk); +} diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index e1c21eba9b15..ae595c9cd91b 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -11,6 +11,7 @@ #include "bug.c" #include "build_assert.c" #include "build_bug.c" +#include "clk.c" #include "cpumask.c" #include "cred.c" #include "device.c" --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pg1-f178.google.com (mail-pg1-f178.google.com [209.85.215.178]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 40CE42690CB for ; Mon, 19 May 2025 07:08:03 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.178 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638485; cv=none; b=hhsoa8ft6GZaiXP4Xo4xysNTZAXfhjUGeYaI8wMjwRUgrPJRih/8iKY+OF4mTV692BzNs9iXsp4IdTHSyrtOECyAF6PpJG0BJRJ8oDMWWkyQC/5Lir2TdafGL7X25komOeOWL0+fuKWbBcf/eUMrD4tLL8aYJk88lNFGD8NuXCs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638485; c=relaxed/simple; bh=5L5Hmj+hoBZ1EgPgIOEh7N2LK8PQQuUGQGeNdU/vBY8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=rwB/J4ke+rrR7Cu5ISvSDiEMrsX3nTd8jr5b3h9BUDs/qQQexnhxRlS4H6YvIvv4dgGJs0G2mLQ9WuGUcG8e07eVEN3fphmX3CJB4SGvMhNICL+H/QBeW7nfFAoJLZzpmCzIPNnptxKEKeR6j/+z5OTkM1kEwIS6D1R38lFhM2M= 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=YSLARzX7; arc=none smtp.client-ip=209.85.215.178 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="YSLARzX7" Received: by mail-pg1-f178.google.com with SMTP id 41be03b00d2f7-b1fd59851baso2400843a12.0 for ; Mon, 19 May 2025 00:08:03 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638482; x=1748243282; 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=DO5+lgLPT8S/OeMtRlQPVr+3mHA37EzCb8FAlkZERxU=; b=YSLARzX7eH7ppZvU6+QUxmSHLz1SdFkd4y3j7eOE9gzHMCnonJ4OVkRoGY0dy/TzkD GFd7B0fwJH93rugUMJ7rRWxiz73Ccj/tpN7uENUIO0Nr6+HqpunLXk8MlI458qBB6AVZ l9/AUAyfY39CGi/zG8zB892v9uTZ/6BT9E2C+jgwHOGnRkntsoTcJlbG99Oqpwgk+pxq QDcS0c5WxoTxkmmBEM9N9DyVkYpgb769CDSUm9x1zRmQcwNLjCoNiSnWfFBX/glvbsgt SnBvZ54Xc4a7gOmw31+Zvl61WjNshgmLDqTpL5rC8figEJNYHNdWMarJRshCP9gZFPSZ SmQA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638482; x=1748243282; 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=DO5+lgLPT8S/OeMtRlQPVr+3mHA37EzCb8FAlkZERxU=; b=TllrtKH2S2BzzjsNoSnH61DbGnlUvirpPqioRdpDoyqpcXOKnxzJ4zi3bzHuQ6W86v tjqYuGlPH1yifu4WYY00fRB0AIRsBXhDHfsguyfLsGfWF36SivfKB4TljHs7iaNQ+6wk mM9zV3QW+OXj4rwcIqmyl5IpX/fxmwLam3gxbzpUlgaeqvM5zqK6iV8+/g2mgcQ8fIcU 8xxLaLQoAnDMwumcW+/jOWRcXpprmmVQxF13wUxh9UB72TRSi4KS7//XSv7ACtjqctPt LjDp/5N2U9fANjjb0uFpnM8/vZYmKzHy2HHKIkrUmI0+k22RK8ILrpv8cv/pX/V3LTi/ Mc1w== X-Forwarded-Encrypted: i=1; AJvYcCVEW3HZdH3Ws3yQr8SaxiyEVJNfhiM+oaqFgUPTfEF0Q8652olbM0QZeeo+QgdbR1A3RlvR3DDz2ngZi1A=@vger.kernel.org X-Gm-Message-State: AOJu0YyTkrl3P4Es6INYkJ3ElzlY1lplhSO7hK5VtPwwNFS+f5V8u7/i 7/G/1WUcscxFAfPuRbbiNW76bnycVlmK6YVh2+k/5pW0JKYvM57pVk11QHdljz917Jk= X-Gm-Gg: ASbGncvezn1Spx8JXBIWWhoPsk2FfXct2iJXRFJSuaG6iZZpe1SCM1z6X00t1MQ6FWj sxMjTlOOlaB8R75dPCJo7QocRRdDuaPqrGVoHeNNS/NKv4UHPr3Fj1Vf5/b2y0jlGDGZkEgesYA Ke7Z3mc9LHMBYhMBqIjebwfQz0ewZ2EXpi4yn5ROJ0jnOWY66TgdzqMW+ZJw+Q1sL2mjiYXERzB ZMF5HHjJJNdE4nVKfLBDJ7dNmXaSFkMlpOBNfSsS0ZBjCdOTslfYQz5eygmiYdfUt2r4N7d0Rek 9akVoKMboKstMULjMhZJI/6QHGOtCgP/896/EzfT5x9KYMWfTmh2 X-Google-Smtp-Source: AGHT+IHjKKphjMeTJbrWdHGlFJHlNdpGPNMrULzrgSDDhULG3ADFXBlhrBdHy3LnjqfpGfHSVht4nA== X-Received: by 2002:a17:903:41c7:b0:224:1221:1ab4 with SMTP id d9443c01a7336-231de317b43mr173678205ad.22.1747638482451; Mon, 19 May 2025 00:08:02 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-231d4ac9fc8sm53183405ad.27.2025.05.19.00.08.01 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:01 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Michael Turquette , Stephen Boyd , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Andrew Ballance , Daniel Almeida , linux-kernel@vger.kernel.org Subject: [PATCH V12 05/15] rust: clk: Add initial abstractions Date: Mon, 19 May 2025 12:37:10 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add initial abstractions for the clk APIs. These provide the minimal functionality needed for common use cases, making them straightforward to introduce in the first iteration. These will be used by Rust based cpufreq / OPP layers to begin with. Tested-by: Daniel Almeida Reviewed-by: Daniel Almeida Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/kernel/clk.rs | 334 +++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 336 insertions(+) create mode 100644 rust/kernel/clk.rs diff --git a/MAINTAINERS b/MAINTAINERS index 608689342aaf..12cde55579a0 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5884,6 +5884,7 @@ F: include/linux/clk-pr* F: include/linux/clk/ F: include/linux/of_clk.h F: rust/helpers/clk.c +F: rust/kernel/clk.rs X: drivers/clk/clkdev.c =20 COMMON INTERNET FILE SYSTEM CLIENT (CIFS and SMB3) diff --git a/rust/kernel/clk.rs b/rust/kernel/clk.rs new file mode 100644 index 000000000000..6041c6d07527 --- /dev/null +++ b/rust/kernel/clk.rs @@ -0,0 +1,334 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Clock abstractions. +//! +//! C header: [`include/linux/clk.h`](srctree/include/linux/clk.h) +//! +//! Reference: + +use crate::ffi::c_ulong; + +/// The frequency unit. +/// +/// Represents a frequency in hertz, wrapping a [`c_ulong`] value. +/// +/// ## Examples +/// +/// ``` +/// use kernel::clk::Hertz; +/// +/// let hz =3D 1_000_000_000; +/// let rate =3D Hertz(hz); +/// +/// assert_eq!(rate.as_hz(), hz); +/// assert_eq!(rate, Hertz(hz)); +/// assert_eq!(rate, Hertz::from_khz(hz / 1_000)); +/// assert_eq!(rate, Hertz::from_mhz(hz / 1_000_000)); +/// assert_eq!(rate, Hertz::from_ghz(hz / 1_000_000_000)); +/// ``` +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub struct Hertz(pub c_ulong); + +impl Hertz { + /// Create a new instance from kilohertz (kHz) + pub fn from_khz(khz: c_ulong) -> Self { + Self(khz * 1_000) + } + + /// Create a new instance from megahertz (MHz) + pub fn from_mhz(mhz: c_ulong) -> Self { + Self(mhz * 1_000_000) + } + + /// Create a new instance from gigahertz (GHz) + pub fn from_ghz(ghz: c_ulong) -> Self { + Self(ghz * 1_000_000_000) + } + + /// Get the frequency in hertz + pub fn as_hz(&self) -> c_ulong { + self.0 + } + + /// Get the frequency in kilohertz + pub fn as_khz(&self) -> c_ulong { + self.0 / 1_000 + } + + /// Get the frequency in megahertz + pub fn as_mhz(&self) -> c_ulong { + self.0 / 1_000_000 + } + + /// Get the frequency in gigahertz + pub fn as_ghz(&self) -> c_ulong { + self.0 / 1_000_000_000 + } +} + +impl From for c_ulong { + fn from(freq: Hertz) -> Self { + freq.0 + } +} + +#[cfg(CONFIG_COMMON_CLK)] +mod common_clk { + use super::Hertz; + use crate::{ + device::Device, + error::{from_err_ptr, to_result, Result}, + prelude::*, + }; + + use core::{ops::Deref, ptr}; + + /// A reference-counted clock. + /// + /// Rust abstraction for the C [`struct clk`]. + /// + /// # Invariants + /// + /// A [`Clk`] instance holds either a pointer to a valid [`struct clk`= ] created by the C + /// portion of the kernel or a NULL pointer. + /// + /// Instances of this type are reference-counted. Calling [`Clk::get`]= ensures that the + /// allocation remains valid for the lifetime of the [`Clk`]. + /// + /// ## Examples + /// + /// The following example demonstrates how to obtain and configure a c= lock for a device. + /// + /// ``` + /// use kernel::c_str; + /// use kernel::clk::{Clk, Hertz}; + /// use kernel::device::Device; + /// use kernel::error::Result; + /// + /// fn configure_clk(dev: &Device) -> Result { + /// let clk =3D Clk::get(dev, Some(c_str!("apb_clk")))?; + /// + /// clk.prepare_enable()?; + /// + /// let expected_rate =3D Hertz::from_ghz(1); + /// + /// if clk.rate() !=3D expected_rate { + /// clk.set_rate(expected_rate)?; + /// } + /// + /// clk.disable_unprepare(); + /// Ok(()) + /// } + /// ``` + /// + /// [`struct clk`]: https://docs.kernel.org/driver-api/clk.html + #[repr(transparent)] + pub struct Clk(*mut bindings::clk); + + impl Clk { + /// Gets [`Clk`] corresponding to a [`Device`] and a connection id. + /// + /// Equivalent to the kernel's [`clk_get`] API. + /// + /// [`clk_get`]: https://docs.kernel.org/core-api/kernel-api.html#= c.clk_get + pub fn get(dev: &Device, name: Option<&CStr>) -> Result { + let con_id =3D if let Some(name) =3D name { + name.as_ptr() + } else { + ptr::null() + }; + + // SAFETY: It is safe to call [`clk_get`] for a valid device p= ointer. + // + // INVARIANT: The reference-count is decremented when [`Clk`] = goes out of scope. + Ok(Self(from_err_ptr(unsafe { + bindings::clk_get(dev.as_raw(), con_id) + })?)) + } + + /// Obtain the raw [`struct clk`] pointer. + #[inline] + pub fn as_raw(&self) -> *mut bindings::clk { + self.0 + } + + /// Enable the clock. + /// + /// Equivalent to the kernel's [`clk_enable`] API. + /// + /// [`clk_enable`]: https://docs.kernel.org/core-api/kernel-api.ht= ml#c.clk_enable + #[inline] + pub fn enable(&self) -> Result { + // SAFETY: By the type invariants, self.as_raw() is a valid ar= gument for + // [`clk_enable`]. + to_result(unsafe { bindings::clk_enable(self.as_raw()) }) + } + + /// Disable the clock. + /// + /// Equivalent to the kernel's [`clk_disable`] API. + /// + /// [`clk_disable`]: https://docs.kernel.org/core-api/kernel-api.h= tml#c.clk_disable + #[inline] + pub fn disable(&self) { + // SAFETY: By the type invariants, self.as_raw() is a valid ar= gument for + // [`clk_disable`]. + unsafe { bindings::clk_disable(self.as_raw()) }; + } + + /// Prepare the clock. + /// + /// Equivalent to the kernel's [`clk_prepare`] API. + /// + /// [`clk_prepare`]: https://docs.kernel.org/core-api/kernel-api.h= tml#c.clk_prepare + #[inline] + pub fn prepare(&self) -> Result { + // SAFETY: By the type invariants, self.as_raw() is a valid ar= gument for + // [`clk_prepare`]. + to_result(unsafe { bindings::clk_prepare(self.as_raw()) }) + } + + /// Unprepare the clock. + /// + /// Equivalent to the kernel's [`clk_unprepare`] API. + /// + /// [`clk_unprepare`]: https://docs.kernel.org/core-api/kernel-api= .html#c.clk_unprepare + #[inline] + pub fn unprepare(&self) { + // SAFETY: By the type invariants, self.as_raw() is a valid ar= gument for + // [`clk_unprepare`]. + unsafe { bindings::clk_unprepare(self.as_raw()) }; + } + + /// Prepare and enable the clock. + /// + /// Equivalent to calling [`Clk::prepare`] followed by [`Clk::enab= le`]. + #[inline] + pub fn prepare_enable(&self) -> Result { + // SAFETY: By the type invariants, self.as_raw() is a valid ar= gument for + // [`clk_prepare_enable`]. + to_result(unsafe { bindings::clk_prepare_enable(self.as_raw())= }) + } + + /// Disable and unprepare the clock. + /// + /// Equivalent to calling [`Clk::disable`] followed by [`Clk::unpr= epare`]. + #[inline] + pub fn disable_unprepare(&self) { + // SAFETY: By the type invariants, self.as_raw() is a valid ar= gument for + // [`clk_disable_unprepare`]. + unsafe { bindings::clk_disable_unprepare(self.as_raw()) }; + } + + /// Get clock's rate. + /// + /// Equivalent to the kernel's [`clk_get_rate`] API. + /// + /// [`clk_get_rate`]: https://docs.kernel.org/core-api/kernel-api.= html#c.clk_get_rate + #[inline] + pub fn rate(&self) -> Hertz { + // SAFETY: By the type invariants, self.as_raw() is a valid ar= gument for + // [`clk_get_rate`]. + Hertz(unsafe { bindings::clk_get_rate(self.as_raw()) }) + } + + /// Set clock's rate. + /// + /// Equivalent to the kernel's [`clk_set_rate`] API. + /// + /// [`clk_set_rate`]: https://docs.kernel.org/core-api/kernel-api.= html#c.clk_set_rate + #[inline] + pub fn set_rate(&self, rate: Hertz) -> Result { + // SAFETY: By the type invariants, self.as_raw() is a valid ar= gument for + // [`clk_set_rate`]. + to_result(unsafe { bindings::clk_set_rate(self.as_raw(), rate.= as_hz()) }) + } + } + + impl Drop for Clk { + fn drop(&mut self) { + // SAFETY: By the type invariants, self.as_raw() is a valid ar= gument for [`clk_put`]. + unsafe { bindings::clk_put(self.as_raw()) }; + } + } + + /// A reference-counted optional clock. + /// + /// A lightweight wrapper around an optional [`Clk`]. An [`OptionalClk= `] represents a [`Clk`] + /// that a driver can function without but may improve performance or = enable additional + /// features when available. + /// + /// # Invariants + /// + /// An [`OptionalClk`] instance encapsulates a [`Clk`] with either a v= alid [`struct clk`] or + /// `NULL` pointer. + /// + /// Instances of this type are reference-counted. Calling [`OptionalCl= k::get`] ensures that the + /// allocation remains valid for the lifetime of the [`OptionalClk`]. + /// + /// ## Examples + /// + /// The following example demonstrates how to obtain and configure an = optional clock for a + /// device. The code functions correctly whether or not the clock is a= vailable. + /// + /// ``` + /// use kernel::c_str; + /// use kernel::clk::{OptionalClk, Hertz}; + /// use kernel::device::Device; + /// use kernel::error::Result; + /// + /// fn configure_clk(dev: &Device) -> Result { + /// let clk =3D OptionalClk::get(dev, Some(c_str!("apb_clk")))?; + /// + /// clk.prepare_enable()?; + /// + /// let expected_rate =3D Hertz::from_ghz(1); + /// + /// if clk.rate() !=3D expected_rate { + /// clk.set_rate(expected_rate)?; + /// } + /// + /// clk.disable_unprepare(); + /// Ok(()) + /// } + /// ``` + /// + /// [`struct clk`]: https://docs.kernel.org/driver-api/clk.html + pub struct OptionalClk(Clk); + + impl OptionalClk { + /// Gets [`OptionalClk`] corresponding to a [`Device`] and a conne= ction id. + /// + /// Equivalent to the kernel's [`clk_get_optional`] API. + /// + /// [`clk_get_optional`]: + /// https://docs.kernel.org/core-api/kernel-api.html#c.clk_get_opt= ional + pub fn get(dev: &Device, name: Option<&CStr>) -> Result { + let con_id =3D if let Some(name) =3D name { + name.as_ptr() + } else { + ptr::null() + }; + + // SAFETY: It is safe to call [`clk_get_optional`] for a valid= device pointer. + // + // INVARIANT: The reference-count is decremented when [`Option= alClk`] goes out of + // scope. + Ok(Self(Clk(from_err_ptr(unsafe { + bindings::clk_get_optional(dev.as_raw(), con_id) + })?))) + } + } + + // Make [`OptionalClk`] behave like [`Clk`]. + impl Deref for OptionalClk { + type Target =3D Clk; + + fn deref(&self) -> &Clk { + &self.0 + } + } +} + +#[cfg(CONFIG_COMMON_CLK)] +pub use common_clk::*; diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 75f78f6bfaa6..3fd7c17cbc06 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -42,6 +42,7 @@ pub mod block; #[doc(hidden)] pub mod build_assert; +pub mod clk; pub mod cpumask; pub mod cred; pub mod device; --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 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 182602676FF for ; Mon, 19 May 2025 07:08:06 +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=1747638488; cv=none; b=nkHJWGzkMMAVQ0FkVvVz/Wj5l7yIITWbd2Uop/mKyG9U5UPP77O5BsDAsXGIVyUZhF1phNMRo712SQsGW4B/Dqctx64CqCnVcf8b3RFPsbzVChqzOApEuyd77bd0l3GaYj5Jnh1vIugIBCYaOBDhSyLBUX6isMRdOpKPi2yHjH4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638488; c=relaxed/simple; bh=RPs39+G/2/WRBdJP3KwTQnQlR3Lp/kvURzUIgtDgvwA=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=qupdL8hob0S+CW2+eyycgVDSsUw9PBrXR+KqFVmvDn/24jXxKMKZHCFI7LS4TU+nt6N69mhlaeDdcTlc0w8o0m5WhXDi390Gso5aUG9YIsNRYH9UXrm80TmQ479i/UFQPpyO6H410WFIJIaViTdkEi/a32Cjn+/+AxHj9Vm6Fjk= 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=TpvJi+Kr; 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="TpvJi+Kr" Received: by mail-pf1-f173.google.com with SMTP id d2e1a72fcca58-73bf5aa95e7so3602000b3a.1 for ; Mon, 19 May 2025 00:08:06 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638486; x=1748243286; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=06XWI3zWvI8xB81BSzBcpZnXhq7zBjUBfZT4cp51CDs=; b=TpvJi+KreG9k+1tnyhg46J2UAumtPDce3pxuk/EPgy9RF25DuB/valuzxXRAOIzTX/ 5zr5MF4xvECZ3/d+xd0M24bFSUzUOtAN24ifMNxOgaFLFeYy16psv0DRCgTt8rzNaK1g hGphfvcsFtV4K5sjUuyugXdLGPIfWxl/ktSsqZ6z0mIpMYWBK5Y1VXjTCOyp0beMSAD0 uOer9o4z9VYJwtpYkawNXQCfECTbUDncvYusT5Ml6duR/7j3ibBX6PdpTUnOrKhEsPtF I8praT4zGMDz5KdygZFooZovOscrT0qfiBc1aIb4kmBiVWPQt37P9ykwEnd9NY8M9KF9 3p/g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638486; x=1748243286; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=06XWI3zWvI8xB81BSzBcpZnXhq7zBjUBfZT4cp51CDs=; b=A63iEXsZlzwcu4CpzQCJlmmEEYEsA4d/f46GkoWobqe3HV1uvioRiVnDCR/pH0AKnS 2c4gGu05fXZGl/5vT8b46amWV7CAJfj6rykdoZ3FIN1iSUEs2jN+wACXcQb0Tkd6ha11 FrRgeqZIyW1rencwIVv+552p+mEEwAA+3TfMQWoOusTFiSkFpoPhAjS+c1eUU9Cc3lL5 G4wgNvhZdnX71nJ1HzwRUNMu6fjOn4OTX+X8IqKh9SbvekWH202nlztcTJb406zsrT9q 9oqsD8V9IHzD3FkwddYZA39F2ag3TCs6c4FLdgSxPdrjKVnyeWUohR1RecS663ulHwBI Y6dw== X-Forwarded-Encrypted: i=1; AJvYcCV8Cav2eJWM8XHoOIbd94i52KAsoe8cidxo+jlN0ze4bcZeprm1hLV62ef5AfrKofU6IwioM+QQUQh/s0c=@vger.kernel.org X-Gm-Message-State: AOJu0YwWZ07zETpPUY1uf/abGyCXJnqj4pVUeSREn8ZhFyoALlQcO/2W Sz8qcRriaJ9yLncwMrdas2liOYdGkiqU11h99s9d3yo4n4/2n66kw+G/kb/Nfjj793Y= X-Gm-Gg: ASbGnctIN5i3xp9XAsp+NVgYgcdxeA/NXrAApUYP7uFDrvoejv90WDpYBPFhvKunf5u dJMe87Qhv1Awr9WJsnUZJ6Ff45QvsfdjaHpC1xSsX66hM4RLvQaqeJKYabLJYiGr6cLvM8u5MIb LRr1fv+vxup+h1z18JsT6YznsV3om6PVNjYzFfUCKwgiO0RmzP+R/CCuurwIxWUzUmgtknIDUKa lvdMlX//qoWhf2Gk9kMlk5gMXz7NOHHl4DW4z0Kx1uutMzg/iDgMeK7V4W7H9ChJMaQI9idEZsS L3wYW9vX6Z5y/sPsP332AUBdGhENMImsoGfdSqNYXbMEIbDY7Cmh X-Google-Smtp-Source: AGHT+IHDxTCILxiZSszxnTc982DJY8orsb9n0sCiFXe5hNTg/g6o+f+sr8ozsUbLXvO9AluZPucbQw== X-Received: by 2002:a05:6a21:a0cb:b0:218:c22:e3e6 with SMTP id adf61e73a8af0-2180c22e3fdmr15396853637.12.1747638486393; Mon, 19 May 2025 00:08:06 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-742acb8731esm5294876b3a.168.2025.05.19.00.08.05 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:05 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , Anisse Astier , linux-kernel@vger.kernel.org Subject: [PATCH V12 06/15] rust: macros: enable use of hyphens in module names Date: Mon, 19 May 2025 12:37:11 +0530 Message-Id: <21b4c30db60f22d56cc6386a18564705ad3a6f4a.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Anisse Astier Some modules might need naming that contains hyphens "-" to match the auto-probing by name in the platform devices that comes from the device tree. But rust identifiers cannot contain hyphens, so replace the module name by an underscore anywhere we'd use it as an identifier. Signed-off-by: Anisse Astier Reviewed-by: Alice Ryhl [Viresh: Replace "-" with '-', and fix line length checkpatch warnings] Signed-off-by: Viresh Kumar Reviewed-by: Benno Lossin --- rust/macros/module.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/rust/macros/module.rs b/rust/macros/module.rs index a9418fbc9b44..27cc72d474f0 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -185,7 +185,9 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { =20 let info =3D ModuleInfo::parse(&mut it); =20 - let mut modinfo =3D ModInfoBuilder::new(info.name.as_ref()); + /* Rust does not allow hyphens in identifiers, use underscore instead = */ + let name_identifier =3D info.name.replace('-', "_"); + let mut modinfo =3D ModInfoBuilder::new(name_identifier.as_ref()); if let Some(author) =3D info.author { modinfo.emit("author", &author); } @@ -310,14 +312,15 @@ mod __module_init {{ #[doc(hidden)] #[link_section =3D \"{initcall_section}\"] #[used] - pub static __{name}_initcall: extern \"C\" fn() -> ker= nel::ffi::c_int =3D __{name}_init; + pub static __{name_identifier}_initcall: extern \"C\" = fn() -> + kernel::ffi::c_int =3D __{name_identifier}_init; =20 #[cfg(not(MODULE))] #[cfg(CONFIG_HAVE_ARCH_PREL32_RELOCATIONS)] core::arch::global_asm!( r#\".section \"{initcall_section}\", \"a\" - __{name}_initcall: - .long __{name}_init - . + __{name_identifier}_initcall: + .long __{name_identifier}_init - . .previous \"# ); @@ -325,7 +328,7 @@ mod __module_init {{ #[cfg(not(MODULE))] #[doc(hidden)] #[no_mangle] - pub extern \"C\" fn __{name}_init() -> kernel::ffi::c_= int {{ + pub extern \"C\" fn __{name_identifier}_init() -> kern= el::ffi::c_int {{ // SAFETY: This function is inaccessible to the ou= tside due to the double // module wrapping it. It is called exactly once b= y the C side via its // placement above in the initcall section. @@ -335,13 +338,13 @@ mod __module_init {{ #[cfg(not(MODULE))] #[doc(hidden)] #[no_mangle] - pub extern \"C\" fn __{name}_exit() {{ + pub extern \"C\" fn __{name_identifier}_exit() {{ // SAFETY: // - This function is inaccessible to the outside = due to the double // module wrapping it. It is called exactly once= by the C side via its // unique name, - // - furthermore it is only called after `__{name}= _init` has returned `0` - // (which delegates to `__init`). + // - furthermore it is only called after `__{name_= identifier}_init` has + // returned `0` (which delegates to `__init`). unsafe {{ __exit() }} }} =20 @@ -381,6 +384,7 @@ unsafe fn __exit() {{ ", type_ =3D info.type_, name =3D info.name, + name_identifier =3D name_identifier, modinfo =3D modinfo.buffer, initcall_section =3D ".initcall6.init" ) --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pj1-f47.google.com (mail-pj1-f47.google.com [209.85.216.47]) (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 72162269AFB for ; Mon, 19 May 2025 07:08:11 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.47 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638493; cv=none; b=o3Ugbrc4iyXhr/R5JC+1GF/rS7s9a+p7JEAIaJAYGansx3lgO9dXbGNcIrqwnDVzcc4STar5QSiCcBKgitdfpCti/GyRj77pFgAuDcJ5/DRFfQ8CJYMdS/cKvHFxklAEyv+xk4hJPkLZ9rPb+6hGi9OjC4177dUoHhKNql726BY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638493; c=relaxed/simple; bh=juOq7g4rijYkdxYFdOONMCnI1QPlZoKOeRbFNRc5CdA=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=lfQKLGiWl68clIgHDhoLeW6hxoLk+sErWwUI2m/+7o79YXr05X0kXuadjO4ly7bYPoAs2Jey/qa1h3VwxpZbW6G/HJoRr2CzYOI6S8ad873QoMJU2RECHUc8LBP0CpAtVxONqVb2rnslX/PKyXWZZ17XZbLTf6LMc9PAakm6Wpk= 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=wPZjBqtt; arc=none smtp.client-ip=209.85.216.47 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="wPZjBqtt" Received: by mail-pj1-f47.google.com with SMTP id 98e67ed59e1d1-30dfd9e7fa8so5058070a91.2 for ; Mon, 19 May 2025 00:08:11 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638490; x=1748243290; 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=4r3X/jvGTdLizcE+YYmP7gaggu0BT8JGhgAP9zX20zQ=; b=wPZjBqttr+hHHhBIqnTEXaCYP6p1mVG29YFLK8j2tQ50zoHy4GnQUg5PtnJNT1PaKV zdDvuE8FhAIO6DomX7fSaiLE+EgRdnx1tz+t5mnaaTG4046YN8/c5lFQvtvA4Mborz3Q QY84k+DhIFRu3mtaM7wm8OeAp6SbdKZnvwkrHs6aofpvWkrrNIMbp7agIW+ePo4imshD 33nw7pjAGEWD+IXsM46daodfEJvDyvXg4apXuL+qsBbC+50RBNXfdleODe+Ah77FBFCO SL4Oayuis4AZWnG6AhoA9swQ4GGp8zUeqhis2sVhYmcoaSOidJy4uEM64VUYIHIxEg7R F/MQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638490; x=1748243290; 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=4r3X/jvGTdLizcE+YYmP7gaggu0BT8JGhgAP9zX20zQ=; b=G/XlU6/9EVIEyLwST+WlZBlSHHbbPGcc9DGu4oxtFLHlIcj7JC3VpZ03YJ/CpLSF/9 Xejh9r5G02I1Q+XwcDEpmNx5Mg3tEU00hkKrujurk/xL35ts5/x8MQrhAbdVpT/SVXy3 F72AV9F6/hrp5XnneocUf1gwN8m/jriUve6J37X2tQ0jxh8kyi8c4PGJpbxNUt/gZPHp EApR6Ct9rkRo9sdqbt/0+bavg82qxrKFVJnfigfpM+T5y6h8PImcNQCmyU2iEq21IAsR QGMDwM1OAwsB1YVJf1UmRiqkHPWKZTcjViVJBxVM+Gr1CT3LOwCHawmzw9jfjNx1vGBG uEFQ== X-Forwarded-Encrypted: i=1; AJvYcCXkHYce51G3PSHInHcN24IPaPs930J1mHZV7XXOoYSj4wzaKpwVl6MIAWBoFVhtZuQxDjT7qDo93KjKspc=@vger.kernel.org X-Gm-Message-State: AOJu0Yz5/ehNVx4bmSxytru0EJU6qemWTm6Q7auwXm284EH0Eip0uZua 5QL5nwNvltC51Xb7xGt9u3c1/GBYmzt3n418gCUdwnQGSaPZoiT+LNabjwFmPp+1uno= X-Gm-Gg: ASbGncvrhuLm1o+r8uXhScFHeChFprLt7IhppONjVVKcQ6yPUxWq+dS2NFJJxMBu+NS lBePOoPHlaqlAzqgYokI9YinL0RRuhJT1enGqIYvU6tnn27Nuu+S3h7jKKOel8V9fNctbcYVOPw 32mYZvGnTJ2h3810nslUu092ymN/xXCnTD4zmTQepJgOwVr4VfC2I0ROKCuE8gQkGKAVtMvyIq4 K+IUPFUVBx5nEcXkWbMNBJJI7tn1XzuMoTGplbktJH9G6JgMaAdji/9LoH62U+tCLZKRvF6R+sk Yokw8h37h1GqFHHU7+mR4Rlah9uS7wquJue/NfOP4cEDoRQs4DJD+++YdwMQNfI= X-Google-Smtp-Source: AGHT+IEwnItI1adJ5eNRnfUIiONeAwIaER/7UxHP7sLjQh/2fUqJp7LQ0oLpGHM32/z5QPdXw+IjVA== X-Received: by 2002:a17:90b:3b8f:b0:2ff:6608:78cd with SMTP id 98e67ed59e1d1-30e830fbe31mr19285978a91.9.1747638490516; Mon, 19 May 2025 00:08:10 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-30e7d4aa777sm5971781a91.21.2025.05.19.00.08.09 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:09 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Thomas Gleixner , Peter Zijlstra Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 07/15] rust: cpu: Add from_cpu() Date: Mon, 19 May 2025 12:37:12 +0530 Message-Id: <19bc845f59e0a7a6bbc5c23353d04f96f23aaed9.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This implements cpu::from_cpu(), which returns a reference to Device for a CPU. The C struct is created at initialization time for CPUs and is never freed and so ARef isn't returned from this function. The new helper will be used by Rust based cpufreq drivers. Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/cpu.rs | 30 ++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 4 files changed, 33 insertions(+) create mode 100644 rust/kernel/cpu.rs diff --git a/MAINTAINERS b/MAINTAINERS index 12cde55579a0..475abf72869c 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -6155,6 +6155,7 @@ F: include/linux/cpuhotplug.h F: include/linux/smpboot.h F: kernel/cpu.c F: kernel/smpboot.* +F: rust/kernel/cpu.rs =20 CPU IDLE TIME MANAGEMENT FRAMEWORK M: "Rafael J. Wysocki" diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index f53d6e1a21f2..ac92c67d2c38 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/cpu.rs b/rust/kernel/cpu.rs new file mode 100644 index 000000000000..10c5c3b25873 --- /dev/null +++ b/rust/kernel/cpu.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Generic CPU definitions. +//! +//! C header: [`include/linux/cpu.h`](srctree/include/linux/cpu.h) + +use crate::{bindings, device::Device, error::Result, prelude::ENODEV}; + +/// Creates a new instance of CPU's device. +/// +/// # Safety +/// +/// Reference counting is not implemented for the CPU device in the C code= . When a CPU is +/// hot-unplugged, the corresponding CPU device is unregistered, but its a= ssociated memory +/// is not freed. +/// +/// Callers must ensure that the CPU device is not used after it has been = unregistered. +/// This can be achieved, for example, by registering a CPU hotplug notifi= er and removing +/// any references to the CPU device within the notifier's callback. +pub unsafe fn from_cpu(cpu: u32) -> Result<&'static Device> { + // SAFETY: It is safe to call `get_cpu_device()` for any CPU. + let ptr =3D unsafe { bindings::get_cpu_device(cpu) }; + if ptr.is_null() { + return Err(ENODEV); + } + + // SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, = is a valid pointer to + // a `struct device` and is never freed by the C code. + Ok(unsafe { Device::as_ref(ptr) }) +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 3fd7c17cbc06..de0a840fcc99 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -43,6 +43,7 @@ #[doc(hidden)] pub mod build_assert; pub mod clk; +pub mod cpu; pub mod cpumask; pub mod cred; pub mod device; --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pf1-f179.google.com (mail-pf1-f179.google.com [209.85.210.179]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E9F5526A0AB for ; Mon, 19 May 2025 07:08:15 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.179 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638498; cv=none; b=HkRiw1AX7jlqLsp6fqiZ5yz88W957RQEFOngUakqA6GCqNG1FrU2OsbAEMUYGw5pq2LKdnnQE5yfMosB6lIdjRv1u2T/DS4Fjkd9myG5gey0nMYC2MRfN2cSTpALVLJmEl7liTov7Osybd3It+UGsdEHKp2MQdm4xGn6GNnmPTA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638498; c=relaxed/simple; bh=iaCNxDEvQFF0BxKHRPZ6sTywDQH6RmrBQNe/gDyVxqg=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=rLwP2aWjbnQVSIodqq36R4ihswytoZpDgRy2TwiIWDtqZkwGJ8LyCDRIcqMirisWJO0+MAbwTO+fEvUBvfkEONdjf2VsrAFzHSlCsRKsM8pZprZ4PeajFrQ4mpST41nzaCW264U1Oe2bNCTBuZQc9/7DOdFMD+kqpjniqOqoKgQ= 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=U2WCg5hH; arc=none smtp.client-ip=209.85.210.179 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="U2WCg5hH" Received: by mail-pf1-f179.google.com with SMTP id d2e1a72fcca58-739b3fe7ce8so3227490b3a.0 for ; Mon, 19 May 2025 00:08:15 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638495; x=1748243295; 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=T0gY3g4CMyk/KLPQ47ChexP08SbMxnytGLgjzVXuWIc=; b=U2WCg5hH3h+SIVcy5nQ4Soix+uZdrkOWAh2I7IUFpVJHaQmuyeUDDRjmMxjPnvLiok f5dYBSzT5rWFkhL6YgBtJNVIEX3HAjcd7h+SGCyM56xoMixrWyQQPz8i6IqIj33Q/fMh 9bNaGPD9ovUSO0meORwBRODvQv78vKjuotAmrA0OFqhi0tNExR9F9hdkMGEift16K6WT Ti3gjWpXESl2IvieGsikHrncj7T2AVQdCnPL+6vpvDesqKDyeYHgLEwDa9zmzs309VIy ym5KUBqJEjrZM/Ac3L1iSmAmv1RTD9tI/391eaS2osheOZ0qwuruMJHoWrHsWzvqtPHL 4/3A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638495; x=1748243295; 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=T0gY3g4CMyk/KLPQ47ChexP08SbMxnytGLgjzVXuWIc=; b=PW3hPN8ltPf/7PPt596aECqpo5q1PNEwGMOMPwR9KTN4yFRZNhAcPoBMedrdua4/5S NfnDrIzKz11RTP9bnzfapXbZl0/oGXuu+swPmmW0ktNHavjl7RtcfUxqJBMASRfyaS3/ 7/MdchNqWySIX41mCIFOV53oRiMTBHjP1nO1guX2UNyx+ib23hNgsH5oxjORXTXvkQma Jh4sBVjjA8X0rOkbMAN/UL6SKLdfx156JjBcT9phmxmlBOq1hDN38lZOhKzRAjfrLYhD qwh0d1mlm/NNtzw7/KO4qhZ+Omb0ZhKPS6PF5jmfww4CmFrIpg+KSVYq5fYBv7vr1Q1m i4aw== X-Forwarded-Encrypted: i=1; AJvYcCUK3MM5J4R3TDYeaZNZ+yuIaBKaph6AINyoOI8MGxSyYj59X7lgnA3q51jvxoBTmvH+dpBn4FOCHYuBSpg=@vger.kernel.org X-Gm-Message-State: AOJu0Yx6VgHX//YTE56lqqaDZHK2p3ZSCM8DGxiGxBz/xUP8Sgm/0Hxm vVF9hLmPxhf3myCu+JcxhiWx0pQL/4H6Mgila6VnMKgvF3N4JzeujAP07+eAy1RoM9w= X-Gm-Gg: ASbGncsrOGnQglX2yb8XV2RnH6WOgAeDxlp3PQG6sA/xXAnqs+E8U6DM1w3O8OpkPJm tejSCb6F7/tIaZJ5RDKkvIlzjdhqKkAoW9SzvqxHUwCg6x/wZlcbYHt+WLFPGoZyushDcMdv8BR aT53SsPYhjdFrDLZ1ydaXUSRngR69yzSiLnHK5GsbxsLjuimqNya5rrRTAB1axNbM7J4UE0laBm 8KsQugQ9R1F/UdgoJwDjBosgW0HNERO15ygBcgmQK+U3ADOOnPiUK7KgV7MfOzzRn4qEIH6rG8q zNs7VKtyrHyJK9arJIaBe0WgQ2s9VveZDRNq3vQBq0wxYvmapxOc X-Google-Smtp-Source: AGHT+IH9j6Bth5f8cWmvK9+922RPLy2g7bS9UUlSkK9L8CsCt0G/VVlItFC0SYxSb2QpytTZz9o0Uw== X-Received: by 2002:aa7:88c8:0:b0:73e:2dc5:a93c with SMTP id d2e1a72fcca58-742a97c4fd9mr15166932b3a.11.1747638495149; Mon, 19 May 2025 00:08:15 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-742a970c86asm5738760b3a.57.2025.05.19.00.08.14 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:14 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 08/15] rust: opp: Add initial abstractions for OPP framework Date: Mon, 19 May 2025 12:37:13 +0530 Message-Id: <1a237a773715cb0738d831aeef9352ed04d2eac8.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Introduce initial Rust abstractions for the Operating Performance Points (OPP) framework. This includes bindings for `struct dev_pm_opp` and `struct dev_pm_opp_data`, laying the groundwork for further OPP integration. Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 2 + rust/kernel/opp.rs | 299 ++++++++++++++++++++++++++++++++ 4 files changed, 303 insertions(+) create mode 100644 rust/kernel/opp.rs diff --git a/MAINTAINERS b/MAINTAINERS index 475abf72869c..931e418f89ed 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -18165,6 +18165,7 @@ F: Documentation/devicetree/bindings/opp/ F: Documentation/power/opp.rst F: drivers/opp/ F: include/linux/pm_opp.h +F: rust/kernel/opp.rs =20 OPL4 DRIVER M: Clemens Ladisch diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index ac92c67d2c38..529f22891e0b 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index de0a840fcc99..ea589254b4ac 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -67,6 +67,8 @@ #[cfg(CONFIG_NET)] pub mod net; pub mod of; +#[cfg(CONFIG_PM_OPP)] +pub mod opp; pub mod page; #[cfg(CONFIG_PCI)] pub mod pci; diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs new file mode 100644 index 000000000000..8f0493a8b6e8 --- /dev/null +++ b/rust/kernel/opp.rs @@ -0,0 +1,299 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Operating performance points. +//! +//! This module provides rust abstractions for interacting with the OPP su= bsystem. +//! +//! C header: [`include/linux/pm_opp.h`](srctree/include/linux/pm_opp.h) +//! +//! Reference: + +use crate::{ + clk::Hertz, + device::Device, + error::{code::*, to_result, Result}, + ffi::c_ulong, + types::{ARef, AlwaysRefCounted, Opaque}, +}; + +use core::ptr; + +/// The voltage unit. +/// +/// Represents voltage in microvolts, wrapping a [`c_ulong`] value. +/// +/// ## Examples +/// +/// ``` +/// use kernel::opp::MicroVolt; +/// +/// let raw =3D 90500; +/// let volt =3D MicroVolt(raw); +/// +/// assert_eq!(usize::from(volt), raw); +/// assert_eq!(volt, MicroVolt(raw)); +/// ``` +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub struct MicroVolt(pub c_ulong); + +impl From for c_ulong { + #[inline] + fn from(volt: MicroVolt) -> Self { + volt.0 + } +} + +/// The power unit. +/// +/// Represents power in microwatts, wrapping a [`c_ulong`] value. +/// +/// ## Examples +/// +/// ``` +/// use kernel::opp::MicroWatt; +/// +/// let raw =3D 1000000; +/// let power =3D MicroWatt(raw); +/// +/// assert_eq!(usize::from(power), raw); +/// assert_eq!(power, MicroWatt(raw)); +/// ``` +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub struct MicroWatt(pub c_ulong); + +impl From for c_ulong { + #[inline] + fn from(power: MicroWatt) -> Self { + power.0 + } +} + +/// Handle for a dynamically created [`OPP`]. +/// +/// The associated [`OPP`] is automatically removed when the [`Token`] is = dropped. +/// +/// ## Examples +/// +/// The following example demonstrates how to create an [`OPP`] dynamicall= y. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::{Data, MicroVolt, Token}; +/// use kernel::types::ARef; +/// +/// fn create_opp(dev: &ARef, freq: Hertz, volt: MicroVolt, level:= u32) -> Result { +/// let data =3D Data::new(freq, volt, level, false); +/// +/// // OPP is removed once token goes out of scope. +/// data.add_opp(dev) +/// } +/// ``` +pub struct Token { + dev: ARef, + freq: Hertz, +} + +impl Token { + /// Dynamically adds an [`OPP`] and returns a [`Token`] that removes i= t on drop. + fn new(dev: &ARef, mut data: Data) -> Result { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] 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 [`De= vice`] and its safety + // requirements. + unsafe { bindings::dev_pm_opp_remove(self.dev.as_raw(), self.freq.= into()) }; + } +} + +/// OPP data. +/// +/// Rust abstraction for the C `struct dev_pm_opp_data`, used to define op= erating performance +/// points (OPPs) dynamically. +/// +/// ## Examples +/// +/// The following example demonstrates how to create an [`OPP`] with [`Dat= a`]. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::{Data, MicroVolt, Token}; +/// use kernel::types::ARef; +/// +/// fn create_opp(dev: &ARef, freq: Hertz, volt: MicroVolt, level:= u32) -> Result { +/// let data =3D Data::new(freq, volt, level, false); +/// +/// // OPP is removed once token goes out of scope. +/// data.add_opp(dev) +/// } +/// ``` +#[repr(transparent)] +pub struct Data(bindings::dev_pm_opp_data); + +impl Data { + /// Creates a new instance of [`Data`]. + /// + /// This can be used to define a dynamic OPP to be added to a device. + pub fn new(freq: Hertz, volt: MicroVolt, level: u32, turbo: bool) -> S= elf { + Self(bindings::dev_pm_opp_data { + turbo, + freq: freq.into(), + u_volt: volt.into(), + level, + }) + } + + /// Adds an [`OPP`] dynamically. + /// + /// Returns a [`Token`] that ensures the OPP is automatically removed + /// when it goes out of scope. + #[inline] + pub fn add_opp(self, dev: &ARef) -> Result { + Token::new(dev, self) + } + + /// Returns the frequency associated with this OPP data. + #[inline] + fn freq(&self) -> Hertz { + Hertz(self.0.freq) + } +} + +/// A reference-counted Operating performance point (OPP). +/// +/// Rust abstraction for the C `struct dev_pm_opp`. +/// +/// # Invariants +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of= the [`OPP`]. +/// +/// Instances of this type are reference-counted. The reference count is i= ncremented by the +/// `dev_pm_opp_get` function and decremented by `dev_pm_opp_put`. The Rus= t 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 cod= e. +#[repr(transparent)] +pub struct OPP(Opaque); + +/// SAFETY: It is okay to send the ownership of [`OPP`] across thread boun= daries. +unsafe impl Send for OPP {} + +/// SAFETY: It is okay to access [`OPP`] through shared references from ot= her threads because we're +/// either accessing properties that don't change or that are properly syn= chronised by C code. +unsafe impl Sync for OPP {} + +/// SAFETY: The type invariants guarantee that [`OPP`] is always refcounte= d. +unsafe impl AlwaysRefCounted for OPP { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference means that the refc= ount is nonzero. + unsafe { bindings::dev_pm_opp_get(self.0.get()) }; + } + + unsafe fn dec_ref(obj: ptr::NonNull) { + // SAFETY: The safety requirements guarantee that the refcount is = nonzero. + unsafe { bindings::dev_pm_opp_put(obj.cast().as_ptr()) } + } +} + +impl OPP { + /// Creates an owned reference to a [`OPP`] from a valid pointer. + /// + /// The refcount is incremented by the C code and will be decremented = by `dec_ref` when the + /// [`ARef`] object is dropped. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and the refcount of the= [`OPP`] is incremented. + /// The caller must also ensure that it doesn't explicitly drop the re= fcount 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) -> Re= sult> { + let ptr =3D ptr::NonNull::new(ptr).ok_or(ENODEV)?; + + // SAFETY: The safety requirements guarantee the validity of the p= ointer. + // + // INVARIANT: The reference-count is decremented when [`OPP`] goes= out of scope. + Ok(unsafe { ARef::from_raw(ptr.cast()) }) + } + + /// Creates a reference to a [`OPP`] from a valid pointer. + /// + /// The refcount is not updated by the Rust API unless the returned re= ference is converted to + /// an [`ARef`] object. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for t= he duration of `'a`. + #[inline] + pub unsafe fn from_raw_opp<'a>(ptr: *mut bindings::dev_pm_opp) -> Resu= lt<&'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(trans= parent)`. + Ok(unsafe { &*ptr.cast() }) + } + + #[inline] + fn as_raw(&self) -> *mut bindings::dev_pm_opp { + self.0.get() + } + + /// Returns the frequency of an [`OPP`]. + pub fn freq(&self, index: Option) -> Hertz { + let index =3D index.unwrap_or(0); + + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + Hertz(unsafe { bindings::dev_pm_opp_get_freq_indexed(self.as_raw()= , index) }) + } + + /// Returns the voltage of an [`OPP`]. + #[inline] + pub fn voltage(&self) -> MicroVolt { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + MicroVolt(unsafe { bindings::dev_pm_opp_get_voltage(self.as_raw())= }) + } + + /// Returns the level of an [`OPP`]. + #[inline] + pub fn level(&self) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_level(self.as_raw()) } + } + + /// Returns the power of an [`OPP`]. + #[inline] + pub fn power(&self) -> MicroWatt { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + MicroWatt(unsafe { bindings::dev_pm_opp_get_power(self.as_raw()) }) + } + + /// Returns the required pstate of an [`OPP`]. + #[inline] + pub fn required_pstate(&self, index: u32) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_required_pstate(self.as_raw(), i= ndex) } + } + + /// Returns true if the [`OPP`] is turbo. + #[inline] + pub fn is_turbo(&self) -> bool { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_is_turbo(self.as_raw()) } + } +} --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pf1-f176.google.com (mail-pf1-f176.google.com [209.85.210.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 0BE9126A0CC for ; Mon, 19 May 2025 07:08:19 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.176 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638503; cv=none; b=HbT4vyZMk3txVile4KhKa+MIMrmQ/l4Jo2QumjyYnf06hKZ/SLNTUAJYAKCjGmGIVN0nDH8AWLnKaNExRBvxRg+R5w1g6SzqJZefKk83ZWBslC8/Wh5ztTfNZub04mtMCMtNxl27sBmxvMuf5bPeQD4v48YFGd7ubndovKELyds= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638503; c=relaxed/simple; bh=RAjLeKI3WBuAp6e6mJAu5A1TpMkFZi2yh4Xbioapaok=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=fhn4Sy+D0+66n4YyJF/Cw6zdcEXO3n9zW/Q7HcI20SK228ePYH7vpgkdQ9Eob78W5HGpD8Mu/nUQAu59K8j8PKYbtb2m+GuAiM7LmPGos4CEx5KW7/6d4eHX9T0f1hIChJKlCAoUwfEbA9/GBH0ssxBcRbr+0qbcRoKKVtK/NQU= 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=CWeFw3kO; arc=none smtp.client-ip=209.85.210.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="CWeFw3kO" Received: by mail-pf1-f176.google.com with SMTP id d2e1a72fcca58-742c27df0daso819817b3a.1 for ; Mon, 19 May 2025 00:08:19 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638499; x=1748243299; 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=cO4wnRGM2Ejv79vsyqjeDReSjXsKi/ultczUPSVrwTg=; b=CWeFw3kOHoxrQx+VQDnw/TRVdyf+4Vxm0WcMFCVcaYFErcy1yB6sFDTtCK+jTwhaqS wImkCAm04H7PK7KzfvRmynv02pBgf5UDgoNJcBfGQ1Zd8PDw5zUb77CquQixsXG9M1FC sVMnyu6ZOjrIVTtrxAStrfFQouQddyWeD3xGCb7UicZH7+hI6mhseiTzAsNaxX5kabI4 2z6oi+/H7dT4cAOm91ePfiwDTI9OM7xMwlvArgdcA3YDd9mhsPXP9W8XXa5fUBm+GEnq 16mjib8rQ12BLsW6LdNSDsOY+NOqr+IAwlfNppXREEjioqmzwcYM/tKD/KbFmtCh4vXk R2ew== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638499; x=1748243299; 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=cO4wnRGM2Ejv79vsyqjeDReSjXsKi/ultczUPSVrwTg=; b=jf1UlcxDLQB6J9hzB+kBFznqkQ21HICu93cOm6dDO0BfCXPcoz+W0K9/fVDolV+DGb mwJFir9fsyX6m+Qk5r748hH284KHY8x9rV2ICIfzJ0IOj16Llc6/GoHxC4jGcZgX9daA G+I2kiHKkuPYCQY4H9g92YY00A3aj51Taxl05EAP5NrtaE9BfpvZrVaFR1sn0RHLlHkO 90RB+WU+InLS+5FncP6w53dXx6YzrXIfqB4ezHbQ9LYxWJ2nCYazpRWwoajO3SAeOWa6 n46dUwcK2nAGGDE9jiLTiZu7xYnYzssho3T0O2RMtl54Vj3VbTeN/vV6WqomIC9rEJf/ kOCw== X-Forwarded-Encrypted: i=1; AJvYcCWhKGupmk1HE+l/pyhlbFNAD5YuMqi1uGxCrb4zk3NwcSbXUw8hpOu4kDXDV2xb0du1SClnxqTFcqlrEHA=@vger.kernel.org X-Gm-Message-State: AOJu0Yy00koGEZyJZvOYXYmZl3l/LtkTn/vA3AQog5xh3n4RP1BYEC90 Cam8C9vxWzkGjuy7ZZaDAgsuEmvzsmlIvm0yv1TvMrDYsx+t3jHcbotOcRD62lw9avE= X-Gm-Gg: ASbGncuXrkntFdBen0Iyzju+K5/HqPckNJLe7oYnG0W/ngEdULrI2pmjgYm5AN/nIte hbcsd1v0cby2ULVMVswVA/Zb1sQ68Em4HUtl0NcAoaJYMz55sEHyX4WmyQgPejkwNI0Fb8YQKBA k4PfmjZE9eRx2rplnsG0YxCiZ+InLbijltmLHE67/2eLE/QiRRM8ACNaoxWdV/Rw8qDp72DCCb9 nMW4NaPJzMaGq8i/kRAB3b0b3JD2hRa25z+XD5vjEXIU7pWC3VUbQm9axCjFInhrCST2eArwKdc 6uhbUu0xScALdMbXzN5yeoGC16x0PH5fU9bK/In+IV4+VPVf6lkT X-Google-Smtp-Source: AGHT+IF91jPSa77aCMbVavywdkUMQvhenQWNThM2xiCVN5W+Sa/SaDi89mcOEbghpdMcZlwk5UkZ2Q== X-Received: by 2002:a05:6a21:3990:b0:1f5:7ea8:a791 with SMTP id adf61e73a8af0-2162189ce3fmr16488703637.10.1747638499079; Mon, 19 May 2025 00:08:19 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-742a9739cdesm5558891b3a.82.2025.05.19.00.08.18 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:18 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 09/15] rust: opp: Add abstractions for the OPP table Date: Mon, 19 May 2025 12:37:14 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Introduce Rust abstractions for `struct opp_table`, enabling access to OPP tables from Rust. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 487 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 486 insertions(+), 1 deletion(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 8f0493a8b6e8..18f55c00a4d6 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -10,8 +10,9 @@ =20 use crate::{ clk::Hertz, + cpumask::{Cpumask, CpumaskVar}, device::Device, - error::{code::*, to_result, Result}, + error::{code::*, from_err_ptr, to_result, Error, Result}, ffi::c_ulong, types::{ARef, AlwaysRefCounted, Opaque}, }; @@ -171,6 +172,469 @@ fn freq(&self) -> Hertz { } } =20 +/// [`OPP`] search options. +/// +/// ## Examples +/// +/// Defines how to search for an [`OPP`] in a [`Table`] relative to a freq= uency. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::error::Result; +/// use kernel::opp::{OPP, SearchType, Table}; +/// use kernel::types::ARef; +/// +/// fn find_opp(table: &Table, freq: Hertz) -> Result> { +/// let opp =3D table.opp_from_freq(freq, Some(true), None, SearchType= ::Exact)?; +/// +/// pr_info!("OPP frequency is: {:?}\n", opp.freq(None)); +/// pr_info!("OPP voltage is: {:?}\n", opp.voltage()); +/// pr_info!("OPP level is: {}\n", opp.level()); +/// pr_info!("OPP power is: {:?}\n", opp.power()); +/// +/// Ok(opp) +/// } +/// ``` +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum SearchType { + /// Match the exact frequency. + Exact, + /// Find the highest frequency less than or equal to the given value. + Floor, + /// Find the lowest frequency greater than or equal to the given value. + Ceil, +} + +/// A reference-counted OPP table. +/// +/// Rust abstraction for the C `struct opp_table`. +/// +/// # Invariants +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of= the [`Table`]. +/// +/// Instances of this type are reference-counted. +/// +/// ## Examples +/// +/// The following example demonstrates how to get OPP [`Table`] for a [`Cp= umask`] and set its +/// frequency. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::cpumask::Cpumask; +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::Table; +/// use kernel::types::ARef; +/// +/// fn get_table(dev: &ARef, mask: &mut Cpumask, freq: Hertz) -> R= esult { +/// let mut opp_table =3D Table::from_of_cpumask(dev, mask)?; +/// +/// if opp_table.opp_count()? =3D=3D 0 { +/// return Err(EINVAL); +/// } +/// +/// pr_info!("Max transition latency is: {} ns\n", opp_table.max_trans= ition_latency_ns()); +/// pr_info!("Suspend frequency is: {:?}\n", opp_table.suspend_freq()); +/// +/// opp_table.set_rate(freq)?; +/// Ok(opp_table) +/// } +/// ``` +pub struct Table { + ptr: *mut bindings::opp_table, + dev: ARef, + #[allow(dead_code)] + em: bool, + #[allow(dead_code)] + of: bool, + cpus: Option, +} + +/// SAFETY: It is okay to send ownership of [`Table`] across thread bounda= ries. +unsafe impl Send for Table {} + +/// SAFETY: It is okay to access [`Table`] through shared references from = other threads because +/// we're either accessing properties that don't change or that are proper= ly synchronised by C code. +unsafe impl Sync for Table {} + +impl Table { + /// Creates a new reference-counted [`Table`] from a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null. + unsafe fn from_raw_table(ptr: *mut bindings::opp_table, dev: &ARef) -> Self { + // SAFETY: By the safety requirements, ptr is valid and its refcou= nt will be incremented. + // + // INVARIANT: The reference-count is decremented when [`Table`] go= es out of scope. + unsafe { bindings::dev_pm_opp_get_opp_table_ref(ptr) }; + + Self { + ptr, + dev: dev.clone(), + em: false, + of: false, + cpus: None, + } + } + + /// Creates a new reference-counted [`Table`] instance for a [`Device`= ]. + pub fn from_dev(dev: &Device) -> Result { + // SAFETY: The requirements are satisfied by the existence of the = [`Device`] and its safety + // requirements. + // + // INVARIANT: The reference-count is incremented by the C code and= is decremented when + // [`Table`] goes out of scope. + let ptr =3D from_err_ptr(unsafe { bindings::dev_pm_opp_get_opp_tab= le(dev.as_raw()) })?; + + Ok(Self { + ptr, + dev: dev.into(), + em: false, + of: false, + cpus: None, + }) + } + + /// Creates a new reference-counted [`Table`] instance for a [`Device`= ] based on device tree + /// entries. + #[cfg(CONFIG_OF)] + pub fn from_of(dev: &ARef, index: i32) -> Result { + // SAFETY: The requirements are satisfied by the existence of the = [`Device`] and its safety + // requirements. + // + // INVARIANT: The reference-count is incremented by the C code and= is decremented when + // [`Table`] goes out of scope. + to_result(unsafe { bindings::dev_pm_opp_of_add_table_indexed(dev.a= s_raw(), index) })?; + + // Get the newly created [`Table`]. + let mut table =3D Self::from_dev(dev)?; + table.of =3D true; + + Ok(table) + } + + /// Remove device tree based [`Table`]. + #[cfg(CONFIG_OF)] + #[inline] + fn remove_of(&self) { + // SAFETY: The requirements are satisfied by the existence of the = [`Device`] and its safety + // requirements. We took the reference from [`from_of`] earlier, i= t is safe to drop the + // same now. + unsafe { bindings::dev_pm_opp_of_remove_table(self.dev.as_raw()) }; + } + + /// Creates a new reference-counted [`Table`] instance for a [`Cpumask= `] based on device tree + /// entries. + #[cfg(CONFIG_OF)] + pub fn from_of_cpumask(dev: &Device, cpumask: &mut Cpumask) -> Result<= Self> { + // SAFETY: The cpumask is valid and the returned pointer will be o= wned by the [`Table`] + // instance. + // + // INVARIANT: The reference-count is incremented by the C code and= is decremented when + // [`Table`] goes out of scope. + to_result(unsafe { bindings::dev_pm_opp_of_cpumask_add_table(cpuma= sk.as_raw()) })?; + + // Fetch the newly created table. + let mut table =3D Self::from_dev(dev)?; + table.cpus =3D Some(CpumaskVar::try_clone(cpumask)?); + + Ok(table) + } + + /// Remove device tree based [`Table`] for a [`Cpumask`]. + #[cfg(CONFIG_OF)] + #[inline] + fn remove_of_cpumask(&self, cpumask: &Cpumask) { + // SAFETY: The cpumask is valid and we took the reference from [`f= rom_of_cpumask`] earlier, + // it is safe to drop the same now. + unsafe { bindings::dev_pm_opp_of_cpumask_remove_table(cpumask.as_r= aw()) }; + } + + /// Returns the number of [`OPP`]s in the [`Table`]. + pub fn opp_count(&self) -> Result { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + let ret =3D unsafe { bindings::dev_pm_opp_get_opp_count(self.dev.a= s_raw()) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ret as u32) + } + } + + /// Returns max clock latency (in nanoseconds) of the [`OPP`]s in the = [`Table`]. + #[inline] + pub fn max_clock_latency_ns(&self) -> usize { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_clock_latency(self.dev.as_ra= w()) } + } + + /// Returns max volt latency (in nanoseconds) of the [`OPP`]s in the [= `Table`]. + #[inline] + pub fn max_volt_latency_ns(&self) -> usize { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_volt_latency(self.dev.as_raw= ()) } + } + + /// Returns max transition latency (in nanoseconds) of the [`OPP`]s in= the [`Table`]. + #[inline] + pub fn max_transition_latency_ns(&self) -> usize { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_transition_latency(self.dev.= as_raw()) } + } + + /// Returns the suspend [`OPP`]'s frequency. + #[inline] + pub fn suspend_freq(&self) -> Hertz { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + Hertz(unsafe { bindings::dev_pm_opp_get_suspend_opp_freq(self.dev.= as_raw()) }) + } + + /// Synchronizes regulators used by the [`Table`]. + #[inline] + pub fn sync_regulators(&self) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_sync_regulators(self.dev.a= s_raw()) }) + } + + /// Gets sharing CPUs. + #[inline] + pub fn sharing_cpus(dev: &Device, cpumask: &mut Cpumask) -> Result<()>= { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_get_sharing_cpus(dev.as_ra= w(), cpumask.as_raw()) }) + } + + /// Sets sharing CPUs. + pub fn set_sharing_cpus(&mut self, cpumask: &mut Cpumask) -> Result<()= > { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_set_sharing_cpus(self.dev.as_raw(), cpuma= sk.as_raw()) + })?; + + if let Some(mask) =3D self.cpus.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)] + #[inline] + pub fn of_sharing_cpus(dev: &Device, cpumask: &mut Cpumask) -> Result<= ()> { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_of_get_sharing_cpus(dev.as_raw(), cpumask= .as_raw()) + }) + } + + /// Updates the voltage value for an [`OPP`]. + #[inline] + pub fn adjust_voltage( + &self, + freq: Hertz, + volt: MicroVolt, + volt_min: MicroVolt, + volt_max: MicroVolt, + ) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_adjust_voltage( + self.dev.as_raw(), + freq.into(), + volt.into(), + volt_min.into(), + volt_max.into(), + ) + }) + } + + /// Configures device with [`OPP`] matching the frequency value. + #[inline] + pub fn set_rate(&self, freq: Hertz) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_set_rate(self.dev.as_raw()= , freq.into()) }) + } + + /// Configures device with [`OPP`]. + #[inline] + pub fn set_opp(&self, opp: &OPP) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] 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, + freq: Hertz, + available: Option, + index: Option, + stype: SearchType, + ) -> Result> { + let raw_dev =3D self.dev.as_raw(); + let index =3D index.unwrap_or(0); + let mut rate =3D freq.into(); + + let ptr =3D from_err_ptr(match stype { + SearchType::Exact =3D> { + if let Some(available) =3D available { + // SAFETY: The requirements are satisfied by the exist= ence of [`Device`] and + // its safety requirements. The returned pointer will = be owned by the new + // [`OPP`] instance. + unsafe { + bindings::dev_pm_opp_find_freq_exact_indexed( + raw_dev, rate, index, available, + ) + } + } else { + return Err(EINVAL); + } + } + + // SAFETY: The requirements are satisfied by the existence of = [`Device`] and its safety + // requirements. The returned pointer will be owned by the new= [`OPP`] instance. + SearchType::Ceil =3D> unsafe { + bindings::dev_pm_opp_find_freq_ceil_indexed(raw_dev, &mut = rate, index) + }, + + // SAFETY: The requirements are satisfied by the existence of = [`Device`] and its safety + // requirements. The returned pointer will be owned by the new= [`OPP`] instance. + SearchType::Floor =3D> unsafe { + bindings::dev_pm_opp_find_freq_floor_indexed(raw_dev, &mut= rate, 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) -> Res= ult> { + let raw_dev =3D self.dev.as_raw(); + + let ptr =3D from_err_ptr(match stype { + // SAFETY: The requirements are satisfied by the existence of = [`Device`] and its safety + // requirements. The returned pointer will be owned by the new= [`OPP`] instance. + SearchType::Exact =3D> unsafe { bindings::dev_pm_opp_find_leve= l_exact(raw_dev, level) }, + + // SAFETY: The requirements are satisfied by the existence of = [`Device`] and its safety + // requirements. The returned pointer will be owned by the new= [`OPP`] instance. + SearchType::Ceil =3D> unsafe { + bindings::dev_pm_opp_find_level_ceil(raw_dev, &mut level) + }, + + // SAFETY: The requirements are satisfied by the existence of = [`Device`] and its safety + // requirements. The returned pointer will be owned by the new= [`OPP`] instance. + SearchType::Floor =3D> unsafe { + bindings::dev_pm_opp_find_level_floor(raw_dev, &mut level) + }, + })?; + + // 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 raw_dev =3D self.dev.as_raw(); + + let ptr =3D from_err_ptr(match stype { + // The OPP core doesn't support this yet. + SearchType::Exact =3D> return Err(EINVAL), + + // SAFETY: The requirements are satisfied by the existence of = [`Device`] and its safety + // requirements. The returned pointer will be owned by the new= [`OPP`] instance. + SearchType::Ceil =3D> unsafe { + bindings::dev_pm_opp_find_bw_ceil(raw_dev, &mut bw, index) + }, + + // SAFETY: The requirements are satisfied by the existence of = [`Device`] and its safety + // requirements. The returned pointer will be owned by the new= [`OPP`] instance. + SearchType::Floor =3D> unsafe { + bindings::dev_pm_opp_find_bw_floor(raw_dev, &mut bw, index) + }, + })?; + + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp_owned(ptr) } + } + + /// Enables the [`OPP`]. + #[inline] + pub fn enable_opp(&self, freq: Hertz) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_enable(self.dev.as_raw(), = freq.into()) }) + } + + /// Disables the [`OPP`]. + #[inline] + pub fn disable_opp(&self, freq: Hertz) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_disable(self.dev.as_raw(),= freq.into()) }) + } + + /// Registers with the 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 [`De= vice`] and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_of_register_em(self.dev.as_raw(), cpumask= .as_raw()) + })?; + + self.em =3D true; + Ok(()) + } + + /// Unregisters with the Energy model. + #[cfg(all(CONFIG_OF, CONFIG_ENERGY_MODEL))] + #[inline] + fn of_unregister_em(&self) { + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. We registered with the EM framework earlier, it i= s safe to unregister now. + unsafe { bindings::em_dev_unregister_perf_domain(self.dev.as_raw()= ) }; + } +} + +impl Drop for Table { + fn drop(&mut self) { + // SAFETY: By the type invariants, we know that `self` owns a refe= rence, so it is safe + // to relinquish it now. + unsafe { bindings::dev_pm_opp_put_opp_table(self.ptr) }; + + #[cfg(CONFIG_OF)] + { + #[cfg(CONFIG_ENERGY_MODEL)] + if self.em { + self.of_unregister_em(); + } + + if self.of { + self.remove_of(); + } else if let Some(cpumask) =3D self.cpus.take() { + self.remove_of_cpumask(&cpumask); + } + } + } +} + /// A reference-counted Operating performance point (OPP). /// /// Rust abstraction for the C `struct dev_pm_opp`. @@ -184,6 +648,27 @@ fn freq(&self) -> Hertz { /// represents a pointer that owns a reference count on the [`OPP`]. /// /// A reference to the [`OPP`], &[`OPP`], isn't refcounted by the Rust cod= e. +/// +/// ## Examples +/// +/// The following example demonstrates how to get [`OPP`] corresponding to= a frequency value and +/// configure the device with it. +/// +/// ``` +/// use kernel::clk::Hertz; +/// use kernel::error::Result; +/// use kernel::opp::{SearchType, Table}; +/// +/// fn configure_opp(table: &Table, freq: Hertz) -> Result { +/// let opp =3D table.opp_from_freq(freq, Some(true), None, SearchType= ::Exact)?; +/// +/// if opp.freq(None) !=3D freq { +/// return Err(EINVAL); +/// } +/// +/// table.set_opp(&opp) +/// } +/// ``` #[repr(transparent)] pub struct OPP(Opaque); =20 --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pf1-f177.google.com (mail-pf1-f177.google.com [209.85.210.177]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id AB6B626A0F8 for ; Mon, 19 May 2025 07:08:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.177 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638505; cv=none; b=kfPL9D43+lwydQuVDHrKwkDtWhK/RVtm3c2voILfhNHmHpmtE2EA+ELsXH1BczkCo+6kMWNj3HOZ4AnkX7ADHBB2dUgliaKF0BWLPEDnuKXDJTwGvin/MvCU9fw4YahvbpBVXFlXGrM8Bk4GBypEHmqpnT3ptAG24uCi+PACJ1Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638505; c=relaxed/simple; bh=GQZ/C13qepiseJqyRqcGLUXRE9t1VF7vW3VUh3qqVoY=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=PeZ5msD7DYXyifyJaxYfUQvkvqo7meV2neJINsfJUwukw3hJe3m1ukuYvLHZyrOoAvWH76n31W+qhRtA/z9/8+QQPJaaKVvoXeJ+Y3FvMjtcwbiYEIWa1IaBER2CUqtDuj2GVCgHcUrO7L1SbkR8AhAgttX3ER/Q6U8Sd/rG9C8= 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=D9YCbw7Z; arc=none smtp.client-ip=209.85.210.177 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="D9YCbw7Z" Received: by mail-pf1-f177.google.com with SMTP id d2e1a72fcca58-73712952e1cso3751888b3a.1 for ; Mon, 19 May 2025 00:08:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638503; x=1748243303; 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=81nTFGvkA/IBrcIFlaJ92uVSha8rn1gDNqnm+5GgOQw=; b=D9YCbw7ZApPOTbxWi04xxtq55Q2gvReahm1BH5ikGbzOGhSkb8OPkurYUsYSmNxtyj saYfrEiXGzJGZgrrxARe7A0W2Q78sAj3Zqss3U9mqxMroIt9M0V3Yd4qiNDno1wf3FJO Ylp853auef4/9/ZdtikCqfSsvlXVSucc558p2MFtcDQOHG/0ReYyWpZoqqZLtSqTeNbt Y5sVbdA48cjUNrXYOI8on5dNl/CC23f8WfezUYfiN94ryJUixMUtS80d75oGTtJwuULk PtomNgdDr+YBHhHBOccYVxzd/xb0/DsvLw94jam6lBJIkEh013xRAr51hzItkNA5yYm4 P7og== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638503; x=1748243303; 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=81nTFGvkA/IBrcIFlaJ92uVSha8rn1gDNqnm+5GgOQw=; b=JFkIp6ppBovJ3imt69rbYfLLc8XyyPlcx5MNspKY/+qvo08UfzxV6UH4aUbdI5Kz3t kqqc4jcwk1zKTw3zZmqwXGr/VdutwfYnkr7KTmk4rzYCTsnrUP1QzLnZ6/auNvbqx8cA EwYNEMZGIGOOIXSqs9xdXKzthfSWyUDwkqmKMOsVDT+Cd2cjlVy1FJ54/+QJYX2ZkL8P FfYSXft5zM0qkrpKZLnK2veuq23rjEjHBw6qRVC9fv1ig9YG3w4EgQV0xMKGOsPNM4O6 0BFdWfMkmOlNjehs2l2SnhZfy3W3h2uB+0Bjd+tiVNotfg4Q1tlWjPADPdjlvYKY+LCT xkdA== X-Forwarded-Encrypted: i=1; AJvYcCU9y2Ihg+rEr4e4zwLu2dRqrxHzpWdHqi3YhrUloYSvBvU7VsMI/sfk+S+4JH5FhCC1/DlKkOEJT8vp4AE=@vger.kernel.org X-Gm-Message-State: AOJu0YztIXXBvCFt9I/sw8KDsLHk5VTcOIIz72kHEg5q54X5BJqwKtuB bRxjccI45Rq0JshB8jcgh+7X3YeZrO5oK1Y1NKgwpCje5kihEbQ+Dx7vtw1LVPHLkgE= X-Gm-Gg: ASbGncsI9IoL+Fm5kNfUa4hBGRiiGbDGoBPd7nZxMNy6o2INm6kD3/fVtXhS6tYPLoN igBhA2FRG9DKD21pi6eoILj08jRN/FA5L0u7r6cc/Nhj1vWifgmS18Fj/9Con7OuieXEmNXoZaL BqG5eHe31bGq160Bb9Cx82yPE0gwWScsryaCfWjqa6S/BHT03+4lc4pJ1BY+hCkl2x1n0vJM6/U LolaY5325R86UdMY+TW3X575xZppOILq79hQgr2NWBFyu6bx4Thn5bK8VUrZaqfFR0pSZnkkdto JkVabilih51GHSxjHf0jZ6bFytf/vuOSi7gkwWHGiIbl7LY0d3/M X-Google-Smtp-Source: AGHT+IHCRYPAYiAYx5Tx1UMCGZquBQ1QMiYKJ2/LxxD9n3pNoawWDcoNg8DtRj0MGmDb4xlY0ykjbA== X-Received: by 2002:a05:6a20:6a28:b0:201:4061:bd94 with SMTP id adf61e73a8af0-2170ccaf4e4mr15295210637.19.1747638502864; Mon, 19 May 2025 00:08:22 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-231d4e981desm53007485ad.124.2025.05.19.00.08.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:22 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 10/15] rust: opp: Add abstractions for the configuration options Date: Mon, 19 May 2025 12:37:15 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Introduce Rust abstractions for the OPP core configuration options, enabling safe access to various configurable aspects of the OPP framework. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 295 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 293 insertions(+), 2 deletions(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 18f55c00a4d6..7be6fd33d93f 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -12,12 +12,29 @@ clk::Hertz, cpumask::{Cpumask, CpumaskVar}, device::Device, - error::{code::*, from_err_ptr, to_result, Error, Result}, + error::{code::*, from_err_ptr, from_result, to_result, Error, Result, = VTABLE_DEFAULT_ERROR}, ffi::c_ulong, + prelude::*, + str::CString, types::{ARef, AlwaysRefCounted, Opaque}, }; =20 -use core::ptr; +use core::{marker::PhantomData, ptr}; + +use macros::vtable; + +/// Creates a null-terminated slice of pointers to [`Cstring`]s. +fn to_c_str_array(names: &[CString]) -> Result> { + // Allocated a null-terminated vector of pointers. + let mut list =3D KVec::with_capacity(names.len() + 1, GFP_KERNEL)?; + + for name in names.iter() { + list.push(name.as_ptr() as _, GFP_KERNEL)?; + } + + list.push(ptr::null(), GFP_KERNEL)?; + Ok(list) +} =20 /// The voltage unit. /// @@ -205,6 +222,280 @@ pub enum SearchType { Ceil, } =20 +/// OPP configuration callbacks. +/// +/// Implement this trait to customize OPP clock and regulator setup for yo= ur device. +#[vtable] +pub trait ConfigOps { + /// This is typically used to scale clocks when transitioning between = OPPs. + #[inline] + fn config_clks(_dev: &Device, _table: &Table, _opp: &OPP, _scaling_dow= n: bool) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// This provides access to the old and new OPPs, allowing for safe re= gulator adjustments. + #[inline] + fn config_regulators( + _dev: &Device, + _opp_old: &OPP, + _opp_new: &OPP, + _data: *mut *mut bindings::regulator, + _count: u32, + ) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } +} + +/// OPP configuration token. +/// +/// Returned by the OPP core when configuration is applied to a [`Device`]= . The associated +/// configuration is automatically cleared when the token is dropped. +pub struct ConfigToken(i32); + +impl Drop for ConfigToken { + fn drop(&mut self) { + // SAFETY: This is the same token value returned by the C code via= `dev_pm_opp_set_config`. + unsafe { bindings::dev_pm_opp_clear_config(self.0) }; + } +} + +/// OPP configurations. +/// +/// Rust abstraction for the C `struct dev_pm_opp_config`. +/// +/// ## Examples +/// +/// The following example demonstrates how to set OPP property-name config= uration for a [`Device`]. +/// +/// ``` +/// use kernel::device::Device; +/// use kernel::error::Result; +/// use kernel::opp::{Config, ConfigOps, ConfigToken}; +/// use kernel::str::CString; +/// use kernel::types::ARef; +/// use kernel::macros::vtable; +/// +/// #[derive(Default)] +/// struct Driver; +/// +/// #[vtable] +/// impl ConfigOps for Driver {} +/// +/// fn configure(dev: &ARef) -> Result { +/// let name =3D CString::try_from_fmt(fmt!("{}", "slow"))?; +/// +/// // The OPP configuration is cleared once the [`ConfigToken`] goes = out of scope. +/// Config::::new() +/// .set_prop_name(name)? +/// .set(dev) +/// } +/// ``` +#[derive(Default)] +pub struct Config +where + T: Default, +{ + clk_names: Option>, + prop_name: Option, + regulator_names: Option>, + supported_hw: Option>, + + // Tuple containing (required device, index) + required_dev: Option<(ARef, u32)>, + _data: PhantomData, +} + +impl Config { + /// Creates a new instance of [`Config`]. + #[inline] + pub fn new() -> Self { + Self::default() + } + + /// Initializes clock names. + pub fn set_clk_names(mut self, names: KVec) -> Result { + if self.clk_names.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.clk_names =3D Some(names); + Ok(self) + } + + /// Initializes property name. + pub fn set_prop_name(mut self, name: CString) -> Result { + if self.prop_name.is_some() { + return Err(EBUSY); + } + + self.prop_name =3D Some(name); + Ok(self) + } + + /// Initializes regulator names. + pub fn set_regulator_names(mut self, names: KVec) -> Result { + if self.regulator_names.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.regulator_names =3D Some(names); + + Ok(self) + } + + /// Initializes required devices. + pub fn set_required_dev(mut self, dev: ARef, index: u32) -> Re= sult { + if self.required_dev.is_some() { + return Err(EBUSY); + } + + self.required_dev =3D Some((dev, index)); + Ok(self) + } + + /// Initializes supported hardware. + pub fn set_supported_hw(mut self, hw: KVec) -> Result { + if self.supported_hw.is_some() { + return Err(EBUSY); + } + + if hw.is_empty() { + return Err(EINVAL); + } + + self.supported_hw =3D Some(hw); + Ok(self) + } + + /// Sets the configuration with the OPP core. + /// + /// The returned [`ConfigToken`] will remove the configuration when dr= opped. + pub fn set(self, dev: &Device) -> Result { + let (_clk_list, clk_names) =3D match &self.clk_names { + Some(x) =3D> { + let list =3D to_c_str_array(x)?; + let ptr =3D list.as_ptr(); + (Some(list), ptr) + } + None =3D> (None, ptr::null()), + }; + + let (_regulator_list, regulator_names) =3D match &self.regulator_n= ames { + Some(x) =3D> { + let list =3D to_c_str_array(x)?; + let ptr =3D list.as_ptr(); + (Some(list), ptr) + } + None =3D> (None, ptr::null()), + }; + + let prop_name =3D self + .prop_name + .as_ref() + .map_or(ptr::null(), |p| p.as_char_ptr()); + + let (supported_hw, supported_hw_count) =3D self + .supported_hw + .as_ref() + .map_or((ptr::null(), 0), |hw| (hw.as_ptr(), hw.len() as u32)); + + let (required_dev, required_dev_index) =3D self + .required_dev + .as_ref() + .map_or((ptr::null_mut(), 0), |(dev, idx)| (dev.as_raw(), *idx= )); + + let mut config =3D bindings::dev_pm_opp_config { + clk_names, + config_clks: if T::HAS_CONFIG_CLKS { + Some(Self::config_clks) + } else { + None + }, + prop_name, + regulator_names, + config_regulators: if T::HAS_CONFIG_REGULATORS { + Some(Self::config_regulators) + } else { + None + }, + supported_hw, + supported_hw_count, + + required_dev, + required_dev_index, + }; + + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. The OPP core guarantees not to access fields of [= `Config`] after this call + // and so we don't need to save a copy of them for future use. + let ret =3D unsafe { bindings::dev_pm_opp_set_config(dev.as_raw(),= &mut config) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ConfigToken(ret)) + } + } + + /// Config's clk callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn config_clks( + dev: *mut bindings::device, + opp_table: *mut bindings::opp_table, + opp: *mut bindings::dev_pm_opp, + _data: *mut kernel::ffi::c_void, + scaling_down: bool, + ) -> kernel::ffi::c_int { + from_result(|| { + // SAFETY: 'dev' is guaranteed by the C code to be valid. + let dev =3D unsafe { Device::get_device(dev) }; + T::config_clks( + &dev, + // SAFETY: 'opp_table' is guaranteed by the C code to be v= alid. + &unsafe { Table::from_raw_table(opp_table, &dev) }, + // SAFETY: 'opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp(opp)? }, + scaling_down, + ) + .map(|()| 0) + }) + } + + /// Config's regulator callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn config_regulators( + dev: *mut bindings::device, + old_opp: *mut bindings::dev_pm_opp, + new_opp: *mut bindings::dev_pm_opp, + regulators: *mut *mut bindings::regulator, + count: kernel::ffi::c_uint, + ) -> kernel::ffi::c_int { + from_result(|| { + // SAFETY: 'dev' is guaranteed by the C code to be valid. + let dev =3D unsafe { Device::get_device(dev) }; + T::config_regulators( + &dev, + // SAFETY: 'old_opp' is guaranteed by the C code to be val= id. + unsafe { OPP::from_raw_opp(old_opp)? }, + // SAFETY: 'new_opp' is guaranteed by the C code to be val= id. + unsafe { OPP::from_raw_opp(new_opp)? }, + regulators, + count, + ) + .map(|()| 0) + }) + } +} + /// A reference-counted OPP table. /// /// Rust abstraction for the C `struct opp_table`. --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pf1-f179.google.com (mail-pf1-f179.google.com [209.85.210.179]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8C4BB26A1DB for ; Mon, 19 May 2025 07:08:28 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.179 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638510; cv=none; b=oVCeuJQ47HylcjvhRuaa5Lr0LV5e96HECYE2ITb1gVa1+8CbtR4vJLqCWS8tsWvAnEWlg2NiUQ/a6sy3nT1ZYnU62EJ5x6Ex6E6jahW01x11rq6Hbg5n/rWK6W3I1FCGtxRLwOabAsfgiMEpW0lqRtvrrD6X9c4O09W+ZfugJPE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638510; c=relaxed/simple; bh=QXMxH7iSPfBkj0Ia64GJx6G2+8KNn9rCCD8XzU/DQ38=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=hzURFX+xhMTGea96h2sh7lI8ge3h81zJKXUk00v6i4jhCAPZWAWaWEGrwKNNoWLchWulFEtBWftSJ87rFq9KG58KtILRSOav55LXE8wkQfitdYT0aUmkh3z3TQZMXGuY3LWyNlSwf2Lzf7i2EYALZ6aTu+fS0TMf3Voj0VqiPD0= 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=gPP2Pc/I; arc=none smtp.client-ip=209.85.210.179 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="gPP2Pc/I" Received: by mail-pf1-f179.google.com with SMTP id d2e1a72fcca58-7370a2d1981so3194095b3a.2 for ; Mon, 19 May 2025 00:08:28 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638508; x=1748243308; 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=PeAHfrp/tGXc/RJP/mrXOf/ij0zku7wQhR0SuexE3Ok=; b=gPP2Pc/IIopet5v0+azJQDtWwrfCFlgkVaGz6TR8CE53W27m/jnturTEikumvOSypJ RdNabbZ9vJBNuQAii66DtCrW6MlCdCJnS+Z+n+xYmVZbSVqZlcnEjsCoF7KoXZPMnPn1 eBKw/IDcc4NhlhocgcnNuPEgqaKEvk0sr22PB7jYdsEYf8hAA/9QRRoJuOlCdRi5LQFc BCban8AKVsOWeers59uF9rllgQMiFu+NuPHRD8W/NuJLNNOcFDFOyeEHyO6NqkK97AQ9 T9/PwfVSmBspEDCU6FrZ24C6yZ53drQy05p1gg8EPWRx+33yNl+dOaB2B0VhUrMqema5 6RTw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638508; x=1748243308; 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=PeAHfrp/tGXc/RJP/mrXOf/ij0zku7wQhR0SuexE3Ok=; b=cE/xOStgwb7h9GXj4sq//F3WlNleF+PGcpq7wi3XP/sKL3k6XONC+01RT/1cDHct21 nlJuv1N0pxe84qRf4MDsyIl65raaeN2KrYmE+PyImTWxoWjdLddk2Ai0eTQCXxY097R7 kabsGBW2iR/5vm2Unsdc4MVv1H1U3WVMYpFjrB69NtmdnXeV6uW7PChuo1hVOZDBm4h1 06WeeUAculvbf9p5K4XJrb6rTN6jQyS6nliSge/gHc9JjG0iTCUyLA+9vc9IV37ffv9Q fN0g3ahtex3WeUeK4qgC+XotfZBsdT5433yLOtwaFowp2uU1E/JJ9IYEi1ncSkVuKHSN LJOQ== X-Forwarded-Encrypted: i=1; AJvYcCUb6J4awV/SVgyI30fK83ixKymcylG/KuKLYwuKjSpEftYyJprmCiYwqFOs4ZZNCJH/tR6KmXvtjt65fUc=@vger.kernel.org X-Gm-Message-State: AOJu0YyeRuhMcEERXygHiwE0PYwyYM5JnLxtre9weYu3EwanSpDNbPjV fG44uTFyFu/pCtDlQNqp2VKdZ3tANoRA2YIgOgXyEOhVI8D5WfW33mVq1XKiKcK4pMg= X-Gm-Gg: ASbGncvylbi1tjN0240T1i+6oJRnt4PI3PhIf7sTJZMuVpK3xNIX07iHWgB2XHv8NUN oGqeTeOfNyWuWraxFYDlFbdUneo+Lo0xtrPkh4GQusiQeUuVLzuzcJX2anVWSmLSXBhth2ppuCz GJsLIwDwXywc4sAPMHjy4Fhps9gbP0zSasA7cq2wsd3pHLIyMqyHbSEEi4pw8VQjxbAfQuZpefW V1rRBERfifgLxVUu6/jKCpyvdTstfPuqNWnPPkKU4Zvx397KUoCDKm5X3LjWnynLOpEAKEGWbPH qRamg158+uAB/7SvLVg7MU5rn/j1z+FNP+I8oWdVtVy4UUdQZhbr X-Google-Smtp-Source: AGHT+IGia5Bc+1wwYUidEZDs6sa6shkoF8XVQlwQc4PAGsofPvtXfajZaWlVn8wBbERNG8VrD6Dv+g== X-Received: by 2002:a05:6a20:c916:b0:203:bb3b:5f1e with SMTP id adf61e73a8af0-2170c7232ffmr15972933637.1.1747638507547; Mon, 19 May 2025 00:08:27 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-742acb8731esm5295547b3a.168.2025.05.19.00.08.26 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:27 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Viresh Kumar Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 11/15] rust: cpufreq: Add initial abstractions for cpufreq framework Date: Mon, 19 May 2025 12:37:16 +0530 Message-Id: <994733d45f0ab11efb8a0a5fd5197c9ed4cc319f.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Introduce initial Rust abstractions for the cpufreq core. This includes basic representations for cpufreq flags, relation types, and the cpufreq table. Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers/cpufreq.c | 10 + rust/helpers/helpers.c | 1 + rust/kernel/cpufreq.rs | 364 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 6 files changed, 379 insertions(+) create mode 100644 rust/helpers/cpufreq.c create mode 100644 rust/kernel/cpufreq.rs diff --git a/MAINTAINERS b/MAINTAINERS index 931e418f89ed..aa56eacbda71 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -6142,6 +6142,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/ =20 CPU HOTPLUG diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 529f22891e0b..7c1d78f68076 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers/cpufreq.c b/rust/helpers/cpufreq.c new file mode 100644 index 000000000000..7c1343c4d65e --- /dev/null +++ b/rust/helpers/cpufreq.c @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +#ifdef CONFIG_CPU_FREQ +void rust_helper_cpufreq_register_em_with_opp(struct cpufreq_policy *polic= y) +{ + cpufreq_register_em_with_opp(policy); +} +#endif diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index ae595c9cd91b..df1fcfb3adf3 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -12,6 +12,7 @@ #include "build_assert.c" #include "build_bug.c" #include "clk.c" +#include "cpufreq.c" #include "cpumask.c" #include "cred.c" #include "device.c" diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs new file mode 100644 index 000000000000..2aa024615d4d --- /dev/null +++ b/rust/kernel/cpufreq.rs @@ -0,0 +1,364 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU frequency scaling. +//! +//! This module provides rust abstractions for interacting with the cpufre= q subsystem. +//! +//! C header: [`include/linux/cpufreq.h`](srctree/include/linux/cpufreq.h) +//! +//! Reference: + +use crate::{ + clk::Hertz, + error::{code::*, to_result, Result}, + ffi::c_ulong, + prelude::*, + types::Opaque, +}; + +use core::{ops::Deref, pin::Pin}; + +/// Default transition latency value in nanoseconds. +pub const ETERNAL_LATENCY_NS: u32 =3D bindings::CPUFREQ_ETERNAL as u32; + +/// CPU frequency driver flags. +pub mod flags { + /// Driver needs to update internal limits even if frequency remains u= nchanged. + pub const NEED_UPDATE_LIMITS: u16 =3D 1 << 0; + + /// Platform where constants like `loops_per_jiffy` are unaffected by = frequency changes. + pub const CONST_LOOPS: u16 =3D 1 << 1; + + /// Register driver as a thermal cooling device automatically. + pub const IS_COOLING_DEV: u16 =3D 1 << 2; + + /// Supports multiple clock domains with per-policy governors in `cpu/= cpuN/cpufreq/`. + pub const HAVE_GOVERNOR_PER_POLICY: u16 =3D 1 << 3; + + /// Allows post-change notifications outside of the `target()` routine. + pub const ASYNC_NOTIFICATION: u16 =3D 1 << 4; + + /// Ensure CPU starts at a valid frequency from the driver's freq-tabl= e. + pub const NEED_INITIAL_FREQ_CHECK: u16 =3D 1 << 5; + + /// Disallow governors with `dynamic_switching` capability. + pub const NO_AUTO_DYNAMIC_SWITCHING: u16 =3D 1 << 6; +} + +/// Relations from the C code. +const CPUFREQ_RELATION_L: u32 =3D 0; +const CPUFREQ_RELATION_H: u32 =3D 1; +const CPUFREQ_RELATION_C: u32 =3D 2; + +/// Can be used with any of the above values. +const CPUFREQ_RELATION_E: u32 =3D 1 << 2; + +/// CPU frequency selection relations. +/// +/// CPU frequency selection relations, each optionally marked as "efficien= t". +#[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 { + // Construct from a C-compatible `u32` value. + fn new(val: u32) -> Result { + let efficient =3D val & CPUFREQ_RELATION_E !=3D 0; + + Ok(match val & !CPUFREQ_RELATION_E { + CPUFREQ_RELATION_L =3D> Self::Low(efficient), + CPUFREQ_RELATION_H =3D> Self::High(efficient), + CPUFREQ_RELATION_C =3D> Self::Close(efficient), + _ =3D> return Err(EINVAL), + }) + } +} + +impl From for u32 { + // Convert to a C-compatible `u32` value. + fn from(rel: Relation) -> Self { + let (mut val, efficient) =3D match rel { + Relation::Low(e) =3D> (CPUFREQ_RELATION_L, e), + Relation::High(e) =3D> (CPUFREQ_RELATION_H, e), + Relation::Close(e) =3D> (CPUFREQ_RELATION_C, e), + }; + + if efficient { + val |=3D CPUFREQ_RELATION_E; + } + + val + } +} + +/// Policy data. +/// +/// Rust abstraction for the C `struct cpufreq_policy_data`. +/// +/// # Invariants +/// +/// A [`PolicyData`] instance always corresponds to a valid C `struct cpuf= req_policy_data`. +/// +/// The callers must ensure that the `struct cpufreq_policy_data` is valid= for access and remains +/// valid for the lifetime of the returned reference. +#[repr(transparent)] +pub struct PolicyData(Opaque); + +impl PolicyData { + /// Creates a mutable reference to an existing `struct cpufreq_policy_= data` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for writing and remains= valid for the lifetime + /// of the returned reference. + #[inline] + pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpufreq_policy_data= ) -> &'a mut Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for writing a= nd remains valid for the + // lifetime of the returned reference. + unsafe { &mut *ptr.cast() } + } + + /// Returns a raw pointer to the underlying C `cpufreq_policy_data`. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_policy_data { + let this: *const Self =3D self; + this.cast_mut().cast() + } + + /// Wrapper for `cpufreq_generic_frequency_table_verify`. + #[inline] + pub fn generic_verify(&self) -> Result<()> { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid. + to_result(unsafe { bindings::cpufreq_generic_frequency_table_verif= y(self.as_raw()) }) + } +} + +/// The frequency table index. +/// +/// Represents index with a frequency table. +/// +/// # Invariants +/// +/// The index must correspond to a valid entry in the [`Table`] it is used= for. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub struct TableIndex(usize); + +impl TableIndex { + /// Creates an instance of [`TableIndex`]. + /// + /// # Safety + /// + /// The caller must ensure that `index` correspond to a valid entry in= the [`Table`] it is used + /// for. + pub unsafe fn new(index: usize) -> Self { + // INVARIANT: The caller ensures that `index` correspond to a vali= d entry in the [`Table`]. + Self(index) + } +} + +impl From for usize { + #[inline] + fn from(index: TableIndex) -> Self { + index.0 + } +} + +/// CPU frequency table. +/// +/// Rust abstraction for the C `struct cpufreq_frequency_table`. +/// +/// # Invariants +/// +/// A [`Table`] instance always corresponds to a valid C `struct cpufreq_f= requency_table`. +/// +/// The callers must ensure that the `struct cpufreq_frequency_table` is v= alid for access and +/// remains valid for the lifetime of the returned reference. +/// +/// ## Examples +/// +/// The following example demonstrates how to read a frequency value from = [`Table`]. +/// +/// ``` +/// use kernel::cpufreq::{Policy, TableIndex}; +/// +/// fn show_freq(policy: &Policy) { +/// let table =3D policy.freq_table().unwrap(); +/// +/// // SAFETY: Index is a valid entry in the table. +/// let index =3D unsafe { TableIndex::new(0) }; +/// +/// pr_info!("The frequency at index 0 is: {:?}\n", table.freq(index).= unwrap()); +/// pr_info!("The flags at index 0 is: {}\n", table.flags(index)); +/// pr_info!("The data at index 0 is: {}\n", table.data(index)); +/// } +/// ``` +#[repr(transparent)] +pub struct Table(Opaque); + +impl Table { + /// Creates a reference to an existing C `struct cpufreq_frequency_tab= le` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for reading and remains= valid for the lifetime + /// of the returned reference. + #[inline] + pub unsafe fn from_raw<'a>(ptr: *const bindings::cpufreq_frequency_tab= le) -> &'a Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for reading a= nd remains valid for the + // lifetime of the returned reference. + unsafe { &*ptr.cast() } + } + + /// Returns the raw mutable pointer to the C `struct cpufreq_frequency= _table`. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_frequency_table { + let this: *const Self =3D self; + this.cast_mut().cast() + } + + /// Returns frequency at `index` in the [`Table`]. + #[inline] + pub fn freq(&self, index: TableIndex) -> Result { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid and `index` is + // guaranteed to be valid by its safety requirements. + Ok(Hertz::from_khz(unsafe { + (*self.as_raw().add(index.into())).frequency.try_into()? + })) + } + + /// Returns flags at `index` in the [`Table`]. + #[inline] + pub fn flags(&self, index: TableIndex) -> u32 { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid and `index` is + // guaranteed to be valid by its safety requirements. + unsafe { (*self.as_raw().add(index.into())).flags } + } + + /// Returns data at `index` in the [`Table`]. + #[inline] + pub fn data(&self, index: TableIndex) -> u32 { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid and `index` is + // guaranteed to be valid by its safety requirements. + unsafe { (*self.as_raw().add(index.into())).driver_data } + } +} + +/// CPU frequency table owned and pinned in memory, created from a [`Table= Builder`]. +pub struct TableBox { + entries: Pin>, +} + +impl TableBox { + /// Constructs a new [`TableBox`] from a [`KVec`] of entries. + /// + /// # Errors + /// + /// Returns `EINVAL` if the entries list is empty. + #[inline] + fn new(entries: KVec) -> Result { + if entries.is_empty() { + return Err(EINVAL); + } + + Ok(Self { + // Pin the entries to memory, since we are passing its pointer= to the C code. + entries: Pin::new(entries), + }) + } + + /// Returns a raw pointer to the underlying C `cpufreq_frequency_table= `. + #[inline] + fn as_raw(&self) -> *const bindings::cpufreq_frequency_table { + // The pointer is valid until the table gets dropped. + self.entries.as_ptr() + } +} + +impl Deref for TableBox { + type Target =3D Table; + + fn deref(&self) -> &Self::Target { + // SAFETY: The caller owns TableBox, it is safe to deref. + unsafe { Self::Target::from_raw(self.as_raw()) } + } +} + +/// CPU frequency table builder. +/// +/// This is used by the CPU frequency drivers to build a frequency table d= ynamically. +/// +/// ## Examples +/// +/// The following example demonstrates how to create a CPU frequency table. +/// +/// ``` +/// use kernel::cpufreq::{TableBuilder, TableIndex}; +/// use kernel::clk::Hertz; +/// +/// let mut builder =3D TableBuilder::new(); +/// +/// // Adds few entries to the table. +/// builder.add(Hertz::from_mhz(700), 0, 1).unwrap(); +/// builder.add(Hertz::from_mhz(800), 2, 3).unwrap(); +/// builder.add(Hertz::from_mhz(900), 4, 5).unwrap(); +/// builder.add(Hertz::from_ghz(1), 6, 7).unwrap(); +/// +/// let table =3D builder.to_table().unwrap(); +/// +/// // SAFETY: Index values correspond to valid entries in the table. +/// let (index0, index2) =3D unsafe { (TableIndex::new(0), TableIndex::new= (2)) }; +/// +/// assert_eq!(table.freq(index0), Ok(Hertz::from_mhz(700))); +/// assert_eq!(table.flags(index0), 0); +/// assert_eq!(table.data(index0), 1); +/// +/// assert_eq!(table.freq(index2), Ok(Hertz::from_mhz(900))); +/// assert_eq!(table.flags(index2), 4); +/// assert_eq!(table.data(index2), 5); +/// ``` +#[derive(Default)] +#[repr(transparent)] +pub struct TableBuilder { + entries: KVec, +} + +impl TableBuilder { + /// Creates a new instance of [`TableBuilder`]. + #[inline] + pub fn new() -> Self { + Self { + entries: KVec::new(), + } + } + + /// Adds a new entry to the table. + pub fn add(&mut self, freq: Hertz, flags: u32, driver_data: u32) -> Re= sult<()> { + // Adds the new entry at the end of the vector. + Ok(self.entries.push( + bindings::cpufreq_frequency_table { + flags, + driver_data, + frequency: freq.as_khz() as u32, + }, + GFP_KERNEL, + )?) + } + + /// Consumes the [`TableBuilder`] and returns [`TableBox`]. + pub fn to_table(mut self) -> Result { + // Add last entry to the table. + self.add(Hertz(c_ulong::MAX), 0, 0)?; + + TableBox::new(self.entries) + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index ea589254b4ac..133ebee4f9d3 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -44,6 +44,8 @@ pub mod build_assert; pub mod clk; pub mod cpu; +#[cfg(CONFIG_CPU_FREQ)] +pub mod cpufreq; pub mod cpumask; pub mod cred; pub mod device; --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pl1-f172.google.com (mail-pl1-f172.google.com [209.85.214.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3155C26AAB5 for ; Mon, 19 May 2025 07:08:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638514; cv=none; b=aiq39crnNa1xQaICQE14gMFzwS9/vuHgr+mI9vQIX0w1Rma5bpYvI33oQXlfgxyNRJgEwW0TM0voHhrgr9plZLHuvAeWAAebl17j7dqizYFrv3CQkV7Rz31reNefwEObJSK1HjSlHhlD2o5+hYjpaOYps+8Ij6en3hXPQB+IL64= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638514; c=relaxed/simple; bh=w75xk8hcGxaoso0uJH+G6H2tRb4FrllY4PtzoOGYwhU=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=W9zb447uZNSjdFR+hlH5rfV/jaDTYxBoSFQXkcqiUpbgMtWH6OdonVsiuL1KNVs6ZtquKmJrlZwuKHuLHCPTFaFybk9MSqc9eWGezP8JB7NWpyKessE5IdX1uzSNE0v7OrCyiCHwdhtWCFFoHrsdwhqO0UtcmLgBsigubfr7xkM= 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=uzdhqiMK; arc=none smtp.client-ip=209.85.214.172 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="uzdhqiMK" Received: by mail-pl1-f172.google.com with SMTP id d9443c01a7336-2320d06b728so9777175ad.1 for ; Mon, 19 May 2025 00:08:32 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638511; x=1748243311; 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=DyCYDi1jmiTRdeD7r0ayi/v9y79Pi1U/bl1JrfBBA8w=; b=uzdhqiMKVtUw6fFV3+qQsxZoC5sc7YKpeR5mMJvsie0WTZB9J5qSXEFBZMFBRuxkMw tW0r/IS4nuTBMrKCUs9icWpeusiJTt3x/jeNYhIzejfu26tIGbd7MGWnY2IlqwVRdKWl t4r7MWOhBwbFxRvVCaFhH7FOf2nncvPiYRZND7MNi5KzStk4AuWEy0D88dWtvWyr71kI WGk4o9pIwAQkhWhUASSvB+JljluxuNYoMupLDWR2khybTkMK/b8TRH+ocpSyub2wG1Ms 9U8OULZkqj3drhrN6mVMtRT3yX5cCeLTGLCMncOVpaEESWudbN89RLhi2qFTKbgroYcT zdzA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638511; x=1748243311; 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=DyCYDi1jmiTRdeD7r0ayi/v9y79Pi1U/bl1JrfBBA8w=; b=XqQBob4DRV11Ltb/H3LvYZcJX/Qhb6mfuygPfZWRIdF0oJnLFJC8gMj4NWX5tVWXQy PPr9hZ+1TTM65NrfjrTUdtIY7gByA1u2eXIGb46+13M1oNEM/bs7jh+d4N4AJXFE+xU8 WAUuQj22Dit2XfdOI6fth5kTKaXDSKm0u9KJQBIuo+t+tMnkeA3qOMtt2vocwaqYE0T5 nFOjfjjbiLUwUDvHwp5govLFnXzjAe00KkYELtL5fdzUK4Dc9kRFV/qrmXBYDtDM6Bvw ls5IUZGGQnEOhgaAFIrnXbf8HflKs2J14pfv1IXh9KsixRtowjwClAAL29e6XoAV5TXJ CIsg== X-Forwarded-Encrypted: i=1; AJvYcCW4C8ORqETuskpqP9LFuteO88nVrB/KfUyGmVNYrPiS8d2wAbu69oq0NTrHH6e3GzE7lmHEAgNevMQM5C4=@vger.kernel.org X-Gm-Message-State: AOJu0Ywi7lcxNMsN60qrqw7lVbQkTJUSjqSl9C6VT8DE8mmLqANvGAMw Mfu/UStpmhEWSdZe/vDW6rtUu9yRRn7JzBACZBuw502FT/jNq1vhPUKld7xSUbhoM6M= X-Gm-Gg: ASbGnctAW15Cdq9FnOWAXMq33u/6KJwJQ2GutgndT2jDnQXQJK8OQmFALFwqRVC2yqW yn7up7CGPlTr/goSHx9GxezmGwRImdPPYbZWnw7LMOHxOjLfld+MP2oQStfOyleITMAhEqoeN+8 BoWYry3+pqbbzX7xUWYNu17vzGZVRZDr+XoHJRV4tS1LAyMkFufK3qkrzmTvI82svuDPsJNiDuj PeIrz5EkofeJfuII9Je5xvQdiTeg4HkkujaNPlbqK0Q7l60tj02PKNdaKOZJLfCon91FuC/r5qu ku3tWx4w3rGtbWsAS7fQSgusAX267j/yvcWPjTjzYxP7IlNdKAJh X-Google-Smtp-Source: AGHT+IFp+mTkIdQA+QBEpF9I1WDmxW6BCz1216dFbfVhAVDgVNSZI0SSTQtOTG0aLfaPnStrV3lcug== X-Received: by 2002:a17:903:2285:b0:223:26da:4b8e with SMTP id d9443c01a7336-231d438a1a3mr176961085ad.4.1747638511390; Mon, 19 May 2025 00:08:31 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-231d4e98251sm52805555ad.138.2025.05.19.00.08.30 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:30 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 12/15] rust: cpufreq: Extend abstractions for policy and driver ops Date: Mon, 19 May 2025 12:37:17 +0530 Message-Id: <2f11306b8a7f05b441256fbd9784ccc2d59b3356.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Extend the cpufreq abstractions to include support for policy handling and driver operations. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 463 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 461 insertions(+), 2 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 2aa024615d4d..4e6d85bd06f4 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -10,13 +10,25 @@ =20 use crate::{ clk::Hertz, - error::{code::*, to_result, Result}, + cpumask, + device::Device, + error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR= }, ffi::c_ulong, prelude::*, + types::ForeignOwnable, types::Opaque, }; =20 -use core::{ops::Deref, pin::Pin}; +#[cfg(CONFIG_COMMON_CLK)] +use crate::clk::Clk; + +use core::{ + ops::{Deref, DerefMut}, + pin::Pin, + ptr, +}; + +use macros::vtable; =20 /// Default transition latency value in nanoseconds. pub const ETERNAL_LATENCY_NS: u32 =3D bindings::CPUFREQ_ETERNAL as u32; @@ -362,3 +374,450 @@ pub fn to_table(mut self) -> Result { TableBox::new(self.entries) } } + +/// CPU frequency policy. +/// +/// Rust abstraction for the C `struct cpufreq_policy`. +/// +/// # Invariants +/// +/// A [`Policy`] instance always corresponds to a valid C `struct cpufreq_= policy`. +/// +/// The callers must ensure that the `struct cpufreq_policy` is valid for = access and remains valid +/// for the lifetime of the returned reference. +/// +/// ## Examples +/// +/// The following example demonstrates how to create a CPU frequency table. +/// +/// ``` +/// use kernel::cpufreq::{ETERNAL_LATENCY_NS, Policy}; +/// +/// fn update_policy(policy: &mut Policy) { +/// policy +/// .set_dvfs_possible_from_any_cpu(true) +/// .set_fast_switch_possible(true) +/// .set_transition_latency_ns(ETERNAL_LATENCY_NS); +/// +/// pr_info!("The policy details are: {:?}\n", (policy.cpu(), policy.c= ur())); +/// } +/// ``` +#[repr(transparent)] +pub struct Policy(Opaque); + +impl Policy { + /// Creates a reference to an existing `struct cpufreq_policy` pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for reading and remains= valid for the lifetime + /// of the returned reference. + #[inline] + pub unsafe fn from_raw<'a>(ptr: *const bindings::cpufreq_policy) -> &'= a Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for reading a= nd remains valid for the + // lifetime of the returned reference. + unsafe { &*ptr.cast() } + } + + /// Creates a mutable reference to an existing `struct cpufreq_policy`= pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid for writing and remains= valid for the lifetime + /// of the returned reference. + #[inline] + pub unsafe fn from_raw_mut<'a>(ptr: *mut bindings::cpufreq_policy) -> = &'a mut Self { + // SAFETY: Guaranteed by the safety requirements of the function. + // + // INVARIANT: The caller ensures that `ptr` is valid for writing a= nd remains valid for the + // lifetime of the returned reference. + unsafe { &mut *ptr.cast() } + } + + /// Returns a raw mutable pointer to the C `struct cpufreq_policy`. + #[inline] + fn as_raw(&self) -> *mut bindings::cpufreq_policy { + let this: *const Self =3D self; + this.cast_mut().cast() + } + + #[inline] + fn as_ref(&self) -> &bindings::cpufreq_policy { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid. + unsafe { &*self.as_raw() } + } + + #[inline] + fn as_mut_ref(&mut self) -> &mut bindings::cpufreq_policy { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid. + unsafe { &mut *self.as_raw() } + } + + /// Returns the primary CPU for the [`Policy`]. + #[inline] + pub fn cpu(&self) -> u32 { + self.as_ref().cpu + } + + /// Returns the minimum frequency for the [`Policy`]. + #[inline] + pub fn min(&self) -> Hertz { + Hertz::from_khz(self.as_ref().min as usize) + } + + /// Set the minimum frequency for the [`Policy`]. + #[inline] + pub fn set_min(&mut self, min: Hertz) -> &mut Self { + self.as_mut_ref().min =3D min.as_khz() as u32; + self + } + + /// Returns the maximum frequency for the [`Policy`]. + #[inline] + pub fn max(&self) -> Hertz { + Hertz::from_khz(self.as_ref().max as usize) + } + + /// Set the maximum frequency for the [`Policy`]. + #[inline] + pub fn set_max(&mut self, max: Hertz) -> &mut Self { + self.as_mut_ref().max =3D max.as_khz() as u32; + self + } + + /// Returns the current frequency for the [`Policy`]. + #[inline] + pub fn cur(&self) -> Hertz { + Hertz::from_khz(self.as_ref().cur as usize) + } + + /// Returns the suspend frequency for the [`Policy`]. + #[inline] + pub fn suspend_freq(&self) -> Hertz { + Hertz::from_khz(self.as_ref().suspend_freq as usize) + } + + /// Sets the suspend frequency for the [`Policy`]. + #[inline] + pub fn set_suspend_freq(&mut self, freq: Hertz) -> &mut Self { + self.as_mut_ref().suspend_freq =3D freq.as_khz() as u32; + self + } + + /// Provides a wrapper to the generic suspend routine. + #[inline] + pub fn generic_suspend(&mut self) -> Result<()> { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid. + to_result(unsafe { bindings::cpufreq_generic_suspend(self.as_mut_r= ef()) }) + } + + /// Provides a wrapper to the generic get routine. + #[inline] + pub fn generic_get(&self) -> Result { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid. + Ok(unsafe { bindings::cpufreq_generic_get(self.cpu()) }) + } + + /// Provides a wrapper to the register with energy model using the OPP= core. + #[cfg(CONFIG_PM_OPP)] + #[inline] + pub fn register_em_opp(&mut self) { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid. + unsafe { bindings::cpufreq_register_em_with_opp(self.as_mut_ref())= }; + } + + /// Gets [`cpumask::Cpumask`] for a cpufreq [`Policy`]. + #[inline] + pub fn cpus(&mut self) -> &mut cpumask::Cpumask { + // SAFETY: The pointer to `cpus` is valid for writing and remains = valid for the lifetime of + // the returned reference. + unsafe { cpumask::CpumaskVar::as_mut_ref(&mut self.as_mut_ref().cp= us) } + } + + /// Sets clock for the [`Policy`]. + /// + /// # Safety + /// + /// The caller must guarantee that the returned [`Clk`] is not dropped= while it is getting used + /// by the C code. + #[cfg(CONFIG_COMMON_CLK)] + pub unsafe fn set_clk(&mut self, dev: &Device, name: Option<&CStr>) ->= Result { + let clk =3D Clk::get(dev, name)?; + self.as_mut_ref().clk =3D clk.as_raw(); + Ok(clk) + } + + /// Allows / disallows frequency switching code to run on any CPU. + #[inline] + pub fn set_dvfs_possible_from_any_cpu(&mut self, val: bool) -> &mut Se= lf { + self.as_mut_ref().dvfs_possible_from_any_cpu =3D val; + self + } + + /// Returns if fast switching of frequencies is possible or not. + #[inline] + pub fn fast_switch_possible(&self) -> bool { + self.as_ref().fast_switch_possible + } + + /// Enables / disables fast frequency switching. + #[inline] + pub fn set_fast_switch_possible(&mut self, val: bool) -> &mut Self { + self.as_mut_ref().fast_switch_possible =3D val; + self + } + + /// Sets transition latency (in nanoseconds) for the [`Policy`]. + #[inline] + pub fn set_transition_latency_ns(&mut self, latency_ns: u32) -> &mut S= elf { + self.as_mut_ref().cpuinfo.transition_latency =3D latency_ns; + self + } + + /// Sets cpuinfo `min_freq`. + #[inline] + pub fn set_cpuinfo_min_freq(&mut self, min_freq: Hertz) -> &mut Self { + self.as_mut_ref().cpuinfo.min_freq =3D min_freq.as_khz() as u32; + self + } + + /// Sets cpuinfo `max_freq`. + #[inline] + pub fn set_cpuinfo_max_freq(&mut self, max_freq: Hertz) -> &mut Self { + self.as_mut_ref().cpuinfo.max_freq =3D max_freq.as_khz() as u32; + self + } + + /// Set `transition_delay_us`, i.e. the minimum time between successiv= e frequency change + /// requests. + #[inline] + pub fn set_transition_delay_us(&mut self, transition_delay_us: u32) ->= &mut Self { + self.as_mut_ref().transition_delay_us =3D transition_delay_us; + self + } + + /// Returns reference to the CPU frequency [`Table`] for the [`Policy`= ]. + pub fn freq_table(&self) -> Result<&Table> { + if self.as_ref().freq_table.is_null() { + return Err(EINVAL); + } + + // SAFETY: The `freq_table` is guaranteed to be valid for reading = and remains valid for the + // lifetime of the returned reference. + Ok(unsafe { Table::from_raw(self.as_ref().freq_table) }) + } + + /// Sets the CPU frequency [`Table`] for the [`Policy`]. + /// + /// # Safety + /// + /// The caller must guarantee that the [`Table`] is not dropped while = it is getting used by the + /// C code. + #[inline] + pub unsafe fn set_freq_table(&mut self, table: &Table) -> &mut Self { + self.as_mut_ref().freq_table =3D table.as_raw(); + self + } + + /// Returns the [`Policy`]'s private data. + pub fn data(&mut self) -> Option<::Borrowed<'_>>= { + if self.as_ref().driver_data.is_null() { + None + } else { + // SAFETY: The data is earlier set from [`set_data`]. + Some(unsafe { T::borrow(self.as_ref().driver_data) }) + } + } + + /// Sets the private data of the [`Policy`] using a foreign-ownable wr= apper. + /// + /// # Errors + /// + /// Returns `EBUSY` if private data is already set. + fn set_data(&mut self, data: T) -> Result<()> { + if self.as_ref().driver_data.is_null() { + // Transfer the ownership of the data to the foreign interface. + self.as_mut_ref().driver_data =3D ::into_= foreign(data) as _; + Ok(()) + } else { + Err(EBUSY) + } + } + + /// Clears and returns ownership of the private data. + fn clear_data(&mut self) -> Option { + if self.as_ref().driver_data.is_null() { + None + } else { + let data =3D Some( + // SAFETY: The data is earlier set by us from [`set_data`]= . It is safe to take + // back the ownership of the data from the foreign interfa= ce. + unsafe { ::from_foreign(self.as_ref()= .driver_data) }, + ); + self.as_mut_ref().driver_data =3D ptr::null_mut(); + data + } + } +} + +/// CPU frequency policy created from a CPU number. +/// +/// This struct represents the CPU frequency policy obtained for a specifi= c CPU, providing safe +/// access to the underlying `cpufreq_policy` and ensuring proper cleanup = when the `PolicyCpu` is +/// dropped. +struct PolicyCpu<'a>(&'a mut Policy); + +impl<'a> PolicyCpu<'a> { + fn from_cpu(cpu: u32) -> Result { + // SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU. + let ptr =3D from_err_ptr(unsafe { bindings::cpufreq_cpu_get(cpu) }= )?; + + Ok(Self( + // SAFETY: The `ptr` is guaranteed to be valid and remains val= id for the lifetime of + // the returned reference. + unsafe { Policy::from_raw_mut(ptr) }, + )) + } +} + +impl<'a> Deref for PolicyCpu<'a> { + type Target =3D Policy; + + fn deref(&self) -> &Self::Target { + self.0 + } +} + +impl<'a> DerefMut for PolicyCpu<'a> { + fn deref_mut(&mut self) -> &mut Policy { + self.0 + } +} + +impl<'a> Drop for PolicyCpu<'a> { + fn drop(&mut self) { + // SAFETY: The underlying pointer is guaranteed to be valid for th= e lifetime of `self`. + unsafe { bindings::cpufreq_cpu_put(self.0.as_raw()) }; + } +} + +/// CPU frequency driver. +/// +/// Implement this trait to provide a CPU frequency driver and its callbac= ks. +/// +/// Reference: +#[vtable] +pub trait Driver { + /// Driver's name. + const NAME: &'static CStr; + + /// Driver's flags. + const FLAGS: u16; + + /// Boost support. + const BOOST_ENABLED: bool; + + /// Policy specific data. + /// + /// Require that `PData` implements `ForeignOwnable`. We guarantee to = never move the underlying + /// wrapped data structure. + type PData: ForeignOwnable; + + /// Driver's `init` callback. + fn init(policy: &mut Policy) -> Result; + + /// Driver's `exit` callback. + fn exit(_policy: &mut Policy, _data: Option) -> Result<()= > { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `online` callback. + fn online(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `offline` callback. + fn offline(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `suspend` callback. + fn suspend(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `resume` callback. + fn resume(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `ready` callback. + fn ready(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `verify` callback. + fn verify(data: &mut PolicyData) -> Result<()>; + + /// Driver's `setpolicy` callback. + fn setpolicy(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `target` callback. + fn target(_policy: &mut Policy, _target_freq: u32, _relation: Relation= ) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `target_index` callback. + fn target_index(_policy: &mut Policy, _index: TableIndex) -> Result<()= > { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `fast_switch` callback. + fn fast_switch(_policy: &mut Policy, _target_freq: u32) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `adjust_perf` callback. + fn adjust_perf(_policy: &mut Policy, _min_perf: usize, _target_perf: u= size, _capacity: usize) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `get_intermediate` callback. + fn get_intermediate(_policy: &mut Policy, _index: TableIndex) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `target_intermediate` callback. + fn target_intermediate(_policy: &mut Policy, _index: TableIndex) -> Re= sult<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `get` callback. + fn get(_policy: &mut Policy) -> Result { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `update_limits` callback. + fn update_limits(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `bios_limit` callback. + fn bios_limit(_policy: &mut Policy, _limit: &mut u32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `set_boost` callback. + fn set_boost(_policy: &mut Policy, _state: i32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `register_em` callback. + fn register_em(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } +} --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pf1-f175.google.com (mail-pf1-f175.google.com [209.85.210.175]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 53A2F26B0AE for ; Mon, 19 May 2025 07:08:36 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.175 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638518; cv=none; b=bd0Do+6ikOwWSt6qfZeLeDtQU13wpHcPTwyb/N/keAQFFH4bZZfqK1U4QpmTx7kAcwUx0SeeksOhXum85hRXfmZ34AgRfF2DyWjbcIh88ayCqJDmetHYbMPwmVXdYJ981LyNTj6+KD+Fh4QF9Q92kU4xaitiSDJN/o9sdGz+YYc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638518; c=relaxed/simple; bh=FfCU9Q4oo8gcC22tgFyIBboGdtEMPSETsVxLls50r58=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=gZ3bKDgJodyrB6dQEaK01dX8TDJseOs2I8LZ8Y8zxq8X9kj2Phh8uK4dp3dnoFVn/7sS7UGBJUAFouEJCJTF4O6WU8+lYy0wu5cEMl6pb2Giw0KkuXTOoxNSY2ZKUic0JTA11OwNbA0zSvXHRgzNgxG0K0BBeiLPEYClD9D0HlE= 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=I2jftAng; arc=none smtp.client-ip=209.85.210.175 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="I2jftAng" Received: by mail-pf1-f175.google.com with SMTP id d2e1a72fcca58-7376e311086so4925026b3a.3 for ; Mon, 19 May 2025 00:08:36 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638516; x=1748243316; 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=HV3P8eRO4ctaNHc7b4PazEg48dgX9jLyy4nzXlr/F9I=; b=I2jftAngPk2nYvle8VVxXSGlDWHyWgez1ASdPNxGxw8VZzx7x30cgTbiWx83mdhi1l FS2Q0cspxVQZs10auxZNkRX0lHZRKMOfNRz5h1/NXmoPr4/KKbmJu3Tk1TzwxweeXET1 NSzKyQ6HoEyeW5m2RW1cqd7KjG5YZGD+slsd/e4MoWXzXL+/hteBNQxmbNvUcgQcT8Vv xo+oJ0YFvZHLQlAj4dogcySz0BOKHd85argL5lVGmsRD8bBhujcxFxo+odo8Tq6SFp40 /ueXL1mYx3J4luJkPCe3TFhtFQ1EpgjXqYhdqNYhU6cuRX4w9gAQp++8xc4l19K/uwM+ /ETg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638516; x=1748243316; 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=HV3P8eRO4ctaNHc7b4PazEg48dgX9jLyy4nzXlr/F9I=; b=a2jPZx0w257cu50fDmx5DFMWf69IdL9SJdJ544gCXga97wWK9QU9JBr9XLZL3Q9/de O3dnVgjyx/oaHtGdsfU5Jk5V4lpT48oSiBhy7wj49wz5j0EebjBkLhz2OMU5fcA/1pzO wpQs1m0k1z4csHKcueNU1KUJ0QyWuOxati8q2p8LHf1/r/AHXTOLuqw+ZFQShH+zKEWe 9WMLA992L5FvNFqfowoVk7RkdqJN/Wan3X0hTlSvOsy+sXP3o81dRVOmOSJsMEMNtS2H FRnqGTbao5GvpCokCOjUAWz0CP7kHdTimtjOoulgWW5rlizSomizAxBnHLt/2imcHIMG lDVQ== X-Forwarded-Encrypted: i=1; AJvYcCV9TZY+QxJGLiVfNC+XsSlorVDYEnWJwdHyCgQRUscwo7UsLt2qeR4FI22MMNXuaH4CY3y03HulGPVcrY0=@vger.kernel.org X-Gm-Message-State: AOJu0Yy9eSG6XafnPsi4bNz+kBO1xOl9aH7zwXhBFUqpU+h1LHnv9/5D c2/LNY/T3fRGNA09thze6JjdB8t6eYzSeErkU6VGzDXzBK/OYu+bLyQ8Tm5DkiwKtPc= X-Gm-Gg: ASbGnct/Ktn+60sZlsLofo+3YUOvcC+W2DomzjW4IQpdxEYYdDvVS5Z2GYPAnDOCYEF kjsMu4BZ9L43pae94hUtzW4dxweUSAYpQMf4IE0V80EQxLGLppegNqR1Wk3b0fg7D4ojnCxzIY8 CFPTCUCCyZc3HFISZI6B397WHZDc5QKMgWUBjqrvvMCnJ3oz/2r9puAmhB5OfK5+ltPnmFpLW7h t+ZfTYnd019xb55U0vBeXb6b6YD0dUMVPXHg95I2WB7XLur56lZzB39iZ3TVsKxAIxLWMvWUk79 nT1P58EwnHKLlbHXsOdv1L5fnnjsZ2p5S6FJWq6bpN/Hw6wyVxCo X-Google-Smtp-Source: AGHT+IEdyzhdQsH+25qu2A2TK3Xj3gokG9tCMu4IZ1sZpYNX8MMi0+GmXfbliVS9lotPKUf5f0cQcQ== X-Received: by 2002:a05:6a00:4b08:b0:730:95a6:3761 with SMTP id d2e1a72fcca58-742a97a720bmr17617921b3a.3.1747638515442; Mon, 19 May 2025 00:08:35 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-742a9871517sm5687725b3a.135.2025.05.19.00.08.34 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:34 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 13/15] rust: cpufreq: Extend abstractions for driver registration Date: Mon, 19 May 2025 12:37:18 +0530 Message-Id: <68906d67109c3b323b54469fb1ee44e10c1c5b1e.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Extend the cpufreq abstractions to support driver registration from Rust. Reviewed-by: Danilo Krummrich Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 493 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 490 insertions(+), 3 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 4e6d85bd06f4..826710c4f4b0 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -11,9 +11,10 @@ use crate::{ clk::Hertz, cpumask, - device::Device, - error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR= }, - ffi::c_ulong, + device::{Bound, Device}, + devres::Devres, + error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_= DEFAULT_ERROR}, + ffi::{c_char, c_ulong}, prelude::*, types::ForeignOwnable, types::Opaque, @@ -23,6 +24,9 @@ use crate::clk::Clk; =20 use core::{ + cell::UnsafeCell, + marker::PhantomData, + mem::MaybeUninit, ops::{Deref, DerefMut}, pin::Pin, ptr, @@ -30,6 +34,9 @@ =20 use macros::vtable; =20 +/// Maximum length of CPU frequency driver's name. +const CPUFREQ_NAME_LEN: usize =3D bindings::CPUFREQ_NAME_LEN as usize; + /// Default transition latency value in nanoseconds. pub const ETERNAL_LATENCY_NS: u32 =3D bindings::CPUFREQ_ETERNAL as u32; =20 @@ -821,3 +828,483 @@ fn register_em(_policy: &mut Policy) { build_error!(VTABLE_DEFAULT_ERROR) } } + +/// CPU frequency driver Registration. +/// +/// ## Examples +/// +/// The following example demonstrates how to register a cpufreq driver. +/// +/// ``` +/// use kernel::{ +/// cpu, cpufreq, +/// c_str, +/// device::{Bound, Device}, +/// macros::vtable, +/// sync::Arc, +/// }; +/// struct FooDevice; +/// +/// #[derive(Default)] +/// struct FooDriver; +/// +/// #[vtable] +/// impl cpufreq::Driver for FooDriver { +/// const NAME: &'static CStr =3D c_str!("cpufreq-foo"); +/// const FLAGS: u16 =3D cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpu= freq::flags::IS_COOLING_DEV; +/// const BOOST_ENABLED: bool =3D true; +/// +/// type PData =3D Arc; +/// +/// fn init(policy: &mut cpufreq::Policy) -> Result { +/// // Initialize here +/// Ok(Arc::new(FooDevice, GFP_KERNEL)?) +/// } +/// +/// fn exit(_policy: &mut cpufreq::Policy, _data: Option)= -> Result<()> { +/// Ok(()) +/// } +/// +/// fn suspend(policy: &mut cpufreq::Policy) -> Result<()> { +/// policy.generic_suspend() +/// } +/// +/// fn verify(data: &mut cpufreq::PolicyData) -> Result<()> { +/// data.generic_verify() +/// } +/// +/// fn target_index(policy: &mut cpufreq::Policy, index: cpufreq::Tabl= eIndex) -> Result<()> { +/// // Update CPU frequency +/// Ok(()) +/// } +/// +/// fn get(policy: &mut cpufreq::Policy) -> Result { +/// policy.generic_get() +/// } +/// } +/// +/// fn foo_probe(dev: &Device) { +/// cpufreq::Registration::::new_foreign_owned(dev).unwrap(= ); +/// } +/// ``` +#[repr(transparent)] +pub struct Registration(KBox>, PhantomData); + +/// SAFETY: `Registration` doesn't offer any methods or access to fields w= hen shared between threads +/// or CPUs, so it is safe to share it. +unsafe impl Sync for Registration {} + +#[allow(clippy::non_send_fields_in_send_ty)] +/// SAFETY: Registration with and unregistration from the cpufreq subsyste= m can happen from any +/// thread. +unsafe impl Send for Registration {} + +impl Registration { + const VTABLE: bindings::cpufreq_driver =3D bindings::cpufreq_driver { + name: Self::copy_name(T::NAME), + boost_enabled: T::BOOST_ENABLED, + flags: T::FLAGS, + + // Initialize mandatory callbacks. + init: Some(Self::init_callback), + verify: Some(Self::verify_callback), + + // Initialize optional callbacks based on the traits of `T`. + setpolicy: if T::HAS_SETPOLICY { + Some(Self::setpolicy_callback) + } else { + None + }, + target: if T::HAS_TARGET { + Some(Self::target_callback) + } else { + None + }, + target_index: if T::HAS_TARGET_INDEX { + Some(Self::target_index_callback) + } else { + None + }, + fast_switch: if T::HAS_FAST_SWITCH { + Some(Self::fast_switch_callback) + } else { + None + }, + adjust_perf: if T::HAS_ADJUST_PERF { + Some(Self::adjust_perf_callback) + } else { + None + }, + get_intermediate: if T::HAS_GET_INTERMEDIATE { + Some(Self::get_intermediate_callback) + } else { + None + }, + target_intermediate: if T::HAS_TARGET_INTERMEDIATE { + Some(Self::target_intermediate_callback) + } else { + None + }, + get: if T::HAS_GET { + Some(Self::get_callback) + } else { + None + }, + update_limits: if T::HAS_UPDATE_LIMITS { + Some(Self::update_limits_callback) + } else { + None + }, + bios_limit: if T::HAS_BIOS_LIMIT { + Some(Self::bios_limit_callback) + } else { + None + }, + online: if T::HAS_ONLINE { + Some(Self::online_callback) + } else { + None + }, + offline: if T::HAS_OFFLINE { + Some(Self::offline_callback) + } else { + None + }, + exit: if T::HAS_EXIT { + Some(Self::exit_callback) + } else { + None + }, + suspend: if T::HAS_SUSPEND { + Some(Self::suspend_callback) + } else { + None + }, + resume: if T::HAS_RESUME { + Some(Self::resume_callback) + } else { + None + }, + ready: if T::HAS_READY { + Some(Self::ready_callback) + } else { + None + }, + set_boost: if T::HAS_SET_BOOST { + Some(Self::set_boost_callback) + } else { + None + }, + register_em: if T::HAS_REGISTER_EM { + Some(Self::register_em_callback) + } else { + None + }, + // SAFETY: All zeros is a valid value for `bindings::cpufreq_drive= r`. + ..unsafe { MaybeUninit::zeroed().assume_init() } + }; + + const fn copy_name(name: &'static CStr) -> [c_char; CPUFREQ_NAME_LEN] { + let src =3D name.as_bytes_with_nul(); + let mut dst =3D [0; CPUFREQ_NAME_LEN]; + + build_assert!(src.len() <=3D CPUFREQ_NAME_LEN); + + let mut i =3D 0; + while i < src.len() { + dst[i] =3D src[i]; + i +=3D 1; + } + + dst + } + + /// Registers a CPU frequency driver with the cpufreq core. + pub fn new() -> Result { + // We can't use `&Self::VTABLE` directly because the cpufreq core = modifies some fields in + // the C `struct cpufreq_driver`, which requires a mutable referen= ce. + let mut drv =3D KBox::new(UnsafeCell::new(Self::VTABLE), GFP_KERNE= L)?; + + // SAFETY: `drv` is guaranteed to be valid for the lifetime of `Re= gistration`. + to_result(unsafe { bindings::cpufreq_register_driver(drv.get_mut()= ) })?; + + Ok(Self(drv, PhantomData)) + } + + /// Same as [`Registration::new`], but does not return a [`Registratio= n`] instance. + /// + /// Instead the [`Registration`] is owned by [`Devres`] and will be re= voked / dropped, once the + /// device is detached. + pub fn new_foreign_owned(dev: &Device) -> Result<()> { + Devres::new_foreign_owned(dev, Self::new()?, GFP_KERNEL) + } +} + +/// CPU frequency driver callbacks. +impl Registration { + /// Driver's `init` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn init_callback(ptr: *mut bindings::cpufreq_policy) -> ker= nel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + + let data =3D T::init(policy)?; + policy.set_data(data)?; + Ok(0) + }) + } + + /// Driver's `exit` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn exit_callback(ptr: *mut bindings::cpufreq_policy) { + // SAFETY: The `ptr` is guaranteed to be valid by the contract wit= h the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + + let data =3D policy.clear_data(); + let _ =3D T::exit(policy, data); + } + + /// Driver's `online` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn online_callback(ptr: *mut bindings::cpufreq_policy) -> k= ernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::online(policy).map(|()| 0) + }) + } + + /// Driver's `offline` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn offline_callback(ptr: *mut bindings::cpufreq_policy) -> = kernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::offline(policy).map(|()| 0) + }) + } + + /// Driver's `suspend` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn suspend_callback(ptr: *mut bindings::cpufreq_policy) -> = kernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::suspend(policy).map(|()| 0) + }) + } + + /// Driver's `resume` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn resume_callback(ptr: *mut bindings::cpufreq_policy) -> k= ernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::resume(policy).map(|()| 0) + }) + } + + /// Driver's `ready` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn ready_callback(ptr: *mut bindings::cpufreq_policy) { + // SAFETY: The `ptr` is guaranteed to be valid by the contract wit= h the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::ready(policy); + } + + /// Driver's `verify` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn verify_callback(ptr: *mut bindings::cpufreq_policy_data)= -> kernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let data =3D unsafe { PolicyData::from_raw_mut(ptr) }; + T::verify(data).map(|()| 0) + }) + } + + /// Driver's `setpolicy` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn setpolicy_callback(ptr: *mut bindings::cpufreq_policy) -= > kernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::setpolicy(policy).map(|()| 0) + }) + } + + /// Driver's `target` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn target_callback( + ptr: *mut bindings::cpufreq_policy, + target_freq: u32, + relation: u32, + ) -> kernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::target(policy, target_freq, Relation::new(relation)?).map(|= ()| 0) + }) + } + + /// Driver's `target_index` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn target_index_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> kernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + + // SAFETY: The C code guarantees that `index` corresponds to a= valid entry in the + // frequency table. + let index =3D unsafe { TableIndex::new(index as usize) }; + + T::target_index(policy, index).map(|()| 0) + }) + } + + /// Driver's `fast_switch` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn fast_switch_callback( + ptr: *mut bindings::cpufreq_policy, + target_freq: u32, + ) -> kernel::ffi::c_uint { + // SAFETY: The `ptr` is guaranteed to be valid by the contract wit= h the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::fast_switch(policy, target_freq) + } + + /// Driver's `adjust_perf` callback. + extern "C" fn adjust_perf_callback( + cpu: u32, + min_perf: usize, + target_perf: usize, + capacity: usize, + ) { + if let Ok(mut policy) =3D PolicyCpu::from_cpu(cpu) { + T::adjust_perf(&mut policy, min_perf, target_perf, capacity); + } + } + + /// Driver's `get_intermediate` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn get_intermediate_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> kernel::ffi::c_uint { + // SAFETY: The `ptr` is guaranteed to be valid by the contract wit= h the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + + // SAFETY: The C code guarantees that `index` corresponds to a val= id entry in the + // frequency table. + let index =3D unsafe { TableIndex::new(index as usize) }; + + T::get_intermediate(policy, index) + } + + /// Driver's `target_intermediate` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn target_intermediate_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> kernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + + // SAFETY: The C code guarantees that `index` corresponds to a= valid entry in the + // frequency table. + let index =3D unsafe { TableIndex::new(index as usize) }; + + T::target_intermediate(policy, index).map(|()| 0) + }) + } + + /// Driver's `get` callback. + extern "C" fn get_callback(cpu: u32) -> kernel::ffi::c_uint { + PolicyCpu::from_cpu(cpu).map_or(0, |mut policy| T::get(&mut policy= ).map_or(0, |f| f)) + } + + /// Driver's `update_limit` callback. + extern "C" fn update_limits_callback(ptr: *mut bindings::cpufreq_polic= y) { + // SAFETY: The `ptr` is guaranteed to be valid by the contract wit= h the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::update_limits(policy); + } + + /// Driver's `bios_limit` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn bios_limit_callback(cpu: i32, limit: *mut u32) -> kernel= ::ffi::c_int { + from_result(|| { + let mut policy =3D PolicyCpu::from_cpu(cpu as u32)?; + + // SAFETY: `limit` is guaranteed by the C code to be valid. + T::bios_limit(&mut policy, &mut (unsafe { *limit })).map(|()| = 0) + }) + } + + /// Driver's `set_boost` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn set_boost_callback( + ptr: *mut bindings::cpufreq_policy, + state: i32, + ) -> kernel::ffi::c_int { + from_result(|| { + // SAFETY: The `ptr` is guaranteed to be valid by the contract= with the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::set_boost(policy, state).map(|()| 0) + }) + } + + /// Driver's `register_em` callback. + /// + /// SAFETY: Called from C. Inputs must be valid pointers. + extern "C" fn register_em_callback(ptr: *mut bindings::cpufreq_policy)= { + // SAFETY: The `ptr` is guaranteed to be valid by the contract wit= h the C code for the + // lifetime of `policy`. + let policy =3D unsafe { Policy::from_raw_mut(ptr) }; + T::register_em(policy); + } +} + +impl Drop for Registration { + /// Unregisters with the cpufreq core. + fn drop(&mut self) { + // SAFETY: `self.0` is guaranteed to be valid for the lifetime of = `Registration`. + unsafe { bindings::cpufreq_unregister_driver(self.0.get_mut()) }; + } +} --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pl1-f181.google.com (mail-pl1-f181.google.com [209.85.214.181]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A3F8026B2C4 for ; Mon, 19 May 2025 07:08:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.181 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638521; cv=none; b=ks3L8eQjDX0ys7+Y9mKW9YJsJ+h6mPsxJYcbO5/3wGe16sqSDYyrnv5foKiJYFt+BqKxH7EHhrTPqBWnMMGEPt6rAUHGMRScTU3KhW2BED9xxgi+a6nV1icx1kKZ/LTOV8g9AyeGeps5/yJ+HXOxBzr8dmcIOdKwllp2hL0zOtU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638521; c=relaxed/simple; bh=QB1NDnIN2+10EfH7zVK4+js+l6z1NvQ0KLDj/lkYjH0=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=oXc0miy0HX/0tAXAweKU/BSjeRN1jGFb3uCRxPySQbqpsYaAFMPHOE4Q5NRAfQH+jGRhjAMuoDcJgzX6gca/twMiB1LWeryQYPWJh1X/c/egMu3/6bIyAAdZk7iGGDCvRF5xJhvs4arbVeVSt3Y7if5plOoM0GIVdSHyemIJQKo= 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=O+cGX1l+; arc=none smtp.client-ip=209.85.214.181 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="O+cGX1l+" Received: by mail-pl1-f181.google.com with SMTP id d9443c01a7336-2322bace4ceso6032075ad.2 for ; Mon, 19 May 2025 00:08:39 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638519; x=1748243319; 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=zV8iUMBX+j7TsKW8lH5BBlCVzlR9XbeiRbiHVvWBeLs=; b=O+cGX1l++cFgpf0MJm1qSDy7j8sY3gwFAhZiW6UaS2xgQSqUCvK6PNz+2/VXJCT0ch PzRG8QT+RhDAe1Ci4DPdXatS/MJ4v+/qqd+O/EfrFDdtsPsrwOljQwV+BSvK1BRzd7FT 1oleRszUJDnkcHmZQOge1VvOLKkrM57M2Tbj/cJHQumD6rW6B8t3UKr4usLP3Z1oCVs/ pdbp2OMQrW3hep+hrHwtp/BP3L9axskR1tUeCYcE43N0tVffVuK8keEt4mR8wD7mlepE mneUVrDBtRLUOPoi23YuJhlSuyozokCi4sOtLBXJb9pjPvIynnMX5Gff8PFl0tUgKTIu Cz9A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638519; x=1748243319; 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=zV8iUMBX+j7TsKW8lH5BBlCVzlR9XbeiRbiHVvWBeLs=; b=QcZs46JYOVzY+sQnuvnkdYf0lXIzsYOF0u1brffgqD4WOP+yoRWopoTgrT6JDKLHy9 e62Wqk8TdpFO8iD+zdAqnWXD4wF8+W6ZPD2YJ5er0k3PkC6GaVBubnog42jKtGVWcyLN LmbB1CedDbMt6km5Apq/8PjlzedW2a9fIycqVNpkbuGg4finc2GRE7QkPdbRUID4rOR1 jsZiprgaD7aXuTEjc6/F0lWHlUKxCAfAauNIZ3/W0bM9EP0rMEdG3DVP29C9v0lFMGBS 8MsSr7hMqYyqF4mrG2b9NkfHjP8UjIL2vWIT4zQVWcGtzT5azz2fN6pe5NjPhQYHOhpt TH2g== X-Forwarded-Encrypted: i=1; AJvYcCU8H59pusy9f1G9X5iqWfH1GIaFhKgYY+ha+YtAGNPoYwELgB1n7BRxl4Q8mYUhyhpxEHCQow0u8D7AyQs=@vger.kernel.org X-Gm-Message-State: AOJu0YzlgI+uGseBPhAVJnpNS8/dHVdfi34Ly47zJsEhbezXPjs+onRq qBTy8SNthTHsbgYuHfaxE9WC18/i6YW2vBjP40WUFhK7wRjWFIGM4iFbi03o/iDQ1po= X-Gm-Gg: ASbGncuuELuUXnCIqf6sPXyeEBmgzKuD6bXOBndZphvk7m5TgTq4BpYxN7RoO7swMrK Mk8Fpslv6nkWW7HtTGERK/k2OesLNwA1gx2xispR4xwJF84/rAMVydj858D0ba7IJA2+DXf/woz hvoHExxeVRf8+mtat+goSlE1i0Ov3D3/RXgxsvrxhCTpKj13bqx3S//8XWE6r+u4e68tSZulM9x SK2RWpqJjT88y2bqIIpJmN1wT6yXOpWsuCglT5lpuVJqaaTMCvq0nqczvB18rbZYN2SjlguiyOJ O8vwt9hL3LyOVsZaKRpj7Q/Jkv8bQZDs6vDh+BHo9zh3UCa9DJhWCR+YEUmFlIM= X-Google-Smtp-Source: AGHT+IHEjkPhd0v9dHUnrSumRKqtP+XO8qTwXgH5hnKDzbAp7zerm30lnT7DxIhX8VkHWyBQkdAPVw== X-Received: by 2002:a17:903:18d:b0:224:c47:cbd with SMTP id d9443c01a7336-231d3257fc6mr161226955ad.0.1747638518855; Mon, 19 May 2025 00:08:38 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-231d4eba368sm53296525ad.200.2025.05.19.00.08.37 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:38 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Nishanth Menon , Stephen Boyd , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 14/15] rust: opp: Extend OPP abstractions with cpufreq support Date: Mon, 19 May 2025 12:37:19 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Extend the OPP abstractions to include support for interacting with the cpufreq core, including the ability to retrieve frequency tables from OPP table. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 7be6fd33d93f..1e5fd9887b3a 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -19,6 +19,69 @@ types::{ARef, AlwaysRefCounted, Opaque}, }; =20 +#[cfg(CONFIG_CPU_FREQ)] +/// Frequency table implementation. +mod freq { + use super::*; + use crate::cpufreq; + use core::ops::Deref; + + /// OPP frequency table. + /// + /// A [`cpufreq::Table`] created from [`Table`]. + pub struct FreqTable { + dev: ARef, + ptr: *mut bindings::cpufreq_frequency_table, + } + + impl FreqTable { + /// Creates a new instance of [`FreqTable`] from [`Table`]. + pub(crate) fn new(table: &Table) -> Result { + let mut ptr: *mut bindings::cpufreq_frequency_table =3D ptr::n= ull_mut(); + + // SAFETY: The requirements are satisfied by the existence of = [`Device`] and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_init_cpufreq_table(table.dev.as_raw()= , &mut ptr) + })?; + + Ok(Self { + dev: table.dev.clone(), + ptr, + }) + } + + /// Returns a reference to the underlying [`cpufreq::Table`]. + #[inline] + fn table(&self) -> &cpufreq::Table { + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + unsafe { cpufreq::Table::from_raw(self.ptr) } + } + } + + impl Deref for FreqTable { + type Target =3D cpufreq::Table; + + #[inline] + fn deref(&self) -> &Self::Target { + self.table() + } + } + + impl Drop for FreqTable { + fn drop(&mut self) { + // SAFETY: The pointer was created via `dev_pm_opp_init_cpufre= q_table`, and is only + // freed here. + unsafe { + bindings::dev_pm_opp_free_cpufreq_table(self.dev.as_raw(),= &mut self.as_raw()) + }; + } + } +} + +#[cfg(CONFIG_CPU_FREQ)] +pub use freq::FreqTable; + use core::{marker::PhantomData, ptr}; =20 use macros::vtable; @@ -753,6 +816,13 @@ pub fn adjust_voltage( }) } =20 + /// Creates [`FreqTable`] from [`Table`]. + #[cfg(CONFIG_CPU_FREQ)] + #[inline] + pub fn cpufreq_table(&mut self) -> Result { + FreqTable::new(self) + } + /// Configures device with [`OPP`] matching the frequency value. #[inline] pub fn set_rate(&self, freq: Hertz) -> Result<()> { --=20 2.31.1.272.g89b43f80a514 From nobody Sat Feb 7 18:52:51 2026 Received: from mail-pj1-f44.google.com (mail-pj1-f44.google.com [209.85.216.44]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2F61F26B96F for ; Mon, 19 May 2025 07:08:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.44 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638527; cv=none; b=QCrqAh4yKAQOo4k7rTXQeEtZsu9vmqlG4FjaPFdYOeBxZHGn5Yd/a9Or5rHByZuhyxr8vUo35IGyBWz3gnMyoHBO2aCGlF34B1HCKORplt0Q1a2rOS7l1GUdtw8U2J8kphpkDu5zI2B0qJP7b3QOnJ4CfKjfp9+NY1f+RgrxMKw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747638527; c=relaxed/simple; bh=bSGfihaGNpTLrew2plb74IvPF9i/L//OlHXrjuPBnlM=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=mCG3LcECUZ4mdKZJGJKwerZXFzbka6UDVyC2KEHfqx2aaoW3ZZ4rSo5EcFi+8kiUJzO0puUJKeSXHa8iVbUzacTMQUp1eJMiifcgtXOADdXIeJqfhDT/pB8HEIRJHd1S1GFESAvv7VS9fmusZ9cPZTJgcagvkvWAR7o8vSaIv00= 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=JT0lb29K; arc=none smtp.client-ip=209.85.216.44 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="JT0lb29K" Received: by mail-pj1-f44.google.com with SMTP id 98e67ed59e1d1-30ea559c18aso2115059a91.2 for ; Mon, 19 May 2025 00:08:43 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1747638523; x=1748243323; 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=uJD5XxP/UbgU2tTClsXxFPL2OFZZwS3SIz16j9nmHb0=; b=JT0lb29KTtR36Wba+Hnnqp6llM+gdcUwHgurfehZ0imFtZ71IurI6yofcVmF63vyKa rhMCLQ8eeMQ5vYYFOOL2Gf90qZrMSWgDv96PI3MKiEit/1R0byGDnx4Cj0lRSq6+OtIx j6rAeofnIUM6unG/7gsb45kULHTZ42VyARti0IguhNL5NJGJXa9kmNbts07BX0S/smb5 /VlKej9JhAwqgNLWd7hjD0LTZ0Bsrn3K3Utk1lokrmaAQV76GG4bNclTpgWNOCAeo8sM tmP9pl2VfBP2smGCwS1+EJfixgB0UIqVfg6nR+s7/NCN0cp6HevzRnrFHPwCOA2IHvza /CVw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747638523; x=1748243323; 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=uJD5XxP/UbgU2tTClsXxFPL2OFZZwS3SIz16j9nmHb0=; b=KkCSTqU9/E6I8UZ8yOd1s0Q2zTTolaLg18voNM/hqn6oggG4XcIxLmgkjitjytsTHG fUQjDcTk+EmZzNzG0ABapda1HpX8cflmQYCe7JNNaTROsN2PzRte5LGIvplHrk4l91gJ mR1noZzV82IZyYYIvdfssKtOyIscUPobpWpKi7h/uOYjBTKz2b3zMhzsvs/XDfP7wpcs 0lBsZRBWvEeo67NGEhxLvkYsjU0Vuw5auBFOWJgMxspsdSpcNuGb4lv8AZ9jF665zEKD +BpHkPpSEOuQSsJa098jGxC8Y4fq5v54nDhLkx7TZn+gzXD11xNX/pw7OAJSPnTM6zSQ EH9g== X-Forwarded-Encrypted: i=1; AJvYcCVGnxfrTIWrWkSBpwv3rV/VBmkwZLypFI+IATsQVTMnx98Qyvj+W4yIabmWJSruyWepQcPttQxV+9bYg1I=@vger.kernel.org X-Gm-Message-State: AOJu0YxgWNvpOWIeV1UVRoJV6com4M73Jjeg33+hzMj0d4Epxn1z5Seo UVcXPMlBP5AjCEcYXmZbiwgo+5ndt+GNCOoIkrK3N1ztxrTc1z8r9HuLnvwqr4KG3Ys= X-Gm-Gg: ASbGncvlwF0hZG0MGDa5F9Gao2ePvCSspPJjluFwOk34cMEYIXzI4eITWNqw51BSvsH +9lt8BEGv2AUpTZ0lDzxYaPnlrLtOyesGqWa5csb8Wu7arCCTIiIxcvtWZjVzSXYpUFAOWyXfMP +7+OLNOIE8It2rVKl2Wqgvbhmsr2/l1jrGhRKHSkfSyb3fpxosQA82Q84rvMHGVGuLJqPs0B4Oz AGgH/LbG+QpCXm6LM+ItyS83/qQdNPhTxlGK5YQYt+tjCq1hPlMIEfCxmy0EwrbZZFjpYMlJNfN pZbd00/KAMlAX43rvT+0NdBnQ57k7ci7G8GbP1anrF/fsXoF6GlU X-Google-Smtp-Source: AGHT+IFo7mmwVBQMKnS8Mxe6oQBwNYviN6LJSTibi/frTfT92J4pR6GkI4npO9nvxXO90t92Edat7Q== X-Received: by 2002:a17:90b:4ccb:b0:2ff:5c4e:5acd with SMTP id 98e67ed59e1d1-30e7d5ca16emr19302001a91.35.1747638523205; Mon, 19 May 2025 00:08:43 -0700 (PDT) Received: from localhost ([122.172.81.72]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-30e6d90654asm6570718a91.34.2025.05.19.00.08.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 19 May 2025 00:08:42 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , =?UTF-8?q?Alex=20Benn=C3=A9e?= , Joakim Bech , Rob Herring , Yury Norov , Burak Emir , Rasmus Villemoes , Russell King , linux-clk@vger.kernel.org, Michael Turquette , Andrew Ballance , linux-kernel@vger.kernel.org Subject: [PATCH V12 15/15] cpufreq: Add Rust-based cpufreq-dt driver Date: Mon, 19 May 2025 12:37:20 +0530 Message-Id: <23209b3d12c33fe5e13f5a80704bb3b319ebbd7c.1747634382.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Introduce a Rust-based implementation of the cpufreq-dt driver, covering most of the functionality provided by the existing C version. Some features, such as retrieving platform data from `cpufreq-dt-platdev.c`, are still pending. The driver has been tested with QEMU, and frequency scaling works as expected. Signed-off-by: Viresh Kumar --- drivers/cpufreq/Kconfig | 12 ++ drivers/cpufreq/Makefile | 1 + drivers/cpufreq/rcpufreq_dt.rs | 229 +++++++++++++++++++++++++++++++++ 3 files changed, 242 insertions(+) create mode 100644 drivers/cpufreq/rcpufreq_dt.rs diff --git a/drivers/cpufreq/Kconfig b/drivers/cpufreq/Kconfig index d64b07ec48e5..78702a08364f 100644 --- a/drivers/cpufreq/Kconfig +++ b/drivers/cpufreq/Kconfig @@ -217,6 +217,18 @@ config CPUFREQ_DT =20 If in doubt, say N. =20 +config CPUFREQ_DT_RUST + tristate "Rust based Generic DT based cpufreq driver" + depends on HAVE_CLK && OF && RUST + select CPUFREQ_DT_PLATDEV + select PM_OPP + help + This adds a Rust based generic DT based cpufreq driver for frequency + management. It supports both uniprocessor (UP) and symmetric + multiprocessor (SMP) systems. + + If in doubt, say N. + config CPUFREQ_VIRT tristate "Virtual cpufreq driver" depends on GENERIC_ARCH_TOPOLOGY diff --git a/drivers/cpufreq/Makefile b/drivers/cpufreq/Makefile index 22ab45209f9b..d38526b8e063 100644 --- a/drivers/cpufreq/Makefile +++ b/drivers/cpufreq/Makefile @@ -15,6 +15,7 @@ obj-$(CONFIG_CPU_FREQ_GOV_COMMON) +=3D cpufreq_governor.o obj-$(CONFIG_CPU_FREQ_GOV_ATTR_SET) +=3D cpufreq_governor_attr_set.o =20 obj-$(CONFIG_CPUFREQ_DT) +=3D cpufreq-dt.o +obj-$(CONFIG_CPUFREQ_DT_RUST) +=3D rcpufreq_dt.o obj-$(CONFIG_CPUFREQ_DT_PLATDEV) +=3D cpufreq-dt-platdev.o obj-$(CONFIG_CPUFREQ_VIRT) +=3D virtual-cpufreq.o =20 diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs new file mode 100644 index 000000000000..d0e60b7db81f --- /dev/null +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust based implementation of the cpufreq-dt driver. + +use kernel::{ + c_str, + clk::Clk, + cpu, cpufreq, + cpumask::CpumaskVar, + device::{Core, 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(dev: &Device, name: &str) -> Option { + let prop_name =3D CString::try_from_fmt(fmt!("{}-supply", name)).ok()?; + dev.property_present(&prop_name) + .then(|| CString::try_from_fmt(fmt!("{name}")).ok()) + .flatten() +} + +/// Finds supply name for the CPU from DT. +fn find_supply_names(dev: &Device, cpu: u32) -> Option> { + // Try "cpu0" for older DTs, fallback to "cpu". + let name =3D (cpu =3D=3D 0) + .then(|| find_supply_name_exact(dev, "cpu0")) + .flatten() + .or_else(|| find_supply_name_exact(dev, "cpu"))?; + + let mut list =3D KVec::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, + _mask: CpumaskVar, + _token: Option, + _clk: Clk, +} + +#[derive(Default)] +struct CPUFreqDTDriver; + +#[vtable] +impl opp::ConfigOps for CPUFreqDTDriver {} + +#[vtable] +impl cpufreq::Driver for CPUFreqDTDriver { + const NAME: &'static CStr =3D c_str!("cpufreq-dt"); + const FLAGS: u16 =3D cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq= ::flags::IS_COOLING_DEV; + const BOOST_ENABLED: bool =3D true; + + type PData =3D Arc; + + fn init(policy: &mut cpufreq::Policy) -> Result { + let cpu =3D policy.cpu(); + // SAFETY: The CPU device is only used during init; it won't get h= ot-unplugged. The cpufreq + // core registers with CPU notifiers and the cpufreq core/driver = won't use the CPU device, + // once the CPU is hot-unplugged. + let dev =3D unsafe { cpu::from_cpu(cpu)? }; + let mut mask =3D CpumaskVar::new_zero(GFP_KERNEL)?; + + mask.set(cpu); + + let token =3D find_supply_names(dev, cpu) + .map(|names| { + opp::Config::::new() + .set_regulator_names(names)? + .set(dev) + }) + .transpose()?; + + // Get OPP-sharing information from "operating-points-v2" bindings. + let fallback =3D match opp::Table::of_sharing_cpus(dev, &mut mask)= { + Ok(()) =3D> false, + Err(e) if e =3D=3D ENOENT =3D> { + // "operating-points-v2" not supported. If the platform ha= sn't + // set sharing CPUs, fallback to all CPUs share the `Polic= y` + // for backward compatibility. + opp::Table::sharing_cpus(dev, &mut mask).is_err() + } + Err(e) =3D> return Err(e), + }; + + // Initialize OPP tables for all policy cpus. + // + // For platforms not using "operating-points-v2" bindings, we do t= his + // before updating policy cpus. Otherwise, we will end up creating + // duplicate OPPs for the CPUs. + // + // OPPs might be populated at runtime, don't fail for error here u= nless + // it is -EPROBE_DEFER. + let mut opp_table =3D match opp::Table::from_of_cpumask(dev, &mut = mask) { + Ok(table) =3D> table, + Err(e) =3D> { + if e =3D=3D EPROBE_DEFER { + return Err(e); + } + + // The table is added dynamically ? + opp::Table::from_dev(dev)? + } + }; + + // The OPP table must be initialized, statically or dynamically, b= y this point. + opp_table.opp_count()?; + + // Set sharing cpus for fallback scenario. + if fallback { + mask.setall(); + opp_table.set_sharing_cpus(&mut mask)?; + } + + let mut transition_latency =3D opp_table.max_transition_latency_ns= () as u32; + if transition_latency =3D=3D 0 { + transition_latency =3D cpufreq::ETERNAL_LATENCY_NS; + } + + policy + .set_dvfs_possible_from_any_cpu(true) + .set_suspend_freq(opp_table.suspend_freq()) + .set_transition_latency_ns(transition_latency); + + let freq_table =3D opp_table.cpufreq_table()?; + // SAFETY: The `freq_table` is not dropped while it is getting use= d by the C code. + unsafe { policy.set_freq_table(&freq_table) }; + + // SAFETY: The returned `clk` is not dropped while it is getting u= sed by the C code. + let clk =3D unsafe { policy.set_clk(dev, None)? }; + + mask.copy(policy.cpus()); + + Ok(Arc::new( + CPUFreqDTDevice { + opp_table, + freq_table, + _mask: mask, + _token: token, + _clk: 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: cpufreq::TableInd= ex) -> Result<()> { + let Some(data) =3D policy.data::() else { + return Err(ENOENT); + }; + + let freq =3D data.freq_table.freq(index)?; + data.opp_table.set_rate(freq) + } + + 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() + } +} + +kernel::of_device_table!( + OF_TABLE, + MODULE_OF_TABLE, + ::IdInfo, + [(of::DeviceId::new(c_str!("operating-points-v2")), ())] +); + +impl platform::Driver for CPUFreqDTDriver { + type IdInfo =3D (); + const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); + + fn probe( + pdev: &platform::Device, + _id_info: Option<&Self::IdInfo>, + ) -> Result>> { + cpufreq::Registration::::new_foreign_owned(pdev.a= s_ref())?; + + let drvdata =3D KBox::new(Self {}, GFP_KERNEL)?; + + Ok(drvdata.into()) + } +} + +module_platform_driver! { + type: CPUFreqDTDriver, + name: "cpufreq-dt", + author: "Viresh Kumar ", + description: "Generic CPUFreq DT driver", + license: "GPL v2", +} --=20 2.31.1.272.g89b43f80a514