From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from mail-qv1-f54.google.com (mail-qv1-f54.google.com [209.85.219.54]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5E7292BE65E for ; Thu, 10 Jul 2025 06:01:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.54 ARC-Seal:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752127270; cv=none; b=I3x0dFGaRE0t7Y17QXqYjiPtpRoMleskT7vjHAgRz/coKgLqD/yOdrDkusz30b4j3e7RfFtfAKKgSDys0QuBTFlIkR6HkbYKqPuBjwejOLSzEVzUu90W2qtsY4pErnPRDvU5ZSJVqJlD0ma/9dbWrp6g2GGdxZE+hwHuKm6Ll3Y= ARC-Message-Signature:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1752127270; c=relaxed/simple; bh=HAq/kPb9ujAzsSU+sqSF/chqGGoNuLKQjburQo4hTb8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=aB63lrqlL1xOCn6UiyTCSQSkp5frahn8uFxSvBcH2Y+n5sKlz1bh5EGuUTS786jhmieOEx217pvgTbVjulZFliTKDn1MLkNxCfttNJ/iyg2wK72K/ZWWGphGtndAzZdWQMR41KIBg5PAvSh4C8MOcJfncIORs8Vj0sePOuCdSpA= ARC-Authentication-Results:i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=ZtLdL949; arc=none smtp.client-ip=209.85.219.54 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="ZtLdL949" Received: by mail-qv1-f54.google.com with SMTP id 6a1803df08f44-6fd0a3cd326so7598696d6.1 for ; Wed, 09 Jul 2025 23:01:06 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1752127265; x=1752732065; darn=lists.linux.dev; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:feedback-id:from:to:cc:subject :date:message-id:reply-to; bh=T8APr2O5lJC3B4ujP5dNsioemZHw0iFX0dcBhhyWrqo=; b=ZtLdL949X2CgZxPl5rYJ8tJVgRNrJZG/Iwp7nCG8F7kypRFVLf54qieJb7AUXiCMEQ E3vxDrrFLu7OvE5ZNTzzrAWCq2cUfW6fWhlykD8ItK3cBrqBWwRfMdpu8xICwr/XMSxI UXGzjLs14PHKFKbGsBW1acsovTcDw2EIk5xcQgozGSzLE5b/KIia3VkN2XdT6sCy6gZc YCidlec2n3vACUrvkqI+Re3e34FbXWSIouKignBwp/+CVVNmI1dRab6My50YhalMVMu+ rmWHLbzhb5Jac/oopRUA839CUyBEfJFDutbAAkb7KxgHga6KqZbjKzPy0cOX1RBqb0GV kdJA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1752127265; x=1752732065; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:feedback-id:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=T8APr2O5lJC3B4ujP5dNsioemZHw0iFX0dcBhhyWrqo=; b=RAN2wp5ROARv3Bma/B98rVt6SN22ppqpKCpoOe/9Y3r+nRpQYryVKSOpALCoDTKu7L ZVtuJsKuZVmJcNUPoJNIIa0LwVanhypOz839qJTU57//FoAWXwah9sL+CUMlWlgm5R67 aiJbL5cur6AgkQez107dwyMJ6X3UJz4hasc4kuCLv1qXEQbdqjUBvCZ1D4TnRKF0U6li Ot+onB2hzPqUwr+3UuQYIVokKBn1BGn/+CaLOK2hLdnlls7O2Xw/euo6QHTtX17NzV7t yp6H452OInsDgwlobaCS+Q9h6+dtNnpvwBwckkF2ovEpByVCKa0pA39CbKc5JzUsnPLd 7Auw== X-Forwarded-Encrypted: i=1; AJvYcCV6YjiEBy9Varr/gH6n3XrHAURNZJ0PCn0tNAQF7edtz+ehMtdjuXFp3tTA+ovq6jP/alI6@lists.linux.dev X-Gm-Message-State: AOJu0YwdoISio1WQoGxkSfyxSYLmf5yucRHgKOpY8lPm5olsk+V3yjD7 QGA0D4YxhFZwnax580qC6B4jMqdD2fTJR3di28uuwNZGCru+TFJwe1EU X-Gm-Gg: ASbGncuXRnyL+/g5xho/Dew+PEKga4n1IE624qEVfLaItmWZeuysXnl4tl0fVzVZrmc tC3poL/Z0VYqn/u1bLylgnz1grVYe4s/cp4ap5TYoHPbrEogRIUP3GZgtNJXc0YYn++jv7xhQf4 Ck3XOqviz9L4NYAK65h4fzRkUfsR8AMmGXIQDqJa9s+sot9OX5xENedh8eXcnRqvukdFmy7eP8e 6BeoFIiw4dEI5HzmGvzjaYY16bZos7TCk6UEWN8pA4626C7V8kFb3hrTP6wVAe2B7aqaReueL1b NIEIDcngOnxkty8n8yNc5LIaOG6WCkm/PiEXrgdWYXTXwHSOHSiChyC2zjUKbuVyjjBFpI3ktc8 v72WKQMVESinRKUVCfftRrNM8bA00+P4ou7ZvicOyt0Hs5HWz4SaLwU1gP5h1jbk= X-Google-Smtp-Source: AGHT+IE8tPZMqE69NFvrAIW1je5hQqrEOgjBcNp5sZnw9s555Jd87fOsPrYBBFfrv14daEqRamAneQ== X-Received: by 2002:a05:6214:1c48:b0:6fb:51c:395 with SMTP id 6a1803df08f44-70498224156mr17953176d6.41.1752127265034; Wed, 09 Jul 2025 23:01:05 -0700 (PDT) Received: from fauth-a2-smtp.messagingengine.com (fauth-a2-smtp.messagingengine.com. [103.168.172.201]) by smtp.gmail.com with ESMTPSA id af79cd13be357-7dcdbb1dc41sm62661885a.4.2025.07.09.23.01.04 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 09 Jul 2025 23:01:04 -0700 (PDT) Received: from phl-compute-08.internal (phl-compute-08.phl.internal [10.202.2.48]) by mailfauth.phl.internal (Postfix) with ESMTP id 066ABF4006C; Thu, 10 Jul 2025 02:01:04 -0400 (EDT) Received: from phl-mailfrontend-01 ([10.202.2.162]) by phl-compute-08.internal (MEProxy); Thu, 10 Jul 2025 02:01:04 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtdefgdefleeijecutefuodetggdotefrod ftvfcurfhrohhfihhlvgemucfhrghsthforghilhdpuffrtefokffrpgfnqfghnecuuegr ihhlohhuthemuceftddtnecusecvtfgvtghiphhivghnthhsucdlqddutddtmdenucfjug hrpefhvfevufffkffojghfggfgsedtkeertdertddtnecuhfhrohhmpeeuohhquhhnucfh vghnghcuoegsohhquhhnrdhfvghnghesghhmrghilhdrtghomheqnecuggftrfgrthhtvg hrnhepgeeljeeitdehvdehgefgjeevfeejjeekgfevffeiueejhfeuiefggeeuheeggefg necuvehluhhsthgvrhfuihiivgeptdenucfrrghrrghmpehmrghilhhfrhhomhepsghoqh hunhdomhgvshhmthhprghuthhhphgvrhhsohhnrghlihhthidqieelvdeghedtieegqddu jeejkeehheehvddqsghoqhhunhdrfhgvnhhgpeepghhmrghilhdrtghomhesfhhigihmvg drnhgrmhgvpdhnsggprhgtphhtthhopedvjedpmhhouggvpehsmhhtphhouhhtpdhrtghp thhtoheplhhinhhugidqkhgvrhhnvghlsehvghgvrhdrkhgvrhhnvghlrdhorhhgpdhrtg hpthhtoheprhhushhtqdhfohhrqdhlihhnuhigsehvghgvrhdrkhgvrhhnvghlrdhorhhg pdhrtghpthhtoheplhhkmhhmsehlihhsthhsrdhlihhnuhigrdguvghvpdhrtghpthhtoh eplhhinhhugidqrghrtghhsehvghgvrhdrkhgvrhhnvghlrdhorhhgpdhrtghpthhtohep ohhjvggurgeskhgvrhhnvghlrdhorhhgpdhrtghpthhtoheprghlvgigrdhgrgihnhhorh esghhmrghilhdrtghomhdprhgtphhtthhopegsohhquhhnrdhfvghnghesghhmrghilhdr tghomhdprhgtphhtthhopehgrghrhiesghgrrhihghhuohdrnhgvthdprhgtphhtthhope gsjhhorhhnfegpghhhsehprhhothhonhhmrghilhdrtghomh X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Thu, 10 Jul 2025 02:01:03 -0400 (EDT) From: Boqun Feng To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, lkmm@lists.linux.dev, linux-arch@vger.kernel.org Cc: "Miguel Ojeda" , "Alex Gaynor" , "Boqun Feng" , "Gary Guo" , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , "Benno Lossin" , "Andreas Hindborg" , "Alice Ryhl" , "Trevor Gross" , "Danilo Krummrich" , "Will Deacon" , "Peter Zijlstra" , "Mark Rutland" , "Wedson Almeida Filho" , "Viresh Kumar" , "Lyude Paul" , "Ingo Molnar" , "Mitchell Levy" , "Paul E. McKenney" , "Greg Kroah-Hartman" , "Linus Torvalds" , "Thomas Gleixner" , Alan Stern Subject: [PATCH v6 5/9] rust: sync: atomic: Add atomic {cmp,}xchg operations Date: Wed, 9 Jul 2025 23:00:48 -0700 Message-Id: <20250710060052.11955-6-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250710060052.11955-1-boqun.feng@gmail.com> References: <20250710060052.11955-1-boqun.feng@gmail.com> Precedence: bulk X-Mailing-List: lkmm@lists.linux.dev List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: 8bit xchg() and cmpxchg() are basic operations on atomic. Provide these based on C APIs. Note that cmpxchg() use the similar function signature as compare_exchange() in Rust std: returning a `Result`, `Ok(old)` means the operation succeeds and `Err(old)` means the operation fails. Reviewed-by: Alice Ryhl Signed-off-by: Boqun Feng --- rust/kernel/sync/atomic/generic.rs | 170 +++++++++++++++++++++++++++++ 1 file changed, 170 insertions(+) diff --git a/rust/kernel/sync/atomic/generic.rs b/rust/kernel/sync/atomic/generic.rs index e044fe21b128..1beb802843ee 100644 --- a/rust/kernel/sync/atomic/generic.rs +++ b/rust/kernel/sync/atomic/generic.rs @@ -287,3 +287,173 @@ pub fn store(&self, v: T, _: Ordering) { }; } } + +impl Atomic +where + T::Repr: AtomicHasXchgOps, +{ + /// Atomic exchange. + /// + /// # Examples + /// + /// ```rust + /// use kernel::sync::atomic::{Atomic, Acquire, Relaxed}; + /// + /// let x = Atomic::new(42); + /// + /// assert_eq!(42, x.xchg(52, Acquire)); + /// assert_eq!(52, x.load(Relaxed)); + /// ``` + #[doc(alias("atomic_xchg", "atomic64_xchg", "swap"))] + #[inline(always)] + pub fn xchg(&self, v: T, _: Ordering) -> T { + let v = into_repr(v); + // CAST: Per the safety requirement of `AllowAtomic`, a valid pointer of `T` is also a + // valid pointer of `T::Repr`. + let a = self.as_ptr().cast::(); + + // SAFETY: + // - For calling the atomic_xchg*() function: + // - `a` is a valid pointer for the function per the CAST justification above. + // - Per the type guarantees, the following atomic operation won't cause data races. + // - For extra safety requirement of usage on pointers returned by `self.as_ptr()`: + // - Atomic operations are used here. + // - For the bit validity of `Atomic`: + // - `v` is a valid bit pattern of `T`, so it's sound to store it in an `Atomic`. + let ret = unsafe { + match Ordering::TYPE { + OrderingType::Full => T::Repr::atomic_xchg(a, v), + OrderingType::Acquire => T::Repr::atomic_xchg_acquire(a, v), + OrderingType::Release => T::Repr::atomic_xchg_release(a, v), + OrderingType::Relaxed => T::Repr::atomic_xchg_relaxed(a, v), + } + }; + + // SAFETY: The atomic variable holds a valid `T`, so `ret` is a valid bit pattern of `T`, + // therefore it's safe to call `from_repr()`. + unsafe { from_repr(ret) } + } + + /// Atomic compare and exchange. + /// + /// Compare: The comparison is done via the byte level comparison between the atomic variables + /// with the `old` value. + /// + /// Ordering: When succeeds, provides the corresponding ordering as the `Ordering` type + /// parameter indicates, and a failed one doesn't provide any ordering, the read part of a + /// failed cmpxchg should be treated as a relaxed read. + /// + /// Returns `Ok(value)` if cmpxchg succeeds, and `value` is guaranteed to be equal to `old`, + /// otherwise returns `Err(value)`, and `value` is the value of the atomic variable when + /// cmpxchg was happening. + /// + /// # Examples + /// + /// ```rust + /// use kernel::sync::atomic::{Atomic, Full, Relaxed}; + /// + /// let x = Atomic::new(42); + /// + /// // Checks whether cmpxchg succeeded. + /// let success = x.cmpxchg(52, 64, Relaxed).is_ok(); + /// # assert!(!success); + /// + /// // Checks whether cmpxchg failed. + /// let failure = x.cmpxchg(52, 64, Relaxed).is_err(); + /// # assert!(failure); + /// + /// // Uses the old value if failed, probably re-try cmpxchg. + /// match x.cmpxchg(52, 64, Relaxed) { + /// Ok(_) => { }, + /// Err(old) => { + /// // do something with `old`. + /// # assert_eq!(old, 42); + /// } + /// } + /// + /// // Uses the latest value regardlessly, same as atomic_cmpxchg() in C. + /// let latest = x.cmpxchg(42, 64, Full).unwrap_or_else(|old| old); + /// # assert_eq!(42, latest); + /// assert_eq!(64, x.load(Relaxed)); + /// ``` + #[doc(alias( + "atomic_cmpxchg", + "atomic64_cmpxchg", + "atomic_try_cmpxchg", + "atomic64_try_cmpxchg", + "compare_exchange" + ))] + #[inline(always)] + pub fn cmpxchg(&self, mut old: T, new: T, o: Ordering) -> Result { + // Note on code generation: + // + // try_cmpxchg() is used to implement cmpxchg(), and if the helper functions are inlined, + // the compiler is able to figure out that branch is not needed if the users don't care + // about whether the operation succeeds or not. One exception is on x86, due to commit + // 44fe84459faf ("locking/atomic: Fix atomic_try_cmpxchg() semantics"), the + // atomic_try_cmpxchg() on x86 has a branch even if the caller doesn't care about the + // success of cmpxchg and only wants to use the old value. For example, for code like: + // + // let latest = x.cmpxchg(42, 64, Full).unwrap_or_else(|old| old); + // + // It will still generate code: + // + // movl $0x40, %ecx + // movl $0x34, %eax + // lock + // cmpxchgl %ecx, 0x4(%rsp) + // jne 1f + // 2: + // ... + // 1: movl %eax, %ecx + // jmp 2b + // + // This might be "fixed" by introducing a try_cmpxchg_exclusive() that knows the "*old" + // location in the C function is always safe to write. + if self.try_cmpxchg(&mut old, new, o) { + Ok(old) + } else { + Err(old) + } + } + + /// Atomic compare and exchange and returns whether the operation succeeds. + /// + /// "Compare" and "Ordering" part are the same as [`Atomic::cmpxchg()`]. + /// + /// Returns `true` means the cmpxchg succeeds otherwise returns `false` with `old` updated to + /// the value of the atomic variable when cmpxchg was happening. + #[inline(always)] + fn try_cmpxchg(&self, old: &mut T, new: T, _: Ordering) -> bool { + let mut old_tmp = into_repr(*old); + let oldp = &raw mut old_tmp; + let new = into_repr(new); + // CAST: Per the safety requirement of `AllowAtomic`, a valid pointer of `T` is also a + // valid pointer of `T::Repr`. + let a = self.0.get().cast::(); + + // SAFETY: + // - For calling the atomic_try_cmpxchg*() function: + // - `a` is a valid pointer for the function per the CAST justification above. + // - `oldp` is a valid pointer for the function. + // - Per the type guarantees, the following atomic operation won't cause data races. + // - For extra safety requirement of usage on pointers returned by `self.as_ptr()`: + // - Atomic operations are used here. + // - For the bit validity of `Atomic`: + // - `new` is a valid bit pattern of `T`, so it's sound to store it in an `Atomic`. + let ret = unsafe { + match Ordering::TYPE { + OrderingType::Full => T::Repr::atomic_try_cmpxchg(a, oldp, new), + OrderingType::Acquire => T::Repr::atomic_try_cmpxchg_acquire(a, oldp, new), + OrderingType::Release => T::Repr::atomic_try_cmpxchg_release(a, oldp, new), + OrderingType::Relaxed => T::Repr::atomic_try_cmpxchg_relaxed(a, oldp, new), + } + }; + + // SAFETY: The atomic variable holds a valid `T`, so `old_tmp` is a valid bit pattern of + // `T`, therefore it's safe to call `from_repr()`. + *old = unsafe { from_repr(old_tmp) }; + + ret + } +} -- 2.39.5 (Apple Git-154)