From nobody Sun Feb 8 01:44:08 2026 Received: from mail-qk1-f171.google.com (mail-qk1-f171.google.com [209.85.222.171]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6BC1622126D; Mon, 9 Jun 2025 22:46:35 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.222.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509197; cv=none; b=iOa8c45lckTvE4fdty4csetke/qOJS+Eu2zxc2llxz90SpOha9B47N4UxZOCo3TxNEtCzesvZyk6jKMhKLfeN2+SQjjxgoGCdqgVZUguTgSj2E2tpcQRffsK9a9n4OKJQNf7NtZwbV+XVnHxOFYL7HhkcAl6Vw2iAzRKFteiE1g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509197; c=relaxed/simple; bh=zqoJKwLbyZOQzJIQrYfDhJ6sUsuqc6WKcd63zLefWC8=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=dQZqHyAt5/M6sFvyM78xpuT9446e98IE4PrP5O94te2+mMNrUE+TyaIbdyu8k343Xckk4FYEFb07lbqrhu+jCHFl/3N7A7UDFwHPYk/hM+LuiMVn6YQCt3NRXOHknD9M1s/0HyOtv2Dcgdzvi9+N4kxTVZy3D21S2hV2qf5fLFU= 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=mDfsbzR8; arc=none smtp.client-ip=209.85.222.171 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="mDfsbzR8" Received: by mail-qk1-f171.google.com with SMTP id af79cd13be357-7d094d1fd7cso634517585a.3; Mon, 09 Jun 2025 15:46:35 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1749509194; x=1750113994; darn=vger.kernel.org; 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=Q54aK1uou80V24Dko93ozgceq+PGaHQ40AHupkMIKss=; b=mDfsbzR87Rfj0cOqA1JIUFvk5octJl+ggxpHnZeVjvsjFnfcGfpZZL0EK0+ca4L1nP 1Q4PZLYEoD8cNo/GqNBKXMpW6G6ETN1CBYOsTqecoViOAsz4MeDHtG9xlwiGu3NEpOVE JUpFqzpx/8weJD6UwNHFa7rE1xe4ONuebUZ1ymaV2zbtWHWdv4Sew7kt4jcEoAU6mfJw 3Ao+x+HTMn3S0Li0oAdyPfgVLp+wfbnjan31pZ9Xgcb/jw0/LSiDDVnyhH5FTEInGhB2 bdnhKGBYDGtNbyYzmckx683tv9d6Y+LRkUxOxN3dVZlN6Imv8m5BT9cqR14BDRBLWR5q CN0A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1749509194; x=1750113994; 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=Q54aK1uou80V24Dko93ozgceq+PGaHQ40AHupkMIKss=; b=waFFTRkU3pEZnMCGt2RZ57ZWJfSXT2JlvOGo1ozx+x0+JbicNgzJsDSY6M0HpZC01c NE3ZMst22J3T49L/wTZ0hWYqfjk3TH4OBW+OU7tDYSRqYd1ZG3bGYDNj40UQzdQDzKuK xUC5R8iDYMQpecC/582nEDQkdqpNKxG0y+mL60UUAOpb5zmHgbffvJMrnt8Gb5Esve11 pPbLL8YzzT1Kl1cGJbqwG7dLdK+F4QkyHluSPbTNyhHlehms8k7VHjchRTBo0cM/K4+3 4jWAh1vYlC2pVDan5N5HSRsJ3uP02AZyWvIHEXT2VlTsxbzn3sflLQz2XCoy64n1rBWM im1Q== X-Forwarded-Encrypted: i=1; AJvYcCVs8DO7inzkhpXw7x3NgGZv7WAOpIWgJA/ZagwIv4cKM+kGH8z5w3YvcYNYnwdhDPrTMmLYzsVJEF6K@vger.kernel.org, AJvYcCXyZ9WLX4TY4jvVfYTJAaVc0fLYSaHrPfp1Zn+AUzZl2VW1pazEMksqXo6JKgYLwARybDDzYDs+GrpfNeVJ6q0=@vger.kernel.org X-Gm-Message-State: AOJu0Yw7xIavDjOnCGCAazg/fYPIvUhGQnnDWwNGxP0cC04hXt733z1R 10IchrIx2poly7jUhWCaz8+axMxTlhdCPHDDd7BG9gyN5MIxg9aPVVkC X-Gm-Gg: ASbGncsPhVSRktpnnhGT8Pi10XiUoEHc6OcPvyVsIDokR/7eUoeQOvTIxNffpWZB5ym brcrwPT8TBiUvjGUs2g/cNHygXV61xZMbjvkyp7ZaelZfLk+F2xfaz/FQYEqPvcvZ0aw1Tvt4Gk LaKsFG+VhCplepBpnhBUqVjaxNkJwk8cj8ZLZJAyulDe53fRA5+aNFr2FzK/v3CjNWXNGfJWDgV Pm+/A2YcVAEqBFlMCbDNz0PpAJ3gOLtkjC9limt1ZSr2wNVXF+XoEVq7/n9KW6PEhdHByIa2+K4 tQcKfgWudtc/Kwyc/kiRrNCzLYPL3EKRoyC4h1MaERuQ7XiFDf2SNZz/YXNReNpPwbVMo7v89v/ QCkI4wUdJiaZfR/yUhQKGqGGyPSo1s6ZVQEDcni8CLnGXVMkiYQpB X-Google-Smtp-Source: AGHT+IEA5S7cGZV/9v0KbKDn4fki0g6rxmKtDbYW2bDjFJq+qLXkGRjYVLgQwJm6xrWA7X66rv+ijA== X-Received: by 2002:a05:620a:4394:b0:7d2:1891:eef8 with SMTP id af79cd13be357-7d2298939bamr2708171985a.25.1749509194222; Mon, 09 Jun 2025 15:46:34 -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-7d2669b5700sm597760385a.113.2025.06.09.15.46.33 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Jun 2025 15:46:33 -0700 (PDT) Received: from phl-compute-11.internal (phl-compute-11.phl.internal [10.202.2.51]) by mailfauth.phl.internal (Postfix) with ESMTP id 45B8D1200043; Mon, 9 Jun 2025 18:46:33 -0400 (EDT) Received: from phl-mailfrontend-02 ([10.202.2.163]) by phl-compute-11.internal (MEProxy); Mon, 09 Jun 2025 18:46:33 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:32 -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" Subject: [PATCH v4 01/10] rust: Introduce atomic API helpers Date: Mon, 9 Jun 2025 15:46:06 -0700 Message-Id: <20250609224615.27061-2-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" In order to support LKMM atomics in Rust, add rust_helper_* for atomic APIs. These helpers ensure the implementation of LKMM atomics in Rust is the same as in C. This could save the maintenance burden of having two similar atomic implementations in asm. Originally-by: Mark Rutland Signed-off-by: Boqun Feng --- rust/helpers/atomic.c | 1038 +++++++++++++++++++++ rust/helpers/helpers.c | 1 + scripts/atomic/gen-atomics.sh | 1 + scripts/atomic/gen-rust-atomic-helpers.sh | 65 ++ 4 files changed, 1105 insertions(+) create mode 100644 rust/helpers/atomic.c create mode 100755 scripts/atomic/gen-rust-atomic-helpers.sh diff --git a/rust/helpers/atomic.c b/rust/helpers/atomic.c new file mode 100644 index 000000000000..00bf10887928 --- /dev/null +++ b/rust/helpers/atomic.c @@ -0,0 +1,1038 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Generated by scripts/atomic/gen-rust-atomic-helpers.sh +// DO NOT MODIFY THIS FILE DIRECTLY + +/* + * This file provides helpers for the various atomic functions for Rust. + */ +#ifndef _RUST_ATOMIC_API_H +#define _RUST_ATOMIC_API_H + +#include + +// TODO: Remove this after LTO helper support is added. +#define __rust_helper + +__rust_helper int +rust_helper_atomic_read(const atomic_t *v) +{ + return atomic_read(v); +} + +__rust_helper int +rust_helper_atomic_read_acquire(const atomic_t *v) +{ + return atomic_read_acquire(v); +} + +__rust_helper void +rust_helper_atomic_set(atomic_t *v, int i) +{ + atomic_set(v, i); +} + +__rust_helper void +rust_helper_atomic_set_release(atomic_t *v, int i) +{ + atomic_set_release(v, i); +} + +__rust_helper void +rust_helper_atomic_add(int i, atomic_t *v) +{ + atomic_add(i, v); +} + +__rust_helper int +rust_helper_atomic_add_return(int i, atomic_t *v) +{ + return atomic_add_return(i, v); +} + +__rust_helper int +rust_helper_atomic_add_return_acquire(int i, atomic_t *v) +{ + return atomic_add_return_acquire(i, v); +} + +__rust_helper int +rust_helper_atomic_add_return_release(int i, atomic_t *v) +{ + return atomic_add_return_release(i, v); +} + +__rust_helper int +rust_helper_atomic_add_return_relaxed(int i, atomic_t *v) +{ + return atomic_add_return_relaxed(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_add(int i, atomic_t *v) +{ + return atomic_fetch_add(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_add_acquire(int i, atomic_t *v) +{ + return atomic_fetch_add_acquire(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_add_release(int i, atomic_t *v) +{ + return atomic_fetch_add_release(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_add_relaxed(int i, atomic_t *v) +{ + return atomic_fetch_add_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic_sub(int i, atomic_t *v) +{ + atomic_sub(i, v); +} + +__rust_helper int +rust_helper_atomic_sub_return(int i, atomic_t *v) +{ + return atomic_sub_return(i, v); +} + +__rust_helper int +rust_helper_atomic_sub_return_acquire(int i, atomic_t *v) +{ + return atomic_sub_return_acquire(i, v); +} + +__rust_helper int +rust_helper_atomic_sub_return_release(int i, atomic_t *v) +{ + return atomic_sub_return_release(i, v); +} + +__rust_helper int +rust_helper_atomic_sub_return_relaxed(int i, atomic_t *v) +{ + return atomic_sub_return_relaxed(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_sub(int i, atomic_t *v) +{ + return atomic_fetch_sub(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_sub_acquire(int i, atomic_t *v) +{ + return atomic_fetch_sub_acquire(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_sub_release(int i, atomic_t *v) +{ + return atomic_fetch_sub_release(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_sub_relaxed(int i, atomic_t *v) +{ + return atomic_fetch_sub_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic_inc(atomic_t *v) +{ + atomic_inc(v); +} + +__rust_helper int +rust_helper_atomic_inc_return(atomic_t *v) +{ + return atomic_inc_return(v); +} + +__rust_helper int +rust_helper_atomic_inc_return_acquire(atomic_t *v) +{ + return atomic_inc_return_acquire(v); +} + +__rust_helper int +rust_helper_atomic_inc_return_release(atomic_t *v) +{ + return atomic_inc_return_release(v); +} + +__rust_helper int +rust_helper_atomic_inc_return_relaxed(atomic_t *v) +{ + return atomic_inc_return_relaxed(v); +} + +__rust_helper int +rust_helper_atomic_fetch_inc(atomic_t *v) +{ + return atomic_fetch_inc(v); +} + +__rust_helper int +rust_helper_atomic_fetch_inc_acquire(atomic_t *v) +{ + return atomic_fetch_inc_acquire(v); +} + +__rust_helper int +rust_helper_atomic_fetch_inc_release(atomic_t *v) +{ + return atomic_fetch_inc_release(v); +} + +__rust_helper int +rust_helper_atomic_fetch_inc_relaxed(atomic_t *v) +{ + return atomic_fetch_inc_relaxed(v); +} + +__rust_helper void +rust_helper_atomic_dec(atomic_t *v) +{ + atomic_dec(v); +} + +__rust_helper int +rust_helper_atomic_dec_return(atomic_t *v) +{ + return atomic_dec_return(v); +} + +__rust_helper int +rust_helper_atomic_dec_return_acquire(atomic_t *v) +{ + return atomic_dec_return_acquire(v); +} + +__rust_helper int +rust_helper_atomic_dec_return_release(atomic_t *v) +{ + return atomic_dec_return_release(v); +} + +__rust_helper int +rust_helper_atomic_dec_return_relaxed(atomic_t *v) +{ + return atomic_dec_return_relaxed(v); +} + +__rust_helper int +rust_helper_atomic_fetch_dec(atomic_t *v) +{ + return atomic_fetch_dec(v); +} + +__rust_helper int +rust_helper_atomic_fetch_dec_acquire(atomic_t *v) +{ + return atomic_fetch_dec_acquire(v); +} + +__rust_helper int +rust_helper_atomic_fetch_dec_release(atomic_t *v) +{ + return atomic_fetch_dec_release(v); +} + +__rust_helper int +rust_helper_atomic_fetch_dec_relaxed(atomic_t *v) +{ + return atomic_fetch_dec_relaxed(v); +} + +__rust_helper void +rust_helper_atomic_and(int i, atomic_t *v) +{ + atomic_and(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_and(int i, atomic_t *v) +{ + return atomic_fetch_and(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_and_acquire(int i, atomic_t *v) +{ + return atomic_fetch_and_acquire(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_and_release(int i, atomic_t *v) +{ + return atomic_fetch_and_release(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_and_relaxed(int i, atomic_t *v) +{ + return atomic_fetch_and_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic_andnot(int i, atomic_t *v) +{ + atomic_andnot(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_andnot(int i, atomic_t *v) +{ + return atomic_fetch_andnot(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_andnot_acquire(int i, atomic_t *v) +{ + return atomic_fetch_andnot_acquire(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_andnot_release(int i, atomic_t *v) +{ + return atomic_fetch_andnot_release(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_andnot_relaxed(int i, atomic_t *v) +{ + return atomic_fetch_andnot_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic_or(int i, atomic_t *v) +{ + atomic_or(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_or(int i, atomic_t *v) +{ + return atomic_fetch_or(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_or_acquire(int i, atomic_t *v) +{ + return atomic_fetch_or_acquire(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_or_release(int i, atomic_t *v) +{ + return atomic_fetch_or_release(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_or_relaxed(int i, atomic_t *v) +{ + return atomic_fetch_or_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic_xor(int i, atomic_t *v) +{ + atomic_xor(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_xor(int i, atomic_t *v) +{ + return atomic_fetch_xor(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_xor_acquire(int i, atomic_t *v) +{ + return atomic_fetch_xor_acquire(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_xor_release(int i, atomic_t *v) +{ + return atomic_fetch_xor_release(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_xor_relaxed(int i, atomic_t *v) +{ + return atomic_fetch_xor_relaxed(i, v); +} + +__rust_helper int +rust_helper_atomic_xchg(atomic_t *v, int new) +{ + return atomic_xchg(v, new); +} + +__rust_helper int +rust_helper_atomic_xchg_acquire(atomic_t *v, int new) +{ + return atomic_xchg_acquire(v, new); +} + +__rust_helper int +rust_helper_atomic_xchg_release(atomic_t *v, int new) +{ + return atomic_xchg_release(v, new); +} + +__rust_helper int +rust_helper_atomic_xchg_relaxed(atomic_t *v, int new) +{ + return atomic_xchg_relaxed(v, new); +} + +__rust_helper int +rust_helper_atomic_cmpxchg(atomic_t *v, int old, int new) +{ + return atomic_cmpxchg(v, old, new); +} + +__rust_helper int +rust_helper_atomic_cmpxchg_acquire(atomic_t *v, int old, int new) +{ + return atomic_cmpxchg_acquire(v, old, new); +} + +__rust_helper int +rust_helper_atomic_cmpxchg_release(atomic_t *v, int old, int new) +{ + return atomic_cmpxchg_release(v, old, new); +} + +__rust_helper int +rust_helper_atomic_cmpxchg_relaxed(atomic_t *v, int old, int new) +{ + return atomic_cmpxchg_relaxed(v, old, new); +} + +__rust_helper bool +rust_helper_atomic_try_cmpxchg(atomic_t *v, int *old, int new) +{ + return atomic_try_cmpxchg(v, old, new); +} + +__rust_helper bool +rust_helper_atomic_try_cmpxchg_acquire(atomic_t *v, int *old, int new) +{ + return atomic_try_cmpxchg_acquire(v, old, new); +} + +__rust_helper bool +rust_helper_atomic_try_cmpxchg_release(atomic_t *v, int *old, int new) +{ + return atomic_try_cmpxchg_release(v, old, new); +} + +__rust_helper bool +rust_helper_atomic_try_cmpxchg_relaxed(atomic_t *v, int *old, int new) +{ + return atomic_try_cmpxchg_relaxed(v, old, new); +} + +__rust_helper bool +rust_helper_atomic_sub_and_test(int i, atomic_t *v) +{ + return atomic_sub_and_test(i, v); +} + +__rust_helper bool +rust_helper_atomic_dec_and_test(atomic_t *v) +{ + return atomic_dec_and_test(v); +} + +__rust_helper bool +rust_helper_atomic_inc_and_test(atomic_t *v) +{ + return atomic_inc_and_test(v); +} + +__rust_helper bool +rust_helper_atomic_add_negative(int i, atomic_t *v) +{ + return atomic_add_negative(i, v); +} + +__rust_helper bool +rust_helper_atomic_add_negative_acquire(int i, atomic_t *v) +{ + return atomic_add_negative_acquire(i, v); +} + +__rust_helper bool +rust_helper_atomic_add_negative_release(int i, atomic_t *v) +{ + return atomic_add_negative_release(i, v); +} + +__rust_helper bool +rust_helper_atomic_add_negative_relaxed(int i, atomic_t *v) +{ + return atomic_add_negative_relaxed(i, v); +} + +__rust_helper int +rust_helper_atomic_fetch_add_unless(atomic_t *v, int a, int u) +{ + return atomic_fetch_add_unless(v, a, u); +} + +__rust_helper bool +rust_helper_atomic_add_unless(atomic_t *v, int a, int u) +{ + return atomic_add_unless(v, a, u); +} + +__rust_helper bool +rust_helper_atomic_inc_not_zero(atomic_t *v) +{ + return atomic_inc_not_zero(v); +} + +__rust_helper bool +rust_helper_atomic_inc_unless_negative(atomic_t *v) +{ + return atomic_inc_unless_negative(v); +} + +__rust_helper bool +rust_helper_atomic_dec_unless_positive(atomic_t *v) +{ + return atomic_dec_unless_positive(v); +} + +__rust_helper int +rust_helper_atomic_dec_if_positive(atomic_t *v) +{ + return atomic_dec_if_positive(v); +} + +__rust_helper s64 +rust_helper_atomic64_read(const atomic64_t *v) +{ + return atomic64_read(v); +} + +__rust_helper s64 +rust_helper_atomic64_read_acquire(const atomic64_t *v) +{ + return atomic64_read_acquire(v); +} + +__rust_helper void +rust_helper_atomic64_set(atomic64_t *v, s64 i) +{ + atomic64_set(v, i); +} + +__rust_helper void +rust_helper_atomic64_set_release(atomic64_t *v, s64 i) +{ + atomic64_set_release(v, i); +} + +__rust_helper void +rust_helper_atomic64_add(s64 i, atomic64_t *v) +{ + atomic64_add(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_add_return(s64 i, atomic64_t *v) +{ + return atomic64_add_return(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_add_return_acquire(s64 i, atomic64_t *v) +{ + return atomic64_add_return_acquire(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_add_return_release(s64 i, atomic64_t *v) +{ + return atomic64_add_return_release(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_add_return_relaxed(s64 i, atomic64_t *v) +{ + return atomic64_add_return_relaxed(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_add(s64 i, atomic64_t *v) +{ + return atomic64_fetch_add(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_add_acquire(s64 i, atomic64_t *v) +{ + return atomic64_fetch_add_acquire(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_add_release(s64 i, atomic64_t *v) +{ + return atomic64_fetch_add_release(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_add_relaxed(s64 i, atomic64_t *v) +{ + return atomic64_fetch_add_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic64_sub(s64 i, atomic64_t *v) +{ + atomic64_sub(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_sub_return(s64 i, atomic64_t *v) +{ + return atomic64_sub_return(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_sub_return_acquire(s64 i, atomic64_t *v) +{ + return atomic64_sub_return_acquire(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_sub_return_release(s64 i, atomic64_t *v) +{ + return atomic64_sub_return_release(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_sub_return_relaxed(s64 i, atomic64_t *v) +{ + return atomic64_sub_return_relaxed(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_sub(s64 i, atomic64_t *v) +{ + return atomic64_fetch_sub(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_sub_acquire(s64 i, atomic64_t *v) +{ + return atomic64_fetch_sub_acquire(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_sub_release(s64 i, atomic64_t *v) +{ + return atomic64_fetch_sub_release(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_sub_relaxed(s64 i, atomic64_t *v) +{ + return atomic64_fetch_sub_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic64_inc(atomic64_t *v) +{ + atomic64_inc(v); +} + +__rust_helper s64 +rust_helper_atomic64_inc_return(atomic64_t *v) +{ + return atomic64_inc_return(v); +} + +__rust_helper s64 +rust_helper_atomic64_inc_return_acquire(atomic64_t *v) +{ + return atomic64_inc_return_acquire(v); +} + +__rust_helper s64 +rust_helper_atomic64_inc_return_release(atomic64_t *v) +{ + return atomic64_inc_return_release(v); +} + +__rust_helper s64 +rust_helper_atomic64_inc_return_relaxed(atomic64_t *v) +{ + return atomic64_inc_return_relaxed(v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_inc(atomic64_t *v) +{ + return atomic64_fetch_inc(v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_inc_acquire(atomic64_t *v) +{ + return atomic64_fetch_inc_acquire(v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_inc_release(atomic64_t *v) +{ + return atomic64_fetch_inc_release(v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_inc_relaxed(atomic64_t *v) +{ + return atomic64_fetch_inc_relaxed(v); +} + +__rust_helper void +rust_helper_atomic64_dec(atomic64_t *v) +{ + atomic64_dec(v); +} + +__rust_helper s64 +rust_helper_atomic64_dec_return(atomic64_t *v) +{ + return atomic64_dec_return(v); +} + +__rust_helper s64 +rust_helper_atomic64_dec_return_acquire(atomic64_t *v) +{ + return atomic64_dec_return_acquire(v); +} + +__rust_helper s64 +rust_helper_atomic64_dec_return_release(atomic64_t *v) +{ + return atomic64_dec_return_release(v); +} + +__rust_helper s64 +rust_helper_atomic64_dec_return_relaxed(atomic64_t *v) +{ + return atomic64_dec_return_relaxed(v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_dec(atomic64_t *v) +{ + return atomic64_fetch_dec(v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_dec_acquire(atomic64_t *v) +{ + return atomic64_fetch_dec_acquire(v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_dec_release(atomic64_t *v) +{ + return atomic64_fetch_dec_release(v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_dec_relaxed(atomic64_t *v) +{ + return atomic64_fetch_dec_relaxed(v); +} + +__rust_helper void +rust_helper_atomic64_and(s64 i, atomic64_t *v) +{ + atomic64_and(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_and(s64 i, atomic64_t *v) +{ + return atomic64_fetch_and(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_and_acquire(s64 i, atomic64_t *v) +{ + return atomic64_fetch_and_acquire(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_and_release(s64 i, atomic64_t *v) +{ + return atomic64_fetch_and_release(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_and_relaxed(s64 i, atomic64_t *v) +{ + return atomic64_fetch_and_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic64_andnot(s64 i, atomic64_t *v) +{ + atomic64_andnot(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_andnot(s64 i, atomic64_t *v) +{ + return atomic64_fetch_andnot(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_andnot_acquire(s64 i, atomic64_t *v) +{ + return atomic64_fetch_andnot_acquire(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_andnot_release(s64 i, atomic64_t *v) +{ + return atomic64_fetch_andnot_release(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_andnot_relaxed(s64 i, atomic64_t *v) +{ + return atomic64_fetch_andnot_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic64_or(s64 i, atomic64_t *v) +{ + atomic64_or(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_or(s64 i, atomic64_t *v) +{ + return atomic64_fetch_or(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_or_acquire(s64 i, atomic64_t *v) +{ + return atomic64_fetch_or_acquire(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_or_release(s64 i, atomic64_t *v) +{ + return atomic64_fetch_or_release(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_or_relaxed(s64 i, atomic64_t *v) +{ + return atomic64_fetch_or_relaxed(i, v); +} + +__rust_helper void +rust_helper_atomic64_xor(s64 i, atomic64_t *v) +{ + atomic64_xor(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_xor(s64 i, atomic64_t *v) +{ + return atomic64_fetch_xor(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_xor_acquire(s64 i, atomic64_t *v) +{ + return atomic64_fetch_xor_acquire(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_xor_release(s64 i, atomic64_t *v) +{ + return atomic64_fetch_xor_release(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_xor_relaxed(s64 i, atomic64_t *v) +{ + return atomic64_fetch_xor_relaxed(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_xchg(atomic64_t *v, s64 new) +{ + return atomic64_xchg(v, new); +} + +__rust_helper s64 +rust_helper_atomic64_xchg_acquire(atomic64_t *v, s64 new) +{ + return atomic64_xchg_acquire(v, new); +} + +__rust_helper s64 +rust_helper_atomic64_xchg_release(atomic64_t *v, s64 new) +{ + return atomic64_xchg_release(v, new); +} + +__rust_helper s64 +rust_helper_atomic64_xchg_relaxed(atomic64_t *v, s64 new) +{ + return atomic64_xchg_relaxed(v, new); +} + +__rust_helper s64 +rust_helper_atomic64_cmpxchg(atomic64_t *v, s64 old, s64 new) +{ + return atomic64_cmpxchg(v, old, new); +} + +__rust_helper s64 +rust_helper_atomic64_cmpxchg_acquire(atomic64_t *v, s64 old, s64 new) +{ + return atomic64_cmpxchg_acquire(v, old, new); +} + +__rust_helper s64 +rust_helper_atomic64_cmpxchg_release(atomic64_t *v, s64 old, s64 new) +{ + return atomic64_cmpxchg_release(v, old, new); +} + +__rust_helper s64 +rust_helper_atomic64_cmpxchg_relaxed(atomic64_t *v, s64 old, s64 new) +{ + return atomic64_cmpxchg_relaxed(v, old, new); +} + +__rust_helper bool +rust_helper_atomic64_try_cmpxchg(atomic64_t *v, s64 *old, s64 new) +{ + return atomic64_try_cmpxchg(v, old, new); +} + +__rust_helper bool +rust_helper_atomic64_try_cmpxchg_acquire(atomic64_t *v, s64 *old, s64 new) +{ + return atomic64_try_cmpxchg_acquire(v, old, new); +} + +__rust_helper bool +rust_helper_atomic64_try_cmpxchg_release(atomic64_t *v, s64 *old, s64 new) +{ + return atomic64_try_cmpxchg_release(v, old, new); +} + +__rust_helper bool +rust_helper_atomic64_try_cmpxchg_relaxed(atomic64_t *v, s64 *old, s64 new) +{ + return atomic64_try_cmpxchg_relaxed(v, old, new); +} + +__rust_helper bool +rust_helper_atomic64_sub_and_test(s64 i, atomic64_t *v) +{ + return atomic64_sub_and_test(i, v); +} + +__rust_helper bool +rust_helper_atomic64_dec_and_test(atomic64_t *v) +{ + return atomic64_dec_and_test(v); +} + +__rust_helper bool +rust_helper_atomic64_inc_and_test(atomic64_t *v) +{ + return atomic64_inc_and_test(v); +} + +__rust_helper bool +rust_helper_atomic64_add_negative(s64 i, atomic64_t *v) +{ + return atomic64_add_negative(i, v); +} + +__rust_helper bool +rust_helper_atomic64_add_negative_acquire(s64 i, atomic64_t *v) +{ + return atomic64_add_negative_acquire(i, v); +} + +__rust_helper bool +rust_helper_atomic64_add_negative_release(s64 i, atomic64_t *v) +{ + return atomic64_add_negative_release(i, v); +} + +__rust_helper bool +rust_helper_atomic64_add_negative_relaxed(s64 i, atomic64_t *v) +{ + return atomic64_add_negative_relaxed(i, v); +} + +__rust_helper s64 +rust_helper_atomic64_fetch_add_unless(atomic64_t *v, s64 a, s64 u) +{ + return atomic64_fetch_add_unless(v, a, u); +} + +__rust_helper bool +rust_helper_atomic64_add_unless(atomic64_t *v, s64 a, s64 u) +{ + return atomic64_add_unless(v, a, u); +} + +__rust_helper bool +rust_helper_atomic64_inc_not_zero(atomic64_t *v) +{ + return atomic64_inc_not_zero(v); +} + +__rust_helper bool +rust_helper_atomic64_inc_unless_negative(atomic64_t *v) +{ + return atomic64_inc_unless_negative(v); +} + +__rust_helper bool +rust_helper_atomic64_dec_unless_positive(atomic64_t *v) +{ + return atomic64_dec_unless_positive(v); +} + +__rust_helper s64 +rust_helper_atomic64_dec_if_positive(atomic64_t *v) +{ + return atomic64_dec_if_positive(v); +} + +#endif /* _RUST_ATOMIC_API_H */ +// b032d261814b3e119b72dbf7d21447f6731325ee diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 0f1b5d115985..0e7e7b388062 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -7,6 +7,7 @@ * Sorted alphabetically. */ =20 +#include "atomic.c" #include "auxiliary.c" #include "blk.c" #include "bug.c" diff --git a/scripts/atomic/gen-atomics.sh b/scripts/atomic/gen-atomics.sh index 5b98a8307693..02508d0d6fe4 100755 --- a/scripts/atomic/gen-atomics.sh +++ b/scripts/atomic/gen-atomics.sh @@ -11,6 +11,7 @@ cat < ${LINUXDIR}/include= /${header} diff --git a/scripts/atomic/gen-rust-atomic-helpers.sh b/scripts/atomic/gen= -rust-atomic-helpers.sh new file mode 100755 index 000000000000..72f2e5bde0c6 --- /dev/null +++ b/scripts/atomic/gen-rust-atomic-helpers.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 + +ATOMICDIR=3D$(dirname $0) + +. ${ATOMICDIR}/atomic-tbl.sh + +#gen_proto_order_variant(meta, pfx, name, sfx, order, atomic, int, arg...) +gen_proto_order_variant() +{ + local meta=3D"$1"; shift + local pfx=3D"$1"; shift + local name=3D"$1"; shift + local sfx=3D"$1"; shift + local order=3D"$1"; shift + local atomic=3D"$1"; shift + local int=3D"$1"; shift + + local atomicname=3D"${atomic}_${pfx}${name}${sfx}${order}" + + local ret=3D"$(gen_ret_type "${meta}" "${int}")" + local params=3D"$(gen_params "${int}" "${atomic}" "$@")" + local args=3D"$(gen_args "$@")" + local retstmt=3D"$(gen_ret_stmt "${meta}")" + +cat < + +// TODO: Remove this after LTO helper support is added. +#define __rust_helper + +EOF + +grep '^[a-z]' "$1" | while read name meta args; do + gen_proto "${meta}" "${name}" "atomic" "int" ${args} +done + +grep '^[a-z]' "$1" | while read name meta args; do + gen_proto "${meta}" "${name}" "atomic64" "s64" ${args} +done + +cat < X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:34 -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" Subject: [PATCH v4 02/10] rust: sync: Add basic atomic operation mapping framework Date: Mon, 9 Jun 2025 15:46:07 -0700 Message-Id: <20250609224615.27061-3-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" Preparation for generic atomic implementation. To unify the implementation of a generic method over `i32` and `i64`, the C side atomic methods need to be grouped so that in a generic method, they can be referred as ::, otherwise their parameters and return value are different between `i32` and `i64`, which would require using `transmute()` to unify the type into a `T`. Introduce `AtomicImpl` to represent a basic type in Rust that has the direct mapping to an atomic implementation from C. This trait is sealed, and currently only `i32` and `i64` impl this. Further, different methods are put into different `*Ops` trait groups, and this is for the future when smaller types like `i8`/`i16` are supported but only with a limited set of API (e.g. only set(), load(), xchg() and cmpxchg(), no add() or sub() etc). While the atomic mod is introduced, documentation is also added for memory models and data races. Also bump my role to the maintainer of ATOMIC INFRASTRUCTURE to reflect my responsiblity on the Rust atomic mod. Signed-off-by: Boqun Feng --- MAINTAINERS | 4 +- rust/kernel/sync.rs | 1 + rust/kernel/sync/atomic.rs | 19 ++++ rust/kernel/sync/atomic/ops.rs | 199 +++++++++++++++++++++++++++++++++ 4 files changed, 222 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/sync/atomic.rs create mode 100644 rust/kernel/sync/atomic/ops.rs diff --git a/MAINTAINERS b/MAINTAINERS index a92290fffa16..fe0cf0a2e6e5 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -3894,7 +3894,7 @@ F: drivers/input/touchscreen/atmel_mxt_ts.c ATOMIC INFRASTRUCTURE M: Will Deacon M: Peter Zijlstra -R: Boqun Feng +M: Boqun Feng R: Mark Rutland L: linux-kernel@vger.kernel.org S: Maintained @@ -3903,6 +3903,8 @@ F: arch/*/include/asm/atomic*.h F: include/*/atomic*.h F: include/linux/refcount.h F: scripts/atomic/ +F: rust/kernel/sync/atomic.rs +F: rust/kernel/sync/atomic/ =20 ATTO EXPRESSSAS SAS/SATA RAID SCSI DRIVER M: Bradley Grove diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index 36a719015583..b620027e0641 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -10,6 +10,7 @@ use pin_init; =20 mod arc; +pub mod atomic; mod condvar; pub mod lock; mod locked_by; diff --git a/rust/kernel/sync/atomic.rs b/rust/kernel/sync/atomic.rs new file mode 100644 index 000000000000..65e41dba97b7 --- /dev/null +++ b/rust/kernel/sync/atomic.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Atomic primitives. +//! +//! These primitives have the same semantics as their C counterparts: and = the precise definitions of +//! semantics can be found at [`LKMM`]. Note that Linux Kernel Memory (Con= sistency) Model is the +//! only model for Rust code in kernel, and Rust's own atomics should be a= voided. +//! +//! # Data races +//! +//! [`LKMM`] atomics have different rules regarding data races: +//! +//! - A normal write from C side is treated as an atomic write if +//! CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC=3Dy. +//! - Mixed-size atomic accesses don't cause data races. +//! +//! [`LKMM`]: srctree/tools/memory-mode/ + +pub mod ops; diff --git a/rust/kernel/sync/atomic/ops.rs b/rust/kernel/sync/atomic/ops.rs new file mode 100644 index 000000000000..f8825f7c84f0 --- /dev/null +++ b/rust/kernel/sync/atomic/ops.rs @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Atomic implementations. +//! +//! Provides 1:1 mapping of atomic implementations. + +use crate::bindings::*; +use crate::macros::paste; + +mod private { + /// Sealed trait marker to disable customized impls on atomic implemen= tation traits. + pub trait Sealed {} +} + +// `i32` and `i64` are only supported atomic implementations. +impl private::Sealed for i32 {} +impl private::Sealed for i64 {} + +/// A marker trait for types that implement atomic operations with C side = primitives. +/// +/// This trait is sealed, and only types that have directly mapping to the= C side atomics should +/// impl this: +/// +/// - `i32` maps to `atomic_t`. +/// - `i64` maps to `atomic64_t`. +pub trait AtomicImpl: Sized + Send + Copy + private::Sealed {} + +// `atomic_t` implements atomic operations on `i32`. +impl AtomicImpl for i32 {} + +// `atomic64_t` implements atomic operations on `i64`. +impl AtomicImpl for i64 {} + +// This macro generates the function signature with given argument list an= d return type. +macro_rules! declare_atomic_method { + ( + $func:ident($($arg:ident : $arg_type:ty),*) $(-> $ret:ty)? + ) =3D> { + paste!( + #[doc =3D concat!("Atomic ", stringify!($func))] + #[doc =3D "# Safety"] + #[doc =3D "- Any pointer passed to the function has to be a va= lid pointer"] + #[doc =3D "- Accesses must not cause data races per LKMM:"] + #[doc =3D " - Atomic read racing with normal read, normal wri= te or atomic write is not data race."] + #[doc =3D " - Atomic write racing with normal read or normal = write is data-race, unless the"] + #[doc =3D " normal accesses are done at C side and consider= ed as immune to data"] + #[doc =3D " races, e.g. CONFIG_KCSAN_ASSUME_PLAIN_WRITES_AT= OMIC."] + unsafe fn [< atomic_ $func >]($($arg: $arg_type,)*) $(-> $ret)= ?; + ); + }; + ( + $func:ident [$variant:ident $($rest:ident)*]($($arg_sig:tt)*) $(->= $ret:ty)? + ) =3D> { + paste!( + declare_atomic_method!( + [< $func _ $variant >]($($arg_sig)*) $(-> $ret)? + ); + ); + + declare_atomic_method!( + $func [$($rest)*]($($arg_sig)*) $(-> $ret)? + ); + }; + ( + $func:ident []($($arg_sig:tt)*) $(-> $ret:ty)? + ) =3D> { + declare_atomic_method!( + $func($($arg_sig)*) $(-> $ret)? + ); + } +} + +// This macro generates the function implementation with given argument li= st and return type, and it +// will replace "call(...)" expression with "$ctype _ $func" to call the r= eal C function. +macro_rules! impl_atomic_method { + ( + ($ctype:ident) $func:ident($($arg:ident: $arg_type:ty),*) $(-> $re= t:ty)? { + call($($c_arg:expr),*) + } + ) =3D> { + paste!( + #[inline(always)] + unsafe fn [< atomic_ $func >]($($arg: $arg_type,)*) $(-> $ret)= ? { + // SAFETY: Per function safety requirement, all pointers a= re valid, and accesses + // won't cause data race per LKMM. + unsafe { [< $ctype _ $func >]($($c_arg,)*) } + } + ); + }; + ( + ($ctype:ident) $func:ident[$variant:ident $($rest:ident)*]($($arg_= sig:tt)*) $(-> $ret:ty)? { + call($($arg:tt)*) + } + ) =3D> { + paste!( + impl_atomic_method!( + ($ctype) [< $func _ $variant >]($($arg_sig)*) $( -> $ret)?= { + call($($arg)*) + } + ); + ); + impl_atomic_method!( + ($ctype) $func [$($rest)*]($($arg_sig)*) $( -> $ret)? { + call($($arg)*) + } + ); + }; + ( + ($ctype:ident) $func:ident[]($($arg_sig:tt)*) $( -> $ret:ty)? { + call($($arg:tt)*) + } + ) =3D> { + impl_atomic_method!( + ($ctype) $func($($arg_sig)*) $(-> $ret)? { + call($($arg)*) + } + ); + } +} + +// Delcares $ops trait with methods and implements the trait for `i32` and= `i64`. +macro_rules! declare_and_impl_atomic_methods { + ($ops:ident ($doc:literal) { + $( + $func:ident [$($variant:ident),*]($($arg_sig:tt)*) $( -> $ret:= ty)? { + call($($arg:tt)*) + } + )* + }) =3D> { + #[doc =3D $doc] + pub trait $ops: AtomicImpl { + $( + declare_atomic_method!( + $func[$($variant)*]($($arg_sig)*) $(-> $ret)? + ); + )* + } + + impl $ops for i32 { + $( + impl_atomic_method!( + (atomic) $func[$($variant)*]($($arg_sig)*) $(-> $ret)?= { + call($($arg)*) + } + ); + )* + } + + impl $ops for i64 { + $( + impl_atomic_method!( + (atomic64) $func[$($variant)*]($($arg_sig)*) $(-> $ret= )? { + call($($arg)*) + } + ); + )* + } + } +} + +declare_and_impl_atomic_methods!( + AtomicHasBasicOps ("Basic atomic operations") { + read[acquire](ptr: *mut Self) -> Self { + call(ptr as *mut _) + } + + set[release](ptr: *mut Self, v: Self) { + call(ptr as *mut _, v) + } + } +); + +declare_and_impl_atomic_methods!( + AtomicHasXchgOps ("Exchange and compare-and-exchange atomic operations= ") { + xchg[acquire, release, relaxed](ptr: *mut Self, v: Self) -> Self { + call(ptr as *mut _, v) + } + + cmpxchg[acquire, release, relaxed](ptr: *mut Self, old: Self, new:= Self) -> Self { + call(ptr as *mut _, old, new) + } + + try_cmpxchg[acquire, release, relaxed](ptr: *mut Self, old: *mut S= elf, new: Self) -> bool { + call(ptr as *mut _, old, new) + } + } +); + +declare_and_impl_atomic_methods!( + AtomicHasArithmeticOps ("Atomic arithmetic operations") { + add[](ptr: *mut Self, v: Self) { + call(v, ptr as *mut _) + } + + fetch_add[acquire, release, relaxed](ptr: *mut Self, v: Self) -> S= elf { + call(v, ptr as *mut _) + } + } +); --=20 2.39.5 (Apple Git-154) From nobody Sun Feb 8 01:44:08 2026 Received: from mail-qk1-f182.google.com (mail-qk1-f182.google.com [209.85.222.182]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 932AF223DC5; Mon, 9 Jun 2025 22:46:38 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.222.182 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509200; cv=none; b=oN81fSs1GfEQVpsixAX2+cOizXZqzPPrUlNfQnU1VTUsqSeDmz2OgYamr/sXEXBNEf0an75srj0E04UyqTh8balofscYWFz4Z/tQwOCFjxn/vVmEFsEtoWqjail1rld0Baewae9S4S4+zUccFN755WuJ3miOFwPSi+XmKDFVsPc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509200; c=relaxed/simple; bh=0bInjRe6WsElsR76wx5HxxQl5ek7EdEBeQSHoOJJMSw=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=Eq27GMFx3e17vcpoKAGSAqzzWcUzCOFp2cX5cXzEnP3LgMzdWMl0BsX+QfqN82E3YrXuwStbqTfgqO81DjTzcuDV+i/RyL1gkcYcyZDb+oe56e7MwyaAM6x9zaxahjULXa5bvxiruFATdmBPB/a28f9W4w8GtCp8X7Wl5UQEUg4= 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=Sg/FW/4W; arc=none smtp.client-ip=209.85.222.182 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="Sg/FW/4W" Received: by mail-qk1-f182.google.com with SMTP id af79cd13be357-7d38ddc198eso207317185a.1; Mon, 09 Jun 2025 15:46:38 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1749509197; x=1750113997; darn=vger.kernel.org; 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=iocCkfb+nHX+01sle1IC4FFymsCULZeQmkzsDFnCdV8=; b=Sg/FW/4W46umMHAhLQIGxuMLeYa3g9z24l4r4MshBzVlHJZFfbSaeoJlnYPYSqSZ/v rrgiuRrJyqBZh5EYWR8l60TiKBJjaiC397Y3c5c/o6Q/gg0ltVu3I1yv2CaIFDa1EAbt tOEOpEutPgM5XPH1tkEZmk7JCsLbwuxENZA3p+FnvnRCAPH7i1NzfNZihRjA9C8xneHG DWqg+fsTA5hnON2ctKE24RDHfaOUrTiwsPmVU/USwkSKNrrU6Nvuglgp8bSMxYrsC/Kr JASn0Eq9Qo3jI311OhUbEKyJ+PZVPP2SDJXtCw1HXhcFQRgnkXQOLhLtWeeKC53ggq+O 099A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1749509197; x=1750113997; 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=iocCkfb+nHX+01sle1IC4FFymsCULZeQmkzsDFnCdV8=; b=UqbyUNDv6EyRr5n5mwVZwjKcyfzf1pakfWmjH05fc1OMpfUqquvNeaCK205wIt89l+ RHlasgF9u1sn0eICXsmNtk2agQllv8A9+iq3xaM+njWale4cg70+kk7qw8155buXRcj3 hdmfOo5iE30awvfF8tjgGwYOy14j6BYw8C9sYCSxi527gm7SIkKMYhlFKLv+ZdhNtt4/ q9R0FoKeZ992tP4nFZuC5UtwBWXJFJImzQmxS9Ln0w7TOrzPPsnaeUXyEySR4Xxjxik3 jJorjYMP8vfKNkvdzlQCjdKJeA4Dw7S3oEp90JKcJ7HT7OfVBCAnjQA9TVZUEKqsLaWs 3akA== X-Forwarded-Encrypted: i=1; AJvYcCWwgEPKY2g+ZFcVC6oeNn3fCKkP3mrKZW55gO3psZLC973YnjKh92HF0HuEjkM0qySSrXcRiGF5nhYA+iBERhw=@vger.kernel.org, AJvYcCXH/lYqXrNRyHpCwonxPA/B4rC25rIsDTQ4kv/QU3Fe23wlTS8fUr0fSgJZqlojQylWzronZx2aBrCT@vger.kernel.org X-Gm-Message-State: AOJu0YyIGG2elB+YwARLCbX2qAYbx2o8ufkbMGaat5L0pBr7wJ4Bjso8 AUadPJ/Vcq9CyYDaF65ugTycflRj1TW8YWCtSdvtjgQP8CBLX83bgPtm X-Gm-Gg: ASbGncu6orcEg8FByVdSx+OJsetjqe/OOYoVcrFTFbEdjXI2BSwdnnmteu8gX466NtM lK3ecm5cJoSUByXoYkKe7ShAjtUq4vpiW6Lk4faPi/zauWw1zvqvScsiiZubU9Dy+pHuJxm4DCz gcLG6vZ5m+7ds7gwI9gTrRI8Jq9qtUSivsIGFcMLtRy1brdXD7bd9cMCqVXzuDpwYBrNmlQJ1lo YDmUOfuWTJhGQif4ZA/sDtWqTyW8ndBsjoBCUPfoGap0rq6esRy1JJyxAoOm1WoEqxoJOZs1uRh tBUUPh2FTLIjLJWkMd/Ya11N1tkRtyfqTE9ESS9Cw9IXqWtVQcbEGAOr+p5fv/MnZeKOTGh15ur QJ9UMxkR+18N0GuR3GVkIoYuUA+CRH+GIGvbB9lSEtDg/6hKV7R8nKjkljMGrWd8= X-Google-Smtp-Source: AGHT+IFntFkNxx24CgiS118e5vZlr/FBZTsgX2Ln2DccFMO21mlALdHdkwVTMB4EKfRtDA/OFpbY0Q== X-Received: by 2002:a05:620a:3726:b0:7ca:cd71:2bf8 with SMTP id af79cd13be357-7d2299339d3mr2562207085a.54.1749509197486; Mon, 09 Jun 2025 15:46:37 -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-7d25a536b91sm597967385a.32.2025.06.09.15.46.36 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Jun 2025 15:46:36 -0700 (PDT) Received: from phl-compute-04.internal (phl-compute-04.phl.internal [10.202.2.44]) by mailfauth.phl.internal (Postfix) with ESMTP id E3EF91200043; Mon, 9 Jun 2025 18:46:35 -0400 (EDT) Received: from phl-mailfrontend-01 ([10.202.2.162]) by phl-compute-04.internal (MEProxy); Mon, 09 Jun 2025 18:46:35 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:35 -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" Subject: [PATCH v4 03/10] rust: sync: atomic: Add ordering annotation types Date: Mon, 9 Jun 2025 15:46:08 -0700 Message-Id: <20250609224615.27061-4-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" Preparation for atomic primitives. Instead of a suffix like _acquire, a method parameter along with the corresponding generic parameter will be used to specify the ordering of an atomic operations. For example, atomic load() can be defined as: impl Atomic { pub fn load(&self, _o: O) -> T { ... } } and acquire users would do: let r =3D x.load(Acquire); relaxed users: let r =3D x.load(Relaxed); doing the following: let r =3D x.load(Release); will cause a compiler error. Compared to suffixes, it's easier to tell what ordering variants an operation has, and it also make it easier to unify the implementation of all ordering variants in one method via generic. The `IS_RELAXED` and `ORDER` associate consts are for generic function to pick up the particular implementation specified by an ordering annotation. Signed-off-by: Boqun Feng --- rust/kernel/sync/atomic.rs | 3 + rust/kernel/sync/atomic/ordering.rs | 94 +++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 rust/kernel/sync/atomic/ordering.rs diff --git a/rust/kernel/sync/atomic.rs b/rust/kernel/sync/atomic.rs index 65e41dba97b7..9fe5d81fc2a9 100644 --- a/rust/kernel/sync/atomic.rs +++ b/rust/kernel/sync/atomic.rs @@ -17,3 +17,6 @@ //! [`LKMM`]: srctree/tools/memory-mode/ =20 pub mod ops; +pub mod ordering; + +pub use ordering::{Acquire, Full, Relaxed, Release}; diff --git a/rust/kernel/sync/atomic/ordering.rs b/rust/kernel/sync/atomic/= ordering.rs new file mode 100644 index 000000000000..14cda8c5d1b1 --- /dev/null +++ b/rust/kernel/sync/atomic/ordering.rs @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Memory orderings. +//! +//! The semantics of these orderings follows the [`LKMM`] definitions and = rules. +//! +//! - [`Acquire`] and [`Release`] are similar to their counterpart in Rust= memory model. +//! - [`Full`] means "fully-ordered", that is: +//! - It provides ordering between all the preceding memory accesses and= the annotated operation. +//! - It provides ordering between the annotated operation and all the f= ollowing memory accesses. +//! - It provides ordering between all the preceding memory accesses and= all the fllowing memory +//! accesses. +//! - All the orderings are the same strong as a full memory barrier (i.= e. `smp_mb()`). +//! - [`Relaxed`] is similar to the counterpart in Rust memory model, exce= pt that dependency +//! orderings are also honored in [`LKMM`]. Dependency orderings are des= cribed in "DEPENDENCY +//! RELATIONS" in [`LKMM`]'s [`explanation`]. +//! +//! [`LKMM`]: srctree/tools/memory-model/ +//! [`explanation`]: srctree/tools/memory-model/Documentation/explanation.= txt + +/// The annotation type for relaxed memory ordering. +pub struct Relaxed; + +/// The annotation type for acquire memory ordering. +pub struct Acquire; + +/// The annotation type for release memory ordering. +pub struct Release; + +/// The annotation type for fully-order memory ordering. +pub struct Full; + +/// The trait bound for operations that only support relaxed ordering. +pub trait RelaxedOnly: AcquireOrRelaxed + ReleaseOrRelaxed + All {} + +impl RelaxedOnly for Relaxed {} + +/// The trait bound for operations that only support acquire or relaxed or= dering. +pub trait AcquireOrRelaxed: All { + /// Describes whether an ordering is relaxed or not. + const IS_RELAXED: bool =3D false; +} + +impl AcquireOrRelaxed for Acquire {} + +impl AcquireOrRelaxed for Relaxed { + const IS_RELAXED: bool =3D true; +} + +/// The trait bound for operations that only support release or relaxed or= dering. +pub trait ReleaseOrRelaxed: All { + /// Describes whether an ordering is relaxed or not. + const IS_RELAXED: bool =3D false; +} + +impl ReleaseOrRelaxed for Release {} + +impl ReleaseOrRelaxed for Relaxed { + const IS_RELAXED: bool =3D true; +} + +/// Describes the exact memory ordering of an `impl` [`All`]. +pub enum OrderingDesc { + /// Relaxed ordering. + Relaxed, + /// Acquire ordering. + Acquire, + /// Release ordering. + Release, + /// Fully-ordered. + Full, +} + +/// The trait bound for annotating operations that should support all orde= rings. +pub trait All { + /// Describes the exact memory ordering. + const ORDER: OrderingDesc; +} + +impl All for Relaxed { + const ORDER: OrderingDesc =3D OrderingDesc::Relaxed; +} + +impl All for Acquire { + const ORDER: OrderingDesc =3D OrderingDesc::Acquire; +} + +impl All for Release { + const ORDER: OrderingDesc =3D OrderingDesc::Release; +} + +impl All for Full { + const ORDER: OrderingDesc =3D OrderingDesc::Full; +} --=20 2.39.5 (Apple Git-154) From nobody Sun Feb 8 01:44:08 2026 Received: from mail-qv1-f42.google.com (mail-qv1-f42.google.com [209.85.219.42]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A20DB226CFE; Mon, 9 Jun 2025 22:46:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.42 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509201; cv=none; b=FbD4C07nn2x3IvB5GBGQJL6V/zx+1P2J6h568KWxx7JL+PQxq0q4mE4gXWDB0ktlw5HnbH1QOJhmb5JftXb1d+yv9OZycMQsMNm5lzmmyNpB3w855rkoV6Cj5A3NLqdxthW9qvVcPSmQxuKhsxzvcTSqNEJgRqBlftaStwgfRqA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509201; c=relaxed/simple; bh=1Kqi2YDsf3sM7uhM+P4TroSNnv4xFt1rwiunRKerjdw=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=JDNzVAO6AJ0mIVvy0TwYEUsMFJ+lTqypzVdW9UCUsTLy487mjzqRMYTLu4Yzc4upESwrRC4gpfD1UwjtAnu93l20gv0EL24asvX7kwwfXluABIDrI6rOWS++tWvA02uyTT5qhoEX7RH0JbRQzHP1Z7PkZixGnTE/SghbdZxuZRs= 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=YtOKIija; arc=none smtp.client-ip=209.85.219.42 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="YtOKIija" Received: by mail-qv1-f42.google.com with SMTP id 6a1803df08f44-6f0ad744811so33801296d6.1; Mon, 09 Jun 2025 15:46:39 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1749509198; x=1750113998; darn=vger.kernel.org; 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=wbnaYQheKaUQhhvZ2OiIVS2CsqlLbAVGNW2lrhmtrNI=; b=YtOKIijaxRCuC5JdWmj/iI8t5TK+WC4vhD0reikrnu6G3ZqbEc6uQ3tsmtYiubfNdt WLRXS+KM3H0keilVxCrq4qSHnJeKmWUXYtVhDYFSLle0osmM59tXHhUDMEbav4ruIj9y Ka8SZ1PIMfPPvN+6AW08MkxjiuRm8zfMC8hlRpDp09pgibBJ3bx2pqMhFOB9eHLVOW76 xUqtRlScCLnjl0/Lwzck8zR4sdbdM3/5H18K0mnt6YE9F7d5B64FgA3JIN2JZK6pnRQm QAS7zhbp66BFuvUBMBhtkrIg4IT+4mYfoKj2JOxf0wGbXQmq6Y6nG+UMptWOgQLMZnLf J8Mw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1749509198; x=1750113998; 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=wbnaYQheKaUQhhvZ2OiIVS2CsqlLbAVGNW2lrhmtrNI=; b=m4r1h9qH2rjVZ7UhTRQ2bkJhiexr4rWDOVcqSPLYbvphHCgX8WCCaJq9aShIlF06rm p814/rUh7H9MewtJ2sq6TvD1sRBgz2qS+SDadPpULrJ6vkYsUQBhM2JxqxadoG0X0zxg VvBmRgKFiPEx7FUTzhPkdNBq+LBpyC/M+VUD3IOpCS4iLKBkILJB8jEMiQH21FoK8EIR oHLwneYgNh2adnJGCL9IN20kCBIDo/LKH1d0jOaCTWxpvKwE/Nssox+DJlK8HUptFVP6 0ftgHEyyxBpMFzvNLBgc83vpOuHtCq06jkZV0xBjZvPkJgLPdk1Gmvjk2liEt2qGQiJn tskw== X-Forwarded-Encrypted: i=1; AJvYcCWFUcmqXpjZMCaCziC1qLZdX0Ub5w252ITjkydw9c2I3eClIYvj15trVwgrYkqGbDh3J4/PqS02dd9c@vger.kernel.org, AJvYcCX2zJM888BUFoDL3eO4lDdAwo8WfUpWBkW6Qn3M6jx9xDp7bCoBNMB8mUC0q7kB+y8mXJESnbbBETTYW1bu7Js=@vger.kernel.org X-Gm-Message-State: AOJu0YyzOLzr/d5qRKzlJHKPuQkr96MAwPOKK4Se3uQeptHHIrYLpDD2 WS5I15pDFbJqNNBRNes+Q3XovoKlJHPvY928WDA5qAvyTBDPfCr76iKW X-Gm-Gg: ASbGncuk/cXW+v90Un/2mx8zPhVtr6aBM+cv3YlMcpjhWQmLSonDr3U1+AHGBxxIoZn ax0CcHlmtWiFqvN/9rKONbM54xEqUpFcwFOaYS19lOPqd+VPVSZqnxakUK87DswXL84YiQiFPtL u/xsXyoJKuFFmo/qdrZP0fXVkA6fh5ea4ClaloWirJVq8owfegZBFKNY+/FZo6+G/293xG9wBOt FKeWrUwyJxEuRdCXSFXbIZTDk5cpFgcjAJCzDZoCc0hnigSBXo4lJ62TF4iPB+LLoW3yGx5Lzti 2u/zEkQpPU3+794uk4CAjGSYn36OvtUeuD85pwHdDTM4HmkA+TXmHKDCLoajvxgoQttmI5r+6ih FHoVSqzKiaoGgavTloNWvDoFPHaheR8F0dwLgZHRvg6yc3AufJvVbn0QJh9ph9+A= X-Google-Smtp-Source: AGHT+IFONR/ySZBK8HoSEotuOUekxGEATR6mmf+1fK7fYeiJWRLxagoM1Bk8TY20rviQW0g88oVS0w== X-Received: by 2002:a05:6214:1bc5:b0:6fa:c6ad:1618 with SMTP id 6a1803df08f44-6fb08f61cc0mr255054656d6.27.1749509198330; Mon, 09 Jun 2025 15:46:38 -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 6a1803df08f44-6fb09b1ce86sm57688286d6.61.2025.06.09.15.46.37 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Jun 2025 15:46:37 -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 3F6541200066; Mon, 9 Jun 2025 18:46:37 -0400 (EDT) Received: from phl-mailfrontend-01 ([10.202.2.162]) by phl-compute-08.internal (MEProxy); Mon, 09 Jun 2025 18:46:37 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:36 -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" Subject: [PATCH v4 04/10] rust: sync: atomic: Add generic atomics Date: Mon, 9 Jun 2025 15:46:09 -0700 Message-Id: <20250609224615.27061-5-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" To provide using LKMM atomics for Rust code, a generic `Atomic` is added, currently `T` needs to be Send + Copy because these are the straightforward usages and all basic types support this. The trait `AllowAtomic` should be only implemented inside atomic mod until the generic atomic framework is mature enough (unless the implementer is a `#[repr(transparent)]` new type). `AtomicImpl` types are automatically `AllowAtomic`, and so far only basic operations load() and store() are introduced. Signed-off-by: Boqun Feng --- rust/kernel/sync/atomic.rs | 2 + rust/kernel/sync/atomic/generic.rs | 258 +++++++++++++++++++++++++++++ 2 files changed, 260 insertions(+) create mode 100644 rust/kernel/sync/atomic/generic.rs diff --git a/rust/kernel/sync/atomic.rs b/rust/kernel/sync/atomic.rs index 9fe5d81fc2a9..a01e44eec380 100644 --- a/rust/kernel/sync/atomic.rs +++ b/rust/kernel/sync/atomic.rs @@ -16,7 +16,9 @@ //! //! [`LKMM`]: srctree/tools/memory-mode/ =20 +pub mod generic; pub mod ops; pub mod ordering; =20 +pub use generic::Atomic; pub use ordering::{Acquire, Full, Relaxed, Release}; diff --git a/rust/kernel/sync/atomic/generic.rs b/rust/kernel/sync/atomic/g= eneric.rs new file mode 100644 index 000000000000..73c26f9cf6b8 --- /dev/null +++ b/rust/kernel/sync/atomic/generic.rs @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Generic atomic primitives. + +use super::ops::*; +use super::ordering::*; +use crate::types::Opaque; + +/// A generic atomic variable. +/// +/// `T` must impl [`AllowAtomic`], that is, an [`AtomicImpl`] has to be ch= osen. +/// +/// # Invariants +/// +/// Doing an atomic operation while holding a reference of [`Self`] won't = cause a data race, this +/// is guaranteed by the safety requirement of [`Self::from_ptr`] and the = extra safety requirement +/// of the usage on pointers returned by [`Self::as_ptr`]. +#[repr(transparent)] +pub struct Atomic(Opaque); + +// SAFETY: `Atomic` is safe to share among execution contexts because a= ll accesses are atomic. +unsafe impl Sync for Atomic {} + +/// Atomics that support basic atomic operations. +/// +/// TODO: Currently the [`AllowAtomic`] types are restricted within basic = integer types (and their +/// transparent new types). In the future, we could extend the scope to mo= re data types when there +/// is a clear and meaningful usage, but for now, [`AllowAtomic`] should o= nly be implemented inside +/// atomic mod for the restricted types mentioned above. +/// +/// # Safety +/// +/// [`Self`] must have the same size and alignment as [`Self::Repr`]. +pub unsafe trait AllowAtomic: Sized + Send + Copy { + /// The backing atomic implementation type. + type Repr: AtomicImpl; + + /// Converts into a [`Self::Repr`]. + fn into_repr(self) -> Self::Repr; + + /// Converts from a [`Self::Repr`]. + fn from_repr(repr: Self::Repr) -> Self; +} + +// An `AtomicImpl` is automatically an `AllowAtomic`. +// +// SAFETY: `T::Repr` is `Self` (i.e. `T`), so they have the same size and = alignment. +unsafe impl AllowAtomic for T { + type Repr =3D Self; + + fn into_repr(self) -> Self::Repr { + self + } + + fn from_repr(repr: Self::Repr) -> Self { + repr + } +} + +impl Atomic { + /// Creates a new atomic. + pub const fn new(v: T) -> Self { + Self(Opaque::new(v)) + } + + /// Creates a reference to [`Self`] from a pointer. + /// + /// # Safety + /// + /// - `ptr` has to be a valid pointer. + /// - `ptr` has to be valid for both reads and writes for the whole li= fetime `'a`. + /// - For the whole lifetime of '`a`, other accesses to the object can= not cause data races + /// (defined by [`LKMM`]) against atomic operations on the returned = reference. + /// + /// [`LKMM`]: srctree/tools/memory-model + /// + /// # Examples + /// + /// Using [`Atomic::from_ptr()`] combined with [`Atomic::load()`] or [= `Atomic::store()`] can + /// achieve the same functionality as `READ_ONCE()`/`smp_load_acquire(= )` or + /// `WRITE_ONCE()`/`smp_store_release()` in C side: + /// + /// ```rust + /// # use kernel::types::Opaque; + /// use kernel::sync::atomic::{Atomic, Relaxed, Release}; + /// + /// // Assume there is a C struct `Foo`. + /// mod cbindings { + /// #[repr(C)] + /// pub(crate) struct foo { pub(crate) a: i32, pub(crate) b: i32 } + /// } + /// + /// let tmp =3D Opaque::new(cbindings::foo { a: 1, b: 2}); + /// + /// // struct foo *foo_ptr =3D ..; + /// let foo_ptr =3D tmp.get(); + /// + /// // SAFETY: `foo_ptr` is a valid pointer, and `.a` is inbound. + /// let foo_a_ptr =3D unsafe { core::ptr::addr_of_mut!((*foo_ptr).a) }; + /// + /// // a =3D READ_ONCE(foo_ptr->a); + /// // + /// // SAFETY: `foo_a_ptr` is a valid pointer for read, and all access= es on it is atomic, so no + /// // data race. + /// let a =3D unsafe { Atomic::from_ptr(foo_a_ptr) }.load(Relaxed); + /// # assert_eq!(a, 1); + /// + /// // smp_store_release(&foo_ptr->a, 2); + /// // + /// // SAFETY: `foo_a_ptr` is a valid pointer for write, and all acces= ses on it is atomic, so no + /// // data race. + /// unsafe { Atomic::from_ptr(foo_a_ptr) }.store(2, Release); + /// ``` + /// + /// However, this should be only used when communicating with C side o= r manipulating a C struct. + pub unsafe fn from_ptr<'a>(ptr: *mut T) -> &'a Self + where + T: Sync, + { + // CAST: `T` is transparent to `Atomic`. + // SAFETY: Per function safety requirement, `ptr` is a valid point= er and the object will + // live long enough. It's safe to return a `&Atomic` because fu= nction safety requirement + // guarantees other accesses won't cause data races. + unsafe { &*ptr.cast::() } + } + + /// Returns a pointer to the underlying atomic variable. + /// + /// Extra safety requirement on using the return pointer: the operatio= ns done via the pointer + /// cannot cause data races defined by [`LKMM`]. + /// + /// [`LKMM`]: srctree/tools/memory-model + pub const fn as_ptr(&self) -> *mut T { + self.0.get() + } + + /// Returns a mutable reference to the underlying atomic variable. + /// + /// This is safe because the mutable reference of the atomic variable = guarantees the exclusive + /// access. + pub fn get_mut(&mut self) -> &mut T { + // SAFETY: `self.as_ptr()` is a valid pointer to `T`, and the obje= ct has already been + // initialized. `&mut self` guarantees the exclusive access, so it= 's safe to reborrow + // mutably. + unsafe { &mut *self.as_ptr() } + } +} + +impl Atomic +where + T::Repr: AtomicHasBasicOps, +{ + /// Loads the value from the atomic variable. + /// + /// # Examples + /// + /// Simple usages: + /// + /// ```rust + /// use kernel::sync::atomic::{Atomic, Relaxed}; + /// + /// let x =3D Atomic::new(42i32); + /// + /// assert_eq!(42, x.load(Relaxed)); + /// + /// let x =3D Atomic::new(42i64); + /// + /// assert_eq!(42, x.load(Relaxed)); + /// ``` + /// + /// Customized new types in [`Atomic`]: + /// + /// ```rust + /// use kernel::sync::atomic::{generic::AllowAtomic, Atomic, Relaxed}; + /// + /// #[derive(Clone, Copy)] + /// #[repr(transparent)] + /// struct NewType(u32); + /// + /// // SAFETY: `NewType` is transparent to `u32`, which has the same s= ize and alignment as + /// // `i32`. + /// unsafe impl AllowAtomic for NewType { + /// type Repr =3D i32; + /// + /// fn into_repr(self) -> Self::Repr { + /// self.0 as i32 + /// } + /// + /// fn from_repr(repr: Self::Repr) -> Self { + /// NewType(repr as u32) + /// } + /// } + /// + /// let n =3D Atomic::new(NewType(0)); + /// + /// assert_eq!(0, n.load(Relaxed).0); + /// ``` + #[doc(alias("atomic_read", "atomic64_read"))] + #[inline(always)] + pub fn load(&self, _: Ordering) -> T { + let a =3D self.as_ptr().cast::(); + + // SAFETY: + // - For calling the atomic_read*() function: + // - `self.as_ptr()` is a valid pointer, and per the safety requ= irement of `AllocAtomic`, + // a `*mut T` is a valid `*mut T::Repr`. Therefore `a` is a v= alid pointer, + // - per the type invariants, 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. + let v =3D unsafe { + if Ordering::IS_RELAXED { + T::Repr::atomic_read(a) + } else { + T::Repr::atomic_read_acquire(a) + } + }; + + T::from_repr(v) + } + + /// Stores a value to the atomic variable. + /// + /// # Examples + /// + /// ```rust + /// use kernel::sync::atomic::{Atomic, Relaxed}; + /// + /// let x =3D Atomic::new(42i32); + /// + /// assert_eq!(42, x.load(Relaxed)); + /// + /// x.store(43, Relaxed); + /// + /// assert_eq!(43, x.load(Relaxed)); + /// ``` + /// + #[doc(alias("atomic_set", "atomic64_set"))] + #[inline(always)] + pub fn store(&self, v: T, _: Ordering) { + let v =3D T::into_repr(v); + let a =3D self.as_ptr().cast::(); + + // SAFETY: + // - For calling the atomic_set*() function: + // - `self.as_ptr()` is a valid pointer, and per the safety requ= irement of `AllocAtomic`, + // a `*mut T` is a valid `*mut T::Repr`. Therefore `a` is a v= alid pointer, + // - per the type invariants, 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. + unsafe { + if Ordering::IS_RELAXED { + T::Repr::atomic_set(a, v) + } else { + T::Repr::atomic_set_release(a, v) + } + }; + } +} --=20 2.39.5 (Apple Git-154) From nobody Sun Feb 8 01:44:08 2026 Received: from mail-qv1-f42.google.com (mail-qv1-f42.google.com [209.85.219.42]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D9ABE227BAD; Mon, 9 Jun 2025 22:46:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.42 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509203; cv=none; b=EsejOGySZaSPyF3ecian9G2omOEVnpyjZkSyaW8jTBzyXxi2LGMjishQeP43I3NBAdtQ+ssMDQbko6ehMz5fdwYcDw7rg4r5pOvc3/N0U9p86s1CiLbMGHbK+gg99fsL1vbISm1QNysqHf581emi2Pk55VJfbVAvFxN753cq6s4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509203; c=relaxed/simple; bh=C9Im3rurc6OjYvlbCyDvwT/Ur5KVIFPvRRV4pmzupDY=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=WtVnAf165BMjkO3QvfzsV0BaqTxtq+uvU7XeX689vap+6em42WcRVsm/766x/JIJcAeZaklgBYembtZjqPKMcBf337Y5nRa6lQbsg6zaY5XCwx40/zOtvG0DlamOLy/meSKACUWpYBCv5xhfhCy0Nb16ZVt1AMbdDAyjS0BGbCU= 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=iX22C2rE; arc=none smtp.client-ip=209.85.219.42 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="iX22C2rE" Received: by mail-qv1-f42.google.com with SMTP id 6a1803df08f44-6fb0eb0f0fbso34514396d6.1; Mon, 09 Jun 2025 15:46:40 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1749509200; x=1750114000; darn=vger.kernel.org; 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=IObR9F++JkDqWSsb6EV+eGSQG5TSZzqg4I7RnfQH8w0=; b=iX22C2rE1GHfdmlPD6F1o55lVA42vh2/9IBtwGMwjWna226eKVJv3VM7bOvSffboav vPvOpx1fh8ZJCi6keZ2ORJHkeU3yzlBVNKMRIWKPnlugFsEpizCf8Z0eQJqjJUP9ZPz+ LAL12H0fVhcQy3fPo2dNCVrd/HqPDnwh8NFDCI/+u9bLyMHUlt6aOQNU+b0y1VtaiP1W kdwxSmcb7oELIzy9MaYmdwC/IRjMEQMdZlxRfgdMtNoVsKIgz0e0pg1qLOt6N2Bb6IjM PA+g5+B9hplBX6avgA0BCdgvcFJO9UnKXyfzePn4NprPZu+OK1y7vdswKo04MTKpK5Dd cy1g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1749509200; x=1750114000; 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=IObR9F++JkDqWSsb6EV+eGSQG5TSZzqg4I7RnfQH8w0=; b=Uf18T9GfJGujwDm0oFsxGsTw1/0mnrE8f58Oz5SKTs2ol9YEF7hZUJIPBRxRBsLbj4 OzzhdQ0WGuA7irbIA/V1XHQSxBPF7icAGvjRkiz1JOE0Kx246/NsuvibqS119G0/sXFQ CwlQcUhCmCzhd/SWBXLzT02PSB/+J8QDm/JXERF99o7Gli+8MGEnpgM1bNik8PQeqOFX WnHzFYS8wDKsYab7ZHM9UiY01HmNsSnajUg2u2zmyeaIMJrMVqe/RkPTdz9m9cKigVE+ xrMFxCBkNee1FgMx5BfrpSBaiZcW9GbxeeuFSl6TXQXhTJbkqvCst2KlvYOB5PW909Rn +Q2Q== X-Forwarded-Encrypted: i=1; AJvYcCU6aatDSTbhkWZuIUiKPiDnJGOZKGxueJnNy6kPVMux55OG+0rhkn+d9ru1tB/4S8PGFVFNn16a0V1vaHtDLqg=@vger.kernel.org, AJvYcCWp9xVkzvZQnuTOdebvkIYibU9oQ/O+QJd9KMp/eF6o3Ou++4HLB/UPTRySX0W4bVRZ7evS3z76/YzP@vger.kernel.org X-Gm-Message-State: AOJu0Yy2nWzFD1yi8qXbdlAMu3khtUO8BXqwSbFu4YZ4KWdCMs3Xrzyq XVb/h7wj1GKnPCFowIsPi+dEeBfxrg+A2kgUPhJnXnU7G4xpOZwBs4DU X-Gm-Gg: ASbGnctzMkj8X8paOjGUnOC9FUtnrnvqpCGYM88/k6N+nIoNTOyUmXz5jhyI/I6t2wH gea5iemNDsRlxhf7wr40sDEp/Fb/fp9bu1dj+6NKS0s/4tRqm5dEZgwqWpuSd8cNzKw7DQDbQLC u18KztbTHk4bZLakBszmusJkXkD96qbaZpsXJacDCU+AIxClRRRCS9j4QofTYiiWrX5pQZENFqf LcRIR9daey23y3UOVDgbhM/eIIjG7rAHDeHol5Uen0gU0jDRnuY39TrFa8YB1vFXupnhLm5I+Y/ BoKA8hnRk1r9Loj0+XCyFCoUNCj2jYvGTiWWWOb90VfOG0WDo/lYLeTNOZsTr72Hxno+HiEe17O ihYuv3TLTRHY8OOAFUiB4VN/kAKpEW3v/J/SfWbHFi5VGjwumT8ld X-Google-Smtp-Source: AGHT+IFMe2T3d3AQDY8nv3ixHYzt2jrNEFp9cLzUunVNKoutc8cZR5sOsy2x0vOgxNB03WtcFwvEiw== X-Received: by 2002:a05:6214:e88:b0:6fa:a5c9:2ee7 with SMTP id 6a1803df08f44-6fb238f98ddmr20547046d6.8.1749509199574; Mon, 09 Jun 2025 15:46:39 -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 6a1803df08f44-6fb09ab94bfsm57591876d6.18.2025.06.09.15.46.38 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Jun 2025 15:46:39 -0700 (PDT) Received: from phl-compute-01.internal (phl-compute-01.phl.internal [10.202.2.41]) by mailfauth.phl.internal (Postfix) with ESMTP id 87AB71200043; Mon, 9 Jun 2025 18:46:38 -0400 (EDT) Received: from phl-mailfrontend-01 ([10.202.2.162]) by phl-compute-01.internal (MEProxy); Mon, 09 Jun 2025 18:46:38 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:37 -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" Subject: [PATCH v4 05/10] rust: sync: atomic: Add atomic {cmp,}xchg operations Date: Mon, 9 Jun 2025 15:46:10 -0700 Message-Id: <20250609224615.27061-6-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" 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. Signed-off-by: Boqun Feng --- rust/kernel/sync/atomic/generic.rs | 154 +++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/rust/kernel/sync/atomic/generic.rs b/rust/kernel/sync/atomic/g= eneric.rs index 73c26f9cf6b8..39a9e208e767 100644 --- a/rust/kernel/sync/atomic/generic.rs +++ b/rust/kernel/sync/atomic/generic.rs @@ -256,3 +256,157 @@ 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 =3D Atomic::new(42); + /// + /// assert_eq!(42, x.xchg(52, Acquire)); + /// assert_eq!(52, x.load(Relaxed)); + /// ``` + #[doc(alias("atomic_xchg", "atomic64_xchg"))] + #[inline(always)] + pub fn xchg(&self, v: T, _: Ordering) -> T { + let v =3D T::into_repr(v); + let a =3D self.as_ptr().cast::(); + + // SAFETY: + // - For calling the atomic_xchg*() function: + // - `self.as_ptr()` is a valid pointer, and per the safety requ= irement of `AllocAtomic`, + // a `*mut T` is a valid `*mut T::Repr`. Therefore `a` is a v= alid pointer, + // - per the type invariants, 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. + let ret =3D unsafe { + match Ordering::ORDER { + OrderingDesc::Full =3D> T::Repr::atomic_xchg(a, v), + OrderingDesc::Acquire =3D> T::Repr::atomic_xchg_acquire(a,= v), + OrderingDesc::Release =3D> T::Repr::atomic_xchg_release(a,= v), + OrderingDesc::Relaxed =3D> T::Repr::atomic_xchg_relaxed(a,= v), + } + }; + + T::from_repr(ret) + } + + /// Atomic compare and exchange. + /// + /// Compare: The comparison is done via the byte level comparison betw= een the atomic variables + /// with the `old` value. + /// + /// Ordering: When succeeds, provides the corresponding ordering as th= e `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 at= omic variable when + /// cmpxchg was happening. + /// + /// # Examples + /// + /// ```rust + /// use kernel::sync::atomic::{Atomic, Full, Relaxed}; + /// + /// let x =3D Atomic::new(42); + /// + /// // Checks whether cmpxchg succeeded. + /// let success =3D x.cmpxchg(52, 64, Relaxed).is_ok(); + /// # assert!(!success); + /// + /// // Checks whether cmpxchg failed. + /// let failure =3D 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(_) =3D> { }, + /// Err(old) =3D> { + /// // do something with `old`. + /// # assert_eq!(old, 42); + /// } + /// } + /// + /// // Uses the latest value regardlessly, same as atomic_cmpxchg() in= C. + /// let latest =3D 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" + ))] + #[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 o= n x86, due to commit + // 44fe84459faf ("locking/atomic: Fix atomic_try_cmpxchg() semanti= cs"), the + // atomic_try_cmpxchg() on x86 has a branch even if the caller doe= sn't care about the + // success of cmpxchg and only wants to use the old value. For exa= mple, for code like: + // + // let latest =3D 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 succ= eeds. + /// + /// "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 old =3D (old as *mut T).cast::(); + let new =3D T::into_repr(new); + let a =3D self.0.get().cast::(); + + // SAFETY: + // - For calling the atomic_try_cmpchg*() function: + // - `self.as_ptr()` is a valid pointer, and per the safety requ= irement of `AllowAtomic`, + // a `*mut T` is a valid `*mut T::Repr`. Therefore `a` is a v= alid pointer, + // - per the type invariants, the following atomic operation won= 't cause data races. + // - `old` is a valid pointer to write because it comes from a m= utable reference. + // - For extra safety requirement of usage on pointers returned by= `self.as_ptr(): + // - atomic operations are used here. + unsafe { + match Ordering::ORDER { + OrderingDesc::Full =3D> T::Repr::atomic_try_cmpxchg(a, old= , new), + OrderingDesc::Acquire =3D> T::Repr::atomic_try_cmpxchg_acq= uire(a, old, new), + OrderingDesc::Release =3D> T::Repr::atomic_try_cmpxchg_rel= ease(a, old, new), + OrderingDesc::Relaxed =3D> T::Repr::atomic_try_cmpxchg_rel= axed(a, old, new), + } + } + } +} --=20 2.39.5 (Apple Git-154) From nobody Sun Feb 8 01:44:08 2026 Received: from mail-qv1-f50.google.com (mail-qv1-f50.google.com [209.85.219.50]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id BDE8D227EAA; Mon, 9 Jun 2025 22:46:41 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.50 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509204; cv=none; b=rX5X46kY61dpf51yDwG+SVpFZzTTCEhoqmXrpkNH8hWE0OQWhIUkP/Bb9+9RIefQPI6O9mARc6fhNanKnrYTbWJRQUFUeSq+YS7j226y0Wi0bUsyZYLd6Cm9zTF5tu2DtznbDqHqrpUi8TdQ3WoFgzW2gD8Goe3YprbAOxWyE7g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509204; c=relaxed/simple; bh=xsHACheX02cEYcLip88x4wtB948B0xWNzAMevS8qR2g=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=kHf6GSNoSSmN7JduCh7ajzCocVSH72YIC4/41HQZUYhr3E5hEWd2m6PxRm/FSvhSm+QVr3PjJVNiaE5T58z8qaAzgsSzeBrLmdu/2wKSseBCbV1rILwbFVXYI/VgPyYFdxUwjnFUn3mFBU9jzYCgAxQzCfpzjVfzIr1l9FZeFfY= 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=cFGxZXbX; arc=none smtp.client-ip=209.85.219.50 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="cFGxZXbX" Received: by mail-qv1-f50.google.com with SMTP id 6a1803df08f44-6fa980d05a8so47334456d6.2; Mon, 09 Jun 2025 15:46:41 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1749509201; x=1750114001; darn=vger.kernel.org; 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=AbuO++RMiLBujeQcBYpEohvl/WMGSiraH57rxKvmSTw=; b=cFGxZXbXfM2OwNny5upwP0G0g63zUnBSD2Vi48VTkw4qtEC5p/dGz5jau02S3JieZK WJJPuGj8zMsMXbh5lBNbjq8ofvu+WmffMRl9vPQUsTE/LYMtmDNpF9KLE9G8Lm0O8fWf LtskpVSq5avPe5tbiIMhf0KNzjbSOMGetBAO2eXPTaNT548bHSBogsM6RUQeLgA45ylf YY4zRLQStVh5zF8+WsIzmFv9RTMZbhFUzQihXnNfefNktCIyg5HzQ+jFbbYJzdx0IITx ewXhZC/NGzTB0auVChyWEQhvD7L6HVp2F8OnSvrQzmOKsrvChQj9mFsnzWkV5gZ9N594 ewEA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1749509201; x=1750114001; 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=AbuO++RMiLBujeQcBYpEohvl/WMGSiraH57rxKvmSTw=; b=LfwnFY9W3Lv5iTyV+kEpqbdzAxUR3x1onoX+HErQ3S5GMpByKZSEiSb+Db88gLYl/J lndavlZn60oRHIO2Z5mzzLggDN2ogWNlDO/39qV0ERmtaKYo7Drvuf1db7RmWgTD86iM TcwYAW0gDKn6DeqSD6DhvtZzUCeHDEo81YiH010lZavFkjeWtieJEFojjgg0S1KOMprz avkOa7sSifGea+XTtgzeQkx3D126sb13mvrrGCg7Rycf6egB6el8p9t+W2E95i61dkeb c8gAuv2NgYBsPung0SGaf6Jn/SCM9DrCOdpFRK7is+t+5rzmg8NUX+Wa69mSWOgPgbLX 6qiA== X-Forwarded-Encrypted: i=1; AJvYcCWtdPPOHKBVCr11ej18H1fVBb+Yo/9QAxw/w3GwZ/UD7pD6Zu5EZgeg2AKcfkkQm+gR8bqY0ZT7+0/n5ADSRoM=@vger.kernel.org, AJvYcCXXQ4OQ6y9AITWsHjhctzeCJDhbc/NhLZaYFX5fs4NUvySBsygKsCW4qBgLVxbJwjyRKrM5aiM8xr2Z@vger.kernel.org X-Gm-Message-State: AOJu0YzlbgQDRobvgIRufpbZ6zQG53UiZ+LvIJX60kNPXZwr65b729Tx n6Zr7nE7ShzaGAM3TElQKkWrBAUEt+yPhzikD2Te3Gw7PVf0JA7zE6vwaWTuPQ== X-Gm-Gg: ASbGncsA7gGRAtCVWalSWkJCU1Ztlqf+16xcc97+TgQLp67sOKbqFnw7yHjrLrbwIF8 pD27P4i8fqi3WEj1xSICZ3gNApIeuUnw8irM63L6eSIuKnm/Tq79Z4qnJIBXK+oVLTb3kv//65G gSK+N7ABiLAh0Sv6U900QkiXiUZLC8SAEt9vzXKgiq0cDRxjsz4ESwtysaD1l3oqWWwZACu0ZO2 hbAcrGEbrEmktLfhIcGONR0wT3SWvOwMEoNbYBUJjzwRVg+MZAoIAAQIHacQSkJ3/o8HvJzjJor /WRDn+P5kkRxEK4SKtB8dUmKY7LVA14yNa40NofXoILJO5X/b3Vr0J/rK5aNJyePqlUm3lNVpid AKzx/QvRUkvJWovr2vDbns8DWWJVAk74Zfkp1esNGLGtU2tpOcPDv X-Google-Smtp-Source: AGHT+IEDIGSzlCnVFl9GQWNMSfgr9LFPsOTm8gYIWNg0ODq/n1RXj0yeteLcHT3eW2v16F5a/3qa+w== X-Received: by 2002:a0c:f643:0:b0:6fb:f00:48a9 with SMTP id 6a1803df08f44-6fb0f004bdamr154394836d6.19.1749509200667; Mon, 09 Jun 2025 15:46:40 -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 6a1803df08f44-6fb09b3648dsm56955106d6.107.2025.06.09.15.46.39 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Jun 2025 15:46:40 -0700 (PDT) Received: from phl-compute-02.internal (phl-compute-02.phl.internal [10.202.2.42]) by mailfauth.phl.internal (Postfix) with ESMTP id C898F1200043; Mon, 9 Jun 2025 18:46:39 -0400 (EDT) Received: from phl-mailfrontend-01 ([10.202.2.162]) by phl-compute-02.internal (MEProxy); Mon, 09 Jun 2025 18:46:39 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:39 -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" Subject: [PATCH v4 06/10] rust: sync: atomic: Add the framework of arithmetic operations Date: Mon, 9 Jun 2025 15:46:11 -0700 Message-Id: <20250609224615.27061-7-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" One important set of atomic operations is the arithmetic operations, i.e. add(), sub(), fetch_add(), add_return(), etc. However it may not make senses for all the types that `AllowAtomic` to have arithmetic operations, for example a `Foo(u32)` may not have a reasonable add() or sub(), plus subword types (`u8` and `u16`) currently don't have atomic arithmetic operations even on C side and might not have them in the future in Rust (because they are usually suboptimal on a few architecures). Therefore add a subtrait of `AllowAtomic` describing which types have and can do atomic arithemtic operations. A few things about this `AllowAtomicArithmetic` trait: * It has an associate type `Delta` instead of using `AllowAllowAtomic::Repr` because, a `Bar(u32)` (whose `Repr` is `i32`) may not wants an `add(&self, i32)`, but an `add(&self, u32)`. * `AtomicImpl` types already implement an `AtomicHasArithmeticOps` trait, so add blanket implementation for them. In the future, `i8` and `i16` may impl `AtomicImpl` but not `AtomicHasArithmeticOps` if arithemtic operations are not available. Only add() and fetch_add() are added. The rest will be added in the future. Signed-off-by: Boqun Feng --- rust/kernel/sync/atomic/generic.rs | 102 +++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/rust/kernel/sync/atomic/generic.rs b/rust/kernel/sync/atomic/g= eneric.rs index 39a9e208e767..f0bc831e8079 100644 --- a/rust/kernel/sync/atomic/generic.rs +++ b/rust/kernel/sync/atomic/generic.rs @@ -3,6 +3,7 @@ //! Generic atomic primitives. =20 use super::ops::*; +use super::ordering; use super::ordering::*; use crate::types::Opaque; =20 @@ -57,6 +58,23 @@ fn from_repr(repr: Self::Repr) -> Self { } } =20 +/// Atomics that allows arithmetic operations with an integer type. +pub trait AllowAtomicArithmetic: AllowAtomic { + /// The delta types for arithmetic operations. + type Delta; + + /// Converts [`Self::Delta`] into the representation of the atomic typ= e. + fn delta_into_repr(d: Self::Delta) -> Self::Repr; +} + +impl AllowAtomicArithmetic for T { + type Delta =3D Self; + + fn delta_into_repr(d: Self::Delta) -> Self::Repr { + d + } +} + impl Atomic { /// Creates a new atomic. pub const fn new(v: T) -> Self { @@ -410,3 +428,87 @@ fn try_cmpxchg(&self, old: &mut T, new:= T, _: Ordering) -> bool { } } } + +impl Atomic +where + T::Repr: AtomicHasArithmeticOps, +{ + /// Atomic add. + /// + /// The addition is a wrapping addition. + /// + /// # Examples + /// + /// ```rust + /// use kernel::sync::atomic::{Atomic, Relaxed}; + /// + /// let x =3D Atomic::new(42); + /// + /// assert_eq!(42, x.load(Relaxed)); + /// + /// x.add(12, Relaxed); + /// + /// assert_eq!(54, x.load(Relaxed)); + /// ``` + #[inline(always)] + pub fn add(&self, v: T::Delta, _: Ordering) { + let v =3D T::delta_into_repr(v); + let a =3D self.as_ptr().cast::(); + + // SAFETY: + // - For calling the atomic_add() function: + // - `self.as_ptr()` is a valid pointer, and per the safety requ= irement of `AllocAtomic`, + // a `*mut T` is a valid `*mut T::Repr`. Therefore `a` is a v= alid pointer, + // - per the type invariants, 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. + unsafe { + T::Repr::atomic_add(a, v); + } + } + + /// Atomic fetch and add. + /// + /// The addition is a wrapping addition. + /// + /// # Examples + /// + /// ```rust + /// use kernel::sync::atomic::{Atomic, Acquire, Full, Relaxed}; + /// + /// let x =3D Atomic::new(42); + /// + /// assert_eq!(42, x.load(Relaxed)); + /// + /// assert_eq!(54, { x.fetch_add(12, Acquire); x.load(Relaxed) }); + /// + /// let x =3D Atomic::new(42); + /// + /// assert_eq!(42, x.load(Relaxed)); + /// + /// assert_eq!(54, { x.fetch_add(12, Full); x.load(Relaxed) } ); + /// ``` + #[inline(always)] + pub fn fetch_add(&self, v: T::Delta, _: Ordering) -> T { + let v =3D T::delta_into_repr(v); + let a =3D self.as_ptr().cast::(); + + // SAFETY: + // - For calling the atomic_fetch_add*() function: + // - `self.as_ptr()` is a valid pointer, and per the safety requ= irement of `AllocAtomic`, + // a `*mut T` is a valid `*mut T::Repr`. Therefore `a` is a v= alid pointer, + // - per the type invariants, 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. + let ret =3D unsafe { + match Ordering::ORDER { + ordering::OrderingDesc::Full =3D> T::Repr::atomic_fetch_ad= d(a, v), + ordering::OrderingDesc::Acquire =3D> T::Repr::atomic_fetch= _add_acquire(a, v), + ordering::OrderingDesc::Release =3D> T::Repr::atomic_fetch= _add_release(a, v), + ordering::OrderingDesc::Relaxed =3D> T::Repr::atomic_fetch= _add_relaxed(a, v), + } + }; + + T::from_repr(ret) + } +} --=20 2.39.5 (Apple Git-154) From nobody Sun Feb 8 01:44:08 2026 Received: from mail-qk1-f172.google.com (mail-qk1-f172.google.com [209.85.222.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 588F3227BA5; Mon, 9 Jun 2025 22:46:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.222.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509205; cv=none; b=T9h2xzfBPe1B6e9CLtMR/hNS+1yDr9dwI8NRbOiyIOj9dMaYIXK/wF7FbBS1uUQYXCcbwO5aM/6Foqw46b968IsEIBXEcmQC9YVImU7NbX+/koINozFCveMDNb9Yc53M+9cYmgAj5HfWeYatkrMZZCU+zRVQEXuyZuKFcHueBNc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509205; c=relaxed/simple; bh=3t90svxWEHL37ohE0fJHFmRBiBXjgm3lFXGoX5OddKc=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=srSiVJX09EzJbHbMZgSB64ZAU0s+pxqPLdlEm8Bc1NNbuBDaeyoVNQXJbDbPb8Lie17aI3AxW4cGP+IEmsXaWqBvW2Ua3bdZ30gAxTFXpIvT9FaUcJQYFTvCAUnAq+Wbx2+6q+4fCqwZ7sTY3/zhOOoiTSgSulWx4VoncQDwNow= 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=fF6BRhOc; arc=none smtp.client-ip=209.85.222.172 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="fF6BRhOc" Received: by mail-qk1-f172.google.com with SMTP id af79cd13be357-7d09f11657cso457383285a.0; Mon, 09 Jun 2025 15:46:43 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1749509202; x=1750114002; darn=vger.kernel.org; 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=Ykfv0JUDwfNHM9Hye+0iZ2AUZ2hpC7+5v9dE8kxQRZU=; b=fF6BRhOcC/eDx6KPpd7jMxDCCcrVboMTEO17iUgrOU3hiTxapAmBHgzkEFRMvOxQjd q2RNaxXDS9AxQQdUwUESzVu9LUXIUATBSgfWnO1qXaFKaJ49BQ8GfQ6UX3rmeZw+TyE3 H+cf92B51C5dtUCFfrldkzY5J9e5+ok6M/T+wxmmOZo11a2gg1vH1RXI1IT8t3NVEsrM Es44lL4UEQd8WdzlRRoruTFW1rnqHY/xzm8zO6mMexXMa/AF9M8S3Pah/aDNkIOrHcza jwGCVMlFZQ4F4Lw8VDDjArWZ76HcCVmdadfbsAmiZEpPeyyox6CsuKnZKoVFM02rnJvF c7ww== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1749509202; x=1750114002; 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=Ykfv0JUDwfNHM9Hye+0iZ2AUZ2hpC7+5v9dE8kxQRZU=; b=QUdu6VP6EiT/kgyPRneGQ84z6pA/XBvURHOaAWqkL22kuMshoaFiczTfSn5WzZpiSl c2Y9j6aAES8aA/ES/guOuvq5KdsGpNBBQ0LXBwrTtbsCODe+3yccY/puAOvxxxo4Uwxo aY60xeTZJDMHhIo1w+gE1L2zJR8Uq5KiJifKnCnpo7DLYaxYbiyxZRYtSH7UeB6U8Zs9 sZAfl2tzBdJbVZU1v8fb6UEwKcjf+/ADbr3OJTd9PG1hHyHZcTaK+ZrLbITqf//HIPK3 c+XIoctHCdXwbJ38HSyHNkFB/x17F9Wj1lxsVHJ/GkiIWVv6iHbZhNFrPK44W6q7X2oj Bozw== X-Forwarded-Encrypted: i=1; AJvYcCUUGiYs1+ihpwzESi+yio4lrWr7ICL4XJiuHBr/TtLNJtkGkA7o8Oty67Ah0G91dS1vfcOCYgJ9aJ2x1ndo1og=@vger.kernel.org, AJvYcCWjVHEjhoLQsaDY5V8WZRZm634RXrIciZmBVmEFWWEgDNV3fo/I5MWhUONJ43okwHIR3T+WEzmhgStU@vger.kernel.org X-Gm-Message-State: AOJu0YwYGiHXF2EKYd+a1vbKpBqYiIZT5EDg6fWXLwSgaEDMBA+aW+Iu vJPfhhA53CuHSbYIVO4qEVf55xvtmOwVIFx4VK0Nyl1w+S2bixi6Mxvz X-Gm-Gg: ASbGnctNbxQkW9CYS0GpAKoP6vc1fHorI0HWDYI9AKSj5Exqfzs3gLup60bz1OF5qRY FOJ9T9oHjL2RuKKgTUd7TD8H0jdrLAgXanK9G90/DSWQWj9uO4UwOl5Q944P6P9o03UAV3pyBT/ 2Gbl6Avj/U0FukCJsmnd9f/H3k+mS6foatk3lNtVub1n6TzochRFTOlH79eXTJM+qBmpcv6RI5M Prx4VGv4n3aBDv/mz7i1cY/E0otbbfPQvW5xq7ht63SyCK+mft9K8UwFE+gmASb4Tp+EOonVzEZ j36h1jUwhWd3w8JJTjBHgzYE2t3qPj31famG0/Ks3jvBRSM2MLsEvv+pSo91odpbPGbRVj2oNTJ nllL7wgjMmkD12iC6r3hSD1z9bSiWfME0lZaPajUhrtTGZuKINrbb X-Google-Smtp-Source: AGHT+IFUi/CH1qbuTMavhtVevTlVgWxfuQBtFoEfwJqR6HTbU+n+FxJv1MMM0BL61L4p6Kak/iTk1Q== X-Received: by 2002:a05:620a:29c9:b0:7c7:694e:1ba0 with SMTP id af79cd13be357-7d2298d6f08mr2328173785a.44.1749509202149; Mon, 09 Jun 2025 15:46:42 -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 6a1803df08f44-6fb09aba071sm57749346d6.24.2025.06.09.15.46.41 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Jun 2025 15:46:41 -0700 (PDT) Received: from phl-compute-09.internal (phl-compute-09.phl.internal [10.202.2.49]) by mailfauth.phl.internal (Postfix) with ESMTP id 459101200043; Mon, 9 Jun 2025 18:46:41 -0400 (EDT) Received: from phl-mailfrontend-01 ([10.202.2.162]) by phl-compute-09.internal (MEProxy); Mon, 09 Jun 2025 18:46:41 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:40 -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" Subject: [PATCH v4 07/10] rust: sync: atomic: Add Atomic Date: Mon, 9 Jun 2025 15:46:12 -0700 Message-Id: <20250609224615.27061-8-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" Add generic atomic support for basic unsigned types that have an `AtomicImpl` with the same size and alignment. Unit tests are added including Atomic and Atomic. Signed-off-by: Boqun Feng --- rust/kernel/sync/atomic.rs | 83 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/rust/kernel/sync/atomic.rs b/rust/kernel/sync/atomic.rs index a01e44eec380..9039591b4d46 100644 --- a/rust/kernel/sync/atomic.rs +++ b/rust/kernel/sync/atomic.rs @@ -22,3 +22,86 @@ =20 pub use generic::Atomic; pub use ordering::{Acquire, Full, Relaxed, Release}; + +// SAFETY: `u64` and `i64` has the same size and alignment. +unsafe impl generic::AllowAtomic for u64 { + type Repr =3D i64; + + fn into_repr(self) -> Self::Repr { + self as _ + } + + fn from_repr(repr: Self::Repr) -> Self { + repr as _ + } +} + +impl generic::AllowAtomicArithmetic for u64 { + type Delta =3D u64; + + fn delta_into_repr(d: Self::Delta) -> Self::Repr { + d as _ + } +} + +// SAFETY: `u32` and `i32` has the same size and alignment. +unsafe impl generic::AllowAtomic for u32 { + type Repr =3D i32; + + fn into_repr(self) -> Self::Repr { + self as _ + } + + fn from_repr(repr: Self::Repr) -> Self { + repr as _ + } +} + +impl generic::AllowAtomicArithmetic for u32 { + type Delta =3D u32; + + fn delta_into_repr(d: Self::Delta) -> Self::Repr { + d as _ + } +} + +use crate::macros::kunit_tests; + +#[kunit_tests(rust_atomics)] +mod tests { + use super::*; + + // Call $fn($val) with each $type of $val. + macro_rules! for_each_type { + ($val:literal in [$($type:ty),*] $fn:expr) =3D> { + $({ + let v: $type =3D $val; + + $fn(v); + })* + } + } + + #[test] + fn atomic_basic_tests() { + for_each_type!(42 in [i32, i64, u32, u64] |v| { + let x =3D Atomic::new(v); + + assert_eq!(v, x.load(Relaxed)); + }); + } + + #[test] + fn atomic_arithmetic_tests() { + for_each_type!(42 in [i32, i64, u32, u64] |v| { + let x =3D Atomic::new(v); + + assert_eq!(v, x.fetch_add(12, Full)); + assert_eq!(v + 12, x.load(Relaxed)); + + x.add(13, Relaxed); + + assert_eq!(v + 25, x.load(Relaxed)); + }); + } +} --=20 2.39.5 (Apple Git-154) From nobody Sun Feb 8 01:44:08 2026 Received: from mail-qt1-f182.google.com (mail-qt1-f182.google.com [209.85.160.182]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 02FAF22A810; Mon, 9 Jun 2025 22:46:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.182 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509206; cv=none; b=ou1sg2oeDBxqEDxhFxtRZyGZ+ZtPRmXUv+L0PK/paOwkiTCKWlz+FJ4wbWE0mo1ujMQ82rEh7XuIUTCWuUbOTJ5sLMl/VQUvkdpiMYx+1obHJDkVxEgoMwS+Kwmh+G/7qzNbUzilgl2O4hev3EaLkhyPfg4F8q1tt9TALDQDJuM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509206; c=relaxed/simple; bh=oFjgr6Gty0sYPZz6lkCRj5C7HTiuBJmRhc3BPpW6Gio=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=Yq6qEgYJbIdwMJdmaoCQfP0HxD1XS/kmupwnYw74lUy0bofunrOUSr7bMWATaLopyyJWV1nc8XV38LEHRyaDw8iS0YCzCfKerroVpQ2RVSEf6T0CpJv1HIOFR8Bw+P5avGvnNPfoJFBucXgchEgag6yS8GJWp8IyqKBTURulsMw= 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=ZXjKoL6s; arc=none smtp.client-ip=209.85.160.182 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="ZXjKoL6s" Received: by mail-qt1-f182.google.com with SMTP id d75a77b69052e-4a44b9b2af8so29842261cf.3; Mon, 09 Jun 2025 15:46:44 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1749509204; x=1750114004; darn=vger.kernel.org; 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=0VUmlWceKq0MhGDhxaelm4U0vrjMGoaihx4g6jot+hI=; b=ZXjKoL6sRWWnUrrTCbLJnw4mr4pQ/kpbMN7xV8ZABhz/DwG2E5vAqEWd16cXN9T72N ERxDFzeCFFN1gXs81NgU3fZggtdMqVzWUo0pmc1LU40lYAqowG7LFHTp90fsZVp2JYRB UAyWEOPv3ak+fGgPqN5FmUA3FHicfKtwaXUb90peJFoaYjiTL6vrvJ641LWyichjDFg0 oh5lXWKfqWLT20zL0BX+nlQdNIZu5dZSfUhSgK4oczAD0Z2vfWtZfclm4tA/RDk/E7Fo xz9i1Vcu2aMocpggW7JDbcyTLtFOUkGLEcFZtbizSlSgaH0j1vUf9arYMMNww691RE76 p1HQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1749509204; x=1750114004; 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=0VUmlWceKq0MhGDhxaelm4U0vrjMGoaihx4g6jot+hI=; b=TFtrmKRUwoMmfWHbYpEPcogUx4883B8Yw1K6lPF7CIrIPa/Z82BfzHUnhYZUryDkT8 x4uvzWNJRZIpfoxCZKWb6M980Hynh4UR9qQHB/ZFfEaWcUiA0uh5zihXogkPu++Xqp/d tdobyU554prvFATGNWxv4FPeI2rx8ZCakyTGwVK5kurAlTJsJrvUgMswvvJPY1KRbVeM 2dA2dQomriExotDaP4dQ3URFYUMpMQy7QarCA7gJ853yI+ABcpIt6kJyo2VFljmZ6Yiy qCAj+NF+p2qhwCaeQL3hMQQ6hNkUz059aTKJeIQStyWBION4SQrei74/U/TWr261DrJU rtww== X-Forwarded-Encrypted: i=1; AJvYcCVVCznnE2oeYl/bva5ogE3nlRNOpBExz6nUu234bq/jLlR3LdWHsFwmhbcGkws5IPpCLGZyFmmocE5CN/4fYvE=@vger.kernel.org, AJvYcCWqbfaG7zf0iLdGKysAzVFjzHVTDsbdaP4rom/0SxWxDc1ZCZrhU0SR/fyP1bDCdmawrPMurIXQaESS@vger.kernel.org X-Gm-Message-State: AOJu0YwY6RTG4FCNlNNUzOIVavyTl4jYYvAhtoYpYcGGE4xeQ/u69AAX yN20LT5Wk8GdGXHmdbzWECox6w+24adk1rS5vqQNOaZkG1r7ZE/tLrfP X-Gm-Gg: ASbGncvDMC/mks77sj2HR2yT9G84kJ39peWNZa2y8v6pbc1N9b7gDyoQ9kbuMG8CZJx mcoB23ycjj8d2qMhhfgqiyCrXDlGaNaTr9a0+1DUiKPZQ/DgbzwybXuBsOwfVagmla6aI2Lv9fJ JYdmqT+I94sBEiZGEKH4Jodyfou46lh2YYZecWtqJVyfIq0aPtDv048nKWYg690pISmuoTdNrQo DryWHNhRkebWXxRQRTjz2BY85gBSOctXoTmCVw1gTbE43mfmHkp8s+dOh+7/X59OAzn79d2eZRh BnBqQq1UbORl4PF6T2onJLBLhsJ8srfBJs8u/9WsAAwy0Ql6fCuYowR/o+SSLChwR9LfaMPmueS pd7BliKxmIczwItmP6DTjn/AkkBjajMsyd3lQvs24MTrusmGMwrth X-Google-Smtp-Source: AGHT+IHUvGILmPxevlLiDdE4/5niU9zwzNHdixZ1E6LRUj9Z/4mSR8N5VsZ6oCwXtJouTe5pBCngUg== X-Received: by 2002:a05:622a:588c:b0:4a4:4202:e77e with SMTP id d75a77b69052e-4a5b9a0528cmr245207171cf.6.1749509203935; Mon, 09 Jun 2025 15:46:43 -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 d75a77b69052e-4a611150018sm62230961cf.8.2025.06.09.15.46.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Jun 2025 15:46:43 -0700 (PDT) Received: from phl-compute-01.internal (phl-compute-01.phl.internal [10.202.2.41]) by mailfauth.phl.internal (Postfix) with ESMTP id 957041200043; Mon, 9 Jun 2025 18:46:42 -0400 (EDT) Received: from phl-mailfrontend-01 ([10.202.2.162]) by phl-compute-01.internal (MEProxy); Mon, 09 Jun 2025 18:46:42 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:42 -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" Subject: [PATCH v4 08/10] rust: sync: atomic: Add Atomic<{usize,isize}> Date: Mon, 9 Jun 2025 15:46:13 -0700 Message-Id: <20250609224615.27061-9-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" Add generic atomic support for `usize` and `isize`. Note that instead of mapping directly to `atomic_long_t`, the represention type (`AllowAtomic::Repr`) is selected based on CONFIG_64BIT. This reduces the necessarity of creating `atomic_long_*` helpers, which could save the binary size of kernel if inline helpers are not available. Signed-off-by: Boqun Feng --- rust/kernel/sync/atomic.rs | 54 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/rust/kernel/sync/atomic.rs b/rust/kernel/sync/atomic.rs index 9039591b4d46..e36431f0b42c 100644 --- a/rust/kernel/sync/atomic.rs +++ b/rust/kernel/sync/atomic.rs @@ -65,6 +65,56 @@ fn delta_into_repr(d: Self::Delta) -> Self::Repr { } } =20 +// SAFETY: `usize` has the same size and the alignment as `i64` for 64bit = and the same as `i32` for +// 32bit. +unsafe impl generic::AllowAtomic for usize { + #[cfg(CONFIG_64BIT)] + type Repr =3D i64; + #[cfg(not(CONFIG_64BIT))] + type Repr =3D i32; + + fn into_repr(self) -> Self::Repr { + self as Self::Repr + } + + fn from_repr(repr: Self::Repr) -> Self { + repr as Self + } +} + +impl generic::AllowAtomicArithmetic for usize { + type Delta =3D usize; + + fn delta_into_repr(d: Self::Delta) -> Self::Repr { + d as Self::Repr + } +} + +// SAFETY: `isize` has the same size and the alignment as `i64` for 64bit = and the same as `i32` for +// 32bit. +unsafe impl generic::AllowAtomic for isize { + #[cfg(CONFIG_64BIT)] + type Repr =3D i64; + #[cfg(not(CONFIG_64BIT))] + type Repr =3D i32; + + fn into_repr(self) -> Self::Repr { + self as Self::Repr + } + + fn from_repr(repr: Self::Repr) -> Self { + repr as Self + } +} + +impl generic::AllowAtomicArithmetic for isize { + type Delta =3D isize; + + fn delta_into_repr(d: Self::Delta) -> Self::Repr { + d as Self::Repr + } +} + use crate::macros::kunit_tests; =20 #[kunit_tests(rust_atomics)] @@ -84,7 +134,7 @@ macro_rules! for_each_type { =20 #[test] fn atomic_basic_tests() { - for_each_type!(42 in [i32, i64, u32, u64] |v| { + for_each_type!(42 in [i32, i64, u32, u64, isize, usize] |v| { let x =3D Atomic::new(v); =20 assert_eq!(v, x.load(Relaxed)); @@ -93,7 +143,7 @@ fn atomic_basic_tests() { =20 #[test] fn atomic_arithmetic_tests() { - for_each_type!(42 in [i32, i64, u32, u64] |v| { + for_each_type!(42 in [i32, i64, u32, u64, isize, usize] |v| { let x =3D Atomic::new(v); =20 assert_eq!(v, x.fetch_add(12, Full)); --=20 2.39.5 (Apple Git-154) From nobody Sun Feb 8 01:44:08 2026 Received: from mail-qk1-f176.google.com (mail-qk1-f176.google.com [209.85.222.176]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 51C3A22B5AA; Mon, 9 Jun 2025 22:46:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.222.176 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509208; cv=none; b=pc/LyvVWh0YMqA3miXrElH5EH6mQPSMnLdQD8e2amNt2mF8ZFlTGBkrasJgl7bVTlKy5wXZAwD3gElQvMCvTv+Spcoe+L89698z5mJMECyyIHJ/v0LCtRn0sSRbSAJJiZOnGTNyjfGOvQzcNKmFsoreA3WaLG4O/kNbfycNAdUk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509208; c=relaxed/simple; bh=oShskdJdNehAIRIfwEnkypGXtdI0C/hh7/P9bKhB/HY=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=Rj9WGWmx2MvMgorrHaQ8XxQF6SCeCN3nwHmwtAEvQnu07+4qtG5h4Wdd0IiH3wdseRh3l5unqY6p1OmlKUdBsRBLm6AV6pkTnx9ZN5Jyoj6sRNKxGe6r15ksZJWtYmbBpinjByhb/++Dp7b/JCoI3mqajcefn05CHLxy/QcMyJs= 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=ZOB+8X3o; arc=none smtp.client-ip=209.85.222.176 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="ZOB+8X3o" Received: by mail-qk1-f176.google.com with SMTP id af79cd13be357-7c5b8d13f73so523696685a.0; Mon, 09 Jun 2025 15:46:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1749509205; x=1750114005; darn=vger.kernel.org; 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=JDojvZPWlL3CFCvJoSK0mwbboSKSCM4nCY+n+4WMk+A=; b=ZOB+8X3o5wK4sgdCw65aBNzNFRhVMKMLLp1QuT84dfmceZF7Y7Wz0RxVR8lqDfkLED IEro/lGhkhuNAhEscXqbu+1kkp9Di744nIgNNZMzbVZiRmtps1obQanFORN/pdxkC9Qt +vbih+d5PjuU+JI4kCmncC5/0i9wQOqbOQqQvWXK5aLdD/KYq7QNa+vYPZIDdhG4TGRc 7AA6r0MpzinPpOUyvg+jeXLEiU0o5O2uBb6oMpqm4t8R3brW7xRg8IucjTAAOsWR8ra0 NxuLjrkVdMKoR/ajYw3SWmevCFDxREn5oavfkTqkibx1pm/jhPvZHTOZrpwqprxWuclE kCSg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1749509205; x=1750114005; 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=JDojvZPWlL3CFCvJoSK0mwbboSKSCM4nCY+n+4WMk+A=; b=R0miGrpidYAakgauJ5kHbUyfihwmJHc3bNAog9Hh5l7Tv8eYsYVfGYLd2QYr508V6O fubg24Xmn5w1BEWXz0o8/c7jhifoxM1CrYF65Ui19vK7yTIsIPvKX2OXfdyykEikq9HE eqV6vEKM3rGHCyxLkdSEMs5L3nXrXWZmy6tcNFt0uyaOC6qopEtqxvH8DI8qiHJBhPxb Z6UzyTNWZJfbLM78x1sVxv3Cqjkcf3h3Ct5V6VjLL2KZ5cCqsl67lcIFlW5a8AnfDZ+K 7LpRZmOYrYacEZJAOdZi/V8QK1VOJnfJF23HtOeqpSyGBUrSOKTWXIvwaC76CHdLCCxs gIXg== X-Forwarded-Encrypted: i=1; AJvYcCUsU57ElmrcCVosYODZJMMXxcoDFR75US78g5MQLGAUhJPaXUosbv1MsciXggfcC67HNCLeczR0x/m0mRuybi8=@vger.kernel.org, AJvYcCXZHLeVjBIyH96XSipOwqrcex7naFFHEMsVQUdWEMoJQ2nuDS6dtUEPgr0/R4nW/BF2KLlrX3Glvzjy@vger.kernel.org X-Gm-Message-State: AOJu0Yy9/UXmQTYV0PMWn7Ac4mrKURgW/VGOMxC9m/dgZOy52TPkgXa7 bj5tkrwqF9iJzYt5kt4SCKsAIQBCp9mibyf7v3eHMJsTtBJbFMXEtqDj X-Gm-Gg: ASbGncvW5+W7x9IfJKgu2rKMVrMLgkqypDRMdXpE9xGgG5CJRIQYEVYaDV2Njx8skwX zhagv3+v9zC7PXb5pku/isq205d37RnMP+f0Vv1q8mYnqzhW2/w66V94C151SEGb19N4ZVxok7L eTSnfl+NftAomsB2LAasgBjE5eJZAo7glxWxq5jqagrAeqhojWZrbiCyFGzYydlP2hcHa21ngUY jrCC2b6uB7/CSVmyaE1CSNsya0ROIb8QXKgF/+dCYiUzU88/gVzwZF2Gc8/NRvdwBz/dlUTSH7Q MQCHbmzEBcTLvb/5ObmaqatQ7QcPpP4WezfnQsaIial8YVximeoFhGQwzkaq6ySHjHbgJRt+R6f /yPPiWSLETuhL+zfY6MX0wsUyF4zDWYwokZ1DcpUpWW3sl/XuuXeH X-Google-Smtp-Source: AGHT+IFWdMXlzex7gDUzqrYkpBHW2HafBlv4t/6SL8q1hA5ZegRGjDNZEMNQbmxRYP3nvG3zy2bOpw== X-Received: by 2002:a05:620a:24c3:b0:7c5:d1b2:166b with SMTP id af79cd13be357-7d229896668mr2335066085a.8.1749509205062; Mon, 09 Jun 2025 15:46:45 -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 6a1803df08f44-6fb09b364c8sm57352876d6.109.2025.06.09.15.46.44 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Jun 2025 15:46:44 -0700 (PDT) Received: from phl-compute-03.internal (phl-compute-03.phl.internal [10.202.2.43]) by mailfauth.phl.internal (Postfix) with ESMTP id 066001200066; Mon, 9 Jun 2025 18:46:44 -0400 (EDT) Received: from phl-mailfrontend-01 ([10.202.2.162]) by phl-compute-03.internal (MEProxy); Mon, 09 Jun 2025 18:46:44 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedtnecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:43 -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" Subject: [PATCH v4 09/10] rust: sync: atomic: Add Atomic<*mut T> Date: Mon, 9 Jun 2025 15:46:14 -0700 Message-Id: <20250609224615.27061-10-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" Add atomic support for raw pointer values, similar to `isize` and `usize`, the representation type is selected based on CONFIG_64BIT. `*mut T` is not `Send`, however `Atomic<*mut T>` definitely needs to be a `Sync`, and that's the whole point of atomics: being able to have multiple shared references in different threads so that they can sync with each other. As a result, a pointer value will be transferred from one thread to another via `Atomic<*mut T>`: x.store(p1, Relaxed); let p =3D x.load(p1, Relaxed); This means a raw pointer value (`*mut T`) needs to be able to transfer across thread boundaries, which is essentially `Send`. To reflect this in the type system, and based on the fact that pointer values can be transferred safely (only using them to dereference is unsafe), as suggested by Alice, extend the `AllowAtomic` trait to include a customized `Send` semantics, that is: `impl AllowAtomic` has to be safe to be transferred across thread boundaries. Suggested-by: Alice Ryhl Signed-off-by: Boqun Feng --- rust/kernel/sync/atomic.rs | 19 +++++++++++++++++++ rust/kernel/sync/atomic/generic.rs | 16 +++++++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/rust/kernel/sync/atomic.rs b/rust/kernel/sync/atomic.rs index e36431f0b42c..e4dd31a3e3e2 100644 --- a/rust/kernel/sync/atomic.rs +++ b/rust/kernel/sync/atomic.rs @@ -114,6 +114,22 @@ fn delta_into_repr(d: Self::Delta) -> Self::Repr { d as Self::Repr } } +// SAFETY: A `*mut T` has the same size and the alignment as `i64` for 64b= it and the same as `i32` +// for 32bit. And it's safe to transfer the ownership of a pointer value t= o another thread. +unsafe impl generic::AllowAtomic for *mut T { + #[cfg(CONFIG_64BIT)] + type Repr =3D i64; + #[cfg(not(CONFIG_64BIT))] + type Repr =3D i32; + + fn into_repr(self) -> Self::Repr { + self as Self::Repr + } + + fn from_repr(repr: Self::Repr) -> Self { + repr as Self + } +} =20 use crate::macros::kunit_tests; =20 @@ -139,6 +155,9 @@ fn atomic_basic_tests() { =20 assert_eq!(v, x.load(Relaxed)); }); + + let x =3D Atomic::new(core::ptr::null_mut::()); + assert!(x.load(Relaxed).is_null()); } =20 #[test] diff --git a/rust/kernel/sync/atomic/generic.rs b/rust/kernel/sync/atomic/g= eneric.rs index f0bc831e8079..e2f60e89fbbb 100644 --- a/rust/kernel/sync/atomic/generic.rs +++ b/rust/kernel/sync/atomic/generic.rs @@ -19,6 +19,10 @@ #[repr(transparent)] pub struct Atomic(Opaque); =20 +// SAFETY: `Atomic` is safe to send between execution contexts, because= `T` is `AllowAtomic` and +// `AllowAtomic`'s safety requirement guarantees that. +unsafe impl Send for Atomic {} + // SAFETY: `Atomic` is safe to share among execution contexts because a= ll accesses are atomic. unsafe impl Sync for Atomic {} =20 @@ -31,8 +35,13 @@ unsafe impl Sync for Atomic {} /// /// # Safety /// -/// [`Self`] must have the same size and alignment as [`Self::Repr`]. -pub unsafe trait AllowAtomic: Sized + Send + Copy { +/// - [`Self`] must have the same size and alignment as [`Self::Repr`]. +/// - The implementer must guarantee it's safe to transfer ownership from = one execution context to +/// another, this means it has to be a [`Send`], but because `*mut T` is= not [`Send`] and that's +/// the basic type needs to support atomic operations, so this safety re= quirement is added to +/// [`AllowAtomic`] trait. This safety requirement is automatically sati= sfied if the type is a +/// [`Send`]. +pub unsafe trait AllowAtomic: Sized + Copy { /// The backing atomic implementation type. type Repr: AtomicImpl; =20 @@ -45,7 +54,8 @@ pub unsafe trait AllowAtomic: Sized + Send + Copy { =20 // An `AtomicImpl` is automatically an `AllowAtomic`. // -// SAFETY: `T::Repr` is `Self` (i.e. `T`), so they have the same size and = alignment. +// SAFETY: `T::Repr` is `Self` (i.e. `T`), so they have the same size and = alignment. And all +// `AtomicImpl` types are `Send`. unsafe impl AllowAtomic for T { type Repr =3D Self; =20 --=20 2.39.5 (Apple Git-154) From nobody Sun Feb 8 01:44:08 2026 Received: from mail-qv1-f46.google.com (mail-qv1-f46.google.com [209.85.219.46]) (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 7ED4022B8D2; Mon, 9 Jun 2025 22:46:47 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.46 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509209; cv=none; b=VsUCeftIEW3oJ7gv9V2VOnu/IJVtvBuY6VuWwc/zceepJdPoIGl0bFeqCdB8u2wS3cPTI2Kl9vJWC7syMrVaTrJimolWBfwsOSZvh11kB6YD6klnshpkM8SUrHrBkRfv+SuXTxbXBdyC77Fq016tRZ3mSMVWudc2nXkoB4IB23Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749509209; c=relaxed/simple; bh=Anqrl5cWjcAsA5b2G9jSaTOPpHxzWAGMmgi9KYl1kyU=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: MIME-Version; b=luZD7iGML5UvGQFjW7HUlz2SCKt209+pw0DgapUbtXE7IqZEwk9YwxPn7xz+Npkmpjwi6P0n1ZvIjhnJE+cMzr/LhPQjXR5oonkv3pPGPSQbJQD1tdX0fRbr05k2kkR9JTpxgYmfPpoWRT6rLwfOoYXnUo4bAo1R1FWZUvbXsZs= 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=FSeWAeB3; arc=none smtp.client-ip=209.85.219.46 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="FSeWAeB3" Received: by mail-qv1-f46.google.com with SMTP id 6a1803df08f44-6f8a70fe146so92811376d6.0; Mon, 09 Jun 2025 15:46:47 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1749509206; x=1750114006; darn=vger.kernel.org; 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=aVh/Q3YvKlU1Rq5I19BJ7b1z8f+dcy4cBENHfBypeho=; b=FSeWAeB36kHbQ5kUiAQC6TsgMU6FFkrreMltHhtS3fLBPyLxEvsUJKxVf/Iq+2jb8g l0Y5osKE4SdAAvVVr5aMr7JmMzk11C1pBwarLbHawEcS8YnYJ8DEM/C0ZPMSzzvF7aYz +F4Eu4g5cqo/CpS3Yb24uPWqiGZCG6L1ddBTG0nmxV8Lz+qsBrKV17W4webKPtesHpry SVh/Z+ppV/zBTI/0KWFohHqoIkY5/SoQpz1yM9sRL/1t8XGhWp1p7SHL6e5HDy1X+Jji 7CxYO4GZOT/aHiM7GDM7yo9bCqnIe7p1FqcKJQRRd4mHjFFEs8stxoQAScdG4m0MzmWU 78zg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1749509206; x=1750114006; 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=aVh/Q3YvKlU1Rq5I19BJ7b1z8f+dcy4cBENHfBypeho=; b=nKpvU1yRDonosAzTSqeElhFmGvw81AilQ+RkuLb1/2cYeGCV8cFn7k1IRXtn8OzCEB rwfSjkpgdqb/KZ+aVlcIJDLTmP2trma7eC3PeE+LP7oqZhxykFuVNnKSotbL0peJruMR l6EZezf++g+Hz7uIGKKGYV4x8B0Yz7T6+fl7fF7m76WeOp1rdyezoxy5D+mVB6zatHY/ ie+ciKs7i1KTlBLdmO1kBmoKNtZ67CEMBBH+J0Skz2PNVQv/fGnjf9dfJ1YqIHJCDglR m2eOUKt0p7IEqSRiqKEk4+XFho2O96FirPGHWf910uXiC1O4DrkSP70gH4TrHgEmRhdU SNSQ== X-Forwarded-Encrypted: i=1; AJvYcCVJNCaDpFs1nAoh1d4np8Hk3iaOGLzeY9KKgRqF2CFaOtEXB36ayvPseuMnn1f8rY2NnlfwJT3Bn0wl@vger.kernel.org, AJvYcCWL6RH1Tzm95GrBLmiQVHA7psy52nDnKBklMFpNXZbZhsCwoY05gKSXN6HLwbEGymRK13AQfFQBroNThBSPvYk=@vger.kernel.org X-Gm-Message-State: AOJu0YzRsNgtgbsqSu89fS3JYhKAtRh3CXKUKKBUCdVLQLxYSe4qfLHN 4Py8fB2dplKnPvDLrN2gQTL48zuo/WXLq6pUjLctDI0ZwbYhGMVQeU4A X-Gm-Gg: ASbGncuRPnM8goSMC15M4nhotgdK8dxEWXAzyGO1bo274Jl1baP2w3vaTsLzAqp9pTs xKNpuC80YWAE+0/2jAilor4nJ8dK7sFysj2Yv2aSu6AVMT7yajpOgG8gJR16QK/0HIb7Ha9KwIB 6hBAJGUxrMP7KLq7GOy9cf8apCmXl5XNCIOxkbNXFEA1sw6D2XmWlYdML42Ke8tNKqC6xL4uWl3 7LCHJc4Ct8QXWcQkIoeOhV9gm7dvPisnCnL2klhuq93310zBs/p2sUIplHV+YlqbGEGc97EYOjC lLavmENw/goh1NW++NNHqNq0gadjwGztrwfGvnTx9r57yw+AZJ0ANcmdLk3PtcynLGMy5Aycaev SgyWXWxXYmDOJufIv8a7T3UwPBc1H9lFTSHUaSWduP/p6dspkc2Wf X-Google-Smtp-Source: AGHT+IFumn8OwjYXPgXZ16qqTX9xz1gY58UxpowoDVxCsQHRJ60EJ7bd/NwPv4mxtLSYcvshs3G6lQ== X-Received: by 2002:a05:6214:268f:b0:6fa:c46c:6f9e with SMTP id 6a1803df08f44-6fb08fd9af0mr224426906d6.5.1749509206360; Mon, 09 Jun 2025 15:46:46 -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 6a1803df08f44-6fb09ab8479sm57902056d6.20.2025.06.09.15.46.45 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 09 Jun 2025 15:46:45 -0700 (PDT) Received: from phl-compute-09.internal (phl-compute-09.phl.internal [10.202.2.49]) by mailfauth.phl.internal (Postfix) with ESMTP id 657911200043; Mon, 9 Jun 2025 18:46:45 -0400 (EDT) Received: from phl-mailfrontend-01 ([10.202.2.162]) by phl-compute-09.internal (MEProxy); Mon, 09 Jun 2025 18:46:45 -0400 X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeffedrtddugdelleduucetufdoteggodetrfdotf fvucfrrhhofhhilhgvmecuhfgrshhtofgrihhlpdggtfgfnhhsuhgsshgtrhhisggvpdfu rfetoffkrfgpnffqhgenuceurghilhhouhhtmecufedttdenucesvcftvggtihhpihgvnh htshculddquddttddmnecujfgurhephffvvefufffkofgjfhgggfestdekredtredttden ucfhrhhomhepuehoqhhunhcuhfgvnhhguceosghoqhhunhdrfhgvnhhgsehgmhgrihhlrd gtohhmqeenucggtffrrghtthgvrhhnpeegleejiedthedvheeggfejveefjeejkefgveff ieeujefhueeigfegueehgeeggfenucevlhhushhtvghrufhiiigvpedunecurfgrrhgrmh epmhgrihhlfhhrohhmpegsohhquhhnodhmvghsmhhtphgruhhthhhpvghrshhonhgrlhhi thihqdeiledvgeehtdeigedqudejjeekheehhedvqdgsohhquhhnrdhfvghngheppehgmh grihhlrdgtohhmsehfihigmhgvrdhnrghmvgdpnhgspghrtghpthhtohepvdeipdhmohgu vgepshhmthhpohhuthdprhgtphhtthhopehlihhnuhigqdhkvghrnhgvlhesvhhgvghrrd hkvghrnhgvlhdrohhrghdprhgtphhtthhopehruhhsthdqfhhorhdqlhhinhhugiesvhhg vghrrdhkvghrnhgvlhdrohhrghdprhgtphhtthhopehlkhhmmheslhhishhtshdrlhhinh hugidruggvvhdprhgtphhtthhopehlihhnuhigqdgrrhgthhesvhhgvghrrdhkvghrnhgv lhdrohhrghdprhgtphhtthhopehojhgvuggrsehkvghrnhgvlhdrohhrghdprhgtphhtth hopegrlhgvgidrghgrhihnohhrsehgmhgrihhlrdgtohhmpdhrtghpthhtohepsghoqhhu nhdrfhgvnhhgsehgmhgrihhlrdgtohhmpdhrtghpthhtohepghgrrhihsehgrghrhihguh hordhnvghtpdhrtghpthhtohepsghjohhrnhefpghghhesphhrohhtohhnmhgrihhlrdgt ohhm X-ME-Proxy: Feedback-ID: iad51458e:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Mon, 9 Jun 2025 18:46:44 -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" Subject: [PATCH v4 10/10] rust: sync: Add memory barriers Date: Mon, 9 Jun 2025 15:46:15 -0700 Message-Id: <20250609224615.27061-11-boqun.feng@gmail.com> X-Mailer: git-send-email 2.39.5 (Apple Git-154) In-Reply-To: <20250609224615.27061-1-boqun.feng@gmail.com> References: <20250609224615.27061-1-boqun.feng@gmail.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 Content-Type: text/plain; charset="utf-8" Memory barriers are building blocks for concurrent code, hence provide a minimal set of them. The compiler barrier, barrier(), is implemented in inline asm instead of using core::sync::atomic::compiler_fence() because memory models are different: kernel's atomics are implemented in inline asm therefore the compiler barrier should be implemented in inline asm as well. Also it's currently only public to the kernel crate until there's a reasonable driver usage. Signed-off-by: Boqun Feng --- rust/helpers/barrier.c | 18 ++++++++++ rust/helpers/helpers.c | 1 + rust/kernel/sync.rs | 1 + rust/kernel/sync/barrier.rs | 67 +++++++++++++++++++++++++++++++++++++ 4 files changed, 87 insertions(+) create mode 100644 rust/helpers/barrier.c create mode 100644 rust/kernel/sync/barrier.rs diff --git a/rust/helpers/barrier.c b/rust/helpers/barrier.c new file mode 100644 index 000000000000..cdf28ce8e511 --- /dev/null +++ b/rust/helpers/barrier.c @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +void rust_helper_smp_mb(void) +{ + smp_mb(); +} + +void rust_helper_smp_wmb(void) +{ + smp_wmb(); +} + +void rust_helper_smp_rmb(void) +{ + smp_rmb(); +} diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 0e7e7b388062..928eca7fbbb4 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -9,6 +9,7 @@ =20 #include "atomic.c" #include "auxiliary.c" +#include "barrier.c" #include "blk.c" #include "bug.c" #include "build_assert.c" diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index b620027e0641..c7c0e552bafe 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -11,6 +11,7 @@ =20 mod arc; pub mod atomic; +pub mod barrier; mod condvar; pub mod lock; mod locked_by; diff --git a/rust/kernel/sync/barrier.rs b/rust/kernel/sync/barrier.rs new file mode 100644 index 000000000000..36a5c70e6716 --- /dev/null +++ b/rust/kernel/sync/barrier.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Memory barriers. +//! +//! These primitives have the same semantics as their C counterparts: and = the precise definitions of +//! semantics can be found at [`LKMM`]. +//! +//! [`LKMM`]: srctree/tools/memory-mode/ + +/// A compiler barrier. +/// +/// An explicic compiler barrier function that prevents the compiler from = moving the memory +/// accesses either side of it to the other side. +pub(crate) fn barrier() { + // By default, Rust inline asms are treated as being able to access an= y memory or flags, hence + // it suffices as a compiler barrier. + // + // SAFETY: An empty asm block should be safe. + unsafe { + core::arch::asm!(""); + } +} + +/// A full memory barrier. +/// +/// A barrier function that prevents both the compiler and the CPU from mo= ving the memory accesses +/// either side of it to the other side. +pub fn smp_mb() { + if cfg!(CONFIG_SMP) { + // SAFETY: `smp_mb()` is safe to call. + unsafe { + bindings::smp_mb(); + } + } else { + barrier(); + } +} + +/// A write-write memory barrier. +/// +/// A barrier function that prevents both the compiler and the CPU from mo= ving the memory write +/// accesses either side of it to the other side. +pub fn smp_wmb() { + if cfg!(CONFIG_SMP) { + // SAFETY: `smp_wmb()` is safe to call. + unsafe { + bindings::smp_wmb(); + } + } else { + barrier(); + } +} + +/// A read-read memory barrier. +/// +/// A barrier function that prevents both the compiler and the CPU from mo= ving the memory read +/// accesses either side of it to the other side. +pub fn smp_rmb() { + if cfg!(CONFIG_SMP) { + // SAFETY: `smp_rmb()` is safe to call. + unsafe { + bindings::smp_rmb(); + } + } else { + barrier(); + } +} --=20 2.39.5 (Apple Git-154)