From patchwork Tue Jan 7 11:21:35 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 855625 Received: from mail-pl1-f182.google.com (mail-pl1-f182.google.com [209.85.214.182]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 7059F1E1C02 for ; Tue, 7 Jan 2025 11:22:16 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.182 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248940; cv=none; b=XYQnJzjvWqVNSoEdyzGb5enR2JEb9eJ1E2BiEJKRE6uxnZ9mMXsnwzt1jcj85W0mX46VPD7JVaHfr0mgFtHXjhsJpGQL2QbmqX+ZwEYYJw+LRMw3650NF63rhcb4UpmJECLJTDM1yueueZOe5oeZrI09bAQTHyc0eh1ZU4skApQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248940; c=relaxed/simple; bh=cdokPHvwKyokV3hwBzmQO12SedZRDpfVgc8m4ctxbwI=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=AXMufTHQBLiwv2100j/IraOBw2B0rvaOGBsNxYgtEhe5NEr3NeDC107l4P87WhVzXskhHPO2blpWFp6eORXO4jW4yhlKl/q2IYPjjBEFaGzRJ0OtFRYDiR1cd0vWHZGxZZlcN498yrDygu9G/Qasgnz+YwHFHBYx8kcZeG86Trk= 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=bdauNgYU; arc=none smtp.client-ip=209.85.214.182 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="bdauNgYU" Received: by mail-pl1-f182.google.com with SMTP id d9443c01a7336-2167141dfa1so220083725ad.1 for ; Tue, 07 Jan 2025 03:22:16 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1736248936; x=1736853736; 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=7ASfdta/u0wkPRjfyeaLnqQ/klht5Qg5KYEOzmHA0l0=; b=bdauNgYUtEnFwVs/pYRQsY0TZ/w0BEq+U5fXKfgfVywTMfIaIOGag9FG7eAI036st+ JDpqkqobj378Fnw80t2TO4Z3jXRT5tINzVf2CbLIr4a1ZRN+SQ2PxlGCuvm+XLt7rqqh bwihGIG8WSqPZqA2s1P/Qm/TcWiscM37TB1QOvdGzCYWPF1LB8KEgXHlTzuErw4niQye ESSbvbRT5NUAOTfh85rpoo3ldY4IdjZlmNO1zsMrMV7ZRFB3EI6wwu/NmjDMQrEd2B1h HhPg7BZM6NP89RpW8Kr6mfqITfK5qnx7c5KEg37xfO4exNMwCJSnF+kqT87tTPIXGuFw Z9nw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736248936; x=1736853736; 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=7ASfdta/u0wkPRjfyeaLnqQ/klht5Qg5KYEOzmHA0l0=; b=eIr2FaNvBN5PBV8HqkG1kS+uzbGh1R9+w7Zr6wjc7w3DVu+4yNSqQPYAo0RDX6jydv KqefAigDLZ1iJuWJNMj5ghyhxu684fFQ/aW83K2lzq0Vj2K6A1LDVETS5Xd/nJ9rVvEL 5BE+qt/P0jxUKqhJpHcWCaQMTzgt/baHOzIXfLWLSoX7ybCRjog9RHg1vvP/JykWU2Ad fsn5MpjfJuKjKv1CsqzS6gfLpIv4zKYd3F5RK3mpQ44row0HduoCfBCkA7b0bOOiA4hI Zbu4xDki5O9PXR1rKLJyDpNEGX+/PyaYedb87QE4Dd4uP58vusC3pUCkRWvFZ+p3zTto 7oIg== X-Gm-Message-State: AOJu0YxSh4bLXh5lKOOWcS67ch7ucglP4Z7lDcpti0cgTMe/gQDeHR8j N2QNvYUhqXtYlO15NvwKteIQHYiatJCWUmC8wAWOe8ZYRqMtag5px65oBoBl0yM= X-Gm-Gg: ASbGncu4BfFyHzg+F4lXuZ0ERUvWjm9qM3XVOKZBJ1vwCMtuQvvRwR1btGqoUGDu8GW c8eGz+nk2DUDwYAnPFaMEPAaYt9JXNOkFM/3EIVW0q/4kTDszJkJaU9W7klYg0FsxsyuoP3h6cX SP2OvT2VlPc0BkjOEDLHyW3IThWoGBLkWBlQxLMt0DfmFYPHhZvX5cN1YWEVXygIyk4gZ9TPhia r6iBpdziAwOBfGrJMUplAmt6qM7ZG5wSCUjDaXHrM5mrnTaUnCFWbLaFMw= X-Google-Smtp-Source: AGHT+IEaWLMcL8bHxAFeukhJpYOpx8QL26UyBSGPga9CzNP9StwHzqf6lsQksJ+v3Nx6VNAD4SfyCg== X-Received: by 2002:a17:902:d482:b0:216:1a59:5bbf with SMTP id d9443c01a7336-21a7a0be85emr36270175ad.0.1736248935755; Tue, 07 Jan 2025 03:22:15 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id 41be03b00d2f7-842aba72f7csm30274625a12.4.2025.01.07.03.22.14 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 07 Jan 2025 03:22:15 -0800 (PST) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?utf-8?q?Alex_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [PATCH V6 02/15] cpufreq: Add cpufreq_table_len() Date: Tue, 7 Jan 2025 16:51:35 +0530 Message-Id: <867ba9728179ba21ff8f8aca97d416b72ccd63d9.1736248242.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Add a function to calculate number of entries in the cpufreq table. This will be used by the Rust implementation. Signed-off-by: Viresh Kumar --- include/linux/cpufreq.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/include/linux/cpufreq.h b/include/linux/cpufreq.h index 7fe0981a7e46..6b882ff4dc24 100644 --- a/include/linux/cpufreq.h +++ b/include/linux/cpufreq.h @@ -783,6 +783,17 @@ bool cpufreq_boost_enabled(void); int cpufreq_enable_boost_support(void); bool policy_has_boost_freq(struct cpufreq_policy *policy); +static inline unsigned int cpufreq_table_len(struct cpufreq_frequency_table *freq_table) +{ + struct cpufreq_frequency_table *pos; + unsigned int count = 0; + + cpufreq_for_each_entry(pos, freq_table) + count++; + + return count; +} + /* Find lowest freq at or above target in a table in ascending order */ static inline int cpufreq_table_find_index_al(struct cpufreq_policy *policy, unsigned int target_freq, From patchwork Tue Jan 7 11:21:37 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 855624 Received: from mail-pj1-f53.google.com (mail-pj1-f53.google.com [209.85.216.53]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5A9391EE7A7 for ; Tue, 7 Jan 2025 11:22:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.53 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248947; cv=none; b=qYCzSTISKc1+dc0WuD7nY+0ExNs2SRxSxzb8aTda3DRNfpPzydJKBA+DlF8chIlaKFm3M0bn1fpDL2iDr7H0YUCjyQLJOWbwbnQ5ZKfQehvHysWoYG7u/zYdDtwpOoBL14yBomwlgSwuq7L4HVewDNURCY8MKdqEXQ576ucH8Pc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248947; c=relaxed/simple; bh=x1jppnh7F+u/qb+q16Mwk7GksVsIqsWg9PfFNzKZF6A=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=SUpVwkWcri89+tft8Lcngh45FY5hsiGZD0iUt4AhnMWVrHj1GmjS9jR882cPNDRgSBEOtOJdBmYFcHtEf6ru1wb1nSB2en25BYbeUl5wirQXjL3HxRRPJRINah6hauXsx0WK2PZVW5Q7q52lGdFlVnsR7htMfLwhNUxCkc6ImiE= 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=MXNMdG+b; arc=none smtp.client-ip=209.85.216.53 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="MXNMdG+b" Received: by mail-pj1-f53.google.com with SMTP id 98e67ed59e1d1-2ee76befe58so22496639a91.2 for ; Tue, 07 Jan 2025 03:22:23 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1736248942; x=1736853742; 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=bxcq9I4UQnaTuD1adWbQtLusduX9hVdyMIuXwSadLE4=; b=MXNMdG+b3PiJRWJFcN7ZZD7k6KM/XDi7lsfWsk3EYXhYUHVU6cqZgRzW4klJCsWabt WLPZ92C1UerbPsgbiKdFpbVzNDC/S1eVgRiFW1XdI44SF4T+bPMgIyRbj7pzMUtmfk8Z BP6AdZmNIKuF7ESqR7d1v3B2qEywtw/JEkx8csMyG8haec8QitVJj/e1uVMDnJcz0UBC wVopEVSGvPoCAemf188ie1tmts+bYtG3v5s1i7YLyvKOUHhq6fxWOu51nm36WnIjTg/z k8knBJzL62jK4ArRZ6+QUopgp4BYUCmOJDIgsc1dxm1am+GYT/gpK916/CgG2xdNga+z Lk3g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736248942; x=1736853742; 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=bxcq9I4UQnaTuD1adWbQtLusduX9hVdyMIuXwSadLE4=; b=suaLSgea0fKbWoaIEfEY9PqgDHacY20YFSBlxlPi2yP7HuSFrp0RF3PR2CyE/Q0kGj hOrl1p8cBlNEOtZhQxOK3RLnjV53hWKOnUl8pwcJY0cVM4aE225B329G0jzCc6CyRbl8 SkTlZunE8l2/kj8AKAWJU+MH+jcVuJVKbKbMRCDJZGQ3BphdFjVMLbrLtO/yPgztoqkb Ha2ezAMPrIskAR/RJCIF8dkIWW47584JG7yR6eP5/srK6jpEw+JLytPude/eBJqvt2a/ J7YzYtrm8zZSkZKOB27uUBJNJVkCY7qLcGmETa8eG3aDzu+khjYK758WKzGVme7MDStj S7cg== X-Forwarded-Encrypted: i=1; AJvYcCUK42H1KZXLNS2V7gRFUK0Tik55W2Ro3tX0QgAetW1GBksbdCYyDj0XAECAjMCZz4PSIEuWcAcT1w==@vger.kernel.org X-Gm-Message-State: AOJu0YxOTPHJCMsF4vVLXYfOEFLQxt4PGvTq/P55WIOQ4MGkuHXWmqb2 +jzTTBtT7OWAVbzkzRVdzQa3Wvp5d99hu4ESEJ/gS9KlzTR9ULfrNRq8g03/jYE= X-Gm-Gg: ASbGncu1W9VkgCuphtjhDxHtc8dzzBxDahrQf2K9aUKg371Y8q4MfpXmE+MDnWJoukV fKEsXyZZY4ETpcPgUtfG29yXX+OzQgpaJ6hbuRSs/v24UgfwksZ8AP7j/8C2HebOGGLn6EVAu4z WRfpZqLQiuEjxSbouBZGSmwEpkIZolMMNNZeYpOV2mFYOvZuP6EYKv83V7h08r4nY67ILo4/0+k u/9cCQQlg0qdOkE/cX6deoEVrRY+OfvPp7w9iwejSeH/KopDnhfXgjSSx8= X-Google-Smtp-Source: AGHT+IHOEcakQrEY0NFbsraOZsTPh16b6theN19EscXJIXJjZKGEh1xL6JV3tVS4LFiWXJdG5cNq/Q== X-Received: by 2002:a17:90b:270d:b0:2ee:6736:8512 with SMTP id 98e67ed59e1d1-2f452e1636emr116424204a91.12.1736248942581; Tue, 07 Jan 2025 03:22:22 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-2f2ee26fc22sm37567007a91.51.2025.01.07.03.22.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 07 Jan 2025 03:22:22 -0800 (PST) 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_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Greg Kroah-Hartman , Danilo Krummrich Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?utf-8?q?Alex_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [PATCH V6 04/15] rust: device: Add few helpers Date: Tue, 7 Jan 2025 16:51:37 +0530 Message-Id: <429b7539f787ad360cd28fd1db6dc3d6c1fe289d.1736248242.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Add from_cpu() and property_present() helpers to the device bindings. Signed-off-by: Viresh Kumar --- rust/bindings/bindings_helper.h | 1 + rust/kernel/device.rs | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 43f5c381aab0..70e4b7b0f638 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs index d5e6a19ff6b7..5bfbc4bdfadc 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -6,6 +6,9 @@ use crate::{ bindings, + error::Result, + prelude::ENODEV, + str::CString, types::{ARef, Opaque}, }; use core::{fmt, ptr}; @@ -59,6 +62,18 @@ pub unsafe fn get_device(ptr: *mut bindings::device) -> ARef { unsafe { Self::as_ref(ptr) }.into() } + /// Creates a new ref-counted instance of device of a CPU. + pub fn from_cpu(cpu: u32) -> Result> { + // SAFETY: It is safe to call `get_cpu_device()` for any CPU number. + let ptr = unsafe { bindings::get_cpu_device(cpu) }; + if ptr.is_null() { + return Err(ENODEV); + } + + // SAFETY: By the safety requirements, ptr is valid. + Ok(unsafe { Device::get_device(ptr) }) + } + /// Obtain the raw `struct device *`. pub(crate) fn as_raw(&self) -> *mut bindings::device { self.0.get() @@ -180,6 +195,12 @@ unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) { ) }; } + + /// Checks if property is present or not. + pub fn property_present(&self, name: &CString) -> bool { + // SAFETY: `name` is null-terminated. `self.as_raw` is valid because `self` is valid. + unsafe { bindings::device_property_present(self.as_raw(), name.as_ptr() as *const _) } + } } // SAFETY: Instances of `Device` are always reference-counted. From patchwork Tue Jan 7 11:21:39 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 855623 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 481BC1EE7DC for ; Tue, 7 Jan 2025 11:22:31 +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=1736248956; cv=none; b=We8M1EhckOFLqPugITRkyS7PUeEvyG9X90FJ7Fkc4umuvJFpBKR6L5ir8d5N/2e2i8Fy5YGaIsjqL1w97/KEIoQ2e3dgurVzRZkMSMFm/9o4n/l4IirL7y3XajFffcDIdF2r73p63lAJARrxZVwlrz6KIJHP+uGlg7vgWLsdlpA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248956; c=relaxed/simple; bh=Fx9XB5ts9sXUh9O3/l7pGwJGGgpdlk1bk0cEGYOweMo=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=DlXKFJUPuZG13I28lgazgbMM5v00o+inelEPin3+vplXQAod3ciwsUfWLydRC1nit8Z0OBZvcd+Ec9GGojslLkezQDgAqi1UaR0oW7Zh5cdQXT+4lqMPSsi+wXvCt/bhdgl80NTzncVzQlQX2/JKfYJEaT3n3azfDOHXBw0jW5Y= 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=woKW3rU8; 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="woKW3rU8" Received: by mail-pl1-f171.google.com with SMTP id d9443c01a7336-216281bc30fso4733785ad.0 for ; Tue, 07 Jan 2025 03:22:31 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1736248950; x=1736853750; 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=jK9fggKbnQIV5hRTBl9969qRmfCDXZjN5H+SCocLudA=; b=woKW3rU8YbZ5atMKY6K4VJZqd6hKuqCVyZm4TOmkD5rPd7CuwKTsuEfct98/SqwCqT jbGZzjLUWdLm6knoU5ZOUKLYpd+LiEP7OJUY/H0tdN1TT4/7ayyDlHEyuWFAAB58HlNs 8FY7Mrh0/B9o5GC1Wsnsl+rdghWJDivOnGKF8haK9atbMygeTNHvUgP05IfrAHb7y0Dh XCNXHJJ/+DlcSREBoIv78EBQAfVAzfI1OkY/e3pEye4uQmijN79xb52IpQn0YqeG7w6y s3CG6zHaLoRhHdeEUdAICp6lJZXUhwzosnIkZz2ENh3rq4r/WmOdaV1EfK2xdP21hpko EJEw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736248950; x=1736853750; 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=jK9fggKbnQIV5hRTBl9969qRmfCDXZjN5H+SCocLudA=; b=apDq9E0hyROwmGXc/RnkMhxh28O2wBzN6xGWlE3syIC2wHb7voePZHU013wKw9TYWz rlrG1/vXIV4zb2rOyhpoSPXSm1H8hVZQrRPFHzsaFi4rAuvHY8OoTL+oGKi5cmFptAh+ fNVgUws057yTRnRq/RunWUryB0pXgJaVyuLVoUCYbOfUSjhCi2mEkSvn+PVhr1TgoCui 7C1s5M7cEM9Kx+1uhdUthrbHIeu00HQFXxnvMKWzJKuA2AbEJqHWhMj1/qL7haedOgJB wDbeCH0PdAPfNb8HMbovPxgZhyXIaWb/bEISe2LFwrCZw38DA4M8qbm9n+pZ6+GN/G2O Sbuw== X-Forwarded-Encrypted: i=1; AJvYcCWIx/IEAPnvlqkaX6UcHrfGzjrnA0CYoEwrnJEYLqikRkZK8/4Et1LRtN7NkMRxye0+VOn7bqQuOg==@vger.kernel.org X-Gm-Message-State: AOJu0YweJ08jPDSB5Zz3L4XOruuR2tamaUFrSMB2WIKr41qlEZP3KoSv tjApaSvQ9AecA3Chd5HayBZxMnJgURvrt1iUssZEDmEvFWPkLqdDiEVpQMTdOpE= X-Gm-Gg: ASbGnctdXPJh74iuwMVc5hB7v9H5B/47az5IMvCBxrVPqbu7kWXpZNofaxInPsOAWMZ Pk/KHyf0TCSUj7df0Bwp1agrdzJ1jIRhscffCXSw1V+HPWfsKqc/dRG72LzCmbSVINtCQOgL/je fqzo4Tben9l6QXFzvTwzsgVLyACAwgjJmXeAsigt8+D4G9+o/IL6EtjpWap3SzUPAJ6Jb34dXbt lC0EVLQy1PQRoDhA1z1poaasMUUYDumMB+JmK9w8PRULySjMLh36DDHgTI= X-Google-Smtp-Source: AGHT+IF9FSxiUi6E3vyUCMwDEsv53WHI4nW1IVtUaahS5ofFQcTzHYCfQCLCjg0emu7ogoZdphf3/A== X-Received: by 2002:a17:902:da8e:b0:215:b058:28a5 with SMTP id d9443c01a7336-219e6ea2855mr823470415ad.18.1736248950516; Tue, 07 Jan 2025 03:22:30 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc962940sm307240865ad.34.2025.01.07.03.22.29 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 07 Jan 2025 03:22:30 -0800 (PST) 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_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?utf-8?q?Alex_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [PATCH V6 06/15] rust: Add bare minimal bindings for clk framework Date: Tue, 7 Jan 2025 16:51:39 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This adds very basic bindings for the clk framework, implements only clk_get() and clk_put(). These are the bare minimum bindings required for many users and are simple enough to add in the first attempt. Signed-off-by: Viresh Kumar --- rust/bindings/bindings_helper.h | 1 + rust/kernel/clk.rs | 48 +++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 50 insertions(+) create mode 100644 rust/kernel/clk.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 3225379abd2b..7a95d999ead8 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/clk.rs b/rust/kernel/clk.rs new file mode 100644 index 000000000000..123cdb43b115 --- /dev/null +++ b/rust/kernel/clk.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Clock abstractions. +//! +//! C header: [`include/linux/clk.h`](srctree/include/linux/clk.h) + +use crate::{ + bindings, + device::Device, + error::{from_err_ptr, Result}, + prelude::*, +}; + +use core::ptr; + +/// A simple implementation of `struct clk` from the C code. +#[repr(transparent)] +pub struct Clk(*mut bindings::clk); + +impl Clk { + /// Creates `Clk` instance for a device and a connection id. + pub fn new(dev: &Device, name: Option<&CStr>) -> Result { + let con_id = if let Some(name) = name { + name.as_ptr() as *const _ + } else { + ptr::null() + }; + + // SAFETY: It is safe to call `clk_get()`, on a device pointer earlier received from the C + // code. + Ok(Self(from_err_ptr(unsafe { + bindings::clk_get(dev.as_raw(), con_id) + })?)) + } + + /// Obtain the raw `struct clk *`. + pub fn as_raw(&self) -> *mut bindings::clk { + self.0 + } +} + +impl Drop for Clk { + fn drop(&mut self) { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // relinquish it now. + unsafe { bindings::clk_put(self.0) }; + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 8a0cd60eb6cc..70694becc9ff 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -38,6 +38,7 @@ #[cfg(CONFIG_BLOCK)] pub mod block; mod build_assert; +pub mod clk; pub mod cpumask; pub mod cred; pub mod device; From patchwork Tue Jan 7 11:21:41 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 855622 Received: from mail-pl1-f178.google.com (mail-pl1-f178.google.com [209.85.214.178]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 539431F03D4 for ; Tue, 7 Jan 2025 11:22:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.178 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248962; cv=none; b=kV5cbYFhy6ySWg3u1HS71qrqA+Y5c6UwVszzjw7h0e+bkdYeFTAZ87ErMpzTkfrB74LNrYXk8oUmzZ4vJj4xDcMNKZ+f3E/W/aXkS6uTPKUHm1RpQGzDY++z2YT7xCnWIl5oHhXyjiiw8c+JBIJPWbFY7lLeHj8eLGT2kSoratw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248962; c=relaxed/simple; bh=F59T52ZUvJkNBV6wo8TzSwdeallQLvy0aM5T1cqDlNw=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=qCW7S8KNaga+F+7HVzgtJxx/zgCurrv/djVkboU1HTGE/BV5lisHU/le8Tvz3TqdzZ67TBHSJx0LkmzDT53Meub+WaReITa3GBPH7mN2Hzn172ug+UPr/eFKMZwiDs5sO22l87U+1cM0trNj5+rJ53I7HW+aKbPX9hl1O0nN+mg= 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=KVzECBiM; arc=none smtp.client-ip=209.85.214.178 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="KVzECBiM" Received: by mail-pl1-f178.google.com with SMTP id d9443c01a7336-2161eb95317so231009455ad.1 for ; Tue, 07 Jan 2025 03:22:39 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1736248959; x=1736853759; 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=fTQCsib1qyn6gEeH65mgzAdRA2+DI7bnecHFZTU0+Uc=; b=KVzECBiMdIBeUD4cf0YvDvCh6g0A+gHViMeeXIr/Ffk3ERnEcesaL2Vxp2Bh8shHI6 ZLgXWch2u8AKwMQQVpt6h1IZ5Mm1Obi5wykWVldvnjWdzoYZBysy/gesdjmK/pd3KoKH aqojVV8g9mic9C+EAFwKYnzR6M+B8Y84KPftXeUkHZIMfo4NorCKw0dgf9dJDxilaVfu JfjkIVkPgSEi4RkNqq1Eq+ImdAI30d0eMcQR3Al9R6Q4phlCpBgLP9cDdjOTN7FRwcZM SHMWM0m140JqDPrYM/steyMxzJYL7tMhIx9RCNc44HMA03zsTJDQ8lEj1vClZSiy/VR/ IqiQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736248959; x=1736853759; 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=fTQCsib1qyn6gEeH65mgzAdRA2+DI7bnecHFZTU0+Uc=; b=Vtj7R611L99awjj4VeV0kywH2hy4eBV1XHOynidxXC2c/xy/2WCGjYcCHKhe/9uVoq tvruwx5p+Di6ow8jd1EGDXB4zUFmKXnhO1mHNLtTRkvr6wRPgURLDICywK+sKOpb0TFd /cYVwkHhe3U5g0x3nubnnf1HR9KL9iE8Pc+nzLrW5uujiYLt3prHuzxeo1jCmZbQ0qAM /9K+V7ePgZrR3tXmQAgQKv3OLiTDqeNNtIJnKMEhDRBS3CHBkek73sw9nVa3nN7QJJ3b kyWtG7y59yd5rG1S5oTv03TQBkhldePU+cQ++Z0Lda9EUBQyXwF1siCQfutF/M5w5mdy mk2A== X-Forwarded-Encrypted: i=1; AJvYcCUcBHp0g81VzmXCCo5aO703OhP39Fp4S84SREtWE0h5gYhaVU/jo9V+1kyhK2oAgAD8CHGuVwRQeA==@vger.kernel.org X-Gm-Message-State: AOJu0YyOaTaoLvGpQKkhM76RXIw1MUibXyGMs5fT5M2kkRF+i0Dt3+vE TRoKys345T3yGEVkZbnMs0KTl65f9lY3JjXXT8YQd7FWAaeOI8FK9P1WN5DEnJM= X-Gm-Gg: ASbGncuysG0+IkqNWbtR/5FJktap1m5FDOPcPnb/FheC98xXf+bh2M48XZv/NmcCQ93 prZooYxaaD16XJlv6wY671HXw75aXFTRtXDZY3dQvjdC5tvfgbh7l5y9XipT0AtM2ys8TuhC73m 9f4f4vaI64UPjmrcKA5eFCog6AiBe32eMoIZmQblPPHOZ1GYw78SkeOYHDEuHab5lJJ44VOMBai qdprJ9B1Z5CxtvtthWQI/omayZdXS7AEcNeHpEx4PxW64jSuMFxUzKS8a4= X-Google-Smtp-Source: AGHT+IGqv/rR48aHxzi2bVTnF7fVAY7ggUgtkv/AUa8oiDegkd82/yPX20CdcqZH4nQtpPQdv4o/Ag== X-Received: by 2002:a05:6a00:3905:b0:725:e73c:c415 with SMTP id d2e1a72fcca58-72abde8fd6fmr86616109b3a.18.1736248958476; Tue, 07 Jan 2025 03:22:38 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-72aad8fba98sm33234399b3a.161.2025.01.07.03.22.37 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 07 Jan 2025 03:22:37 -0800 (PST) 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?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?utf-8?q?Alex_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [PATCH V6 08/15] rust: Extend OPP bindings for the OPP table Date: Tue, 7 Jan 2025 16:51:41 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This extends OPP bindings with the bindings for the `struct opp_table`. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 382 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 381 insertions(+), 1 deletion(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index becb33880c92..b1e277c660d4 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -8,8 +8,9 @@ use crate::{ bindings, + cpumask::Cpumask, device::Device, - error::{code::*, to_result, Result}, + error::{code::*, from_err_ptr, to_result, Error, Result}, types::{ARef, AlwaysRefCounted, Opaque}, }; @@ -67,6 +68,385 @@ fn freq(&self) -> usize { } } +/// OPP search types. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum SearchType { + /// Search for exact value. + Exact, + /// Search for highest value less than equal to value. + Floor, + /// Search for lowest value greater than equal to value. + Ceil, +} + +/// Operating performance point (OPP) table. +/// +/// Wraps the kernel's `struct opp_table`. +/// +/// The pointer stored in `Self` is non-null and valid for the lifetime of the `Table`. +pub struct Table { + ptr: *mut bindings::opp_table, + dev: ARef, + em: bool, + of: bool, + cpumask: Option, +} + +// SAFETY: It is okay to send ownership of `Table` across thread boundaries. +unsafe impl Send for Table {} + +// SAFETY: It's OK to access `Table` through shared references from other threads because we're +// either accessing properties that don't change or that are properly synchronised by C code. +unsafe impl Sync for Table {} + +impl Table { + /// Creates a new OPP table instance from raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null. + unsafe fn from_raw_table(ptr: *mut bindings::opp_table, dev: &ARef) -> Self { + // SAFETY: By the safety requirements, ptr is valid and its refcount will be incremented. + unsafe { bindings::dev_pm_opp_get_opp_table_ref(ptr) }; + + Self { + ptr, + dev: dev.clone(), + em: false, + of: false, + cpumask: None, + } + } + + /// Find OPP table from device. + pub fn from_dev(dev: &ARef) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. Refcount of the OPP table is incremented by the C code. + let ptr = from_err_ptr(unsafe { bindings::dev_pm_opp_get_opp_table(dev.as_raw()) })?; + + Ok(Self { + ptr, + dev: dev.clone(), + em: false, + of: false, + cpumask: None, + }) + } + + /// Add device tree based OPP table for the device. + #[cfg(CONFIG_OF)] + pub fn from_of(dev: &ARef, index: i32) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. Refcount of the OPP table is incremented by the C code. + to_result(unsafe { bindings::dev_pm_opp_of_add_table_indexed(dev.as_raw(), index) })?; + + // Fetch the newly created table. + let mut table = Self::from_dev(dev)?; + table.of = true; + + Ok(table) + } + + // Remove device tree based OPP table for the device. + #[cfg(CONFIG_OF)] + fn remove_of(&self) { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. We took the reference earlier from `from_of` earlier, it is safe to drop + // the same now. + unsafe { bindings::dev_pm_opp_of_remove_table(self.dev.as_raw()) }; + } + + /// Add device tree based OPP table for CPU devices. + #[cfg(CONFIG_OF)] + pub fn from_of_cpumask(dev: &ARef, cpumask: &mut Cpumask) -> Result { + // SAFETY: The cpumask is valid and the returned ptr will be owned by the [`Table`] instance. + to_result(unsafe { bindings::dev_pm_opp_of_cpumask_add_table(cpumask.as_raw()) })?; + + // Fetch the newly created table. + let mut table = Self::from_dev(dev)?; + + let mut mask = Cpumask::new()?; + cpumask.copy(&mut mask); + table.cpumask = Some(mask); + + Ok(table) + } + + // Remove device tree based OPP table for CPU devices. + #[cfg(CONFIG_OF)] + fn remove_of_cpumask(&self, mut cpumask: Cpumask) { + // SAFETY: The cpumask is valid and we took the reference from `from_of_cpumask` earlier, + // it is safe to drop the same now. + unsafe { bindings::dev_pm_opp_of_cpumask_remove_table(cpumask.as_raw()) }; + } + + /// Returns the number of OPPs in the table. + pub fn opp_count(&self) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + let ret = unsafe { bindings::dev_pm_opp_get_opp_count(self.dev.as_raw()) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ret as u32) + } + } + + /// Returns max clock latency of the OPPs in the table. + pub fn max_clock_latency(&self) -> usize { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_clock_latency(self.dev.as_raw()) } + } + + /// Returns max volt latency of the OPPs in the table. + pub fn max_volt_latency(&self) -> usize { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_volt_latency(self.dev.as_raw()) } + } + + /// Returns max transition latency of the OPPs in the table. + pub fn max_transition_latency(&self) -> usize { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_max_transition_latency(self.dev.as_raw()) } + } + + /// Returns the suspend OPP. + pub fn suspend_freq(&self) -> usize { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_get_suspend_opp_freq(self.dev.as_raw()) } + } + + /// Synchronizes regulators used by the OPP table. + pub fn sync_regulators(&self) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_sync_regulators(self.dev.as_raw()) }) + } + + /// Gets sharing CPUs. + pub fn sharing_cpus(dev: &Device, cpumask: &mut Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_get_sharing_cpus(dev.as_raw(), cpumask.as_raw()) + }) + } + + /// Sets sharing CPUs. + pub fn set_sharing_cpus(&mut self, cpumask: &mut Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_set_sharing_cpus(self.dev.as_raw(), cpumask.as_raw()) + })?; + + if let Some(mask) = self.cpumask.as_mut() { + // Update the cpumask as this will be used while removing the table. + cpumask.copy(mask); + } + + Ok(()) + } + + /// Gets sharing CPUs from Device tree. + #[cfg(CONFIG_OF)] + pub fn of_sharing_cpus(dev: &Device, cpumask: &mut Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_of_get_sharing_cpus(dev.as_raw(), cpumask.as_raw()) + }) + } + + /// Updates the voltage value for an OPP. + pub fn adjust_voltage( + &self, + freq: usize, + u_volt: usize, + u_volt_min: usize, + u_volt_max: usize, + ) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_adjust_voltage( + self.dev.as_raw(), + freq, + u_volt, + u_volt_min, + u_volt_max, + ) + }) + } + + /// Sets a matching OPP based on frequency. + pub fn set_rate(&self, freq: usize) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_set_rate(self.dev.as_raw(), freq) }) + } + + /// Sets exact OPP. + pub fn set_opp(&self, opp: &OPP) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_set_opp(self.dev.as_raw(), opp.as_raw()) }) + } + + /// Finds OPP based on frequency. + pub fn opp_from_freq( + &self, + mut freq: usize, + available: Option, + index: Option, + stype: SearchType, + ) -> Result> { + let rdev = self.dev.as_raw(); + let index = index.unwrap_or(0); + + let ptr = from_err_ptr(match stype { + SearchType::Exact => { + if let Some(available) = available { + // SAFETY: The requirements are satisfied by the existence of `Device` and + // its safety requirements. The returned ptr will be owned by the new [`OPP`] + // instance. + unsafe { + bindings::dev_pm_opp_find_freq_exact_indexed(rdev, freq, index, available) + } + } else { + return Err(EINVAL); + } + } + + // SAFETY: The requirements are satisfied by the existence of `Device` and its + // safety requirements. The returned ptr will be owned by the new [`OPP`] instance. + SearchType::Ceil => unsafe { + bindings::dev_pm_opp_find_freq_ceil_indexed(rdev, &mut freq as *mut usize, index) + }, + + // SAFETY: The requirements are satisfied by the existence of `Device` and its + // safety requirements. The returned ptr will be owned by the new [`OPP`] instance. + SearchType::Floor => unsafe { + bindings::dev_pm_opp_find_freq_floor_indexed(rdev, &mut freq as *mut usize, index) + }, + })?; + + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp_owned(ptr) } + } + + /// Finds OPP based on level. + pub fn opp_from_level(&self, mut level: u32, stype: SearchType) -> Result> { + let rdev = self.dev.as_raw(); + + let ptr = from_err_ptr(match stype { + // SAFETY: The requirements are satisfied by the existence of `Device` and its + // safety requirements. The returned ptr will be owned by the new [`OPP`] instance. + SearchType::Exact => unsafe { bindings::dev_pm_opp_find_level_exact(rdev, level) }, + + // SAFETY: The requirements are satisfied by the existence of `Device` and its + // safety requirements. The returned ptr will be owned by the new [`OPP`] instance. + SearchType::Ceil => unsafe { + bindings::dev_pm_opp_find_level_ceil(rdev, &mut level as *mut u32) + }, + + // SAFETY: The requirements are satisfied by the existence of `Device` and its + // safety requirements. The returned ptr will be owned by the new [`OPP`] instance. + SearchType::Floor => unsafe { + bindings::dev_pm_opp_find_level_floor(rdev, &mut level as *mut u32) + }, + })?; + + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp_owned(ptr) } + } + + /// Finds OPP based on bandwidth. + pub fn opp_from_bw(&self, mut bw: u32, index: i32, stype: SearchType) -> Result> { + let rdev = self.dev.as_raw(); + + let ptr = from_err_ptr(match stype { + // The OPP core doesn't support this yet. + SearchType::Exact => return Err(EINVAL), + + // SAFETY: The requirements are satisfied by the existence of `Device` and its + // safety requirements. The returned ptr will be owned by the new [`OPP`] instance. + SearchType::Ceil => unsafe { + bindings::dev_pm_opp_find_bw_ceil(rdev, &mut bw as *mut u32, index) + }, + + // SAFETY: The requirements are satisfied by the existence of `Device` and its + // safety requirements. The returned ptr will be owned by the new [`OPP`] instance. + SearchType::Floor => unsafe { + bindings::dev_pm_opp_find_bw_floor(rdev, &mut bw as *mut u32, index) + }, + })?; + + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp_owned(ptr) } + } + + /// Enable the OPP. + pub fn enable_opp(&self, freq: usize) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_enable(self.dev.as_raw(), freq) }) + } + + /// Disable the OPP. + pub fn disable_opp(&self, freq: usize) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_disable(self.dev.as_raw(), freq) }) + } + + /// Registers with Energy model. + #[cfg(CONFIG_OF)] + pub fn of_register_em(&mut self, cpumask: &mut Cpumask) -> Result<()> { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_of_register_em(self.dev.as_raw(), cpumask.as_raw()) + })?; + + self.em = true; + Ok(()) + } + + // Unregisters with Energy model. + #[cfg(CONFIG_OF)] + fn of_unregister_em(&self) { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. We registered with the EM framework earlier, it is safe to unregister now. + unsafe { bindings::em_dev_unregister_perf_domain(self.dev.as_raw()) }; + } +} + +impl Drop for Table { + fn drop(&mut self) { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe + // to relinquish it now. + unsafe { bindings::dev_pm_opp_put_opp_table(self.ptr) }; + + #[cfg(CONFIG_OF)] + { + if self.em { + self.of_unregister_em(); + } + + if self.of { + self.remove_of(); + } else if let Some(cpumask) = self.cpumask.take() { + self.remove_of_cpumask(cpumask); + } + } + } +} + /// Operating performance point (OPP). /// /// Wraps the kernel's `struct dev_pm_opp`. From patchwork Tue Jan 7 11:21:43 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 855621 Received: from mail-pl1-f173.google.com (mail-pl1-f173.google.com [209.85.214.173]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 045B41F0E57 for ; Tue, 7 Jan 2025 11:22:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.173 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248971; cv=none; b=XK7c2KIjU9B2T4LMyILbwsIxRk2dt/POgxjr44TpiaatjiyUlI3qVK0gApZydPpWeZAcqVaUf8vcnzFtpiHptRtsvp6Ni2WPD3usmPawefAyHBkeqkn9lvymM25HTsYxXW31T2PUxSCuSIstfxx+X4XNs6p3qJzB+rhx+F9ScA8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248971; c=relaxed/simple; bh=rTvkUg8TSAwbpVq8htbrxHio/yXXpqaXKu8xmyXvlsI=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=hxCxjHK+P3PUX+/j1BSGb4JX3sLWlLsK2x9qWVCo70Xm3pr0TiPhCFxWYex2w9qUDOX8BNaVl9xFKmh/fjS/SqGf9SRungeIqpyZAf4+gDGVYs2YfPEHc+oTSKG0G5Z7/1pxfpmMhMb/ZZTvdcuRdvqp/mJaAjkRvxhP3wr7b3U= 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=uiwvc3Y2; arc=none smtp.client-ip=209.85.214.173 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="uiwvc3Y2" Received: by mail-pl1-f173.google.com with SMTP id d9443c01a7336-2165cb60719so228251085ad.0 for ; Tue, 07 Jan 2025 03:22:46 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1736248966; x=1736853766; 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=4GirQKr1CrJ4lbsHTZW131CE79vWTAUxlJNTFw3lOtI=; b=uiwvc3Y27McNjDqmInDPdmkOv3r1AX6n1L9QcZugXLIfOjOCxen4rHFtizhXJw/qcz Ijl7TyLMYsKjNuDGnl8TQiqwa6eLu7AgxTrR06YZ1GzaS1ySTeINGKfGy7mvCMiviuBO 9dm2TazGNmMIDC5/f1rm2I6R2NnMqJiaEbQ7aTCGuC04BY6jGYdUk3SRYy7jfdXJ/OBY jJpF/FPaiU+YsAjV01toqPJ085i42vmvrmNyeK5GUhhORyf2TXukm4SwWJfw9z2ZEi7Z X5x45bMX8zNBRVgtR9D1kF1kybwGQWOh9FixTZo92O6HDVzDmdZUCqtLjMlHLbydDJKG VI6w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736248966; x=1736853766; 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=4GirQKr1CrJ4lbsHTZW131CE79vWTAUxlJNTFw3lOtI=; b=d9FkiPjKmL0UAushbA5NM2VaqHll2O8zJaSyh1Uk8KILwjwrJkfy1fFm8FYmtTt3BE xI1orTbRxlJ4HeqzfoXVmRju/edroNosa7LwKDpZsDi/fQ60kRoNsefzsrZ8T5eLh7f6 lFOLy3FxtMuuH+geoYm7obE+iTBlT5PqUuZrfIiXDjDVx7wg/MLyQHp3wP7RfI8NuM6H gnMVkPzIXdoSzhuww137Zq/l5ezn7IdFoLLZGG4mnwF/rg+9ZJAj3tS7jbmJfQ9RH1pt zdZHqgfp7jpndgQwffQBLuN/1ZIoPZiE5D3uU5Su7Y94Y+y7pxXONh7aTEYtTzmogWMA 5z0A== X-Gm-Message-State: AOJu0Yy2MHic4OPHaqaXIYc4FJJUBxAu3oo4RSbiukJVONrbtKXcoXKl OcPvZN0CmiVF8KtR6n1ZPVP0rnnU6WK1GpHF4RjaUcevnamK/lSpAVOI/KwGHPk= X-Gm-Gg: ASbGnct4iQk4Ttr8Xut3ahjZFsnqeRSwdua65cfHmAgH74t9XrrGxXF7g8DudNTVnXF tdS/dVA0jjsJfhlWZNdwPF+LasBKUGAWG49lyJ5hfdTZAeNkVYHhLsRpUgoZiCXM5kQI3tTUCM9 oStgKOK++pm3inFxFBSx+tEYxWSGfXVUH1l1AgVgi/xggZQJMD6MqS2cYEzz/EyYcMEhfZSRrY0 5dBGGWARmSCSxBBaWedj8nhyo72eXFi2/P/dmBubi8uk8CvtrTRGPFfEUA= X-Google-Smtp-Source: AGHT+IFFxonaPDUSw5GDuK6y9YEM45DNTx4nOsm8oXu1zAiQSki75MjEYrGMGno+TTY/2jdIWdALLg== X-Received: by 2002:a17:903:32c5:b0:215:e98c:c5bb with SMTP id d9443c01a7336-219e6eb43d6mr902213635ad.28.1736248966309; Tue, 07 Jan 2025 03:22:46 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc96eae7sm308153165ad.85.2025.01.07.03.22.45 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 07 Jan 2025 03:22:45 -0800 (PST) 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_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Viresh Kumar Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?utf-8?q?Alex_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [PATCH V6 10/15] rust: Add initial bindings for cpufreq framework Date: Tue, 7 Jan 2025 16:51:43 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This commit adds initial Rust bindings for the cpufreq core. This adds basic bindings for cpufreq flags, relations and cpufreq table. Reviewed-by: Manos Pitsidianakis Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers/cpufreq.c | 16 ++ rust/helpers/helpers.c | 1 + rust/kernel/cpufreq.rs | 254 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 6 files changed, 275 insertions(+) create mode 100644 rust/helpers/cpufreq.c create mode 100644 rust/kernel/cpufreq.rs diff --git a/MAINTAINERS b/MAINTAINERS index bfcdbe4aa119..35ab20b99f90 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5957,6 +5957,7 @@ F: drivers/cpufreq/ F: include/linux/cpufreq.h F: include/linux/sched/cpufreq.h F: kernel/sched/cpufreq*.c +F: rust/kernel/cpufreq.rs F: tools/testing/selftests/cpufreq/ CPU HOTPLUG diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 5f900532e5ec..bd706ad1e58a 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -16,6 +16,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..28f8ebf96032 --- /dev/null +++ b/rust/helpers/cpufreq.c @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +#ifdef CONFIG_CPU_FREQ +unsigned int +rust_helper_cpufreq_table_len(struct cpufreq_frequency_table *freq_table) +{ + return cpufreq_table_len(freq_table); +} + +void rust_helper_cpufreq_register_em_with_opp(struct cpufreq_policy *policy) +{ + cpufreq_register_em_with_opp(policy); +} +#endif diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 1943b98aec2b..f258e3b1a0bb 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 "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..07ff03cb2991 --- /dev/null +++ b/rust/kernel/cpufreq.rs @@ -0,0 +1,254 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU frequency scaling. +//! +//! This module provides bindings for interacting with the cpufreq subsystem. +//! +//! C header: [`include/linux/cpufreq.h`](srctree/include/linux/cpufreq.h) + +use crate::{ + bindings, + error::{code::*, to_result, Result}, + prelude::*, +}; + +use core::{ + pin::Pin, +}; + +/// Default transition latency value. +pub const ETERNAL_LATENCY: u32 = bindings::CPUFREQ_ETERNAL as u32; + +/// Container for cpufreq driver flags. +pub mod flags { + use crate::bindings; + + /// Set by drivers that need to update internal upper and lower boundaries along with the + /// target frequency and so the core and governors should also invoke the driver if the target + /// frequency does not change, but the policy min or max may have changed. + pub const NEED_UPDATE_LIMITS: u16 = bindings::CPUFREQ_NEED_UPDATE_LIMITS as _; + + /// Set by drivers for platforms where loops_per_jiffy or other kernel "constants" aren't + /// affected by frequency transitions. + pub const CONST_LOOPS: u16 = bindings::CPUFREQ_CONST_LOOPS as _; + + /// Set by drivers that want the core to automatically register the cpufreq driver as a thermal + /// cooling device. + pub const IS_COOLING_DEV: u16 = bindings::CPUFREQ_IS_COOLING_DEV as _; + + /// Set by drivers for platforms that have multiple clock-domains, i.e. supporting multiple + /// policies. With this sysfs directories of governor would be created in cpu/cpuN/cpufreq/ + /// directory and so they can use the same governor with different tunables for different + /// clusters. + pub const HAVE_GOVERNOR_PER_POLICY: u16 = bindings::CPUFREQ_HAVE_GOVERNOR_PER_POLICY as _; + + /// Set by drivers which do POSTCHANGE notifications from outside of their ->target() routine. + pub const ASYNC_NOTIFICATION: u16 = bindings::CPUFREQ_ASYNC_NOTIFICATION as _; + + /// Set by drivers that want cpufreq core to check if CPU is running at a frequency present in + /// freq-table exposed by the driver. For these drivers if CPU is found running at an out of + /// table freq, the cpufreq core will try to change the frequency to a value from the table. + /// And if that fails, it will stop further boot process by issuing a BUG_ON(). + pub const NEED_INITIAL_FREQ_CHECK: u16 = bindings::CPUFREQ_NEED_INITIAL_FREQ_CHECK as _; + + /// Set by drivers to disallow use of governors with "dynamic_switching" flag set. + pub const NO_AUTO_DYNAMIC_SWITCHING: u16 = bindings::CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING as _; +} + +/// CPU frequency selection relations. Each value contains a `bool` argument which corresponds to +/// the Relation being efficient. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Relation { + /// Select the lowest frequency at or above target. + Low(bool), + /// Select the highest frequency below or at target. + High(bool), + /// Select the closest frequency to the target. + Close(bool), +} + +impl Relation { + // Converts from a value compatible with the C code. + fn new(val: u32) -> Result { + let efficient = val & bindings::CPUFREQ_RELATION_E != 0; + + Ok(match val & !bindings::CPUFREQ_RELATION_E { + bindings::CPUFREQ_RELATION_L => Self::Low(efficient), + bindings::CPUFREQ_RELATION_H => Self::High(efficient), + bindings::CPUFREQ_RELATION_C => Self::Close(efficient), + _ => return Err(EINVAL), + }) + } + + /// Converts to a value compatible with the C code. + pub fn val(&self) -> u32 { + let (mut val, e) = match self { + Self::Low(e) => (bindings::CPUFREQ_RELATION_L, e), + Self::High(e) => (bindings::CPUFREQ_RELATION_H, e), + Self::Close(e) => (bindings::CPUFREQ_RELATION_C, e), + }; + + if *e { + val |= bindings::CPUFREQ_RELATION_E; + } + + val + } +} + +/// Equivalent to `struct cpufreq_policy_data` in the C code. +#[repr(transparent)] +pub struct PolicyData(*mut bindings::cpufreq_policy_data); + +impl PolicyData { + /// Creates new instance of [`PolicyData`]. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null. + pub unsafe fn from_raw_policy_data(ptr: *mut bindings::cpufreq_policy_data) -> Self { + Self(ptr) + } + + /// Returns the raw pointer to the C structure. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_policy_data { + self.0 + } + + /// Provides a wrapper to the generic verify routine. + pub fn generic_verify(&self) -> Result<()> { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it now. + to_result(unsafe { bindings::cpufreq_generic_frequency_table_verify(self.as_raw()) }) + } +} + +/// Builder for the `struct cpufreq_frequency_table` in the C code. +#[repr(transparent)] +#[derive(Default)] +pub struct TableBuilder { + entries: KVec, +} + +impl TableBuilder { + /// Creates new instance of [`TableBuilder`]. + pub fn new() -> Self { + Self { + entries: KVec::new(), + } + } + + /// Adds a new entry to the table. + pub fn add(&mut self, frequency: u32, flags: u32, driver_data: u32) -> Result<()> { + // Adds new entry to the end of the vector. + Ok(self.entries.push( + bindings::cpufreq_frequency_table { + flags, + driver_data, + frequency, + }, + GFP_KERNEL, + )?) + } + + /// Creates [`Table`] from [`TableBuilder`]. + pub fn into_table(mut self) -> Result { + // Add last entry to the table. + self.add(bindings::CPUFREQ_TABLE_END as u32, 0, 0)?; + Table::from_builder(self.entries) + } +} + +/// A simple implementation of the cpufreq table, equivalent to the `struct +/// cpufreq_frequency_table` in the C code. +pub struct Table { + #[allow(dead_code)] + // Dynamically created table. + entries: Option>>, + + // Pointer to the statically or dynamically created table. + ptr: *mut bindings::cpufreq_frequency_table, + + // Number of entries in the table. + len: usize, +} + +impl Table { + /// Creates new instance of [`Table`] from [`TableBuilder`]. + fn from_builder(entries: KVec) -> Result { + let len = entries.len(); + if len == 0 { + return Err(EINVAL); + } + + // Pin the entries to memory, since we are passing its pointer to the C code. + let mut entries = Pin::new(entries); + + // The pointer is valid until the table gets dropped. + let ptr = entries.as_mut_ptr(); + + Ok(Self { + entries: Some(entries), + ptr, + // The last entry in table is reserved for `CPUFREQ_TABLE_END`. + len: len - 1, + }) + } + + /// Creates new instance of [`Table`] from raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null for the lifetime of the [`Table`]. + pub unsafe fn from_raw(ptr: *mut bindings::cpufreq_frequency_table) -> Self { + Self { + entries: None, + ptr, + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `Self`. + len: unsafe { bindings::cpufreq_table_len(ptr) } as usize, + } + } + + // Validate the index. + fn validate(&self, index: usize) -> Result<()> { + if index >= self.len { + Err(EINVAL) + } else { + Ok(()) + } + } + + /// Returns raw pointer to the `struct cpufreq_frequency_table` compatible with the C code. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_frequency_table { + self.ptr + } + + /// Returns `frequency` at index in the [`Table`]. + pub fn freq(&self, index: usize) -> Result { + self.validate(index)?; + + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `self` and `index` is + // also validated before this and is guaranteed to be within limits of the frequency table. + Ok(unsafe { (*self.ptr.add(index)).frequency }) + } + + /// Returns `flags` at index in the [`Table`]. + pub fn flags(&self, index: usize) -> Result { + self.validate(index)?; + + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `self` and `index` is + // also validated before this and is guaranteed to be within limits of the frequency table. + Ok(unsafe { (*self.ptr.add(index)).flags }) + } + + /// Returns `data` at index in the [`Table`]. + pub fn data(&self, index: usize) -> Result { + self.validate(index)?; + + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `self` and `index` is + // also validated before this and is guaranteed to be within limits of the frequency table. + Ok(unsafe { (*self.ptr.add(index)).driver_data }) + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 16e534024323..1c5a20679c7e 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -39,6 +39,8 @@ pub mod block; mod build_assert; pub mod clk; +#[cfg(CONFIG_CPU_FREQ)] +pub mod cpufreq; pub mod cpumask; pub mod cred; pub mod device; From patchwork Tue Jan 7 11:21:45 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 855620 Received: from mail-pl1-f179.google.com (mail-pl1-f179.google.com [209.85.214.179]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 917181F130C for ; Tue, 7 Jan 2025 11:22:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.179 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248980; cv=none; b=N38GQ59+Wcx1ZfBVcIJ2gP/xBx3INmpuMoXzhJQ7ktfD2lUqJMhM5hQAygmMyMcydA0atZ+b2hBFIo7sgzT+XKLnGvRrzpL10BUDkL84qgQAzJ+uEicNhi0zFtGE0bsPvTdtcUFAnEw29fMm/uyZ47n2HMZgBk4eVQSFe1UXyMg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248980; c=relaxed/simple; bh=NnzzCrfLaF7RDoHxNRMuw0UCltIYGqbLoX1BiVkKIHQ=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=kwCNtZzXDoL7JROWLT/YRlDnSKa468cABoR+1TR3i/xGUrh0AeF7Oa6IKxcpOlHytWDdKq+uw0rpbBHxLYhQJ9Jy9cPZlv9ECx2W6LaIR2Sez16iW5ssWkOw/3mqIwE38/9KL9m6nkRC7rYorUe7M/F19g0Z51t3BgVS3hr8M6A= 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=hHNin5S5; arc=none smtp.client-ip=209.85.214.179 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="hHNin5S5" Received: by mail-pl1-f179.google.com with SMTP id d9443c01a7336-21661be2c2dso204594835ad.1 for ; Tue, 07 Jan 2025 03:22:54 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1736248974; x=1736853774; 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=rKIZ2uftRPa42dy9DF/KdtPQL3DLYHbffECBdyIXeKo=; b=hHNin5S5hQuWgs2LSJNrfgzW/fpi7b8pTrqBve6om5OKEKrk8NAeXti5sP6gx3sB9N +jE/tFBozQL8J06+nFiMzuh1cBOYs3Rsh9RWo5EadtSDuKjHA0g/9Jal+fKqGoJqU0rM 5FFYXJ5YJE33Zjh1kKcVx7d+lEEhS/7aobUf9ZXyHkAE/yAi7POmpehfrg+KTnvDCZ2/ KYOFOaVjyayr+X24gCiv9jOLCEj1jnNvXl3FP+djHix7gq9hDDpHVGNZPiE3Zk5K0Kfa LCF8v4FR4gqwFPJAkyeyeGuLuKxXZJT/TUN3spf60FSrHyQx+agfcFJbqGDY8U/ZaCNy WtQg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736248974; x=1736853774; 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=rKIZ2uftRPa42dy9DF/KdtPQL3DLYHbffECBdyIXeKo=; b=kRJxndT8NiEOVH0opn8IPh6iG05pj4ngrDk/0CQd2xtDkxyqDVcjZmjCDE9l2QbIlA Le+NKM6Ycbq537arOokAuXuiI2OHtwYcgxGtp/qULHZb++r/lHcX7Vp02u2B2hWJeciK 0pnLzyPlln0hwKY0jifbEcCbn7A+LbBE3KImEGeYC1rtzZjlx+UuPhMWlldU6bB/auWd 3tlGMovtHJpdoFju9BVdKNr4Xeh1khtl92svo+m95lp3GSV2Bs7M82d7CaeHAEITwh6S AttYFYYp+55jyd/QEC/5cS5eQLH47m3ZxWe58BnAS8fzB2yE3wl53i6EikKcL1zw8AWj 2YLg== X-Gm-Message-State: AOJu0Yz9fF3ZGCSWastPvC8VaXodJashloQArHsh16zG8eBm5NPdEV7P ZyaGIVuJ87VFuM5rr1VZUIyYLDhh9yKhYklzEnlN5RkhNWCtVKOgpCWMeGPM0H8= X-Gm-Gg: ASbGncvg8I20+vyihSKs7uGnb1h5eKTxFuv+yQ2x2VVovFehpRD1flQ9WmXza23hZ3m TD6V4Q5kkNZmQtv5Gw3zO1RCGkcSUOBQZEeVgk9/MW6uFZxy0pbIK3BpZQ3DXb6LggEMaGWgo3u ACrE2qBAFy35qNrND3Mhsjk5krKrtRC8VBivOja++iNnUe550lCtJrZ6X3X3vFz7RIGtDCMeD3R 1vXky8wemowbyHKJho9JK6UEaR4mx1GWTb/Q5yVEQIVWjmRB9QSSgCWUGI= X-Google-Smtp-Source: AGHT+IHI0hZqSt8qstoDq+YLsZM9sLik+m8qSOqJNeWLo39CMlWn3en8Z8SfBVp97ZbZOce+jpwJ6w== X-Received: by 2002:a17:902:f687:b0:215:b473:1dc9 with SMTP id d9443c01a7336-219e6f0e62dmr762857705ad.46.1736248973577; Tue, 07 Jan 2025 03:22:53 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc972251sm309334155ad.96.2025.01.07.03.22.52 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 07 Jan 2025 03:22:53 -0800 (PST) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?utf-8?q?Alex_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [PATCH V6 12/15] rust: Extend cpufreq bindings for driver registration Date: Tue, 7 Jan 2025 16:51:45 +0530 Message-Id: <1ad2d1286e124e1c15e7e5fba2383d26f3f77618.1736248242.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This extends the cpufreq bindings with bindings for registering a driver. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 476 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 474 insertions(+), 2 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index f95e38291b15..e651989cb142 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -9,14 +9,17 @@ use crate::{ bindings, clk, cpumask, device::Device, - error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR}, + devres::Devres, + error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_DEFAULT_ERROR}, prelude::*, types::ForeignOwnable, }; use core::{ + cell::UnsafeCell, + marker::PhantomData, pin::Pin, - ptr::self, + ptr::{self, addr_of_mut}, }; use macros::vtable; @@ -605,3 +608,472 @@ fn register_em(_policy: &mut Policy) { kernel::build_error(VTABLE_DEFAULT_ERROR) } } + +/// Registration of a cpufreq driver. +pub struct Registration { + drv: KBox>, + _p: PhantomData, +} + +// SAFETY: `Registration` doesn't offer any methods or access to fields when shared between threads +// or CPUs, so it is safe to share it. +unsafe impl Sync for Registration {} + +#[allow(clippy::non_send_fields_in_send_ty)] +// SAFETY: Registration with and unregistration from the cpufreq subsystem can happen from any thread. +// Additionally, `T::Data` (which is dropped during unregistration) is `Send`, so it is okay to move +// `Registration` to different threads. +unsafe impl Send for Registration {} + +impl Registration { + /// Registers a cpufreq driver with the rest of the kernel. + pub fn new(name: &'static CStr, data: T::Data, flags: u16, boost: bool) -> Result { + let mut drv = KBox::new( + UnsafeCell::new(bindings::cpufreq_driver::default()), + GFP_KERNEL, + )?; + let drv_ref = drv.get_mut(); + + // Account for the trailing null character. + let len = name.len() + 1; + if len > drv_ref.name.len() { + return Err(EINVAL); + }; + + // SAFETY: `name` is a valid Cstr, and we are copying it to an array of equal or larger + // size. + let name = unsafe { &*(name.as_bytes_with_nul() as *const [u8]) }; + drv_ref.name[..len].copy_from_slice(name); + + drv_ref.boost_enabled = boost; + drv_ref.flags = flags; + + // Allocate an array of 3 pointers to be passed to the C code. + let mut attr = KBox::new([ptr::null_mut(); 3], GFP_KERNEL)?; + let mut next = 0; + + // SAFETY: The C code returns a valid pointer here, which is again passed to the C code in + // an array. + attr[next] = unsafe { + addr_of_mut!(bindings::cpufreq_freq_attr_scaling_available_freqs) as *mut _ + }; + next += 1; + + if boost { + // SAFETY: The C code returns a valid pointer here, which is again passed to the C code + // in an array. + attr[next] = unsafe { + addr_of_mut!(bindings::cpufreq_freq_attr_scaling_boost_freqs) as *mut _ + }; + next += 1; + } + attr[next] = ptr::null_mut(); + + // Pass the ownership of the memory block to the C code. This will be freed when + // the [`Registration`] object goes out of scope. + drv_ref.attr = KBox::leak(attr) as *mut _; + + // Initialize mandatory callbacks. + drv_ref.init = Some(Self::init_callback); + drv_ref.verify = Some(Self::verify_callback); + + // Initialize optional callbacks. + drv_ref.setpolicy = if T::HAS_SETPOLICY { + Some(Self::setpolicy_callback) + } else { + None + }; + drv_ref.target = if T::HAS_TARGET { + Some(Self::target_callback) + } else { + None + }; + drv_ref.target_index = if T::HAS_TARGET_INDEX { + Some(Self::target_index_callback) + } else { + None + }; + drv_ref.fast_switch = if T::HAS_FAST_SWITCH { + Some(Self::fast_switch_callback) + } else { + None + }; + drv_ref.adjust_perf = if T::HAS_ADJUST_PERF { + Some(Self::adjust_perf_callback) + } else { + None + }; + drv_ref.get_intermediate = if T::HAS_GET_INTERMEDIATE { + Some(Self::get_intermediate_callback) + } else { + None + }; + drv_ref.target_intermediate = if T::HAS_TARGET_INTERMEDIATE { + Some(Self::target_intermediate_callback) + } else { + None + }; + drv_ref.get = if T::HAS_GET { + Some(Self::get_callback) + } else { + None + }; + drv_ref.update_limits = if T::HAS_UPDATE_LIMITS { + Some(Self::update_limits_callback) + } else { + None + }; + drv_ref.bios_limit = if T::HAS_BIOS_LIMIT { + Some(Self::bios_limit_callback) + } else { + None + }; + drv_ref.online = if T::HAS_ONLINE { + Some(Self::online_callback) + } else { + None + }; + drv_ref.offline = if T::HAS_OFFLINE { + Some(Self::offline_callback) + } else { + None + }; + drv_ref.exit = if T::HAS_EXIT { + Some(Self::exit_callback) + } else { + None + }; + drv_ref.suspend = if T::HAS_SUSPEND { + Some(Self::suspend_callback) + } else { + None + }; + drv_ref.resume = if T::HAS_RESUME { + Some(Self::resume_callback) + } else { + None + }; + drv_ref.ready = if T::HAS_READY { + Some(Self::ready_callback) + } else { + None + }; + drv_ref.set_boost = if T::HAS_SET_BOOST { + Some(Self::set_boost_callback) + } else { + None + }; + drv_ref.register_em = if T::HAS_REGISTER_EM { + Some(Self::register_em_callback) + } else { + None + }; + + // Set driver data before registering the driver, as the cpufreq core may call few + // callbacks before `cpufreq_register_driver()` returns. + Self::set_data(drv_ref, data)?; + + // SAFETY: It is safe to register the driver with the cpufreq core in the C code. + to_result(unsafe { bindings::cpufreq_register_driver(drv_ref) })?; + + Ok(Self { + drv, + _p: PhantomData, + }) + } + + /// Same as [Registration::new`], but does not return a `Registration` instance. + /// Instead the `Registration` is owned by devres and will be revoked / dropped, once the + /// device is detached. + pub fn new_foreign_owned( + dev: &Device, + name: &'static CStr, + data: T::Data, + flags: u16, + boost: bool, + ) -> Result<()> { + let reg = Self::new(name, data, flags, boost)?; + Devres::new_foreign_owned(dev, reg, GFP_KERNEL)?; + Ok(()) + } + + // Sets the data for a cpufreq driver. + fn set_data(drv: &mut bindings::cpufreq_driver, data: T::Data) -> Result<()> { + if drv.driver_data.is_null() { + // Pass the ownership of the data to the foreign interface. + drv.driver_data = ::into_foreign(data) as _; + Ok(()) + } else { + Err(EBUSY) + } + } + + /// Returns the previous set data for a cpufreq driver. + pub fn data(&mut self) -> Option<::Borrowed<'static>> { + let drv = self.drv.get_mut(); + + if drv.driver_data.is_null() { + None + } else { + // SAFETY: The data is earlier set by us from [`set_data()`]. + Some(unsafe { ::borrow(drv.driver_data) }) + } + } + + // Clears and returns the data for a cpufreq driver. + fn clear_data(&mut self) -> Option { + let drv = self.drv.get_mut(); + + if drv.driver_data.is_null() { + None + } else { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // relinquish it now. + let data = Some(unsafe { ::from_foreign(drv.driver_data) }); + drv.driver_data = ptr::null_mut(); + data + } + } +} + +// cpufreq driver callbacks. +impl Registration { + // Policy's init callback. + extern "C" fn init_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + + let data = T::init(&mut policy)?; + policy.set_data(data)?; + Ok(0) + }) + } + + // Policy's exit callback. + extern "C" fn exit_callback(ptr: *mut bindings::cpufreq_policy) { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + + let data = policy.clear_data(); + let _ = T::exit(&mut policy, data); + } + + // Policy's online callback. + extern "C" fn online_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::online(&mut policy).map(|()| 0) + }) + } + + // Policy's offline callback. + extern "C" fn offline_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::offline(&mut policy).map(|()| 0) + }) + } + + // Policy's suspend callback. + extern "C" fn suspend_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::suspend(&mut policy).map(|()| 0) + }) + } + + // Policy's resume callback. + extern "C" fn resume_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::resume(&mut policy).map(|()| 0) + }) + } + + // Policy's ready callback. + extern "C" fn ready_callback(ptr: *mut bindings::cpufreq_policy) { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::ready(&mut policy); + } + + // Policy's verify callback. + extern "C" fn verify_callback(ptr: *mut bindings::cpufreq_policy_data) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut data = unsafe { PolicyData::from_raw_policy_data(ptr) }; + T::verify(&mut data).map(|()| 0) + }) + } + + // Policy's setpolicy callback. + extern "C" fn setpolicy_callback(ptr: *mut bindings::cpufreq_policy) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::setpolicy(&mut policy).map(|()| 0) + }) + } + + // Policy's target callback. + extern "C" fn target_callback( + ptr: *mut bindings::cpufreq_policy, + target_freq: u32, + relation: u32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::target(&mut policy, target_freq, Relation::new(relation)?).map(|()| 0) + }) + } + + // Policy's target_index callback. + extern "C" fn target_index_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::target_index(&mut policy, index).map(|()| 0) + }) + } + + // Policy's fast_switch callback. + extern "C" fn fast_switch_callback( + ptr: *mut bindings::cpufreq_policy, + target_freq: u32, + ) -> core::ffi::c_uint { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::fast_switch(&mut policy, target_freq) + } + + // Policy's adjust_perf callback. + extern "C" fn adjust_perf_callback(cpu: u32, min_perf: usize, target_perf: usize, capacity: usize) { + if let Ok(mut policy) = Policy::from_cpu(cpu) { + T::adjust_perf(&mut policy, min_perf, target_perf, capacity); + } + } + + // Policy's get_intermediate callback. + extern "C" fn get_intermediate_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> core::ffi::c_uint { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::get_intermediate(&mut policy, index) + } + + // Policy's target_intermediate callback. + extern "C" fn target_intermediate_callback( + ptr: *mut bindings::cpufreq_policy, + index: u32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::target_intermediate(&mut policy, index).map(|()| 0) + }) + } + + // Policy's get callback. + extern "C" fn get_callback(cpu: u32) -> core::ffi::c_uint { + Policy::from_cpu(cpu).map_or(0, |mut policy| T::get(&mut policy).map_or(0, |f| f)) + } + + // Policy's update_limit callback. + extern "C" fn update_limits_callback(cpu: u32) { + if let Ok(mut policy) = Policy::from_cpu(cpu) { + T::update_limits(&mut policy); + } + } + + // Policy's bios_limit callback. + extern "C" fn bios_limit_callback(cpu: i32, limit: *mut u32) -> core::ffi::c_int { + from_result(|| { + let mut policy = Policy::from_cpu(cpu as u32)?; + + // SAFETY: The pointer is guaranteed by the C code to be valid. + T::bios_limit(&mut policy, &mut (unsafe { *limit })).map(|()| 0) + }) + } + + // Policy's set_boost callback. + extern "C" fn set_boost_callback( + ptr: *mut bindings::cpufreq_policy, + state: i32, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::set_boost(&mut policy, state).map(|()| 0) + }) + } + + // Policy's register_em callback. + extern "C" fn register_em_callback(ptr: *mut bindings::cpufreq_policy) { + // SAFETY: `ptr` is valid by the contract with the C code. `policy` is alive only for the + // duration of this call, so it is guaranteed to remain alive for the lifetime of + // `ptr`. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + T::register_em(&mut policy); + } +} + +impl Drop for Registration { + // Removes the registration from the kernel if it has completed successfully before. + fn drop(&mut self) { + pr_info!("Registration dropped\n"); + let drv = self.drv.get_mut(); + + // SAFETY: The driver was earlier registered from `new()`. + unsafe { bindings::cpufreq_unregister_driver(drv) }; + + // Free the previously leaked memory to the C code. + if !drv.attr.is_null() { + // SAFETY: The pointer was earlier initialized from the result of `KBox::leak`. + unsafe { drop(KBox::from_raw(drv.attr)) }; + } + + // Free data + drop(self.clear_data()); + } +} From patchwork Tue Jan 7 11:21:47 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 855619 Received: from mail-pl1-f182.google.com (mail-pl1-f182.google.com [209.85.214.182]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 13C8E1F1911 for ; Tue, 7 Jan 2025 11:23:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.182 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248986; cv=none; b=Ftz+xzpR+/Y8T2q2AFyhc29behEmsa2I268jBkAli/fzPfpU0diO4APOen2nBknNT+MWdRxWBR2qNrXS21r4sgRJC92XtXerlXsfZiucIoh4s81n8NBWoRH3eRZr44O8i8yLqtDC3B/kQBLY6+Gsjo+60W9vNf6edgItOmMoBWE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736248986; c=relaxed/simple; bh=Zh+zceVRDe4q1VK/iKv7tBO8zGZlwvb7fLfjCUgyxcI=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=UtRJK4q04smLyAQP6pVKAZatTAIbNgyyU4XMXrjs4MS6UxM9cZg7c8rzPgiTDydtdfGCNCq9YQ1vcYcrzIWrWFFa5hjzAiFctwmjiS5L/NFDDAoWpXfmMRCR0PC25OafRJTuBJ2TwRpECahAgdQtx5szsj12ol+XT3zzwizkKDM= 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=r78PjdTc; arc=none smtp.client-ip=209.85.214.182 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="r78PjdTc" Received: by mail-pl1-f182.google.com with SMTP id d9443c01a7336-21661be2c2dso204596115ad.1 for ; Tue, 07 Jan 2025 03:23:01 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1736248981; x=1736853781; 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=oEZZKnPd0bzb6THTbxBmj6P2rsKvzK5VMvCnwY2nlJ0=; b=r78PjdTcmoRW1nIJLsrqyic+mOxl93BzA/dABLudZOA2Otc0WKqZY0qRP4v+9xlY0r KrFZxfYmaWg/FqEt/bt3aHob83/3bdb6K7yeKvkKWdJRwKecK0jEpFTChKU0g91HHyqq z6dtkURmjmGIXmY7QNT+jxMc5jaH9YS6DkhsjxFM/DhHidaKceR/Ojhd+8cBIyeXrkgm QbT4boeBFY46qx/ic93USGA7Pw7Q+n1gwPlhsSSVOK7hDeOvcpTIG9WPB/4/BZ1dSXr3 4dNmPC2CTUv3mhKaZuLqoJCYBIyy/sBtbmiekhg0mlnil0HIgnO/7Fa8+oQBPwzkjkqQ DRYA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736248981; x=1736853781; 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=oEZZKnPd0bzb6THTbxBmj6P2rsKvzK5VMvCnwY2nlJ0=; b=qYnOL2JdpMUV3UGCyLClRKQOyVfUwbW1kKI3aNzS128Jlt8MjVS+pkt2rzRiS5xJkW YMXrfi+2HtE7D0QEJ57dWRfvDdD85x8hfjrocNXddXUkv8rnSSQJGA59fUn4GEYRWmnu OKjIDFo/krXMBw6y6ZrH5KkXLqjYHLrslBT/2wwLqDLdkEsqymc0SUICecBgq44ieq8V jGnXjHjC/tqMpAFlRl1Eo/4gjZo1egtVAWuAyryehTq3zCL1hqM8UetPZNvqgjHKTZWB HWs+zHW/4tEqI/azTJOVcYzI3+rrP5LEEmt1NfuvlqiQ6oHVr5dvlgmSC9ysoULeYe6K kikA== X-Gm-Message-State: AOJu0Yz31Qmxa/XMvlsqYfIfl82WydbVpTl49zMMYcsfFJOn0/0uxx0s q41UEZL+72ip/4dj7ldGSGlR5eIJwyQbUPddqrp4xk0cuSImkGuIgf98enU7dBs= X-Gm-Gg: ASbGncv4xA6WHfihwlJmwFjsntRj9iCFE7ZW8/YiP3ebxft6bBlrIBDrEfp2WiTrLlt e2cKPPV6bsNcF7+eZwXliMjRYtJR65zdHZegp3VGELjVnYWYZBSVbGaHi5qo2S/RPAO1p05Ig0o JEtK1bTxjHuyq/FC5WiYNBdkDTs6RvD9ihZV9797oa0ApYuXiv1CGXeRsFtzV67O0pUz/uwdI6v QterGBuXApjua6fUTORdFDQW0/MPWZ/mh6xc9f9Ddlsj8gXluw+pBCTMMQ= X-Google-Smtp-Source: AGHT+IFkKEhXYseuNv5arMgQ5CUD8uPU++D1W3eQ+KvaVzXDpwhzlvnZqwRbRsF/95raPkieH9woYA== X-Received: by 2002:a17:903:228d:b0:215:a2f2:cfbf with SMTP id d9443c01a7336-219e6e9ded8mr761215475ad.18.1736248980773; Tue, 07 Jan 2025 03:23:00 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-219dc9cde66sm308089705ad.145.2025.01.07.03.22.59 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 07 Jan 2025 03:23:00 -0800 (PST) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?B?= =?utf-8?q?j=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross Cc: linux-pm@vger.kernel.org, Vincent Guittot , Stephen Boyd , Nishanth Menon , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?utf-8?q?Alex_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [PATCH V6 14/15] cpufreq: Add Rust based cpufreq-dt driver Date: Tue, 7 Jan 2025 16:51:47 +0530 Message-Id: <41a674fc8ebca6174bcc3af6cdd9155a18b19d42.1736248242.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This commit adds a Rust based cpufreq-dt driver, which covers most of the functionality of the existing C based driver. Only a handful of things are left, like fetching platform data from cpufreq-dt-platdev.c. This is tested with the help of QEMU for now and switching of frequencies work as expected. Signed-off-by: Viresh Kumar --- drivers/cpufreq/Kconfig | 12 ++ drivers/cpufreq/Makefile | 1 + drivers/cpufreq/rcpufreq_dt.rs | 232 +++++++++++++++++++++++++++++++++ 3 files changed, 245 insertions(+) create mode 100644 drivers/cpufreq/rcpufreq_dt.rs diff --git a/drivers/cpufreq/Kconfig b/drivers/cpufreq/Kconfig index 92a83a9bb2e1..5e60dfb6f93e 100644 --- a/drivers/cpufreq/Kconfig +++ b/drivers/cpufreq/Kconfig @@ -217,6 +217,18 @@ config CPUFREQ_DT If in doubt, say N. +config CPUFREQ_DT_RUST + tristate "Rust based Generic DT based cpufreq driver" + depends on HAVE_CLK && OF && RUST + select CPUFREQ_DT_PLATDEV + select PM_OPP + help + This adds a Rust based generic DT based cpufreq driver for frequency + management. It supports both uniprocessor (UP) and symmetric + multiprocessor (SMP) systems. + + If in doubt, say N. + config CPUFREQ_VIRT tristate "Virtual cpufreq driver" depends on GENERIC_ARCH_TOPOLOGY diff --git a/drivers/cpufreq/Makefile b/drivers/cpufreq/Makefile index d35a28dd9463..db38d1d5562d 100644 --- a/drivers/cpufreq/Makefile +++ b/drivers/cpufreq/Makefile @@ -15,6 +15,7 @@ obj-$(CONFIG_CPU_FREQ_GOV_COMMON) += cpufreq_governor.o obj-$(CONFIG_CPU_FREQ_GOV_ATTR_SET) += cpufreq_governor_attr_set.o obj-$(CONFIG_CPUFREQ_DT) += cpufreq-dt.o +obj-$(CONFIG_CPUFREQ_DT_RUST) += rcpufreq_dt.o obj-$(CONFIG_CPUFREQ_DT_PLATDEV) += cpufreq-dt-platdev.o obj-$(CONFIG_CPUFREQ_VIRT) += virtual-cpufreq.o diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs new file mode 100644 index 000000000000..62831629bd93 --- /dev/null +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust based implementation of the cpufreq-dt driver. + +use core::format_args; + +use kernel::{ + c_str, clk, cpufreq, cpumask::Cpumask, device::Device, + error::code::*, fmt, macros::vtable, module_platform_driver, of, opp, platform, prelude::*, + str::CString, sync::Arc, +}; + +// Finds exact supply name from the OF node. +fn find_supply_name_exact(dev: &Device, name: &str) -> Option { + let name_cstr = CString::try_from_fmt(fmt!("{}-supply", name)).ok()?; + + if dev.property_present(&name_cstr) { + CString::try_from_fmt(fmt!("{}", name)).ok() + } else { + None + } +} + +// Finds supply name for the CPU from DT. +fn find_supply_names(dev: &Device, cpu: u32) -> Option> { + // Try "cpu0" for older DTs. + let name = match cpu { + 0 => find_supply_name_exact(dev, "cpu0"), + _ => None, + } + .or(find_supply_name_exact(dev, "cpu"))?; + + let mut list = 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: Cpumask, + #[allow(dead_code)] + token: Option, + #[allow(dead_code)] + clk: clk::Clk, +} + +struct CPUFreqDTDriver { + _pdev: platform::Device, +} + +#[vtable] +impl opp::ConfigOps for CPUFreqDTDriver {} + +#[vtable] +impl cpufreq::Driver for CPUFreqDTDriver { + type Data = (); + type PData = Arc; + + fn init(policy: &mut cpufreq::Policy) -> Result { + let cpu = policy.cpu(); + let dev = Device::from_cpu(cpu)?; + let mut mask = Cpumask::new()?; + + mask.set(cpu); + + let token = match find_supply_names(&dev, cpu) { + Some(names) => Some( + opp::Config::::new() + .set_regulator_names(names)? + .set(&dev)?, + ), + _ => None, + }; + + // Get OPP-sharing information from "operating-points-v2" bindings. + let fallback = match opp::Table::of_sharing_cpus(&dev, &mut mask) { + Ok(()) => false, + Err(e) => { + if e != ENOENT { + return Err(e); + } + + // "operating-points-v2" not supported. If the platform hasn't + // set sharing CPUs, fallback to all CPUs share the `Policy` + // for backward compatibility. + opp::Table::sharing_cpus(&dev, &mut mask).is_err() + } + }; + + // Initialize OPP tables for all policy cpus. + // + // For platforms not using "operating-points-v2" bindings, we do this + // before updating policy cpus. Otherwise, we will end up creating + // duplicate OPPs for the CPUs. + // + // OPPs might be populated at runtime, don't fail for error here unless + // it is -EPROBE_DEFER. + let mut opp_table = match opp::Table::from_of_cpumask(&dev, &mut mask) { + Ok(table) => table, + Err(e) => { + if e == EPROBE_DEFER { + return Err(e); + } + + // The table is added dynamically ? + opp::Table::from_dev(&dev)? + } + }; + + // The OPP table must be initialized, statically or dynamically, by this point. + opp_table.opp_count()?; + + // Set sharing cpus for fallback scenario. + if fallback { + mask.set_all(); + opp_table.set_sharing_cpus(&mut mask)?; + } + + let mut transition_latency = opp_table.max_transition_latency() as u32; + if transition_latency == 0 { + transition_latency = cpufreq::ETERNAL_LATENCY; + } + + let freq_table = opp_table.to_cpufreq_table()?; + let clk = policy + .set_freq_table(freq_table.table()) + .set_dvfs_possible_from_any_cpu() + .set_suspend_freq((opp_table.suspend_freq() / 1000) as u32) + .set_transition_latency(transition_latency) + .set_clk(&dev, None)?; + + mask.copy(policy.cpus()); + + Ok(Arc::new( + CPUFreqDTDevice { + opp_table, + freq_table, + mask, + token, + clk, + }, + GFP_KERNEL, + )?) + } + + fn exit(_policy: &mut cpufreq::Policy, _data: Option) -> Result<()> { + Ok(()) + } + + fn online(_policy: &mut cpufreq::Policy) -> Result<()> { + // We did light-weight tear down earlier, nothing to do here. + Ok(()) + } + + fn offline(_policy: &mut cpufreq::Policy) -> Result<()> { + // Preserve policy->data and don't free resources on light-weight + // tear down. + Ok(()) + } + + fn suspend(policy: &mut cpufreq::Policy) -> Result<()> { + policy.generic_suspend() + } + + fn verify(data: &mut cpufreq::PolicyData) -> Result<()> { + data.generic_verify() + } + + fn target_index(policy: &mut cpufreq::Policy, index: u32) -> Result<()> { + let data = match policy.data::() { + Some(data) => data, + None => return Err(ENOENT), + }; + + let freq = data.freq_table.freq(index.try_into().unwrap())? as usize; + data.opp_table.set_rate(freq * 1000) + } + + fn get(policy: &mut cpufreq::Policy) -> Result { + policy.generic_get() + } + + fn set_boost(_policy: &mut cpufreq::Policy, _state: i32) -> Result<()> { + Ok(()) + } + + fn register_em(policy: &mut cpufreq::Policy) { + policy.register_em_opp() + } +} + +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 = (); + const OF_ID_TABLE: Option> = Some(&OF_TABLE); + + fn probe(pdev: &mut platform::Device, _id_info: Option<&Self::IdInfo>) -> Result>> { + cpufreq::Registration::::new_foreign_owned( + pdev.as_ref(), + c_str!("cpufreq-dt"), + (), + cpufreq::flags::NEED_INITIAL_FREQ_CHECK | cpufreq::flags::IS_COOLING_DEV, + true, + )?; + + pr_info!("CPUFreq DT driver registered\n"); + + let drvdata = KBox::new(Self { _pdev: pdev.clone() }, GFP_KERNEL)?; + + Ok(drvdata.into()) + } +} + +module_platform_driver! { + type: CPUFreqDTDriver, + name: "cpufreq_dt", + author: "Viresh Kumar ", + description: "Generic CPUFreq DT driver", + license: "GPL v2", +}