view.rs 7.1 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Block storage management.
//!
//! This module provides the implementation for managing collections of blocks
//! and their storage. It handles the relationship between storage, layout,
//! and individual blocks.

Ryan Olson's avatar
Ryan Olson committed
22
23
use super::{BlockDataExt, BlockError, Storage};
use crate::block_manager::storage::StorageType;
Ryan Olson's avatar
Ryan Olson committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

pub trait Kind: std::marker::Sized + std::fmt::Debug + Clone + Copy + Send + Sync {}

#[derive(Debug, Clone, Copy)]
pub struct BlockKind;
impl Kind for BlockKind {}

#[derive(Debug, Clone, Copy)]
pub struct LayerKind;
impl Kind for LayerKind {}

pub type BlockView<'a, S> = MemoryView<'a, S, BlockKind>;
pub type BlockViewMut<'a, S> = MemoryViewMut<'a, S, BlockKind>;

pub type LayerView<'a, S> = MemoryView<'a, S, LayerKind>;
pub type LayerViewMut<'a, S> = MemoryViewMut<'a, S, LayerKind>;

/// Storage view that provides safe access to a region of storage
#[derive(Debug)]
pub struct MemoryView<'a, S: Storage, K: Kind> {
Ryan Olson's avatar
Ryan Olson committed
44
    _block_data: &'a dyn BlockDataExt<S>,
Ryan Olson's avatar
Ryan Olson committed
45
46
    addr: usize,
    size: usize,
Ryan Olson's avatar
Ryan Olson committed
47
    storage_type: StorageType,
Ryan Olson's avatar
Ryan Olson committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    kind: std::marker::PhantomData<K>,
}

impl<'a, S, K> MemoryView<'a, S, K>
where
    S: Storage,
    K: Kind,
{
    /// Create a new storage view
    ///
    /// # Safety
    /// The caller must ensure:
    /// - addr + size <= storage.size()
    /// - The view does not outlive the storage
    pub(crate) unsafe fn new(
Ryan Olson's avatar
Ryan Olson committed
63
        _block_data: &'a dyn BlockDataExt<S>,
Ryan Olson's avatar
Ryan Olson committed
64
65
        addr: usize,
        size: usize,
Ryan Olson's avatar
Ryan Olson committed
66
        storage_type: StorageType,
Ryan Olson's avatar
Ryan Olson committed
67
68
69
70
71
    ) -> Result<Self, BlockError> {
        Ok(Self {
            _block_data,
            addr,
            size,
Ryan Olson's avatar
Ryan Olson committed
72
            storage_type,
Ryan Olson's avatar
Ryan Olson committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
            kind: std::marker::PhantomData,
        })
    }

    /// Get a raw pointer to the view's data
    ///
    /// # Safety
    /// The caller must ensure:
    /// - The pointer is not used after the view is dropped
    /// - Access patterns respect the storage's thread safety model
    pub unsafe fn as_ptr(&self) -> *const u8 {
        self.addr as *const u8
    }

    /// Size of the view in bytes
    pub fn size(&self) -> usize {
        self.size
    }
}

/// Mutable storage view that provides exclusive access to a region of storage
#[derive(Debug)]
pub struct MemoryViewMut<'a, S: Storage, K: Kind> {
Ryan Olson's avatar
Ryan Olson committed
96
    _block_data: &'a mut dyn BlockDataExt<S>,
Ryan Olson's avatar
Ryan Olson committed
97
98
    addr: usize,
    size: usize,
Ryan Olson's avatar
Ryan Olson committed
99
    storage_type: StorageType,
Ryan Olson's avatar
Ryan Olson committed
100
101
102
103
104
105
106
107
108
109
110
111
    kind: std::marker::PhantomData<K>,
}

impl<'a, S: Storage, K: Kind> MemoryViewMut<'a, S, K> {
    /// Create a new mutable storage view
    ///
    /// # Safety
    /// The caller must ensure:
    /// - addr + size <= storage.size()
    /// - The view does not outlive the storage
    /// - No other views exist for this region
    pub(crate) unsafe fn new(
Ryan Olson's avatar
Ryan Olson committed
112
        _block_data: &'a mut dyn BlockDataExt<S>,
Ryan Olson's avatar
Ryan Olson committed
113
114
        addr: usize,
        size: usize,
Ryan Olson's avatar
Ryan Olson committed
115
        storage_type: StorageType,
Ryan Olson's avatar
Ryan Olson committed
116
117
118
119
120
    ) -> Result<Self, BlockError> {
        Ok(Self {
            _block_data,
            addr,
            size,
Ryan Olson's avatar
Ryan Olson committed
121
            storage_type,
Ryan Olson's avatar
Ryan Olson committed
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
            kind: std::marker::PhantomData,
        })
    }

    /// Get a raw mutable pointer to the view's data
    ///
    /// # Safety
    /// The caller must ensure:
    /// - The pointer is not used after the view is dropped
    /// - No other references exist while the pointer is in use
    /// - Access patterns respect the storage's thread safety model
    pub unsafe fn as_mut_ptr(&mut self) -> *mut u8 {
        self.addr as *mut u8
    }

    /// Size of the view in bytes
    pub fn size(&self) -> usize {
        self.size
    }
}

mod nixl {
    use super::*;

    use super::super::nixl::*;

Ryan Olson's avatar
Ryan Olson committed
148
    pub use crate::block_manager::storage::StorageType;
Ryan Olson's avatar
Ryan Olson committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    pub use nixl_sys::{MemType, MemoryRegion, NixlDescriptor};

    impl<S: Storage, K: Kind> MemoryRegion for MemoryView<'_, S, K> {
        unsafe fn as_ptr(&self) -> *const u8 {
            self.addr as *const u8
        }

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

    impl<S, K> NixlDescriptor for MemoryView<'_, S, K>
    where
        S: Storage + NixlDescriptor,
        K: Kind,
    {
        fn mem_type(&self) -> MemType {
Ryan Olson's avatar
Ryan Olson committed
167
            self._block_data.storage_type().nixl_mem_type()
Ryan Olson's avatar
Ryan Olson committed
168
169
170
        }

        fn device_id(&self) -> u64 {
Ryan Olson's avatar
Ryan Olson committed
171
172
173
174
175
176
            match self.storage_type {
                StorageType::System | StorageType::Pinned => 0,
                StorageType::Device(device_id) => device_id as u64,
                StorageType::Disk(fd) => fd,
                _ => panic!("Invalid storage type"),
            }
Ryan Olson's avatar
Ryan Olson committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
        }
    }

    impl<S: Storage, K: Kind> MemoryRegion for MemoryViewMut<'_, S, K> {
        unsafe fn as_ptr(&self) -> *const u8 {
            self.addr as *const u8
        }

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

    impl<S: Storage, K: Kind> NixlDescriptor for MemoryViewMut<'_, S, K>
    where
        S: Storage + NixlDescriptor,
        K: Kind,
    {
        fn mem_type(&self) -> MemType {
Ryan Olson's avatar
Ryan Olson committed
196
            self._block_data.storage_type().nixl_mem_type()
Ryan Olson's avatar
Ryan Olson committed
197
198
199
        }

        fn device_id(&self) -> u64 {
Ryan Olson's avatar
Ryan Olson committed
200
201
202
203
204
205
            match self.storage_type {
                StorageType::System | StorageType::Pinned => 0,
                StorageType::Device(device_id) => device_id as u64,
                StorageType::Disk(fd) => fd,
                _ => panic!("Invalid storage type"),
            }
Ryan Olson's avatar
Ryan Olson committed
206
207
208
209
210
211
212
213
214
215
216
        }
    }

    impl<'a, S, K> MemoryView<'a, S, K>
    where
        S: Storage + NixlDescriptor, // Ensure the underlying storage is a NixlDescriptor
        K: Kind,
    {
        /// Creates an immutable NIXL memory descriptor from this view.
        pub fn as_nixl_descriptor(&self) -> NixlMemoryDescriptor<'a, K, IsImmutable> {
            NixlMemoryDescriptor::new(
Ryan Olson's avatar
Ryan Olson committed
217
218
219
220
                self.addr as u64, // Address from the view
                self.size(),      // Size from the view
                self.mem_type(),
                self.device_id(),
Ryan Olson's avatar
Ryan Olson committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
            )
        }
    }

    impl<'a, S, K> MemoryViewMut<'a, S, K>
    where
        S: Storage + NixlDescriptor,
        K: Kind,
    {
        /// Creates a mutable NIXL memory descriptor from this view.
        // Note: We return a mutable descriptor even from an immutable borrow (&self)
        // because the underlying memory region *can* be mutated.
        pub fn as_nixl_descriptor_mut(&mut self) -> NixlMemoryDescriptor<'a, K, IsMutable> {
            NixlMemoryDescriptor::new(
                self.addr as u64,
                self.size(),
Ryan Olson's avatar
Ryan Olson committed
237
238
                self.mem_type(),
                self.device_id(),
Ryan Olson's avatar
Ryan Olson committed
239
240
241
242
            )
        }
    }
}