oxicuda-memory 0.1.0

OxiCUDA Memory - Type-safe GPU memory management with Rust ownership semantics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Virtual memory management for fine-grained GPU address space control.
//!
//! This module provides abstractions for CUDA's virtual memory management
//! API (`cuMemAddressReserve`, `cuMemCreate`, `cuMemMap`, etc.), which
//! allows separating the concepts of virtual address reservation and
//! physical memory allocation.
//!
//! # Concepts
//!
//! * **Virtual Address Range** — A reservation of contiguous virtual
//!   addresses in the GPU address space. No physical memory is committed
//!   until explicitly mapped.
//!
//! * **Physical Allocation** — A chunk of physical GPU memory that can
//!   be mapped to one or more virtual address ranges.
//!
//! * **Mapping** — The association of a physical allocation with a region
//!   of a virtual address range.
//!
//! # Use Cases
//!
//! * **Sparse arrays** — Reserve a large virtual range but only commit
//!   physical memory for the tiles/pages that are actually used.
//!
//! * **Resizable buffers** — Reserve a large virtual range up-front and
//!   map additional physical memory as the buffer grows, without changing
//!   the base address.
//!
//! * **Multi-GPU memory** — Map physical allocations from different devices
//!   into the same virtual address space.
//!
//! # Status
//!
//! The virtual memory driver functions are not yet loaded in
//! `oxicuda-driver`. All operations that would require driver calls
//! currently return [`CudaError::NotSupported`]. The data structures
//! are fully functional for planning and validation purposes.
//!
//! # Example
//!
//! ```rust,no_run
//! use oxicuda_memory::virtual_memory::{
//!     VirtualAddressRange, PhysicalAllocation, VirtualMemoryManager, AccessFlags,
//! };
//!
//! // Reserve 1 GiB of virtual address space with 2 MiB alignment.
//! let va = VirtualMemoryManager::reserve(1 << 30, 1 << 21)?;
//! assert_eq!(va.size(), 1 << 30);
//!
//! // The actual GPU calls are not yet available, so alloc/map/unmap
//! // return NotSupported.
//! # Ok::<(), oxicuda_driver::error::CudaError>(())
//! ```

use std::fmt;

use oxicuda_driver::error::{CudaError, CudaResult};

// ---------------------------------------------------------------------------
// AccessFlags
// ---------------------------------------------------------------------------

/// Memory access permission flags for virtual memory mappings.
///
/// These flags control how a mapped virtual address range can be accessed
/// by a given device.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum AccessFlags {
    /// No access permitted. The mapping exists but cannot be read or written.
    #[default]
    None,
    /// Read-only access. The device can read but not write.
    Read,
    /// Full read-write access.
    ReadWrite,
}

impl fmt::Display for AccessFlags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::None => write!(f, "None"),
            Self::Read => write!(f, "Read"),
            Self::ReadWrite => write!(f, "ReadWrite"),
        }
    }
}

// ---------------------------------------------------------------------------
// VirtualAddressRange
// ---------------------------------------------------------------------------

/// A reserved range of virtual addresses in the GPU address space.
///
/// This represents a contiguous block of virtual addresses that has been
/// reserved but not necessarily backed by physical memory. Physical memory
/// is associated with the range via [`VirtualMemoryManager::map`].
///
/// # Note
///
/// On systems without CUDA virtual memory support, the `base` address
/// is set to 0 and operations on the range will return
/// [`CudaError::NotSupported`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VirtualAddressRange {
    base: u64,
    size: usize,
    alignment: usize,
}

impl VirtualAddressRange {
    /// Returns the base virtual address of the range.
    #[inline]
    pub fn base(&self) -> u64 {
        self.base
    }

    /// Returns the size of the range in bytes.
    #[inline]
    pub fn size(&self) -> usize {
        self.size
    }

    /// Returns the alignment of the range in bytes.
    #[inline]
    pub fn alignment(&self) -> usize {
        self.alignment
    }

    /// Returns whether the range contains the given virtual address.
    pub fn contains(&self, addr: u64) -> bool {
        addr >= self.base && addr < self.base.saturating_add(self.size as u64)
    }

    /// Returns the end address (exclusive) of the range.
    #[inline]
    pub fn end(&self) -> u64 {
        self.base.saturating_add(self.size as u64)
    }
}

impl fmt::Display for VirtualAddressRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "VA[0x{:016x}..0x{:016x}, {} bytes, align={}]",
            self.base,
            self.end(),
            self.size,
            self.alignment,
        )
    }
}

// ---------------------------------------------------------------------------
// PhysicalAllocation
// ---------------------------------------------------------------------------

/// A physical memory allocation on a specific GPU device.
///
/// Physical allocations represent actual GPU VRAM that can be mapped
/// into virtual address ranges. Multiple virtual ranges can map to
/// the same physical allocation (aliasing).
///
/// # Note
///
/// On systems without CUDA virtual memory support, the `handle` is
/// set to 0 and the allocation is not backed by real memory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhysicalAllocation {
    handle: u64,
    size: usize,
    device_ordinal: i32,
}

impl PhysicalAllocation {
    /// Returns the opaque handle for this physical allocation.
    #[inline]
    pub fn handle(&self) -> u64 {
        self.handle
    }

    /// Returns the size of this allocation in bytes.
    #[inline]
    pub fn size(&self) -> usize {
        self.size
    }

    /// Returns the device ordinal this allocation belongs to.
    #[inline]
    pub fn device_ordinal(&self) -> i32 {
        self.device_ordinal
    }
}

impl fmt::Display for PhysicalAllocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "PhysAlloc[handle=0x{:016x}, {} bytes, dev={}]",
            self.handle, self.size, self.device_ordinal,
        )
    }
}

// ---------------------------------------------------------------------------
// MappingRecord — tracks virtual-to-physical mappings
// ---------------------------------------------------------------------------

/// A record of a virtual-to-physical memory mapping.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MappingRecord {
    /// Offset within the virtual address range where the mapping starts.
    pub va_offset: usize,
    /// Size of the mapped region in bytes.
    pub size: usize,
    /// Handle of the physical allocation backing this mapping.
    pub phys_handle: u64,
    /// Access permissions for this mapping.
    pub access: AccessFlags,
}

// ---------------------------------------------------------------------------
// VirtualMemoryManager
// ---------------------------------------------------------------------------

/// Manager for GPU virtual memory operations.
///
/// Provides methods for reserving virtual address ranges, allocating
/// physical memory, mapping/unmapping, and setting access permissions.
///
/// # Status
///
/// The underlying CUDA virtual memory driver functions
/// (`cuMemAddressReserve`, `cuMemCreate`, `cuMemMap`, `cuMemUnmap`,
/// `cuMemSetAccess`) are not yet loaded in `oxicuda-driver`. All
/// methods that would require driver calls return
/// [`CudaError::NotSupported`].
///
/// The [`reserve`](Self::reserve) method creates a local placeholder
/// object for planning purposes.
pub struct VirtualMemoryManager;

impl VirtualMemoryManager {
    /// Reserves a range of virtual addresses in the GPU address space.
    ///
    /// The reserved range is not backed by physical memory until
    /// [`map`](Self::map) is called.
    ///
    /// # Parameters
    ///
    /// * `size` - Size of the virtual range to reserve in bytes.
    ///   Must be a multiple of `alignment`.
    /// * `alignment` - Alignment requirement in bytes. Must be a power
    ///   of two and non-zero.
    ///
    /// # Errors
    ///
    /// * [`CudaError::InvalidValue`] if `size` is zero, `alignment` is
    ///   zero, `alignment` is not a power of two, or `size` is not a
    ///   multiple of `alignment`.
    pub fn reserve(size: usize, alignment: usize) -> CudaResult<VirtualAddressRange> {
        if size == 0 {
            return Err(CudaError::InvalidValue);
        }
        if alignment == 0 || !alignment.is_power_of_two() {
            return Err(CudaError::InvalidValue);
        }
        if size % alignment != 0 {
            return Err(CudaError::InvalidValue);
        }

        // TODO: call cuMemAddressReserve when available in DriverApi.
        // For now, create a placeholder with a synthetic base address.
        // We use a deterministic address based on size+alignment for
        // reproducible testing.
        let synthetic_base = 0x0000_7F00_0000_0000_u64
            .wrapping_add(size as u64)
            .wrapping_add(alignment as u64);

        Ok(VirtualAddressRange {
            base: synthetic_base,
            size,
            alignment,
        })
    }

    /// Releases a previously reserved virtual address range.
    ///
    /// After this call, the virtual addresses are no longer reserved
    /// and may be reused by future reservations.
    ///
    /// # Errors
    ///
    /// Returns [`CudaError::NotSupported`] because the driver function
    /// `cuMemAddressFree` is not yet loaded.
    pub fn release(_va: VirtualAddressRange) -> CudaResult<()> {
        // TODO: call cuMemAddressFree when available
        Err(CudaError::NotSupported)
    }

    /// Allocates physical memory on the specified device.
    ///
    /// The allocated memory is not accessible until mapped into a
    /// virtual address range via [`map`](Self::map).
    ///
    /// # Parameters
    ///
    /// * `size` - Size of the allocation in bytes. Must be non-zero.
    /// * `device_ordinal` - Ordinal of the device to allocate on.
    ///
    /// # Errors
    ///
    /// * [`CudaError::InvalidValue`] if `size` is zero.
    /// * [`CudaError::NotSupported`] because the driver function
    ///   `cuMemCreate` is not yet loaded.
    pub fn alloc_physical(size: usize, device_ordinal: i32) -> CudaResult<PhysicalAllocation> {
        if size == 0 {
            return Err(CudaError::InvalidValue);
        }
        // TODO: call cuMemCreate when available in DriverApi
        Err(CudaError::NotSupported)?;

        // This code is unreachable today but shows the intended return type.
        Ok(PhysicalAllocation {
            handle: 0,
            size,
            device_ordinal,
        })
    }

    /// Frees a physical memory allocation.
    ///
    /// The allocation must not be currently mapped to any virtual range.
    ///
    /// # Errors
    ///
    /// Returns [`CudaError::NotSupported`] because the driver function
    /// `cuMemRelease` is not yet loaded.
    pub fn free_physical(_phys: PhysicalAllocation) -> CudaResult<()> {
        // TODO: call cuMemRelease when available
        Err(CudaError::NotSupported)
    }

    /// Maps a physical allocation to a region of a virtual address range.
    ///
    /// After mapping, GPU kernels can access the virtual addresses and
    /// reads/writes will be routed to the physical memory.
    ///
    /// # Parameters
    ///
    /// * `va` - The virtual address range to map into.
    /// * `phys` - The physical allocation to map.
    /// * `offset` - Byte offset within the virtual range at which to
    ///   start the mapping. Must be aligned to the VA's alignment.
    ///
    /// # Errors
    ///
    /// * [`CudaError::InvalidValue`] if `offset` is not aligned, or if
    ///   the physical allocation would extend past the end of the virtual
    ///   range.
    /// * [`CudaError::NotSupported`] because the driver function
    ///   `cuMemMap` is not yet loaded.
    pub fn map(
        va: &VirtualAddressRange,
        phys: &PhysicalAllocation,
        offset: usize,
    ) -> CudaResult<()> {
        // Validate alignment
        if va.alignment > 0 && offset % va.alignment != 0 {
            return Err(CudaError::InvalidValue);
        }
        // Validate bounds
        let end = offset
            .checked_add(phys.size)
            .ok_or(CudaError::InvalidValue)?;
        if end > va.size {
            return Err(CudaError::InvalidValue);
        }
        // TODO: call cuMemMap when available
        Err(CudaError::NotSupported)
    }

    /// Unmaps a region of a virtual address range.
    ///
    /// After unmapping, accesses to the affected virtual addresses will
    /// fault. The physical memory is not freed — it can be remapped
    /// elsewhere.
    ///
    /// # Parameters
    ///
    /// * `va` - The virtual address range to unmap from.
    /// * `offset` - Byte offset within the range where unmapping starts.
    /// * `size` - Number of bytes to unmap.
    ///
    /// # Errors
    ///
    /// * [`CudaError::InvalidValue`] if the offset+size exceeds the
    ///   virtual range bounds.
    /// * [`CudaError::NotSupported`] because the driver function
    ///   `cuMemUnmap` is not yet loaded.
    pub fn unmap(va: &VirtualAddressRange, offset: usize, size: usize) -> CudaResult<()> {
        let end = offset.checked_add(size).ok_or(CudaError::InvalidValue)?;
        if end > va.size {
            return Err(CudaError::InvalidValue);
        }
        // TODO: call cuMemUnmap when available
        Err(CudaError::NotSupported)
    }

    /// Sets access permissions for a virtual address range on a device.
    ///
    /// This controls whether the specified device can read and/or write
    /// to the mapped virtual addresses.
    ///
    /// # Parameters
    ///
    /// * `va` - The virtual address range to set permissions on.
    /// * `device_ordinal` - The device to grant/deny access for.
    /// * `flags` - The access permission flags.
    ///
    /// # Errors
    ///
    /// Returns [`CudaError::NotSupported`] because the driver function
    /// `cuMemSetAccess` is not yet loaded.
    pub fn set_access(
        _va: &VirtualAddressRange,
        _device_ordinal: i32,
        _flags: AccessFlags,
    ) -> CudaResult<()> {
        // TODO: call cuMemSetAccess when available
        Err(CudaError::NotSupported)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reserve_valid_range() {
        let va = VirtualMemoryManager::reserve(4096, 4096);
        assert!(va.is_ok());
        let va = va.ok();
        assert!(va.is_some());
        if let Some(va) = va {
            assert_eq!(va.size(), 4096);
            assert_eq!(va.alignment(), 4096);
            assert!(va.base() > 0);
        }
    }

    #[test]
    fn reserve_zero_size_fails() {
        let result = VirtualMemoryManager::reserve(0, 4096);
        assert_eq!(result, Err(CudaError::InvalidValue));
    }

    #[test]
    fn reserve_zero_alignment_fails() {
        let result = VirtualMemoryManager::reserve(4096, 0);
        assert_eq!(result, Err(CudaError::InvalidValue));
    }

    #[test]
    fn reserve_non_power_of_two_alignment_fails() {
        let result = VirtualMemoryManager::reserve(4096, 3);
        assert_eq!(result, Err(CudaError::InvalidValue));
    }

    #[test]
    fn reserve_misaligned_size_fails() {
        // 4096+1 is not a multiple of 4096
        let result = VirtualMemoryManager::reserve(4097, 4096);
        assert_eq!(result, Err(CudaError::InvalidValue));
    }

    #[test]
    fn reserve_large_range() {
        // Reserve 1 GiB with 2 MiB alignment.
        let gib = 1 << 30;
        let mib2 = 1 << 21;
        let va = VirtualMemoryManager::reserve(gib, mib2);
        assert!(va.is_ok());
        if let Ok(va) = va {
            assert_eq!(va.size(), gib);
            assert_eq!(va.alignment(), mib2);
        }
    }

    #[test]
    fn virtual_address_range_contains() {
        let va = VirtualMemoryManager::reserve(8192, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            assert!(va.contains(va.base()));
            assert!(va.contains(va.base() + 1));
            assert!(va.contains(va.base() + 8191));
            assert!(!va.contains(va.end()));
            assert!(!va.contains(va.base().wrapping_sub(1)));
        }
    }

    #[test]
    fn virtual_address_range_end() {
        let va = VirtualMemoryManager::reserve(4096, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            assert_eq!(va.end(), va.base() + 4096);
        }
    }

    #[test]
    fn virtual_address_range_display() {
        let va = VirtualMemoryManager::reserve(4096, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            let disp = format!("{va}");
            assert!(disp.contains("VA["));
            assert!(disp.contains("4096 bytes"));
        }
    }

    #[test]
    fn alloc_physical_zero_size_fails() {
        let result = VirtualMemoryManager::alloc_physical(0, 0);
        assert_eq!(result, Err(CudaError::InvalidValue));
    }

    #[test]
    fn alloc_physical_returns_not_supported() {
        let result = VirtualMemoryManager::alloc_physical(4096, 0);
        assert_eq!(result, Err(CudaError::NotSupported));
    }

    #[test]
    fn release_returns_not_supported() {
        let va = VirtualMemoryManager::reserve(4096, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            let result = VirtualMemoryManager::release(va);
            assert_eq!(result, Err(CudaError::NotSupported));
        }
    }

    #[test]
    fn map_validates_alignment() {
        let va = VirtualMemoryManager::reserve(8192, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            let phys = PhysicalAllocation {
                handle: 1,
                size: 4096,
                device_ordinal: 0,
            };
            // Offset 1 is not aligned to 4096
            let result = VirtualMemoryManager::map(&va, &phys, 1);
            assert_eq!(result, Err(CudaError::InvalidValue));
        }
    }

    #[test]
    fn map_validates_bounds() {
        let va = VirtualMemoryManager::reserve(4096, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            let phys = PhysicalAllocation {
                handle: 1,
                size: 8192, // larger than VA range
                device_ordinal: 0,
            };
            let result = VirtualMemoryManager::map(&va, &phys, 0);
            assert_eq!(result, Err(CudaError::InvalidValue));
        }
    }

    #[test]
    fn map_returns_not_supported_when_valid() {
        let va = VirtualMemoryManager::reserve(8192, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            let phys = PhysicalAllocation {
                handle: 1,
                size: 4096,
                device_ordinal: 0,
            };
            let result = VirtualMemoryManager::map(&va, &phys, 0);
            assert_eq!(result, Err(CudaError::NotSupported));
        }
    }

    #[test]
    fn unmap_validates_bounds() {
        let va = VirtualMemoryManager::reserve(4096, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            let result = VirtualMemoryManager::unmap(&va, 0, 8192);
            assert_eq!(result, Err(CudaError::InvalidValue));
        }
    }

    #[test]
    fn unmap_returns_not_supported_when_valid() {
        let va = VirtualMemoryManager::reserve(4096, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            let result = VirtualMemoryManager::unmap(&va, 0, 4096);
            assert_eq!(result, Err(CudaError::NotSupported));
        }
    }

    #[test]
    fn set_access_returns_not_supported() {
        let va = VirtualMemoryManager::reserve(4096, 4096);
        assert!(va.is_ok());
        if let Ok(va) = va {
            let result = VirtualMemoryManager::set_access(&va, 0, AccessFlags::ReadWrite);
            assert_eq!(result, Err(CudaError::NotSupported));
        }
    }

    #[test]
    fn access_flags_default() {
        assert_eq!(AccessFlags::default(), AccessFlags::None);
    }

    #[test]
    fn access_flags_display() {
        assert_eq!(format!("{}", AccessFlags::None), "None");
        assert_eq!(format!("{}", AccessFlags::Read), "Read");
        assert_eq!(format!("{}", AccessFlags::ReadWrite), "ReadWrite");
    }

    #[test]
    fn physical_allocation_display() {
        let phys = PhysicalAllocation {
            handle: 0x1234,
            size: 4096,
            device_ordinal: 0,
        };
        let disp = format!("{phys}");
        assert!(disp.contains("4096 bytes"));
        assert!(disp.contains("dev=0"));
    }

    #[test]
    fn mapping_record_fields() {
        let record = MappingRecord {
            va_offset: 0,
            size: 4096,
            phys_handle: 42,
            access: AccessFlags::ReadWrite,
        };
        assert_eq!(record.va_offset, 0);
        assert_eq!(record.size, 4096);
        assert_eq!(record.phys_handle, 42);
        assert_eq!(record.access, AccessFlags::ReadWrite);
    }

    #[test]
    fn free_physical_returns_not_supported() {
        let phys = PhysicalAllocation {
            handle: 1,
            size: 4096,
            device_ordinal: 0,
        };
        let result = VirtualMemoryManager::free_physical(phys);
        assert_eq!(result, Err(CudaError::NotSupported));
    }
}