From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0590530AD00 for ; Mon, 13 Oct 2025 15:53:56 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370838; cv=none; b=nwBrh1OAnDmzCqOQfF9m5k6jXdJDmI5dKFp4bAWwxPKKFUjcuEaAxYg9Swcz9agsjE5XNvOznLn/cbpSaC55iHERG2u8JHCttXphxhe+1QII04tSG1tGPzF+FNyDjSLN/4kIjPWj8zFYqnOSBA+c5phITOHwMAAz6DbAjroRIT8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370838; c=relaxed/simple; bh=/dCx9r/U8UG2l5Mcbc2KOJix8VyRJqMpv2JirRyVJ9k=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=kbBwB+YKQhZL42jNdht1/NSwLq3/6ebO8wy9MiDe1cnvVP7L+wVTSSEav04srlSfnqavctoqVIlFdK7/VJUqn8VW+lvBqxAUZp18YUvyIpoSQbZL/Zm4gzIopbCQgcONLvBHo2Svk4RGUIZ6VDvaz0n+Rz1PCIG3QnguKQ1fkDo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=fR2YIs+J; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="fR2YIs+J" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370836; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=pIWnafYZvpDpu4eOTrAw6osXsXYCsEI4K9wvhKujihY=; b=fR2YIs+J7zXVnWa1QBZNbfH96kQO24AG9j3HZV0Dpi7KSccIfpG9utrCYXtzbK/Hq6Oz5o nuGFbdCM1aMV82+EDLvPbYVh+m5ZrjDOSJjzCbEZ/qJ9pNh/40Auzx7Ahpb5mM//eOm66l GQDn4WHE+5EMhYcTB1iIIYgG3SADJos= Received: from mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-628-EuVqN5lNPA2qFbLoLfga_w-1; Mon, 13 Oct 2025 11:53:51 -0400 X-MC-Unique: EuVqN5lNPA2qFbLoLfga_w-1 X-Mimecast-MFC-AGG-ID: EuVqN5lNPA2qFbLoLfga_w_1760370828 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id BAB71180057B; Mon, 13 Oct 2025 15:53:47 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id C68D93000384; Mon, 13 Oct 2025 15:53:42 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Joel Fernandes , Danilo Krummrich , Lorenzo Stoakes , Vlastimil Babka , "Liam R. Howlett" , Uladzislau Rezki , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , "Rafael J. Wysocki" , Viresh Kumar , Sebastian Andrzej Siewior , Ingo Molnar , "Peter Zijlstra (Intel)" , Ryo Takakura , K Prateek Nayak , linux-pm@vger.kernel.org (open list:CPU FREQUENCY SCALING FRAMEWORK) Subject: [PATCH v13 01/17] preempt: Track NMI nesting to separate per-CPU counter Date: Mon, 13 Oct 2025 11:48:03 -0400 Message-ID: <20251013155205.2004838-2-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" From: Joel Fernandes Move NMI nesting tracking from the preempt_count bits to a separate per-CPU counter (nmi_nesting). This is to free up the NMI bits in the preempt_count, allowing those bits to be repurposed for other uses. This also has the ben= efit of tracking more than 16-levels deep if there is ever a need. Suggested-by: Boqun Feng Signed-off-by: Joel Fernandes Signed-off-by: Lyude Paul --- include/linux/hardirq.h | 17 +++++++++++++---- kernel/softirq.c | 2 ++ rust/kernel/alloc/kvec.rs | 5 +---- rust/kernel/cpufreq.rs | 3 +-- 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/include/linux/hardirq.h b/include/linux/hardirq.h index d57cab4d4c06f..177eed1de35cc 100644 --- a/include/linux/hardirq.h +++ b/include/linux/hardirq.h @@ -10,6 +10,8 @@ #include #include =20 +DECLARE_PER_CPU(unsigned int, nmi_nesting); + extern void synchronize_irq(unsigned int irq); extern bool synchronize_hardirq(unsigned int irq); =20 @@ -102,14 +104,17 @@ void irq_exit_rcu(void); */ =20 /* - * nmi_enter() can nest up to 15 times; see NMI_BITS. + * nmi_enter() can nest - nesting is tracked in a per-CPU counter. */ #define __nmi_enter() \ do { \ lockdep_off(); \ arch_nmi_enter(); \ - BUG_ON(in_nmi() =3D=3D NMI_MASK); \ - __preempt_count_add(NMI_OFFSET + HARDIRQ_OFFSET); \ + BUG_ON(__this_cpu_read(nmi_nesting) =3D=3D UINT_MAX); \ + __this_cpu_inc(nmi_nesting); \ + __preempt_count_add(HARDIRQ_OFFSET); \ + if (__this_cpu_read(nmi_nesting) =3D=3D 1) \ + __preempt_count_add(NMI_OFFSET); \ } while (0) =20 #define nmi_enter() \ @@ -124,8 +129,12 @@ void irq_exit_rcu(void); =20 #define __nmi_exit() \ do { \ + unsigned int nesting; \ BUG_ON(!in_nmi()); \ - __preempt_count_sub(NMI_OFFSET + HARDIRQ_OFFSET); \ + __preempt_count_sub(HARDIRQ_OFFSET); \ + nesting =3D __this_cpu_dec_return(nmi_nesting); \ + if (!nesting) \ + __preempt_count_sub(NMI_OFFSET); \ arch_nmi_exit(); \ lockdep_on(); \ } while (0) diff --git a/kernel/softirq.c b/kernel/softirq.c index 77198911b8dd4..af47ea23aba3b 100644 --- a/kernel/softirq.c +++ b/kernel/softirq.c @@ -88,6 +88,8 @@ EXPORT_PER_CPU_SYMBOL_GPL(hardirqs_enabled); EXPORT_PER_CPU_SYMBOL_GPL(hardirq_context); #endif =20 +DEFINE_PER_CPU(unsigned int, nmi_nesting); + /* * SOFTIRQ_OFFSET usage: * diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index e94aebd084c83..1d6cc81bdeef5 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -7,10 +7,7 @@ layout::ArrayLayout, AllocError, Allocator, Box, Flags, NumaNode, }; -use crate::{ - fmt, - page::AsPageIter, -}; +use crate::{fmt, page::AsPageIter}; use core::{ borrow::{Borrow, BorrowMut}, marker::PhantomData, diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index 21b5b9b8acc10..1a555fcb120a9 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -38,8 +38,7 @@ const CPUFREQ_NAME_LEN: usize =3D bindings::CPUFREQ_NAME_LEN as usize; =20 /// Default transition latency value in nanoseconds. -pub const DEFAULT_TRANSITION_LATENCY_NS: u32 =3D - bindings::CPUFREQ_DEFAULT_TRANSITION_LATENCY_NS; +pub const DEFAULT_TRANSITION_LATENCY_NS: u32 =3D bindings::CPUFREQ_DEFAULT= _TRANSITION_LATENCY_NS; =20 /// CPU frequency driver flags. pub mod flags { --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8601230AD0C for ; Mon, 13 Oct 2025 15:53:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370841; cv=none; b=fmsV5yKtrJac7RbsCmX1AJgro9s+SEeGX1ZDFVcWaehXA0oWYJnI9mSvfOD5QgLTiRCbBInLB99Ye5Dlz7vnmlJ/2bZKYpR21oCRddVmJIfrRIaq7N+CDPf41zeedDCfRxAc5Xb5NVH+NCickU+24xh/c8fVQVsVecqRFXw6RqE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370841; c=relaxed/simple; bh=ZpSKpSwSgy2+bZiInyaF9yiqXJC5kaf+6/28l0BJf8A=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=oA2wbgKE30Xt1ESo7CQhTsyva5JmENnM6MkukX5CAmujkBdjjyfNK7EWA7Rg4mwP/z+60zQpJ7WCNpopFrw3n8FR2eIpFMGAkO5FkP0pQedf1Y0j7WPt4bk9bTsAjtz3b9mlJjgXeaD0zam9cMsUJPaUY1Yfybzg9S6OgfmXeVw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=XXaEKoOV; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="XXaEKoOV" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370838; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=qkKuLomsboIzRmpMuA/8oznn1T53sfJ8Aky18psSQVc=; b=XXaEKoOVV+lCWIsyeLTEQGscZ6eg2oNmVTl0chJP/rDUJnPaG0DtGciVWeKFawhW4oJTtb 0OLz2HSgzr+9yvMGypdqDm5j4KV9Ztnp0+MsH91SB/og6GzhQ4taFjcPFA5hIMr4oqkIZn mluEr+lDy08LUbnItJB0yRe+PSui2iI= Received: from mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-142-qDYfbeCNPdWHUsnBK6SilA-1; Mon, 13 Oct 2025 11:53:53 -0400 X-MC-Unique: qDYfbeCNPdWHUsnBK6SilA-1 X-Mimecast-MFC-AGG-ID: qDYfbeCNPdWHUsnBK6SilA_1760370831 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 86FDA19560B5; Mon, 13 Oct 2025 15:53:51 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 215E730002D0; Mon, 13 Oct 2025 15:53:47 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Joel Fernandes , Ingo Molnar , Peter Zijlstra , Juri Lelli , Vincent Guittot , Dietmar Eggemann , Steven Rostedt , Ben Segall , Mel Gorman , Valentin Schneider Subject: [PATCH v13 02/17] preempt: Reduce NMI_MASK to single bit and restore HARDIRQ_BITS Date: Mon, 13 Oct 2025 11:48:04 -0400 Message-ID: <20251013155205.2004838-3-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" From: Joel Fernandes Now that NMI nesting is tracked in a separate per-CPU variable (nmi_nesting), we no longer need multiple bits in preempt_count for NMI tracking. Reduce NMI_BITS from 3 to 1, using it only to detect if we're in an NMI. Signed-off-by: Joel Fernandes Signed-off-by: Lyude Paul --- include/linux/preempt.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/include/linux/preempt.h b/include/linux/preempt.h index 102202185d7a2..9580b972e1545 100644 --- a/include/linux/preempt.h +++ b/include/linux/preempt.h @@ -17,6 +17,7 @@ * * - bits 0-7 are the preemption count (max preemption depth: 256) * - bits 8-15 are the softirq count (max # of softirqs: 256) + * - bit 28 is the NMI flag (no nesting count, tracked separately) * * The hardirq count could in theory be the same as the number of * interrupts in the system, but we run all interrupt handlers with @@ -24,16 +25,19 @@ * there are a few palaeontologic drivers which reenable interrupts in * the handler, so we need more than one bit here. * + * NMI nesting depth is tracked in a separate per-CPU variable + * (nmi_nesting) to save bits in preempt_count. + * * PREEMPT_MASK: 0x000000ff * SOFTIRQ_MASK: 0x0000ff00 * HARDIRQ_MASK: 0x000f0000 - * NMI_MASK: 0x00f00000 + * NMI_MASK: 0x10000000 * PREEMPT_NEED_RESCHED: 0x80000000 */ #define PREEMPT_BITS 8 #define SOFTIRQ_BITS 8 #define HARDIRQ_BITS 4 -#define NMI_BITS 4 +#define NMI_BITS 1 =20 #define PREEMPT_SHIFT 0 #define SOFTIRQ_SHIFT (PREEMPT_SHIFT + PREEMPT_BITS) --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1430E30B505 for ; Mon, 13 Oct 2025 15:54:00 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370842; cv=none; b=qO3jI1Ll3hvkFpjCumHDHuxMI6S7/WeV7iz2izW5WLaBh58UMtFW9F1HK6/zpAU1SSVgJvMtlwpBAlL2bS5NTJdP7u31q3KxlDi5S4kFRrXUsmk76w/rWV5avf7JziP4Bo8Fv5i4xuhxeyfAA8hydEirkamxPwRpQiBgNDrPZQQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370842; c=relaxed/simple; bh=hBc14BMRRNXM11BVaiAzJmC7UB6s1pT3oRdF7g1guVQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=cHiFP7y6j8Ta4956nW6zCt8qT3lO5jP8aqTiXd9GG3jcOxVdgw+RDpXVoF6HjFERoRTOHqlBRWxvmP7PHVZ4YXIUs5cBpNd2m6tfsOWYKZ7ClifdqY133f/lvs96lYZgwtjuF/8FxpjQgB/aM6G/+C3z0hN5/xtlVIXv6HzrG7k= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=fDGsaXcB; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="fDGsaXcB" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370840; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=RN/1F3QpB2l7Sd/YK8Ux0Q95f92VJ0VHzZU9NZhIDLk=; b=fDGsaXcBnmHE8OoC2pirPJh9LvhBh2QLyPDVS7cmeyeSzWfutxVQWMjAdNFRBAIAm+5EEA 1v0eVUNDsWHpIKMOvxR0J0M5fBuMALgkO2ZYcSRZ4y1CZeyfqTD6IWP+304efrMd2SElBa edkhoBCs6OxCweJMvUXODOZuE6LA+Ec= Received: from mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-436-74H41NIoMdCX6bBGTF3kug-1; Mon, 13 Oct 2025 11:53:57 -0400 X-MC-Unique: 74H41NIoMdCX6bBGTF3kug-1 X-Mimecast-MFC-AGG-ID: 74H41NIoMdCX6bBGTF3kug_1760370835 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 06307195410A; Mon, 13 Oct 2025 15:53:55 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 0479530002D0; Mon, 13 Oct 2025 15:53:51 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Ingo Molnar , Peter Zijlstra , Juri Lelli , Vincent Guittot , Dietmar Eggemann , Steven Rostedt , Ben Segall , Mel Gorman , Valentin Schneider Subject: [PATCH v13 03/17] preempt: Introduce HARDIRQ_DISABLE_BITS Date: Mon, 13 Oct 2025 11:48:05 -0400 Message-ID: <20251013155205.2004838-4-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" From: Boqun Feng In order to support preempt_disable()-like interrupt disabling, that is, using part of preempt_count() to track interrupt disabling nested level, change the preempt_count() layout to contain 8-bit HARDIRQ_DISABLE count. Note that HARDIRQ_BITS and NMI_BITS are reduced by 1 because of this, and it changes the maximum of their (hardirq and nmi) nesting level. Signed-off-by: Boqun Feng Signed-off-by: Lyude Paul --- include/linux/preempt.h | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/include/linux/preempt.h b/include/linux/preempt.h index 9580b972e1545..bbd2e51363d8f 100644 --- a/include/linux/preempt.h +++ b/include/linux/preempt.h @@ -17,6 +17,8 @@ * * - bits 0-7 are the preemption count (max preemption depth: 256) * - bits 8-15 are the softirq count (max # of softirqs: 256) + * - bits 16-23 are the hardirq disable count (max # of hardirq disable: 2= 56) + * - bits 24-27 are the hardirq count (max # of hardirqs: 16) * - bit 28 is the NMI flag (no nesting count, tracked separately) * * The hardirq count could in theory be the same as the number of @@ -30,29 +32,34 @@ * * PREEMPT_MASK: 0x000000ff * SOFTIRQ_MASK: 0x0000ff00 - * HARDIRQ_MASK: 0x000f0000 + * HARDIRQ_DISABLE_MASK: 0x00ff0000 + * HARDIRQ_MASK: 0x0f000000 * NMI_MASK: 0x10000000 * PREEMPT_NEED_RESCHED: 0x80000000 */ #define PREEMPT_BITS 8 #define SOFTIRQ_BITS 8 +#define HARDIRQ_DISABLE_BITS 8 #define HARDIRQ_BITS 4 #define NMI_BITS 1 =20 #define PREEMPT_SHIFT 0 #define SOFTIRQ_SHIFT (PREEMPT_SHIFT + PREEMPT_BITS) -#define HARDIRQ_SHIFT (SOFTIRQ_SHIFT + SOFTIRQ_BITS) +#define HARDIRQ_DISABLE_SHIFT (SOFTIRQ_SHIFT + SOFTIRQ_BITS) +#define HARDIRQ_SHIFT (HARDIRQ_DISABLE_SHIFT + HARDIRQ_DISABLE_BITS) #define NMI_SHIFT (HARDIRQ_SHIFT + HARDIRQ_BITS) =20 #define __IRQ_MASK(x) ((1UL << (x))-1) =20 #define PREEMPT_MASK (__IRQ_MASK(PREEMPT_BITS) << PREEMPT_SHIFT) #define SOFTIRQ_MASK (__IRQ_MASK(SOFTIRQ_BITS) << SOFTIRQ_SHIFT) +#define HARDIRQ_DISABLE_MASK (__IRQ_MASK(SOFTIRQ_BITS) << HARDIRQ_DISABLE_= SHIFT) #define HARDIRQ_MASK (__IRQ_MASK(HARDIRQ_BITS) << HARDIRQ_SHIFT) #define NMI_MASK (__IRQ_MASK(NMI_BITS) << NMI_SHIFT) =20 #define PREEMPT_OFFSET (1UL << PREEMPT_SHIFT) #define SOFTIRQ_OFFSET (1UL << SOFTIRQ_SHIFT) +#define HARDIRQ_DISABLE_OFFSET (1UL << HARDIRQ_DISABLE_SHIFT) #define HARDIRQ_OFFSET (1UL << HARDIRQ_SHIFT) #define NMI_OFFSET (1UL << NMI_SHIFT) =20 --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E432A30BF5D for ; Mon, 13 Oct 2025 15:54:10 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370852; cv=none; b=RwY+Uz7fkxpk0+57rg/dYCF8yiWmP2U3E7kVIsGoP6Q8RwMoRzzMDG/YOWB5Z3gQvhxvz4w/YZ1snKKQS5RYRjeP2s2tu7lq4J4iAANO8DbQjw7/PQU10robJB4ynLR4xsKHmJzZl94bogdhXpfvk22VcstSHVtT0rj9A0N+YMw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370852; c=relaxed/simple; bh=OvzJovNv1ctaRAi0qWxBvnsOPU9DoRZIj3SLiUKtWkA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=ZAlouNtgkyvAHD+N9Iztmr8BFgE9S5ajoeokznVg74Xpe7CticQxFunBbmvH07mn92eDGCJD7ulBzAF+cxX4iX71J2YTnDpN1wVszjVXLXCH7wSDF855dzZA/LR4O5FTBz5iBnnxsW6YKCCpjdPUKiv+kRKNw40pS9lPBzW8tOQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=H1Ery4GN; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="H1Ery4GN" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370850; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=wVWnS0RcSrifKORRkaxSlEBfAdbDlyJkXOwnKgyyCWE=; b=H1Ery4GNWaTQt44idTDIRD/6BQjfFEA2QYkV0b8h4Ss71woR3hsx51Vx27rCr/JZMLbpsi aMKGuR4jokU+vQ6FjSTCqXEVCM4ThdkdcTG7beP+SCQSnQ2gE+RvVka9cKtXhdSsifRsLC vp42kHMzE8QQqbY7eyPPq+QjbUsQ23Y= Received: from mx-prod-mc-04.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-104-hoQr19x9MGeShnhZzexXCg-1; Mon, 13 Oct 2025 11:54:05 -0400 X-MC-Unique: hoQr19x9MGeShnhZzexXCg-1 X-Mimecast-MFC-AGG-ID: hoQr19x9MGeShnhZzexXCg_1760370842 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-04.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id D86331954105; Mon, 13 Oct 2025 15:54:01 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 9BC8E30002D0; Mon, 13 Oct 2025 15:53:56 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Catalin Marinas , Will Deacon , Heiko Carstens , Vasily Gorbik , Alexander Gordeev , Christian Borntraeger , Sven Schnelle , Ingo Molnar , Borislav Petkov , Dave Hansen , x86@kernel.org (maintainer:X86 ARCHITECTURE (32-BIT AND 64-BIT)), "H. Peter Anvin" , Arnd Bergmann , Jinjie Ruan , Ada Couprie Diaz , Juergen Christ , Brian Gerst , Uros Bizjak , linux-arm-kernel@lists.infradead.org (moderated list:ARM64 PORT (AARCH64 ARCHITECTURE)), linux-s390@vger.kernel.org (open list:S390 ARCHITECTURE), linux-arch@vger.kernel.org (open list:GENERIC INCLUDE/ASM HEADER FILES) Subject: [PATCH v13 04/17] preempt: Introduce __preempt_count_{sub, add}_return() Date: Mon, 13 Oct 2025 11:48:06 -0400 Message-ID: <20251013155205.2004838-5-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" From: Boqun Feng In order to use preempt_count() to tracking the interrupt disable nesting level, __preempt_count_{add,sub}_return() are introduced, as their name suggest, these primitives return the new value of the preempt_count() after changing it. The following example shows the usage of it in local_interrupt_disable(): // increase the HARDIRQ_DISABLE bit new_count =3D __preempt_count_add_return(HARDIRQ_DISABLE_OFFSET); // if it's the first-time increment, then disable the interrupt // at hardware level. if (new_count & HARDIRQ_DISABLE_MASK =3D=3D HARDIRQ_DISABLE_OFFSET) { local_irq_save(flags); raw_cpu_write(local_interrupt_disable_state.flags, flags); } Having these primitives will avoid a read of preempt_count() after changing preempt_count() on certain architectures. Signed-off-by: Boqun Feng --- V10: * Add commit message I forgot * Rebase against latest pcpu_hot changes V11: * Remove CONFIG_PROFILE_ALL_BRANCHES workaround from __preempt_count_add_return() arch/arm64/include/asm/preempt.h | 18 ++++++++++++++++++ arch/s390/include/asm/preempt.h | 10 ++++++++++ arch/x86/include/asm/preempt.h | 10 ++++++++++ include/asm-generic/preempt.h | 14 ++++++++++++++ 4 files changed, 52 insertions(+) diff --git a/arch/arm64/include/asm/preempt.h b/arch/arm64/include/asm/pree= mpt.h index 932ea4b620428..0dd8221d1bef7 100644 --- a/arch/arm64/include/asm/preempt.h +++ b/arch/arm64/include/asm/preempt.h @@ -55,6 +55,24 @@ static inline void __preempt_count_sub(int val) WRITE_ONCE(current_thread_info()->preempt.count, pc); } =20 +static inline int __preempt_count_add_return(int val) +{ + u32 pc =3D READ_ONCE(current_thread_info()->preempt.count); + pc +=3D val; + WRITE_ONCE(current_thread_info()->preempt.count, pc); + + return pc; +} + +static inline int __preempt_count_sub_return(int val) +{ + u32 pc =3D READ_ONCE(current_thread_info()->preempt.count); + pc -=3D val; + WRITE_ONCE(current_thread_info()->preempt.count, pc); + + return pc; +} + static inline bool __preempt_count_dec_and_test(void) { struct thread_info *ti =3D current_thread_info(); diff --git a/arch/s390/include/asm/preempt.h b/arch/s390/include/asm/preemp= t.h index 6ccd033acfe52..5ae366e26c57d 100644 --- a/arch/s390/include/asm/preempt.h +++ b/arch/s390/include/asm/preempt.h @@ -98,6 +98,16 @@ static __always_inline bool should_resched(int preempt_o= ffset) return unlikely(READ_ONCE(get_lowcore()->preempt_count) =3D=3D preempt_of= fset); } =20 +static __always_inline int __preempt_count_add_return(int val) +{ + return val + __atomic_add(val, &get_lowcore()->preempt_count); +} + +static __always_inline int __preempt_count_sub_return(int val) +{ + return __preempt_count_add_return(-val); +} + #define init_task_preempt_count(p) do { } while (0) /* Deferred to CPU bringup time */ #define init_idle_preempt_count(p, cpu) do { } while (0) diff --git a/arch/x86/include/asm/preempt.h b/arch/x86/include/asm/preempt.h index 578441db09f0b..1220656f3370b 100644 --- a/arch/x86/include/asm/preempt.h +++ b/arch/x86/include/asm/preempt.h @@ -85,6 +85,16 @@ static __always_inline void __preempt_count_sub(int val) raw_cpu_add_4(__preempt_count, -val); } =20 +static __always_inline int __preempt_count_add_return(int val) +{ + return raw_cpu_add_return_4(__preempt_count, val); +} + +static __always_inline int __preempt_count_sub_return(int val) +{ + return raw_cpu_add_return_4(__preempt_count, -val); +} + /* * Because we keep PREEMPT_NEED_RESCHED set when we do _not_ need to resch= edule * a decrement which hits zero means we have no preempt_count and should diff --git a/include/asm-generic/preempt.h b/include/asm-generic/preempt.h index 51f8f3881523a..c8683c046615d 100644 --- a/include/asm-generic/preempt.h +++ b/include/asm-generic/preempt.h @@ -59,6 +59,20 @@ static __always_inline void __preempt_count_sub(int val) *preempt_count_ptr() -=3D val; } =20 +static __always_inline int __preempt_count_add_return(int val) +{ + *preempt_count_ptr() +=3D val; + + return *preempt_count_ptr(); +} + +static __always_inline int __preempt_count_sub_return(int val) +{ + *preempt_count_ptr() -=3D val; + + return *preempt_count_ptr(); +} + static __always_inline bool __preempt_count_dec_and_test(void) { /* --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E4F4530C352 for ; Mon, 13 Oct 2025 15:54:20 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370863; cv=none; b=hulBWK8Qlxe4hyTwFjawXRqEvf0oWUds2R2BrZhr2BhmWAQefDNibte/mW1oCeHBjLu139htnrQB+Ui3SmTDVrv8G5CyrRIgSnKHIM0R9VG3L2oxpeS67j/mjYEdGgJmFpxBRkfTmKV+rIPj13nInZBU/2HSsYyoXHd2xAD5Z4A= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370863; c=relaxed/simple; bh=+9E9r1CGuLJ9I37viVCnzQnIf8OU6kS/sUbq+eiNmgc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=g8cA9IKb5Yj5Lq9zd0AoouS53gjv1JqYoxCAbBcDxTVlE54CrxnTXVtptSQ04HZFtCBQC6Jvr+E0JcGFdKDPuSpzPYd3j8iDKHoEy7ItarRyJ1PO1pxcWwx3DO7rVzyRN+Uo5WHWHSO9qzlAEhouqrNzvs6NsNv1dbsSNIjtDfU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=Ka6y3byV; arc=none smtp.client-ip=170.10.129.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="Ka6y3byV" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370859; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=bbABfGRSOwlCFCUPD2ed7Jo3f/9REAJMn2CKzcFcwRk=; b=Ka6y3byVVfwny6oeeMMEJGITFjhiHmpIXt0FaFEFa4jL1K84TdQXMDyk/H1RCMP+RwGwpg oxiwktSuQA2xV5lvVZJO9O4kpwAP35lHR2lSXS5RYda9dcQ6beqZOLBqWN1MsHoL+/+z0g OYrVPhTaZObpbT8WAICs0FTg1790nmM= Received: from mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-111-KslJdOEVMxOsD5ddKR9ilQ-1; Mon, 13 Oct 2025 11:54:14 -0400 X-MC-Unique: KslJdOEVMxOsD5ddKR9ilQ-1 X-Mimecast-MFC-AGG-ID: KslJdOEVMxOsD5ddKR9ilQ_1760370851 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id AB4BF1800378; Mon, 13 Oct 2025 15:54:10 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 34ABE3000386; Mon, 13 Oct 2025 15:54:04 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Ingo Molnar , Peter Zijlstra , Juri Lelli , Vincent Guittot , Dietmar Eggemann , Steven Rostedt , Ben Segall , Mel Gorman , Valentin Schneider , Will Deacon , Waiman Long , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , David Woodhouse , Sebastian Andrzej Siewior , Joel Fernandes , Ryo Takakura , K Prateek Nayak Subject: [PATCH v13 05/17] irq & spin_lock: Add counted interrupt disabling/enabling Date: Mon, 13 Oct 2025 11:48:07 -0400 Message-ID: <20251013155205.2004838-6-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" From: Boqun Feng Currently the nested interrupt disabling and enabling is present by _irqsave() and _irqrestore() APIs, which are relatively unsafe, for example: spin_lock_irqsave(l1, flag1); spin_lock_irqsave(l2, flag2); spin_unlock_irqrestore(l1, flags1); // accesses to interrupt-disable protect data will cause races. This is even easier to triggered with guard facilities: unsigned long flag2; scoped_guard(spin_lock_irqsave, l1) { spin_lock_irqsave(l2, flag2); } // l2 locked but interrupts are enabled. spin_unlock_irqrestore(l2, flag2); (Hand-to-hand locking critical sections are not uncommon for a fine-grained lock design) And because this unsafety, Rust cannot easily wrap the interrupt-disabling locks in a safe API, which complicates the design. To resolve this, introduce a new set of interrupt disabling APIs: * local_interrupt_disable(); * local_interrupt_enable(); They work like local_irq_save() and local_irq_restore() except that 1) the outermost local_interrupt_disable() call save the interrupt state into a percpu variable, so that the outermost local_interrupt_enable() can restore the state, and 2) a percpu counter is added to record the nest level of these calls, so that interrupts are not accidentally enabled inside the outermost critical section. Also add the corresponding spin_lock primitives: spin_lock_irq_disable() and spin_unlock_irq_enable(), as a result, code as follow: spin_lock_irq_disable(l1); spin_lock_irq_disable(l2); spin_unlock_irq_enable(l1); // Interrupts are still disabled. spin_unlock_irq_enable(l2); doesn't have the issue that interrupts are accidentally enabled. This also makes the wrapper of interrupt-disabling locks on Rust easier to design. Signed-off-by: Boqun Feng --- V10: * Add missing __raw_spin_lock_irq_disable() definition in spinlock.c V11: * Move definition of spin_trylock_irq_disable() into this commit * Get rid of leftover space * Remove unneeded preempt_disable()/preempt_enable() V12: * Move local_interrupt_enable()/local_interrupt_disable() out of include/linux/spinlock.h, into include/linux/irqflags.h include/linux/irqflags.h | 39 ++++++++++++++++++++++++++++++++ include/linux/irqflags_types.h | 6 +++++ include/linux/preempt.h | 4 ++++ include/linux/spinlock.h | 24 ++++++++++++++++++++ include/linux/spinlock_api_smp.h | 27 ++++++++++++++++++++++ include/linux/spinlock_api_up.h | 8 +++++++ include/linux/spinlock_rt.h | 15 ++++++++++++ kernel/locking/spinlock.c | 29 ++++++++++++++++++++++++ kernel/softirq.c | 3 +++ 9 files changed, 155 insertions(+) diff --git a/include/linux/irqflags.h b/include/linux/irqflags.h index 57b074e0cfbbb..439db0b124167 100644 --- a/include/linux/irqflags.h +++ b/include/linux/irqflags.h @@ -13,6 +13,7 @@ #define _LINUX_TRACE_IRQFLAGS_H =20 #include +#include #include #include #include @@ -262,6 +263,44 @@ extern void warn_bogus_irq_restore(void); =20 #define irqs_disabled_flags(flags) raw_irqs_disabled_flags(flags) =20 +DECLARE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_st= ate); + +static inline void local_interrupt_disable(void) +{ + unsigned long flags; + int new_count; + + new_count =3D hardirq_disable_enter(); + + if ((new_count & HARDIRQ_DISABLE_MASK) =3D=3D HARDIRQ_DISABLE_OFFSET) { + local_irq_save(flags); + raw_cpu_write(local_interrupt_disable_state.flags, flags); + } +} + +static inline void local_interrupt_enable(void) +{ + int new_count; + + new_count =3D hardirq_disable_exit(); + + if ((new_count & HARDIRQ_DISABLE_MASK) =3D=3D 0) { + unsigned long flags; + + flags =3D raw_cpu_read(local_interrupt_disable_state.flags); + local_irq_restore(flags); + /* + * TODO: re-read preempt count can be avoided, but it needs + * should_resched() taking another parameter as the current + * preempt count + */ +#ifdef PREEMPTION + if (should_resched(0)) + __preempt_schedule(); +#endif + } +} + DEFINE_LOCK_GUARD_0(irq, local_irq_disable(), local_irq_enable()) DEFINE_LOCK_GUARD_0(irqsave, local_irq_save(_T->flags), diff --git a/include/linux/irqflags_types.h b/include/linux/irqflags_types.h index c13f0d915097a..277433f7f53eb 100644 --- a/include/linux/irqflags_types.h +++ b/include/linux/irqflags_types.h @@ -19,4 +19,10 @@ struct irqtrace_events { =20 #endif =20 +/* Per-cpu interrupt disabling state for local_interrupt_{disable,enable}(= ) */ +struct interrupt_disable_state { + unsigned long flags; + long count; +}; + #endif /* _LINUX_IRQFLAGS_TYPES_H */ diff --git a/include/linux/preempt.h b/include/linux/preempt.h index bbd2e51363d8f..4e0a25059fc97 100644 --- a/include/linux/preempt.h +++ b/include/linux/preempt.h @@ -153,6 +153,10 @@ static __always_inline unsigned char interrupt_context= _level(void) #define in_softirq() (softirq_count()) #define in_interrupt() (irq_count()) =20 +#define hardirq_disable_count() ((preempt_count() & HARDIRQ_DISABLE_MASK) = >> HARDIRQ_DISABLE_SHIFT) +#define hardirq_disable_enter() __preempt_count_add_return(HARDIRQ_DISABLE= _OFFSET) +#define hardirq_disable_exit() __preempt_count_sub_return(HARDIRQ_DISABLE_= OFFSET) + /* * The preempt_count offset after preempt_disable(); */ diff --git a/include/linux/spinlock.h b/include/linux/spinlock.h index d3561c4a080e2..80dfac144e10a 100644 --- a/include/linux/spinlock.h +++ b/include/linux/spinlock.h @@ -272,9 +272,11 @@ static inline void do_raw_spin_unlock(raw_spinlock_t *= lock) __releases(lock) #endif =20 #define raw_spin_lock_irq(lock) _raw_spin_lock_irq(lock) +#define raw_spin_lock_irq_disable(lock) _raw_spin_lock_irq_disable(lock) #define raw_spin_lock_bh(lock) _raw_spin_lock_bh(lock) #define raw_spin_unlock(lock) _raw_spin_unlock(lock) #define raw_spin_unlock_irq(lock) _raw_spin_unlock_irq(lock) +#define raw_spin_unlock_irq_enable(lock) _raw_spin_unlock_irq_enable(lock) =20 #define raw_spin_unlock_irqrestore(lock, flags) \ do { \ @@ -300,6 +302,13 @@ static inline void do_raw_spin_unlock(raw_spinlock_t *= lock) __releases(lock) 1 : ({ local_irq_restore(flags); 0; }); \ }) =20 +#define raw_spin_trylock_irq_disable(lock) \ +({ \ + local_interrupt_disable(); \ + raw_spin_trylock(lock) ? \ + 1 : ({ local_interrupt_enable(); 0; }); \ +}) + #ifndef CONFIG_PREEMPT_RT /* Include rwlock functions for !RT */ #include @@ -376,6 +385,11 @@ static __always_inline void spin_lock_irq(spinlock_t *= lock) raw_spin_lock_irq(&lock->rlock); } =20 +static __always_inline void spin_lock_irq_disable(spinlock_t *lock) +{ + raw_spin_lock_irq_disable(&lock->rlock); +} + #define spin_lock_irqsave(lock, flags) \ do { \ raw_spin_lock_irqsave(spinlock_check(lock), flags); \ @@ -401,6 +415,11 @@ static __always_inline void spin_unlock_irq(spinlock_t= *lock) raw_spin_unlock_irq(&lock->rlock); } =20 +static __always_inline void spin_unlock_irq_enable(spinlock_t *lock) +{ + raw_spin_unlock_irq_enable(&lock->rlock); +} + static __always_inline void spin_unlock_irqrestore(spinlock_t *lock, unsig= ned long flags) { raw_spin_unlock_irqrestore(&lock->rlock, flags); @@ -421,6 +440,11 @@ static __always_inline int spin_trylock_irq(spinlock_t= *lock) raw_spin_trylock_irqsave(spinlock_check(lock), flags); \ }) =20 +static __always_inline int spin_trylock_irq_disable(spinlock_t *lock) +{ + return raw_spin_trylock_irq_disable(&lock->rlock); +} + /** * spin_is_locked() - Check whether a spinlock is locked. * @lock: Pointer to the spinlock. diff --git a/include/linux/spinlock_api_smp.h b/include/linux/spinlock_api_= smp.h index 9ecb0ab504e32..92532103b9eaa 100644 --- a/include/linux/spinlock_api_smp.h +++ b/include/linux/spinlock_api_smp.h @@ -28,6 +28,8 @@ _raw_spin_lock_nest_lock(raw_spinlock_t *lock, struct loc= kdep_map *map) void __lockfunc _raw_spin_lock_bh(raw_spinlock_t *lock) __acquires(lock); void __lockfunc _raw_spin_lock_irq(raw_spinlock_t *lock) __acquires(lock); +void __lockfunc _raw_spin_lock_irq_disable(raw_spinlock_t *lock) + __acquires(lock); =20 unsigned long __lockfunc _raw_spin_lock_irqsave(raw_spinlock_t *lock) __acquires(lock); @@ -39,6 +41,7 @@ int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock); void __lockfunc _raw_spin_unlock(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_bh(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_irq(raw_spinlock_t *lock) __releases(lock= ); +void __lockfunc _raw_spin_unlock_irq_enable(raw_spinlock_t *lock) __releas= es(lock); void __lockfunc _raw_spin_unlock_irqrestore(raw_spinlock_t *lock, unsigned long flags) __releases(lock); @@ -55,6 +58,11 @@ _raw_spin_unlock_irqrestore(raw_spinlock_t *lock, unsign= ed long flags) #define _raw_spin_lock_irq(lock) __raw_spin_lock_irq(lock) #endif =20 +/* Use the same config as spin_lock_irq() temporarily. */ +#ifdef CONFIG_INLINE_SPIN_LOCK_IRQ +#define _raw_spin_lock_irq_disable(lock) __raw_spin_lock_irq_disable(lock) +#endif + #ifdef CONFIG_INLINE_SPIN_LOCK_IRQSAVE #define _raw_spin_lock_irqsave(lock) __raw_spin_lock_irqsave(lock) #endif @@ -79,6 +87,11 @@ _raw_spin_unlock_irqrestore(raw_spinlock_t *lock, unsign= ed long flags) #define _raw_spin_unlock_irq(lock) __raw_spin_unlock_irq(lock) #endif =20 +/* Use the same config as spin_unlock_irq() temporarily. */ +#ifdef CONFIG_INLINE_SPIN_UNLOCK_IRQ +#define _raw_spin_unlock_irq_enable(lock) __raw_spin_unlock_irq_enable(loc= k) +#endif + #ifdef CONFIG_INLINE_SPIN_UNLOCK_IRQRESTORE #define _raw_spin_unlock_irqrestore(lock, flags) __raw_spin_unlock_irqrest= ore(lock, flags) #endif @@ -120,6 +133,13 @@ static inline void __raw_spin_lock_irq(raw_spinlock_t = *lock) LOCK_CONTENDED(lock, do_raw_spin_trylock, do_raw_spin_lock); } =20 +static inline void __raw_spin_lock_irq_disable(raw_spinlock_t *lock) +{ + local_interrupt_disable(); + spin_acquire(&lock->dep_map, 0, 0, _RET_IP_); + LOCK_CONTENDED(lock, do_raw_spin_trylock, do_raw_spin_lock); +} + static inline void __raw_spin_lock_bh(raw_spinlock_t *lock) { __local_bh_disable_ip(_RET_IP_, SOFTIRQ_LOCK_OFFSET); @@ -160,6 +180,13 @@ static inline void __raw_spin_unlock_irq(raw_spinlock_= t *lock) preempt_enable(); } =20 +static inline void __raw_spin_unlock_irq_enable(raw_spinlock_t *lock) +{ + spin_release(&lock->dep_map, _RET_IP_); + do_raw_spin_unlock(lock); + local_interrupt_enable(); +} + static inline void __raw_spin_unlock_bh(raw_spinlock_t *lock) { spin_release(&lock->dep_map, _RET_IP_); diff --git a/include/linux/spinlock_api_up.h b/include/linux/spinlock_api_u= p.h index 819aeba1c87e6..d02a73671713b 100644 --- a/include/linux/spinlock_api_up.h +++ b/include/linux/spinlock_api_up.h @@ -36,6 +36,9 @@ #define __LOCK_IRQ(lock) \ do { local_irq_disable(); __LOCK(lock); } while (0) =20 +#define __LOCK_IRQ_DISABLE(lock) \ + do { local_interrupt_disable(); __LOCK(lock); } while (0) + #define __LOCK_IRQSAVE(lock, flags) \ do { local_irq_save(flags); __LOCK(lock); } while (0) =20 @@ -52,6 +55,9 @@ #define __UNLOCK_IRQ(lock) \ do { local_irq_enable(); __UNLOCK(lock); } while (0) =20 +#define __UNLOCK_IRQ_ENABLE(lock) \ + do { __UNLOCK(lock); local_interrupt_enable(); } while (0) + #define __UNLOCK_IRQRESTORE(lock, flags) \ do { local_irq_restore(flags); __UNLOCK(lock); } while (0) =20 @@ -64,6 +70,7 @@ #define _raw_read_lock_bh(lock) __LOCK_BH(lock) #define _raw_write_lock_bh(lock) __LOCK_BH(lock) #define _raw_spin_lock_irq(lock) __LOCK_IRQ(lock) +#define _raw_spin_lock_irq_disable(lock) __LOCK_IRQ_DISABLE(lock) #define _raw_read_lock_irq(lock) __LOCK_IRQ(lock) #define _raw_write_lock_irq(lock) __LOCK_IRQ(lock) #define _raw_spin_lock_irqsave(lock, flags) __LOCK_IRQSAVE(lock, flags) @@ -80,6 +87,7 @@ #define _raw_write_unlock_bh(lock) __UNLOCK_BH(lock) #define _raw_read_unlock_bh(lock) __UNLOCK_BH(lock) #define _raw_spin_unlock_irq(lock) __UNLOCK_IRQ(lock) +#define _raw_spin_unlock_irq_enable(lock) __UNLOCK_IRQ_ENABLE(lock) #define _raw_read_unlock_irq(lock) __UNLOCK_IRQ(lock) #define _raw_write_unlock_irq(lock) __UNLOCK_IRQ(lock) #define _raw_spin_unlock_irqrestore(lock, flags) \ diff --git a/include/linux/spinlock_rt.h b/include/linux/spinlock_rt.h index f6499c37157df..074182f7cfeea 100644 --- a/include/linux/spinlock_rt.h +++ b/include/linux/spinlock_rt.h @@ -93,6 +93,11 @@ static __always_inline void spin_lock_irq(spinlock_t *lo= ck) rt_spin_lock(lock); } =20 +static __always_inline void spin_lock_irq_disable(spinlock_t *lock) +{ + rt_spin_lock(lock); +} + #define spin_lock_irqsave(lock, flags) \ do { \ typecheck(unsigned long, flags); \ @@ -116,12 +121,22 @@ static __always_inline void spin_unlock_irq(spinlock_= t *lock) rt_spin_unlock(lock); } =20 +static __always_inline void spin_unlock_irq_enable(spinlock_t *lock) +{ + rt_spin_unlock(lock); +} + static __always_inline void spin_unlock_irqrestore(spinlock_t *lock, unsigned long flags) { rt_spin_unlock(lock); } =20 +static __always_inline int spin_trylock_irq_disable(spinlock_t *lock) +{ + return rt_spin_trylock(lock); +} + #define spin_trylock(lock) \ __cond_lock(lock, rt_spin_trylock(lock)) =20 diff --git a/kernel/locking/spinlock.c b/kernel/locking/spinlock.c index 7685defd7c526..da54b220b5a45 100644 --- a/kernel/locking/spinlock.c +++ b/kernel/locking/spinlock.c @@ -125,6 +125,19 @@ static void __lockfunc __raw_##op##_lock_bh(locktype##= _t *lock) \ */ BUILD_LOCK_OPS(spin, raw_spinlock); =20 +/* No rwlock_t variants for now, so just build this function by hand */ +static void __lockfunc __raw_spin_lock_irq_disable(raw_spinlock_t *lock) +{ + for (;;) { + local_interrupt_disable(); + if (likely(do_raw_spin_trylock(lock))) + break; + local_interrupt_enable(); + + arch_spin_relax(&lock->raw_lock); + } +} + #ifndef CONFIG_PREEMPT_RT BUILD_LOCK_OPS(read, rwlock); BUILD_LOCK_OPS(write, rwlock); @@ -172,6 +185,14 @@ noinline void __lockfunc _raw_spin_lock_irq(raw_spinlo= ck_t *lock) EXPORT_SYMBOL(_raw_spin_lock_irq); #endif =20 +#ifndef CONFIG_INLINE_SPIN_LOCK_IRQ +noinline void __lockfunc _raw_spin_lock_irq_disable(raw_spinlock_t *lock) +{ + __raw_spin_lock_irq_disable(lock); +} +EXPORT_SYMBOL_GPL(_raw_spin_lock_irq_disable); +#endif + #ifndef CONFIG_INLINE_SPIN_LOCK_BH noinline void __lockfunc _raw_spin_lock_bh(raw_spinlock_t *lock) { @@ -204,6 +225,14 @@ noinline void __lockfunc _raw_spin_unlock_irq(raw_spin= lock_t *lock) EXPORT_SYMBOL(_raw_spin_unlock_irq); #endif =20 +#ifndef CONFIG_INLINE_SPIN_UNLOCK_IRQ +noinline void __lockfunc _raw_spin_unlock_irq_enable(raw_spinlock_t *lock) +{ + __raw_spin_unlock_irq_enable(lock); +} +EXPORT_SYMBOL_GPL(_raw_spin_unlock_irq_enable); +#endif + #ifndef CONFIG_INLINE_SPIN_UNLOCK_BH noinline void __lockfunc _raw_spin_unlock_bh(raw_spinlock_t *lock) { diff --git a/kernel/softirq.c b/kernel/softirq.c index af47ea23aba3b..b681545eabbbe 100644 --- a/kernel/softirq.c +++ b/kernel/softirq.c @@ -88,6 +88,9 @@ EXPORT_PER_CPU_SYMBOL_GPL(hardirqs_enabled); EXPORT_PER_CPU_SYMBOL_GPL(hardirq_context); #endif =20 +DEFINE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_sta= te); +EXPORT_PER_CPU_SYMBOL_GPL(local_interrupt_disable_state); + DEFINE_PER_CPU(unsigned int, nmi_nesting); =20 /* --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id BF1FC30BBB8 for ; Mon, 13 Oct 2025 15:54:18 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370860; cv=none; b=cZ9fFx7ygmM5VjKB+rgdP89u7uc9+4vF4s5MNNBE+UPbGbZdC8tWhAUb5j0JYO6+MsV8l3C9gJbnaigHXHZKZ1NNq7L5AnP7BGVE8E5JOY53W0sk1b6oCerJB2IPbO5B3V0T3CsaZH54mPQsQVqDBP7hwGDuZbHbP9KNwM5aqS0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370860; c=relaxed/simple; bh=Sr2zSAWp/KGYw6WaiNnxX7Z/IpWgNhxXIr6TD5JxX5g=; h=From:To:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=u/ouzZrkPfSsK/gd0k2Ms6H3zBs5Ry8AgjV3P4bKhPHtALQWW/xM3ZoFTutp5nf0+2PV1Hf7wQv0p0offXSFBcTwCCHnIOe/6sb+40BwNU9TZXfAiDZ9cQsblD1N/8REjN6Wai4baAwxiIbFxKq0WD8bL6yUmpVHbcDTu20gd6k= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=bUILi4+f; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="bUILi4+f" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370857; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=ihbGN0n4ZjeRyq9wFH/xJp+DT7ttUlyQ4B7QQXTOa0w=; b=bUILi4+f0/ZjZD/dHr0wFgC+TKXHUiQ70+b6geHvhdluBbTf/RHvy98KNQHiv9H98ewoo4 9450fc39IAWOq2JW0uGuiRtGZi/sj1QlFqk4ZTOHpDM5cnDOXiAaP8t6Ts2trp5+YpGkwo Iw8VgglrdRHFn6m6oqIV0VvPuzpZsnI= Received: from mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-58-mn3dUqCWMLWC2pMyEJsJ9A-1; Mon, 13 Oct 2025 11:54:14 -0400 X-MC-Unique: mn3dUqCWMLWC2pMyEJsJ9A-1 X-Mimecast-MFC-AGG-ID: mn3dUqCWMLWC2pMyEJsJ9A_1760370852 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id D1180180034A; Mon, 13 Oct 2025 15:54:12 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 8FFF23000384; Mon, 13 Oct 2025 15:54:11 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Subject: [PATCH v13 06/17] irq: Add KUnit test for refcounted interrupt enable/disable Date: Mon, 13 Oct 2025 11:48:08 -0400 Message-ID: <20251013155205.2004838-7-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 While making changes to the refcounted interrupt patch series, at some point on my local branch I broke something and ended up writing some kunit tests for testing refcounted interrupts as a result. So, let's include these tests now that we have refcounted interrupts. Signed-off-by: Lyude Paul --- V13: * Add missing MODULE_DESCRIPTION/MODULE_LICENSE lines * Switch from kunit_test_suites(=E2=80=A6) to kunit_test_suite(=E2=80=A6) kernel/irq/Makefile | 1 + kernel/irq/refcount_interrupt_test.c | 109 +++++++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 kernel/irq/refcount_interrupt_test.c diff --git a/kernel/irq/Makefile b/kernel/irq/Makefile index 6ab3a40556670..7b5bb5510b110 100644 --- a/kernel/irq/Makefile +++ b/kernel/irq/Makefile @@ -20,3 +20,4 @@ obj-$(CONFIG_SMP) +=3D affinity.o obj-$(CONFIG_GENERIC_IRQ_DEBUGFS) +=3D debugfs.o obj-$(CONFIG_GENERIC_IRQ_MATRIX_ALLOCATOR) +=3D matrix.o obj-$(CONFIG_IRQ_KUNIT_TEST) +=3D irq_test.o +obj-$(CONFIG_KUNIT) +=3D refcount_interrupt_test.o diff --git a/kernel/irq/refcount_interrupt_test.c b/kernel/irq/refcount_int= errupt_test.c new file mode 100644 index 0000000000000..d10375743142f --- /dev/null +++ b/kernel/irq/refcount_interrupt_test.c @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit test for refcounted interrupt enable/disables. + */ + +#include +#include + +#define TEST_IRQ_ON() KUNIT_EXPECT_FALSE(test, irqs_disabled()) +#define TEST_IRQ_OFF() KUNIT_EXPECT_TRUE(test, irqs_disabled()) + +/* =3D=3D=3D=3D=3D Test cases =3D=3D=3D=3D=3D */ +static void test_single_irq_change(struct kunit *test) +{ + local_interrupt_disable(); + TEST_IRQ_OFF(); + local_interrupt_enable(); +} + +static void test_nested_irq_change(struct kunit *test) +{ + local_interrupt_disable(); + TEST_IRQ_OFF(); + local_interrupt_disable(); + TEST_IRQ_OFF(); + local_interrupt_disable(); + TEST_IRQ_OFF(); + + local_interrupt_enable(); + TEST_IRQ_OFF(); + local_interrupt_enable(); + TEST_IRQ_OFF(); + local_interrupt_enable(); + TEST_IRQ_ON(); +} + +static void test_multiple_irq_change(struct kunit *test) +{ + local_interrupt_disable(); + TEST_IRQ_OFF(); + local_interrupt_disable(); + TEST_IRQ_OFF(); + + local_interrupt_enable(); + TEST_IRQ_OFF(); + local_interrupt_enable(); + TEST_IRQ_ON(); + + local_interrupt_disable(); + TEST_IRQ_OFF(); + local_interrupt_enable(); + TEST_IRQ_ON(); +} + +static void test_irq_save(struct kunit *test) +{ + unsigned long flags; + + local_irq_save(flags); + TEST_IRQ_OFF(); + local_interrupt_disable(); + TEST_IRQ_OFF(); + local_interrupt_enable(); + TEST_IRQ_OFF(); + local_irq_restore(flags); + TEST_IRQ_ON(); + + local_interrupt_disable(); + TEST_IRQ_OFF(); + local_irq_save(flags); + TEST_IRQ_OFF(); + local_irq_restore(flags); + TEST_IRQ_OFF(); + local_interrupt_enable(); + TEST_IRQ_ON(); +} + +static struct kunit_case test_cases[] =3D { + KUNIT_CASE(test_single_irq_change), + KUNIT_CASE(test_nested_irq_change), + KUNIT_CASE(test_multiple_irq_change), + KUNIT_CASE(test_irq_save), + {}, +}; + +/* (init and exit are the same */ +static int test_init(struct kunit *test) +{ + TEST_IRQ_ON(); + + return 0; +} + +static void test_exit(struct kunit *test) +{ + TEST_IRQ_ON(); +} + +static struct kunit_suite refcount_interrupt_test_suite =3D { + .name =3D "refcount_interrupt", + .test_cases =3D test_cases, + .init =3D test_init, + .exit =3D test_exit, +}; + +kunit_test_suite(refcount_interrupt_test_suite); +MODULE_AUTHOR("Lyude Paul "); +MODULE_DESCRIPTION("Refcounted interrupt unit test suite"); +MODULE_LICENSE("GPL"); --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2B37D30E83E for ; Mon, 13 Oct 2025 15:54:28 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370870; cv=none; b=cwr4txG0MsWqAiIWyCy0la/pT4oWH9B3ZKXuLDUTYA1eFfcK6GRTEmA06m4zGJ6qJZ5QuCRYr8tRnfskAEJz6GugT31H3Kt3fiZn5P2QXZcHjAsedSZy9fs8XgGNgNj8qrcxNuzrfocmRHh24tA1maRJVUYD18Kiip4RW4kaSHQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370870; c=relaxed/simple; bh=4he4jiIAoAbyeZWVjbYkIsDNdmML3owFBrc+YzFGJVg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=LLfqrIZkzxg6EQrpKOTRtP0kScMBxbgUQ6LF5S8YdXQCQbI3whzyVCfgg+bDf5mZpnQ7IhxRWGuVfvCe47V+vLo5lZYzcqahEXUpm9jy9bahd2MC7fmlMtbTW/U8W3VRL60GGeFqIFcEluD9oCEZLBC2pM6PiweFaNHw3X1nGD4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=WPsflF9o; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="WPsflF9o" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370867; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=V0wD+yzVVKK5U4LC8P3lLzuyUM/hOvIp3NviRgZGEp0=; b=WPsflF9ok4QQK+BeqempcjUOb8IXN/GyHcf+BJtdGir6eXT8/4Mqqa1VmiLO9aVqi1x2Eq PYnHWJxqrcQEq5Q09tTyjN1I/MuidR6mhC47B6jV+1dph3Lp/6ufnxIS6NDgR/5s8Diy8K QHIfxgPxJWQ0QDmoA2QyXoikVZL9DNo= Received: from mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-496-pJdm0-gPMU2rK3jXX17KjQ-1; Mon, 13 Oct 2025 11:54:24 -0400 X-MC-Unique: pJdm0-gPMU2rK3jXX17KjQ-1 X-Mimecast-MFC-AGG-ID: pJdm0-gPMU2rK3jXX17KjQ_1760370861 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id A36CF1800288; Mon, 13 Oct 2025 15:54:21 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id CBC5630002D0; Mon, 13 Oct 2025 15:54:17 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Benno Lossin , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , Viresh Kumar , FUJITA Tomonori , Krishna Ketan Rai , Ingo Molnar , Mitchell Levy , Tamir Duberstein , Wedson Almeida Filho Subject: [PATCH v13 07/17] rust: Introduce interrupt module Date: Mon, 13 Oct 2025 11:48:09 -0400 Message-ID: <20251013155205.2004838-8-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 This introduces a module for dealing with interrupt-disabled contexts, including the ability to enable and disable interrupts along with the ability to annotate functions as expecting that IRQs are already disabled on the local CPU. [Boqun: This is based on Lyude's work on interrupt disable abstraction, I port to the new local_interrupt_disable() mechanism to make it work as a guard type. I cannot even take the credit of this design, since Lyude also brought up the same idea in zulip. Anyway, this is only for POC purpose, and of course all bugs are mine] Signed-off-by: Lyude Paul Co-developed-by: Boqun Feng Signed-off-by: Boqun Feng Reviewed-by: Benno Lossin Reviewed-by: Andreas Hindborg --- V10: * Fix documentation typos V11: * Get rid of unneeded `use bindings;` * Move ASSUME_DISABLED into assume_disabled() * Confirm using lockdep_assert_irqs_disabled() that local interrupts are in fact disabled when LocalInterruptDisabled::assume_disabled() is called. rust/helpers/helpers.c | 1 + rust/helpers/interrupt.c | 18 +++++++++ rust/helpers/sync.c | 5 +++ rust/kernel/interrupt.rs | 86 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 5 files changed, 111 insertions(+) create mode 100644 rust/helpers/interrupt.c create mode 100644 rust/kernel/interrupt.rs diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 551da6c9b5064..01ffade6c0389 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -29,6 +29,7 @@ #include "err.c" #include "irq.c" #include "fs.c" +#include "interrupt.c" #include "io.c" #include "jump_label.c" #include "kunit.c" diff --git a/rust/helpers/interrupt.c b/rust/helpers/interrupt.c new file mode 100644 index 0000000000000..f2380dd461ca5 --- /dev/null +++ b/rust/helpers/interrupt.c @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +void rust_helper_local_interrupt_disable(void) +{ + local_interrupt_disable(); +} + +void rust_helper_local_interrupt_enable(void) +{ + local_interrupt_enable(); +} + +bool rust_helper_irqs_disabled(void) +{ + return irqs_disabled(); +} diff --git a/rust/helpers/sync.c b/rust/helpers/sync.c index ff7e68b488101..45b2f519f4e2e 100644 --- a/rust/helpers/sync.c +++ b/rust/helpers/sync.c @@ -11,3 +11,8 @@ void rust_helper_lockdep_unregister_key(struct lock_class= _key *k) { lockdep_unregister_key(k); } + +void rust_helper_lockdep_assert_irqs_disabled(void) +{ + lockdep_assert_irqs_disabled(); +} diff --git a/rust/kernel/interrupt.rs b/rust/kernel/interrupt.rs new file mode 100644 index 0000000000000..6c8d2f58bca70 --- /dev/null +++ b/rust/kernel/interrupt.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Interrupt controls +//! +//! This module allows Rust code to annotate areas of code where local pro= cessor interrupts should +//! be disabled, along with actually disabling local processor interrupts. +//! +//! # =E2=9A=A0=EF=B8=8F Warning! =E2=9A=A0=EF=B8=8F +//! +//! The usage of this module can be more complicated than meets the eye, e= specially surrounding +//! [preemptible kernels]. It's recommended to take care when using the fu= nctions and types defined +//! here and familiarize yourself with the various documentation we have b= efore using them, along +//! with the various documents we link to here. +//! +//! # Reading material +//! +//! - [Software interrupts and realtime (LWN)](https://lwn.net/Articles/52= 0076) +//! +//! [preemptible kernels]: https://www.kernel.org/doc/html/latest/locking/= preempt-locking.html + +use kernel::types::NotThreadSafe; + +/// A guard that represents local processor interrupt disablement on preem= ptible kernels. +/// +/// [`LocalInterruptDisabled`] is a guard type that represents that local = processor interrupts have +/// been disabled on a preemptible kernel. +/// +/// Certain functions take an immutable reference of [`LocalInterruptDisab= led`] in order to require +/// that they may only be run in local-interrupt-disabled contexts on pree= mptible kernels. +/// +/// This is a marker type; it has no size, and is simply used as a compile= -time guarantee that local +/// processor interrupts are disabled on preemptible kernels. Note that no= guarantees about the +/// state of interrupts are made by this type on non-preemptible kernels. +/// +/// # Invariants +/// +/// Local processor interrupts are disabled on preemptible kernels for as = long as an object of this +/// type exists. +pub struct LocalInterruptDisabled(NotThreadSafe); + +/// Disable local processor interrupts on a preemptible kernel. +/// +/// This function disables local processor interrupts on a preemptible ker= nel, and returns a +/// [`LocalInterruptDisabled`] token as proof of this. On non-preemptible = kernels, this function is +/// a no-op. +/// +/// **Usage of this function is discouraged** unless you are absolutely su= re you know what you are +/// doing, as kernel interfaces for rust that deal with interrupt state wi= ll typically handle local +/// processor interrupt state management on their own and managing this by= hand is quite error +/// prone. +pub fn local_interrupt_disable() -> LocalInterruptDisabled { + // SAFETY: It's always safe to call `local_interrupt_disable()`. + unsafe { bindings::local_interrupt_disable() }; + + LocalInterruptDisabled(NotThreadSafe) +} + +impl Drop for LocalInterruptDisabled { + fn drop(&mut self) { + // SAFETY: Per type invariants, a `local_interrupt_disable()` must= be called to create this + // object, hence call the corresponding `local_interrupt_enable()`= is safe. + unsafe { bindings::local_interrupt_enable() }; + } +} + +impl LocalInterruptDisabled { + /// Assume that local processor interrupts are disabled on preemptible= kernels. + /// + /// This can be used for annotating code that is known to be run in co= ntexts where local + /// processor interrupts are disabled on preemptible kernels. It makes= no changes to the local + /// interrupt state on its own. + /// + /// # Safety + /// + /// For the whole life `'a`, local interrupts must be disabled on pree= mptible kernels. This + /// could be a context like for example, an interrupt handler. + pub unsafe fn assume_disabled<'a>() -> &'a LocalInterruptDisabled { + const ASSUME_DISABLED: &LocalInterruptDisabled =3D &LocalInterrupt= Disabled(NotThreadSafe); + + // Confirm they're actually disabled if lockdep is available + // SAFETY: It's always safe to call `lockdep_assert_irqs_disabled(= )` + unsafe { bindings::lockdep_assert_irqs_disabled() }; + + ASSUME_DISABLED + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 3dd7bebe78882..75a466d9319b2 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -96,6 +96,7 @@ pub mod fs; pub mod id_pool; pub mod init; +pub mod interrupt; pub mod io; pub mod ioctl; pub mod iov; --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 868EC30C349 for ; Mon, 13 Oct 2025 15:54:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370874; cv=none; b=YY8d7IRIZPvPJmQaanByxwfk8Kc4A6ZmpyiAYXkSFO1OPrnrsQNHYzxRP7Kl1VvoupvzwuhV9Fjla3zxaA1sKrZPWnXUtLgcTbPbY6GiBa1gaP4+ukBq0C0FmSSVYoHpWBGVjybtIwq6AbyOUIH6fADpB1pAwRf0yUN6sHgpJ2Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370874; c=relaxed/simple; bh=foIGyWrqMyymH0NNnQeXIY5UOAZIW9xQsIxg3P+q67k=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=aX0ReKyrpO1cWZldE6z8FjcWUla9NLfWmrqbE/S0QKHQGAX4I3sTLEEJsiqUlqo34MwoaEjk1/AZFk5kNR20ceLmAdICr/E5BaHT2jXYBn3yUf+dEArMVmMvw3jN5L3eQLD/2C2vPQMvOm12Rm8yQ4B1yr/GQvBW361aosLag7A= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=UoViahLk; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="UoViahLk" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370871; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=HJhEp2LAGRhkIca8lz9vxyIiHP8wRjw4VX8WQB4u9HM=; b=UoViahLkOXBBHd84tFpD01sU7SrxEYdaO36eHgNa8NiJ822SJF6Kr3gGZ8FBVnoKpyF2tb SxzAL1vbZ+XbhgHua7wcgpjDpr8wIS9Qti2w42pBFJJ7QHg9bzKi9dVwKRN++s3uzLluU9 D1tQCC1xYbHGKu3+G/J/mUAFzSGjF/E= Received: from mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-282-RvvP-grKMACg6WajSGWUOg-1; Mon, 13 Oct 2025 11:54:28 -0400 X-MC-Unique: RvvP-grKMACg6WajSGWUOg-1 X-Mimecast-MFC-AGG-ID: RvvP-grKMACg6WajSGWUOg_1760370866 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id B611B1800451; Mon, 13 Oct 2025 15:54:25 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 054803000384; Mon, 13 Oct 2025 15:54:21 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Subject: [PATCH v13 08/17] rust: helper: Add spin_{un,}lock_irq_{enable,disable}() helpers Date: Mon, 13 Oct 2025 11:48:10 -0400 Message-ID: <20251013155205.2004838-9-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" From: Boqun Feng spin_lock_irq_disable() and spin_unlock_irq_enable() are inline functions, to use them in Rust, helpers are introduced. This is for interrupt disabling lock abstraction in Rust. Signed-off-by: Boqun Feng Signed-off-by: Lyude Paul Reviewed-by: Andreas Hindborg --- rust/helpers/spinlock.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/rust/helpers/spinlock.c b/rust/helpers/spinlock.c index 42c4bf01a23e4..d4e61057c2a7a 100644 --- a/rust/helpers/spinlock.c +++ b/rust/helpers/spinlock.c @@ -35,3 +35,18 @@ void rust_helper_spin_assert_is_held(spinlock_t *lock) { lockdep_assert_held(lock); } + +void rust_helper_spin_lock_irq_disable(spinlock_t *lock) +{ + spin_lock_irq_disable(lock); +} + +void rust_helper_spin_unlock_irq_enable(spinlock_t *lock) +{ + spin_unlock_irq_enable(lock); +} + +int rust_helper_spin_trylock_irq_disable(spinlock_t *lock) +{ + return spin_trylock_irq_disable(lock); +} --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id ED64630F522 for ; Mon, 13 Oct 2025 15:54:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370882; cv=none; b=LX0wRCsbj9cecWIaNK6t1RI5v7W3YZTzj9bn+PK1R18utu03zt46bz3f4vWkORXVpm4/NfIxbtqEF9WNJebaYmDlerAixfxwDTHcN/tEet2XXCQtngypw/NEWGU5S41jdo1jpbDqz30Y0DH2jZINqdnnDfs/s8phxOOR+QBYPlY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370882; c=relaxed/simple; bh=Og7WSW0vevPcua5L9mzCDNQPoTvIT+qt2a2wGpOuN68=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=cXGXGI2vOEbOJHAaUUbiaxq+WLkc+jPhHrhP8Pt/Sy4y0FyDiWPKDYJoWNDVvhRPI5in7Yn6j9u+5cJvPZE8RaKBHd+zV5Dso9W9LJXJnhr3oEAWfRcJWtCrnGRZcV8fgpuDwt2aGKHS+FpPng5ZJgC88tLp9VNzj9hxGGrNofA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=FghZPcU5; arc=none smtp.client-ip=170.10.129.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="FghZPcU5" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370880; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=08Hx604JvIL8PyclYrLwIO9JXFUdUaBjFIx/uexuLLI=; b=FghZPcU5g1K78X1zFSsGok9lvNkmfR7tF26Xlpxyphoz+EuUJBTDzB1KvH54qNl4Bx5x78 kYS1TM5w0mC8Kbv4fupwmhzjpwx0h0G7vTgWt4eg3JW3wFJ/smW3KyK9AlyY3Y1oTuiZHQ RUl7mLeLhUNDVrzhJvPiD8foTo1KXfU= Received: from mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-157-Ra-_bymdOoKPHottX55l5g-1; Mon, 13 Oct 2025 11:54:33 -0400 X-MC-Unique: Ra-_bymdOoKPHottX55l5g-1 X-Mimecast-MFC-AGG-ID: Ra-_bymdOoKPHottX55l5g_1760370871 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id EE8BD1956096; Mon, 13 Oct 2025 15:54:30 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id B61A130002D0; Mon, 13 Oct 2025 15:54:26 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Mitchell Levy , Shankari Anand , Wedson Almeida Filho Subject: [PATCH v13 09/17] rust: sync: Add SpinLockIrq Date: Mon, 13 Oct 2025 11:48:11 -0400 Message-ID: <20251013155205.2004838-10-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" A variant of SpinLock that is expected to be used in noirq contexts, so lock() will disable interrupts and unlock() (i.e. `Guard::drop()` will undo the interrupt disable. [Boqun: Port to use spin_lock_irq_disable() and spin_unlock_irq_enable()] Signed-off-by: Lyude Paul Co-developed-by: Boqun Feng Signed-off-by: Boqun Feng Reviewed-by: Andreas Hindborg --- V10: * Also add support to GlobalLock * Documentation fixes from Dirk V11: * Add unit test requested by Daniel Almeida rust/kernel/sync.rs | 4 +- rust/kernel/sync/lock/global.rs | 3 + rust/kernel/sync/lock/spinlock.rs | 229 ++++++++++++++++++++++++++++++ 3 files changed, 235 insertions(+), 1 deletion(-) diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index cf5b638a097d9..f293bbe13e855 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -26,7 +26,9 @@ pub use condvar::{new_condvar, CondVar, CondVarTimeoutResult}; pub use lock::global::{global_lock, GlobalGuard, GlobalLock, GlobalLockBac= kend, GlobalLockedBy}; pub use lock::mutex::{new_mutex, Mutex, MutexGuard}; -pub use lock::spinlock::{new_spinlock, SpinLock, SpinLockGuard}; +pub use lock::spinlock::{ + new_spinlock, new_spinlock_irq, SpinLock, SpinLockGuard, SpinLockIrq, = SpinLockIrqGuard, +}; pub use locked_by::LockedBy; pub use refcount::Refcount; =20 diff --git a/rust/kernel/sync/lock/global.rs b/rust/kernel/sync/lock/global= .rs index d65f94b5caf26..47e200b750c1d 100644 --- a/rust/kernel/sync/lock/global.rs +++ b/rust/kernel/sync/lock/global.rs @@ -299,4 +299,7 @@ macro_rules! global_lock_inner { (backend SpinLock) =3D> { $crate::sync::lock::spinlock::SpinLockBackend }; + (backend SpinLockIrq) =3D> { + $crate::sync::lock::spinlock::SpinLockIrqBackend + }; } diff --git a/rust/kernel/sync/lock/spinlock.rs b/rust/kernel/sync/lock/spin= lock.rs index d7be38ccbdc7d..6e6d571acd90c 100644 --- a/rust/kernel/sync/lock/spinlock.rs +++ b/rust/kernel/sync/lock/spinlock.rs @@ -3,6 +3,7 @@ //! A kernel spinlock. //! //! This module allows Rust code to use the kernel's `spinlock_t`. +use crate::prelude::*; =20 /// Creates a [`SpinLock`] initialiser with the given name and a newly-cre= ated lock class. /// @@ -139,3 +140,231 @@ unsafe fn assert_is_held(ptr: *mut Self::State) { unsafe { bindings::spin_assert_is_held(ptr) } } } + +/// Creates a [`SpinLockIrq`] initialiser with the given name and a newly-= created lock class. +/// +/// It uses the name if one is given, otherwise it generates one based on = the file name and line +/// number. +#[macro_export] +macro_rules! new_spinlock_irq { + ($inner:expr $(, $name:literal)? $(,)?) =3D> { + $crate::sync::SpinLockIrq::new( + $inner, $crate::optional_name!($($name)?), $crate::static_lock= _class!()) + }; +} +pub use new_spinlock_irq; + +/// A spinlock that may be acquired when local processor interrupts are di= sabled. +/// +/// This is a version of [`SpinLock`] that can only be used in contexts wh= ere interrupts for the +/// local CPU are disabled. It can be acquired in two ways: +/// +/// - Using [`lock()`] like any other type of lock, in which case the bind= ings will modify the +/// interrupt state to ensure that local processor interrupts remain dis= abled for at least as long +/// as the [`SpinLockIrqGuard`] exists. +/// - Using [`lock_with()`] in contexts where a [`LocalInterruptDisabled`]= token is present and +/// local processor interrupts are already known to be disabled, in whic= h case the local interrupt +/// state will not be touched. This method should be preferred if a [`Lo= calInterruptDisabled`] +/// token is present in the scope. +/// +/// For more info on spinlocks, see [`SpinLock`]. For more information on = interrupts, +/// [see the interrupt module](kernel::interrupt). +/// +/// # Examples +/// +/// The following example shows how to declare, allocate initialise and ac= cess a struct (`Example`) +/// that contains an inner struct (`Inner`) that is protected by a spinloc= k that requires local +/// processor interrupts to be disabled. +/// +/// ``` +/// use kernel::sync::{new_spinlock_irq, SpinLockIrq}; +/// +/// struct Inner { +/// a: u32, +/// b: u32, +/// } +/// +/// #[pin_data] +/// struct Example { +/// #[pin] +/// c: SpinLockIrq, +/// #[pin] +/// d: SpinLockIrq, +/// } +/// +/// impl Example { +/// fn new() -> impl PinInit { +/// pin_init!(Self { +/// c <- new_spinlock_irq!(Inner { a: 0, b: 10 }), +/// d <- new_spinlock_irq!(Inner { a: 20, b: 30 }), +/// }) +/// } +/// } +/// +/// // Allocate a boxed `Example` +/// let e =3D KBox::pin_init(Example::new(), GFP_KERNEL)?; +/// +/// // Accessing an `Example` from a context where interrupts may not be d= isabled already. +/// let c_guard =3D e.c.lock(); // interrupts are disabled now, +1 interru= pt disable refcount +/// let d_guard =3D e.d.lock(); // no interrupt state change, +1 interrupt= disable refcount +/// +/// assert_eq!(c_guard.a, 0); +/// assert_eq!(c_guard.b, 10); +/// assert_eq!(d_guard.a, 20); +/// assert_eq!(d_guard.b, 30); +/// +/// drop(c_guard); // Dropping c_guard will not re-enable interrupts just = yet, since d_guard is +/// // still in scope. +/// drop(d_guard); // Last interrupt disable reference dropped here, so in= terrupts are re-enabled +/// // now +/// # Ok::<(), Error>(()) +/// ``` +/// +/// [`lock()`]: SpinLockIrq::lock +/// [`lock_with()`]: SpinLockIrq::lock_with +pub type SpinLockIrq =3D super::Lock; + +/// A kernel `spinlock_t` lock backend that is acquired in interrupt disab= led contexts. +pub struct SpinLockIrqBackend; + +/// A [`Guard`] acquired from locking a [`SpinLockIrq`] using [`lock()`]. +/// +/// This is simply a type alias for a [`Guard`] returned from locking a [`= SpinLockIrq`] using +/// [`lock_with()`]. It will unlock the [`SpinLockIrq`] and decrement the = local processor's +/// interrupt disablement refcount upon being dropped. +/// +/// [`Guard`]: super::Guard +/// [`lock()`]: SpinLockIrq::lock +/// [`lock_with()`]: SpinLockIrq::lock_with +pub type SpinLockIrqGuard<'a, T> =3D super::Guard<'a, T, SpinLockIrqBacken= d>; + +// SAFETY: The underlying kernel `spinlock_t` object ensures mutual exclus= ion. `relock` uses the +// default implementation that always calls the same locking method. +unsafe impl super::Backend for SpinLockIrqBackend { + type State =3D bindings::spinlock_t; + type GuardState =3D (); + + unsafe fn init( + ptr: *mut Self::State, + name: *const crate::ffi::c_char, + key: *mut bindings::lock_class_key, + ) { + // SAFETY: The safety requirements ensure that `ptr` is valid for = writes, and `name` and + // `key` are valid for read indefinitely. + unsafe { bindings::__spin_lock_init(ptr, name, key) } + } + + unsafe fn lock(ptr: *mut Self::State) -> Self::GuardState { + // SAFETY: The safety requirements of this function ensure that `p= tr` points to valid + // memory, and that it has been initialised before. + unsafe { bindings::spin_lock_irq_disable(ptr) } + } + + unsafe fn unlock(ptr: *mut Self::State, _guard_state: &Self::GuardStat= e) { + // SAFETY: The safety requirements of this function ensure that `p= tr` is valid and that the + // caller is the owner of the spinlock. + unsafe { bindings::spin_unlock_irq_enable(ptr) } + } + + unsafe fn try_lock(ptr: *mut Self::State) -> Option { + // SAFETY: The `ptr` pointer is guaranteed to be valid and initial= ized before use. + let result =3D unsafe { bindings::spin_trylock_irq_disable(ptr) }; + + if result !=3D 0 { + Some(()) + } else { + None + } + } + + unsafe fn assert_is_held(ptr: *mut Self::State) { + // SAFETY: The `ptr` pointer is guaranteed to be valid and initial= ized before use. + unsafe { bindings::spin_assert_is_held(ptr) } + } +} + +#[kunit_tests(rust_spinlock_irq_condvar)] +mod tests { + use super::*; + use crate::{ + sync::*, + workqueue::{self, impl_has_work, new_work, Work, WorkItem}, + }; + + struct TestState { + value: u32, + waiter_ready: bool, + } + + #[pin_data] + struct Test { + #[pin] + state: SpinLockIrq, + + #[pin] + state_changed: CondVar, + + #[pin] + waiter_state_changed: CondVar, + + #[pin] + wait_work: Work, + } + + impl_has_work! { + impl HasWork for Test { self.wait_work } + } + + impl Test { + pub(crate) fn new() -> Result> { + Arc::try_pin_init( + try_pin_init!( + Self { + state <- new_spinlock_irq!(TestState { + value: 1, + waiter_ready: false + }), + state_changed <- new_condvar!(), + waiter_state_changed <- new_condvar!(), + wait_work <- new_work!("IrqCondvarTest::wait_work") + } + ), + GFP_KERNEL, + ) + } + } + + impl WorkItem for Test { + type Pointer =3D Arc; + + fn run(this: Arc) { + // Wait for the test to be ready to wait for us + let mut state =3D this.state.lock(); + + while !state.waiter_ready { + this.waiter_state_changed.wait(&mut state); + } + + // Deliver the exciting value update our test has been waiting= for + state.value +=3D 1; + this.state_changed.notify_sync(); + } + } + + #[test] + fn spinlock_irq_condvar() -> Result { + let testdata =3D Test::new()?; + + let _ =3D workqueue::system().enqueue(testdata.clone()); + + // Let the updater know when we're ready to wait + let mut state =3D testdata.state.lock(); + state.waiter_ready =3D true; + testdata.waiter_state_changed.notify_sync(); + + // Wait for the exciting value update + testdata.state_changed.wait(&mut state); + assert_eq!(state.value, 2); + Ok(()) + } +} --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 975DB30EF96 for ; Mon, 13 Oct 2025 15:54:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370882; cv=none; b=rmrZOkvgp1xpp8En/luhRGlD+/wawM5I49+77MjIXLpOO3CjynEB3yX9g3xOHL6ca6Xd1INZMShnWZHVeoFGDm6PWKUQLf0UQfwsTarEqFpyAc1RR3GoJO67Z+A10dGXT6tjJOXKBNxwXEBFsKwpAP2tRTM4LIKd7tFIpjmJNbI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370882; c=relaxed/simple; bh=vduko4sGUpP7pjMVck+KUjdVmIvmQ9r4zWWxZQSS4iA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=dU0NCDRFmaPNMInB10CHPsBtM2IUACNDljhI28RneGRKqLKUertdINinwgSMPGhPYs28pVmgi1+EBx5RlQ2WRqT1QJzdkI+tEwgrIr/SNl1sv/6jGyRBNUnU8uXYH0G8EcKII7CBVTP0q8pfvzxmMAd4WGb1b27QtjbHNTlsTJE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=i3zQMnZT; arc=none smtp.client-ip=170.10.129.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="i3zQMnZT" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370879; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=8oZkaOhh491/dt/LBPcIdZtDtOEojeqJg0p/jpHGuJg=; b=i3zQMnZT1b/2vwKq9sVLtOFlPJb49JDyBCkmdNfrSS9Y665YIRE1T6U5xtFCJWaId9XtJP w2WsQgr88f48JUgqZx5mv0txkyot3OGrbMGGht8fYMP0xSb+iPJztQJQuN3X6a+whBPpw5 z1UyItgZhqJg+WFSvF8REncZYuy0R5Q= Received: from mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-515-6wU7HW9KNG2nNODMD7Uq_Q-1; Mon, 13 Oct 2025 11:54:36 -0400 X-MC-Unique: 6wU7HW9KNG2nNODMD7Uq_Q-1 X-Mimecast-MFC-AGG-ID: 6wU7HW9KNG2nNODMD7Uq_Q_1760370874 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 349E419560B7; Mon, 13 Oct 2025 15:54:34 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 663A43000382; Mon, 13 Oct 2025 15:54:31 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Subject: [PATCH v13 10/17] rust: sync: Introduce lock::Backend::Context Date: Mon, 13 Oct 2025 11:48:12 -0400 Message-ID: <20251013155205.2004838-11-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" Now that we've introduced an `InterruptDisabled` token for marking contexts in which IRQs are disabled, we can have a way to avoid `SpinLockIrq` disabling interrupts if the interrupts have already been disabled. Basically, a `SpinLockIrq` should work like a `SpinLock` if interrupts are disabled. So a function: (&'a SpinLockIrq, &'a InterruptDisabled) -> Guard<'a, .., SpinLockBackend> makes senses. Note that due to `Guard` and `InterruptDisabled` having the same lifetime, interrupts cannot be enabled while the Guard exists. Add a `lock_with()` interface for `Lock`, and an associate type of `Backend` to describe the context. Signed-off-by: Lyude Paul Co-developed-by: Boqun Feng Signed-off-by: Boqun Feng --- V10: - Fix typos - Dirk rust/kernel/sync/lock.rs | 12 +++++++++++- rust/kernel/sync/lock/mutex.rs | 1 + rust/kernel/sync/lock/spinlock.rs | 4 +++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs index 27202beef90c8..ae42458bff1c0 100644 --- a/rust/kernel/sync/lock.rs +++ b/rust/kernel/sync/lock.rs @@ -44,6 +44,9 @@ pub unsafe trait Backend { /// [`unlock`]: Backend::unlock type GuardState; =20 + /// The context which can be provided to acquire the lock with a diffe= rent backend. + type Context<'a>; + /// Initialises the lock. /// /// # Safety @@ -163,8 +166,15 @@ pub unsafe fn from_raw<'a>(ptr: *mut B::State) -> &'a = Self { } =20 impl Lock { + /// Acquires the lock with the given context and gives the caller acce= ss to the data protected + /// by it. + pub fn lock_with<'a>(&'a self, _context: B::Context<'a>) -> Guard<'a, = T, B> { + todo!() + } + /// Acquires the lock and gives the caller access to the data protecte= d by it. - pub fn lock(&self) -> Guard<'_, T, B> { + #[inline] + pub fn lock<'a>(&'a self) -> Guard<'a, T, B> { // SAFETY: The constructor of the type calls `init`, so the existe= nce of the object proves // that `init` was called. let state =3D unsafe { B::lock(self.state.get()) }; diff --git a/rust/kernel/sync/lock/mutex.rs b/rust/kernel/sync/lock/mutex.rs index 581cee7ab842a..be1e2e18cf42d 100644 --- a/rust/kernel/sync/lock/mutex.rs +++ b/rust/kernel/sync/lock/mutex.rs @@ -101,6 +101,7 @@ macro_rules! new_mutex { unsafe impl super::Backend for MutexBackend { type State =3D bindings::mutex; type GuardState =3D (); + type Context<'a> =3D (); =20 unsafe fn init( ptr: *mut Self::State, diff --git a/rust/kernel/sync/lock/spinlock.rs b/rust/kernel/sync/lock/spin= lock.rs index 6e6d571acd90c..73a7ec554baac 100644 --- a/rust/kernel/sync/lock/spinlock.rs +++ b/rust/kernel/sync/lock/spinlock.rs @@ -3,7 +3,7 @@ //! A kernel spinlock. //! //! This module allows Rust code to use the kernel's `spinlock_t`. -use crate::prelude::*; +use crate::{interrupt::LocalInterruptDisabled, prelude::*}; =20 /// Creates a [`SpinLock`] initialiser with the given name and a newly-cre= ated lock class. /// @@ -101,6 +101,7 @@ macro_rules! new_spinlock { unsafe impl super::Backend for SpinLockBackend { type State =3D bindings::spinlock_t; type GuardState =3D (); + type Context<'a> =3D (); =20 unsafe fn init( ptr: *mut Self::State, @@ -243,6 +244,7 @@ macro_rules! new_spinlock_irq { unsafe impl super::Backend for SpinLockIrqBackend { type State =3D bindings::spinlock_t; type GuardState =3D (); + type Context<'a> =3D &'a LocalInterruptDisabled; =20 unsafe fn init( ptr: *mut Self::State, --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A166030F549 for ; Mon, 13 Oct 2025 15:54:45 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370887; cv=none; b=XmXsWyKExE6jf6nvCBQxC0gez85Th9kiax0BoprL80ps3/knqO20FhwqF/u0n0SBnQ2jzwbWk10/klu0z9/M2uIlEZ2wSR0f8eXidEAfZbxbaMzdORni34O9f+67WtTJE8dVpwB2KMfN4O+AWkY1FDlbaDcd6/7yzxCh7mSPJEM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370887; c=relaxed/simple; bh=GxnT3/FlLlGVb7q6mi1v55NznU43HPXkReU6ZUFPFnI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=QiKMmvsPzCI7vPn/P76Q4NC7Q11p6Ws9JflCYyHec4f52+4E8/vgyAaARrPRtVysh3kU76ZLc/f/EuNu3fzr3qRgmxLU9fzUFUqWpjfc/86PGUUEO5fFVs4E/b0mJDzES7QKkNDAysrzrbpWwyRrOYfnDU1yZ669QGyJFmm+Hfw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=C84k2+WJ; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="C84k2+WJ" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370884; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=fhtkQPVAa1XptEVRdqKo0p52z9KBMa6sJD3KnkQXSYk=; b=C84k2+WJm9y4mAV7L5HxepU5P8MaMk7IXrqgMWBhAHdG1bBa0Bq2+ORYTh1+XS7UMOd6dt PYZhyE43RQH2KZ7pxXrWqFaoC58bVRo2DobrPzsJJENEx4HNRtiH3KTf1/IUXiTXTPrE85 LPZVn1QRS/E4obPlcFtnnVR/zS0CNek= Received: from mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-298-9bC3BAlKNyuximHpUHUMwA-1; Mon, 13 Oct 2025 11:54:40 -0400 X-MC-Unique: 9bC3BAlKNyuximHpUHUMwA-1 X-Mimecast-MFC-AGG-ID: 9bC3BAlKNyuximHpUHUMwA_1760370878 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id E8CD0180045C; Mon, 13 Oct 2025 15:54:37 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id B245C3000386; Mon, 13 Oct 2025 15:54:34 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Subject: [PATCH v13 11/17] rust: sync: lock: Add `Backend::BackendInContext` Date: Mon, 13 Oct 2025 11:48:13 -0400 Message-ID: <20251013155205.2004838-12-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" From: Boqun Feng `SpinLock`'s backend can be used for `SpinLockIrq`, if the interrupts are disabled. And it actually provides performance gains since interrupts are not needed to be disabled anymore. So add `Backend::BackendInContext` to describe the case where one backend can be used for another. Use it to implement the `lock_with()` so that `SpinLockIrq` can avoid disabling interrupts by using `SpinLock`'s backend. Signed-off-by: Boqun Feng Co-developed-by: Lyude Paul Signed-off-by: Lyude Paul --- V10: * Fix typos - Dirk/Lyude * Since we're adding support for context locks to GlobalLock as well, let's also make sure to cover try_lock while we're at it and add try_lock_with * Add a private function as_lock_in_context() for handling casting from a Lock to Lock so we don't have to duplicate safety comments V11: * Fix clippy::ref_as_ptr error in Lock::as_lock_in_context() rust/kernel/sync/lock.rs | 61 ++++++++++++++++++++++++++++++- rust/kernel/sync/lock/mutex.rs | 1 + rust/kernel/sync/lock/spinlock.rs | 41 +++++++++++++++++++++ 3 files changed, 101 insertions(+), 2 deletions(-) diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs index ae42458bff1c0..36c8ae2cef1aa 100644 --- a/rust/kernel/sync/lock.rs +++ b/rust/kernel/sync/lock.rs @@ -30,10 +30,15 @@ /// is owned, that is, between calls to [`lock`] and [`unlock`]. /// - Implementers must also ensure that [`relock`] uses the same locking = method as the original /// lock operation. +/// - Implementers must ensure if [`BackendInContext`] is a [`Backend`], i= t's safe to acquire the +/// lock under the [`Context`], the [`State`] of two backends must be th= e same. /// /// [`lock`]: Backend::lock /// [`unlock`]: Backend::unlock /// [`relock`]: Backend::relock +/// [`BackendInContext`]: Backend::BackendInContext +/// [`Context`]: Backend::Context +/// [`State`]: Backend::State pub unsafe trait Backend { /// The state required by the lock. type State; @@ -47,6 +52,9 @@ pub unsafe trait Backend { /// The context which can be provided to acquire the lock with a diffe= rent backend. type Context<'a>; =20 + /// The alternative backend we can use if a [`Context`](Backend::Conte= xt) is provided. + type BackendInContext: Sized; + /// Initialises the lock. /// /// # Safety @@ -166,10 +174,59 @@ pub unsafe fn from_raw<'a>(ptr: *mut B::State) -> &'a= Self { } =20 impl Lock { + /// Casts the lock as a `Lock`. + fn as_lock_in_context<'a>( + &'a self, + _context: B::Context<'a>, + ) -> &'a Lock + where + B::BackendInContext: Backend, + { + // SAFETY: + // - Per the safety guarantee of `Backend`, if `B::BackendInContex= t` and `B` should + // have the same state, the layout of the lock is the same so it= 's safe to convert one to + // another. + // - The caller provided `B::Context<'a>`, so it is safe to recast= and return this lock. + unsafe { &*(core::ptr::from_ref(self) as *const _) } + } + /// Acquires the lock with the given context and gives the caller acce= ss to the data protected /// by it. - pub fn lock_with<'a>(&'a self, _context: B::Context<'a>) -> Guard<'a, = T, B> { - todo!() + pub fn lock_with<'a>(&'a self, context: B::Context<'a>) -> Guard<'a, T= , B::BackendInContext> + where + B::BackendInContext: Backend, + { + let lock =3D self.as_lock_in_context(context); + + // SAFETY: The constructor of the type calls `init`, so the existe= nce of the object proves + // that `init` was called. Plus the safety guarantee of `Backend` = guarantees that `B::State` + // is the same as `B::BackendInContext::State`, also it's safe to = call another backend + // because there is `B::Context<'a>`. + let state =3D unsafe { B::BackendInContext::lock(lock.state.get())= }; + + // SAFETY: The lock was just acquired. + unsafe { Guard::new(lock, state) } + } + + /// Tries to acquire the lock with the given context. + /// + /// Returns a guard that can be used to access the data protected by t= he lock if successful. + pub fn try_lock_with<'a>( + &'a self, + context: B::Context<'a>, + ) -> Option> + where + B::BackendInContext: Backend, + { + let lock =3D self.as_lock_in_context(context); + + // SAFETY: The constructor of the type calls `init`, so the existe= nce of the object proves + // that `init` was called. Plus the safety guarantee of `Backend` = guarantees that `B::State` + // is the same as `B::BackendInContext::State`, also it's safe to = call another backend + // because there is `B::Context<'a>`. + unsafe { + B::BackendInContext::try_lock(lock.state.get()).map(|state| Gu= ard::new(lock, state)) + } } =20 /// Acquires the lock and gives the caller access to the data protecte= d by it. diff --git a/rust/kernel/sync/lock/mutex.rs b/rust/kernel/sync/lock/mutex.rs index be1e2e18cf42d..662a530750703 100644 --- a/rust/kernel/sync/lock/mutex.rs +++ b/rust/kernel/sync/lock/mutex.rs @@ -102,6 +102,7 @@ unsafe impl super::Backend for MutexBackend { type State =3D bindings::mutex; type GuardState =3D (); type Context<'a> =3D (); + type BackendInContext =3D (); =20 unsafe fn init( ptr: *mut Self::State, diff --git a/rust/kernel/sync/lock/spinlock.rs b/rust/kernel/sync/lock/spin= lock.rs index 73a7ec554baac..68cbd225c3860 100644 --- a/rust/kernel/sync/lock/spinlock.rs +++ b/rust/kernel/sync/lock/spinlock.rs @@ -102,6 +102,7 @@ unsafe impl super::Backend for SpinLockBackend { type State =3D bindings::spinlock_t; type GuardState =3D (); type Context<'a> =3D (); + type BackendInContext =3D (); =20 unsafe fn init( ptr: *mut Self::State, @@ -221,6 +222,45 @@ macro_rules! new_spinlock_irq { /// # Ok::<(), Error>(()) /// ``` /// +/// The next example demonstrates locking a [`SpinLockIrq`] using [`lock_w= ith()`] in a function +/// which can only be called when local processor interrupts are already d= isabled. +/// +/// ``` +/// use kernel::sync::{new_spinlock_irq, SpinLockIrq}; +/// use kernel::interrupt::*; +/// +/// struct Inner { +/// a: u32, +/// } +/// +/// #[pin_data] +/// struct Example { +/// #[pin] +/// inner: SpinLockIrq, +/// } +/// +/// impl Example { +/// fn new() -> impl PinInit { +/// pin_init!(Self { +/// inner <- new_spinlock_irq!(Inner { a: 20 }), +/// }) +/// } +/// } +/// +/// // Accessing an `Example` from a function that can only be called in n= o-interrupt contexts. +/// fn noirq_work(e: &Example, interrupt_disabled: &LocalInterruptDisabled= ) { +/// // Because we know interrupts are disabled from interrupt_disable,= we can skip toggling +/// // interrupt state using lock_with() and the provided token +/// assert_eq!(e.inner.lock_with(interrupt_disabled).a, 20); +/// } +/// +/// # let e =3D KBox::pin_init(Example::new(), GFP_KERNEL)?; +/// # let interrupt_guard =3D local_interrupt_disable(); +/// # noirq_work(&e, &interrupt_guard); +/// # +/// # Ok::<(), Error>(()) +/// ``` +/// /// [`lock()`]: SpinLockIrq::lock /// [`lock_with()`]: SpinLockIrq::lock_with pub type SpinLockIrq =3D super::Lock; @@ -245,6 +285,7 @@ unsafe impl super::Backend for SpinLockIrqBackend { type State =3D bindings::spinlock_t; type GuardState =3D (); type Context<'a> =3D &'a LocalInterruptDisabled; + type BackendInContext =3D SpinLockBackend; =20 unsafe fn init( ptr: *mut Self::State, --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 4B44B30F81D for ; Mon, 13 Oct 2025 15:54:49 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370891; cv=none; b=Lc8bES9vjec3/4NPpYJwyegO9sF6Aklu+ecjiFStwWla41cbBD4A1LskCMRqo+hAKqBP8pr5FrMcE/LKX+YmQQps6kwLyEfpwmdSMvm31xPOecK7jCNVIm/tufilmG86stVphIYr+oiaLtaC9RdZ9xWHhsTxI0dENBDctqKH5go= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370891; c=relaxed/simple; bh=8VqjZ0ZBhXI8OkrxtlCotuTancax8ei0GnWF8z7SXww=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=VQSHY7w/d9ebAErvv+NHa5sn9UDO+iat5i91HwTbrEypB3lfvtrCiYI8FEVpzePj7skBC7Y6ym9GuKpZAjyj/qF5Kh3tVU5ys28aCZBWQHcdOZNsMTxLwIWg97TxymDkQpY+Aj5UQpmE5MUwa1yXQR4JlGEDJtxw9cgcAAjtylM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=ANHOK/sH; arc=none smtp.client-ip=170.10.129.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="ANHOK/sH" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370888; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=0/5qL/qnNe5zk2Pn3wwrfvpRtt2hfl3oZ5LQZHqwjnI=; b=ANHOK/sHFB5tGgYuoD/tqUGequLsd9cenSwdHXJGbBv232xIWM0M4GobHIb9ngS03SrVWb 9KZpcBLZLSO7XV6a1b1V8WaZwqOzLtklySvUKJ8PswVirno0qcUoAUyemHVFRLZBmtV5R5 4uq1XaXPrBxaWy695uRF6dR5SiQ1ToI= Received: from mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-669-oLhRt9OCMTKOcNcT-PY8nA-1; Mon, 13 Oct 2025 11:54:44 -0400 X-MC-Unique: oLhRt9OCMTKOcNcT-PY8nA-1 X-Mimecast-MFC-AGG-ID: oLhRt9OCMTKOcNcT-PY8nA_1760370882 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 1E4D8180057E; Mon, 13 Oct 2025 15:54:42 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 6621730002D0; Mon, 13 Oct 2025 15:54:38 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Subject: [PATCH v13 12/17] rust: sync: lock/global: Rename B to G in trait bounds Date: Mon, 13 Oct 2025 11:48:14 -0400 Message-ID: <20251013155205.2004838-13-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" Due to the introduction of Backend::BackendInContext, if we want to be able support Lock types with a Context we need to be able to handle the fact that the Backend for a returned Guard may not exactly match the Backend for the lock. Before we add this though, rename B to G in all of our trait bounds to make sure things don't become more difficult to understand once we add a Backend bound. There should be no functional changes in this patch. Signed-off-by: Lyude Paul --- rust/kernel/sync/lock/global.rs | 56 ++++++++++++++++----------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/rust/kernel/sync/lock/global.rs b/rust/kernel/sync/lock/global= .rs index 47e200b750c1d..dfdd913d6c1f5 100644 --- a/rust/kernel/sync/lock/global.rs +++ b/rust/kernel/sync/lock/global.rs @@ -33,18 +33,18 @@ pub trait GlobalLockBackend { /// Type used for global locks. /// /// See [`global_lock!`] for examples. -pub struct GlobalLock { - inner: Lock, +pub struct GlobalLock { + inner: Lock, } =20 -impl GlobalLock { +impl GlobalLock { /// Creates a global lock. /// /// # Safety /// /// * Before any other method on this lock is called, [`Self::init`] m= ust be called. - /// * The type `B` must not be used with any other lock. - pub const unsafe fn new(data: B::Item) -> Self { + /// * The type `G` must not be used with any other lock. + pub const unsafe fn new(data: G::Item) -> Self { Self { inner: Lock { state: Opaque::uninit(), @@ -68,23 +68,23 @@ pub unsafe fn init(&'static self) { // `init` before using any other methods. As `init` can only be ca= lled once, all other // uses of this lock must happen after this call. unsafe { - B::Backend::init( + G::Backend::init( self.inner.state.get(), - B::NAME.as_char_ptr(), - B::get_lock_class().as_ptr(), + G::NAME.as_char_ptr(), + G::get_lock_class().as_ptr(), ) } } =20 /// Lock this global lock. - pub fn lock(&'static self) -> GlobalGuard { + pub fn lock(&'static self) -> GlobalGuard { GlobalGuard { inner: self.inner.lock(), } } =20 /// Try to lock this global lock. - pub fn try_lock(&'static self) -> Option> { + pub fn try_lock(&'static self) -> Option> { Some(GlobalGuard { inner: self.inner.try_lock()?, }) @@ -94,19 +94,19 @@ pub fn try_lock(&'static self) -> Option= > { /// A guard for a [`GlobalLock`]. /// /// See [`global_lock!`] for examples. -pub struct GlobalGuard { - inner: Guard<'static, B::Item, B::Backend>, +pub struct GlobalGuard { + inner: Guard<'static, G::Item, G::Backend>, } =20 -impl core::ops::Deref for GlobalGuard { - type Target =3D B::Item; +impl core::ops::Deref for GlobalGuard { + type Target =3D G::Item; =20 fn deref(&self) -> &Self::Target { &self.inner } } =20 -impl core::ops::DerefMut for GlobalGuard { +impl core::ops::DerefMut for GlobalGuard { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } @@ -115,33 +115,33 @@ fn deref_mut(&mut self) -> &mut Self::Target { /// A version of [`LockedBy`] for a [`GlobalLock`]. /// /// See [`global_lock!`] for examples. -pub struct GlobalLockedBy { - _backend: PhantomData, +pub struct GlobalLockedBy { + _backend: PhantomData, value: UnsafeCell, } =20 // SAFETY: The same thread-safety rules as `LockedBy` apply to `GlobalLock= edBy`. -unsafe impl Send for GlobalLockedBy +unsafe impl Send for GlobalLockedBy where T: ?Sized, - B: GlobalLockBackend, - LockedBy: Send, + G: GlobalLockBackend, + LockedBy: Send, { } =20 // SAFETY: The same thread-safety rules as `LockedBy` apply to `GlobalLock= edBy`. -unsafe impl Sync for GlobalLockedBy +unsafe impl Sync for GlobalLockedBy where T: ?Sized, - B: GlobalLockBackend, - LockedBy: Sync, + G: GlobalLockBackend, + LockedBy: Sync, { } =20 -impl GlobalLockedBy { +impl GlobalLockedBy { /// Create a new [`GlobalLockedBy`]. /// - /// The provided value will be protected by the global lock indicated = by `B`. + /// The provided value will be protected by the global lock indicated = by `G`. pub fn new(val: T) -> Self { Self { value: UnsafeCell::new(val), @@ -150,11 +150,11 @@ pub fn new(val: T) -> Self { } } =20 -impl GlobalLockedBy { +impl GlobalLockedBy { /// Access the value immutably. /// /// The caller must prove shared access to the lock. - pub fn as_ref<'a>(&'a self, _guard: &'a GlobalGuard) -> &'a T { + pub fn as_ref<'a>(&'a self, _guard: &'a GlobalGuard) -> &'a T { // SAFETY: The lock is globally unique, so there can only be one g= uard. unsafe { &*self.value.get() } } @@ -162,7 +162,7 @@ pub fn as_ref<'a>(&'a self, _guard: &'a GlobalGuard)= -> &'a T { /// Access the value mutably. /// /// The caller must prove shared exclusive to the lock. - pub fn as_mut<'a>(&'a self, _guard: &'a mut GlobalGuard) -> &'a mut= T { + pub fn as_mut<'a>(&'a self, _guard: &'a mut GlobalGuard) -> &'a mut= T { // SAFETY: The lock is globally unique, so there can only be one g= uard. unsafe { &mut *self.value.get() } } --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CA31030F941 for ; Mon, 13 Oct 2025 15:54:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370896; cv=none; b=f0fHT+ISo9CNtu+oJ5gWj2pKp0ILh3NIcuUbpTnqQCyG9j77qZeJO1qgglNmdqk3UnNEGLapm/sdGTJrVxmatus7X7P7BGHfbvB+gvivJG5enfTkCnTYxanaEjXw9XWBcOwaX9Zd2AN2ERYA29eyyrBzWY0z5R2OCoIkNfUHzFA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370896; c=relaxed/simple; bh=K3DkSMvgF1FHfAkUVUQNbgggdOS4fhfvKRT5d875ah8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=X3rk6QhPyjFEW+8Oj/DPPMgqfGqHRN3YErEi88+S7tv0iPIuKIag9X2ZaiEO9gGoVV7DBvWDI6H3rW+de3xaMYRZVRx4YB4Uzsmn2kHRroHtLospcAqO0TPW6gsaVQwY/FPcWjTMA0rtZz7PPJo/EOczNPIPncgxEK884ExCheY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=ixMC58P/; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="ixMC58P/" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370894; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=UrTOrtS1qOxBO7CX/FTveHXi3lG76HMcpOsvHpUE5Ss=; b=ixMC58P/A5zNPtlMBY8KhVrNqHWBa4e35Wt8E0hEMzinQJoaeE6TTIwA0Lje9277V1GTTz X8oKIu57b00EX9rU8w/uFA4hD9UjLnJNVvGvCJk1bHOCzzApGwjtyZmeF7OyFqr5ibLLmV yn4rICtfe/MV2hLK3W7u4FRRjexoHl8= Received: from mx-prod-mc-01.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-342-64eRGEQYOMSJrqFe1sFH-A-1; Mon, 13 Oct 2025 11:54:50 -0400 X-MC-Unique: 64eRGEQYOMSJrqFe1sFH-A-1 X-Mimecast-MFC-AGG-ID: 64eRGEQYOMSJrqFe1sFH-A_1760370885 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 76B631956089; Mon, 13 Oct 2025 15:54:45 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 645AD30002D0; Mon, 13 Oct 2025 15:54:42 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Subject: [PATCH v13 13/17] rust: sync: Add a lifetime parameter to lock::global::GlobalGuard Date: Mon, 13 Oct 2025 11:48:15 -0400 Message-ID: <20251013155205.2004838-14-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" While a GlobalLock is always going to be static, in the case of locks with explicit backend contexts the GlobalGuard will not be 'static and will instead share the lifetime of the context. So, add a lifetime parameter to GlobalGuard to allow for this so we can implement GlobalGuard support for SpinlockIrq. Signed-off-by: Lyude Paul --- rust/kernel/sync/lock/global.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/rust/kernel/sync/lock/global.rs b/rust/kernel/sync/lock/global= .rs index dfdd913d6c1f5..f846ecf9168e7 100644 --- a/rust/kernel/sync/lock/global.rs +++ b/rust/kernel/sync/lock/global.rs @@ -77,14 +77,14 @@ pub unsafe fn init(&'static self) { } =20 /// Lock this global lock. - pub fn lock(&'static self) -> GlobalGuard { + pub fn lock(&'static self) -> GlobalGuard<'static, G> { GlobalGuard { inner: self.inner.lock(), } } =20 /// Try to lock this global lock. - pub fn try_lock(&'static self) -> Option> { + pub fn try_lock(&'static self) -> Option> { Some(GlobalGuard { inner: self.inner.try_lock()?, }) @@ -94,11 +94,11 @@ pub fn try_lock(&'static self) -> Option= > { /// A guard for a [`GlobalLock`]. /// /// See [`global_lock!`] for examples. -pub struct GlobalGuard { - inner: Guard<'static, G::Item, G::Backend>, +pub struct GlobalGuard<'a, G: GlobalLockBackend> { + inner: Guard<'a, G::Item, G::Backend>, } =20 -impl core::ops::Deref for GlobalGuard { +impl<'a, G: GlobalLockBackend> core::ops::Deref for GlobalGuard<'a, G> { type Target =3D G::Item; =20 fn deref(&self) -> &Self::Target { @@ -106,7 +106,7 @@ fn deref(&self) -> &Self::Target { } } =20 -impl core::ops::DerefMut for GlobalGuard { +impl<'a, G: GlobalLockBackend> core::ops::DerefMut for GlobalGuard<'a, G> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } @@ -154,7 +154,7 @@ impl GlobalLockedBy { /// Access the value immutably. /// /// The caller must prove shared access to the lock. - pub fn as_ref<'a>(&'a self, _guard: &'a GlobalGuard) -> &'a T { + pub fn as_ref<'a>(&'a self, _guard: &'a GlobalGuard<'_, G>) -> &'a T { // SAFETY: The lock is globally unique, so there can only be one g= uard. unsafe { &*self.value.get() } } @@ -162,7 +162,7 @@ pub fn as_ref<'a>(&'a self, _guard: &'a GlobalGuard)= -> &'a T { /// Access the value mutably. /// /// The caller must prove shared exclusive to the lock. - pub fn as_mut<'a>(&'a self, _guard: &'a mut GlobalGuard) -> &'a mut= T { + pub fn as_mut<'a>(&'a self, _guard: &'a mut GlobalGuard<'_, G>) -> &'a= mut T { // SAFETY: The lock is globally unique, so there can only be one g= uard. unsafe { &mut *self.value.get() } } @@ -232,7 +232,7 @@ pub fn get_mut(&mut self) -> &mut T { /// /// Increment the counter in this instance. /// /// /// /// The caller must hold the `MY_MUTEX` mutex. -/// fn increment(&self, guard: &mut GlobalGuard) -> u32 { +/// fn increment(&self, guard: &mut GlobalGuard<'_, MY_MUTEX>) -> u32 { /// let my_counter =3D self.my_counter.as_mut(guard); /// *my_counter +=3D 1; /// *my_counter --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 442EA30FC09 for ; Mon, 13 Oct 2025 15:54:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370898; cv=none; b=hd2wz9uHVP3023qZY/NLJgBtwoln9bf1rAYhAQAuVXXTsVcPouKZnnocLOO20gjgzeW+fYiwndXtgcBqXJRDrH6IZ81xI4Chr8gYNURljCTYXfa/iQVD3b28NMWiWx05NuEe1kihZ45OypS8he4C1/YRY2e8QhNVeiDsS8X+nHA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370898; c=relaxed/simple; bh=TW7CS6Qsw+aLPc6lMbQGdFy69oe9GTP0J1/W+/vIvvk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Mar3Zs14d8DdoFiEeUjFmpXdDxHrxN5PbOnKWC/1eQi6G9Ud4891Nf3BBiSPRvtLODmIbwal5LGuiLxZ5u2THKhFFclVMbWqFKh14Da4AVo8Xb3OCcbx2vhhnUpZ/HtjcatlzDWrk8hHaCcWQKM23t0tGVOsa3GOUv4w31V3xOk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=IagsZhQg; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="IagsZhQg" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370896; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=yYVXlVAo1VL3f8OamE57FZQqo5mYq7IRNQ67P7LbgHk=; b=IagsZhQgGFsBxZugGOV5eHZoZ7lGR/vx/PuEWhhniXrU7kvzBwk5LCy+NjXZRZw4w5S2ZF 0quOcYeGH4FJeV8V4M4Ptw+6PFBUALZLtq7c/2g/499b1ms83kZjwdipYJfyHKCo9grJMd CPlWa/4ORf+5srxFWhzPD3AnHgIeXhQ= Received: from mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-606-efPyUXQaMpiV_Q4bukenUw-1; Mon, 13 Oct 2025 11:54:51 -0400 X-MC-Unique: efPyUXQaMpiV_Q4bukenUw-1 X-Mimecast-MFC-AGG-ID: efPyUXQaMpiV_Q4bukenUw_1760370889 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-06.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 1E5AD18004D4; Mon, 13 Oct 2025 15:54:49 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 2E48E3000383; Mon, 13 Oct 2025 15:54:46 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Mitchell Levy , Shankari Anand Subject: [PATCH v13 14/17] rust: sync: Expose lock::Backend Date: Mon, 13 Oct 2025 11:48:16 -0400 Message-ID: <20251013155205.2004838-15-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" Due to the addition of sync::lock::Backend::Context, lock guards can be returned with a different Backend than their respective lock. Since we'll be adding a trait bound for Backend to GlobalGuard in order to support this, users will need to be able to directly refer to Backend so that they can use it in trait bounds. So, let's make this easier for users and expose Backend in sync. Signed-off-by: Lyude Paul --- rust/kernel/sync.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index f293bbe13e855..795cbf3fc10f7 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -29,6 +29,7 @@ pub use lock::spinlock::{ new_spinlock, new_spinlock_irq, SpinLock, SpinLockGuard, SpinLockIrq, = SpinLockIrqGuard, }; +pub use lock::Backend; pub use locked_by::LockedBy; pub use refcount::Refcount; =20 --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2132930FC3E for ; Mon, 13 Oct 2025 15:55:00 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370902; cv=none; b=FUvObflq08mwbkCqKhk1L6c1d1Zu55SKe+KRXPysJOE7RejB8eFuwhpifdnAM4Hdshtv2MJ5CqiWvwzTHj+GgBDPLZY7bQ0c21PyORcowheMyi1jFzmfYmUmC/1OOEgwzHuOQgb78upAogr+gnEK/xFTqE1tEgtdRqZ/mc+MsY8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370902; c=relaxed/simple; bh=x8DU/TNpRsAa5FP1AQMU3YH3HVa07+SbVCrQd2L6b4U=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Lj6glowArSyL3nU75Qh5V+WN5q3jC4UMuu2kNMYJVz/+s+0eAiXvaDy07XZqRwlHNI+bA+sJ4V52cIn3Q9qkEyIdg6kXYvmc+FlIwF2amGLrFLF6hpYXIA0Bo8EWCgA+ey53bWJL25gtZJW4/7KDaJjwltkEDkjkt6b7I74nd/8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=CEGTvsR1; arc=none smtp.client-ip=170.10.129.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="CEGTvsR1" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370900; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=W5PsqCnEp2V/5XTwj3ipQ8NPd5lW79byKPZwKAmCNIw=; b=CEGTvsR1argoF06gyF2Lp1XA29C0OrrNn3PpEENJQMD8uf8lhdFw3Gz9RZo1CmOjgQEYFf fZ834tUinjCc22bzXGL/PfSQDOa70HyHo5hn/t32pHygDGUGsco4x4H10X5W91nOmn2Jsb OxQvPheiwgEFisa0hEq4HRE1kCGZAfY= Received: from mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-441-sgjmFNPHPxGgFRbOKLz9-g-1; Mon, 13 Oct 2025 11:54:55 -0400 X-MC-Unique: sgjmFNPHPxGgFRbOKLz9-g-1 X-Mimecast-MFC-AGG-ID: sgjmFNPHPxGgFRbOKLz9-g_1760370893 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 4762E180048E; Mon, 13 Oct 2025 15:54:53 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 878C730002D0; Mon, 13 Oct 2025 15:54:49 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Subject: [PATCH v13 15/17] rust: sync: lock/global: Add Backend parameter to GlobalGuard Date: Mon, 13 Oct 2025 11:48:17 -0400 Message-ID: <20251013155205.2004838-16-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" Due to the introduction of sync::lock::Backend::Context, it's now possible for normal locks to return a Guard with a different Backend than their respective lock (e.g. Backend::BackendInContext). We want to be able to support global locks with contexts as well, so add a trait bound to explicitly specify which Backend is in use for a GlobalGuard. Signed-off-by: Lyude Paul --- rust/kernel/sync/lock/global.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/rust/kernel/sync/lock/global.rs b/rust/kernel/sync/lock/global= .rs index f846ecf9168e7..f9a9c4bdc46b0 100644 --- a/rust/kernel/sync/lock/global.rs +++ b/rust/kernel/sync/lock/global.rs @@ -77,14 +77,14 @@ pub unsafe fn init(&'static self) { } =20 /// Lock this global lock. - pub fn lock(&'static self) -> GlobalGuard<'static, G> { + pub fn lock(&'static self) -> GlobalGuard<'static, G, G::Backend> { GlobalGuard { inner: self.inner.lock(), } } =20 /// Try to lock this global lock. - pub fn try_lock(&'static self) -> Option> { + pub fn try_lock(&'static self) -> Option> { Some(GlobalGuard { inner: self.inner.try_lock()?, }) @@ -94,11 +94,11 @@ pub fn try_lock(&'static self) -> Option> { /// A guard for a [`GlobalLock`]. /// /// See [`global_lock!`] for examples. -pub struct GlobalGuard<'a, G: GlobalLockBackend> { - inner: Guard<'a, G::Item, G::Backend>, +pub struct GlobalGuard<'a, G: GlobalLockBackend, B: Backend> { + inner: Guard<'a, G::Item, B>, } =20 -impl<'a, G: GlobalLockBackend> core::ops::Deref for GlobalGuard<'a, G> { +impl<'a, G: GlobalLockBackend, B: Backend> core::ops::Deref for GlobalGuar= d<'a, G, B> { type Target =3D G::Item; =20 fn deref(&self) -> &Self::Target { @@ -106,7 +106,7 @@ fn deref(&self) -> &Self::Target { } } =20 -impl<'a, G: GlobalLockBackend> core::ops::DerefMut for GlobalGuard<'a, G> { +impl<'a, G: GlobalLockBackend, B: Backend> core::ops::DerefMut for GlobalG= uard<'a, G, B> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } @@ -154,7 +154,7 @@ impl GlobalLockedBy { /// Access the value immutably. /// /// The caller must prove shared access to the lock. - pub fn as_ref<'a>(&'a self, _guard: &'a GlobalGuard<'_, G>) -> &'a T { + pub fn as_ref<'a, B: Backend>(&'a self, _guard: &'a GlobalGuard<'_, G,= B>) -> &'a T { // SAFETY: The lock is globally unique, so there can only be one g= uard. unsafe { &*self.value.get() } } @@ -162,7 +162,7 @@ pub fn as_ref<'a>(&'a self, _guard: &'a GlobalGuard<'_,= G>) -> &'a T { /// Access the value mutably. /// /// The caller must prove shared exclusive to the lock. - pub fn as_mut<'a>(&'a self, _guard: &'a mut GlobalGuard<'_, G>) -> &'a= mut T { + pub fn as_mut<'a, B: Backend>(&'a self, _guard: &'a mut GlobalGuard<'_= , G, B>) -> &'a mut T { // SAFETY: The lock is globally unique, so there can only be one g= uard. unsafe { &mut *self.value.get() } } @@ -216,7 +216,7 @@ pub fn get_mut(&mut self) -> &mut T { /// ``` /// # mod ex { /// # use kernel::prelude::*; -/// use kernel::sync::{GlobalGuard, GlobalLockedBy}; +/// use kernel::sync::{Backend, GlobalGuard, GlobalLockedBy}; /// /// kernel::sync::global_lock! { /// // SAFETY: Initialized in module initializer before first use. @@ -232,7 +232,7 @@ pub fn get_mut(&mut self) -> &mut T { /// /// Increment the counter in this instance. /// /// /// /// The caller must hold the `MY_MUTEX` mutex. -/// fn increment(&self, guard: &mut GlobalGuard<'_, MY_MUTEX>) -> u32 { +/// fn increment(&self, guard: &mut GlobalGuard<'_, MY_MUT= EX, B>) -> u32 { /// let my_counter =3D self.my_counter.as_mut(guard); /// *my_counter +=3D 1; /// *my_counter --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 92B7430FF20 for ; Mon, 13 Oct 2025 15:55:03 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370905; cv=none; b=RMr6LyIHpipKepSTz8cS2VHljlYnEmio4YWcGlFBeWy48aT9bxgM136y2AjY/BpCJ/iGCpWAGNkwYZeUt09NjZ4HS1sI1J/F/ykYgWxrfyDPbtON2M3/D+Xsv4mAeZhTh7H4a6pPhq9ozPfs2mK4JdQAwV4rrGYFWcqjQWUlrqc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370905; c=relaxed/simple; bh=ph/JrEd4QQTEskma9qDgko7pFckjWIPHEyhpEe/ntWY=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=VStaQdG5ie5a+CWQfU2fu8vnhvg+74jY6GEJLco6eyeD9ncAkKItyLI+mjV/0mnqoAMz6o3LsnyCHXLHfkJ4+rd5LSwPeiiko08tQe5D2DLL2dVny4SJOzyFMA453+pRpf3J868C7tKkwuh8Nl1UMHHiBki73BISUePwLvkqhCQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=GrPe3sEb; arc=none smtp.client-ip=170.10.133.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="GrPe3sEb" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370902; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=CGWiDHXT406CGjkkYVuYWQ9EmOtFGOr3azcQz/D+icE=; b=GrPe3sEbqsx76FeXmzwGVNEvsOEj1a2Bs+EwF/yfHceWo/vKUDI6klJ4kJufXup/s+0r9W KfQSVk5Bvwq2T64m0lSLcPgnbaV0C+ppAhqR6H4no+31kwE0WC/tAJ5MtlTl4g23Pq4II/ Cz3hINumueGuQJ5UtUvhW5z6Ay2H4Q0= Received: from mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-150-pZR5Qch2P3Ox7EqLzySHbg-1; Mon, 13 Oct 2025 11:54:59 -0400 X-MC-Unique: pZR5Qch2P3Ox7EqLzySHbg-1 X-Mimecast-MFC-AGG-ID: pZR5Qch2P3Ox7EqLzySHbg_1760370897 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 03EA51955F2F; Mon, 13 Oct 2025 15:54:57 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id A716C30002D0; Mon, 13 Oct 2025 15:54:53 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Miguel Ojeda , Alex Gaynor , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich Subject: [PATCH v13 16/17] rust: sync: lock/global: Add BackendInContext support to GlobalLock Date: Mon, 13 Oct 2025 11:48:18 -0400 Message-ID: <20251013155205.2004838-17-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" Now that we have the ability to provide an explicit lifetime for a GlobalGuard and an explicit Backend for a GlobalGuard, we can finally implement lock_with() and try_lock_with(). Signed-off-by: Lyude Paul --- rust/kernel/sync/lock/global.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/rust/kernel/sync/lock/global.rs b/rust/kernel/sync/lock/global= .rs index f9a9c4bdc46b0..1f28bf5fc8851 100644 --- a/rust/kernel/sync/lock/global.rs +++ b/rust/kernel/sync/lock/global.rs @@ -89,6 +89,34 @@ pub fn try_lock(&'static self) -> Option> { inner: self.inner.try_lock()?, }) } + + /// Lock this global lock with the provided `context`. + pub fn lock_with<'a, B>( + &'static self, + context: ::Context<'a>, + ) -> GlobalGuard<'a, G, B> + where + G::Backend: Backend, + B: Backend, + { + GlobalGuard { + inner: self.inner.lock_with(context), + } + } + + /// Try to lock this global lock with the provided `context`. + pub fn try_lock_with<'a, B>( + &'static self, + context: ::Context<'a>, + ) -> Option> + where + G::Backend: Backend, + B: Backend, + { + Some(GlobalGuard { + inner: self.inner.try_lock_with(context)?, + }) + } } =20 /// A guard for a [`GlobalLock`]. --=20 2.51.0 From nobody Fri Dec 19 15:38:53 2025 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2FAD230FF20 for ; Mon, 13 Oct 2025 15:55:12 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370914; cv=none; b=YgM8nt7CL4iR/N5rRtq25D9SHl4yfx2IQjeCgVezqPYgs8+ADi6zbtqAOaxM2kx0F/OJYe3dbHSAJi5/Ki9ISt81w64hFXDmzoVXKH9D0iihkohxTp57g9QhewoK4vwwaZf8OpnWQpsamtbWorcN1oUDQ8nDGlG5bhk8NnPYgsU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760370914; c=relaxed/simple; bh=SR16SDEApWSuMuV78M5goXrZEkHtPoydA3cpBeRk3pk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=O2bE7f6wE0PF4kJ5NjLQd6PGYfIYdBz/oYcwosRiZNktyK6wzQSA2ypGkNJ4hB6uePodV5/u5wUwEL02t0tkQu33emX/lo2vKfjpCZrRYwa9wAS3yx4k+UP28NDFX3HvolCvZz1dFTLsTuUuE50rO2rX6RNW4bkAh9EhLHolTVE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=UGZq/Zcl; arc=none smtp.client-ip=170.10.129.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="UGZq/Zcl" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1760370912; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=GcmkubQ76k3OEo3+5mJ3yaxqP/LkJrk4TvFyQj+rU4A=; b=UGZq/Zcl/3tc2EjdThjzvSCU5wvvkeqZKn7QRkW2C1svlsKwoRS/1453gO7RyC6fzMtxcA kNKjJ1Pk1McMjPh098HnZnm5lsxXtBpqdiZfcleW74wMHsSE2g07E9SlnWlwc7crBtt29W bfwaHVKMli2i0xsz3EV0WDqkmp5vWy4= Received: from mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-241-U3XbwU-2O6uDqALszE9nSA-1; Mon, 13 Oct 2025 11:55:06 -0400 X-MC-Unique: U3XbwU-2O6uDqALszE9nSA-1 X-Mimecast-MFC-AGG-ID: U3XbwU-2O6uDqALszE9nSA_1760370901 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 440AF1954105; Mon, 13 Oct 2025 15:55:00 +0000 (UTC) Received: from chopper.lan (unknown [10.22.81.1]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 716383000386; Mon, 13 Oct 2025 15:54:57 +0000 (UTC) From: Lyude Paul To: rust-for-linux@vger.kernel.org, Thomas Gleixner , Boqun Feng , linux-kernel@vger.kernel.org, Daniel Almeida Cc: Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Sebastian Andrzej Siewior , Clark Williams , Steven Rostedt , linux-rt-devel@lists.linux.dev (open list:Real-time Linux (PREEMPT_RT):Keyword:PREEMPT_RT) Subject: [PATCH v13 17/17] locking: Switch to _irq_{disable,enable}() variants in cleanup guards Date: Mon, 13 Oct 2025 11:48:19 -0400 Message-ID: <20251013155205.2004838-18-lyude@redhat.com> In-Reply-To: <20251013155205.2004838-1-lyude@redhat.com> References: <20251013155205.2004838-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" From: Boqun Feng The semantics of various irq disabling guards match what *_irq_{disable,enable}() provide, i.e. the interrupt disabling is properly nested, therefore it's OK to switch to use *_irq_{disable,enable}() primitives. Signed-off-by: Boqun Feng --- V10: * Add PREEMPT_RT build fix from Guangbo Cui include/linux/spinlock.h | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/include/linux/spinlock.h b/include/linux/spinlock.h index 80dfac144e10a..aff1b8c5f7cd7 100644 --- a/include/linux/spinlock.h +++ b/include/linux/spinlock.h @@ -567,10 +567,10 @@ DEFINE_LOCK_GUARD_1(raw_spinlock_nested, raw_spinlock= _t, raw_spin_unlock(_T->lock)) =20 DEFINE_LOCK_GUARD_1(raw_spinlock_irq, raw_spinlock_t, - raw_spin_lock_irq(_T->lock), - raw_spin_unlock_irq(_T->lock)) + raw_spin_lock_irq_disable(_T->lock), + raw_spin_unlock_irq_enable(_T->lock)) =20 -DEFINE_LOCK_GUARD_1_COND(raw_spinlock_irq, _try, raw_spin_trylock_irq(_T->= lock)) +DEFINE_LOCK_GUARD_1_COND(raw_spinlock_irq, _try, raw_spin_trylock_irq_disa= ble(_T->lock)) =20 DEFINE_LOCK_GUARD_1(raw_spinlock_bh, raw_spinlock_t, raw_spin_lock_bh(_T->lock), @@ -579,12 +579,11 @@ DEFINE_LOCK_GUARD_1(raw_spinlock_bh, raw_spinlock_t, DEFINE_LOCK_GUARD_1_COND(raw_spinlock_bh, _try, raw_spin_trylock_bh(_T->lo= ck)) =20 DEFINE_LOCK_GUARD_1(raw_spinlock_irqsave, raw_spinlock_t, - raw_spin_lock_irqsave(_T->lock, _T->flags), - raw_spin_unlock_irqrestore(_T->lock, _T->flags), - unsigned long flags) + raw_spin_lock_irq_disable(_T->lock), + raw_spin_unlock_irq_enable(_T->lock)) =20 DEFINE_LOCK_GUARD_1_COND(raw_spinlock_irqsave, _try, - raw_spin_trylock_irqsave(_T->lock, _T->flags)) + raw_spin_trylock_irq_disable(_T->lock)) =20 DEFINE_LOCK_GUARD_1(spinlock, spinlock_t, spin_lock(_T->lock), @@ -593,11 +592,11 @@ DEFINE_LOCK_GUARD_1(spinlock, spinlock_t, DEFINE_LOCK_GUARD_1_COND(spinlock, _try, spin_trylock(_T->lock)) =20 DEFINE_LOCK_GUARD_1(spinlock_irq, spinlock_t, - spin_lock_irq(_T->lock), - spin_unlock_irq(_T->lock)) + spin_lock_irq_disable(_T->lock), + spin_unlock_irq_enable(_T->lock)) =20 DEFINE_LOCK_GUARD_1_COND(spinlock_irq, _try, - spin_trylock_irq(_T->lock)) + spin_trylock_irq_disable(_T->lock)) =20 DEFINE_LOCK_GUARD_1(spinlock_bh, spinlock_t, spin_lock_bh(_T->lock), @@ -607,12 +606,11 @@ DEFINE_LOCK_GUARD_1_COND(spinlock_bh, _try, spin_trylock_bh(_T->lock)) =20 DEFINE_LOCK_GUARD_1(spinlock_irqsave, spinlock_t, - spin_lock_irqsave(_T->lock, _T->flags), - spin_unlock_irqrestore(_T->lock, _T->flags), - unsigned long flags) + spin_lock_irq_disable(_T->lock), + spin_unlock_irq_enable(_T->lock)) =20 DEFINE_LOCK_GUARD_1_COND(spinlock_irqsave, _try, - spin_trylock_irqsave(_T->lock, _T->flags)) + spin_trylock_irq_disable(_T->lock)) =20 DEFINE_LOCK_GUARD_1(read_lock, rwlock_t, read_lock(_T->lock), --=20 2.51.0