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
|
// SPDX-License-Identifier: GPL-2.0
//! Page table mapping operations for NVIDIA GPUs.
use core::marker::PhantomData;
use kernel::{
gpu::buddy::{
AllocatedBlocks,
GpuBuddyAllocFlags,
GpuBuddyAllocMode, //
},
io::io_write,
prelude::*,
ptr::Alignment,
rbtree::{
RBTree,
RBTreeNode, //
},
sizes::SZ_4K, //
};
use super::{
walk::{
PtWalkInner,
WalkPdeResult,
WalkResult, //
},
AperturePde,
AperturePte,
DualPdeOps,
MmuConfig,
MmuV2,
MmuV3,
MmuVersion,
PageTableLevel,
PdeOps,
PteOps, //
};
use crate::{
mm::{
GpuMm,
Pfn,
Vfn,
VramAddress,
PAGE_SIZE, //
},
num::{
IntoSafeCast, //
},
};
/// A pre-allocated and zeroed page table page.
///
/// Created during the mapping prepare phase and consumed during the execute phase.
/// Stored in an [`RBTree`] keyed by the PDE slot address (`install_addr`).
pub(in crate::mm) struct PreparedPtPage {
/// The allocated and zeroed page table page.
pub(in crate::mm) alloc: Pin<KBox<AllocatedBlocks>>,
/// Page table level -- needed to determine if this PT page is for a dual PDE.
pub(in crate::mm) level: PageTableLevel,
}
/// Page table mapper.
pub(in crate::mm) struct PtMapInner<M: MmuConfig> {
walker: PtWalkInner<M>,
pdb_addr: VramAddress,
_phantom: PhantomData<M>,
}
impl<M: MmuConfig> PtMapInner<M> {
/// Create a new [`PtMapInner`].
pub(super) fn new(pdb_addr: VramAddress) -> Self {
Self {
walker: PtWalkInner::<M>::new(pdb_addr),
pdb_addr,
_phantom: PhantomData,
}
}
/// Allocate and zero a physical page table page.
fn alloc_and_zero_page(mm: &mut GpuMm<'_>, level: PageTableLevel) -> Result<PreparedPtPage> {
let blocks = KBox::pin_init(
mm.buddy().alloc_blocks(
GpuBuddyAllocMode::Simple,
SZ_4K.into_safe_cast(),
Alignment::new::<SZ_4K>(),
GpuBuddyAllocFlags::default(),
),
GFP_KERNEL,
)?;
let page_vram = VramAddress::from_raw(blocks.iter().next().ok_or(ENOMEM)?.offset());
// Zero via PRAMIN.
let window = mm
.pramin_mut()
.window_at::<[u64; PAGE_SIZE / 8]>(page_vram)?;
for i in 0..PAGE_SIZE / 8 {
io_write!(window.view(), [build: i], 0);
}
Ok(PreparedPtPage {
alloc: blocks,
level,
})
}
/// Ensure all intermediate page table pages exist for a single VFN.
///
/// The mutable PRAMIN borrow ends before each allocation.
fn ensure_single_pte_path(
&self,
mm: &mut GpuMm<'_>,
vfn: Vfn,
pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
) -> Result {
let max_iter = 2 * M::PDE_LEVELS.len();
for _ in 0..max_iter {
let result = self
.walker
.walk_pde_levels(mm.pramin_mut(), vfn, |install_addr| {
pt_pages.get(&install_addr).and_then(|p| {
p.alloc
.iter()
.next()
.map(|b| VramAddress::from_raw(b.offset()))
})
})?;
match result {
WalkPdeResult::Complete { .. } => {
return Ok(());
}
WalkPdeResult::Missing {
install_addr,
level,
} => {
let page = Self::alloc_and_zero_page(mm, level)?;
let node = RBTreeNode::new(install_addr, page, GFP_KERNEL)?;
let old = pt_pages.insert(node);
if old.is_some() {
kernel::pr_warn_once!(
"VMM: duplicate install_addr in pt_pages (internal consistency error)\n"
);
return Err(EIO);
}
}
}
}
kernel::pr_warn!(
"VMM: ensure_pte_path: loop exhausted after {} iters (VFN {:?})\n",
max_iter,
vfn
);
Err(EIO)
}
/// Prepare page table resources for mapping `num_pages` pages starting at `vfn_start`.
///
/// Reserves capacity in `page_table_allocs`, then walks the hierarchy
/// per-VFN to prepare pages for all missing PDEs.
pub(super) fn prepare_map(
&self,
mm: &mut GpuMm<'_>,
vfn_start: Vfn,
num_pages: usize,
page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
) -> Result {
// Pre-reserve so install_mappings() can use push_within_capacity (no alloc
// in fence signalling critical path).
let pt_upper_bound = M::pt_pages_upper_bound(num_pages);
page_table_allocs.reserve(pt_upper_bound, GFP_KERNEL)?;
// Walk the hierarchy per-VFN to prepare pages for all missing PDEs.
for i in 0..num_pages {
let i_u64: u64 = i.into_safe_cast();
let vfn = Vfn::new(vfn_start.raw() + i_u64);
self.ensure_single_pte_path(mm, vfn, pt_pages)?;
}
Ok(())
}
/// Install prepared PDEs and write PTEs, then flush TLB.
///
/// Drains `pt_pages` and moves allocations into `page_table_allocs`.
pub(super) fn install_mappings(
&self,
mm: &mut GpuMm<'_>,
pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
vfn_start: Vfn,
pfns: &[Pfn],
writable: bool,
) -> Result {
{
let pramin = mm.pramin_mut();
// Drain prepared PT pages, install all pending PDEs.
let mut cursor = pt_pages.cursor_front_mut();
while let Some(c) = cursor {
let (next, node) = c.remove_current();
let (install_addr, page) = node.to_key_value();
let page_vram =
VramAddress::from_raw(page.alloc.iter().next().ok_or(ENOMEM)?.offset());
if page.level == M::DUAL_PDE_LEVEL {
let new_dpde = M::DualPde::new_small(Pfn::from(page_vram));
new_dpde.write(pramin, install_addr)?;
} else {
let new_pde = M::Pde::new(AperturePde::VideoMemory, Pfn::from(page_vram));
new_pde.write(pramin, install_addr)?;
}
page_table_allocs
.push_within_capacity(page.alloc)
.map_err(|_| ENOMEM)?;
cursor = next;
}
// Write PTEs (all PDEs now installed in HW).
for (i, &pfn) in pfns.iter().enumerate() {
let i_u64: u64 = i.into_safe_cast();
let vfn = Vfn::new(vfn_start.raw() + i_u64);
let result = self.walker.walk_to_pte_lookup_with_window(pramin, vfn)?;
match result {
WalkResult::Unmapped { pte_addr } | WalkResult::Mapped { pte_addr, .. } => {
let pte = M::Pte::new(AperturePte::VideoMemory, pfn, writable);
pte.write(pramin, pte_addr)?;
}
WalkResult::PageTableMissing => {
kernel::pr_warn_once!("VMM: page table missing for VFN {vfn:?}\n");
return Err(EIO);
}
}
}
}
// Flush TLB.
mm.tlb().flush(self.pdb_addr)
}
/// Invalidate PTEs for a range and flush TLB.
pub(super) fn invalidate_ptes(
&self,
mm: &mut GpuMm<'_>,
vfn_start: Vfn,
num_pages: usize,
) -> Result {
let invalid_pte = M::Pte::invalid();
{
let pramin = mm.pramin_mut();
for i in 0..num_pages {
let i_u64: u64 = i.into_safe_cast();
let vfn = Vfn::new(vfn_start.raw() + i_u64);
let result = self.walker.walk_to_pte_lookup_with_window(pramin, vfn)?;
match result {
WalkResult::Mapped { pte_addr, .. } | WalkResult::Unmapped { pte_addr } => {
invalid_pte.write(pramin, pte_addr)?;
}
WalkResult::PageTableMissing => {
continue;
}
}
}
}
mm.tlb().flush(self.pdb_addr)
}
}
macro_rules! pt_map_dispatch {
($self:expr, $method:ident ( $($arg:expr),* $(,)? )) => {
match $self {
PtMap::V2(inner) => inner.$method($($arg),*),
PtMap::V3(inner) => inner.$method($($arg),*),
}
};
}
/// Page table mapper dispatch.
pub(in crate::mm) enum PtMap {
/// MMU v2 (Turing/Ampere/Ada).
V2(PtMapInner<MmuV2>),
/// MMU v3 (Hopper+).
V3(PtMapInner<MmuV3>),
}
impl PtMap {
/// Create a new page table mapper for the given MMU version.
pub(in crate::mm) fn new(pdb_addr: VramAddress, version: MmuVersion) -> Self {
match version {
MmuVersion::V2 => Self::V2(PtMapInner::<MmuV2>::new(pdb_addr)),
MmuVersion::V3 => Self::V3(PtMapInner::<MmuV3>::new(pdb_addr)),
}
}
/// Prepare page table resources for a mapping.
pub(in crate::mm) fn prepare_map(
&self,
mm: &mut GpuMm<'_>,
vfn_start: Vfn,
num_pages: usize,
page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
) -> Result {
pt_map_dispatch!(
self,
prepare_map(mm, vfn_start, num_pages, page_table_allocs, pt_pages)
)
}
/// Install prepared PDEs and write PTEs, then flush TLB.
pub(in crate::mm) fn install_mappings(
&self,
mm: &mut GpuMm<'_>,
pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
vfn_start: Vfn,
pfns: &[Pfn],
writable: bool,
) -> Result {
pt_map_dispatch!(
self,
install_mappings(mm, pt_pages, page_table_allocs, vfn_start, pfns, writable)
)
}
/// Invalidate PTEs for a range and flush TLB.
pub(in crate::mm) fn invalidate_ptes(
&self,
mm: &mut GpuMm<'_>,
vfn_start: Vfn,
num_pages: usize,
) -> Result {
pt_map_dispatch!(self, invalidate_ptes(mm, vfn_start, num_pages))
}
}
|