system.rs 8.1 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
// SPDX-License-Identifier: Apache-2.0

//! System memory storage backed by malloc.

6
use super::{MemoryDescriptor, Result, StorageError, StorageKind, actions, nixl::NixlDescriptor};
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
use std::any::Any;
use std::ptr::NonNull;

/// System memory allocated via malloc.
#[derive(Debug)]
pub struct SystemStorage {
    ptr: NonNull<u8>,
    len: usize,
}

unsafe impl Send for SystemStorage {}
unsafe impl Sync for SystemStorage {}

impl SystemStorage {
    /// Allocate new system memory of the given size.
    pub fn new(len: usize) -> Result<Self> {
        if len == 0 {
            return Err(StorageError::AllocationFailed(
                "zero-sized allocations are not supported".into(),
            ));
        }

        let mut ptr: *mut libc::c_void = std::ptr::null_mut();

        // We need 4KB alignment here for NIXL disk transfers to work.
        // The O_DIRECT flag is required for GDS.
        // However, a limitation of this flag is that all operations involving disk
        // (both read and write) must be page-aligned.
        // Pinned memory is already page-aligned, so we only need to align system memory.
        // TODO(jthomson04): Is page size always 4KB?

        // SAFETY: malloc returns suitably aligned memory or null on failure.
        let result = unsafe { libc::posix_memalign(&mut ptr, 4096, len) };
        if result != 0 {
            return Err(StorageError::AllocationFailed(format!(
                "posix_memalign failed for size {}",
                len
            )));
        }
        let ptr = NonNull::new(ptr as *mut u8).ok_or_else(|| {
            StorageError::AllocationFailed(format!("malloc failed for size {}", len))
        })?;

        // Zero-initialize the memory
        unsafe {
            std::ptr::write_bytes(ptr.as_ptr(), 0, len);
        }

        Ok(Self { ptr, len })
    }

    /// Get a pointer to the underlying memory.
    ///
    /// # Safety
    /// The caller must ensure the pointer is not used after this storage is dropped.
    pub unsafe fn as_ptr(&self) -> *const u8 {
        self.ptr.as_ptr()
    }

    /// Get a mutable pointer to the underlying memory.
    ///
    /// # Safety
    /// The caller must ensure the pointer is not used after this storage is dropped
    /// and that there are no other references to this memory.
    pub unsafe fn as_mut_ptr(&mut self) -> *mut u8 {
        self.ptr.as_ptr()
    }
}

impl Drop for SystemStorage {
    fn drop(&mut self) {
        // SAFETY: pointer was allocated by malloc.
        unsafe {
            libc::free(self.ptr.as_ptr() as *mut libc::c_void);
        }
    }
}

85
impl MemoryDescriptor for SystemStorage {
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
    fn addr(&self) -> usize {
        self.ptr.as_ptr() as usize
    }

    fn size(&self) -> usize {
        self.len
    }

    fn storage_kind(&self) -> StorageKind {
        StorageKind::System
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn nixl_descriptor(&self) -> Option<NixlDescriptor> {
        None
    }
}

// Support for NIXL registration
impl super::nixl::NixlCompatible for SystemStorage {
    fn nixl_params(&self) -> (*const u8, usize, nixl_sys::MemType, u64) {
        (self.ptr.as_ptr(), self.len, nixl_sys::MemType::Dram, 0)
    }
}

impl actions::Memset for SystemStorage {
    fn memset(&mut self, value: u8, offset: usize, size: usize) -> Result<()> {
        let end = offset
            .checked_add(size)
            .ok_or_else(|| StorageError::OperationFailed("memset: offset overflow".into()))?;
        if end > self.len {
            return Err(StorageError::OperationFailed(
                "memset: offset + size > storage size".into(),
            ));
        }
        unsafe {
            let ptr = self.ptr.as_ptr().add(offset);
            std::ptr::write_bytes(ptr, value, size);
        }
        Ok(())
    }
}

impl actions::Slice for SystemStorage {
    unsafe fn as_slice(&self) -> Result<&[u8]> {
        // SAFETY: SystemStorage owns the memory allocated via the global allocator.
        // The memory remains valid as long as this SystemStorage instance exists.
        // The ptr is guaranteed to be valid for `self.len` bytes.
        // Caller must ensure no concurrent mutable access per trait contract.
        // SAFETY: The pointer is valid, properly aligned, and points to `self.len` bytes.
        Ok(unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) })
    }
}
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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::actions::{Memset, Slice};

    #[test]
    fn test_system_storage_new() {
        let storage = SystemStorage::new(1024).expect("allocation should succeed");
        assert_eq!(storage.size(), 1024);
        assert!(storage.addr() != 0);
    }

    #[test]
    fn test_system_storage_zero_size_fails() {
        let result = SystemStorage::new(0);
        assert!(result.is_err());
    }

    #[test]
    fn test_system_storage_storage_kind() {
        let storage = SystemStorage::new(1024).unwrap();
        assert_eq!(storage.storage_kind(), StorageKind::System);
    }

    #[test]
    fn test_system_storage_as_any() {
        let storage = SystemStorage::new(1024).unwrap();
        let any = storage.as_any();
        assert!(any.downcast_ref::<SystemStorage>().is_some());
    }

    #[test]
    fn test_system_storage_nixl_descriptor() {
        let storage = SystemStorage::new(1024).unwrap();
        // Unregistered storage has no NIXL descriptor
        assert!(storage.nixl_descriptor().is_none());
    }

    #[test]
    fn test_system_storage_as_ptr() {
        let storage = SystemStorage::new(1024).unwrap();
        unsafe {
            let ptr = storage.as_ptr();
            assert!(!ptr.is_null());
            assert_eq!(ptr as usize, storage.addr());
        }
    }

    #[test]
    fn test_system_storage_as_mut_ptr() {
        let mut storage = SystemStorage::new(1024).unwrap();
        unsafe {
            let ptr = storage.as_mut_ptr();
            assert!(!ptr.is_null());
            assert_eq!(ptr as usize, storage.addr());

            // Write and read back to verify the pointer works
            *ptr = 0xAB;
            assert_eq!(*ptr, 0xAB);
        }
    }

    #[test]
    fn test_system_storage_zero_initialized() {
        let storage = SystemStorage::new(1024).unwrap();
        unsafe {
            let slice = storage.as_slice().unwrap();
            // Memory should be zero-initialized
            assert!(slice.iter().all(|&b| b == 0));
        }
    }

    #[test]
    fn test_system_storage_memset_and_read() {
        let mut storage = SystemStorage::new(1024).unwrap();
        storage.memset(0xCD, 0, 1024).unwrap();

        unsafe {
            let slice = storage.as_slice().unwrap();
            assert!(slice.iter().all(|&b| b == 0xCD));
        }
    }

    #[test]
    fn test_system_storage_multiple_allocations_independent() {
        let storage1 = SystemStorage::new(512).unwrap();
        let storage2 = SystemStorage::new(512).unwrap();

        // Different allocations should have different addresses
        assert_ne!(storage1.addr(), storage2.addr());
    }

    #[test]
    fn test_system_storage_alignment() {
        let storage = SystemStorage::new(1024).unwrap();
        // posix_memalign allocates with 4096-byte alignment
        assert!(storage.addr().is_multiple_of(4096));
    }

    #[test]
    fn test_system_storage_nixl_compatible() {
        use crate::nixl::NixlCompatible;

        let storage = SystemStorage::new(2048).unwrap();
        let (ptr, size, mem_type, device_id) = storage.nixl_params();

        assert_eq!(ptr as usize, storage.addr());
        assert_eq!(size, 2048);
        assert_eq!(mem_type, nixl_sys::MemType::Dram);
        assert_eq!(device_id, 0);
    }

    #[test]
    fn test_system_storage_large_allocation() {
        // Allocate 1MB to test larger sizes
        let storage = SystemStorage::new(1024 * 1024).unwrap();
        assert_eq!(storage.size(), 1024 * 1024);
    }

    #[test]
    fn test_system_storage_debug() {
        let storage = SystemStorage::new(1024).unwrap();
        let debug_str = format!("{:?}", storage);
        assert!(debug_str.contains("SystemStorage"));
    }
}