Skip to main content

oa/core/
memory.rs

1//! Checked host-memory operations and explicit cache policy.
2//!
3//! Ordinary copies retain the platform's bulk-copy implementation while using
4//! compiler-sized blocks for small dynamic lengths. Streaming copies are an
5//! explicit contract for destinations that the CPU will not consume soon,
6//! such as GPU upload storage. They never change copy correctness.
7
8use std::sync::atomic::{Ordering, compiler_fence};
9
10use super::{Error, Result};
11
12#[cfg(all(target_arch = "x86_64", not(miri)))]
13#[path = "memory/x86.rs"]
14mod x86;
15
16#[cfg(all(target_arch = "x86_64", not(miri)))]
17const STREAMING_MIN_BYTES: usize = 1024;
18#[cfg(all(target_arch = "x86_64", not(miri)))]
19const STREAMING_MAX_BYTES: usize = 4 * 1024 * 1024;
20
21/// Copy one complete byte slice into another non-overlapping slice.
22///
23/// Small dynamic copies use fixed compiler-known blocks. Qualified medium
24/// copies use cached SIMD stores; bulk copies retain the platform implementation.
25///
26/// # Errors
27///
28/// Returns an error when the slices have different lengths.
29#[inline(always)]
30pub fn copy(destination: &mut [u8], source: &[u8]) -> Result<()> {
31	if destination.len() != source.len() {
32		return Err(length_mismatch(
33			destination.len(),
34			source.len(),
35			"memory::copy",
36		));
37	}
38	// SAFETY: equal slice lengths prove both ranges contain `source.len()` live
39	// bytes. Safe Rust's mutable/shared borrow rules make the ranges disjoint.
40	unsafe {
41		copy_to_ptr(destination.as_mut_ptr(), source.as_ptr(), source.len());
42	}
43	Ok(())
44}
45
46/// Copy one complete byte slice using an explicit one-way streaming policy.
47///
48/// The destination must not be consumed by the CPU soon. On a qualified x86-64
49/// target, medium-sized copies use non-temporal stores. Other sizes use cached
50/// stores, preferring the platform routine above the small-copy range.
51///
52/// # Errors
53///
54/// Returns an error when the slices have different lengths.
55#[inline(always)]
56pub fn copy_streaming(destination: &mut [u8], source: &[u8]) -> Result<()> {
57	if destination.len() != source.len() {
58		return Err(length_mismatch(
59			destination.len(),
60			source.len(),
61			"memory::copy_streaming",
62		));
63	}
64	// SAFETY: equal slice lengths prove both ranges contain `source.len()` live
65	// bytes. Safe Rust's mutable/shared borrow rules make the ranges disjoint.
66	unsafe {
67		copy_streaming_to_ptr(destination.as_mut_ptr(), source.as_ptr(), source.len());
68	}
69	Ok(())
70}
71
72/// Compare two byte slices with ordinary early-exit semantics.
73#[must_use]
74pub fn equal(left: &[u8], right: &[u8]) -> bool {
75	if left.len() != right.len() {
76		return false;
77	}
78	if left.as_ptr() == right.as_ptr() || left.is_empty() {
79		return true;
80	}
81
82	#[cfg(all(target_arch = "x86_64", not(miri)))]
83	if std::arch::is_x86_feature_detected!("avx512f")
84		&& std::arch::is_x86_feature_detected!("avx512bw")
85	{
86		// SAFETY: the feature checks admit AVX-512F and AVX-512BW. Both
87		// slices contain the same number of initialized bytes and remain live.
88		return unsafe { x86::equal_avx512(left.as_ptr(), right.as_ptr(), left.len()) };
89	}
90
91	#[cfg(all(target_arch = "x86_64", not(miri)))]
92	if std::arch::is_x86_feature_detected!("avx2") {
93		// SAFETY: the feature check admits AVX2. Both slices contain the same
94		// number of initialized bytes and remain live for the call.
95		return unsafe { x86::equal_avx2(left.as_ptr(), right.as_ptr(), left.len()) };
96	}
97
98	left == right
99}
100
101/// Compare equal-length byte slices without content-dependent early exit.
102///
103/// Different public lengths may return immediately. For equal lengths, every
104/// byte is visited before the result is produced. This is a bounded primitive,
105/// not a claim of system-wide constant-time behavior on every platform.
106#[must_use]
107pub fn equal_constant_time(left: &[u8], right: &[u8]) -> bool {
108	if left.len() != right.len() {
109		return false;
110	}
111
112	#[cfg(all(target_arch = "x86_64", not(miri)))]
113	if std::arch::is_x86_feature_detected!("avx512f")
114		&& std::arch::is_x86_feature_detected!("avx512bw")
115	{
116		// SAFETY: the feature checks admit AVX-512F and AVX-512BW. Both
117		// slices contain the same number of initialized bytes and remain live.
118		return unsafe { x86::equal_constant_time_avx512(left.as_ptr(), right.as_ptr(), left.len()) };
119	}
120
121	#[cfg(all(target_arch = "x86_64", not(miri)))]
122	if std::arch::is_x86_feature_detected!("avx2") {
123		// SAFETY: the feature check admits AVX2. Both slices contain the same
124		// number of initialized bytes and remain live for the call.
125		return unsafe { x86::equal_constant_time_avx2(left.as_ptr(), right.as_ptr(), left.len()) };
126	}
127
128	let mut difference = 0_u8;
129	for (&left_byte, &right_byte) in left.iter().zip(right) {
130		difference |= left_byte ^ right_byte;
131	}
132	compiler_fence(Ordering::SeqCst);
133	difference == 0
134}
135
136/// Erase every byte through observable stores.
137///
138/// Unlike ordinary filling or zeroing, these writes are retained even when the
139/// compiler can prove the destination is not subsequently read. This does not
140/// erase copies held elsewhere or guarantee removal from caches or swap.
141pub fn zero_secure(bytes: &mut [u8]) {
142	for byte in bytes {
143		// SAFETY: `byte` is a live, aligned mutable reference to one byte. The
144		// volatile store is used solely to prevent dead-store elimination.
145		unsafe {
146			std::ptr::write_volatile(byte, 0);
147		}
148	}
149	compiler_fence(Ordering::SeqCst);
150}
151
152#[cold]
153#[inline(never)]
154fn length_mismatch(destination: usize, source: usize, operation: &'static str) -> Error {
155	Error::invalid_argument(format!(
156		"{operation} requires equal lengths; destination is {destination} bytes, source is {source} bytes"
157	))
158}
159
160/// Copy initialized bytes to a disjoint writable range.
161///
162/// # Safety
163///
164/// `destination` must be valid for writes of `length` bytes, `source` must be
165/// valid for reads of `length` initialized bytes, and the two ranges must not
166/// overlap. Both ranges must remain live for the call.
167#[inline(always)]
168pub(crate) unsafe fn copy_to_ptr(destination: *mut u8, source: *const u8, length: usize) {
169	#[cfg(all(target_arch = "x86_64", not(target_feature = "avx2")))]
170	{
171		// SAFETY: the caller provides disjoint readable/writable ranges.
172		unsafe { std::ptr::copy_nonoverlapping(source, destination, length) };
173	}
174	#[cfg(not(all(target_arch = "x86_64", not(target_feature = "avx2"))))]
175	// SAFETY: the caller proves the same range and aliasing contract.
176	unsafe {
177		copy_native_to_ptr(destination, source, length)
178	};
179}
180
181#[inline(always)]
182#[cfg(not(all(target_arch = "x86_64", not(target_feature = "avx2"))))]
183unsafe fn copy_native_to_ptr(destination: *mut u8, source: *const u8, length: usize) {
184	if length > 256 {
185		#[cfg(all(target_arch = "x86_64", not(miri)))]
186		if length <= 4096
187			&& (cfg!(target_feature = "avx512f") || length >= 2048)
188			&& std::arch::is_x86_feature_detected!("avx512f")
189		{
190			// SAFETY: AVX-512F is checked or guaranteed by this build target;
191			// the caller proves live disjoint ranges and length is > 256.
192			unsafe { x86::copy_cached_avx512(destination, source, length) };
193			return;
194		}
195		// SAFETY: the caller proves disjoint readable/writable ranges. Give bulk
196		// copies a direct path without walking the small-copy dispatch tree.
197		unsafe {
198			std::ptr::copy_nonoverlapping(source, destination, length);
199		}
200		return;
201	}
202	if length == 0 {
203		return;
204	}
205
206	// SAFETY: the caller provides disjoint live ranges of `length` bytes. Every
207	// fixed block below remains inside those ranges; blocks may overlap other
208	// blocks from the same copy, but source and destination never overlap.
209	unsafe {
210		if length <= 16 {
211			if length >= 8 {
212				copy_block::<8>(destination, source);
213				copy_block::<8>(destination.add(length - 8), source.add(length - 8));
214			} else if length >= 4 {
215				copy_block::<4>(destination, source);
216				copy_block::<4>(destination.add(length - 4), source.add(length - 4));
217			} else if length >= 2 {
218				copy_block::<2>(destination, source);
219				copy_block::<2>(destination.add(length - 2), source.add(length - 2));
220			} else {
221				copy_block::<1>(destination, source);
222			}
223			return;
224		}
225
226		if length <= 32 {
227			copy_block::<16>(destination, source);
228			copy_block::<16>(destination.add(length - 16), source.add(length - 16));
229			return;
230		}
231
232		if length <= 64 {
233			copy_block::<32>(destination, source);
234			copy_block::<32>(destination.add(length - 32), source.add(length - 32));
235			return;
236		}
237
238		if length <= 128 {
239			copy_block::<32>(destination, source);
240			copy_block::<32>(destination.add(32), source.add(32));
241			copy_block::<32>(destination.add(length - 64), source.add(length - 64));
242			copy_block::<32>(destination.add(length - 32), source.add(length - 32));
243			return;
244		}
245
246		if length <= 256 {
247			copy_block::<32>(destination, source);
248			copy_block::<32>(destination.add(32), source.add(32));
249			copy_block::<32>(destination.add(64), source.add(64));
250			copy_block::<32>(destination.add(96), source.add(96));
251			copy_block::<32>(destination.add(length - 128), source.add(length - 128));
252			copy_block::<32>(destination.add(length - 96), source.add(length - 96));
253			copy_block::<32>(destination.add(length - 64), source.add(length - 64));
254			copy_block::<32>(destination.add(length - 32), source.add(length - 32));
255		}
256	}
257}
258
259/// Copy initialized bytes to a disjoint writable range using one-way policy.
260///
261/// # Safety
262///
263/// `destination` must be valid for writes of `length` bytes, `source` must be
264/// valid for reads of `length` initialized bytes, and the two ranges must not
265/// overlap. Both ranges must remain live for the call. The CPU must not consume
266/// the destination soon after this function returns.
267#[inline(always)]
268pub(crate) unsafe fn copy_streaming_to_ptr(destination: *mut u8, source: *const u8, length: usize) {
269	#[cfg(all(target_arch = "x86_64", not(miri)))]
270	if (STREAMING_MIN_BYTES..=STREAMING_MAX_BYTES).contains(&length)
271		&& std::arch::is_x86_feature_detected!("avx512f")
272		&& std::arch::is_x86_feature_detected!("avx512bw")
273	{
274		// SAFETY: the caller proves the pointer contract and the feature checks
275		// admit AVX-512F and AVX-512BW. Arbitrary alignment and length are valid.
276		unsafe {
277			x86::copy_streaming_avx512(destination, source, length);
278		}
279		return;
280	}
281
282	#[cfg(all(target_arch = "x86_64", not(miri)))]
283	if (STREAMING_MIN_BYTES..=STREAMING_MAX_BYTES).contains(&length)
284		&& std::arch::is_x86_feature_detected!("avx2")
285	{
286		// SAFETY: the caller proves the pointer contract and the feature check
287		// admits AVX2. The operation handles arbitrary byte alignment and length.
288		unsafe {
289			x86::copy_streaming_avx2(destination, source, length);
290		}
291		return;
292	}
293
294	// SAFETY: the caller proves disjoint live ranges. Outside the NT window,
295	// one-way medium/bulk copies use the platform routine: the cached SIMD
296	// path is tuned for reuse and can lose on a cold streaming arena.
297	unsafe {
298		if length > 256 {
299			std::ptr::copy_nonoverlapping(source, destination, length);
300		} else {
301			copy_to_ptr(destination, source, length);
302		}
303	}
304}
305
306#[inline(always)]
307#[cfg(not(all(target_arch = "x86_64", not(target_feature = "avx2"))))]
308unsafe fn copy_block<const LENGTH: usize>(destination: *mut u8, source: *const u8) {
309	// SAFETY: the caller proves both ranges contain `LENGTH` bytes and do not
310	// overlap. The byte type imposes no additional alignment requirement.
311	unsafe {
312		std::ptr::copy_nonoverlapping(source, destination, LENGTH);
313	}
314}