singe_cuda/memory/device/copy.rs
1use std::sync::Arc;
2
3use super::DeviceMemory;
4use crate::{
5 error::{Error, Result},
6 memory::{MemoryCopyKind, PinnedHostSlice, PinnedHostSliceMut, transfer},
7 stream::{Stream, StreamScope},
8 submission::{Access, AccessMode},
9 utility::checked_bytes,
10 view::{AnyBitPatternDeviceRepr, DeviceRegionProvider, DeviceRepr, DeviceSlice, HostSlice},
11};
12
13impl<T> DeviceMemory<T> {
14 /// Copies host values and waits until the device range contains the uploaded values.
15 ///
16 /// # Errors
17 ///
18 /// Returns an error for unequal element counts or byte-size overflow.
19 /// Also propagates access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
20 /// A nonempty synchronous transfer is rejected during stream capture.
21 pub fn copy_from_host(&mut self, host_slice: &[T]) -> Result<()>
22 where
23 T: DeviceRepr,
24 {
25 transfer::copy_from_host(self, host_slice)
26 }
27
28 /// Copies from page-locked host memory into this device allocation.
29 ///
30 /// The source length must match this allocation's length.
31 /// This is the pinned-memory-specific counterpart to [`DeviceMemory::copy_from_host`].
32 ///
33 /// # Errors
34 ///
35 /// Returns an error if the lengths differ, byte-size arithmetic overflows, or CUDA rejects the host-to-device copy.
36 pub fn copy_from_pinned<B>(&mut self, src: &B) -> Result<()>
37 where
38 B: PinnedHostSlice<T> + ?Sized,
39 T: DeviceRepr,
40 {
41 let context = Arc::clone(self.context());
42 self.bind()?;
43 let () = T::LAYOUT;
44 if HostSlice::len(src) != self.length {
45 return Err(Error::length_mismatch(
46 "host source",
47 self.length,
48 HostSlice::len(src),
49 ));
50 }
51
52 if self.length == 0 {
53 return Ok(());
54 }
55
56 checked_bytes::<T>(self.length, "byte length")?;
57 let _access = context.acquire_accesses(&[
58 Access::new(self.region(), AccessMode::Write),
59 Access::host(src.host_region(), AccessMode::Read),
60 ])?;
61 // SAFETY: the guards acquired above cover both regions, and the lengths were checked to match.
62 unsafe {
63 transfer::copy_synchronous(
64 self.ptr,
65 src.as_host_ptr(),
66 self.length,
67 MemoryCopyKind::HostToDevice,
68 None,
69 )
70 }
71 }
72
73 /// Enqueues a copy from page-locked host memory into this device allocation.
74 ///
75 /// The [`StreamScope`] ties the source and destination lifetimes to the queued copy.
76 ///
77 /// # Errors
78 ///
79 /// Returns an error if the lengths differ, byte-size arithmetic overflows, or CUDA cannot enqueue the host-to-device copy.
80 pub fn copy_from_pinned_scoped<'env, B>(
81 &'env mut self,
82 src: &'env B,
83 stream: &StreamScope<'_, 'env>,
84 ) -> Result<()>
85 where
86 B: PinnedHostSlice<T> + ?Sized,
87 T: DeviceRepr,
88 {
89 self.bind_stream(stream.stream())?;
90 let () = T::LAYOUT;
91 if HostSlice::len(src) != self.length {
92 return Err(Error::length_mismatch(
93 "host source",
94 self.length,
95 HostSlice::len(src),
96 ));
97 }
98
99 checked_bytes::<T>(self.length, "byte length")?;
100 if self.length == 0 {
101 return Ok(());
102 }
103
104 let accesses = [
105 Access::new(self.region(), AccessMode::Write),
106 Access::host(src.host_region(), AccessMode::Read),
107 ];
108 // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
109 unsafe {
110 stream.enqueue(&accesses, || {
111 Self::copy_async(
112 self.ptr,
113 src.as_host_ptr(),
114 self.length,
115 MemoryCopyKind::HostToDevice,
116 stream.stream(),
117 )
118 })
119 }
120 }
121
122 /// Enqueues a host-to-device copy of the entire allocation in a stream scope.
123 ///
124 /// The scope retains both borrows until the transfer completes.
125 ///
126 /// # Errors
127 ///
128 /// Returns an error if the element counts differ, the byte count overflows, or the scope’s stream belongs to another context.
129 /// Also propagates context-binding, scope submission, and CUDA copy errors.
130 pub fn copy_from_host_scoped<'env>(
131 &'env mut self,
132 host_slice: &'env [T],
133 stream: &StreamScope<'_, 'env>,
134 ) -> Result<()>
135 where
136 T: DeviceRepr,
137 {
138 let () = T::LAYOUT;
139 if host_slice.len() != self.len() {
140 return Err(Error::length_mismatch(
141 "host slice",
142 self.len(),
143 host_slice.len(),
144 ));
145 }
146
147 checked_bytes::<T>(self.len(), "byte length")?;
148 self.bind_stream(stream.stream())?;
149 if self.is_empty() {
150 return Ok(());
151 }
152
153 let accesses = [Access::new(self.region(), AccessMode::Write)];
154 // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
155 unsafe {
156 stream.enqueue(&accesses, || {
157 Self::copy_async(
158 self.ptr,
159 host_slice.as_ptr(),
160 self.len(),
161 MemoryCopyKind::HostToDevice,
162 stream.stream(),
163 )
164 })
165 }
166 }
167
168 /// Enqueues a copy of `host_slice` into this allocation on `stream`.
169 ///
170 /// # Safety
171 ///
172 /// The caller must ensure `self` and `host_slice` both remain valid until `stream` has completed the transfer.
173 ///
174 /// # Errors
175 ///
176 /// Returns an error if the host and device element counts differ, the stream belongs to another context, or the byte count overflows.
177 /// Also propagates context-binding, producer-ordering, and CUDA asynchronous copy errors.
178 pub unsafe fn copy_from_host_async(&mut self, host_slice: &[T], stream: &Stream) -> Result<()> {
179 self.bind_stream(stream)?;
180 if host_slice.len() != self.len() {
181 return Err(Error::length_mismatch(
182 "host slice",
183 self.len(),
184 host_slice.len(),
185 ));
186 }
187
188 if self.is_empty() {
189 return Ok(());
190 }
191
192 stream.join_regions(&[self.region()])?;
193 // SAFETY: the lengths match, `stream` is ordered after the allocation's producer, and the caller keeps both ranges valid until `stream` completes the copy.
194 unsafe {
195 Self::copy_async(
196 self.as_mut_ptr(),
197 host_slice.as_ptr(),
198 self.len(),
199 MemoryCopyKind::HostToDevice,
200 stream,
201 )
202 }
203 }
204
205 /// Copies all device elements into an equally sized host slice and waits for completion.
206 ///
207 /// # Errors
208 ///
209 /// Returns an error for unequal element counts or byte-size overflow.
210 /// Also propagates access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
211 /// A nonempty synchronous transfer is rejected during stream capture.
212 pub fn copy_to_host(&self, host_slice: &mut [T]) -> Result<()>
213 where
214 T: AnyBitPatternDeviceRepr,
215 {
216 transfer::copy_to_host(self, host_slice)
217 }
218
219 /// Copies device values to host storage under a kernel-specific validity contract.
220 ///
221 /// # Safety
222 ///
223 /// Every source element must be initialized and contain a valid value of `T`.
224 /// `T` must be transferable without duplicating ownership or host references.
225 ///
226 /// # Errors
227 ///
228 /// Returns an error if host and device element counts differ or the byte count overflows.
229 /// Also propagates access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
230 /// A nonempty synchronous transfer is rejected during stream capture.
231 pub unsafe fn copy_to_host_unchecked(&self, host_slice: &mut [T]) -> Result<()>
232 where
233 T: DeviceRepr,
234 {
235 // SAFETY: the caller vouches that every source element is a valid, transferable `T`.
236 unsafe { transfer::copy_to_host_unchecked(self, host_slice) }
237 }
238
239 /// Copies this device allocation into page-locked host memory.
240 ///
241 /// The destination length must match this allocation's length.
242 /// This is the pinned-memory-specific counterpart to [`DeviceMemory::copy_to_host`].
243 ///
244 /// # Errors
245 ///
246 /// Returns an error if the lengths differ, byte-size arithmetic overflows, or CUDA rejects the device-to-host copy.
247 pub fn copy_to_pinned<B>(&self, dst: &mut B) -> Result<()>
248 where
249 B: PinnedHostSliceMut<T> + ?Sized,
250 T: AnyBitPatternDeviceRepr,
251 {
252 let context = Arc::clone(self.context());
253 self.bind()?;
254 let () = T::LAYOUT;
255 if HostSlice::len(dst) != self.length {
256 return Err(Error::length_mismatch(
257 "host destination",
258 self.length,
259 HostSlice::len(dst),
260 ));
261 }
262
263 if self.length == 0 {
264 return Ok(());
265 }
266
267 checked_bytes::<T>(self.length, "byte length")?;
268 let _access = context.acquire_accesses(&[
269 Access::new(self.region(), AccessMode::Read),
270 Access::host(dst.host_region(), AccessMode::Write),
271 ])?;
272 // SAFETY: the guards acquired above cover both regions, and the lengths were checked to match.
273 unsafe {
274 transfer::copy_synchronous(
275 dst.as_host_mut_ptr(),
276 self.ptr,
277 self.length,
278 MemoryCopyKind::DeviceToHost,
279 None,
280 )
281 }
282 }
283
284 /// Enqueues a copy from this device allocation into page-locked host memory.
285 ///
286 /// The [`StreamScope`] ties the source and destination lifetimes to the queued copy.
287 ///
288 /// # Errors
289 ///
290 /// Returns an error if the lengths differ, byte-size arithmetic overflows, or CUDA cannot enqueue the device-to-host copy.
291 pub fn copy_to_pinned_scoped<'env, B>(
292 &'env self,
293 dst: &'env mut B,
294 stream: &StreamScope<'_, 'env>,
295 ) -> Result<()>
296 where
297 B: PinnedHostSliceMut<T> + ?Sized,
298 T: AnyBitPatternDeviceRepr,
299 {
300 self.bind_stream(stream.stream())?;
301 let () = T::LAYOUT;
302 if HostSlice::len(dst) != self.length {
303 return Err(Error::length_mismatch(
304 "host destination",
305 self.length,
306 HostSlice::len(dst),
307 ));
308 }
309
310 checked_bytes::<T>(self.length, "byte length")?;
311 if self.length == 0 {
312 return Ok(());
313 }
314
315 let accesses = [
316 Access::new(self.region(), AccessMode::Read),
317 Access::host(dst.host_region(), AccessMode::Write),
318 ];
319 // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
320 unsafe {
321 stream.enqueue(&accesses, || {
322 Self::copy_async(
323 dst.as_host_mut_ptr(),
324 self.ptr,
325 self.length,
326 MemoryCopyKind::DeviceToHost,
327 stream.stream(),
328 )
329 })
330 }
331 }
332
333 /// Enqueues a device-to-host copy of the entire allocation in a stream scope.
334 ///
335 /// The scope retains the source and exclusive destination borrows until the transfer completes.
336 ///
337 /// # Errors
338 ///
339 /// Returns an error if the element counts differ, the byte count overflows, or the scope’s stream belongs to another context.
340 /// Also propagates context-binding, scope submission, and CUDA copy errors.
341 pub fn copy_to_host_scoped<'env>(
342 &'env self,
343 host_slice: &'env mut [T],
344 stream: &StreamScope<'_, 'env>,
345 ) -> Result<()>
346 where
347 T: AnyBitPatternDeviceRepr,
348 {
349 let () = T::LAYOUT;
350 if host_slice.len() != self.len() {
351 return Err(Error::length_mismatch(
352 "host slice",
353 self.len(),
354 host_slice.len(),
355 ));
356 }
357
358 checked_bytes::<T>(self.len(), "byte length")?;
359 self.bind_stream(stream.stream())?;
360 if self.is_empty() {
361 return Ok(());
362 }
363
364 let accesses = [Access::new(self.region(), AccessMode::Read)];
365 // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
366 unsafe {
367 stream.enqueue(&accesses, || {
368 Self::copy_async(
369 host_slice.as_mut_ptr(),
370 self.ptr,
371 self.len(),
372 MemoryCopyKind::DeviceToHost,
373 stream.stream(),
374 )
375 })
376 }
377 }
378
379 /// Enqueues a copy of this allocation into `host_slice` on `stream`.
380 ///
381 /// # Safety
382 ///
383 /// The caller must ensure `self` and `host_slice` both remain valid until `stream` has completed the transfer.
384 /// Every source element must be initialized and valid for `T`, without Rust ownership or host references.
385 ///
386 /// # Errors
387 ///
388 /// Returns an error if the host and device element counts differ, the stream belongs to another context, or the byte count overflows.
389 /// Also propagates context-binding, producer-ordering, and CUDA asynchronous copy errors.
390 pub unsafe fn copy_to_host_async(&self, host_slice: &mut [T], stream: &Stream) -> Result<()> {
391 self.bind_stream(stream)?;
392 if host_slice.len() != self.len() {
393 return Err(Error::length_mismatch(
394 "host slice",
395 self.len(),
396 host_slice.len(),
397 ));
398 }
399
400 if self.is_empty() {
401 return Ok(());
402 }
403
404 stream.join_regions(&[self.region()])?;
405 // SAFETY: the lengths match, `stream` is ordered after the allocation's producer, and the caller keeps both ranges valid until `stream` completes and vouches for the source values.
406 unsafe {
407 Self::copy_async(
408 host_slice.as_mut_ptr(),
409 self.as_ptr(),
410 self.len(),
411 MemoryCopyKind::DeviceToHost,
412 stream,
413 )
414 }
415 }
416
417 /// Copies all device elements into a new host vector and waits for completion.
418 ///
419 /// # Errors
420 ///
421 /// Propagates byte-size overflow, access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
422 /// A nonempty synchronous transfer is rejected during stream capture.
423 pub fn copy_to_host_vec(&self) -> Result<Vec<T>>
424 where
425 T: AnyBitPatternDeviceRepr,
426 {
427 transfer::copy_to_host_vec(self)
428 }
429
430 /// Copies initialized device values into a host vector under a kernel-specific validity contract.
431 ///
432 /// # Safety
433 ///
434 /// Every source element must contain a valid value of `T`.
435 /// `T` must be transferable without duplicating ownership or host references.
436 ///
437 /// # Errors
438 ///
439 /// Propagates byte-size, access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
440 /// A nonempty synchronous transfer is rejected during stream capture.
441 pub unsafe fn copy_to_host_vec_unchecked(&self) -> Result<Vec<T>> {
442 let context = Arc::clone(self.context());
443 let _access = context.acquire_host_access(&[self.region()])?;
444 self.bind()?;
445 // SAFETY: the context is bound, the access guard orders tracked producers, `ptr` holds `length` elements, and the caller vouches that each is a valid `T`.
446 unsafe {
447 transfer::copy_to_host_vec_unchecked(self.ptr, self.length, self.region().stream())
448 }
449 }
450
451 /// Copies a disjoint device range into this allocation and waits for completion.
452 ///
453 /// # Errors
454 ///
455 /// Returns an error if contexts or element counts differ, the ranges overlap within one allocation, or the byte count overflows.
456 /// Also propagates access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
457 /// A nonempty synchronous transfer is rejected during stream capture.
458 pub fn copy_from_device<S>(&mut self, source: &S) -> Result<()>
459 where
460 T: DeviceRepr,
461 S: DeviceSlice<T> + ?Sized,
462 {
463 transfer::copy_device(self, source)
464 }
465
466 /// Enqueues a device-to-device copy of the entire allocation in a stream scope.
467 ///
468 /// The scope retains both borrows until the transfer completes.
469 ///
470 /// # Errors
471 ///
472 /// Returns an error if source and destination contexts or element counts differ, the byte count overflows, or the scope’s stream belongs to another context.
473 /// Also propagates context-binding, scope submission, and CUDA copy errors.
474 pub fn copy_from_device_scoped<'env>(
475 &'env mut self,
476 src: &'env Self,
477 stream: &StreamScope<'_, 'env>,
478 ) -> Result<()> {
479 if self.context() != src.context() {
480 return Err(Error::MemoryContextMismatch);
481 }
482
483 if src.len() != self.len() {
484 return Err(Error::length_mismatch("source", self.len(), src.len()));
485 }
486
487 checked_bytes::<T>(self.len(), "byte length")?;
488 self.bind_stream(stream.stream())?;
489 if self.is_empty() {
490 return Ok(());
491 }
492
493 let accesses = [
494 Access::new(self.region(), AccessMode::Write),
495 Access::new(src.region(), AccessMode::Read),
496 ];
497 // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
498 unsafe {
499 stream.enqueue(&accesses, || {
500 Self::copy_async(
501 self.ptr,
502 src.as_ptr(),
503 self.len(),
504 MemoryCopyKind::DeviceToDevice,
505 stream.stream(),
506 )
507 })
508 }
509 }
510
511 /// Enqueues a copy of `src` into this allocation on `stream`.
512 ///
513 /// # Safety
514 ///
515 /// The caller must ensure `self` and `src` both remain valid until `stream` has completed the transfer.
516 ///
517 /// # Errors
518 ///
519 /// Returns an error if source and destination contexts or element counts differ, the stream belongs to another context, or the byte count overflows.
520 /// Also propagates context-binding, producer-ordering, and CUDA asynchronous copy errors.
521 pub unsafe fn copy_from_device_async(&mut self, src: &Self, stream: &Stream) -> Result<()> {
522 if self.context() != src.context() {
523 return Err(Error::MemoryContextMismatch);
524 }
525
526 self.bind_stream(stream)?;
527 if src.len() != self.len() {
528 return Err(Error::length_mismatch("source", self.len(), src.len()));
529 }
530
531 if self.is_empty() {
532 return Ok(());
533 }
534
535 stream.join_regions(&[self.region(), src.region()])?;
536 // SAFETY: contexts and lengths match, `&mut self` keeps the ranges disjoint, `stream` is ordered after both producers, and the caller keeps both valid until `stream` completes.
537 unsafe {
538 Self::copy_async(
539 self.as_mut_ptr(),
540 src.as_ptr(),
541 self.len(),
542 MemoryCopyKind::DeviceToDevice,
543 stream,
544 )
545 }
546 }
547}