From nobody Fri Dec 19 19:07:38 2025 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 D80B222539D for ; Wed, 16 Apr 2025 06:39:55 +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=1744785597; cv=none; b=Csy6AE1HLxCyBID+L+9F+ZeFaBmCISv77uPWSSw4UrmlGPiqEQiSOLMdJaIKOZaMYZN/gyBxWBe1ScE0J73H0m81SKuKTWRz4utY2Kzj4mJZ6IZfc9szEn0+lzAuCftGxLT/ebEYLmfQwek4LLe/egEVVJQ+6aOwFS0VbFrC8Ic= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785597; c=relaxed/simple; bh=oQ/uumB9dZEnQv7fbXO+2/DavkdF+8BaxTejDAZiJqM=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=aVR3GtKUqXk/zuU/7X8K+7SyKGryCMKKoUsd4wZscT0xkgXCgxJJfOVj4XHCwHzDtO6eS1ODhaHhO1vL6gIv8hOJXTKpN4IwhKdcjeNnNFwxa0Jvdp4+JRb08Dbm1g9TYMHuOaB6gTJyzMXFYFNMiUaMLQ+B3X+Xn98W6Nrbdog= 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=ib2FhzMV; 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="ib2FhzMV" Received: by mail-pf1-f172.google.com with SMTP id d2e1a72fcca58-7399838db7fso416979b3a.0 for ; Tue, 15 Apr 2025 23:39:55 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785595; x=1745390395; 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=Br+IpXn10n+9CXIhhXnelWYoEuJ5Sc8cDeYzc7Zl6Z4=; b=ib2FhzMVdjhE8Ima3d9pvbNLIsGNzlzhF2/5JbBYFtPhiJu6X34TUzC5OyrjOXxYNl XjZAvQd8notnbNpecYZ337tWqvrmsZ0Qrl5gmXYq+ZfhO3Wxb/FkbDypFqc78hugsM7J wVkSntcD58FAONVG0HOQz0t+RSkB5pzy9b7b1wUT8Wpntee2pa9e/VejZ0RLUHaJAlRJ ffzGRo3dgTWW6suM29zduUHYDfbSWgcoIRu8q8uGwXmCHLgvEyJdh9ro86MpMN59Yg9P c2yKs3Su0sxTxwGnChcajqLNejHprJQzCSBG7SIRlEMRWDcEgzuoNjgJ/DZLlbg4BAf3 /rHg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785595; x=1745390395; 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=Br+IpXn10n+9CXIhhXnelWYoEuJ5Sc8cDeYzc7Zl6Z4=; b=oyj3Z0RByiBsxzxlsogTcSc0i3AibPFiY/D3OzVJhq9mUJyWL0OPtWBsZy/M1+ravm TOZ9tGivfNPlXs4JEzLinUlbwpJhzvuuFnD+epHRHbAxhnPKAW6dOoft+9yHYHYG+Xvi KCIEHcayhhYPdDcBYJAYIpFFGWu6d8QV0LHl7+ZF675WrNQGqWr3mXTn9hhlmYr4uN3p xw2Fph0OEZFrFll1x/0ZND1n4KgbtujfXYyUIgyL1lorOtME+/iKKrHoeMahWs8Hx3z9 fTl0ps5l8T8SibbvB+W/fPWDYh4hR8k6olNIpvwNoKuO8/I34MrcID6i4esDB+3WQZ5q NyVw== X-Forwarded-Encrypted: i=1; AJvYcCUINHwCyblwKBukV1ooiEf+eNOhTXmm8jqG5YDKxWfPmwtY0Dwuaj0tsuAfeyenJZTO6WpF5/nY0GCMLE8=@vger.kernel.org X-Gm-Message-State: AOJu0YzGS0qweGSYIcfbyfY9c9RZzmWqG+ozwBHQ06CsTlDzo65sg4ru fphGpUHtlVHB+bKk8UFrq4Sulc+sT3Dn2amJSp1UouJj0BYRvZ4Nf83rSq3+kjU= X-Gm-Gg: ASbGncut6pH2NeRTj34GQtCXCm+nxMS0wqOkSJn9CivaOwI1QqG9R4hYysGyef2Sead uz7GWJF+vSIRg4kmCCnuvAjDv00q69aEB8WEqH3/Kyil6571O7RRmkd0GTCZRYpV0tNmMWfiNhB EfWe4lMSPk+Fdz85yXozPckxmc8sY+w5JVt5vmfyFHdzs6rPAQTHcjwnzEQd+dxyJpSMzB2fg0i 1fwxKAJ6DBv6qCNpFApFsk5IQFYaflENfPNFasw28sEpB3gdAKAJFYF4l91HRN1XqIQbEEPfyr8 iHjMmt37smZTVOL9K85zYttk9bb1TroSZ3LsNBLS9A== X-Google-Smtp-Source: AGHT+IFdD6luOUWiu9XjQ7/e9KFVr+7wVcpXj2xETy5cd4GCfwB2LGWz+opg97LDR1wqgUuvWsquiA== X-Received: by 2002:a05:6a00:4098:b0:736:b400:b58f with SMTP id d2e1a72fcca58-73c26b73c05mr1127405b3a.0.1744785595123; Tue, 15 Apr 2025 23:39:55 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73bd22f8850sm9582141b3a.87.2025.04.15.23.39.54 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:39:54 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 01/15] rust: cpumask: Add few more helpers Date: Wed, 16 Apr 2025 12:09:18 +0530 Message-Id: <944ee57ad1b190f6975c739802b4d93166bd00c5.1744783509.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 --- 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 Fri Dec 19 19:07:38 2025 Received: from mail-pl1-f174.google.com (mail-pl1-f174.google.com [209.85.214.174]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D28B922D4D9 for ; Wed, 16 Apr 2025 06:39:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.174 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785603; cv=none; b=hvswbW7k1+KnbITiO8UC10UICwcCEDsryP+/GgmDCi9tIykdJ02/Nk//MeV+1WqYz9n4V5XSoyTP3S9VMST9QJkDnPdV4gNFvJrbO9ZFQjXRLE+rMzxECeuhaTTkelpAWFTzwGlT4bPiBw0nb1Bg02sLHNZDyoLa7avAPYG7qjU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785603; c=relaxed/simple; bh=6bdBeyQA7PvDMni0+v4HEV40R5KCJ3SAKrl8WzzUVVY=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=VNaw42v1So1QNyY9AlvSSxzB9VZNLGIW0NpoomUX2Tas2CejLmtSrknaEhYlsmr1UBkdhwi6KOkciMSLgY3RT0iBxNOLcDgEmOsgBZGZj1cGlYUcddMjgMcAQY6v7eLw1xTWdPj6IHZRFR5muS8Qlf31NvwlTG/hEeFLbXLGSgQ= 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=Mi0DhAl7; arc=none smtp.client-ip=209.85.214.174 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="Mi0DhAl7" Received: by mail-pl1-f174.google.com with SMTP id d9443c01a7336-22423adf751so59342935ad.2 for ; Tue, 15 Apr 2025 23:39:59 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785599; x=1745390399; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=pYpmBeA7UxnY21oeYlIxfV+okNCfPfqyF8VN8X/0Ne0=; b=Mi0DhAl7LCmpA6886+JcUUgt2BFgqI4P64t66tCPDBIJVtHaXOqeFNdhO/2oflqKtK uidbcPLgR+7yQ+CgBxjjl3avZg7of1ONYAY/0dsuVZl3UeMNaZdVm6zWFly9qe4qPeAA +5PYkg9c7vVg5TDVuAWHydoX+Y8Oay+yNBQ+T7tLmmZhoq+/k9wEsGu1ZN03/s8+TGCW 4VcazVR5p+zZ4Wri1vmZLWIIt8J2VBIaJCAjPEyZjI8DuXCRdsLh7i/paYvNoARVPicO MgBHTGcVDVWjscfRbqUtNLl/9ldnzmAFpYfLZNzoyk0MeGb5JkA7bUTPTvgWWSCwpi89 hNyA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785599; x=1745390399; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=pYpmBeA7UxnY21oeYlIxfV+okNCfPfqyF8VN8X/0Ne0=; b=XBGKHzxBysEiAQ4Uqorku7U5aZDC9VKb/vokLQ7iUEtkpHMJVel5IHuy+6JZw5NGjC XIWnT9t5iM0+P3haD75mkOarAyQ3YMoEO3YSbMb1+xQ9usWXeyNdjNpxOWKbUfVdbueZ Byd2By2gf3K6n6Bn1smb/FFDtqkka47n+LOwwLn5gQTNDI1o/Hz0cnrfAdJd4HU3pxJx Hs92UskhIPE8NONUzxVlaX6H8FFvWOVJWAbop6XABwh7W5SfOWpTnzrIjb1bvI2Rh33m qg2ZYNq4nO3WBPOgaiV6/Ca4Vd3cZbM7UtjXNdYhQ72FcMgTPAjPe/8W9+z9fc8cfUCU Jlaw== X-Forwarded-Encrypted: i=1; AJvYcCVa9k0jiePzIop/rt8YtkCMm7qjPWG2slx6RQz5GNzeZUHB4ws+o1FNaanlrumN7zVE1BOifAVAOxzIDMc=@vger.kernel.org X-Gm-Message-State: AOJu0Yxqq36rNohOcaJo7ZC9qQeTt6KzM/l1iD2N/ara0xMJRkQDo9Hf mO1qZMJ9MO47nm5TzrR2zNAaQqCBd+n/a2hCXgoVCuLeVSaniwQv56Rev0SywLM= X-Gm-Gg: ASbGncutApV6zzD9GvlnIGrb+C8R5ljuO7JnWlujJpLKZ5AKvzPv2Pn6m8s881j9Ks3 U6MttR+KLqfbJSmrxBSa3FhB1wS6ydAS7FVZA6SiA2KgHIkDc/+9SxggMMGslzEE8+Ux2VJctvq kF67NXWmzrf7+2l4cUBGRPFuGYeLM/qhqExB29RBzHoN8XK9rArUGtbTNBwuINPIePKrNesAzhb 72CKR3cwUm/Tj7uYsUJ9cd+SozklAwObeRixmvFEK45ZqHFrpwGzjncAsREu6THtQhXW7iTqklQ HS1iV32eP4cCL1hPVs5H0ie9LUPoMQvq+w/wxIssEA== X-Google-Smtp-Source: AGHT+IF7+Znv/mh7oQp9bmsmrTu5Ck/d5f/pMdRTPsL2N0g8egNebJnX1OOrb+ljUt4NujTr3M8rdA== X-Received: by 2002:a17:902:d548:b0:224:1af1:87f4 with SMTP id d9443c01a7336-22c358db40amr11897185ad.22.1744785599024; Tue, 15 Apr 2025 23:39:59 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73bd230e32dsm9646607b3a.150.2025.04.15.23.39.58 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:39:58 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 02/15] rust: cpumask: Add initial abstractions Date: Wed, 16 Apr 2025 12:09:19 +0530 Message-Id: <4a8f23fd447897cb76ccc46d03cc30a2086a0e90.1744783509.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 --- 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 Fri Dec 19 19:07:38 2025 Received: from mail-pl1-f176.google.com (mail-pl1-f176.google.com [209.85.214.176]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3DFE322D7A1 for ; Wed, 16 Apr 2025 06:40:03 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.176 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785604; cv=none; b=GhGTWCrpQ0rYrg8CS9RmlSWjek9a71ATTVs35NXujqc8Z7Lp0ywKBlJD84lUyP2yDcjtPNLcUj1Cp0+REQFHeQnEwHPRyIIzloAeo8BJFFPQC/S6d56SBNACH3SC9NPLIVR5CiuKEgGlaO4s7xk2jX/j2Ro6eKNt2iqwNjEJAuk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785604; c=relaxed/simple; bh=pRm5rikPg836Cpaht6T2Bti6G/gsdEEiL/oreW2ehWs=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=NZzR4kpG3woCyhCkIRPcKBdqWh4m40oO9aUqfCoBE3qeeDd6clJ7aOJZA4vGUy6VG37whSZgLlfmZ3zH2W/k5Veg/35m/h9iPvvf+THc2dBuehOE6nt6TtTtaDSuYMQ4iKiSUFf5D21VHS5XN1Krnc1zKxfi3qGYH+pxk/X82/4= 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=JhrTT8/m; arc=none smtp.client-ip=209.85.214.176 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="JhrTT8/m" Received: by mail-pl1-f176.google.com with SMTP id d9443c01a7336-2295d78b45cso90447805ad.0 for ; Tue, 15 Apr 2025 23:40:02 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785602; x=1745390402; 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=JhrTT8/m6kO4m1EAju7eGEsIHuUpRJFWF1FdOvfrMlmY8vdAC0MKW92hpOqLqIeD3u C91iwFkVxT9dlwB7IPoQiEch9vxGD9JZwTpKADUy542/ZXjDrR80cTQ+QtYbjH4Cvi3k ZT5pqaH/w+rTipU32vW7bx5E5gP1WqRpDNi1+7KTzkCo5OjtcsQYsD09bBal5lgmVyIV RNGSuguuqi/ASd1VOp/wdEzjEC4/eENq0TaSJjXJUmIm59x+6VS7c7CMVTqJE1Zzalbs xHoZkCoyF6S01/ZP4kCq+S+vBViL2B6fngMgXJOBTcqF4UclE9+fnanYGihsQazr3qeG q9HA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785602; x=1745390402; 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=tzWBm2u0XnKAyqc8ek7zzyGiJMEy8xnT3Jk7bXXRuPw93i/qVA6lOnTZCNr/DwtqaB Nk7MjhaZkUuGGNH0iIHjFi9WN5Jr8+eruZCK3YnzlKf6LZBHbDKponONAmfUkgjCpKYW pny+4gODXTbf6vY/Q3BfR0YirDG7+LZcSfewBE+NkeICXIy7WA+TRSsFe/8aINOlBLqx 53dgZJ/gnRCI2lo9isuh0STVTwpn/GDBP5MmxhJvfM4n+46zzkndFU7twD0dWLIpSX+4 /NebU/ylHh15rVhuG/1UfW5Tk6x02qvfHEY58obg61VnmO64IbGAGzOQtlLzaMFm3r54 t/wA== X-Forwarded-Encrypted: i=1; AJvYcCVlP24bJecBKQIB7Ets8Okyf2J4yLwJUSwd+D6Ig8rzxDiM3q5MT2r20P4NHCcIE5SJSgrsoIXcogwxY44=@vger.kernel.org X-Gm-Message-State: AOJu0YydJhQlzKmJm9Z0XAKMmW/iOco2GCS42fr4i2esmAsmGzIpwP2s 3yb6JMsAP3aVf7CFYTvx2Ex1Fmi2+878936H+Sn6q9HdqVrDAQ/aCeAemxAbnmc= X-Gm-Gg: ASbGncsa9vzkWJVELn+HPMqoPh2omvM+1rxTI6NN12dRDfkN+Ng9LHlOWKnTzvwE9aA o4rRqJwCYhnvy1dbGd81aFjT8CufiTq0TRrk9rKdcgSuSHRjhyFEw5Ho4o77F3eAzNSnpnW3jcI bR5CcN89T2VWF6np0gq9j+65RYpFaoqJsaprLGAXCRRAt5linj0HjoM+I8BGHrtLGtUiQUwIClF HK2iCtxz/2cVieHlag2WYEyZ8LUV0jqO4x6NQr9X6PguRr2pxWzCx5v9UL5fFRDwbg+HNfd5gsf f0crUKMUiyuBHeK6ls+FbxTOb3YYiLke9TOvL7zEKA== X-Google-Smtp-Source: AGHT+IEZ0BjxMEufYyWXS1DlCdKaeRakmruSioO3vp2nVRyRnB2tMQN8Qlo8XDozRJzOoVI66wZ2Yw== X-Received: by 2002:a17:903:1aaf:b0:224:1781:a947 with SMTP id d9443c01a7336-22c358de2cdmr12563915ad.21.1744785602483; Tue, 15 Apr 2025 23:40:02 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c33f1d3cbsm6459055ad.97.2025.04.15.23.40.01 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:02 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 03/15] MAINTAINERS: Add entry for Rust cpumask API Date: Wed, 16 Apr 2025 12:09:20 +0530 Message-Id: <9115c43e4eae9fd958344e7befc945e0e649a6c5.1744783509.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 Fri Dec 19 19:07:38 2025 Received: from mail-pl1-f174.google.com (mail-pl1-f174.google.com [209.85.214.174]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 73E4B22B8BE for ; Wed, 16 Apr 2025 06:40:07 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.174 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785609; cv=none; b=fTGEXP1InTH3CVkgOt/XNfPNtLfv+fs1nbzlUhr7XEwvEcjAV57k2kCfRVxXFilC8VSboPaGqsdvjs5s6AG0vD2UgFMNwDhEzri8O1+P8iPgHBabNyZTAXgSVN67HQNggmbJujoChHBB0SQfQPkFtCqFKoA8QLba86PR03x0eyQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785609; c=relaxed/simple; bh=4HWksdgns8ejVb++Q4NJVdKDSuHEDHdMmvi+j+YhGlo=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=MGwe0YNSTLg7YxrD1GxxI7Ubyj4q+dGrI0/TUqetS2vaN7CwGzd2+1dQ8e4Y3cV7rhbKL6MfmOhfMUGc6cdBfUo1LcalScKm1uaQHjpbsxZy+E3i2LgvFp96Z1WZIF/LItYoSuoo9tMFBo9H4FTsrnZBRviaKa6kqEsuftVeM/8= 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=yVkwDNHK; arc=none smtp.client-ip=209.85.214.174 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="yVkwDNHK" Received: by mail-pl1-f174.google.com with SMTP id d9443c01a7336-2295d78b433so66567595ad.2 for ; Tue, 15 Apr 2025 23:40:07 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785607; x=1745390407; 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=yVkwDNHKd773ietJQVhcDSIcPR0scv67jKk94RIHiTDgBIoYEtjWTsxKy0bZdTXtTM oC5bscRTdZ/wLlxMw44OlWfMxBSkug+3RYxl9Xo2sGo0Eg3ipqfWHzJixXZ4jgeegd6D eNpI+xWdRng1ygV35TW3u8QTo9DWfrZTpZavG4gPL8WQrslQkhSNNjsX7XcPDwYwa/2x h4UXgDeZwKGf7JdNIbWfZzHl/T1+L7gcgQ4uTq6ABe8hThJjvhOlqUYPee4Ro8cFBEnh CBTWV3+cMYZyxu1WoRy0r5X064DxNplYitVyvlGFdLEvlMA+Lp7MLbszHgI2jNM8/r8i kF/A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785607; x=1745390407; 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=UyigMDdjy+TQsTDvukyISJljj/quIMO0up4S2sYIc2S9bhWxsfH+W8e5y69AkaPNMt UGvxzqNnmPXICevNqym6ACVbGngjMFGpEQ8jV9ntIpvFtm4XYzgYgeH0l60mhzBniAT9 HXHSFWOSFFkZyVa1PjcsgWsw326JSMHEMBFofLVHCwvCQMBXk9oovBTxhBzJt+u6TDd3 PzyOgrB+LhpOWIPzRsL+eelfWrFECfaWnd6jcbebonF0SnBJUrimW9xa966Ch0AiqK8i O7wX4tBeFnz4LMAcBRySPmsa4bn/3NfO4KO1+7MsZ68AsBOSy+XhNtP6JN5MWTwls1AR 90Sw== X-Forwarded-Encrypted: i=1; AJvYcCWSKnzxMmiqNHJrwjaqnvM0aQL59A3GFbHoG5waLu/JZvq2HNuFhtB57GTp2mnNX6Go3UxrOYKcSRkP+PU=@vger.kernel.org X-Gm-Message-State: AOJu0YxV4dDRoaAZpiWFAIJ7R88sFvxrTWZ9uuNiu0B96g1vawbhs/eJ Q6CWwRg5GqfR9h71aTxfxWgpW8KRkih6kqxw42XEmYVou6kmnLUdXDwL7RVoAac= X-Gm-Gg: ASbGncvRTtLW0X82s7s3+95K0WW3cFSA3D1R1Hbl0o5ZnO1cZYNRguPllGvT1LhYfcd TTO2twfyBcoIWGc9yd1PNpbwi22E0U5al2+UheC0nc5bywx7Nlscp4ukxFi8S1ibl6CGy/jBhQq 81IxjPEmIZY1IlBL3dAQSTYBkSKMOp0fNYnIM+0BzdEhpg9J1Su9R1TGvOmCX7Y02cUAUBLNKPM LEGBVqHU/Vsj6NYFhDgdNkAchDFtAs/8FcfKPWAnMn5GIJEdUGCjQzhTpAy/52QGm8tRgzVB54+ GWwi1NttxJka2rYYVgBZvw/NDgGPUF/kCN0/ONZGKw== X-Google-Smtp-Source: AGHT+IEjYJIomZsBzT4VP3kt4Qqlp10kJpH2tsSbgblMt/ChgJzb0bcD6XJqL4gtPDZEGDyA54icng== X-Received: by 2002:a17:902:fc86:b0:225:adf8:8634 with SMTP id d9443c01a7336-22c359913a1mr10848965ad.51.1744785606709; Tue, 15 Apr 2025 23:40:06 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73bd22f1259sm9656834b3a.119.2025.04.15.23.40.05 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:06 -0700 (PDT) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=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, Daniel Almeida , linux-kernel@vger.kernel.org Subject: [PATCH V10 04/15] rust: clk: Add helpers for Rust code Date: Wed, 16 Apr 2025 12:09:21 +0530 Message-Id: <97741e1c82feecbd650183c6a52d2e8bbafad79f.1744783509.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 Fri Dec 19 19:07:38 2025 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 B8EF522FE03 for ; Wed, 16 Apr 2025 06:40:11 +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=1744785614; cv=none; b=jDDAusYY7b59TrFqVvTfUcTnDVfu6OlvpoboKq/3HtEMQOhq3EoA9Edw2JYkR+it8LPGFuBc2iB4W3bv1NyuKARNkjDYgpsGGJzFk/dSU2Np0dymgN+OaXwc/wWtvjSzXiQGnaF3zTgHRkuX5E/bthRL1mhx6XiYcdEpcRVuTVE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785614; c=relaxed/simple; bh=OK9LP8IuB4dZ4tNPJ7BqHK7tgUFvTgGIoVzWhWAVPdY=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=Tjpg0lJukJRQF6qQJTOI/62EdvUc4hcjJATJR+KayEd0/qhbIXbuCZzwLy+X2jK4XFw/2cPfdkePcjuCoMZ6bvVPiqb4kw+nUnzu91JSdcxo67k3g5uiQkXNvs6xrYTSB1h/5cz3txS82lwgbgk4zINFBDrbWgODW4RC5qUKehQ= 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=TULXhWD/; 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="TULXhWD/" Received: by mail-pl1-f172.google.com with SMTP id d9443c01a7336-227a8cdd241so75746885ad.3 for ; Tue, 15 Apr 2025 23:40:11 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785611; x=1745390411; 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=JtiIzVJT0XSWQl5nAIRSPSyCufgx9olJIUW0gvaR0zI=; b=TULXhWD/CRn2zolmJ1YU3NrM0E/0iVD12hRBEbyVoA7ynkS5eeJEdkJ26ZStL6Hh5q jQTOL0x+MCiACebhOHgmOW2Fz9RUOVJulpg6c2hcYd+ipTqNxI4UYYT9CFh87x9AAjDu RMxIeE4SUEwvPwT1AdTperQBnY85VqEz9e1wANDfBqDNeEzHgi7KU8yDGTYj25U1DL8l hIk3/l/NgreJ1UDcz1dLNHer44oHgehSMdHeym5l2XFvaicVsEfvB4UXF0oJr1Ltw+Jp pCDiKCD2UDAEyvUyBPLvkrn5JKPLxFvjt42VdnV0pbNfN+TSLQiXlGmjHI9eYrFm63Xi 7U7A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785611; x=1745390411; 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=JtiIzVJT0XSWQl5nAIRSPSyCufgx9olJIUW0gvaR0zI=; b=tOnikMk6FDZY+FOKEeYOgdmsuGCXAXs88Ic6NTMuPlr8DGWRGP83iNe4kIGqFP+XtB 0DA1h5YyiXlO/PlPVi+lzZezp3MNy02yfDua5U3Iz8uF1KeMzqApJcJHdMqSXLVInaiO Y4724eSzhI2jhOH8g9pMtkr/eqXthJxXqvTnfsao7t9pScvLzMqBi0MVQjgeFTRgzXBk eg2KanL6EzkBdzic7j6rCQO7wGOJKO9Ltbuc8nJunpJ8DkGy755Eaq1FwqT24x1o5PnY po6RbnLOlW9G4ICSzAH49zpAvc14SO3nysoQP7xKWWYh77hdfsOcWnB0R4yuL+h1jFaU VKTA== X-Forwarded-Encrypted: i=1; AJvYcCW5xpUVBfoAHx6Q3r13YQ7RkfGMjOaoC4b77NMdVt2XaRnxXvicyj+HB2DXgozPOmg+fE2ubjkuF4plSm0=@vger.kernel.org X-Gm-Message-State: AOJu0YzpLjtvS7Mcb9Wh4dsorWiFgcNs/CthwTH4iCGbBdmnc21klPuf E+ui7hDcAdqV56LuEjrVyiCezQgkRiosVdkYQ75dO7Ebow0mjvVcc4jUfLrifUU= X-Gm-Gg: ASbGncs9sOaUaKmb1lpoU/5kL1qMGAJz63kD2G9JyzKy7Puf7AqX+ai0XHFue+bYv38 pq5M3OCWy7Kao0+0jcc2peA0gA8M0iHahLavFKf9Ja7eg/kZgP6ZMXuEC3jv6RAymIOqOVGkr5p MvrrgB3bP6rHPi04zytVry7gCzpl9gN8tgzjhMRXtbE6cqPupWOpRw3H9SUA7PSMwyxzoaMVAtf ABjNrPWajMYqXUg+KNqH1Lkic5LURQE0y5+yF63dq+Y7oJ36AJOWqXfmwaufTInQ+37AQxy2GC9 f4lBgOSIB+8nynIXRn1kCCRDQVTr6nUDprIjH5vEjg== X-Google-Smtp-Source: AGHT+IEWuhQLaBTU4M/wgFAv18zSV246NrzKwik2ssZOtfWRe58J3TX0f/3yOuGQ17po2sEwvCNH9g== X-Received: by 2002:a17:903:238a:b0:216:644f:bc0e with SMTP id d9443c01a7336-22c3590dcadmr13395765ad.24.1744785610853; Tue, 15 Apr 2025 23:40:10 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c33fe8de8sm6377705ad.248.2025.04.15.23.40.09 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:10 -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, Daniel Almeida , linux-kernel@vger.kernel.org Subject: [PATCH V10 05/15] rust: clk: Add initial abstractions Date: Wed, 16 Apr 2025 12:09:22 +0530 Message-Id: <4207f5bf540de148e1bd31a88dc75eaac1aaf897.1744783509.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 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 | 318 +++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 3 files changed, 321 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..698e05cd41f8 --- /dev/null +++ b/rust/kernel/clk.rs @@ -0,0 +1,318 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Clock abstractions. +//! +//! C header: [`include/linux/clk.h`](srctree/include/linux/clk.h) +//! +//! Reference: + +use crate::{ + device::Device, + error::{from_err_ptr, to_result, Result}, + ffi::c_ulong, + prelude::*, +}; + +use core::{ops::Deref, ptr}; + +/// 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 + } +} + +/// A reference-counted clock. +/// +/// Rust abstraction for the C [`struct clk`]. +/// +/// # Invariants +/// +/// A [`Clk`] instance holds either a pointer to a valid [`struct clk`] cr= eated by the C portion of +/// the kernel or a NULL pointer. +/// +/// Instances of this type are reference-counted. Calling [`Clk::get`] ens= ures that the allocation +/// remains valid for the lifetime of the [`Clk`]. +/// +/// ## Examples +/// +/// The following example demonstrates how to obtain and configure a clock= 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.cl= k_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 point= er. + // + // 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.html#c= .clk_enable + #[inline] + pub fn enable(&self) -> Result { + // SAFETY: By the type invariants, self.as_raw() is a valid argume= nt 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.html#= c.clk_disable + #[inline] + pub fn disable(&self) { + // SAFETY: By the type invariants, self.as_raw() is a valid argume= nt 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.html#= c.clk_prepare + #[inline] + pub fn prepare(&self) -> Result { + // SAFETY: By the type invariants, self.as_raw() is a valid argume= nt 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.htm= l#c.clk_unprepare + #[inline] + pub fn unprepare(&self) { + // SAFETY: By the type invariants, self.as_raw() is a valid argume= nt for [`clk_unprepare`]. + unsafe { bindings::clk_unprepare(self.as_raw()) }; + } + + /// Prepare and enable the clock. + /// + /// Equivalent to calling [`Clk::prepare`] followed by [`Clk::enable`]. + #[inline] + pub fn prepare_enable(&self) -> Result { + // SAFETY: By the type invariants, self.as_raw() is a valid argume= nt 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::unprepar= e`]. + #[inline] + pub fn disable_unprepare(&self) { + // SAFETY: By the type invariants, self.as_raw() is a valid argume= nt 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 argume= nt 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 argume= nt for [`clk_set_rate`]. + to_result(unsafe { bindings::clk_set_rate(self.as_raw(), rate.as_h= z()) }) + } +} + +impl Drop for Clk { + fn drop(&mut self) { + // SAFETY: By the type invariants, self.as_raw() is a valid argume= nt for [`clk_put`]. + unsafe { bindings::clk_put(self.as_raw()) }; + } +} + +/// A reference-counted optional clock. +/// +/// A lightweight wrapper around an optional [`Clk`]. An [`OptionalClk`] r= epresents a [`Clk`] that +/// a driver can function without but may improve performance or enable ad= ditional features when +/// available. +/// +/// # Invariants +/// +/// An [`OptionalClk`] instance encapsulates a [`Clk`] with either a valid= [`struct clk`] or `NULL` +/// pointer. +/// +/// Instances of this type are reference-counted. Calling [`OptionalClk::g= et`] ensures that the +/// allocation remains valid for the lifetime of the [`OptionalClk`]. +/// +/// ## Examples +/// +/// The following example demonstrates how to obtain and configure an opti= onal clock for a device. +/// The code functions correctly whether or not the clock is available. +/// +/// ``` +/// 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 connectio= n 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_optional + 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 dev= ice pointer. + // + // INVARIANT: The reference-count is decremented when [`OptionalCl= k`] 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 + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 75f78f6bfaa6..f4dcfefe94be 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -42,6 +42,8 @@ pub mod block; #[doc(hidden)] pub mod build_assert; +#[cfg(CONFIG_COMMON_CLK)] +pub mod clk; pub mod cpumask; pub mod cred; pub mod device; --=20 2.31.1.272.g89b43f80a514 From nobody Fri Dec 19 19:07:38 2025 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 27D9E22CBF4 for ; Wed, 16 Apr 2025 06:40:14 +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=1744785616; cv=none; b=Y5iNjZ6j2PeLyI+71QzqVc60Or2sRGK/+QLdKh0/0jvyyA59roRndusYnb9caxag4+A+Xs15r4yMeneg2zmYHMsyWYfl+N54Xkwu48bDv8KSsOh9eHwVfZXtehsNzYIp3HdPrRzuHOcHuHPyk64ztcOZ/NC+a+SLXAvlBSi9kRQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785616; c=relaxed/simple; bh=RPs39+G/2/WRBdJP3KwTQnQlR3Lp/kvURzUIgtDgvwA=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=p6IaibS6EwM6lsV1b+vlzKeZPbi0x2NCjyRmO0/7QHyIIDcMNWHFk6bltpgsajYbBqqpZlJxXyVHKvlDY9xdTa2D6OaLqthJhGMr0ET7yvhbHgDGLtApHfsOYBKLtfRsJ22ZO4A9BhzYYDNvw3M+6TO9tG+8ULI1yFsqg8PQwK4= 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=DroUADkf; 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="DroUADkf" Received: by mail-pl1-f181.google.com with SMTP id d9443c01a7336-22c336fcdaaso3104385ad.3 for ; Tue, 15 Apr 2025 23:40:14 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785614; x=1745390414; 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=DroUADkfGP9ENmXbc0Ucy2ZkNEfwC5hYWmEuM/MFlN9DGve7mzqEKrl6YjeKJLGDzQ M7oEKXY8WkeBgKssiS+4MZJhzL+yMh8+IaNGcreuFFMa+78svFmVlCF3QQOzPUvopZw3 n0MX089dXsGmhZDM6prwNGq5XHjcAKt0iAbLGMf74cAQSf8M3K3xkFxqO/32ZVJWTgOS mzE7FmNUj9uJoTJpXn0871RgLg1s5VqOxT7eQVo4ovVJHj1ra7FRrmm4O0HeVPSa7Y1T 6dLZiMgTiqDBWt1cHGRHp3JSRVHl8M3IH8EhYDNQUzRFXFNiYKMmSsDf+ol99rlYbK0S lM6A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785614; x=1745390414; 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=QyswOrKXOq30xLugXcFVp/AaOi/Jap/gxMa2V9wXOM4BqoOoOE6r4/JQc75L7NWwc7 nlqnZZQwdpfRLfaevjnRKtufDt8ww93feLQ8Ki7wsAIP1DhamrtDiunhJEiCdHR3Xzl9 f6u7Bk0k9168HnkjQWS7N1M0hMd6QOmrqdKfVFrSIIFssc++UP/V0HkAquJQMW68qcwt JyZMzGGpQz2LrPSGd4TVMNNsr1QWn5hydSte+idwhjpzESuZbKe7TChDdHuywjqSBSwb KmRjwxCecG5qxkMXj212uOBWLMfOstQlkgPTplQrshJnjgwCLFfI4ePAJsMQ7vhCL6By 96JA== X-Forwarded-Encrypted: i=1; AJvYcCWxYVDzNoazZV/tsX9o0RVonrk/e6kwIJKgdlP1jMJENZT3LsV5BJtY4sFLY8PojgYCeKfC596IwOErqqw=@vger.kernel.org X-Gm-Message-State: AOJu0Yzs+Tn/cIxKH30qO68y7FZViQg4uO44n5+nC6eEh/Z/grHFBlOy X+Iqxh4F0T+o9Bw/JmcCWHvf/shFFWIzy6gCWqQ72aeSpAwWK+bIPSMptr6mrG4= X-Gm-Gg: ASbGncuC+VmWd1c3L4ZTRXxoDxTzGbUUI1Tmcvy/icalbbImwF0bjDoYexwLZ3FDjZf dUcR1uYxSX7t9jd+R76dPB+bZpb1IQ12xlZNnv8S69YSatum1LcWpaJn1oRAXYXpArP5auQVzdT P6eOkVdgMgkimqgloL2HZCqOWgN7D+AkRDgw9AK2bqjj0to2YmJy3hBZLwOSi0/yBkdvoIQfcSo XfbZbu252oxSUWadl/SKIoVgVbrvXLCPaZVmm+/SU7kvWcVb4Bds4aan8kSA4hxcNTGQjDkZ983 M9qJF77IhEUWU2CCjkmSVIp7p3K2pNejBPk6JMZ7zA== X-Google-Smtp-Source: AGHT+IF2Rglo7eHxKgDEgBNsJGaQtvp/oXKgIHcXad7KTacx4TnahZHOzUtBIJLTVG1uvlzQ1gByKw== X-Received: by 2002:a17:903:84f:b0:224:122d:d2de with SMTP id d9443c01a7336-22c358ddb96mr9533055ad.16.1744785614335; Tue, 15 Apr 2025 23:40:14 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c33ef0e83sm6446415ad.35.2025.04.15.23.40.13 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:13 -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 , Anisse Astier , linux-kernel@vger.kernel.org Subject: [PATCH V10 06/15] rust: macros: enable use of hyphens in module names Date: Wed, 16 Apr 2025 12:09:23 +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" From: Anisse Astier Some modules might need naming that contains hyphens "-" to match the auto-probing by name in the platform devices that comes from the device tree. But rust identifiers cannot contain hyphens, so replace the module name by an underscore anywhere we'd use it as an identifier. Signed-off-by: Anisse Astier Reviewed-by: Alice Ryhl [Viresh: Replace "-" with '-', and fix line length checkpatch warnings] Signed-off-by: Viresh Kumar --- rust/macros/module.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/rust/macros/module.rs b/rust/macros/module.rs index a9418fbc9b44..27cc72d474f0 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -185,7 +185,9 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { =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 Fri Dec 19 19:07:38 2025 Received: from mail-pf1-f169.google.com (mail-pf1-f169.google.com [209.85.210.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 45AF4230BDF for ; Wed, 16 Apr 2025 06:40:19 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.169 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785621; cv=none; b=V6WWD6oBPMzLsj04x5EuO3lydmjFnvRSfLkBAEw+WUgSozHWnFKI35zBpg8oEIVDCXis0aWMAOVD6NB9+EJIFjx3DhlcwokY+8TuxloUq1/ioWn1xGVN849mGYRxZTK51dgp3htQQTYZTJ++qvjHhia3vuAWc3w+ejaBAT4Nuak= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785621; c=relaxed/simple; bh=FXN7MqRrTtWb3HqWkB4bVWXQmRagu7xa10NZ2Fw72s8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=eQn5RGbZP+o9m+gVQBU24wJt/f4O6/AtLDyDPtQBxb5hYZq631CeajXRVdtWQUBtFwpkpyAX8ki59g2aGKSXy0kKX4SmsKPl7LF2mxDPNvOTHUiZGU+i8P8B9rT7stK4hcX8uCKfiNZtYYmhDGnsnxsLTAXf+3mXSV0RLncxm8M= 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=Xidwe0V7; arc=none smtp.client-ip=209.85.210.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="Xidwe0V7" Received: by mail-pf1-f169.google.com with SMTP id d2e1a72fcca58-739525d4e12so5895449b3a.3 for ; Tue, 15 Apr 2025 23:40:19 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785618; x=1745390418; 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=8I9rp3cxJf7RfTSYMTTz5L7zI5/p8FTKb0IR9cJ6SsU=; b=Xidwe0V7wfxWDgHsAStGUguKV3Skl485YhNSuWeLrDUvT2Mbu7kFP7XXwkWmc+Zk2I ekQNNSfdFw63oaDlO4RKTkEpIXB9ahHvFulnWhSYE+IioINb/X834cLcQfuPeXGUyV5J jBwHurnbItPYW9B42bsbmiZoE4BpvpvYtK0vzCVLJTnizVBuMleOXUwkh77Tn0pslFg7 N03mjesuZLvqTUNqH5LOCf3Euywf3HQ6ifpmHjCQVjO9PTyQTmKmve4J05XCd/XE6lWy MI9IZ/qzK/wBW1GZDjiO2kerJF5cUc61EDne5KqhncI7Sa0yysHE+Tghy3DER15q1HlX ZCjQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785618; x=1745390418; 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=8I9rp3cxJf7RfTSYMTTz5L7zI5/p8FTKb0IR9cJ6SsU=; b=Kz0tZ4vEqi16idWzWq1qU7eq1XrQN6hGic6MTNNGuIjoLUXQKHTvjIhYFoH3Db0dji sWGxJdWw+CzLNLoyISt4rojbzbz8bhDXX3BIhe56Q8kuzX5BouJMzfZ8xe3rg6eRGLzH gSEBC1rqIlY/GnIjEorKylQ+E8tjIeAn+H+KS2wQOEjksuYHrTEwZGhHb/MJL/7p3oi6 Upvms8sdRxDzJs/TuEb6wvEZFrhTWtFpxPKBNopWYGRdQ9Olv1UQk4DQXd2CX2eEzOIc EqP+Z7sdgAMTLK0qGE3yVgZpJ6YqclRNQMALJZRrAR0asXr4spoY9km/t6HXrFWZC4JE GLfQ== X-Forwarded-Encrypted: i=1; AJvYcCVXBqFYF9Qmd0p9qFQp+EI95DfFcJFtAF/AtgU0wzp4h+7ZjT8QoeUT+5aFEmZ64sH3pv1bAPWE6tbUYDg=@vger.kernel.org X-Gm-Message-State: AOJu0YzmOemQpHXognG6BxVSuekuUYRb/wp1Jstqyz7pERFVl/mekVjg BdKpnlB7rAGtV8BNESuEjbULIdoLhgLwjWY3lSQskEYEdiDf5vbhFzpCMWqfnmE= X-Gm-Gg: ASbGncu1JORLFrlAfL3VWhooiT2UE4vS5cSZSLkNPitrPizP0aOx4zknqnlKywB59Ri 1qF5Bx5r7e6LL4kptoBpqhBvq9odpDHXE4JdMyZ0LoSqTgyn+8genn2D/r99LTOIkQUjKIgtP/9 fr4A48fwlsGbhGPHDmgFKuYviPCupm4wDvOJwPZ/BW9UYFbeQlQsgB8xrUjYuqcNtdhF53oPiUg ifvBMRyKc8osfgG7NdS+lxiEhthVxsXiyHv9Zo5Sj/6dV11c1K+OpOEuRrrg0afpIL5zNkps+hQ ygLLsL4dbNHsJ43uLHT+qjTb2ZAkWFh1YQprGWVYRg== X-Google-Smtp-Source: AGHT+IF0ex/iD+sUrbitNrvOanXTZ6pYvDsy9aAY8JPu8xZYMYJcxxzu0L7Lfm7GAzJbTIuYn066Rw== X-Received: by 2002:a05:6a20:e68f:b0:1ee:c8e7:203c with SMTP id adf61e73a8af0-203b3eea03dmr933373637.24.1744785618538; Tue, 15 Apr 2025 23:40:18 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id 41be03b00d2f7-b0b2221bb77sm582080a12.71.2025.04.15.23.40.17 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:18 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 07/15] rust: cpu: Add from_cpu() Date: Wed, 16 Apr 2025 12:09:24 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This 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 f4dcfefe94be..db372f806875 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -44,6 +44,7 @@ pub mod build_assert; #[cfg(CONFIG_COMMON_CLK)] pub mod clk; +pub mod cpu; pub mod cpumask; pub mod cred; pub mod device; --=20 2.31.1.272.g89b43f80a514 From nobody Fri Dec 19 19:07:38 2025 Received: from mail-pf1-f170.google.com (mail-pf1-f170.google.com [209.85.210.170]) (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 93AC62343C0 for ; Wed, 16 Apr 2025 06:40:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.210.170 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785626; cv=none; b=MG4nNtnwQbXFEwhIY1tyBOyHawvq0yGWRypvu/ec1Y/Jq3swvXXJxl/sYjheWE1MNifZv8i0mYa4kD2gfNPOxyEYPFrQX4O8AAbSYkz8d1qk4EwTCRgqxmvmOtRnWxE0SbgBDOmGlHqp1T1Vv9v7aOL5PDrrJReukTHV5l6wJhk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785626; c=relaxed/simple; bh=I1t7iU9jhwvLXBuU8hfiaosgzTZnx2xZVO9nWUc6iC4=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=mBAd4642tGLb6jiu9fu3b5BWq1/rAhAW7jpB6pt6fgXuKYRffAX5rEDgvhs6KozUGt1TQJLaz2peL83Iq42vSYyp4Y7TTRCqGPtGpdpChmLcpijcyOZJdDBnyXCn6UYitTrSyg5GNETUSRsD5oKz3BZguWwtxefBwxXWYhJI72U= 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=uSGEEN+T; arc=none smtp.client-ip=209.85.210.170 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="uSGEEN+T" Received: by mail-pf1-f170.google.com with SMTP id d2e1a72fcca58-736b350a22cso5514186b3a.1 for ; Tue, 15 Apr 2025 23:40:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785623; x=1745390423; 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=1f8927gH4OXWVNjPTvv3LzcJ2zClxOXj6x0cZ+ChIL0=; b=uSGEEN+TsE3vTW9kBm/ZyxYarct5rou+SYBJiNFs40Ay0GhxmHpojJVj5FJvpmV3w3 GLH55aJDA598pNDLtkIRZA/QgNj7OFQu8qzoA1Qjc4nvbSnBRkWI40+oe+GOMpxhUQBH xdPvdjyYdyX7eFzyW6hkkPr3D4UIAZvE4xyu1Dv1/eopnCPb5mvF+Od1RPXhEnx/JcLT 2qLozOV65M0nkAH4gl2wsj/MCqg+NnB+UX4+7cTBCOD++XNvH0+exNU1Q3s2o7aigK2X a9gEDDIVTBZ9zmSYBt+fNHZL/RLHeQErW3j8SJ6xpGwjQoO2cpOjq7xrZQwJ7Aga8C3y zZmg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785623; x=1745390423; 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=1f8927gH4OXWVNjPTvv3LzcJ2zClxOXj6x0cZ+ChIL0=; b=UlmeY4+TsZlOP+lGoBVKW3T4gXt7PgbxrzPzGG0kUlN55K1/zzIpUrAl47xRyQC2LX pPytmx5XcHT1BHynn0+ykdykoCOSwNVimVe6yfKrL/yZSvqU9GniKyCgqrGOvlh8JD6z PDayzv6+xqbmGo4NKQfSUGclW7B5dsfzpOY5KHbYrcZAPWluomKf+C+HQ5WwXWlzZqY/ zmBzDz7V6Q7L6UXhCodYNviZC9Y0oOqsurFEi+vi5Ag+G8qfTLV0sDVhotVNragL4LhL z6hdTYOjiG8eojSJdfIJY1E1V281TSg/jR5HDhKpqHrFEzMAP8H9oH7S9k1RRtqLUDQO QE3A== X-Forwarded-Encrypted: i=1; AJvYcCXGcle+puBoCVFJ/RtZVF6VFBBFGT2/dkf1R/hoKv+eN2dU/WgNHrOgfFuELAhFgC/eOdt1wn5oEO9RWDs=@vger.kernel.org X-Gm-Message-State: AOJu0Yxdx4tprL+Qc3EQaYDAZ08ftuyKAtZa7BA1/idPY34WUjaLJZoV w/XRrFAjAq1hg6q5LYS9kjQyLBYarD3NiaaSsUvC0NeXY+MpdqRtnPIsCuEJvVo= X-Gm-Gg: ASbGncvL716OVqzYPKy1LaJSmvo2JUeaMMJxtqxRaNZLCs6mOWs7Q4MIRJyX7zAMXzh 24km6P/dAhCJD4u7vR/PMGJAZjGr3GF850gX/uMgVc6/gK3qoXwBfiih2WsXOAQsZ5aj5kA2vRA w0Yf2pXDTDArzThb4MqzKX9GMsVnCTIaXgNhEFQq633FH8Za3X3rkf+/O3ZGcyTaUCQNT0Ggs5X xX3qnnf4lIIdwGOJM7mErgCjq7wsLGZt4RiVw3wGxNwrW7Qw/qXR8Awxb07xPgk+kjcEj+SIZxx sqVzDIOegCSk5I57y8EBK1svFMTYRa9OemvpBDghxA== X-Google-Smtp-Source: AGHT+IE5rdw3FqJb3eH2eqckhW2GScLx0laJ//RkuqA0Y3UNttepQcIgCsE41Shc841uEd672M84gw== X-Received: by 2002:a17:90b:520a:b0:2fe:b907:3b05 with SMTP id 98e67ed59e1d1-3086416f4dbmr1024536a91.29.1744785622846; Tue, 15 Apr 2025 23:40:22 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c33fe6894sm6396445ad.215.2025.04.15.23.40.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:22 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 08/15] rust: opp: Add initial abstractions for OPP framework Date: Wed, 16 Apr 2025 12:09:25 +0530 Message-Id: <18bf0ffd9c0ea525d28235378fc15dbe4d496d97.1744783509.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 db372f806875..11d333c8c673 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -68,6 +68,8 @@ #[cfg(CONFIG_NET)] pub mod net; pub mod of; +#[cfg(CONFIG_PM_OPP)] +pub mod opp; pub mod page; #[cfg(CONFIG_PCI)] pub mod pci; diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs new file mode 100644 index 000000000000..ec4f67c8aab4 --- /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 bound= aries. +unsafe impl Send for OPP {} + +// SAFETY: It is okay to access [`OPP`] through shared references from oth= er threads because we're +// either accessing properties that don't change or that are properly sync= hronised by C code. +unsafe impl Sync for OPP {} + +// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted. +unsafe impl AlwaysRefCounted for OPP { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference means that the 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 Fri Dec 19 19:07:38 2025 Received: from mail-pl1-f176.google.com (mail-pl1-f176.google.com [209.85.214.176]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8DB8522CBFE for ; Wed, 16 Apr 2025 06:40:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.176 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785629; cv=none; b=V2Hy/xcZnqLZnOId10NymrbuXimX316bS7QBnOQ2FYZXM3wpu3vcfRTHMO8W8IXhzkxvYLyeo7Lf9AIW4nRyO9ekeXlOvB3Wjt4aOlKldCPgbYO1jHx1d0NUd2VPDVI4tR6ULk6VoixUmBoGdQcZB5ZkgC+W6FOXEsqxUzcmtO4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785629; c=relaxed/simple; bh=wX73VZYHmPeMIrJ9k0YbY3LA3cWnBUH+KwsxFLck6gk=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=LmYhvZsh2j2ubc8WPZoL7/2aGOG3pHeP7RBZZl30OvBGKJAr0COtlITcH+bvxKppINpMjVqz/Z8wbGCP97Cw327uCPq9ns/7TgBWWjsVlt8x7MboS3tmtun00H7VuC3sDU2F8jxfSY4VG8YcAnCsqgOV3bA9skmYYmTDvYJE/Go= 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=NE+58O49; arc=none smtp.client-ip=209.85.214.176 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="NE+58O49" Received: by mail-pl1-f176.google.com with SMTP id d9443c01a7336-227d6b530d8so63200455ad.3 for ; Tue, 15 Apr 2025 23:40:27 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785627; x=1745390427; 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=+S2sEL5meSUB9+YQljONr3D0FsAJqb7ubVG6yrKMgHo=; b=NE+58O49FuwsIWF5lV5vdMcOQ2ApVd2VqJacnc3GijIcifvXEpPcKi8kuIVRUvJnD9 0YjpIbglaQMbLqUewKhqIxSa3fHTwHXq9ETrB5ueJKlUObsZoCQsZ4ALfUgI9iZwKlG5 tp71AIkwrBhOuEocFdlnOd0NozrO8P11PfQ88KtXj706yQormBQ6ZMJBabGwAIk86SRw UCK7bYs8yAvJtcooDgAXBK0gSuX4ZzjS6zZW4kr0C7yFTE1FhCVqkT7RgnLaEkUmve+D zQyW+Ici4KOrmGuvR0lJGV2kqoGyt7h+o1Ed9ashsLJ9jB0JLm2u35EsfAtq1XAQ1frY JWAg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785627; x=1745390427; 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=+S2sEL5meSUB9+YQljONr3D0FsAJqb7ubVG6yrKMgHo=; b=chkOkI7v38WNjXdTOdC6HNhG32Ka358W6bMhNIxYROaLDMCgkAHbY7te512e4jFhE4 zVVtJ/P7wGZFADaseVLsjl3E/Ire2kuGFwlneQ5+JpC8xF5U9RwASyR6EoumtFSL5kUa SXIjYC/7P2BZPHJWKjERLzqEttBPRrInxaYYkzM1pY6T09OsAz28WfZrHeTzGUx2quMV WUD5NTmoaGRBLGcHN8MXPr9phlnH2wx4ghTb2sVZTro9ZFJetbsfvpdSZoOPwfKNEGY0 L7d2MFo6OixH9dDT7wFGIxRxZq20Xcs7bI1DMBYV2sy6GhHf+C8D9l6sb9bmyDaB9Bve w4+g== X-Forwarded-Encrypted: i=1; AJvYcCVnBYJvXdGAPWrA+9uW80h51+xIRwf0RN2ySbOQQp91AUhdWtjRSbE63/iRabGbGQ50IP/d1kTbtoBkbnA=@vger.kernel.org X-Gm-Message-State: AOJu0YyOPvj1WbAkhojrV+2fZp/5RI1osiQbUsXU8uN31wMhO3z9NAik vBtPEdTtOQokosez9TJ7jmB6zecwzA2U6q12Dim/vknoMCOqy/Y4wWMb6Dcig0E= X-Gm-Gg: ASbGncugTnAyRtYOX0PTqFaQkqn1++KN0UUrfIK7wPp2ACiXtujSK4DhqdMiyScLhWk tq+1CowL2xye82Ays0mYxRqGDby0KuQOF56LzAza4LYuyLGPVrU6yjGc6E6SIFq34fcU4Fbq/1w +5PiIMehiZ1m0q4G9SUhAQvX8xnRsTgz8Y8WZL5+XBCuAZi5hrdZl/nOHbrlmYwOpICRz/8EZMT SlbfGLGiTwMmTIekxiV3sjtQOFbXSsAPGjwBSvxRYcG2wgNOd3qIUkS7Enu9gBtCf5+5vg5LiPg jiBQWScBp8bbaR+v+DwLUyxD5CCePZ8m/50/B54I3Qt/fb30hcrC X-Google-Smtp-Source: AGHT+IEpDWc7qWL9wYy3dPe93hrwkiv4ulv+62ZSCaFTby+C1vglRJZGtIhXDSWvfozhxZ4xpY80TQ== X-Received: by 2002:a17:903:2a85:b0:221:7eae:163b with SMTP id d9443c01a7336-22c359a2402mr12147645ad.46.1744785626802; Tue, 15 Apr 2025 23:40:26 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c33f1d118sm6444095ad.86.2025.04.15.23.40.25 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:26 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 09/15] rust: opp: Add abstractions for the OPP table Date: Wed, 16 Apr 2025 12:09:26 +0530 Message-Id: <1fcad3f3da1e516293a7df65b3ffdd037a33831a.1744783509.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 Rust abstractions for `struct opp_table`, enabling access to OPP tables from Rust. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 485 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 484 insertions(+), 1 deletion(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index ec4f67c8aab4..389bcd5e5711 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,467 @@ 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, + em: bool, + of: bool, + cpus: Option, +} + +// SAFETY: It is okay to send ownership of [`Table`] across thread boundar= ies. +unsafe impl Send for Table {} + +// SAFETY: It is okay to access [`Table`] through shared references from o= ther threads because +// we're either accessing properties that don't change or that are properl= y 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 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 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 +646,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 Fri Dec 19 19:07:38 2025 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 59DF323815F for ; Wed, 16 Apr 2025 06:40:31 +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=1744785634; cv=none; b=sPOdAvjk8htedoAE6Cu5Enr4pfj2qEcOCPKEfiqw7mR2kmlwl/1AHby3Fu8iE8oSgFZeTJcHfBLPuJI759+dPe95vYpLvLaEWczaaSMxZsHGPYsZoeMokJ+NYsYvNE2Y2+E2MeInE2P3Xt3WIkHtyjdgQAn05w3R4R4cWy0WCC8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785634; c=relaxed/simple; bh=T50Ga95kSn+9NtxiOs6JrtIn7NkL2WVYkANiJ5yZFb0=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=QQg3yPdvl9yV/htWiP59KTftdlGNAIuLK6I7lFf6Bb+UhQNz87wF4G9HQeLdPC2jMcyBQ1bdrn20EDEN8m0zlbz3sXrRCHydeNlICcB07hYET8dtGQjcY4vJ9fZpn+q5KxA1PoCPliV8xhjYAxDMikaA0NLp3YHbPnuhLF6MXPc= 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=xNVH6a4w; 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="xNVH6a4w" Received: by mail-pf1-f177.google.com with SMTP id d2e1a72fcca58-736aaeed234so5198730b3a.0 for ; Tue, 15 Apr 2025 23:40:31 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785631; x=1745390431; 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=s+K/gBIYl2Kr7ijqVEgdSrVb5Amle+vHAau4JDWU5xs=; b=xNVH6a4weL91mZYCgYZ423kJhRiWa9AFM3IiXQ4g3mw870gBcE2js+1mK5lkd/tR3z b4a60Aodx+OyUd2jnle+eYDOpveQZlTI37XhiARMWKKuigwlrtd4JHeWeWhStHUQUgK/ RRKOR7FrA/3VhADewF3RnduAZGalI/9q86I/YADODK8BX1nrxFClIKZQfOll8O0Dy9BW sj3phAoUFjMozzSkc+7I84gf/8F2wvxIQ2pcx5ylKqCfzV4IEDODKgS0pgqNvo282VYB Nij9uhf7zgikUiuhF1CMXSCFipTEmq20WYiD43aT5w69PtryihgYm1OjRnk0hvYDMkMB UKhg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785631; x=1745390431; 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=s+K/gBIYl2Kr7ijqVEgdSrVb5Amle+vHAau4JDWU5xs=; b=kkwFyzEtZCKhnZi0R6UG9OThiwebLoaWFSiIKa3arn0vM80wmZCr3OE4NXp7suGCVC Dwd5axsHaehHYrcuFNXTp0dBIUmQ2KNRvra72KUfSIJY1XA+o82V+yjKceAvU4r3TEBL PUr+SYvOBzDYRrLqoFk03VFdhOlNhCRVU2ASen3Cigd75Yz0z2BM5yNXmDRFxUjqeFWE /rPLBiwEY8Dm/vb1E4aNMp0Nvqw2pXK3l3jTUgicwU0mFNa6o4PDJdui2ys/sj3cqj1d p7f8WwqRf/MvohqUDgWMk4hmaRLqwbSuwqb0UWzGF79AhH0tK1QKPwG5bmL2/SfHiSUV xXBQ== X-Forwarded-Encrypted: i=1; AJvYcCUX/uhvXiiCzO4q7BmRd7q/Zi8UyJQ4gDlzJaQMljrJUbrgUeZ+ouFUQpbbx6RWTLv7eBtv2weweSOqa44=@vger.kernel.org X-Gm-Message-State: AOJu0YxBbcQgv34Uq7FFLkAl9xec9vIxgm3RrUo7dW44RHdIFIIod+Pk /1cOSxFEJZ5KZQN2ljmg5xOnc0/zPwitJKVj8tF1f0Og9/y++tuhTw39dy4TByg= X-Gm-Gg: ASbGncsn5GiahfZuEmBIU86QEOO4ccRXSm8ao/k3mujra5pG4gOnFmoqwkqVyeS9B4f Adr8UU05ACJWUEDc0ijWGr9s4iV3u4OZsbjkvb02xwUnpd4SEeaNLnsI3jx/l+C7XtqrumBBkPl Wb29TB54uC5YdQTGQl2qB+8JsnddVwCl0+Y7z0CebaWljJ3UexCLAaykvAe4A3fyMI2me1U6SXe X9nPmffmHBue00WVI25gpMjit6nJ8Y/W26gzp68cIwGilutmROWZL+M4v17xqCfAJXOYbW2o+v5 /QUKh1T2Mo6uTGNhEFOWj/ReIDl3TgXcu7xOVbf+AQ== X-Google-Smtp-Source: AGHT+IEzC8KIse29zHey+MXXD+WYDXgIA7jNlSka52BGWcK+5jGFkrn13++zmHt/b/3VTNNBxf0hrQ== X-Received: by 2002:a05:6a00:1d81:b0:736:34ca:dee2 with SMTP id d2e1a72fcca58-73c266b4d3cmr1216072b3a.4.1744785630534; Tue, 15 Apr 2025 23:40:30 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73bd2333841sm9682083b3a.160.2025.04.15.23.40.29 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:30 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 10/15] rust: opp: Add abstractions for the configuration options Date: Wed, 16 Apr 2025 12:09:27 +0530 Message-Id: <25a286667b785734f534ba13fefc693e06e8b8ef.1744783509.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 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 389bcd5e5711..44e11808793a 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 Fri Dec 19 19:07:38 2025 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 EF2F222D792 for ; Wed, 16 Apr 2025 06:40:35 +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=1744785638; cv=none; b=LBDaxtxMGqus9CFs+NkHLw7n9k1scjasFDe6hC1IaLULtcNbiylNGj6VdR08SHLQcApq/MS6cY4LctyJ2e/cYaeH6lH4vM8T68LXh/GZV3XzovnIhBAbslUb43nN7WZc+q20RpWdNNiVry3tnUyuEp/ILeqzEjPfNjS+p1pisbc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785638; c=relaxed/simple; bh=ziZgMQLsFplAbFdyhmmL3J7VdGL8acvZSZ5DzxK0wlU=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=EgzGIXywpxwzSMVtmQ1vRPCG8urg1Ng1lCUWa5hgy+HFDh7R52FYHNwJhYBJAOJt0QKDM3XTyzNWoVvxZbEXu2lsp4dDcJB0D6QFHBdxU9uPcoFY4oz/t4NI8KFipr1orfO/NT0psUsrx1dsuM9F3g6KZrzDe8rNYa1iuOm+NtI= 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=SWgHoD2X; 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="SWgHoD2X" Received: by mail-pf1-f173.google.com with SMTP id d2e1a72fcca58-73712952e1cso6139865b3a.1 for ; Tue, 15 Apr 2025 23:40:35 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785635; x=1745390435; 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=DW1qs6atmS8GbQWfQI5DosVxmJVfV2TCrrT1uWb7BkM=; b=SWgHoD2Xa6Z7f28gRvXoZJlbM1O1UfIcv73uSP9L/b6z3FapP1GK5N/NDaqU76qczY 9BDvSD80fEXH8OFCx224A9raVdF6XloMbysjLYMyfc76Oy4zjaQW6HdIZuBj74PNDauz AAmwcoSAXRO2B0Qf4ccEf9IJuzIoPpSSXKIyT+Lj1wRbSfLKgheakQ145o5i1nooVX8c KA13gaZJcnoSwlVnXg3RNM6r1MUcrpwHIk+pVRBtAl2+032rLsuIrvBhPeOzYIQU69sj Br85u5BLpDA33Q2OegaZB8DwE8BnxwzrhQtYbbijwnqH9OGQafwywdatpUTMq03i6R6+ bS4w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785635; x=1745390435; 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=DW1qs6atmS8GbQWfQI5DosVxmJVfV2TCrrT1uWb7BkM=; b=FwHqQSdhomDdStzik+qZKkcDLOKBXhbdMKcSNDzDxa/iZRFWcuheWH/r8FE0Q/axsy 8IZEb97sApZXqTeawVn92SsW/u/OYVjExRnw6lhxNK7XaL/0RiCVKIxcT5YTM2ReMHOX yRjkUYm+Qdx1NlheSEn+vLF5oTBChyD6a87BV1Nkc0LBH7f7Q+TRJh9QUvQ7wpwgB6U2 t25sBX1GV+7q2frHAOXze5fb0Li+x7WJL2Zs0KQGiQf3KH43MgB4lFmQhS7cPU6FqoIn pxcIkGlxWII2bIjOLQjnVGEi7An5h6tMp3uaQTtvtAjqGkT9IW8F8ILcZ7RMTBLBPLN+ 7wrg== X-Forwarded-Encrypted: i=1; AJvYcCV0MWPqsRLYmAGQBIYKsyPeXyqAhR80VLXuV9QEh9E96m2d7w+iDsW2LXHAF1osJ7XUIMqskCNLvlHeM3k=@vger.kernel.org X-Gm-Message-State: AOJu0Yw0qDRyZPnngwZFZ38uFCZMsJJNy4RoJ19VFtxAIjzhLAFrqtrB 2K5Qyj8D38IlpaMUWqPa44yt6uWqZcaAoAP9RPYQ+P0XY9IMCGjal5Q0q2pCbkU= X-Gm-Gg: ASbGncvXO9kCX/Jx3Z85QFoa5BaybmJkVluwc5KaHPyqAXbV7imiFTxvCVWeaQLmRrT xTaalNT3HA+wBb/eXRTg32dD1QZn2teODUSDm8ep6I7dH+dNw1L9vsccZ4kCEGjYXeAv0nTmKCJ FfeMPX6ZtwxkWhQwT9+5luKMNTffsP4yr9UBjYDbpUI+v52Tm3CKq16VWEN1M6QNao3S2qaNazq hIxpZK4QHyT0LSAoYbvDCyzM4UL/m37tD/i1IWNRKif5+QaHCRmfGaHALZ7NEdnS2qYwVsJ2ufa vnWLGfjxazNXBYvJLjgsavEjd9pYIWhJgyRIO4Q9vQ== X-Google-Smtp-Source: AGHT+IGivDluYSNRbYVAREJ0mxGQVA4d18wcvk2K0U1bpJcwJQn6cow74PXYi6k7LWWUakBsB3u0kA== X-Received: by 2002:a05:6a21:9183:b0:1f5:9098:e42e with SMTP id adf61e73a8af0-203b3e4fe98mr929777637.7.1744785635125; Tue, 15 Apr 2025 23:40:35 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73bd2198958sm9647372b3a.30.2025.04.15.23.40.34 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:34 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 11/15] rust: cpufreq: Add initial abstractions for cpufreq framework Date: Wed, 16 Apr 2025 12:09:28 +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 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 | 348 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 6 files changed, 363 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..d9face425d47 --- /dev/null +++ b/rust/kernel/cpufreq.rs @@ -0,0 +1,348 @@ +// 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::{ + error::{code::*, to_result, Result}, + ffi::c_ulong, + prelude::*, +}; + +use core::{ + 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()) }) + } +} + +/// 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; +/// +/// fn show_freq(policy: &Policy) { +/// let table =3D policy.freq_table().unwrap(); +/// +/// // SAFETY: The index values passed are correct. +/// unsafe { +/// pr_info!("The frequency at index 0 is: {:?}\n", table.freq(0).= unwrap()); +/// pr_info!("The flags at index 0 is: {}\n", table.flags(0)); +/// pr_info!("The data at index 0 is: {}\n", table.data(0)); +/// } +/// } +/// ``` +#[allow(dead_code)] +#[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`]. + /// + /// # Safety + /// + /// The caller must ensure that `index` corresponds to a valid table e= ntry. + #[inline] + pub unsafe fn freq(&self, index: usize) -> Result { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid and `index` is + // guaranteed to be valid by the safety requirements of the functi= on. + Ok(Hertz::from_khz(unsafe { + (*self.as_raw().add(index)).frequency.try_into()? + })) + } + + /// Returns flags at `index` in the [`Table`]. + /// + /// # Safety + /// + /// The caller must ensure that `index` corresponds to a valid table e= ntry. + #[inline] + pub unsafe fn flags(&self, index: usize) -> u32 { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid and `index` is + // guaranteed to be valid by the safety requirements of the functi= on. + unsafe { (*self.as_raw().add(index)).flags } + } + + /// Returns data at `index` in the [`Table`]. + /// + /// # Safety + /// + /// The caller must ensure that `index` corresponds to a valid table e= ntry. + #[inline] + pub unsafe fn data(&self, index: usize) -> u32 { + // SAFETY: By the type invariant, the pointer stored in `self` is = valid and `index` is + // guaranteed to be valid by the safety requirements of the functi= on. + unsafe { (*self.as_raw().add(index)).driver_data } + } +} + +/// CPU frequency table owned and pinned in memory, created from a [`Table= Builder`]. +pub struct TableBox { + #[allow(dead_code)] + 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; +/// 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: The index values passed are correct. +/// unsafe { +/// assert_eq!(table.freq(0), Ok(Hertz::from_mhz(700))); +/// assert_eq!(table.flags(0), 0); +/// assert_eq!(table.data(0), 1); +/// +/// assert_eq!(table.freq(2), Ok(Hertz::from_mhz(900))); +/// assert_eq!(table.flags(2), 4); +/// assert_eq!(table.data(2), 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 11d333c8c673..871fcdc09b35 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -45,6 +45,8 @@ #[cfg(CONFIG_COMMON_CLK)] 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 Fri Dec 19 19:07:38 2025 Received: from mail-pl1-f170.google.com (mail-pl1-f170.google.com [209.85.214.170]) (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 D0C1A23AE8D for ; Wed, 16 Apr 2025 06:40:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.170 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785642; cv=none; b=Ry6gAlH0KtXA5DGwOzGgKk9PY8pkGXbFSbZFbqq3MKCSxI+GQH2FkYLVbf/hEEHOL5lfe4gvlgC4swjOfgXgLTUh7XCQr4R3pK7Qj5itfiqd+ldeBSwBTrTWDOtUkE1XM1OXgi2RGJvNKJsUsV4b/tuqc8UqcNO2fYkZHB5bOPU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785642; c=relaxed/simple; bh=G0pmXNLUXAb3eCePQJZ5QhL56ydxt1gjfb8YB65k1eU=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=ju9bGY2bi70VPzKQBHeiOWXL5YnCyLuuPXdvSbQt9fGCWasPsdbJT9krY1ep7rXLllbpgzgoZNSKnx2bPE/MhBdNLzqv9sjfLhzluQHg6aOhtTcXpdWT2ImZokc+qkeoeHnqxyvT2M1YvaiStYeSW3hTZ510GKae9tMuDSiSZtY= 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=EFVXURQk; arc=none smtp.client-ip=209.85.214.170 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="EFVXURQk" Received: by mail-pl1-f170.google.com with SMTP id d9443c01a7336-22c33ac23edso3688265ad.0 for ; Tue, 15 Apr 2025 23:40:39 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785639; x=1745390439; 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=5uv8QgainGGqFWtfVNXtqhQ8aLq7TNgS+wvUJbfZwLM=; b=EFVXURQkdBpipKrj9UZzNgReYsPLbZrVq1w7sIfE0i7wILQt+9RqE4A2sqyCduMFEG amBYWLl/zRHxSk03hp3sr/1SxdG192dW5DNLAa7+murfIB+4nE+C/s0o4qcBHUAV2s8I z6rJCOQbmtjujwJPWVBiZS1wFjSbG6MTJCPouX5UBAgScZnR3/umsys7dyyjRVMHsqEO WkFHOCtMjFVlFlZ9ymXst08SZ/gpK810u0c3FV9+b3uQi/bdZta+gG0pF+Qm88aXfbSH R7GfKtdMeI+SdQ5oPjEv/vMIEk74vW8wP7wxnqkN3L1kYdU943ebNZBjlVNuY8YOVfcg R+1w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785639; x=1745390439; 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=5uv8QgainGGqFWtfVNXtqhQ8aLq7TNgS+wvUJbfZwLM=; b=I2dyI/TtO9UktgUEloLMIHaQX013/nEoFbQx/8WdoT8A1pg6WzmEPfaUo1JP+2wSd4 I6DphTYKLyXwKiW5P2MHtzyfOWp39b4GGentZ2RJxjHaCA7UAchA1W9nWdtCLCsVk/zd iPE+9VXUNdh6sQFZ0rIkVcrOQ0m3kTtZvK+KKk7bHhP3VCv9/O/uDSyhLC54kOeMHb3V Q7azdUbmYU8fBwoK0f+ndBUj0VzvadCKEruRlCzRezGHFoU6HyTOsckyNId1mSeVEiuS glKVq4SuGFcYgYnSIg7UxInI8DITRqqPBsq/aWm27/d4yA8nunMYX3rpU7uftlKDJquS FZAA== X-Forwarded-Encrypted: i=1; AJvYcCUo78VYGMvhjGpNMFVF+5Cao3jHhWkeFYwVgD5rLRETdMRS1jZMvA81GPtXi6zJ7sZzSnYoNBd6GiUzjm8=@vger.kernel.org X-Gm-Message-State: AOJu0Yzqv6wN1JeteCX2BikPpYQlkf4J2ec6feJDFuUyMnie3014Wu+e crnjh5Y+t5g8A89xmZZc/MGZOVPNLIG8tAkdEpW1wvKC6+PBCdtd+CV3L0u298I= X-Gm-Gg: ASbGncv40xqf2Vp9cpZDp62nLcPobcMAb6EsAtRUGbf3JRdK669j2g64Gmc4G1kySSm tdNnEnGe0x6R+lEd9CLy869Rwad6fHzgX43HzD5NwX4uyXwA9WStcuJdizbiclHz1qyOBzAEcPt J5wcrL4Wl2qOd0x1eBtVWy45wlpSTQPTarBcrQaP8erI2461R6WzXUjDJilR89lFzMAyuT92p+9 oefBQps0osRMbdzn6voPzEX8LwsEpIhYKy8nb02IrtLgs+OuN6D463iTaDXdMgsy3iuqFSzmBMH K5gUv/rgLvnZ2yofU8NBFpCsW62TI4RU+Jbihd6lpw== X-Google-Smtp-Source: AGHT+IGHJ+14d4c94eNRvjN1xaiY12FX4RhJFywwuHYvJRpGkssRqu3ulNzKFKTVxkvjUfnSKiNxfw== X-Received: by 2002:a17:903:238a:b0:224:2207:5130 with SMTP id d9443c01a7336-22c35983cccmr9959655ad.45.1744785639023; Tue, 15 Apr 2025 23:40:39 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c33f1cd87sm6463245ad.73.2025.04.15.23.40.38 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:38 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 12/15] rust: cpufreq: Extend abstractions for policy and driver ops Date: Wed, 16 Apr 2025 12:09:29 +0530 Message-Id: <7a859b2da97e44a7b8e9d694bb7ffdd34e886cdc.1744783509.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 | 457 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 456 insertions(+), 1 deletion(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index d9face425d47..fd605921add4 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -9,15 +9,24 @@ //! Reference: =20 use crate::{ - error::{code::*, to_result, Result}, + clk::{Clk, Hertz}, + cpumask, + device::Device, + error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR= }, ffi::c_ulong, prelude::*, + types::ForeignOwnable, + types::Opaque, }; =20 use core::{ + ops::{Deref, DerefMut}, pin::Pin, + ptr, }; =20 +use macros::vtable; + /// Default transition latency value in nanoseconds. pub const ETERNAL_LATENCY_NS: u32 =3D bindings::CPUFREQ_ETERNAL as u32; =20 @@ -346,3 +355,449 @@ pub fn to_table(mut self) -> Result { TableBox::new(self.entries) } } + +/// CPU frequency policy. +/// +/// Rust abstraction for the C `struct cpufreq_policy`. +/// +/// # Invariants +/// +/// A [`Policy`] instance always corresponds to a valid C `struct cpufreq_= policy`. +/// +/// The callers must ensure that the `struct cpufreq_policy` is valid for = access and remains valid +/// for the lifetime of the returned reference. +/// +/// ## Examples +/// +/// The following example demonstrates how to create a CPU frequency table. +/// +/// ``` +/// use kernel::cpufreq::{ETERNAL_LATENCY_NS, Policy}; +/// +/// fn update_policy(policy: &mut Policy) { +/// policy +/// .set_dvfs_possible_from_any_cpu(true) +/// .set_fast_switch_possible(true) +/// .set_transition_latency_ns(ETERNAL_LATENCY_NS); +/// +/// pr_info!("The policy details are: {:?}\n", (policy.cpu(), policy.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. + 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 wra= pper. + // + // # 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 specific= CPU, providing safe +// access to the underlying `cpufreq_policy` and ensuring proper cleanup w= hen 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: u32) -> 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: u32) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `target_intermediate` callback. + fn target_intermediate(_policy: &mut Policy, _index: u32) -> Result<()= > { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `get` callback. + fn get(_policy: &mut Policy) -> Result { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `update_limits` callback. + fn update_limits(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `bios_limit` callback. + fn bios_limit(_policy: &mut Policy, _limit: &mut u32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `set_boost` callback. + fn set_boost(_policy: &mut Policy, _state: i32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Driver's `register_em` callback. + fn register_em(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } +} --=20 2.31.1.272.g89b43f80a514 From nobody Fri Dec 19 19:07:38 2025 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 81BF822AE5D for ; Wed, 16 Apr 2025 06:40:43 +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=1744785645; cv=none; b=VY5gFCeXClUAat+eTqOPWSH917bPQXVRna+MXN1usIVwcX+fyVn6kZcQBg6a27ZuZPv5cXqbF5VqdNsiFwl6lY7B6qCd3q96G9RPWCNiNUlAoyRn+jKkUDqN8jpTHtITsG2n2QzW0KQYNR5Rt6Mpkgr4jRrKyjOrMidz2pLWRDo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785645; c=relaxed/simple; bh=Sr9rAuYr8ID2mLrVyqriEpQmNGbv/dVay/wcUnsNZrQ=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=QUed4rhQFJu7LYLTTV47dmYbqZ57hznuKdOrMtViwWzyGiFzbHFv9upLMc45bBGSKHtA/gMZeGr9jId+UX9YVesIvTk/FroaKuBzq0xCAqU3ZEsrX5iuzS7/HF27M3wsO1qbQIWfwvfwOq/PALTi8hXzw2yDS2oLFTQQdTCQsuM= 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=pN4f8XE3; 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="pN4f8XE3" Received: by mail-pl1-f169.google.com with SMTP id d9443c01a7336-227d6b530d8so63202015ad.3 for ; Tue, 15 Apr 2025 23:40:43 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785643; x=1745390443; 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=nra1/y1QUgh6AgleDK5Vc1vrrwimHbIG9HYBJFdcQfg=; b=pN4f8XE3AAP2AUk+0k3P7ww21BxPUHaP1+uEk/UT6Frdm0CpdZ8IlR+x3DS+KkyehF zsrsAn2PWKid1gIavzA3kewAoybBxnUb9F5hVcgKY67O2Ne9N+rezZKedLn5pL5gbbrE Yp6J+0X/F53m+sJnOXNohCidhiclgwqoAGY9p+QYwIz4F8amoA33D48u745FZ5n4yoiY IX1GorBt7VWHTmzGi3iI/B9tOuxsukiZp5qKhvrmqQKacUCaXJwrvOAqJJ5J+IU36Acj HGRpg4dLJkezVRBSJ7HjSkt7/gPJO/Qm1X9uMmKSv5oOGF1wBf+z/cHs0XPBD6tuTn3u 0x7A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785643; x=1745390443; 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=nra1/y1QUgh6AgleDK5Vc1vrrwimHbIG9HYBJFdcQfg=; b=bhPX6DY/1l5BrRpYnUWwGa7tQbB5iBCgnZKaCaF+GAHSLZrzrLxbtTvcm6wNAdg8Ka Vgg6SjBZCIoe6SS23xodI3EhYhXx4HTGJPIMQ0gU00ZcI7a8VmmmR26rCdC5H3Ff+3bF dZnDktjY4/GME0y4QV9fyiq7nFf7aaq+tHPo4a9+xq3PaMe5Uz2Cx9tqEcNdgbMbUQr6 pDzw3vF4on0IQHlUF/2uNAWev4Y7g6uW37HdpJ5uF9xgn3LlkRI3FjI/65WApYMyD/8T cQ9s9VJYjjIvEcc4k3Ue/J5lvADprYhGegY7Jd/jDvFSjL6XEWp0LDfzQwKxW/ruVVP6 1EuQ== X-Forwarded-Encrypted: i=1; AJvYcCUiB6sCkfReuHAnoyXHSZ8ZgAC7Pg4gAcpwImkA12jPYcqYzrWKGBe9exz8wBU7ISC++GG83I265RJrYBI=@vger.kernel.org X-Gm-Message-State: AOJu0YzjDy6Ts8aMk2ukxnGwE1FsRdQFELr2/JFUNY5/jkVi7DLg4HXU kQYlrDiAj3tOMjvw5Q/ZAdt0tm6H89l0N3SPK9MFC73QT986ISe/Gel6oaiPkWM= X-Gm-Gg: ASbGncvdkwLyqADQrGzrwp1H0a6S2Ya+MHLLMzXmHdfk/HNTKMBZP2b31CQmqN4IhFZ v1WfUgc5rXgYrQGNjEFHUJdHXff/GMN2djSzLkPad2kLe3Apxo3SVhwLTexBtdl0p4YVkU1iFop c2ZTSYu9KCYdPAFhmEs1qscWbZKbHXptE2lbZXHXDMcQGR/xwhAPBT0zMb+fOr1tW42C80EyiFH qwDl+7TBNlOta4jl1qkK+Kj7y8YGPlG8AIRlbgVbO7PPToIHFUJpO+2JsFj67uQTzb2/yodWQ/o nqFuaMkSbSEOhd5g0EZwXK84Xv68M81zCAHQ8XMSIw== X-Google-Smtp-Source: AGHT+IHfv4TXGee8ischTd2l0mhcpY+jrfYOqJPhK7dDPNeUP1SWyHXE6UuQWPB+/HGeogEvX68lJA== X-Received: by 2002:a17:903:1247:b0:220:ca39:d453 with SMTP id d9443c01a7336-22c358d878cmr9655275ad.17.1744785642912; Tue, 15 Apr 2025 23:40:42 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c33fa5febsm6384525ad.117.2025.04.15.23.40.41 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40: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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 13/15] rust: cpufreq: Extend abstractions for driver registration Date: Wed, 16 Apr 2025 12:09:30 +0530 Message-Id: <8d04ef19d7a16610dbf0dfb5c9a611c6e1e3e318.1744783509.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. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 480 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 477 insertions(+), 3 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index fd605921add4..87a54a8af198 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -9,24 +9,31 @@ //! Reference: =20 use crate::{ + alloc::AllocError, clk::{Clk, Hertz}, cpumask, device::Device, - error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR= }, - ffi::c_ulong, + 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, }; =20 use core::{ + marker::PhantomData, + mem::MaybeUninit, ops::{Deref, DerefMut}, pin::Pin, - ptr, + ptr::{self, NonNull}, }; =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 @@ -801,3 +808,470 @@ 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::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: u32) -> Resul= t<()> { +/// // 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(NonNull, Phan= tomData); + +// SAFETY: `Registration` doesn't offer any methods or access to fields wh= en shared between threads +// or CPUs, so it is safe to share it. +unsafe impl Sync for Registration {} + +#[allow(clippy::non_send_fields_in_send_ty)] +// SAFETY: Registration with and unregistration from the cpufreq subsystem= 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 { + let drv: *const bindings::cpufreq_driver =3D &Self::VTABLE; + let drv =3D drv.cast_mut(); + + // SAFETY: It is safe to register the driver with the cpufreq core= in the kernel C code. + to_result(unsafe { bindings::cpufreq_register_driver(drv) })?; + + Ok(Self( + NonNull::new(drv.cast()).ok_or(AllocError)?, + 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)?; + Ok(()) + } +} + +// 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) }; + 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) }; + 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) }; + 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(cpu: u32) { + if let Ok(mut policy) =3D PolicyCpu::from_cpu(cpu) { + T::update_limits(&mut 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 { + // Removes the `Registration` from the kernel, if it has initialized s= uccessfully earlier. + fn drop(&mut self) { + // SAFETY: The driver was earlier registered from `new`. + unsafe { bindings::cpufreq_unregister_driver(self.0.as_ptr()) }; + } +} --=20 2.31.1.272.g89b43f80a514 From nobody Fri Dec 19 19:07:38 2025 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 00CBA23E336 for ; Wed, 16 Apr 2025 06:40:46 +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=1744785648; cv=none; b=LwPsF6e9Pr9Gql1keGLSHxRm7WOusnKn5OLstBWvt44RTa8U0X4jE/PhpETgOXnGlZy/3ZMsMg2J3NkGcWDROcFZIOJub3CmIdQL81womtcQkU9f7wpMiRPodTV/bPVTwlcjQXSvOxId9f5HaEGL37Bnw9OWaIb4+/2YQyjh4nk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785648; c=relaxed/simple; bh=0oAPeXp/PuUtI+r6+VnpeufFCyNZfY1rcOa88ugE1TE=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=HC4E9tBIx9D0StJmVNtDxg4Ch/kEaBLqVSVDa8InmyT0a6VXR70+qXmce7evMVKvue5VD8fgx+tr2wO5b8vpM9Bh+qggpcrQCnX6WcFCua4zyVoGcGORxC3ZAbRSUF3p+hJY+80YMtq71P6i4iSlIFU1JCT5TBoBP4iQoedh1Zk= 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=Qw5l8c3Q; 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="Qw5l8c3Q" Received: by mail-pf1-f176.google.com with SMTP id d2e1a72fcca58-736aa9d0f2aso7150175b3a.0 for ; Tue, 15 Apr 2025 23:40:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785646; x=1745390446; 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=0lQWbn6xCAFQD5C3/8f6kegHNBrNwg8cRG4PxnN6CGw=; b=Qw5l8c3QR2PZqgl9BQjWJ98u6hZKlktnzESsW+s5O08BGS3z0UZqcCkm4DW+yfVIAQ b1jQTn/wkVtvJgGQzAugJhBQSUL+aHfMdcAefR29gaiWNNR3ARJrLZr0BlT3K9RlCv9z f8D3Ha3kYF6hcWFZwSZYDPJrzU41TvIaxJuCoBNbBwbUn3hEPF56zEj/dzl8njKQwPAM dvSaqR2huOp7iweqsVNSnzQfUQMRE4RR2NtaH+1ZkOHHW7B2i5j3f4sK2g2CvCqQGtuD dvMqFXVkgYKhlfSPM1SkW32KTNLhCU61bFOKzRPpfpiXYHnIJurxwN8aqtR+Wl5R9Ylk fyDg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785646; x=1745390446; 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=0lQWbn6xCAFQD5C3/8f6kegHNBrNwg8cRG4PxnN6CGw=; b=t0vQt7vDIUdNkG9mg/4/5ksWTj2vTpbzxM6HM6acwmly6++BmwwGKjEGY1v8nTDwKm MsyHwbfmYBs8Tij+rvyAdTh++74kb/cspVY16PTJvZ1bt94zZ3eroo1E9MxyJfQ4d6WY dnbsm6ly+TvA3JWKd54WrvNLfBHYQjMbnVqQwov6bjah454fSM3FfPgNlQJu3bd0+Fy+ hYyHT/bwNiehTleNy0nxYTUe5N3HyWlvLDDeX1wLqtSuPIPpltXx5pZFSNZmUoVME8o0 gv5oC33xD9/+8t/CZKCPbNGP1POtHQ0HBwKH3Z8Cse29xLVRQOXEP9Y2SDGIKwEprP9H HCTA== X-Forwarded-Encrypted: i=1; AJvYcCUKFojr3oiQJmC5awQkfCPMqPCklOlB0jPLvI9WrW0Cb2aPqVhJ8goKqlgaeIB42RiGEd7AiOf5v/choHA=@vger.kernel.org X-Gm-Message-State: AOJu0YzxBS0hSAJGFQlpokDDOv7abS3K/CcLPGgucIswWyIYky3OgJTO 2O8aU8bF1Ulp/8mlRd+DNm6vRKnABzk3EHLnMsnGP37PW1piAiWMalpOdTOq/Vk= X-Gm-Gg: ASbGncvtQPZByL23yE3Mkm7J5PPFvgutXXKJS4VRLIrBFeYD96sF1e72mxweeAFSCXK YOYcoTKf99LwXY+vp0o+By/6XE9vX8MQ5hj5c4VB20ff5jf/1E3BLfYzERtjsorb8Djhr2xiTKo YldEIavmdwL1vBcUjtbnABFHDyOSiNFOSRnOOc7VyzjQymmJukydoZpUZR8bnptm5huT4VdgWTu kYu6bWT8q1Ix7vKa/83djeaYxM9KtknT2rc2qR15p/AusiZv4sJPXyEaL7s1rCWSIHCmiPOcg9/ T80sO/c6T9o+Z/iTgMYF/AbxIzFGCjfd9QO9ND10jb2WeIxcxo4X X-Google-Smtp-Source: AGHT+IGcC7USaY6oAxRsHSPlQeIONoztyY2iv3IC1aLwlzT7hWILIJ8jWmGaRC16byakE8SVjYhJkg== X-Received: by 2002:a05:6a00:1487:b0:736:ab48:18f0 with SMTP id d2e1a72fcca58-73c266b318cmr900916b3a.1.1744785646320; Tue, 15 Apr 2025 23:40:46 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73bd22f1259sm9658028b3a.119.2025.04.15.23.40.45 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:45 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 14/15] rust: opp: Extend OPP abstractions with cpufreq support Date: Wed, 16 Apr 2025 12:09:31 +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 | 67 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 44e11808793a..734be8b6d0ef 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -19,6 +19,12 @@ types::{ARef, AlwaysRefCounted, Opaque}, }; =20 +#[cfg(CONFIG_CPU_FREQ)] +use crate::cpufreq; + +#[cfg(CONFIG_CPU_FREQ)] +use core::ops::Deref; + use core::{marker::PhantomData, ptr}; =20 use macros::vtable; @@ -496,6 +502,60 @@ extern "C" fn config_regulators( } } =20 +/// OPP frequency table. +/// +/// A [`cpufreq::Table`] created from [`Table`]. +#[cfg(CONFIG_CPU_FREQ)] +pub struct FreqTable { + dev: ARef, + ptr: *mut bindings::cpufreq_frequency_table, +} + +#[cfg(CONFIG_CPU_FREQ)] +impl FreqTable { + /// Creates a new instance of [`FreqTable`] from [`Table`]. + fn new(table: &Table) -> Result { + let mut ptr: *mut bindings::cpufreq_frequency_table =3D ptr::null_= mut(); + + // SAFETY: The requirements are satisfied by the existence of [`De= vice`] and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_init_cpufreq_table(table.dev.as_raw(), &m= ut ptr) + })?; + + Ok(Self { + dev: table.dev.clone(), + 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) } + } +} + +#[cfg(CONFIG_CPU_FREQ)] +impl Deref for FreqTable { + type Target =3D cpufreq::Table; + + #[inline] + fn deref(&self) -> &Self::Target { + self.table() + } +} + +#[cfg(CONFIG_CPU_FREQ)] +impl Drop for FreqTable { + fn drop(&mut self) { + // SAFETY: The pointer was created via `dev_pm_opp_init_cpufreq_ta= ble`, and is only freed + // here. + unsafe { bindings::dev_pm_opp_free_cpufreq_table(self.dev.as_raw()= , &mut self.as_raw()) }; + } +} + /// A reference-counted OPP table. /// /// Rust abstraction for the C `struct opp_table`. @@ -751,6 +811,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 Fri Dec 19 19:07:38 2025 Received: from mail-pl1-f171.google.com (mail-pl1-f171.google.com [209.85.214.171]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2E1F22459D1 for ; Wed, 16 Apr 2025 06:40:51 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785654; cv=none; b=uJTnGuM5XAcY/I8PVVFaNQIjnIFdL6x2GZ+l9zup3jkdUy88Tx+0qSobeiouZ5e6+W2xha1O76vkGesdK6wpARJPfsFVvFUM6bNHymFWrFqGDkBeLObkg/8KZd9Wek8MkbpepKxNW5nk4A8KPbPLDZ7FIlOsusAG0k+sYmEoM/8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744785654; c=relaxed/simple; bh=YCUW7M3FpgyiiQGjw35St6tdqJBkxe3Qu+wxpKDUfUw=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=cgTDrAXIpt8U9irXszthiGpBa4vE07aeBZbJOIcApMqwvuQozHTEPo0wdnxbC7FmA0nY8BPZwEksjp51U13IfnE9Oz9GNLFqecu4J+sUSFq/vWwKjYX2h8tLSyIQ+P5AGRJBihFlqaaFs7z6Z7Z6zygvi7rCuC386ZnlBXzg5tA= 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=fDjFcA9C; arc=none smtp.client-ip=209.85.214.171 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="fDjFcA9C" Received: by mail-pl1-f171.google.com with SMTP id d9443c01a7336-227cf12df27so3518555ad.0 for ; Tue, 15 Apr 2025 23:40:51 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1744785650; x=1745390450; 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=N/mvtnXNN1pJbPS5ASieAHCptDhOrKeUchHsYheFMok=; b=fDjFcA9CZoYgTGPZhwnpsEmiQ5GSqU2n+9xaxnJOwqbxzl6fenRcSlbGMAhcfY0vOc B8AV4jl7z1f08auin1FDl2qNLmBQqZ59udosBXnXlb/xJ9NdYCdycKKPexrtvHaFaz3+ 0DkAwIp5xatzThJENXrKa4XKsYxRYXKwLPI2jLXZNNsN2REq98xe8QsNA7XZXqikzURG m1Ts6cy3tVyTApQyjsvCRprWMbINGopICeWV3NMs6AKfgEsAcWgDMyl8c6lCj2X+BV/o u4pzaMuR5fRKByh2X9K1n63S0yQCpGGJTqXA+49kv6BEI1Rxm6aq7QQ0eoyVUNnvbq8e bXFg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744785650; x=1745390450; 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=N/mvtnXNN1pJbPS5ASieAHCptDhOrKeUchHsYheFMok=; b=Xh68p144j95QQMXOgnX2A0TiBeu1hf4pozceLsLZqlA1Eaw4Ejn321oad05cozVDP/ ECX62qp3ifu/936kFoQarKNjk70S5LrCSLYxotdu6jZ3lVNPsk/BJ05Dr1XlRPCzQrPp TP7dcrnihqWUhwAzngv6EsbV0ltr6/pSoG+OCldCU6mrmXVBltP+KqkHk8qwf1iQ2odp J9SGNSoHqxSaEFrezpjVVnPaxvsDivUG7+jzvSUJ84CdoDmL+BX26v0hG3MuhK0RyhWo yPzL5S15vz9uHelqg0gukFFLJpp2yCJYf2u3AAup0bgVGWs1klZuu7r2EfVr9PRGzvFU 8gcw== X-Forwarded-Encrypted: i=1; AJvYcCWXMCnAgQx2rH80eHmY2avYdHNDT96v4TYqoPTytEx6SYpqnWQxVWIuFoFUlsnkD0Vijai00uH8pEJpgFE=@vger.kernel.org X-Gm-Message-State: AOJu0YxfKjmEPg2LE1DBUxv0wzqAWo9u94wOJrz2dgk6ew+yR+jLRR0w 72vYR42Gm1U6zjG+GvqT80Rj0jQGUjSZSGtPT7sIu/mvz53/Y3m18rVv5wXchiM= X-Gm-Gg: ASbGnctkSYCNunVMYCpXyTSUDuZp2vNGtrfQ3pu/zNRVRsUDuL1OEWm2hNlibRCx7bs Pf66JyJhi2Z6T7uxL2/3Hy0jek2FcUk9HAVyiR9jRpp+mdJYJW5CxUD5MalDDldEvZcNDWZ8+aV TZcLe9JfibIdpUprM86IyR6gAI9k5+Pbaf6Sy8DZSGs5j6UpQ50vRDY4KU0Pg022b5AdYLQ93Eh 4EhrXkOFDLRpfjOtOgWe3b8N6NfI6Qm5ZS1rr06na7CRuQW+nrKbAnaR23kXprtCuJK6ObURnBJ +lbsSyfgRQZv5qkZFHz59OPIU0Uo+gKvTNCRBpKY3A== X-Google-Smtp-Source: AGHT+IHsyZn4vaNkqCMpGot94/NaRC26FvkgWryRgtlbTWHkBqMeg8qk1kmY2mX8fUHHHMTa/r6A2g== X-Received: by 2002:a17:902:f683:b0:223:fb95:b019 with SMTP id d9443c01a7336-22c35f16999mr9717555ad.24.1744785650447; Tue, 15 Apr 2025 23:40:50 -0700 (PDT) Received: from localhost ([122.172.83.32]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-22c33f1cd56sm6491425ad.83.2025.04.15.23.40.49 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 15 Apr 2025 23:40:49 -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 , linux-kernel@vger.kernel.org Subject: [PATCH V10 15/15] cpufreq: Add Rust-based cpufreq-dt driver Date: Wed, 16 Apr 2025 12:09:32 +0530 Message-Id: <312f14531b97a7530446cc44e38d6dbe10fef083.1744783509.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 | 233 +++++++++++++++++++++++++++++++++ 3 files changed, 246 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..81ede13909b7 --- /dev/null +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -0,0 +1,233 @@ +// 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, + #[allow(dead_code)] + mask: CpumaskVar, + #[allow(dead_code)] + token: Option, + #[allow(dead_code)] + clk: Clk, +} + +#[derive(Default)] +struct CPUFreqDTDriver; + +#[vtable] +impl opp::ConfigOps for CPUFreqDTDriver {} + +#[vtable] +impl cpufreq::Driver for CPUFreqDTDriver { + const NAME: &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, + token, + clk, + }, + GFP_KERNEL, + )?) + } + + fn exit(_policy: &mut cpufreq::Policy, _data: Option) -> = Result<()> { + Ok(()) + } + + fn online(_policy: &mut cpufreq::Policy) -> Result<()> { + // We did light-weight tear down earlier, nothing to do here. + Ok(()) + } + + fn offline(_policy: &mut cpufreq::Policy) -> Result<()> { + // Preserve policy->data and don't free resources on light-weight + // tear down. + Ok(()) + } + + fn suspend(policy: &mut cpufreq::Policy) -> Result<()> { + policy.generic_suspend() + } + + fn verify(data: &mut cpufreq::PolicyData) -> Result<()> { + data.generic_verify() + } + + fn target_index(policy: &mut cpufreq::Policy, index: u32) -> Result<()= > { + let Some(data) =3D policy.data::() else { + return Err(ENOENT); + }; + + // SAFETY: `index` is guaranteed to be valid by the C API. + let freq =3D unsafe { data.freq_table.freq(index.try_into()?)? }; + 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