Skip to content

Commit 95eb872

Browse files
committed
Port outline-atomics to rust
This has a very long history, summarized in rust-lang/rust#109064. This port is a very minimal subset of `aarch64/lse.S` from LLVM's compiler-rt. In particular, it is missing the following: 1. Any form of runtime dispatch between LL/SC and LSE. Determining which version of the intrinsics to use requires one of the following: i) `getauxval` from glibc. It's unclear whether `compiler_builtins` is allowed to depend on libc at all, and musl doesn't even support getauxval. Don't enshrine the requirement "de-facto" by making it required for outline-atomics. ii) kernel support. Linux and FreeBSD have limited support, but it requires an extremely recent kernel version and doesn't work at all under QEMU (rust-lang/rust#109064 (comment)). Instead, we hard-code LL/SC intrinsics. Users who want LSE support should use the LLVM compiler-rt (if you're building from source in rust-lang/rust, make sure you have `src/llvm-project` checked out locally. the goal is to soon add a new `optimized-compiler-builtins` option so this is easier to discover). 2. The global `___aarch64_have_lse_atomics` CTOR, required to do runtime dispatch. Thom Chiviolani has this to say about global CTORs: > static ctors are problems because we are pretty eager about dead code elim > in general if you have a module that isnt directly reference we will probably not have its static ctors > also, while llvm has a super robust way to have a static ctor (theres s special "appending global" to use for c++), we dont use that and just have people make a #[used] static in a special section > 1. the robust way kinda requires rust knowing that the argument is a static ctor (maybe a #[rustc_static_ctor] attribute). it also would be... finnicky, since on windows we actually care beyond being a static ctor, that we run as part in a specific group of ctors, which means a very specific section (one for TLS and the other for, uh, i dont remember) > 2. we still actually have to codegen the cgu that isn't referenced. but maybe we could remember that it has that attribute and use that So while this is possible in theory, it's decidedly non-trivial, and needs invasive changes to rust itself. In any case, it doesn't matter until we decide the story around libc. 3. The 16-byte (i128) version of compare_and_swap. This wouldn't be *too* hard to add, but it would be hard to test. The way I tested the existing code was not just with unit tests but also by loading it as a path dependency and running `x test core` - the latter caught several bugs the unit tests didn't catch (because I originally wrote the tests wrong). So I am slightly nervous about adding a 16-byte version that is much more poorly tested than the other intrinsics.
1 parent ea1e63c commit 95eb872

File tree

5 files changed

+358
-2
lines changed

5 files changed

+358
-2
lines changed

build.rs

+47-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::env;
1+
use std::{env, sync::atomic::Ordering, collections::HashMap};
22

33
fn main() {
44
println!("cargo:rerun-if-changed=build.rs");
@@ -90,6 +90,52 @@ fn main() {
9090
{
9191
println!("cargo:rustc-cfg=kernel_user_helpers")
9292
}
93+
94+
if llvm_target[0] == "aarch64" {
95+
generate_aarch64_outlined_atomics();
96+
}
97+
}
98+
99+
fn aarch64_symbol(ordering: Ordering) -> &'static str {
100+
match ordering {
101+
Ordering::Relaxed => "relax",
102+
Ordering::Acquire => "acq",
103+
Ordering::Release => "rel",
104+
Ordering::AcqRel => "acq_rel",
105+
_ => panic!("unknown symbol for {:?}", ordering),
106+
}
107+
}
108+
109+
fn generate_aarch64_outlined_atomics() {
110+
use std::fmt::Write;
111+
let gen_macro = |name| format!("#[macro_export] macro_rules! foreach_{name} {{
112+
($macro:path) => {{\n");
113+
114+
let sym_names = ["cas", "ldadd", "ldclr", "ldeor", "ldset", "swp"];
115+
let mut macros = HashMap::new();
116+
for sym in sym_names {
117+
macros.insert(sym, gen_macro(sym));
118+
}
119+
120+
// The `concat_idents` macro is extremely annoying and doesn't allow us to define new items.
121+
// Define them from the build script instead.
122+
// Note that the majority of the code is still defined through the `CAS!` macro inline.
123+
for ordering in [Ordering::Relaxed, Ordering::Acquire, Ordering::Release, Ordering::AcqRel] {
124+
let sym_ordering = aarch64_symbol(ordering);
125+
for size in [1, 2, 4, 8/* , 16*/] { // TODO: support CAS 16
126+
for (sym, macro_) in &mut macros {
127+
let name = format!("__aarch64_{sym}{size}_{sym_ordering}");
128+
writeln!(macro_, "$macro!( {ordering:?}, {size}, {name} );").unwrap();
129+
}
130+
}
131+
}
132+
133+
let mut buf = String::new();
134+
for macro_def in macros.values() {
135+
buf += &macro_def;
136+
buf += "}; }";
137+
}
138+
std::fs::write(std::env::var("OUT_DIR").unwrap() + "/outlined_atomics.rs", buf).unwrap();
93139
}
94140

95141
#[cfg(feature = "c")]

src/aarch64.rs

+221
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
//! Aarch64 targets have two possible implementations for atomics:
2+
//! 1. Load-Locked, Store-Conditional (LL/SC), older and slower.
3+
//! 2. Large System Extensions (LSE), newer and faster.
4+
//! To avoid breaking backwards compat, C toolchains introduced a concept of "outlined atomics",
5+
//! where atomic operations call into the compiler runtime to dispatch between two depending on
6+
//! which is supported on the current CPU.
7+
//! See https://community.arm.com/arm-community-blogs/b/tools-software-ides-blog/posts/making-the-most-of-the-arm-architecture-in-gcc-10#:~:text=out%20of%20line%20atomics for more discussion.
8+
//!
9+
//! Currently we only support LL/SC, because LSE requires `getauxval` from libc in order to do runtime detection.
10+
//! Use the `compiler-rt` intrinsics if you want LSE support.
11+
//!
12+
//! Ported from `aarch64/lse.S` in LLVM's compiler-rt.
13+
//!
14+
//! Generate functions for each of the following symbols:
15+
//! __aarch64_swpN_ORDER
16+
//! __aarch64_ldaddN_ORDER
17+
//! __aarch64_ldclrN_ORDER
18+
//! __aarch64_ldeorN_ORDER
19+
//! __aarch64_ldsetN_ORDER
20+
//! for N = {1, 2, 4, 8}, M = {1, 2, 4, 8}, ORDER = { relax, acq, rel, acq_rel }
21+
//!
22+
//! TODO: M = 16
23+
//!
24+
//! The original `lse.S` has some truly horrifying code that expects to be compiled multiple times with different constants.
25+
//! We do something similar, but with macro arguments.
26+
27+
/// We don't do runtime dispatch so we don't have to worry about the global ctor.
28+
/// Apparently MacOS uses a different number of underscores in the symbol name (???)
29+
// #[cfg(target_vendor = "apple")]
30+
// macro_rules! have_lse {
31+
// () => { ___aarch64_have_lse_atomics }
32+
// }
33+
34+
// #[cfg(not(target_vendor = "apple"))]
35+
// macro_rules! have_lse {
36+
// () => { __aarch64_have_lse_atomics }
37+
// }
38+
39+
/// Translate a byte size to a Rust type.
40+
macro_rules! int_ty {
41+
// forward
42+
// ($bytes:tt) => { int_ty!(@ $bytes) };
43+
(1) => { i8 };
44+
(2) => { i16 };
45+
(4) => { i32 };
46+
(8) => { i64 };
47+
(16) => { i128 };
48+
}
49+
50+
/// Given a byte size and a register number, return a register of the appropriate size.
51+
///
52+
/// See <https://developer.arm.com/documentation/102374/0101/Registers-in-AArch64---general-purpose-registers>.
53+
macro_rules! reg {
54+
(1, $num:literal) => { concat!("w", $num) };
55+
(2, $num:literal) => { concat!("w", $num) };
56+
(4, $num:literal) => { concat!("w", $num) };
57+
(8, $num:literal) => { concat!("x", $num) };
58+
}
59+
60+
/// Given an atomic ordering, translate it to the acquire suffix for the lxdr aarch64 ASM instruction.
61+
macro_rules! acquire {
62+
(Relaxed) => { "" };
63+
(Acquire) => { "a" };
64+
(Release) => { "" };
65+
(AcqRel) => { "a" };
66+
}
67+
68+
/// Given an atomic ordering, translate it to the release suffix for the stxr aarch64 ASM instruction.
69+
macro_rules! release {
70+
(Relaxed) => { "" };
71+
(Acquire) => { "" };
72+
(Release) => { "l" };
73+
(AcqRel) => { "l" };
74+
}
75+
76+
/// Given a size in bytes, translate it to the byte suffix for the aarch64 ASM instruction.
77+
macro_rules! size {
78+
(1) => { "b" };
79+
(2) => { "h" };
80+
(4) => { "" };
81+
(8) => { "" };
82+
(16) => { "" };
83+
}
84+
85+
/// Given a byte size, translate it to an Unsigned eXTend instruction
86+
/// with the correct semantics.
87+
///
88+
/// See <https://developer.arm.com/documentation/ddi0596/2020-12/Base-Instructions/UXTB--Unsigned-Extend-Byte--an-alias-of-UBFM->
89+
macro_rules! uxt {
90+
// forward
91+
($bytes:tt) => { uxt!(@ $bytes) };
92+
(@ 1) => { "uxtb" };
93+
(@ 2) => { "uxth" };
94+
(@ $_:tt) => { "mov" };
95+
}
96+
97+
/// Given an atomic ordering and byte size, translate it to a LoaD eXclusive Register instruction
98+
/// with the correct semantics.
99+
///
100+
/// See <https://developer.arm.com/documentation/ddi0596/2020-12/Base-Instructions/LDXR--Load-Exclusive-Register->.
101+
macro_rules! ldxr {
102+
($ordering:ident, $bytes:tt) => { concat!("ld", acquire!($ordering), "xr", size!($bytes)) }
103+
}
104+
105+
/// Given an atomic ordering and byte size, translate it to a STore eXclusive Register instruction
106+
/// with the correct semantics.
107+
///
108+
/// See <https://developer.arm.com/documentation/ddi0596/2020-12/Base-Instructions/STXR--Store-Exclusive-Register->.
109+
macro_rules! stxr {
110+
($ordering:ident, $bytes:tt) => { concat!("st", release!($ordering), "xr", size!($bytes)) }
111+
}
112+
113+
/// See <https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicI8.html#method.compare_and_swap>.
114+
macro_rules! compare_and_swap {
115+
($ordering:ident, $bytes:tt, $name:ident) => {
116+
intrinsics! {
117+
#[maybe_use_optimized_c_shim]
118+
#[naked]
119+
pub extern "C" fn $name (
120+
expected: int_ty!($bytes), desired: int_ty!($bytes), ptr: *mut int_ty!($bytes)
121+
) -> int_ty!($bytes) {
122+
// We can't use `AtomicI8::compare_and_swap`; we *are* compare_and_swap.
123+
unsafe { core::arch::asm! {
124+
// UXT s(tmp0), s(0)
125+
concat!(uxt!($bytes), " ", reg!($bytes, 16), ", ", reg!($bytes, 0)),
126+
"0:",
127+
// LDXR s(0), [x2]
128+
concat!(ldxr!($ordering, $bytes), " ", reg!($bytes, 0), ", [x2]"),
129+
// cmp s(0), s(tmp0)
130+
concat!("cmp ", reg!($bytes, 0), ", ", reg!($bytes, 16)),
131+
"bne 1f",
132+
// STXR w(tmp1), s(1), [x2]
133+
concat!(stxr!($ordering, $bytes), " w17, ", reg!($bytes, 1), ", [x2]"),
134+
"cbnz w17, 0b",
135+
"1:",
136+
"ret",
137+
options(noreturn)
138+
} }
139+
}
140+
}
141+
}
142+
}
143+
144+
145+
macro_rules! swap {
146+
($ordering:ident, $bytes:tt, $name:ident) => {
147+
intrinsics! {
148+
#[maybe_use_optimized_c_shim]
149+
#[naked]
150+
pub extern "C" fn $name (
151+
left: int_ty!($bytes), right_ptr: *mut int_ty!($bytes)
152+
) -> int_ty!($bytes) {
153+
unsafe { core::arch::asm! {
154+
// mov s(tmp0), s(0)
155+
concat!("mov ", reg!($bytes, 16), ", ", reg!($bytes, 0)),
156+
"0:",
157+
// LDXR s(0), [x1]
158+
concat!(ldxr!($ordering, $bytes), " ", reg!($bytes, 0), ", [x1]"),
159+
// STXR w(tmp1), s(tmp0), [x1]
160+
concat!(stxr!($ordering, $bytes), " w17, ", reg!($bytes, 16), ", [x1]"),
161+
"cbnz w17, 0b",
162+
"ret",
163+
options(noreturn)
164+
} }
165+
}
166+
}
167+
}
168+
}
169+
170+
macro_rules! fetch_op {
171+
($ordering:ident, $bytes:tt, $name:ident, $op:literal) => {
172+
intrinsics! {
173+
#[maybe_use_optimized_c_shim]
174+
#[naked]
175+
pub extern "C" fn $name (
176+
val: int_ty!($bytes), ptr: *mut int_ty!($bytes)
177+
) -> int_ty!($bytes) {
178+
unsafe { core::arch::asm! {
179+
// mov s(tmp0), s(0)
180+
concat!("mov ", reg!($bytes, 16), ", ", reg!($bytes, 0)),
181+
"0:",
182+
// LDXR s(0), [x1]
183+
concat!(ldxr!($ordering, $bytes), " ", reg!($bytes, 0), ", [x1]"),
184+
// OP s(tmp1), s(0), s(tmp0)
185+
concat!($op, " ", reg!($bytes, 17), ", ", reg!($bytes, 0), ", ", reg!($bytes, 16)),
186+
// STXR w(tmp2), s(tmp1), [x1]
187+
concat!(stxr!($ordering, $bytes), " w15, ", reg!($bytes, 17), ", [x1]"),
188+
"cbnz w15, 0b",
189+
"ret",
190+
options(noreturn)
191+
} }
192+
}
193+
}
194+
}
195+
}
196+
197+
macro_rules! add {
198+
($ordering:ident, $bytes:tt, $name:ident) => { fetch_op! { $ordering, $bytes, $name, "add" } }
199+
}
200+
201+
macro_rules! and {
202+
($ordering:ident, $bytes:tt, $name:ident) => { fetch_op! { $ordering, $bytes, $name, "bic" } }
203+
}
204+
205+
macro_rules! xor {
206+
($ordering:ident, $bytes:tt, $name:ident) => { fetch_op! { $ordering, $bytes, $name, "eor" } }
207+
}
208+
209+
macro_rules! or {
210+
($ordering:ident, $bytes:tt, $name:ident) => { fetch_op! { $ordering, $bytes, $name, "orr" } }
211+
}
212+
213+
include!(concat!(env!("OUT_DIR"), "/outlined_atomics.rs"));
214+
foreach_cas!(compare_and_swap);
215+
foreach_swp!(swap);
216+
foreach_ldadd!(add);
217+
foreach_ldclr!(and);
218+
foreach_ldeor!(xor);
219+
foreach_ldset!(or);
220+
221+
// TODO: CAS 16

src/lib.rs

+8
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![allow(unexpected_cfgs)]
12
#![cfg_attr(feature = "compiler-builtins", compiler_builtins)]
23
#![cfg_attr(not(feature = "no-asm"), feature(asm))]
34
#![feature(abi_unadjusted)]
@@ -11,6 +12,10 @@
1112
#![feature(linkage)]
1213
#![feature(naked_functions)]
1314
#![feature(repr_simd)]
15+
#![feature(concat_idents)]
16+
#![feature(pointer_is_aligned)]
17+
#![feature(atomic_from_ptr)]
18+
#![feature(integer_atomics)]
1419
#![no_builtins]
1520
#![no_std]
1621
#![allow(unused_features)]
@@ -57,6 +62,9 @@ pub mod mem;
5762
#[cfg(target_arch = "arm")]
5863
pub mod arm;
5964

65+
#[cfg(target_arch = "aarch64")]
66+
pub mod aarch64;
67+
6068
#[cfg(all(
6169
kernel_user_helpers,
6270
any(target_os = "linux", target_os = "android"),

src/macros.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -419,7 +419,7 @@ macro_rules! intrinsics {
419419
(
420420
#[naked]
421421
$(#[$($attr:tt)*])*
422-
pub unsafe extern $abi:tt fn $name:ident( $($argname:ident: $ty:ty),* ) $(-> $ret:ty)? {
422+
pub $(unsafe)? extern $abi:tt fn $name:ident( $($argname:ident: $ty:ty),* ) $(-> $ret:ty)? {
423423
$($body:tt)*
424424
}
425425

testcrate/tests/lse.rs

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#![cfg(target_arch = "aarch64")]
2+
#![feature(decl_macro)]
3+
4+
/// Translate a byte size to a Rust type.
5+
macro int_ty {
6+
(1) => { i8 },
7+
(2) => { i16 },
8+
(4) => { i32 },
9+
(8) => { i64 },
10+
(16) => { i128 }
11+
}
12+
13+
mod cas {
14+
pub(super) macro test {
15+
($_ordering:ident, $bytes:tt, $name:ident) => {
16+
#[test]
17+
fn $name() {
18+
testcrate::fuzz_2(10000, |expected: super::int_ty!($bytes), new| {
19+
let mut target = expected.wrapping_add(10);
20+
// The return value is always the previous value.
21+
assert_eq!(unsafe { compiler_builtins::aarch64::$name::$name(expected, new, &mut target) }, expected.wrapping_add(10));
22+
// Make sure we didn't change `target`.
23+
assert_eq!(target, expected.wrapping_add(10));
24+
25+
target = expected;
26+
assert_eq!(unsafe { compiler_builtins::aarch64::$name::$name(expected, new, &mut target) }, expected);
27+
// This time we should have updated `target`.
28+
assert_eq!(target, new);
29+
});
30+
}
31+
}
32+
}
33+
}
34+
35+
mod swap {
36+
pub(super) macro test {
37+
($_ordering:ident, $bytes:tt, $name:ident) => {
38+
#[test]
39+
fn $name() {
40+
testcrate::fuzz_2(10000, |left: super::int_ty!($bytes), mut right| {
41+
let orig_right = right;
42+
assert_eq!(unsafe { compiler_builtins::aarch64::$name::$name(left, &mut right) }, orig_right);
43+
assert_eq!(left, right);
44+
});
45+
}
46+
}
47+
}
48+
}
49+
50+
macro_rules! test_op {
51+
($mod:ident, $( $op:tt )* ) => {
52+
mod $mod {
53+
pub(super) macro test {
54+
($_ordering:ident, $bytes:tt, $name:ident) => {
55+
#[test]
56+
fn $name() {
57+
testcrate::fuzz_2(10000, |old, val| {
58+
let mut target = old;
59+
let op: fn(super::int_ty!($bytes), super::int_ty!($bytes)) -> _ = $($op)*;
60+
let expected = op(old, val);
61+
assert_eq!(old, unsafe { compiler_builtins::aarch64::$name::$name(val, &mut target) }, "{} should return original value", stringify!($name));
62+
assert_eq!(expected, target, "{} should store to target", stringify!($name));
63+
});
64+
}
65+
}
66+
}
67+
}
68+
};
69+
}
70+
71+
test_op!(add, |left, right| left.wrapping_add(right));
72+
test_op!(clr, |left, right| left & !right);
73+
test_op!(xor, std::ops::BitXor::bitxor);
74+
test_op!(or, std::ops::BitOr::bitor);
75+
76+
compiler_builtins::foreach_cas!(cas::test);
77+
compiler_builtins::foreach_swp!(swap::test);
78+
compiler_builtins::foreach_ldadd!(add::test);
79+
compiler_builtins::foreach_ldclr!(clr::test);
80+
compiler_builtins::foreach_ldeor!(xor::test);
81+
compiler_builtins::foreach_ldset!(or::test);

0 commit comments

Comments
 (0)