From patchwork Thu Feb 6 09:28:22 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 862874 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 08253227597 for ; Thu, 6 Feb 2025 09:28:57 +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=1738834139; cv=none; b=nY8y09YGQI3F/K9lQGY++BsqVTwgnX6vEMX1ynpI3C5jqG7DS0Kg8q/YFKaqmBYtKYGAFJOBthN6Du/RUAdgvim5uZlYwM1YZZHl/b5jCQmzDsAVv6hGpMfPdvYyvK1rRm00lnwAdge1hxUXJEtSsongu9twvF6nUZIYJuydC/0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834139; c=relaxed/simple; bh=Ot/T0jCd4T7tNCR433fIHwM84YOZJZy/rRbe6ZLnftM=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=ppz6MquGOBZ/k3LCfSq658Tg+hrnwq4yF5N3tmVbTfGoqsVjr5A1P0bSI8OG0z/cfrB2I4FPFfRxtSpMn/LpHSgVNR0xzQhvzhQtbUwiTjDjL/GmIbkXYtfzo1USccWEMXUxB/P62PhcAm3Spm6oNiwWVqSRJBnpRJvZf1z/ESI= 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=zUoR3pTF; 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="zUoR3pTF" Received: by mail-pl1-f174.google.com with SMTP id d9443c01a7336-21670dce0a7so16610285ad.1 for ; Thu, 06 Feb 2025 01:28:57 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834137; x=1739438937; 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=H9/+ITx7jdgxCni5rtLO0HfiqPVNFjTWeSm9ZunqSOA=; b=zUoR3pTF6YmbxQRUQ8Ws3B0zZbQMmK0CTochc8/i7A/gnubm0ADABBO9+k7MXWRqAS urZGm2dDo2ZZePeWLFvvihxJ1TYZzJZJ3HjMW5+DO27fr8/V/NtablMOmIyPK+WAMOuD 084PT5xrhzqYZMelFQWI7MTZY/unlUScwFsjzqR6k2MYKqRhr7Q/9NvJvhQGyE82J6dU 4FmZ+hDMzSoPcOy1IoFb/d9Npmy74SBGSrvoLxtoMmbda9Vb0fA83qWGT8YnODCzsF3n nKPoUKXyCjMoUpvxK4tFr1r4azrehnKIQBe/prHlKI2kNAkKN3Ba5YB78ILHlnMVw7eV 51GQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834137; x=1739438937; 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=H9/+ITx7jdgxCni5rtLO0HfiqPVNFjTWeSm9ZunqSOA=; b=c4a8BgmpEkyiCVjOC3hNyCdTJR51PpuEknUeAo5Ot3r5KdOOvZniYABSPRcghtqprA VuC0ipLCZpJ1/auwFoCPJ4Vp88LC2b1jtqOTBT3hFaqReeGwX7GROGP0gerXKIfUtzkI 0+WX4BRzGT5LyQ1ajFoLoMeDL/tHVjdI2mPMUqn/aQSWqz979ELPVfxKRrGhGjYu9lIA vp+p0/pRwHrI+PpqBmiShmUdge+yOXRAAb4YEwAVzNusUXqXr6TTTKkevunP6P7Ivh4k h3QX3UYMfMx8cgm6SNUVoRAyZQcyVf4eeMVd7KOlfKW6cmx0YAIyw4gDGf40J8iGaYj+ Bkcg== X-Forwarded-Encrypted: i=1; AJvYcCUhiV8fjG7+Q+11M9ePk9igjcCtT0lQ0q0LeNPzWjfYu/SLhoVwjN4XeRIqC/E0Mz7mpPdX82U8Ig==@vger.kernel.org X-Gm-Message-State: AOJu0YzJBcHBW4DpvKzBeVnAJ0cthQglGMdmy5sbbfxWJu3u/hhOXPLe 57ze/OsOH4KZRrJSE4sWM0RTYOV5rnSPRGEkAZakQlV5XL6Kp+klRRdnrT8rGa0= X-Gm-Gg: ASbGncuHhPsrMGQpCK9XiTl3r79VYg4/3LUBNJ0eNbiFoG1kTnUuC/FsA5192Z3FPGb 9v9zRI+jn4Zz/GansNJxo2TuX7f3/IZbzQqbRaQkfdpB/KH+GZopQh7UgL/Tdgi6T29R1GzYBO2 R8UsySJxjPErVTxsB9kgbkXYT+snvhlG7nFqQVtjF4QkKufybkh77BK8n6zU2C0ieL5IOhEbDy8 fnZ8XerGz+2ddkEujkCbr88SJlRRfGJ8vExEqFg8LNn6Wb7dupr1yKKC09sxoKWV4w++YCKPGt4 hR9QIF+/KCbRnuzZHw== X-Google-Smtp-Source: AGHT+IGJC2iQJEI3sTGW6GjKdvP/nRc87YJ1GkI47hpYxHY8P6Qy5pjuZWMZBFlY67UgbnD1fdAThg== X-Received: by 2002:a17:903:41c1:b0:21e:ff3a:7593 with SMTP id d9443c01a7336-21f17dde2d4mr80139535ad.6.1738834137385; Thu, 06 Feb 2025 01:28:57 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-21f3653b02dsm8145955ad.74.2025.02.06.01.28.56 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:28:56 -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 , Anisse Astier , linux-kernel@vger.kernel.org Subject: [PATCH V8 01/14] rust: macros: enable use of hyphens in module names Date: Thu, 6 Feb 2025 14:58:22 +0530 Message-Id: <99ca28045252ba77c302d74e57c2976e60744c4d.1738832118.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 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 '-'] Signed-off-by: Viresh Kumar --- rust/macros/module.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/rust/macros/module.rs b/rust/macros/module.rs index cdf94f4982df..2e740bbdb598 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -182,7 +182,9 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { let info = ModuleInfo::parse(&mut it); - let mut modinfo = ModInfoBuilder::new(info.name.as_ref()); + /* Rust does not allow hyphens in identifiers, use underscore instead */ + let name_identifier = info.name.replace('-', "_"); + let mut modinfo = ModInfoBuilder::new(name_identifier.as_ref()); if let Some(author) = info.author { modinfo.emit("author", &author); } @@ -298,14 +300,14 @@ mod __module_init {{ #[doc(hidden)] #[link_section = \"{initcall_section}\"] #[used] - pub static __{name}_initcall: extern \"C\" fn() -> kernel::ffi::c_int = __{name}_init; + pub static __{name_identifier}_initcall: extern \"C\" fn() -> kernel::ffi::c_int = __{name_identifier}_init; #[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 \"# ); @@ -313,7 +315,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() -> kernel::ffi::c_int {{ // 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 // placement above in the initcall section. @@ -323,12 +325,12 @@ 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` + // - furthermore it is only called after `__{name_identifier}_init` has returned `0` // (which delegates to `__init`). unsafe {{ __exit() }} }} @@ -369,6 +371,7 @@ unsafe fn __exit() {{ ", type_ = info.type_, name = info.name, + name_identifier = name_identifier, modinfo = modinfo.buffer, initcall_section = ".initcall6.init" ) From patchwork Thu Feb 6 09:28:23 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 863220 Received: from mail-pl1-f175.google.com (mail-pl1-f175.google.com [209.85.214.175]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 7415622616E for ; Thu, 6 Feb 2025 09:29:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.175 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834143; cv=none; b=P/P0HYVwUlGdBVlDQHQDu1CnVVTaY8a2L4hzzoQ1+coq3ghBWM0qcBLGIVWUi6wsafptUzsTLvEiKACSkCBN36Ufz6/0CLVQ7hkaF8jVLswKSL+Dg8ZqslgoaK0PBTI4fOsnfmvxE3kBFv5kMZuCtf24DukcZj+NJmdPWiOEadw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834143; c=relaxed/simple; bh=t2NVGvjKSZ8jGPHeqUP8byps2cHUv/LlWtK1ugt6aZ4=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=bi4ZquqiTtf2dKjpQTfyzYwZ+IWNkkBdTk9yMO/9f5/WAUFMW9V0FImfOhOaartViQGWc0Fk689YyAtdcJUSQLKCotMb6jlf72dI8wLJP7ANCK2F5StHgPNdf1Iy/vceewdUZD9Gdj7cr6HcZWxdBCXtJ1/fT8otjRKFwQfafsY= 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=QpzFPYDs; arc=none smtp.client-ip=209.85.214.175 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="QpzFPYDs" Received: by mail-pl1-f175.google.com with SMTP id d9443c01a7336-2164b662090so13687755ad.1 for ; Thu, 06 Feb 2025 01:29:01 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834141; x=1739438941; 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=IkWjr0H8S/ljloJuoBCwCDqimDzQkeaXdlPta4A4wUg=; b=QpzFPYDs5uF7AGEy9d5dgcKHK5ELcTQ8G/LPO9gDyiwUBfHK1CaceSUUG4Yzz42/AV NyQfgdK2EMYBqcKOKZbq+a5xBFf26hpPxGHLO9u63HJINmwT8Mv/tLkbmlMzEF7vgiAm ODMkzU7HNLqwfrjc8uGn+3vvqoHPDENCILq9YEdXIPy0Ixlrq1xwr0oBVuIww8b/cP0Q J+d4Qxk4XB+96S1QORQNHFOpwVxBYN6VL307QPfe9GXSO6VETUe+yj869/f+uyfj9YT3 PHkzPyeUbpmQD9e34sVKqIIuiqVxAgZlGlQW8fX2g4L0YLe3tLOEHWgxCrYntLcjGY8A 8vgw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834141; x=1739438941; 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=IkWjr0H8S/ljloJuoBCwCDqimDzQkeaXdlPta4A4wUg=; b=g75I8P0jUMdZdYAnv18qhVFJ03c+1f2Hv429ryGLBsVbKLeH4PDFqnshM/JDCx7WBU Q74e3pPm9c4HgfYo0yBIzM0DmELYwhbVCYgkw0b8qngKYY3V314oueJNYfRiyXsCb/Ar dEGSJ+8XChSLXUkD+XcbgrwORxy9ekPrF/HijpVMcNJgSW5biiwbCV2Z1W3KyXLRHXH6 UvCESNwnH5PcntJmAcDZAiDk+ie63CWzBELhItAEtgRnDEnObq0iV6+PJSGQ+2Su8IaB NMdoDtwhFej9aMZriPFVvFPM1PV8w/ng3gaRSIhmF1LuW7gu7h01bxSfFgSGOU6vQbaV HVsQ== X-Gm-Message-State: AOJu0YzPyQ0sS3G2y+f9+vT6H84Jsw3IdoJEBY5dCj815hpHCvOcm+R/ iHiL+HAJpkihQKe8q2krXhohFdDCChlUIiLwpwG1dWf5S6KuGl3kvJd9gdqx3+c= X-Gm-Gg: ASbGncvxp82EgUN9Sd4bEuXWf53G07ZIiT8zPOf49s6JqQOiQ4LkL8RzpXHZtVyBR/Z f+jJ+MIe4umPdXMldJUsU7yspCDUOFLxmY75sX4wpHNoqqyisaL1m34g0LJvp0Ybo+5lB1M4gzs s5fYjbY/48PV8vZQ6DMkDeaOXRZG77PsvThhLW1NgUaitqt+Q77nmnq2kOtCFTTR/yAc+CHemqU zqxRMNL/1jBAwO3C3Xm5YctNwPUbUPibD2Bof4TB9Voz+TjRuCTSIOdSMs5iHNit4bUKET8Vh6Z yVIk8QAjSWb2h1EvaA== X-Google-Smtp-Source: AGHT+IH1/6xK/rRw8mY8TBJIKn2KcQgONJf1mDB8CNf90rvvV01LuVGRr4XBp/OKymX25kOUJ+f8Qw== X-Received: by 2002:a17:903:244e:b0:21f:b6f:3f34 with SMTP id d9443c01a7336-21f17df36a4mr89345215ad.15.1738834140797; Thu, 06 Feb 2025 01:29:00 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-21f368bae51sm7952415ad.234.2025.02.06.01.28.59 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29: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 V8 02/14] cpufreq: Use enum for cpufreq flags that use BIT() Date: Thu, 6 Feb 2025 14:58:23 +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 The BIT() macro is too complex for Rust's bindgen to interpret as integer constants. This results in many of the cpufreq macros being undefined in Rust auto-generated bindings. By replacing the "#define" macros with an "enum", we ensure that bindgen can properly evaluate these values, enabling their seamless use in Rust code. No intentional functional impact. Suggested-by: Alice Ryhl Signed-off-by: Viresh Kumar --- include/linux/cpufreq.h | 96 ++++++++++++++++++++++------------------- 1 file changed, 51 insertions(+), 45 deletions(-) diff --git a/include/linux/cpufreq.h b/include/linux/cpufreq.h index 7fe0981a7e46..bd67728081ad 100644 --- a/include/linux/cpufreq.h +++ b/include/linux/cpufreq.h @@ -292,11 +292,12 @@ static inline void cpufreq_stats_record_transition(struct cpufreq_policy *policy * CPUFREQ DRIVER INTERFACE * *********************************************************************/ -#define CPUFREQ_RELATION_L 0 /* lowest frequency at or above target */ -#define CPUFREQ_RELATION_H 1 /* highest frequency below or at target */ -#define CPUFREQ_RELATION_C 2 /* closest frequency to target */ -/* relation flags */ -#define CPUFREQ_RELATION_E BIT(2) /* Get if possible an efficient frequency */ +enum { + CPUFREQ_RELATION_L = 0, /* lowest frequency at or above target */ + CPUFREQ_RELATION_H = BIT(0), /* highest frequency below or at target */ + CPUFREQ_RELATION_C = BIT(1), /* closest frequency to target */ + CPUFREQ_RELATION_E = BIT(2), /* Get if possible an efficient frequency */ +}; #define CPUFREQ_RELATION_LE (CPUFREQ_RELATION_L | CPUFREQ_RELATION_E) #define CPUFREQ_RELATION_HE (CPUFREQ_RELATION_H | CPUFREQ_RELATION_E) @@ -418,52 +419,57 @@ struct cpufreq_driver { /* flags */ -/* - * 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 diver if the target frequency does not change, but the policy min or max - * may have changed. - */ -#define CPUFREQ_NEED_UPDATE_LIMITS BIT(0) +enum { + /* + * 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 diver if the target frequency does + * not change, but the policy min or max may have changed. + */ + CPUFREQ_NEED_UPDATE_LIMITS = BIT(0), -/* loops_per_jiffy or other kernel "constants" aren't affected by frequency transitions */ -#define CPUFREQ_CONST_LOOPS BIT(1) + /* + * loops_per_jiffy or other kernel "constants" aren't affected by + * frequency transitions. + */ + CPUFREQ_CONST_LOOPS = BIT(1), -/* - * Set by drivers that want the core to automatically register the cpufreq - * driver as a thermal cooling device. - */ -#define CPUFREQ_IS_COOLING_DEV BIT(2) + /* + * Set by drivers that want the core to automatically register the + * cpufreq driver as a thermal cooling device. + */ + CPUFREQ_IS_COOLING_DEV = BIT(2), -/* - * This should be set by platforms having multiple clock-domains, i.e. - * supporting multiple policies. With this sysfs directories of governor would - * be created in cpu/cpu/cpufreq/ directory and so they can use the same - * governor with different tunables for different clusters. - */ -#define CPUFREQ_HAVE_GOVERNOR_PER_POLICY BIT(3) + /* + * This should be set by platforms having multiple clock-domains, i.e. + * supporting multiple policies. With this sysfs directories of governor + * would be created in cpu/cpu/cpufreq/ directory and so they can + * use the same governor with different tunables for different clusters. + */ + CPUFREQ_HAVE_GOVERNOR_PER_POLICY = BIT(3), -/* - * Driver will do POSTCHANGE notifications from outside of their ->target() - * routine and so must set cpufreq_driver->flags with this flag, so that core - * can handle them specially. - */ -#define CPUFREQ_ASYNC_NOTIFICATION BIT(4) + /* + * Driver will do POSTCHANGE notifications from outside of their + * ->target() routine and so must set cpufreq_driver->flags with this + * flag, so that core can handle them specially. + */ + CPUFREQ_ASYNC_NOTIFICATION = BIT(4), -/* - * Set by drivers which 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, we will try to set it to a freq - * from the table. And if that fails, we will stop further boot process by - * issuing a BUG_ON(). - */ -#define CPUFREQ_NEED_INITIAL_FREQ_CHECK BIT(5) + /* + * Set by drivers which 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, we will try + * to set it to a freq from the table. And if that fails, we will stop + * further boot process by issuing a BUG_ON(). + */ + CPUFREQ_NEED_INITIAL_FREQ_CHECK = BIT(5), -/* - * Set by drivers to disallow use of governors with "dynamic_switching" flag - * set. - */ -#define CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING BIT(6) + /* + * Set by drivers to disallow use of governors with "dynamic_switching" + * flag set. + */ + CPUFREQ_NO_AUTO_DYNAMIC_SWITCHING = BIT(6), +}; int cpufreq_register_driver(struct cpufreq_driver *driver_data); void cpufreq_unregister_driver(struct cpufreq_driver *driver_data); From patchwork Thu Feb 6 09:28:24 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 862873 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 86A29226167 for ; Thu, 6 Feb 2025 09:29:05 +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=1738834147; cv=none; b=QzFCtjk4nGTQOPUT1jqF4UVAXYz6EbprxtH4ic93mvrvSRuf4gyYwp+Q1bvjXvdhuGBkeyejX7fFoHzA36ay8AGVJ4FTJvKoF7FtWyCYKAgPsqvGaqj5cK4m7YHOoADoiqLuPAp8mxtjoh+byx5HV1Xotlmu7bSpQi2GZe+74+8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834147; c=relaxed/simple; bh=hNxUaqce8sjnkwzAQlWMlhW9DvX+XlFNHHx9DRtSdzs=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=jTb2IlJ/xD9Ud4ZrVShanZsF5BzCJ5ymT4aaLQpvZ/ieMW+AmJ1HTs+LbNhzqkwbzKBmRUU4T6EcS5GtAPU3/C6vrc4RGUTyWMSO1vIOAdp6DDaKXR5BsjkP4ipi8JSrrA1rH13olRqiqNtyQddLeToEvLB/KjAAi2rbzzBMD8M= 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=GJwe2eN9; 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="GJwe2eN9" Received: by mail-pl1-f173.google.com with SMTP id d9443c01a7336-21f40deb941so2739625ad.2 for ; Thu, 06 Feb 2025 01:29:05 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834145; x=1739438945; 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=2G2VXwMXVVwTjOULFIF4Y5hQffUd1BBYLZ5S5agX+0E=; b=GJwe2eN9R6OS5SV+yyTFO9EaC9rcaVkKbk1AbGKR/GRW0MAQtw/AP5VuDnq7I16ceR Gg2u92epq0vMtGdRboNkMm1AXjOKDdVqDloKntpGvuRWcPY+U7iK+/pjwxA2kkRz0r/O 2tv39HFfoHKReiXN9HkQDCiL/pOFvl/aDR1cM/t+MFUZwRJ2BiiMxDMboDzaF+77mpU4 IpY/yOdUD3lv4IRB7lEmagk+LAQ/ntV0Myk0j8bCBXKkuSROMa1Iwc4mLupSViXvG8Qp 3gzTGMAp07WeYyhYh1hZbSgYYQvd3lIIKWPNw/S57tx0ruOy0NnVAsf8Lc2hBgNuXcVp bN1A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834145; x=1739438945; 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=2G2VXwMXVVwTjOULFIF4Y5hQffUd1BBYLZ5S5agX+0E=; b=Lnrwf5SIOWGRqS9ztZpIp0pM5UgL/LT8fwVkH6iXNUulAraA8oTJaODFudvBD8EXmY pQMeiuZSsAOHZpCD2aizD3E3HwcxmAf20UZ+2ek5YHeV9da6HtphGhkkbJfF9GPwDN2+ 7J2SobCZytc+wFeq4XIyC3OqlgJiaH2k7nkOddHmk/vdIE4OW/8aYKsDgXmrJjwcFall OgJ36BZZfohDkxFynyLKe6Rn0h7dnrNSYCCIZICIDDQp4xzGSS2D3DaQEQE5VRdLu54f 92E8mqomp1OLoSVIHrAy3IxllCV1BWoX1KS8YJZS+VzObeHLS3P92I/TmOQXX6tg2fdp SrQA== X-Forwarded-Encrypted: i=1; AJvYcCVoz2OE2mw04G4I5xNDxVj6zPliBCSngTHqS4H2fWgvexa4/5rO9F/KYnnx0vfXMsVEeiZpKET4EA==@vger.kernel.org X-Gm-Message-State: AOJu0Yw2adQVmhr3lESbYf8wFYVLUc1HL7j2o9p3KO5Qv9RQcE03Knat b64Oqs7L5tJt9SKcGGiK2o0eNwzrosTrtoIDwSMG2oNbf+HxtpQUDstsHN0WXMs= X-Gm-Gg: ASbGncston+Ky5qzrKmRE3PUF6dAgFs6LrRoIKtlagdTUsxWASKbQmX8Il2I8ty18ne Au7whtSZ7H3XgKg3amtCBMUzkg1pbV8eNX05/7oY2knsGl22KFecKNuR5W94OQyhxN4A2tZ80g1 srvHmEfQ12PBSuP2jzTGtWf5C16zJWZz3DjD+9AJoKzWRQY9KLMbNJl73Hy50dizMMFWoPlZ7ZR tk2VdQfYUEwMEeLtwfDF3wpfsn81blI8tuv0U8I82b3yZ7Njf05WYhRCSV4lHBWbfm+WZusVo3f EXcSvQTKy+ytJ1pbWQ== X-Google-Smtp-Source: AGHT+IERZaH/yV6NhctlMcXLudgaGLxhDTf+gOxPascB2hUakJ8YcCEV+KZm6lvDnBVxg1aOgdZhiA== X-Received: by 2002:a17:903:8c4:b0:215:a3fd:61f5 with SMTP id d9443c01a7336-21f17dde0c8mr99801325ad.5.1738834144997; Thu, 06 Feb 2025 01:29:04 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-21f3683ddc0sm8071205ad.123.2025.02.06.01.29.04 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:04 -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 , 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 , Erik Schilling , =?utf-8?q?Alex_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [PATCH V8 03/14] rust: cpu: Add from_cpu() Date: Thu, 6 Feb 2025 14:58:24 +0530 Message-Id: <35ef3767cb9e65cb4c95df7ed50c6f3f6190066e.1738832118.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 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 | 31 +++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 4 files changed, 34 insertions(+) create mode 100644 rust/kernel/cpu.rs diff --git a/MAINTAINERS b/MAINTAINERS index 896a307fa065..ee6709599df5 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -6034,6 +6034,7 @@ F: include/linux/cpuhotplug.h F: include/linux/smpboot.h F: kernel/cpu.c F: kernel/smpboot.* +F: rust/kernel/cpu.rs CPU IDLE TIME MANAGEMENT FRAMEWORK M: "Rafael J. Wysocki" diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 55354e4dec14..fda1e0d8f376 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/kernel/cpu.rs b/rust/kernel/cpu.rs new file mode 100644 index 000000000000..3054165d3818 --- /dev/null +++ b/rust/kernel/cpu.rs @@ -0,0 +1,31 @@ +// 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 associated 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 notifier and removing +/// any references to the CPU device within the notifier's callback. +pub unsafe fn from_cpu(cpu: u32) -> Result<&'static Device> { + // 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. + let ptr = 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 496ed32b0911..415c500212dd 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -40,6 +40,7 @@ pub mod block; #[doc(hidden)] pub mod build_assert; +pub mod cpu; pub mod cred; pub mod device; pub mod device_id; From patchwork Thu Feb 6 09:28:25 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 863219 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 BD93622CBF3 for ; Thu, 6 Feb 2025 09:29:09 +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=1738834151; cv=none; b=DoWqotFypgztUnzj/dPQL0RjiS5YTfJUQuRBPCV/MTmEecZ5FAo4T7vocRgHjtcjVORwvg90+vJDVI3M7RNHNXZ0xLLo0DcKGElwMue8qLZqk+Q58RSKsGb6L6ia4AkmQ9gJhU4WosCtDqY12bdm6Q22nonnRTs8GnB0DJZTD7w= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834151; c=relaxed/simple; bh=N5KuSHGuim/2ltuf1CgPtREiUHrSzunHBtCeRYx+xXs=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=nXPK9EvMEUiLJUAXdWYMvwFNS2h17Wo73zB3dpXGz6k2n6+UkprHPR+Na7RjSSgLlyZgFF/+mTWDUHz8qq2RR29lgMc3TqsFsm3hkPN7+7d1k+WB43rUsqA/nL/tpcsxNTmkC7hXPAEbShuJszs23w55NpLlLoOBjg7VM+/7gVY= 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=sc77Q82G; 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="sc77Q82G" Received: by mail-pl1-f171.google.com with SMTP id d9443c01a7336-2163dc5155fso12915335ad.0 for ; Thu, 06 Feb 2025 01:29:09 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834149; x=1739438949; 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=mnnLlALAvod9HBe452p93Qf9oTal7xzFyAI477ScgZM=; b=sc77Q82GSplB60NLau89LR+M2b6Blb8An7/PuaqQytPQbrvV8RreaRXa3K4CrVrXwM EvLhxFhV1AjDeXHvFyCuTb8Pkysh3w1CFadPv1W8H+3NzekGaouLlP2zahkmqKNlaTAS aocz2PKJ5iJay0chM/YwdGJymhpNY6pa/fX3yB1c/r8OzDE5z8xbidnT8JsD/Y4tOcZ0 fw5yzBx4LBxBs5MWz8LbkhVHlmh1W58mbZxbx9eFutpohMhSG9VAf6MAg3YlTqb1rZ6G XEw96wB30BNF5EUVrNUk8AmNThbXy5SdEDtxvwqdQwJnraN/AGCoup7954Nxc7C/gs2X 3VhQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834149; x=1739438949; 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=mnnLlALAvod9HBe452p93Qf9oTal7xzFyAI477ScgZM=; b=j0YL+ucwLnG5d/v7ETo9RDsXHvxrbe9vAj56AEoXLMvpCxtwEEuJ6guC510fzqM9h5 NKiSkrJNTramyfyGBL5JyNzMHlsPeVmAthdD3N2fDGlAiC2zdtmbwB4x6VtUn9icWnFH /6MqQUNffPmDhXadUDrcEqIKpV9KvRsKmFPWeZ9RwPLLEFt5pifEkSNEOvKMllELjg3a AjhqsgmHv8T5AnNg1Ya3auL4ulvnurfxuTi5RixbXZfU9iXIYCobjW1Tm+VwLoOfSO6T TqM6/xtoiKttE3HUqhwbcAOVqmMphCtTGLX/f4gLrK3ZkccNIPuKkWF3pZlkZrZsQYEz cFow== X-Forwarded-Encrypted: i=1; AJvYcCWrKgF3WF9OIvURB/H4nChzKceT0k50iwLjggYslL4V3NnYgNz1Ji+7OfejMZfI5Q34G2uYuB+Gnw==@vger.kernel.org X-Gm-Message-State: AOJu0Yx2E1VX9ZtWbXRifWSMfjUjsa7IxIWWC1kRfMBb5qEdHnAY/lgM N9K6kH+MpibpjEaZN1/tbnkOIqEogJFw/8d8qgQLmojhysNCdbZxDgNuniue95A= X-Gm-Gg: ASbGncsBIwl780rmP4mXppjVilrsvXRJCOnGwO7e8lYcdki9JTgsIAIC/oE04Aosqzy nFlCmv+SVpD9BJ/tfICL4hrKXrY9+7QYH7lwxQIVRvWCoVgnOrsKjryrbED8AqOruaOgy66ylKu 1DfzPQKbltMQhxurLkjG7qSx0XkrBsAJSKjmkKxcV0QZZuQFGP2H3ajqakYmgn8A//q6co+LbbO nrg0qC/r7fUD2KgTgIu4u1JZyeXOt3Oqr6B0M/kcd5s8fCqf8sspAAAZD9Wsb9wVdgsegMUyq7p ungtzoo8wxK4jnyjOQ== X-Google-Smtp-Source: AGHT+IFhy+AgYokZxM3HWCBUPc9xYncGxlqmLNHYEWBcgsKtPNb/mhJ3KsrxJ6CgY09YEPKvYF5m8g== X-Received: by 2002:a17:902:ce87:b0:215:5ea2:6544 with SMTP id d9443c01a7336-21f17dd685bmr96867085ad.7.1738834149070; Thu, 06 Feb 2025 01:29:09 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-21f368ce622sm7994205ad.241.2025.02.06.01.29.08 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:08 -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 , Yury Norov , Rasmus Villemoes 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 V8 04/14] rust: Add cpumask helpers Date: Thu, 6 Feb 2025 14:58:25 +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 In order to prepare for adding Rust abstractions for cpumask, this patch adds cpumask helpers. Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers/cpumask.c | 40 +++++++++++++++++++++++++++++++++ rust/helpers/helpers.c | 1 + 4 files changed, 43 insertions(+) create mode 100644 rust/helpers/cpumask.c diff --git a/MAINTAINERS b/MAINTAINERS index ee6709599df5..bfc1bf2ebd77 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4021,6 +4021,7 @@ F: lib/cpumask_kunit.c F: lib/find_bit.c F: lib/find_bit_benchmark.c F: lib/test_bitmap.c +F: rust/helpers/cpumask.c F: tools/include/linux/bitfield.h F: tools/include/linux/bitmap.h F: tools/include/linux/bits.h diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index fda1e0d8f376..59b4bc49d039 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/helpers/cpumask.c b/rust/helpers/cpumask.c new file mode 100644 index 000000000000..49267ad33b3c --- /dev/null +++ b/rust/helpers/cpumask.c @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +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); +} + +void rust_helper_cpumask_setall(struct cpumask *dstp) +{ + cpumask_setall(dstp); +} + +unsigned int rust_helper_cpumask_weight(struct cpumask *srcp) +{ + return cpumask_weight(srcp); +} + +void rust_helper_cpumask_copy(struct cpumask *dstp, const struct cpumask *srcp) +{ + cpumask_copy(dstp, srcp); +} + +bool rust_helper_zalloc_cpumask_var(cpumask_var_t *mask, gfp_t flags) +{ + return zalloc_cpumask_var(mask, flags); +} + +#ifndef CONFIG_CPUMASK_OFFSTACK +void rust_helper_free_cpumask_var(cpumask_var_t mask) +{ + free_cpumask_var(mask); +} +#endif diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 0640b7e115be..de2341cfd917 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 "cpumask.c" #include "cred.c" #include "device.c" #include "err.c" From patchwork Thu Feb 6 09:28:26 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 862872 Received: from mail-pj1-f52.google.com (mail-pj1-f52.google.com [209.85.216.52]) (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 CB59422DF8F for ; Thu, 6 Feb 2025 09:29:13 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.52 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834155; cv=none; b=bgx05FVPA/18e7GBokReir45y5DPB4OVR9pCWUwHkCT5k+8a+nsaC8+xniIekrn5cqYf3vdkJ8C6sGVMF5oBmH5U0X9rZl9SJz4EitFahjv1SxDL7cEQr1ZuuTtHhrCzay8A+N7XjryHoDslIvXrQT0bmETxsHlZ9Gu9LKjpmLg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834155; c=relaxed/simple; bh=MHUCeyWGdx4+O3tnwVilY3SO1wVVguCwKtOWnA285dU=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=abTuM/XKJs8OXNOCIVeQet/EXhx+7E4mMW4QaHpb/nZKIw7JyaVRxVF+iW+CJRarbpBUOgpQbEbvLjOVFXhaCRzyTPlGmRH/a8dYCFKbIGNz1Vl9zIKHQAA5OvWqqODM/EpkUU0+kHBydijLX1yoUsR1BBNUbHvCHtqTxLBtPbA= 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=o42qFJG6; arc=none smtp.client-ip=209.85.216.52 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="o42qFJG6" Received: by mail-pj1-f52.google.com with SMTP id 98e67ed59e1d1-2f9bd7c480eso1223443a91.1 for ; Thu, 06 Feb 2025 01:29:13 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834153; x=1739438953; 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=rVs26K7IXsmnaOMuPyO8w7b9kowAGAQ924n9Jrfg/D0=; b=o42qFJG6IeOO+/its2C7fFn34N1uoc3D2vfglSSmlHbkOiJfwBw9ncik9C0/CzAazY axzbpqxFevsWvSLAFSlxa5qd0xGaU6ds+rmAEKO5LTdmwdmCVyLLpjf/J0qIGj+n0x9+ BB6AlQ21KGMiccn89K3dIEu5i8cljCGyONXVisCuv5nBBkxymLUxMGmW7UMYxxQTBbrY mvUzEGSN1PU7/+PE8CD6Gi3uRimsAvdNe1RyutkyeAnrORvmmn/TqWsAJFoitORlPVf3 nVqhmZaForxUY8xjr4peswh/grWR1TRa1ceQBgHwOde82fXMpZuJhvBMbCqfqzgCjc04 Z1LA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834153; x=1739438953; 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=rVs26K7IXsmnaOMuPyO8w7b9kowAGAQ924n9Jrfg/D0=; b=Wor0TZAw1Pn9suUAuzwnOeLOZl7973D/FC+OWWBN60wjxSOvMn9oF4Aj2PqHU6vguT Dj9EqIkmVt1JBQU91d0cg+7FZ7uFwr9uijsl7q0rFmIlOsyOHAteivnJc7J4aT/xWvrH 5TXL0DTeMgiwApNrTJY0Sz531B64WUbkFni1ZT2P394p6IlEcMdXlYMrTojkdjcFYN7l HT46tiCo6jkfeXJOziDQ0gFAhfjzeqxE48uh+AX03pl0IBIy91S8jyqgMs9N1m6lx/AG vtXstC/SN3BCfpjFui3uOX3DE1bItEt7CRX5HhGJXZBDimKDHwP4584YQ9orkCyo9/+4 jn1Q== X-Forwarded-Encrypted: i=1; AJvYcCWCggwzcZSGn3cDZlCCpiJYMNBYGsK7BhlmHSI6VsVvTyaKpZ14yWWfJi7Y84sb2wUIHoteGsL84Q==@vger.kernel.org X-Gm-Message-State: AOJu0Yy7eN0xr1XUo8m/8ToMhQ45qC4zIhr6TMAzjLrLnVWhGsruEMV1 170S4dkTCVCb04RIDU2FGlJIFmHDe8rOXcyu8FZV7N0xHwIQmwUju3BMRDXtEq0= X-Gm-Gg: ASbGncsRIRA5owCGcpKfgVreJAAJuuDCACcgkkpaVwjtBK591VsovWOxvRTCCSEPWOm /T47DS1GblwsZVeFYISYg2L12Hk5pCVhFU/a5DTDW5I/x/WZfXVh9dN7LTSBbhihRgF09ChkiUD wLDVZGlZxruuBv/Or0ZtzWDA/HM1nuALyoUtD71esuaQEy0QMSnPV5T0E0DATqCklvlfBwXn79f Un9ZBF6hc4lxTVYbAxmH69xe8M0hx6vNgPePxioaa/jkKmu+pE8GSA+eRaODg+OzzlSNRwnLsjn szqkiwq4LR8rHIaAuw== X-Google-Smtp-Source: AGHT+IGnyPwyaOO7/lgpcYGVnoHbX60CW7ZMAJ7F4lxcsN/sc25hvQOSIHnC4nQu7UJd993EFWvnJQ== X-Received: by 2002:a17:90b:5109:b0:2ee:b0b0:8e02 with SMTP id 98e67ed59e1d1-2f9e080f2femr9401731a91.28.1738834152989; Thu, 06 Feb 2025 01:29:12 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-2fa09a1848asm889701a91.12.2025.02.06.01.29.12 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:12 -0800 (PST) From: Viresh Kumar To: "Rafael J. Wysocki" , Miguel Ojeda , Danilo Krummrich , Yury Norov , Rasmus Villemoes , 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 V8 05/14] rust: Add bindings for cpumask Date: Thu, 6 Feb 2025 14:58:26 +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 patch adds basic Rust bindings for struct cpumask. These will be used by Rust based cpufreq / OPP core. Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/kernel/cpumask.rs | 138 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 140 insertions(+) create mode 100644 rust/kernel/cpumask.rs diff --git a/MAINTAINERS b/MAINTAINERS index bfc1bf2ebd77..ff4511914e0a 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4022,6 +4022,7 @@ F: lib/find_bit.c F: lib/find_bit_benchmark.c F: lib/test_bitmap.c F: rust/helpers/cpumask.c +F: rust/kernel/cpumask.rs F: tools/include/linux/bitfield.h F: tools/include/linux/bitmap.h F: tools/include/linux/bits.h diff --git a/rust/kernel/cpumask.rs b/rust/kernel/cpumask.rs new file mode 100644 index 000000000000..b0be8c75a2c2 --- /dev/null +++ b/rust/kernel/cpumask.rs @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! CPU mask abstractions. +//! +//! C header: [`include/linux/cpumask.h`](srctree/include/linux/cpumask.h) + +use crate::{bindings, error::Result, prelude::ENOMEM}; + +#[cfg(not(CONFIG_CPUMASK_OFFSTACK))] +use crate::prelude::{KBox, GFP_KERNEL}; + +#[cfg(CONFIG_CPUMASK_OFFSTACK)] +use core::ptr; + +/// A simple implementation of `struct cpumask` from the C code. +pub struct Cpumask { + ptr: *mut bindings::cpumask, + owned: bool, +} + +impl Cpumask { + /// Creates empty cpumask. + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + pub fn new() -> Result { + let mut ptr: *mut bindings::cpumask = ptr::null_mut(); + + // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it + // is always safe to call this method. + if !unsafe { bindings::zalloc_cpumask_var(&mut ptr, bindings::GFP_KERNEL) } { + return Err(ENOMEM); + } + + Ok(Self { ptr, owned: true }) + } + + /// Creates empty cpumask. + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + pub fn new() -> Result { + let ptr = KBox::into_raw(KBox::new([bindings::cpumask::default(); 1], GFP_KERNEL)?); + + // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it + // is always safe to call this method. + if !unsafe { bindings::zalloc_cpumask_var(ptr, bindings::GFP_KERNEL) } { + return Err(ENOMEM); + } + + Ok(Self { + ptr: ptr as *mut _, + owned: true, + }) + } + + /// Creates a new abstraction instance of an existing `struct cpumask` pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid, and non-null. + #[cfg(CONFIG_CPUMASK_OFFSTACK)] + pub unsafe fn get_cpumask(ptr: &mut *mut bindings::cpumask) -> Self { + Self { + ptr: *ptr, + owned: false, + } + } + + /// Creates a new abstraction instance of an existing `struct cpumask` pointer. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid, and non-null. + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + pub unsafe fn get_cpumask(ptr: &mut bindings::cpumask_var_t) -> Self { + Self { + ptr: ptr as *mut _, + owned: false, + } + } + + /// Obtain the raw `struct cpumask *`. + pub fn as_raw(&mut self) -> *mut bindings::cpumask { + self.ptr + } + + /// Sets CPU in the cpumask. + /// + /// Update the cpumask with a single CPU. + pub fn set(&mut self, cpu: u32) { + // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to + // call `cpumask_set_cpus()` for any CPU. + unsafe { bindings::cpumask_set_cpu(cpu, self.ptr) }; + } + + /// Clears CPU in the cpumask. + /// + /// Update the cpumask with a single CPU. + pub fn clear(&mut self, cpu: i32) { + // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to + // call `cpumask_clear_cpu()` for any CPU. + unsafe { bindings::cpumask_clear_cpu(cpu, self.ptr) }; + } + + /// Sets all CPUs in the cpumask. + pub fn set_all(&mut self) { + // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to + // call `cpumask_setall()`. + unsafe { bindings::cpumask_setall(self.ptr) }; + } + + /// Gets weight of a cpumask. + pub fn weight(&self) -> u32 { + // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to + // call `cpumask_weight()`. + unsafe { bindings::cpumask_weight(self.ptr) } + } + + /// Copies cpumask. + pub fn copy(&self, dstp: &mut Self) { + // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe to + // call `cpumask_copy()`. + unsafe { bindings::cpumask_copy(dstp.as_raw(), self.ptr) }; + } +} + +impl Drop for Cpumask { + fn drop(&mut self) { + if self.owned { + // SAFETY: `ptr` is guaranteed to be valid for the lifetime of `self`. And it is safe + // to call `free_cpumask_var()`. + unsafe { bindings::free_cpumask_var(self.ptr) } + + #[cfg(not(CONFIG_CPUMASK_OFFSTACK))] + // SAFETY: The pointer was earlier initialized from the result of `KBox::into_raw()`. + unsafe { + drop(KBox::from_raw(self.ptr)) + }; + } + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 415c500212dd..ccbf7fa087a0 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -41,6 +41,7 @@ #[doc(hidden)] pub mod build_assert; pub mod cpu; +pub mod cpumask; pub mod cred; pub mod device; pub mod device_id; From patchwork Thu Feb 6 09:28:27 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 863218 Received: from mail-pl1-f177.google.com (mail-pl1-f177.google.com [209.85.214.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 CABA322DFB6 for ; Thu, 6 Feb 2025 09:29:17 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.177 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834159; cv=none; b=Bs/MzYx7QuyX23+XSHv3wZ+FXLxx2ecGWtG/mmxprVe7dPlYUj3x5pACp2R5uNT8TjInb4WNQKwJNKjGvJdH1vde1XBuWbec7+G9XJNo3dhwzmcfbzJKkLEC+JmRMwODXaLMIMKX1AyRXgmHerNKtvh91zhWpwAkMWj85U6lVzI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834159; c=relaxed/simple; bh=3cYUP4ZgznWOZmDbqnOVZhRLIIwxzB7xzdnixIMBEUE=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=XX2pTf+Of58NEP5e7IdsH9v6paXzBv5y0LhL2B/UYIQfb4sGxeEugHsGX8YBGYukhTSaxjNOf9nnghceMKkeJzuEoEme+e1gHzxGzdF8kgFDE5rNpwtdmQx7lWVWWyhLCW6mpjumoTUDh8BlTR+iyDu13cdk7f/6bAMxEEaOiEE= 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=ldcr8WEo; arc=none smtp.client-ip=209.85.214.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="ldcr8WEo" Received: by mail-pl1-f177.google.com with SMTP id d9443c01a7336-21670dce0a7so16617765ad.1 for ; Thu, 06 Feb 2025 01:29:17 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834157; x=1739438957; 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=X0B68fWX1cr1APKh0mAnlDXaXZbPEk2ia+lGAswFIw0=; b=ldcr8WEos3NDA7dj1Oeid0prRSIBJF9qx3xZabZ46t62pnQzRJrlneNzKQ1S3x4Kej GD29HX29Pp5ZeoeAHJgZuIx3HtwH9ejufb3UDfzcn9+vRV99zRYqNAxuafPbzNbkBZTE lr3CmhMWRNp64M9xuTN5sAAURXygFppkwFjSGUDC++BXUZUc34UaRhPDfS4/2VRfrJs/ 0hZMdmgYZ3WS+YEwzS+E09ua6+w9wkzWjvHIb0SCfye221+5N2pUOWkLWG6dJIM0fZuz fkD4DhvL5veiE7m9dbFmzubHpRSQV4uFa4vAECPsw1Y1CQ+pd6XpGzvrWgTN5hKhNO7X QQpw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834157; x=1739438957; 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=X0B68fWX1cr1APKh0mAnlDXaXZbPEk2ia+lGAswFIw0=; b=i863SUBobEx+8er5lwZXbFk73gn6w0dUyYLXl+Knn+VEdS7BETjdhMv9jbsAQ66EGf tmK1RV6RfS6YxhoajLaJNkTNa6Azzh5DT2/9HC6aI/EGXvTIXrvTDms03+eA+wjm2KJy 86B19qMAWqjxiXFgWRVeKvzAwaMvqVCrS/s+SspqXJKm4ouFZLOu5ue2Ka/1jb5HIpnS yobrOgRpyJIblYJkSPG2I8ek/Y3VTmzQel52Pc9FmbJoBom98ismWpkTPa702P+Bj2ur TkJFvt2LTiHr2T2ERhBbe4IE1W+mnIMovzz35LX2drrg8iXr3PNQlC/TeZjO8+AkTMoj bVDQ== X-Forwarded-Encrypted: i=1; AJvYcCWl6YXsJ6IcVKuC89y4X0yoz1ho4i7e3kuhkO64eHUmW998GHbBbHaLA7obFzSW7hX+dWOmtaJ1og==@vger.kernel.org X-Gm-Message-State: AOJu0YwaGJnwhWet/ey7h+QRE9rqX1b3alhWMwkN6q+Glhd81LKxZ4pH MrHwAFl+YQuAGsT3Ny6K60a8OwwSJ2mSPrg+p29rUojfEu1W1ua0yuCcs+GJX3U= X-Gm-Gg: ASbGncstq/x00sLzAHMfQNKiHebWZ+BZmYWYEs3eB38kG2iYu4fXI5ry7YOXdoLNPBP T08ex/9DzLVtcqroJcju/+ufTHzAlgGRHLEky8wNJj9jQoB4CrqMIf0TtM1ZUdhjcp37cRoGjEG cpgS/y7eJsNTmCnRK2x2OwbtCrgl0llNzWgfBc123g506UhIWytw1AguYMSY86/zPKUY5DA8RAJ VAyCwFtFLrhJYkkjEYCtSewYVZYaOvaWgym2X2+VqoQbhSqkN6+qT8hYFFg3J0R1RHPeUPVmIsn iMk6kq/5R5L9UakM4w== X-Google-Smtp-Source: AGHT+IElDAOxzrGahKe43tZNe0gD8sTNEOXo/yB4R0zYTSZc3KLuS4C5s8EHFmMR+PrUabkKHjkhcg== X-Received: by 2002:a17:902:ec87:b0:216:5e6e:68cb with SMTP id d9443c01a7336-21f17df5c3amr101820155ad.16.1738834157071; Thu, 06 Feb 2025 01:29:17 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-21f3653baa8sm8255655ad.73.2025.02.06.01.29.16 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:16 -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 , Michael Turquette , Stephen Boyd Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , 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, linux-clk@vger.kernel.org Subject: [PATCH V8 06/14] rust: Add bare minimal bindings for clk framework Date: Thu, 6 Feb 2025 14:58:27 +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. These will be used by Rust based cpufreq / OPP core to begin with. Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/clk.rs | 48 +++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 ++ 4 files changed, 52 insertions(+) create mode 100644 rust/kernel/clk.rs diff --git a/MAINTAINERS b/MAINTAINERS index ff4511914e0a..604717065476 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5780,6 +5780,7 @@ F: include/dt-bindings/clock/ F: include/linux/clk-pr* F: include/linux/clk/ F: include/linux/of_clk.h +F: rust/kernel/clk.rs X: drivers/clk/clkdev.c COMMON INTERNET FILE SYSTEM CLIENT (CIFS and SMB3) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 59b4bc49d039..4eadcf645df0 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/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 ccbf7fa087a0..77d3b1f82154 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -40,6 +40,8 @@ pub mod block; #[doc(hidden)] pub mod build_assert; +#[cfg(CONFIG_COMMON_CLK)] +pub mod clk; pub mod cpu; pub mod cpumask; pub mod cred; From patchwork Thu Feb 6 09:28:28 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 862871 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 A063A22E40A for ; Thu, 6 Feb 2025 09:29:21 +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=1738834163; cv=none; b=p0vDt6/jy8sfd8UZbITjBmQEjxNTn4HezH4o1bpIkAQKv4pTzwbPlHX98EOexDwe1rfUoeDPciQSlJw+8wMIgny5JwgyDpUtl8Zg7/zdQzYi6UvtFDPE6r/stDd8uU4/bjwkdgkB4Y7A4Ws3hYnVHS9ZUIl80hWNj52KK/1xHoY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834163; c=relaxed/simple; bh=bPUupsLrIu41ca6hGCG0wALTX0HU8RTO1Tyl+R7nuzo=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=SIXy9rjuVi5ZmOpDPA6g1uuTKL4NBs2CBKff72nrTEkYx65f6tmamkDxORdBkS+R8rhY7R5Idp10S6btW9QgxJ3iVXIPq9NO3LPRlbklKNvZQO4FxZu3mIhjXPjoN2XIihs4Y18WN7i4N04zsEjKa6MEoLTGU5VSVu1aZEhmlLI= 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=Lm/Ns4dq; 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="Lm/Ns4dq" Received: by mail-pl1-f174.google.com with SMTP id d9443c01a7336-2166651f752so15132235ad.3 for ; Thu, 06 Feb 2025 01:29:21 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834161; x=1739438961; 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=HLPBv8n1rYnynPBOyeV9rCbHyxpotow0FwOsn2TAncA=; b=Lm/Ns4dqsdB0dwgmSg5i7fTwR1O77q6JMtlOemIy4E00l+8/rslXGF1rIEFbPKIFMD 9CcKieC9aVMCc7EGh/u/JjAJjcZOoU65gadeWqDcsznN+MOjSg73doSVZsLmSsqYYfDz MokEPus3IJJVqWMvVoLi3UT0O8iTHstSmxy7srtg0S/nH1zgxk+ofb6/q/vejKhLz607 51SvoZM6LN+EGAsnFUzz4eiSyLFzEXutABBMbBWiM+i0+eLRVXvdFtMozOmHauf8meeE ssWe45iTMaD79xLZgxFrBTBiSynxf2/+ukBWOCDlxL7dUoDW7sxYdwLYVelM1MY8HwFx Uj0g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834161; x=1739438961; 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=HLPBv8n1rYnynPBOyeV9rCbHyxpotow0FwOsn2TAncA=; b=G4UarX7aKta8UX3DFqaupfz1WsveJaIJp1m1+4EEnjVIXlOlAUbmfZGUo3gGOwJOms 4LjwdMxmVK2bh5oBXUlChfbiiyMcFOSVTw/oCDxwFD8NMwsi5djWs7enGCLC5305WdOn W2sQegimbVTP48yeuR/1aUnc055TAXySdJg+Z9FyQ6MhXL0dOC3ERGrWndgNs1MO2QM3 jkEyP+9mcuSYE4+EGFB+eNaHRPnrsjQXwnKM3m3QLIU/K+oK3yoasOTBd/MilhNAffGg Qk/xFmTZ42ITRkS8K6/csA7fket0rdktcZO6oJHO4t5Cy12+lbHYWoAiqO/cw+Bg+oxn Srog== X-Forwarded-Encrypted: i=1; AJvYcCWOTQgpRjMidhQvPM+r2DyBe/VaiowVARaSJSKEJpwJf9GHrkOS1cDsjeSoFhJdi5J3F7hC2L27dQ==@vger.kernel.org X-Gm-Message-State: AOJu0YytZgVzzVN242qo5xtfQhM1SeIEVYzOTqjTr9xDojVG5VYADlKf 91vPWKEcE8vpemsLVSagYBZRVan8AB1QHNmouZcXq8TXn1U+3DTxKOLtcKVqGH8= X-Gm-Gg: ASbGncsP16RJd3dCLaMvP3IqkSXPZaQsRwlF7jsqEvAXGHdgkrbT0JYGwwmocJ4yxvo yubdXdSr8LvAdJmUtN9jHN/hBiV2p4rKP04lMRDh6noV6/rfPJfbhNa3nkLVHsaTAveE/2/OeVz dfPZeHvozWJuTx5BvhT/hQdPL5bUQiSVMIDiBRzZd7LLJxVD4jyv6pFcP6nExvAvE88gWpocY0Y uwVn/6IdatoXlNgV3l2Gw6SPv2ltwm+VaXeRpb15/wlodv1PpXwrdWqeQbOBqkypmfgdOc41dHS 0o7jv4MbKf3FtjaA8w== X-Google-Smtp-Source: AGHT+IE/W0NhCGRwbtqLAwKKUgdYRFcvvn5hRH/Tb4ko9jZOCyaNyJuBFvVBTRIS/Hx2rkjxNWoO9g== X-Received: by 2002:a17:902:fc86:b0:215:5625:885b with SMTP id d9443c01a7336-21f17edb780mr104861365ad.52.1738834161000; Thu, 06 Feb 2025 01:29:21 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-21f368aac7fsm8129745ad.221.2025.02.06.01.29.20 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:20 -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 , Nishanth Menon , Stephen Boyd Cc: Viresh Kumar , linux-pm@vger.kernel.org, Vincent Guittot , rust-for-linux@vger.kernel.org, Manos Pitsidianakis , Erik Schilling , =?utf-8?q?Alex_Benn=C3=A9e?= , Joakim Bech , Rob Herring , linux-kernel@vger.kernel.org Subject: [PATCH V8 07/14] rust: Add initial bindings for OPP framework Date: Thu, 6 Feb 2025 14:58:28 +0530 Message-Id: <62c57b517a3503dee94f83f3fc284d69fb65ca1a.1738832119.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This commit adds initial Rust bindings for the Operating performance points (OPP) core. This adds bindings for struct dev_pm_opp and struct dev_pm_opp_data to begin with. Reviewed-by: Manos Pitsidianakis Signed-off-by: Viresh Kumar --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 2 + rust/kernel/opp.rs | 189 ++++++++++++++++++++++++++++++++ 4 files changed, 193 insertions(+) create mode 100644 rust/kernel/opp.rs diff --git a/MAINTAINERS b/MAINTAINERS index 604717065476..cda0d2b74e29 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -17732,6 +17732,7 @@ F: Documentation/devicetree/bindings/opp/ F: Documentation/power/opp.rst F: drivers/opp/ F: include/linux/pm_opp.h +F: rust/kernel/opp.rs OPL4 DRIVER M: Clemens Ladisch diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 4eadcf645df0..7f851d5907af 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 77d3b1f82154..8956f78a2805 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -64,6 +64,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..becb33880c92 --- /dev/null +++ b/rust/kernel/opp.rs @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Operating performance points. +//! +//! This module provides bindings for interacting with the OPP subsystem. +//! +//! C header: [`include/linux/pm_opp.h`](srctree/include/linux/pm_opp.h) + +use crate::{ + bindings, + device::Device, + error::{code::*, to_result, Result}, + types::{ARef, AlwaysRefCounted, Opaque}, +}; + +use core::ptr; + +/// Dynamically created Operating performance point (OPP). +pub struct Token { + dev: ARef, + freq: usize, +} + +impl Token { + /// Adds an OPP dynamically. + pub fn new(dev: &ARef, mut data: Data) -> Result { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { bindings::dev_pm_opp_add_dynamic(dev.as_raw(), &mut data.0) })?; + Ok(Self { + dev: dev.clone(), + freq: data.freq(), + }) + } +} + +impl Drop for Token { + fn drop(&mut self) { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_remove(self.dev.as_raw(), self.freq) }; + } +} + +/// Equivalent to `struct dev_pm_opp_data` in the C Code. +#[repr(transparent)] +pub struct Data(bindings::dev_pm_opp_data); + +impl Data { + /// Creates new instance of [`Data`]. + pub fn new(freq: usize, u_volt: usize, level: u32, turbo: bool) -> Self { + Self(bindings::dev_pm_opp_data { + turbo, + freq, + u_volt, + level, + }) + } + + /// Adds an OPP dynamically. The OPP is freed once the [`Token`] gets freed. + pub fn add_opp(self, dev: &ARef) -> Result { + Token::new(dev, self) + } + + fn freq(&self) -> usize { + self.0.freq + } +} + +/// Operating performance point (OPP). +/// +/// Wraps the kernel's `struct dev_pm_opp`. +/// +/// The pointer to `struct dev_pm_opp` is non-null and valid for the lifetime of the `OPP` +/// instance. +/// +/// # Invariants +/// +/// Instances of this type are reference-counted. The reference count is incremented by the +/// `dev_pm_opp_get()` function and decremented by `dev_pm_opp_put`. The Rust type `ARef` +/// represents a pointer that owns a reference count on the OPP. +/// +/// A reference to the `OPP`, `&OPP` isn't refcounted by the Rust code. + +#[repr(transparent)] +pub struct OPP(Opaque); + +// SAFETY: It's OK to send the ownership of `OPP` across thread boundaries. +unsafe impl Send for OPP {} + +// SAFETY: It's OK to access `OPP` through shared references from other threads because we're +// either accessing properties that don't change or that are properly synchronised by C code. +unsafe impl Sync for OPP {} + +// SAFETY: The type invariants guarantee that [`OPP`] is always refcounted. +unsafe impl AlwaysRefCounted for OPP { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference means that the refcount is nonzero. + unsafe { bindings::dev_pm_opp_get(self.0.get()) }; + } + + unsafe fn dec_ref(obj: ptr::NonNull) { + // SAFETY: The safety requirements guarantee that the refcount is nonzero. + unsafe { bindings::dev_pm_opp_put(obj.cast().as_ptr()) } + } +} + +impl OPP { + /// Creates an owned reference to a [`OPP`] from a valid pointer. + /// + /// The refcount is incremented by the C code and will be decremented by `dec_ref()` when the + /// ARef object is dropped. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and the OPP's refcount is incremented. The + /// caller must also ensure that it doesn't explicitly drop the refcount of the OPP, as the + /// returned ARef object takes over the refcount increment on the underlying object and the + /// same will be dropped along with it. + pub unsafe fn from_raw_opp_owned(ptr: *mut bindings::dev_pm_opp) -> Result> { + let ptr = ptr::NonNull::new(ptr).ok_or(ENODEV)?; + + // SAFETY: The safety requirements guarantee the validity of the pointer. + Ok(unsafe { ARef::from_raw(ptr.cast()) }) + } + + /// Creates a reference to a [`OPP`] from a valid pointer. + /// + /// The refcount is not updated by the Rust API unless the returned reference is converted to + /// an ARef object. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` is valid and remains valid for the duration of 'a. + pub unsafe fn from_raw_opp<'a>(ptr: *mut bindings::dev_pm_opp) -> Result<&'a Self> { + // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the + // duration of 'a. The cast is okay because `OPP` is `repr(transparent)`. + Ok(unsafe { &*ptr.cast() }) + } + + #[inline] + fn as_raw(&self) -> *mut bindings::dev_pm_opp { + self.0.get() + } + + /// Returns the frequency of an OPP. + pub fn freq(&self, index: Option) -> usize { + let index = index.unwrap_or(0); + + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_freq_indexed(self.as_raw(), index) } + } + + /// Returns the voltage of an OPP. + pub fn voltage(&self) -> usize { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_voltage(self.as_raw()) } + } + + /// Returns the level of an OPP. + pub fn level(&self) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_level(self.as_raw()) } + } + + /// Returns the power of an OPP. + pub fn power(&self) -> usize { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_power(self.as_raw()) } + } + + /// Returns the required pstate of an OPP. + pub fn required_pstate(&self, index: u32) -> u32 { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_get_required_pstate(self.as_raw(), index) } + } + + /// Returns true if the OPP is turbo. + pub fn is_turbo(&self) -> bool { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it. + unsafe { bindings::dev_pm_opp_is_turbo(self.as_raw()) } + } +} From patchwork Thu Feb 6 09:28:29 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 863217 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 5C06D22F149 for ; Thu, 6 Feb 2025 09:29:25 +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=1738834167; cv=none; b=egKkEVDVdDg/JomMUpRu3C881koDxb4Lp2yomp7+DzAei1JOKsD/ce90EIk4CYo5HQILaer5JBeJeCiaxzcJPrYp9tSMt3cQtfCkACgHTYN53741BdEK37ZqqEvKSloL0uDoy7S4KMiUSVlXWS+QV1s0d3kBJe7exQvP25jcRHs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834167; c=relaxed/simple; bh=Oa2XFgSHeunQUvvePEymJCrKZVVgYdxYRhH8wlmfyPc=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=H+5pxn2ZNWdJ9hV/Jh4P09fShL+kNYixsMcEE26UJnOUrMpqZKK6x5Ngc+kfwUtEjKw4ENY9ZB9HezVoLfucqM9YrW0GpO7TZhvIvRcNxOJbdsYM1T/b5oZArU0lGj2O0yYrBxz2w1iLVUDJuCjvPQuw3AeH1RzLG7PMKp2cHtI= 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=pHageWcl; 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="pHageWcl" Received: by mail-pl1-f173.google.com with SMTP id d9443c01a7336-21670dce0a7so16619935ad.1 for ; Thu, 06 Feb 2025 01:29:25 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834165; x=1739438965; 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=2le/vHJEXggx9Bs0rUuIVJtSrtEWf3xR+mhgiTrMzXc=; b=pHageWcll7aCohUppAziwRtNXQcE21aWQxRVk+lBHK4jvrRbkJHQ1Ek8HxtHNU/uKm oY2oHUSfe4mdlSFyCnPvy7v8wq9cEnnSiLCMf2eGR+T7X987EcVxXkRg5hGwWcGMbFn6 qwVrGJBqrgbvL/hrqAVQQRlurr7DGbnArZb8r7ANVSKuMWFzOal4w7UH30nqmo2u8Yfg pwJRdf4gbLwNmVHAeMYzwTJ9uMUthFH5DSqD4+DrLYe3Roct8g3CNfzUSiSn3VHNvfAr igLVMPQKc9VG1i4X8g9LyyoEZg9hmNwJDOr5KO1MuSexFKHLXnDTK8NNWA+EXPH6vyuW MqsQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834165; x=1739438965; 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=2le/vHJEXggx9Bs0rUuIVJtSrtEWf3xR+mhgiTrMzXc=; b=hRDiQPpIG8JHAnRnJjQ8WTdEqUT/G+IDLgPN3hLk0aphz7TRvn+4zIR9RGqmABcJMg zEBC2fzuU3o3e4W704egYmRWCoiMDYKQHPMEtGOFt0l5GztwriTyy3sKzsn1pv3hqzn3 UufGvMH3iDFITRNvagxcxY1D0MHZL7Yv5ihkhSeyNMdn4CpD6UPo5qj8xSy8iJmwEMZU 3dCMs7ORWNikUnH1WoVCfYNOxoOk7ipVvLrC6zzUjbYRt4zKT9uZN0tSzD8PBbKHp5ZB 3gelzZQJ1/wrC8a/seY45VOc8RLuESiAX3AKe8WCo9VzPs2x7QJq0wVjvZbdDcH4AYVh fHFw== X-Forwarded-Encrypted: i=1; AJvYcCV/ComewlOFz96sw+uoOwDYPFE0AUXyjZ2XXFlWkL2cTmPGvmgDeruKfyhOf29ifGC/mDIUqMSlRw==@vger.kernel.org X-Gm-Message-State: AOJu0YyeZG9i2S9/tJfs0eQ9vsf2fxvYo+lGeMDVi3ZGTafIvHBodX3i 10wakiRVpBhAGYGBmLMZUGPYQX/gXakOLRuL7FIYrivzXf9ki8FRiR8c2HI9u7c= X-Gm-Gg: ASbGncto3Dda+EYiMsK8dv6cXM5kzyZ1U++yYRvuKJrU54AdaYDT0+YVRkzNy6dvMu9 67QzFeCB6IeHyDR0Bx/nTWFsPFKeks0Z1e4XCFvfwif4hu1Ht/cwz4adHiMg1Ytfk2n1a/9c+Hb 3c7F76+zB8PwSx+eVBo93djGOi6vvU55cMATiuJtCmmqMbWBt7uADeDUhoAp2KHdW3tV3OxNo0f hTLSrR7b9/L3p/qdNArp2iZy4ZZOXnvcGVGy89H4PgdxM/r8L9qmUo5cqHgf2kx114Wz2o9xOO0 l9PfYXfz9TndhNsGjA== X-Google-Smtp-Source: AGHT+IE8FkDTE8Y0kYGkWDg9FsTO+r75g3OEwtTMrWsDV3pD2JpFL7oND4Nj0xfIcPFIIU2ypRG81w== X-Received: by 2002:a17:902:f54b:b0:21f:1553:12b5 with SMTP id d9443c01a7336-21f17ec7bcemr112589125ad.36.1738834164608; Thu, 06 Feb 2025 01:29:24 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-21f3650cde8sm8291475ad.45.2025.02.06.01.29.23 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:24 -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 V8 08/14] rust: Extend OPP bindings for the OPP table Date: Thu, 6 Feb 2025 14:58:29 +0530 Message-Id: <3be7d783c3447cc62725fdd9fbd6d34166c796cb.1738832119.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This extends OPP bindings with the bindings for the 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..c0daeadfb188 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: &Device) -> 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.into(), + 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: &Device, 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(all(CONFIG_OF, CONFIG_ENERGY_MODEL))] + 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)] + { + #[cfg(CONFIG_ENERGY_MODEL)] + 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 Thu Feb 6 09:28:30 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 862870 Received: from mail-pl1-f175.google.com (mail-pl1-f175.google.com [209.85.214.175]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C6C7822F16A for ; Thu, 6 Feb 2025 09:29:28 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.175 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834170; cv=none; b=hVGjt4U8qg74WYPOqWLMV9PeTM4UERFtcRkfKGkFj44UzTbQ52a5K+5a2R3XJxoAUJluPtaCZChilY3P0/ZgLJ38ZGgJBGlExoEMeFO1xQ41joYL2v7Dsu/6kWVQVGclaV6CX6UECw78dLAasIr3A9x5rV3ItybNgSn/bIxPEFw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834170; c=relaxed/simple; bh=Btyip5cttvaDpQ47Hobx3+HFANarQIo3DBo0MaIGqeo=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=oT4Bpo3QfShOVbyqX+6M3O1BM45Get/pKoCucNrovIq4B7bszPml7TyrNugIOPTStbbobkWywrvZlgGmi87AN49LVSH2HCQ424GO0fMh0dOi71oERiVnDJm4JTnMbs8Z+T5enPDXEltvUmJnL741+F2Tcu8MjGkjJO3twtR8w28= 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=u1LDwLou; arc=none smtp.client-ip=209.85.214.175 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="u1LDwLou" Received: by mail-pl1-f175.google.com with SMTP id d9443c01a7336-21661be2c2dso12919075ad.1 for ; Thu, 06 Feb 2025 01:29:28 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834168; x=1739438968; 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=SCUMLmrIOnRhbVUxbyJm2yfzH22vl8wPDByGbPiWd2g=; b=u1LDwLou7bY0gbt3sI7wKyY873eAsAJyJtEaPltZHeMETsh3CPeRNci3ZrT/HzcI7h bJ+6BfrbvVj/p9RenwbTBpyIJ6RiuYBaW5b+0kXWM1uI4RHERj7UENOH5hhrkc9SbVX3 e6+mX2QiJYzGxrB3qb97uYrFlYEXQN1hVuNnpW2XxyET/nOnRw4gzccCA6eZlUrV9zsn JpOHvs7e7TVjwyRXq8o6yhmeRgVK69xmXiimow6POEwyVN00bdI/GMuupyoKnnO4gNt/ cgBSqKzKH/PeXAT59g6z7+DoiihZzOfgGdMii+PIfhQUOxT+wgnLzxZcgwWIZrzNvyiN qYXQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834168; x=1739438968; 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=SCUMLmrIOnRhbVUxbyJm2yfzH22vl8wPDByGbPiWd2g=; b=QofjLlc6+cRPC2/vS5kqsoe4chc1NyHRvDHQR7gLbssRU5ZNFb5VsFhvVbca7zZjPL ecP57dSynWUcpgjt2pOeOVeo2/McFXaIOfQUVV9hvf+OyBWKSzAvArpXiriCgqg1UsYE hotayTYZ9yHv1F24XQv1aET7PhbqyX+JPTTgCb1bzKR+iPBwRvUN5l1k/KTYRflqhR8k JeEkJy/4IYxiFOYzAJqYMH2uzQrk4l0TXNDWuiyJ9aXxcNrr9dx/sUDVgmo4KaJgJa1B 2iC2Cg7nJv8YVJ+C30gfPRIpEHNkmRPjfBiui3JgOAcgk+3VG7dMNZg3O9Q0QGIIProv TT1w== X-Forwarded-Encrypted: i=1; AJvYcCUnSlKJc34zh1tQtabZhmpb16nygHFzoU/tEVf/n6deXqMFSkHS976GdC4aZIsygZNVlZxwpQHyTQ==@vger.kernel.org X-Gm-Message-State: AOJu0YzoezHpNNC/gy66aAtfhA+CNNKZ5jr63lx4D80XmU/F4stUgiiD yb1+WWCjDVBdN4ICcumM3pm/le9aCOloGFUSZVSmWxrO1HfD/7BBPru+CWgOZqM= X-Gm-Gg: ASbGnctJlrfeJy6g96BuVZuhc1iMma+2LLkfZeDsYC75iJmcf7rs6CXQg8O6v0EUFEO kkveHRbbdocVZ3Adl07Y5uSaa21wUzUYOc7LM7WKL/eeDRFsHQm0AzdOmVLBKA5+yydfk9CT98c GH5jla8AgVsOYpNYO5Cj0beZLQaEt+rXUdAT+heQqH89szOog2/fH6aJtxPQ63bVeaAcFQkREhH xI4Yl/MXTlB3j9syh1O0Zrrd6bjPQVjR5hBx6HObFXw1nHinL+qYZoqbyr7DJVq5rZ+IeYy0RQH /41rqnrllCO3BcjTpA== X-Google-Smtp-Source: AGHT+IHmOhiNOHtcB647gHK2pP1h0sRGNI8hEpCMxo+dj0zatC2leoJLviSo0fMpbheyGPKxBwoovQ== X-Received: by 2002:a05:6a21:8dca:b0:1e1:ae4a:1d42 with SMTP id adf61e73a8af0-1ede88ad419mr13625445637.31.1738834168119; Thu, 06 Feb 2025 01:29:28 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id 41be03b00d2f7-ad51aeb8d09sm822696a12.15.2025.02.06.01.29.27 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:27 -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 V8 09/14] rust: Extend OPP bindings for the configuration options Date: Thu, 6 Feb 2025 14:58:30 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This extends OPP bindings with the bindings for the OPP core configuration options. Reviewed-by: Manos Pitsidianakis Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 262 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 260 insertions(+), 2 deletions(-) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index c0daeadfb188..8028245e94aa 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -10,11 +10,28 @@ bindings, cpumask::Cpumask, device::Device, - error::{code::*, from_err_ptr, to_result, Error, Result}, + error::{code::*, from_err_ptr, from_result, to_result, Error, Result, VTABLE_DEFAULT_ERROR}, + prelude::*, + str::CString, types::{ARef, AlwaysRefCounted, Opaque}, }; -use core::ptr; +use core::{marker::PhantomData, ptr}; + +use macros::vtable; + +// Creates a null-terminated slice of pointers to Cstrings. +fn to_c_str_array(names: &[CString]) -> Result> { + // Allocated a null-terminated vector of pointers. + let mut list = 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) +} /// Dynamically created Operating performance point (OPP). pub struct Token { @@ -79,6 +96,247 @@ pub enum SearchType { Ceil, } +/// Implement this trait to provide OPP Configuration callbacks. +#[vtable] +pub trait ConfigOps { + /// Called by the OPP core to configure OPP clks. + fn config_clks(_dev: &Device, _table: &Table, _opp: &OPP, _scaling_down: bool) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Called by the OPP core to configure OPP regulators. + fn config_regulators( + _dev: &Device, + _opp_old: &OPP, + _opp_new: &OPP, + _data: *mut *mut bindings::regulator, + _count: u32, + ) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } +} + +/// Config token returned by the C code. +pub struct ConfigToken(i32); + +impl Drop for ConfigToken { + fn drop(&mut self) { + // SAFETY: Its safe to return the configuration token number previously received from the C + // code. + unsafe { bindings::dev_pm_opp_clear_config(self.0) }; + } +} + +/// Equivalent to `struct dev_pm_opp_config` in the C Code. +#[derive(Default)] +pub struct Config { + clk_names: Option>, + prop_name: Option, + regulator_names: Option>, + supported_hw: Option>, + required_dev: Option>, + required_dev_index: Option, + _data: PhantomData, +} + +impl Config { + /// Creates a new instance of [`Config`]. + pub fn new() -> Self { + Self { + clk_names: None, + prop_name: None, + regulator_names: None, + supported_hw: None, + required_dev: None, + required_dev_index: None, + _data: PhantomData, + } + } + + /// Initializes clock names. + pub fn set_clk_names(mut self, names: KVec) -> Result { + // Already configured. + if self.clk_names.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.clk_names = Some(names); + Ok(self) + } + + /// Initializes property name. + pub fn set_prop_name(mut self, name: CString) -> Result { + // Already configured. + if self.prop_name.is_some() { + return Err(EBUSY); + } + + self.prop_name = Some(name); + Ok(self) + } + + /// Initializes regulator names. + pub fn set_regulator_names(mut self, names: KVec) -> Result { + // Already configured. + if self.regulator_names.is_some() { + return Err(EBUSY); + } + + if names.is_empty() { + return Err(EINVAL); + } + + self.regulator_names = Some(names); + + Ok(self) + } + + /// Initializes required devices. + pub fn set_required_dev(mut self, dev: ARef, index: u32) -> Result { + // Already configured. + if self.required_dev.is_some() { + return Err(EBUSY); + } + + self.required_dev = Some(dev); + self.required_dev_index = Some(index); + Ok(self) + } + + /// Initializes supported hardware. + pub fn set_supported_hw(mut self, hw: KVec) -> Result { + // Already configured. + if self.supported_hw.is_some() { + return Err(EBUSY); + } + + if hw.is_empty() { + return Err(EINVAL); + } + + self.supported_hw = Some(hw); + Ok(self) + } + + /// Sets the configuration with the OPP core. + pub fn set(self, dev: &Device) -> Result { + let (_clk_list, clk_names) = match &self.clk_names { + Some(x) => { + let list = to_c_str_array(x)?; + let ptr = list.as_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null()), + }; + + let (_regulator_list, regulator_names) = match &self.regulator_names { + Some(x) => { + let list = to_c_str_array(x)?; + let ptr = list.as_ptr(); + (Some(list), ptr) + } + None => (None, ptr::null()), + }; + + let prop_name = match &self.prop_name { + Some(x) => x.as_char_ptr(), + None => ptr::null(), + }; + + let (supported_hw, supported_hw_count) = match &self.supported_hw { + Some(x) => (x.as_ptr(), x.len() as u32), + None => (ptr::null(), 0), + }; + + let (required_dev, required_dev_index) = match &self.required_dev { + Some(x) => (x.as_raw(), self.required_dev_index.unwrap()), + None => (ptr::null_mut(), 0), + }; + + let mut config = bindings::dev_pm_opp_config { + clk_names, + config_clks: if T::HAS_CONFIG_CLKS { + Some(Self::config_clks) + } else { + None + }, + prop_name, + regulator_names, + config_regulators: if T::HAS_CONFIG_REGULATORS { + Some(Self::config_regulators) + } else { + None + }, + supported_hw, + supported_hw_count, + + required_dev, + required_dev_index, + }; + + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. The OPP core guarantees to not use fields of `config`, after this call has + // returned and so we don't need to save a copy of them for future use + let ret = unsafe { bindings::dev_pm_opp_set_config(dev.as_raw(), &mut config) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ConfigToken(ret)) + } + } + + // Config's config_clks callback. + extern "C" fn config_clks( + dev: *mut bindings::device, + opp_table: *mut bindings::opp_table, + opp: *mut bindings::dev_pm_opp, + _data: *mut core::ffi::c_void, + scaling_down: bool, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: 'dev' is guaranteed by the C code to be valid. + let dev = unsafe { Device::get_device(dev) }; + T::config_clks( + &dev, + // SAFETY: 'opp_table' is guaranteed by the C code to be valid. + &unsafe { Table::from_raw_table(opp_table, &dev) }, + // SAFETY: 'opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp(opp)? }, + scaling_down, + ) + .map(|()| 0) + }) + } + + // Config's config_regulators callback. + extern "C" fn config_regulators( + dev: *mut bindings::device, + old_opp: *mut bindings::dev_pm_opp, + new_opp: *mut bindings::dev_pm_opp, + regulators: *mut *mut bindings::regulator, + count: core::ffi::c_uint, + ) -> core::ffi::c_int { + from_result(|| { + // SAFETY: 'dev' is guaranteed by the C code to be valid. + let dev = unsafe { Device::get_device(dev) }; + T::config_regulators( + &dev, + // SAFETY: 'old_opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp(old_opp)? }, + // SAFETY: 'new_opp' is guaranteed by the C code to be valid. + unsafe { OPP::from_raw_opp(new_opp)? }, + regulators, + count, + ) + .map(|()| 0) + }) + } +} + /// Operating performance point (OPP) table. /// /// Wraps the kernel's `struct opp_table`. From patchwork Thu Feb 6 09:28:31 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 863216 Received: from mail-pj1-f42.google.com (mail-pj1-f42.google.com [209.85.216.42]) (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 5C7EB22F390 for ; Thu, 6 Feb 2025 09:29:33 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.42 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834175; cv=none; b=Im1qBD4S7mRe4HsO7+Sqhf/f3KQVTbEvZMJ83xv5YktCZmZOUVxZ1fG8VqajY6P+GUK5P+dsSGVrEcN1cn1pqmI5sgYUJU5Q0xgzmBTGIFZyCpo02Q+R8ColbJFYTswjvxEpz5U5LeiUQOE/aEoiB45f60dGjVBeWG8J4ULOaKE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834175; c=relaxed/simple; bh=tnICjcIhVFFy17Cq4G+BHstf/G1WFVbXzocDK31tTZ8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=YGbaAajeIyka5G+inCLQth00K4GGXxLcy0otWycfPPVSOcQGWRhm6amirdVBpukSLT0IrC1R4WxUfxNrl4Lz4aEGqGzu/P+27A9Rx7ffhV2sx+BeSUoJlAeH9l6KrAcO1m4eZmEZSNKzvsqvDz8vdyH4G6PWFZ9TAjsWAoDULIc= 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=y+hIGgs5; arc=none smtp.client-ip=209.85.216.42 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="y+hIGgs5" Received: by mail-pj1-f42.google.com with SMTP id 98e67ed59e1d1-2f9c3ef6849so1207340a91.3 for ; Thu, 06 Feb 2025 01:29:33 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834172; x=1739438972; 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=ssve9dmZgI6qS1KPS1tMtwF1lG6DTg964KCzf8z+2OY=; b=y+hIGgs5xX+L7rZHUvsInfj2z9m7DybqhCwxTMaF+1lW5jaFxf0kMtdaucru1YBzi5 FL9tzPDESeL3dA3fE3SEENf9aCWRB1a5OodfZban85mun2hu6xWWICzagzUUTeVKQQ4S JZP1SnnSPAbMnkk0tPf9n060hHxamGV15plwVZzG3kaUO3L+VP9FkegbDRzVcqM+Qd+p HotlUhe46yeFHCmoGA+EtMGHB/uX2sD4srgEqcoua2DC7H6cBjkHsQ/pvqhbaFChVhM1 i66wxU+G13rfxhV0SiLmGOQC40bvUjIbGu2CZrMuIktgixnseiOoWnEL4RC9wGJ2e0St iymw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834172; x=1739438972; 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=ssve9dmZgI6qS1KPS1tMtwF1lG6DTg964KCzf8z+2OY=; b=A12+CKwTJueRsxttUAoaziakwprOAlUH5A1Kn5IP3Heu/9gc3XDC4Te7FkfrUJ86gX vPEf/v/h4TUuN7WVpsgBnDwVUdFxrKMzd9jsTxB8an3+q/D54x9QMKwZt2YpxsqIl38g BDjv3t56WuwGQS+OJgsCj9kSySMBwZr+79FrB9mO7NlGubtG/9YeRY+IJqhck99DqMET PUAWYGbZEEULQ0SOLvG/sDwcx4QI+3TT2h3tacXZGBBrL8c8Hzw/o89ipUDSJG4rLbmn +7YmNH2yioJVWSeRquKG7ZrTfJwEANK5QKm08DzaXGsaHJ/Ieoq9cA9/9bPSayyjJb00 6roQ== X-Gm-Message-State: AOJu0YxkLQ0kbAMir6bjHZDawhmPy16jAw8aIOdk3gwqQJbMEPH4WM8R cZwBETT7KFG2HPWkr4u3QoPn54RFTW4HyHdrcLUNG/ozdeWUnQlvrzhDTwXpSog= X-Gm-Gg: ASbGncuXhnQKr7soq5ceZB3NMNtnMr/lnKPwKoSuKigsQogU26Pw7WtzS6QAFnnInys jzumQsa9UUHnZMjQ6CzPAO95HBr6MABhteZI9FvsLlS3CHivXPgMaRfjYe3q4KKoxwXFIheHQl0 JU1sHGkYXDTzo6GhUHDnv2E+yPZ2yGNlMtZd+ttRsy6MKnseWirKGhW7ORqLsYv7aT2EC5Bc86X hdFR2IlkK/6id/KYI5Xb6V5RtJkfANza53y1eyQAysy9YhF28WSr0GU2TKrLBxncaPrQ9c/gBfA 0LFcq6SIsghglG1ltg== X-Google-Smtp-Source: AGHT+IHmkA9y1OofEwZ0TlDzuR/nVNF/oPVAK27Xb6GbzCKrWlWgxuFLMMtmHljRUa/MOaRJPGT9iA== X-Received: by 2002:a05:6a00:2908:b0:72d:8fa2:9998 with SMTP id d2e1a72fcca58-7303513ac4amr10286481b3a.14.1738834172363; Thu, 06 Feb 2025 01:29:32 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73048ad26c5sm854293b3a.46.2025.02.06.01.29.31 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:31 -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 V8 10/14] rust: Add initial bindings for cpufreq framework Date: Thu, 6 Feb 2025 14:58:31 +0530 Message-Id: <4dd915bf503b77166b134e4b3dfeed389b1a5bcf.1738832119.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This commit adds initial Rust bindings for the cpufreq core. This adds basic bindings for cpufreq flags, relations and cpufreq table. Reviewed-by: Manos Pitsidianakis 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 | 228 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 6 files changed, 243 insertions(+) create mode 100644 rust/helpers/cpufreq.c create mode 100644 rust/kernel/cpufreq.rs diff --git a/MAINTAINERS b/MAINTAINERS index cda0d2b74e29..f0270ceb82d9 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -6024,6 +6024,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 7f851d5907af..68bf1bc5bae8 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 *policy) +{ + cpufreq_register_em_with_opp(policy); +} +#endif diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index de2341cfd917..32d0462219e5 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..4546a70c7063 --- /dev/null +++ b/rust/kernel/cpufreq.rs @@ -0,0 +1,228 @@ +// 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, +} + +impl Table { + /// Creates new instance of [`Table`] from [`TableBuilder`]. + fn from_builder(entries: KVec) -> Result { + if entries.is_empty() { + 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, + }) + } + + /// 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 } + } + + /// 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 { + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `self` and `index` is + // guaranteed to be within limits of the frequency table by the C API. + Ok(unsafe { (*self.ptr.add(index)).frequency }) + } + + /// Returns `flags` at index in the [`Table`]. + pub fn flags(&self, index: usize) -> Result { + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `self` and `index` is + // guaranteed to be within limits of the frequency table by the C API. + Ok(unsafe { (*self.ptr.add(index)).flags }) + } + + /// Returns `data` at index in the [`Table`]. + pub fn data(&self, index: usize) -> Result { + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `self` and `index` is + // guaranteed to be within limits of the frequency table by the C API. + Ok(unsafe { (*self.ptr.add(index)).driver_data }) + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 8956f78a2805..2a42e21d57f2 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -43,6 +43,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; From patchwork Thu Feb 6 09:28:32 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 862869 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 D74D322F3B4 for ; Thu, 6 Feb 2025 09:29:36 +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=1738834178; cv=none; b=gquSnW1pUkLvqouTRdi0PQgryIDxiztrgCMg7oYx2ruqkFfW7poQxu1/iatir5tuGq6vJelRlBf0nDOq7gO3amyXKw3N2Hv52C6gX1h3RYPdsZpjDdwkzklOshlC81Q8c0fHUC6Z4DEK6o4i90atAVBWIwERdeLqaDZM0adxHE0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834178; c=relaxed/simple; bh=hzuNhO1Q3IkyXCT/x1RQcToG9eFKeb1mwBR+qRFJhIU=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=i330e4YRRwCN22N6RkXn5WvKFRKoa3JNzq6FwG4qC8A4OB1zJOHuUMtFxMJ8eAet1zJNrtUh42lEU3KIex4dNLsnJgynclyzSIOL9HLHXrbzFxErt7l8ByzDy/reh7FKXgmEluCJxOj5zdk0nQLm+TDvMa9Q1PXh9FfcDqxUwmI= 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=YrnBv0uV; 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="YrnBv0uV" Received: by mail-pl1-f171.google.com with SMTP id d9443c01a7336-21f2f09865bso12373205ad.0 for ; Thu, 06 Feb 2025 01:29:36 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834176; x=1739438976; 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=BewoLF4XXJE59tcPINPOfVWWxQlIhp/bpFbTZBnmMRo=; b=YrnBv0uV3Yx55AZ0z2c3aNCCjwz2vbhEYI9GyJEyLpwU7TdDTe+f1s1VR8VbVhphbI ZTKLRtbouMd0Oy6a02qtOg1LMqoCjyJIqMdFkG8ETjOloWLhXZZzI4k/K+TPeST+4qEz lwfPIIIUELVLZxSfLcYtDQ/NATLxIjrWGxhfcosO3iiwJHZAl/NTZkkN2bWE3E/JWotP APfWJarrCgzFMPbhoos8sKOej1osj9Cc3erZJlPQb8v9pIzsGO9M5ScqTv8zEARBM+78 WfPXwW/R2eJAO9c3iFT6ep52sGU+oRbatoBmm9xM44tgVa+CtSsv3aC9FNB6FsT34Cxe VOTw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834176; x=1739438976; 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=BewoLF4XXJE59tcPINPOfVWWxQlIhp/bpFbTZBnmMRo=; b=FTPYevqRnRhG6phHK3CQUSVfUFdyzhy8VlyrdI3K00jgiNMAnBFxU5KiwJpty5N5Ot S1BPPYhnyHtn5m1LWWNgA6IBTkvp+9cQANhsitdriARYX9AHtMG7agWcmkMu3/OHTVN3 k5tHdEGO1wSS2h0PNdJf2A2NV29Qy+F6XBrJ40bwolBTxDKzagqwQnq9qLosFdFIoh4r Ux3c/7bqp1+70tHKiB82AdptdTYLO2tv4smnUFDvrhIkvKpsKxvzikFk2An8dmgj0II+ wxrv9PcSoSStvlp4FyqQ9+kZTgzSxUgPvQiG9DTb6niegPgrhK9CCAJMKWAblFEL+0Ls dSWQ== X-Gm-Message-State: AOJu0YxAK9jj3nwZXSg9vQVtRuEgRzZKN9dp6nbugjOAXOTwYVsFvkKR P582px2EnBnggjAP3X6bQ9G2ahO8HYmklBAlxSh9eGRqxnK0bPFcgHI4iOq9qmU= X-Gm-Gg: ASbGncvMNXXaP5k4HVHeuoJHHpW+Pr8tMbOIzU5W1K7qHiEO/XRDvliw5h3lwHHmVym 6+dU4sRYN9JZ/DGDh7v5WRkganK6KS1jNsVtYQlEVf/dBpyX9ertq6c/lIBnTcRgb0s99PT5vtu e4q0MvOA7aP4Dcz6B6/KNV+bgc/EY9Pyfe5NfYkOdBPb6U8gHRJHRqxZIlJxeCogU+4fxOSOrMf UJl+bsVusV/TLNjOZsi2RMofZooX31k6vcZKCSHzsQf2m2qFNfHIIAbf+thZiF46WEErCST39hI pT8uiHGkZT0i5eCkdw== X-Google-Smtp-Source: AGHT+IHyxQAOrCYMKMTrZjWvo9bFWT1K8eOlTJFH1d5xana7tiWBgQrQ4rVBlR8ev+13dQ3LVmaKDg== X-Received: by 2002:a05:6a21:900b:b0:1e0:c166:18ba with SMTP id adf61e73a8af0-1edf367d34bmr4946817637.12.1738834176089; Thu, 06 Feb 2025 01:29:36 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73048a9d350sm877632b3a.11.2025.02.06.01.29.35 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:35 -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 V8 11/14] rust: Extend cpufreq bindings for policy and driver ops Date: Thu, 6 Feb 2025 14:58:32 +0530 Message-Id: X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This extends the cpufreq bindings with bindings for cpufreq policy and driver operations. Signed-off-by: Viresh Kumar --- rust/kernel/cpufreq.rs | 357 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 355 insertions(+), 2 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 4546a70c7063..63ea816017c0 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -7,15 +7,20 @@ //! C header: [`include/linux/cpufreq.h`](srctree/include/linux/cpufreq.h) use crate::{ - bindings, - error::{code::*, to_result, Result}, + bindings, clk, cpumask, + device::Device, + error::{code::*, from_err_ptr, to_result, Result, VTABLE_DEFAULT_ERROR}, prelude::*, + types::ForeignOwnable, }; use core::{ pin::Pin, + ptr::self, }; +use macros::vtable; + /// Default transition latency value. pub const ETERNAL_LATENCY: u32 = bindings::CPUFREQ_ETERNAL as u32; @@ -226,3 +231,351 @@ pub fn data(&self, index: usize) -> Result { Ok(unsafe { (*self.ptr.add(index)).driver_data }) } } + +/// Equivalent to `struct cpufreq_policy` in the C code. +pub struct Policy { + ptr: *mut bindings::cpufreq_policy, + put_cpu: bool, + cpumask: cpumask::Cpumask, +} + +impl Policy { + /// Creates a new instance of [`Policy`]. + /// + /// # Safety + /// + /// Callers must ensure that `ptr` is valid and non-null. + pub unsafe fn from_raw_policy(ptr: *mut bindings::cpufreq_policy) -> Self { + Self { + ptr, + put_cpu: false, + // SAFETY: The pointer is guaranteed to be valid for the lifetime of `Self`. The `cpus` + // pointer is guaranteed to be valid by the C code. + cpumask: unsafe { cpumask::Cpumask::get_cpumask(&mut ((*ptr).cpus)) }, + } + } + + fn from_cpu(cpu: u32) -> Result { + // SAFETY: It is safe to call `cpufreq_cpu_get()` for any CPU. + let ptr = from_err_ptr(unsafe { bindings::cpufreq_cpu_get(cpu) })?; + + // SAFETY: The pointer is guaranteed to be valid by the C code. + let mut policy = unsafe { Policy::from_raw_policy(ptr) }; + policy.put_cpu = true; + Ok(policy) + } + + /// Raw pointer to the underlying cpufreq policy. + #[inline] + pub fn as_raw(&self) -> *mut bindings::cpufreq_policy { + self.ptr + } + + fn as_ref(&self) -> &bindings::cpufreq_policy { + // SAFETY: By the type invariants, we know that `self` owns a reference to the pointer. + unsafe { &(*self.ptr) } + } + fn as_mut_ref(&mut self) -> &mut bindings::cpufreq_policy { + // SAFETY: By the type invariants, we know that `self` owns a reference to the pointer. + unsafe { &mut (*self.ptr) } + } + + /// Returns the primary CPU for a cpufreq policy. + pub fn cpu(&self) -> u32 { + self.as_ref().cpu + } + + /// Returns the minimum frequency for a cpufreq policy. + pub fn min(&self) -> u32 { + self.as_ref().min + } + + /// Set the minimum frequency for a cpufreq policy. + pub fn set_min(&mut self, min: u32) -> &mut Self { + self.as_mut_ref().min = min; + self + } + + /// Returns the maximum frequency for a cpufreq policy. + pub fn max(&self) -> u32 { + self.as_ref().max + } + + /// Set the maximum frequency for a cpufreq policy. + pub fn set_max(&mut self, max: u32) -> &mut Self { + self.as_mut_ref().max = max; + self + } + + /// Returns the current frequency for a cpufreq policy. + pub fn cur(&self) -> u32 { + self.as_ref().cur + } + + /// Sets the suspend frequency for a cpufreq policy. + pub fn set_suspend_freq(&mut self, freq: u32) -> &mut Self { + self.as_mut_ref().suspend_freq = freq; + self + } + + /// Returns the suspend frequency for a cpufreq policy. + pub fn suspend_freq(&self) -> u32 { + self.as_ref().suspend_freq + } + + /// Provides a wrapper to the generic suspend routine. + pub fn generic_suspend(&self) -> Result<()> { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it now. + to_result(unsafe { bindings::cpufreq_generic_suspend(self.as_raw()) }) + } + + /// Provides a wrapper to the generic get routine. + pub fn generic_get(&self) -> Result { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it now. + Ok(unsafe { bindings::cpufreq_generic_get(self.cpu()) }) + } + + /// Provides a wrapper to the register em with OPP routine. + pub fn register_em_opp(&self) { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to + // use it now. + unsafe { bindings::cpufreq_register_em_with_opp(self.as_raw()) }; + } + + /// Gets raw pointer to cpufreq policy's CPUs mask. + pub fn cpus(&mut self) -> &mut cpumask::Cpumask { + &mut self.cpumask + } + + /// Sets clock for a cpufreq policy. + pub fn set_clk(&mut self, dev: &Device, name: Option<&CStr>) -> Result { + let clk = clk::Clk::new(dev, name)?; + self.as_mut_ref().clk = clk.as_raw(); + Ok(clk) + } + + /// Allows frequency switching code to run on any CPU. + pub fn set_dvfs_possible_from_any_cpu(&mut self) -> &mut Self { + self.as_mut_ref().dvfs_possible_from_any_cpu = true; + self + } + + /// Get fast_switch_possible value. + pub fn fast_switch_possible(&self) -> bool { + self.as_ref().fast_switch_possible + } + + /// Enable/disable fast frequency switching. + pub fn set_fast_switch_possible(&mut self, val: bool) -> &mut Self { + self.as_mut_ref().fast_switch_possible = val; + self + } + + /// Sets transition latency for a cpufreq policy. + pub fn set_transition_latency(&mut self, latency: u32) -> &mut Self { + self.as_mut_ref().cpuinfo.transition_latency = latency; + self + } + + /// Set cpuinfo.min_freq. + pub fn set_cpuinfo_min_freq(&mut self, min_freq: u32) -> &mut Self { + self.as_mut_ref().cpuinfo.min_freq = min_freq; + self + } + + /// Set cpuinfo.max_freq. + pub fn set_cpuinfo_max_freq(&mut self, max_freq: u32) -> &mut Self { + self.as_mut_ref().cpuinfo.max_freq = max_freq; + self + } + + /// Set transition_delay_us, i.e. time between successive freq. change requests. + pub fn set_transition_delay_us(&mut self, transition_delay_us: u32) -> &mut Self { + self.as_mut_ref().transition_delay_us = transition_delay_us; + self + } + + /// Returns the cpufreq table for a cpufreq policy. The cpufreq table is recreated in a + /// light-weight manner from the raw pointer. The table in C code is not freed once this table + /// is dropped. + pub fn freq_table(&self) -> Result
{ + if self.as_ref().freq_table.is_null() { + return Err(EINVAL); + } + + // SAFETY: The `freq_table` is guaranteed to be valid. + Ok(unsafe { Table::from_raw(self.as_ref().freq_table) }) + } + + /// Sets the cpufreq table for a cpufreq policy. + /// + /// The cpufreq driver must guarantee that the frequency table does not get freed while it is + /// still being used by the C code. + pub fn set_freq_table(&mut self, table: &Table) -> &mut Self { + self.as_mut_ref().freq_table = table.as_raw(); + self + } + + /// Returns the data for a cpufreq policy. + pub fn data(&mut self) -> Option<::Borrowed<'_>> { + if self.as_ref().driver_data.is_null() { + None + } else { + // SAFETY: The data is earlier set by us from [`set_data()`]. + Some(unsafe { T::borrow(self.as_ref().driver_data) }) + } + } + + // Sets the data for a cpufreq policy. + fn set_data(&mut self, data: T) -> Result<()> { + if self.as_ref().driver_data.is_null() { + // Pass the ownership of the data to the foreign interface. + self.as_mut_ref().driver_data = ::into_foreign(data) as _; + Ok(()) + } else { + Err(EBUSY) + } + } + + // Returns the data for a cpufreq policy. + fn clear_data(&mut self) -> Option { + if self.as_ref().driver_data.is_null() { + None + } else { + let data = 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 interface. + unsafe { ::from_foreign(self.as_ref().driver_data) }, + ); + self.as_mut_ref().driver_data = ptr::null_mut(); + data + } + } +} + +impl Drop for Policy { + fn drop(&mut self) { + if self.put_cpu { + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe + // to relinquish it now. + unsafe { bindings::cpufreq_cpu_put(self.as_raw()) }; + } + } +} + +/// Operations to be implemented by a cpufreq driver. +#[vtable] +pub trait Driver { + /// Driver specific data. + /// + /// Corresponds to the data retrieved via the kernel's + /// `cpufreq_get_driver_data()` function. + /// + /// Require that `Data` implements `ForeignOwnable`. We guarantee to + /// never move the underlying wrapped data structure. + type Data: ForeignOwnable; + + /// Policy specific data. + /// + /// Require that `PData` implements `ForeignOwnable`. We guarantee to + /// never move the underlying wrapped data structure. + type PData: ForeignOwnable; + + /// Policy's init callback. + fn init(policy: &mut Policy) -> Result; + + /// Policy's exit callback. + fn exit(_policy: &mut Policy, _data: Option) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's online callback. + fn online(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's offline callback. + fn offline(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's suspend callback. + fn suspend(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's resume callback. + fn resume(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's ready callback. + fn ready(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's verify callback. + fn verify(data: &mut PolicyData) -> Result<()>; + + /// Policy's setpolicy callback. + fn setpolicy(_policy: &mut Policy) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's target callback. + fn target(_policy: &mut Policy, _target_freq: u32, _relation: Relation) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's target_index callback. + fn target_index(_policy: &mut Policy, _index: u32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's fast_switch callback. + fn fast_switch(_policy: &mut Policy, _target_freq: u32) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's adjust_perf callback. + fn adjust_perf(_policy: &mut Policy, _min_perf: usize, _target_perf: usize, _capacity: usize) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's get_intermediate callback. + fn get_intermediate(_policy: &mut Policy, _index: u32) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's target_intermediate callback. + fn target_intermediate(_policy: &mut Policy, _index: u32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's get callback. + fn get(_policy: &mut Policy) -> Result { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's update_limits callback. + fn update_limits(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's bios_limit callback. + fn bios_limit(_policy: &mut Policy, _limit: &mut u32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's set_boost callback. + fn set_boost(_policy: &mut Policy, _state: i32) -> Result<()> { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Policy's register_em callback. + fn register_em(_policy: &mut Policy) { + build_error!(VTABLE_DEFAULT_ERROR) + } +} From patchwork Thu Feb 6 09:28:33 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 863215 Received: from mail-pj1-f50.google.com (mail-pj1-f50.google.com [209.85.216.50]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B5B2922FDE5 for ; Thu, 6 Feb 2025 09:29:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.50 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834183; cv=none; b=J53NqDeU8oYtiisdvuQulkEknoIg33e3Kyy8DZxxIGJKApPzVjbofLIusSrOG0R+0Iqh/UsCJ7N8M2zHI4UQrrDfV5akf6TR3RStTMFE7CKmKWsjdebLVQHZe+t0fhh9YRJ+jd1fwyxwLhGWIf84WqnEHxKspVH37Bw3JH/QRgM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834183; c=relaxed/simple; bh=l/VIi63UGc+3u6vflgZumPAhzfpIgDQMkROcsChH9BE=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=YYhd4M7NDpAGh68KvJrhFWBqnNhj2WIp8ap5jQFDSrhphc5zVYr8ruiORJX5lQUJGV6NkFV9ggh23u+tGV+MDI4WXUl3ueejaBKXq9wU2TWVqHGJxK3iy+42y+BOhdqXSyiL1gaKE3yOPDWinLlhLJrYxMCVi/6l6za/XSMN3tk= 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=j56OlRHB; arc=none smtp.client-ip=209.85.216.50 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="j56OlRHB" Received: by mail-pj1-f50.google.com with SMTP id 98e67ed59e1d1-2f83a8afcbbso992057a91.1 for ; Thu, 06 Feb 2025 01:29:40 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834180; x=1739438980; 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=W6Z09wEUbdjhQQCnF4pncU5PBUEGY4K3sFzwx7fQzBM=; b=j56OlRHBbO31lKVuDT3GyLfYUebuhFd6+etnIW6OjTwS23d4ySTOUAVUulz6yrGY7A UYordM6URjWAGx1UmqVpmnY+JIA/jgzztt2xSoHC3D0BS60bh7h7dF27Ct5nkFcfh+SN YOhbRm8rFZsxsNS5MhaYOBm9bGLI0ZPuJU46PP9x38sdgFEsFZRV3xqCxAXLfvLfedvA 3qVufLtWBs3kQnHWxkL3TwmyejvqokKqL/9MWTaOmtGehHoGhn0ZPZhBCuQfhaCDaXKg aV8DyObtAw9hpk3iwJ07p6K1nPDcRffa4e9ctaMJkSdlpYAQSmlz8ggjCn4rer01qtGf QpSQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834180; x=1739438980; 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=W6Z09wEUbdjhQQCnF4pncU5PBUEGY4K3sFzwx7fQzBM=; b=sz0w6e9KLifwDKZbQNzkw/5O1Gl2fKZp/Eypl3tPDSx6sK48B3X/+GuM75ZTBNqhRc GIUt0sJh0ua59ZkB5zQbZ8/gHmFdW87M7i7ptLY/6EFhotByaGGFA9LsLm5xIivQkJDt vvILMdGVB10SiRqDAR4ni6JPgfvzkurebBvc2Cht12pm0DgTZnw9F4AbUFjeJaLssR/t dw3CY9zbqN3Z74+wR8LHTNuUh//LhmFOMPZen8gpNdoivRvdpjYsNPB4N8Ps+u2yTn1q WHzd1WGAT2LD5tGC1wgg3NFg3z+6imvvbInF7SN9IHCterQD0XqBXseKiqQqnHPC5wAv 2N/w== X-Gm-Message-State: AOJu0YxhJYNWxtDKCKwsEYcRWu8OXmA7ckvCZhc/XY70zTaJCblqOowW rCrhI51fcx/b2YjKZ/kAQQVFbtf3EdKMlQkUqhNXkPmXAezEdvsCUfohqRxjtto= X-Gm-Gg: ASbGncuwi0HgvUMFccFm3pCuzSN10+LZb/vXYaEzith4jwu3/o8e6ervykEeYzloWN2 ZmNi5BS4ZHUrOXU1JuYnofOam4wdf5wLRglaoEx5Y9dbsyi3/Kq9yWsigYl3ejtz02+YfRcGtgr +4Z3nxLQg4KOdnz/3cDkWt9jIwtIHnq+PqpVHk6EjNjsSknFcVJJ7oKibtl+cSKSNdKyQgqMcao w6Y+0QnJYs2KyvJ7tHxgOW/4P0mSGJiN+p7aDOBlvS5W/QSoT+yeceDszhBAqdIp6gPRoGQsLf2 WocNfXiZhsFSou0ofg== X-Google-Smtp-Source: AGHT+IGvzDmiMJGRpepS/9/HxxBD6K4uQOyrmZ5Z/P0VpVjMavBRgfYTNtKdzE8d9q/kFMstDAByZQ== X-Received: by 2002:a17:90b:3b41:b0:2f7:4c7a:b5f with SMTP id 98e67ed59e1d1-2f9ff786427mr4766379a91.2.1738834179821; Thu, 06 Feb 2025 01:29:39 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-2fa09b3f803sm872055a91.32.2025.02.06.01.29.38 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:39 -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 V8 12/14] rust: Extend cpufreq bindings for driver registration Date: Thu, 6 Feb 2025 14:58:33 +0530 Message-Id: <5860ff88ff81d09838f7786507ec47a33cf16158.1738832119.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 | 475 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 473 insertions(+), 2 deletions(-) diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 63ea816017c0..f92259d339d3 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; @@ -579,3 +582,471 @@ fn register_em(_policy: &mut Policy) { 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 Thu Feb 6 09:28:34 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Viresh Kumar X-Patchwork-Id: 862868 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 DC8F422FE14 for ; Thu, 6 Feb 2025 09:29:43 +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=1738834185; cv=none; b=uj9zADnVtGh4WGjE/nXN3OdJ3jg62JI72ry+9LNLQJIrLmwX1gX4FtlEiHiYBIXGQ0C2ztldTA3EMzVb7dTXcHPjIo+7PiN0A/0CipwabBowUSLkokJedxye/U+3P+WeHGpucDibzBrIuR7BFYcSVxHhX/rzF2Lo4sOanNUArl0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834185; c=relaxed/simple; bh=6Nr6juVTcJnK5KJdfVIW7dgp4mA/0Bv/HaCQhKWQ1L8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=cT4FzDhxxb/tG0PzVA1twqIEVgio6BdJ04FINCV48mMICeaJuxUGBqMypOcL3zIj8m1lcaL4w3sYOW2qMm0xjGVIhL1BE/dbKCYXJhhrSxCBL19Rr0bD9f/taH3fqqQWT5XnrA57XEQ0xAKZJUq2250MmXuY5pVaNznuLZuytPY= 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=KvhZ2EcZ; 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="KvhZ2EcZ" Received: by mail-pl1-f171.google.com with SMTP id d9443c01a7336-21c2f1b610dso17532555ad.0 for ; Thu, 06 Feb 2025 01:29:43 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834183; x=1739438983; 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=Q7GVksBxvKvwIJslQZYHPVaVtikmNSrbgR1tm3RBWUA=; b=KvhZ2EcZwvUuhxtx2+tAV4tI4wJXGSUSnm+dMFMj6Q6RsEjGY0T3xNOGLZ+uo6gDdf M+kvhYUlQiKV8GOcJO1OME4oyes4pBQeJdgixCsVFjcU5VRcSL5lRzA/NToGRpWhvj2+ fJTEQdyDSYTggC3PXegB9nuy6hF1Igm1pdkZK9Y/moSqGE0DrE9uVBXqj7G9SCIDg2uB NDFougi7F0n93TStKRtEqlGpgd76C2pjHH30efWxYAwe5BLwOO4gKk8TCubMkwmdvPSB R2Nhg+aEpJpqx5HVQN459D+0+k+4cvN8Hsi4vdaXctoCg5de7jFfYgq7PcdRbZbIL83D 2PbQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834183; x=1739438983; 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=Q7GVksBxvKvwIJslQZYHPVaVtikmNSrbgR1tm3RBWUA=; b=PFNo38epc2yspPQTFgYyxsiJM495C6AHse6MrVzet5YkDBUH1vL/xiZw/IHpgGL9JH AvhxG3K6x6mO9H0szq3IOOckMhTNNm/NfKY3bSw4bYdHDQVu88cjJ/eUU1LjnPq/9tgB 5cDaaiJD0DKK6zrc/8p/Ej1mXcW2VvT6eJ0e0jXtFAnsfUXiCKJ7kjU4nkSkvfTQdpf0 0mHW6ln1sEBoPTteGnq/INAUYSSBbREf+QU0JuWl2Ro4EY6cy05fqfiwlCCMolyST4JD ocHKYq20q5qpb2R5Mzw6DKsJy5OA3c4QNJXLkyMOUzFSig3G5BATNvKUPShNDozlqsz0 IDHg== X-Forwarded-Encrypted: i=1; AJvYcCUYhaMVjFJ5Iow7SfPv+ZJEiTVjYmGzXXBp4z4ZuUepJf3tqxEvnI/yJCwiZesSXcSgaTumrePidw==@vger.kernel.org X-Gm-Message-State: AOJu0YwRjbsQ0eHGyUozLY5pdpnYqIVj+SXzSDH7FgFEjvyqj1/sqRn8 2S8FABsuCzmo8REWO4ZKgrY+bDO72mCw9FehIy3zLS8OsXZAZMPQuP3HSSK22tc= X-Gm-Gg: ASbGncs7pksjDmtqG4h654hausToKRDQnxcUdWZJbClOhz+Sj9VFoprMxRTSh+JEj/q 7pdLtLKzor86zQQFc9Uvja99LHIWcG9RF5F1kegUbDsH35o/47CvYB1H/b1qe9oob9HcMF3v9/c nvdDMgO8Jl+CkCchBEGCNwhCUGavT5IgfaPUi+BQhEEUUXyNsOuc9hh/irmkxETonSMt3OkwjG/ GDoSD7oZwqPpZBFY+sE+3MpnZyRz/Dw7gPUySihfeN80zFlQwyrehzD7D5FdfV1T24PFntxey2B +CEG+14TIADK7Zy1Hw== X-Google-Smtp-Source: AGHT+IGILzk1MC7IIM8lCYB+bVOwC6qPckXvdAEjdQCycRHBampUmw7KPycs3BkF8bGTuy8Qvqtp5g== X-Received: by 2002:a17:902:f54b:b0:21f:1553:12b5 with SMTP id d9443c01a7336-21f17ec7bcemr112601805ad.36.1738834183178; Thu, 06 Feb 2025 01:29:43 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d9443c01a7336-21f3683d5a5sm8089985ad.128.2025.02.06.01.29.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:42 -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 V8 13/14] rust: Extend OPP bindings with CPU frequency table Date: Thu, 6 Feb 2025 14:58:34 +0530 Message-Id: <5dc8ce40dd0e0ce7defb002e7f6e614d5d8a5c18.1738832119.git.viresh.kumar@linaro.org> X-Mailer: git-send-email 2.31.1.272.g89b43f80a514 In-Reply-To: References: Precedence: bulk X-Mailing-List: linux-pm@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 This commit adds bindings for CPUFreq core related API. Signed-off-by: Viresh Kumar --- rust/kernel/opp.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/rust/kernel/opp.rs b/rust/kernel/opp.rs index 8028245e94aa..4030953c2001 100644 --- a/rust/kernel/opp.rs +++ b/rust/kernel/opp.rs @@ -16,6 +16,12 @@ types::{ARef, AlwaysRefCounted, Opaque}, }; +#[cfg(CONFIG_CPU_FREQ)] +use crate::cpufreq; + +#[cfg(CONFIG_CPU_FREQ)] +use core::ops::Deref; + use core::{marker::PhantomData, ptr}; use macros::vtable; @@ -337,6 +343,56 @@ extern "C" fn config_regulators( } } +/// CPU Frequency table created from OPP entries. +#[cfg(CONFIG_CPU_FREQ)] +pub struct FreqTable { + dev: ARef, + table: cpufreq::Table, +} + +#[cfg(CONFIG_CPU_FREQ)] +impl FreqTable { + /// Creates new instance of [`FreqTable`] from raw pointer. + fn new(table: &Table) -> Result { + let mut ptr: *mut bindings::cpufreq_frequency_table = ptr::null_mut(); + + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + to_result(unsafe { + bindings::dev_pm_opp_init_cpufreq_table(table.dev.as_raw(), &mut ptr) + })?; + Ok(Self { + dev: table.dev.clone(), + // SAFETY: The `ptr` is guaranteed by the C code to be valid. + table: unsafe { cpufreq::Table::from_raw(ptr) }, + }) + } + + /// Returns reference to the underlying [`cpufreq::Table`]. + pub fn table(&self) -> &cpufreq::Table { + &self.table + } +} + +#[cfg(CONFIG_CPU_FREQ)] +impl Deref for FreqTable { + type Target = cpufreq::Table; + + #[inline] + fn deref(&self) -> &Self::Target { + &self.table + } +} + +#[cfg(CONFIG_CPU_FREQ)] +impl Drop for FreqTable { + fn drop(&mut self) { + // SAFETY: The requirements are satisfied by the existence of `Device` and its safety + // requirements. + unsafe { bindings::dev_pm_opp_free_cpufreq_table(self.dev.as_raw(), &mut self.as_raw()) }; + } +} + /// Operating performance point (OPP) table. /// /// Wraps the kernel's `struct opp_table`. @@ -540,6 +596,12 @@ pub fn adjust_voltage( }) } + /// Create cpufreq table from OPP table. + #[cfg(CONFIG_CPU_FREQ)] + pub fn to_cpufreq_table(&mut self) -> Result { + FreqTable::new(self) + } + /// Sets a matching OPP based on frequency. pub fn set_rate(&self, freq: usize) -> Result<()> { // SAFETY: The requirements are satisfied by the existence of `Device` and its safety From patchwork Thu Feb 6 09:28: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: 863214 Received: from mail-pj1-f50.google.com (mail-pj1-f50.google.com [209.85.216.50]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2CCEF23027F for ; Thu, 6 Feb 2025 09:29:47 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.50 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834190; cv=none; b=lnBbqXHVT3U11UlvEMSRD7O0cf9YZeuLU5xZGR3ZxGP+SQ4ait6tQgBU+9wFzukm0HWlMM4Ur8asAJFna4zeSMAwGp/Qutt9Bv21gYOGT5FjYvSCN5gZ6r8md/F362QC5VG/shMGnPTFiQit4Og2+f/DD778XjZ1IgsiobOrLts= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738834190; c=relaxed/simple; bh=lQwGxkeDyLZl4gzxKTY+sfg/kgWYDadG6FIOwNqQWm8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=ORhNWUx9ftAYnqyHV87S0W87czxdlfR5265AsOQqVwGhkkmcWzcdaYTexu1CmSduNvUldOAO/6WcK5wPmDA9OdmbB89U6UADFmWqcnXjTZfP3wI/p03Q6JFP85fQg68ygJVEfSD/ity9Pu+bhaVni2Gj5yitlWCDs+cOMj0UXBo= 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=u9GXNw4R; arc=none smtp.client-ip=209.85.216.50 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linaro.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=linaro.org header.i=@linaro.org header.b="u9GXNw4R" Received: by mail-pj1-f50.google.com with SMTP id 98e67ed59e1d1-2ef72924e53so1259103a91.3 for ; Thu, 06 Feb 2025 01:29:47 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1738834187; x=1739438987; 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=u3kmMrnO07/rY8kDURhyasWYzOo/7PtXahiPnASlEac=; b=u9GXNw4RMZ0Dk0GqRASj9PFgIrNS32tRoQhnMwUj184G5nhPZ/O86D+lp/edk07w9n kUOHc0ksNfx/+ZX1sCs32U9jUDB02/tYq2s6VJQe1Djnylhq7ebOni4Z7EwGtydnOTRr toar/ivIQwXMmmFZ7fgtqN2zCRnjU0QNuDLpdtXp3xocEzmfEsKOo6LhqRO3P1CM0sJK KxiU5Apj6sTQ4Ch9Lay9nzINZOLiJ22sgn49lEW5dVr8jAYcmT9+V9RpEjfh+ynkUJZk mg5YdnAdn/HE1gjnWxosNNM0H0HwLSUGWnh3IngmJi49jmmSnAE2Sdz/rAnQKoBQO8rQ 0dlA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738834187; x=1739438987; 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=u3kmMrnO07/rY8kDURhyasWYzOo/7PtXahiPnASlEac=; b=YCA3VWfxsXBS48/UMOjZWOvy8HupxgA8ELw4UNYQdNEqmkKWOQfCCI4rjxxjhVsjQk tHa0rVVBxeKGcBP5cCNKbidqIh3GHqdxfLkdeIXFnybkRb0KxGUsMJGjR8spCxuprKtH 1mxjzUWJNsh2mFIaJgZMLPDDw+zSbsjY0bKCulHG2VPwRzus8lYhKBIxygNkPGHi1ZjB 42d3Nkoub1JAnMfjdadNAho0J2OXZn0NF1enBOSvzKB+F9X6bH7QkhlTQ0oNBXaGsmqq OZCbEemVGQjf19RctcqsXRpaXYRaCRAFbTh1hlGMix17duGU5oL8MS/5i9g6b8rytmOj 7wBA== X-Gm-Message-State: AOJu0YwkvxyaKEpkOJK4QOwmm4Mziu2XpRptXzeNl+JrQbdVZAscAwt3 IBKtMV3FqU7dqbfTnnWDgc33yfv7KTaKcB9Ftw347ENySYQI0l3GkgEIT1z9EHo= X-Gm-Gg: ASbGncuR4+RIS7MM+wr9GpBFKduv4y25aCeqP+BUSkzX4nIfSOQ/0tlx2YuH5Y5CEQ/ 5CDJuhguRLPVbrsXyWoSJEv8pyP72WgTOX4o9Mqifdmr3LfwD9cMJCyIc8cLdCTab4hSfNVfDPC pCjKKViVnIdBoP6gPBxCV8GBSPYqZilVbdPvIntD3OJzx6MNhoLJFh4ypVxBgC9zL8X8hvIDPob P46aw4iel4e2cj0sj1C97fNgaiQFai060H+57YfyTtAxDIqCSvcvE/wcu7QaUS5wx1/Hi/3GES1 PE6ywG5k8s791heRyA== X-Google-Smtp-Source: AGHT+IGkNEhqQ7+Hl8c3zRCkviXXDjX9Vvx04qeZh3UAEF2BzHwjV8tkWb9YU/Rv9U3rFPCfG1+Zfw== X-Received: by 2002:a05:6a00:2287:b0:725:e499:5b86 with SMTP id d2e1a72fcca58-7303521977bmr9464530b3a.20.1738834187287; Thu, 06 Feb 2025 01:29:47 -0800 (PST) Received: from localhost ([122.172.84.139]) by smtp.gmail.com with ESMTPSA id d2e1a72fcca58-73048ae7e54sm855752b3a.76.2025.02.06.01.29.46 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Feb 2025 01:29:46 -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 V8 14/14] cpufreq: Add Rust based cpufreq-dt driver Date: Thu, 6 Feb 2025 14:58:35 +0530 Message-Id: <3054a0eb12330914cd6165ad460d9844ee8c19e2.1738832119.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 | 238 +++++++++++++++++++++++++++++++++ rust/kernel/cpufreq.rs | 10 +- 4 files changed, 257 insertions(+), 4 deletions(-) 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 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 890fff99f37d..7fa29bdec3c7 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..461e88006ed9 --- /dev/null +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust based implementation of the cpufreq-dt driver. + +use core::format_args; + +use kernel::{ + c_str, clk, cpu, 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(); + // SAFETY: The CPU device is only used from the init() callback during which the CPU can't + // get hot-unplugged. Also the cpufreq core in C library, registers with CPU notifiers and + // the cpufreq core/driver won't use the CPU device, once the CPU is hot-unplugged. + let dev = unsafe { cpu::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, + )?; + + 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", +} diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index f92259d339d3..ecf7c6e2cb89 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -628,15 +628,17 @@ pub fn new(name: &'static CStr, data: T::Data, flags: u16, boost: bool) -> Resul // 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 _ }; + 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 _ }; + attr[next] = unsafe { + addr_of_mut!(bindings::cpufreq_freq_attr_scaling_boost_freqs) as *mut _ + }; next += 1; } attr[next] = ptr::null_mut();