xref: /linux/drivers/gpu/nova-core/mm/vmm.rs (revision d669686f8170c234edf12212fac9180ea18b1448)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Virtual Memory Manager for NVIDIA GPU page table management.
4 //!
5 //! The [`Vmm`] provides high-level page mapping and unmapping operations for GPU
6 //! virtual address spaces (Channels, BAR1, BAR2).
7 
8 use kernel::{
9     gpu::buddy::AllocatedBlocks,
10     maple_tree::MapleTreeAlloc,
11     prelude::*,
12     rbtree::RBTree, //
13 };
14 
15 use core::{
16     cell::Cell,
17     ops::Range, //
18 };
19 
20 use crate::{
21     mm::{
22         pagetable::{
23             map::{
24                 PtMap, //
25             },
26             walk::{
27                 PtWalk,
28                 WalkResult, //
29             },
30             MmuVersion, //
31         },
32         GpuMm,
33         Pfn,
34         Vfn,
35         VramAddress,
36         PAGE_SIZE, //
37     },
38     num::{
39         IntoSafeCast, //
40     },
41 };
42 
43 /// Multi-page prepared mapping -- VA range allocated, ready for execute.
44 ///
45 /// Produced by [`Vmm::prepare_map()`], consumed by [`Vmm::execute_map()`].
46 /// The VA space allocation is tracked in the [`Vmm`]'s maple tree and freed
47 /// on error or via [`Vmm::unmap_pages()`].
48 ///
49 /// Dropping without calling [`Vmm::execute_map()`] logs a warning and leaks
50 /// the VA range in the maple tree.
51 pub(crate) struct PreparedMapping {
52     vfn_start: Vfn,
53     num_pages: usize,
54     /// Logs a warning if dropped without executing.
55     _drop_guard: MustExecuteGuard,
56 }
57 
58 /// Result of a mapping operation -- tracks the active mapped range.
59 ///
60 /// Returned by [`Vmm::execute_map()`] and [`Vmm::map_pages()`].
61 /// Callers must call [`Vmm::unmap_pages()`] before dropping to invalidate
62 /// PTEs and free the VA range. Dropping without unmapping logs a warning
63 /// and leaks the VA range in the maple tree.
64 pub(crate) struct MappedRange {
65     pub(super) vfn_start: Vfn,
66     pub(super) num_pages: usize,
67     /// Logs a warning if dropped without unmapping.
68     _drop_guard: MustUnmapGuard,
69 }
70 
71 /// Guard that logs a warning if a [`PreparedMapping`] is dropped without
72 /// being consumed by [`Vmm::execute_map()`].
73 struct MustExecuteGuard {
74     armed: Cell<bool>,
75 }
76 
77 impl MustExecuteGuard {
78     const fn new() -> Self {
79         Self {
80             armed: Cell::new(true),
81         }
82     }
83 
84     fn disarm(&self) {
85         self.armed.set(false);
86     }
87 }
88 
89 impl Drop for MustExecuteGuard {
90     fn drop(&mut self) {
91         if self.armed.get() {
92             kernel::pr_warn!("PreparedMapping dropped without calling execute_map()\n");
93         }
94     }
95 }
96 
97 /// Guard that logs a warning if a [`MappedRange`] is dropped without
98 /// calling [`Vmm::unmap_pages()`].
99 struct MustUnmapGuard {
100     armed: Cell<bool>,
101 }
102 
103 impl MustUnmapGuard {
104     const fn new() -> Self {
105         Self {
106             armed: Cell::new(true),
107         }
108     }
109 
110     fn disarm(&self) {
111         self.armed.set(false);
112     }
113 }
114 
115 impl Drop for MustUnmapGuard {
116     fn drop(&mut self) {
117         if self.armed.get() {
118             kernel::pr_warn!("MappedRange dropped without calling unmap_pages()\n");
119         }
120     }
121 }
122 
123 /// Virtual Memory Manager for a GPU address space.
124 ///
125 /// Each [`Vmm`] instance manages a single address space identified by its Page
126 /// Directory Base (`PDB`) address. Used for Channel, BAR1 and BAR2 mappings.
127 pub(crate) struct Vmm {
128     /// Page Directory Base address for this address space.
129     #[expect(dead_code)]
130     pdb_addr: VramAddress,
131     /// Page table walker for reading existing mappings.
132     pt_walk: PtWalk,
133     /// Page table mapper for prepare/execute operations.
134     pt_map: PtMap,
135     /// Page table allocations required for mappings.
136     page_table_allocs: KVec<Pin<KBox<AllocatedBlocks>>>,
137     /// Maple tree allocator for virtual address range tracking.
138     virt_alloc: Pin<KBox<MapleTreeAlloc<()>>>,
139     /// Total number of pages in the virtual address space.
140     va_pages: usize,
141     /// Prepared PT pages pending PDE installation, keyed by `install_addr`.
142     ///
143     /// Populated during prepare phase and drained in execute phase. Shared by all
144     /// pending maps, preventing races on the same PDE slot.
145     pt_pages: RBTree<VramAddress, super::pagetable::map::PreparedPtPage>,
146 }
147 
148 impl Vmm {
149     /// Create a new [`Vmm`] for the given Page Directory Base address.
150     ///
151     /// The [`Vmm`] will manage a virtual address space of `va_size` bytes.
152     pub(crate) fn new(
153         pdb_addr: VramAddress,
154         mmu_version: MmuVersion,
155         va_size: u64,
156     ) -> Result<Self> {
157         let page_size: u64 = PAGE_SIZE.into_safe_cast();
158         let va_pages: usize = (va_size / page_size).into_safe_cast();
159         let virt_alloc = KBox::pin_init(MapleTreeAlloc::<()>::new(), GFP_KERNEL)?;
160 
161         Ok(Self {
162             pdb_addr,
163             pt_walk: PtWalk::new(pdb_addr, mmu_version),
164             pt_map: PtMap::new(pdb_addr, mmu_version),
165             page_table_allocs: KVec::new(),
166             virt_alloc,
167             va_pages,
168             pt_pages: RBTree::new(),
169         })
170     }
171 
172     /// Allocate a contiguous virtual frame number range.
173     fn alloc_vfn_range(&self, num_pages: usize, va_range: Option<Range<u64>>) -> Result<Vfn> {
174         let page_size: u64 = PAGE_SIZE.into_safe_cast();
175 
176         let start_vfn = match va_range {
177             Some(r) => {
178                 let num_pages_u64: u64 = num_pages.into_safe_cast();
179                 let size = num_pages_u64.checked_mul(page_size).ok_or(EOVERFLOW)?;
180                 let range_size = r.end.checked_sub(r.start).ok_or(EOVERFLOW)?;
181                 if range_size != size {
182                     return Err(EINVAL);
183                 }
184                 let start_vfn: usize = (r.start / page_size).into_safe_cast();
185                 let end_vfn: usize = (r.end / page_size).into_safe_cast();
186                 self.virt_alloc
187                     .insert_range(start_vfn..end_vfn, (), GFP_KERNEL)?;
188                 start_vfn
189             }
190             None => self
191                 .virt_alloc
192                 .alloc_range(num_pages, (), ..self.va_pages, GFP_KERNEL)?,
193         };
194 
195         Ok(Vfn::new(start_vfn.into_safe_cast()))
196     }
197 
198     /// Free a virtual frame number range back to the maple tree.
199     fn free_vfn(&self, vfn: Vfn) {
200         let vfn_index: usize = vfn.raw().into_safe_cast();
201         if self.virt_alloc.erase(vfn_index).is_none() {
202             kernel::pr_warn!("free_vfn: VFN {} not found in maple tree\n", vfn_index);
203         }
204     }
205 
206     /// Read the [`Pfn`] for a mapped [`Vfn`] if one is mapped.
207     pub(super) fn read_mapping(&self, mm: &mut GpuMm<'_>, vfn: Vfn) -> Result<Option<Pfn>> {
208         match self.pt_walk.walk_to_pte(mm, vfn)? {
209             WalkResult::Mapped { pfn, .. } => Ok(Some(pfn)),
210             WalkResult::Unmapped { .. } | WalkResult::PageTableMissing => Ok(None),
211         }
212     }
213 
214     /// Prepare resources for mapping `num_pages` pages.
215     ///
216     /// Allocates a contiguous VA range, then walks the hierarchy per-VFN to prepare pages
217     /// for all missing PDEs. Returns a [`PreparedMapping`] with the VA allocation.
218     ///
219     /// If `va_range` is not `None`, the VA range is constrained to the given range. Safe
220     /// to call outside the fence signalling critical path.
221     pub(crate) fn prepare_map(
222         &mut self,
223         mm: &mut GpuMm<'_>,
224         num_pages: usize,
225         va_range: Option<Range<u64>>,
226     ) -> Result<PreparedMapping> {
227         if num_pages == 0 {
228             return Err(EINVAL);
229         }
230 
231         // Allocate contiguous VA range.
232         let vfn_start = self.alloc_vfn_range(num_pages, va_range)?;
233 
234         if let Err(e) = self.pt_map.prepare_map(
235             mm,
236             vfn_start,
237             num_pages,
238             &mut self.page_table_allocs,
239             &mut self.pt_pages,
240         ) {
241             self.free_vfn(vfn_start);
242             return Err(e);
243         }
244 
245         Ok(PreparedMapping {
246             vfn_start,
247             num_pages,
248             _drop_guard: MustExecuteGuard::new(),
249         })
250     }
251 
252     /// Execute a prepared multi-page mapping.
253     ///
254     /// Installs all prepared PDEs and writes PTEs into the page table, then flushes TLB.
255     pub(crate) fn execute_map(
256         &mut self,
257         mm: &mut GpuMm<'_>,
258         prepared: PreparedMapping,
259         pfns: &[Pfn],
260         writable: bool,
261     ) -> Result<MappedRange> {
262         if pfns.len() != prepared.num_pages {
263             self.free_vfn(prepared.vfn_start);
264             return Err(EINVAL);
265         }
266 
267         let PreparedMapping {
268             vfn_start,
269             num_pages,
270             _drop_guard,
271         } = prepared;
272         _drop_guard.disarm();
273 
274         if let Err(e) = self.pt_map.install_mappings(
275             mm,
276             &mut self.pt_pages,
277             &mut self.page_table_allocs,
278             vfn_start,
279             pfns,
280             writable,
281         ) {
282             self.free_vfn(vfn_start);
283             return Err(e);
284         }
285 
286         Ok(MappedRange {
287             vfn_start,
288             num_pages,
289             _drop_guard: MustUnmapGuard::new(),
290         })
291     }
292 
293     /// Map pages doing prepare and execute in the same call.
294     ///
295     /// This is a convenience wrapper for callers outside the fence signalling critical
296     /// path (e.g., BAR mappings). For DRM usecases, [`Vmm::prepare_map()`] and
297     /// [`Vmm::execute_map()`] will be called separately.
298     pub(crate) fn map_pages(
299         &mut self,
300         mm: &mut GpuMm<'_>,
301         pfns: &[Pfn],
302         va_range: Option<Range<u64>>,
303         writable: bool,
304     ) -> Result<MappedRange> {
305         if pfns.is_empty() {
306             return Err(EINVAL);
307         }
308 
309         // Check if provided VA range is sufficient (if provided).
310         if let Some(ref range) = va_range {
311             let required: u64 = pfns
312                 .len()
313                 .checked_mul(PAGE_SIZE)
314                 .ok_or(EOVERFLOW)?
315                 .into_safe_cast();
316             let available = range.end.checked_sub(range.start).ok_or(EINVAL)?;
317             if available < required {
318                 return Err(EINVAL);
319             }
320         }
321 
322         let prepared = self.prepare_map(mm, pfns.len(), va_range)?;
323         self.execute_map(mm, prepared, pfns, writable)
324     }
325 
326     /// Unmap all pages in a [`MappedRange`] with a single TLB flush.
327     pub(crate) fn unmap_pages(&mut self, mm: &mut GpuMm<'_>, range: MappedRange) -> Result {
328         let result = self
329             .pt_map
330             .invalidate_ptes(mm, range.vfn_start, range.num_pages);
331 
332         // TODO: Internal page table pages (PDE, PTE pages) are still kept around.
333         // This is by design as repeated maps/unmaps will be fast. As a future TODO,
334         // we can add a reclaimer here to reclaim if VRAM is short. For now, the PT
335         // pages are dropped once the `Vmm` is dropped.
336 
337         // Free the VA range regardless of PTE invalidation success, so that the VA
338         // range is recovered even on failure (PTEs may be stale, but that is better
339         // than leaking both PTEs and VA range).
340         self.free_vfn(range.vfn_start);
341 
342         // Unmap complete, safe to drop `MappedRange`.
343         range._drop_guard.disarm();
344         result
345     }
346 }
347