kernel/mm/virt.rs
1// SPDX-License-Identifier: GPL-2.0
2
3// Copyright (C) 2024 Google LLC.
4
5//! Virtual memory.
6//!
7//! This module deals with managing a single VMA in the address space of a userspace process. Each
8//! VMA corresponds to a region of memory that the userspace process can access, and the VMA lets
9//! you control what happens when userspace reads or writes to that region of memory.
10//!
11//! The module has several different Rust types that all correspond to the C type called
12//! `vm_area_struct`. The different structs represent what kind of access you have to the VMA, e.g.
13//! [`VmaRef`] is used when you hold the mmap or vma read lock. Using the appropriate struct
14//! ensures that you can't, for example, accidentally call a function that requires holding the
15//! write lock when you only hold the read lock.
16
17use crate::{
18 bindings,
19 error::{code::EINVAL, to_result, Result},
20 mm::MmWithUser,
21 page::Page,
22 types::Opaque,
23};
24
25use core::ops::Deref;
26use safety_macro::safety;
27/// A wrapper for the kernel's `struct vm_area_struct` with read access.
28///
29/// It represents an area of virtual memory.
30///
31/// # Invariants
32///
33/// The caller must hold the mmap read lock or the vma read lock.
34#[repr(transparent)]
35pub struct VmaRef {
36 vma: Opaque<bindings::vm_area_struct>,
37}
38
39// Methods you can call when holding the mmap or vma read lock (or stronger). They must be usable
40// no matter what the vma flags are.
41impl VmaRef {
42 /// Access a virtual memory area given a raw pointer.
43 ///
44 /// # Safety
45 ///
46 /// Callers must ensure that `vma` is valid for the duration of 'a, and that the mmap or vma
47 /// read lock (or stronger) is held for at least the duration of 'a.
48 #[safety{ValidVma(vma, a), LockHold(mmap-or-vma_read, a)}]
49 #[inline]
50 pub unsafe fn from_raw<'a>(vma: *const bindings::vm_area_struct) -> &'a Self {
51 // SAFETY: The caller ensures that the invariants are satisfied for the duration of 'a.
52 unsafe { &*vma.cast() }
53 }
54
55 /// Returns a raw pointer to this area.
56 #[inline]
57 pub fn as_ptr(&self) -> *mut bindings::vm_area_struct {
58 self.vma.get()
59 }
60
61 /// Access the underlying `mm_struct`.
62 #[inline]
63 pub fn mm(&self) -> &MmWithUser {
64 // SAFETY: By the type invariants, this `vm_area_struct` is valid and we hold the mmap/vma
65 // read lock or stronger. This implies that the underlying mm has a non-zero value of
66 // `mm_users`.
67 unsafe { MmWithUser::from_raw((*self.as_ptr()).vm_mm) }
68 }
69
70 /// Returns the flags associated with the virtual memory area.
71 ///
72 /// The possible flags are a combination of the constants in [`flags`].
73 #[inline]
74 pub fn flags(&self) -> vm_flags_t {
75 // SAFETY: By the type invariants, the caller holds at least the mmap read lock, so this
76 // access is not a data race.
77 unsafe { (*self.as_ptr()).__bindgen_anon_2.vm_flags }
78 }
79
80 /// Returns the (inclusive) start address of the virtual memory area.
81 #[inline]
82 pub fn start(&self) -> usize {
83 // SAFETY: By the type invariants, the caller holds at least the mmap read lock, so this
84 // access is not a data race.
85 unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_start }
86 }
87
88 /// Returns the (exclusive) end address of the virtual memory area.
89 #[inline]
90 pub fn end(&self) -> usize {
91 // SAFETY: By the type invariants, the caller holds at least the mmap read lock, so this
92 // access is not a data race.
93 unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_end }
94 }
95
96 /// Zap pages in the given page range.
97 ///
98 /// This clears page table mappings for the range at the leaf level, leaving all other page
99 /// tables intact, and freeing any memory referenced by the VMA in this range. That is,
100 /// anonymous memory is completely freed, file-backed memory has its reference count on page
101 /// cache folio's dropped, any dirty data will still be written back to disk as usual.
102 ///
103 /// It may seem odd that we clear at the leaf level, this is however a product of the page
104 /// table structure used to map physical memory into a virtual address space - each virtual
105 /// address actually consists of a bitmap of array indices into page tables, which form a
106 /// hierarchical page table level structure.
107 ///
108 /// As a result, each page table level maps a multiple of page table levels below, and thus
109 /// span ever increasing ranges of pages. At the leaf or PTE level, we map the actual physical
110 /// memory.
111 ///
112 /// It is here where a zap operates, as it the only place we can be certain of clearing without
113 /// impacting any other virtual mappings. It is an implementation detail as to whether the
114 /// kernel goes further in freeing unused page tables, but for the purposes of this operation
115 /// we must only assume that the leaf level is cleared.
116 #[inline]
117 pub fn zap_page_range_single(&self, address: usize, size: usize) {
118 let (end, did_overflow) = address.overflowing_add(size);
119 if did_overflow || address < self.start() || self.end() < end {
120 // TODO: call WARN_ONCE once Rust version of it is added
121 return;
122 }
123
124 // SAFETY: By the type invariants, the caller has read access to this VMA, which is
125 // sufficient for this method call. This method has no requirements on the vma flags. The
126 // address range is checked to be within the vma.
127 unsafe {
128 bindings::zap_page_range_single(self.as_ptr(), address, size, core::ptr::null_mut())
129 };
130 }
131
132 /// If the [`VM_MIXEDMAP`] flag is set, returns a [`VmaMixedMap`] to this VMA, otherwise
133 /// returns `None`.
134 ///
135 /// This can be used to access methods that require [`VM_MIXEDMAP`] to be set.
136 ///
137 /// [`VM_MIXEDMAP`]: flags::MIXEDMAP
138 #[inline]
139 pub fn as_mixedmap_vma(&self) -> Option<&VmaMixedMap> {
140 if self.flags() & flags::MIXEDMAP != 0 {
141 // SAFETY: We just checked that `VM_MIXEDMAP` is set. All other requirements are
142 // satisfied by the type invariants of `VmaRef`.
143 Some(unsafe { VmaMixedMap::from_raw(self.as_ptr()) })
144 } else {
145 None
146 }
147 }
148}
149
150/// A wrapper for the kernel's `struct vm_area_struct` with read access and [`VM_MIXEDMAP`] set.
151///
152/// It represents an area of virtual memory.
153///
154/// This struct is identical to [`VmaRef`] except that it must only be used when the
155/// [`VM_MIXEDMAP`] flag is set on the vma.
156///
157/// # Invariants
158///
159/// The caller must hold the mmap read lock or the vma read lock. The `VM_MIXEDMAP` flag must be
160/// set.
161///
162/// [`VM_MIXEDMAP`]: flags::MIXEDMAP
163#[repr(transparent)]
164pub struct VmaMixedMap {
165 vma: VmaRef,
166}
167
168// Make all `VmaRef` methods available on `VmaMixedMap`.
169impl Deref for VmaMixedMap {
170 type Target = VmaRef;
171
172 #[inline]
173 fn deref(&self) -> &VmaRef {
174 &self.vma
175 }
176}
177
178impl VmaMixedMap {
179 /// Access a virtual memory area given a raw pointer.
180 ///
181 /// # Safety
182 ///
183 /// Callers must ensure that `vma` is valid for the duration of 'a, and that the mmap read lock
184 /// (or stronger) is held for at least the duration of 'a. The `VM_MIXEDMAP` flag must be set.
185 #[safety{ValidVma(vma, a), LockHold(mmap-read, a), FlagSet(VM_MIXEDMAP)}]
186 #[inline]
187 pub unsafe fn from_raw<'a>(vma: *const bindings::vm_area_struct) -> &'a Self {
188 // SAFETY: The caller ensures that the invariants are satisfied for the duration of 'a.
189 unsafe { &*vma.cast() }
190 }
191
192 /// Maps a single page at the given address within the virtual memory area.
193 ///
194 /// This operation does not take ownership of the page.
195 #[inline]
196 pub fn vm_insert_page(&self, address: usize, page: &Page) -> Result {
197 // SAFETY: By the type invariant of `Self` caller has read access and has verified that
198 // `VM_MIXEDMAP` is set. By invariant on `Page` the page has order 0.
199 to_result(unsafe { bindings::vm_insert_page(self.as_ptr(), address, page.as_ptr()) })
200 }
201}
202
203/// A configuration object for setting up a VMA in an `f_ops->mmap()` hook.
204///
205/// The `f_ops->mmap()` hook is called when a new VMA is being created, and the hook is able to
206/// configure the VMA in various ways to fit the driver that owns it. Using `VmaNew` indicates that
207/// you are allowed to perform operations on the VMA that can only be performed before the VMA is
208/// fully initialized.
209///
210/// # Invariants
211///
212/// For the duration of 'a, the referenced vma must be undergoing initialization in an
213/// `f_ops->mmap()` hook.
214#[repr(transparent)]
215pub struct VmaNew {
216 vma: VmaRef,
217}
218
219// Make all `VmaRef` methods available on `VmaNew`.
220impl Deref for VmaNew {
221 type Target = VmaRef;
222
223 #[inline]
224 fn deref(&self) -> &VmaRef {
225 &self.vma
226 }
227}
228
229impl VmaNew {
230 /// Access a virtual memory area given a raw pointer.
231 ///
232 /// # Safety
233 ///
234 /// Callers must ensure that `vma` is undergoing initial vma setup for the duration of 'a.
235 #[safety{Init(vma, biding::vm_area_struct, 1)}]
236 #[inline]
237 pub unsafe fn from_raw<'a>(vma: *mut bindings::vm_area_struct) -> &'a Self {
238 // SAFETY: The caller ensures that the invariants are satisfied for the duration of 'a.
239 unsafe { &*vma.cast() }
240 }
241
242 /// Internal method for updating the vma flags.
243 ///
244 /// # Safety
245 ///
246 /// This must not be used to set the flags to an invalid value.
247 #[safety{ValidNum}]
248 #[inline]
249 unsafe fn update_flags(&self, set: vm_flags_t, unset: vm_flags_t) {
250 let mut flags = self.flags();
251 flags |= set;
252 flags &= !unset;
253
254 // SAFETY: This is not a data race: the vma is undergoing initial setup, so it's not yet
255 // shared. Additionally, `VmaNew` is `!Sync`, so it cannot be used to write in parallel.
256 // The caller promises that this does not set the flags to an invalid value.
257 unsafe { (*self.as_ptr()).__bindgen_anon_2.__vm_flags = flags };
258 }
259
260 /// Set the `VM_MIXEDMAP` flag on this vma.
261 ///
262 /// This enables the vma to contain both `struct page` and pure PFN pages. Returns a reference
263 /// that can be used to call `vm_insert_page` on the vma.
264 #[inline]
265 pub fn set_mixedmap(&self) -> &VmaMixedMap {
266 // SAFETY: We don't yet provide a way to set VM_PFNMAP, so this cannot put the flags in an
267 // invalid state.
268 unsafe { self.update_flags(flags::MIXEDMAP, 0) };
269
270 // SAFETY: We just set `VM_MIXEDMAP` on the vma.
271 unsafe { VmaMixedMap::from_raw(self.vma.as_ptr()) }
272 }
273
274 /// Set the `VM_IO` flag on this vma.
275 ///
276 /// This is used for memory mapped IO and similar. The flag tells other parts of the kernel to
277 /// avoid looking at the pages. For memory mapped IO this is useful as accesses to the pages
278 /// could have side effects.
279 #[inline]
280 pub fn set_io(&self) {
281 // SAFETY: Setting the VM_IO flag is always okay.
282 unsafe { self.update_flags(flags::IO, 0) };
283 }
284
285 /// Set the `VM_DONTEXPAND` flag on this vma.
286 ///
287 /// This prevents the vma from being expanded with `mremap()`.
288 #[inline]
289 pub fn set_dontexpand(&self) {
290 // SAFETY: Setting the VM_DONTEXPAND flag is always okay.
291 unsafe { self.update_flags(flags::DONTEXPAND, 0) };
292 }
293
294 /// Set the `VM_DONTCOPY` flag on this vma.
295 ///
296 /// This prevents the vma from being copied on fork. This option is only permanent if `VM_IO`
297 /// is set.
298 #[inline]
299 pub fn set_dontcopy(&self) {
300 // SAFETY: Setting the VM_DONTCOPY flag is always okay.
301 unsafe { self.update_flags(flags::DONTCOPY, 0) };
302 }
303
304 /// Set the `VM_DONTDUMP` flag on this vma.
305 ///
306 /// This prevents the vma from being included in core dumps. This option is only permanent if
307 /// `VM_IO` is set.
308 #[inline]
309 pub fn set_dontdump(&self) {
310 // SAFETY: Setting the VM_DONTDUMP flag is always okay.
311 unsafe { self.update_flags(flags::DONTDUMP, 0) };
312 }
313
314 /// Returns whether `VM_READ` is set.
315 ///
316 /// This flag indicates whether userspace is mapping this vma as readable.
317 #[inline]
318 pub fn readable(&self) -> bool {
319 (self.flags() & flags::READ) != 0
320 }
321
322 /// Try to clear the `VM_MAYREAD` flag, failing if `VM_READ` is set.
323 ///
324 /// This flag indicates whether userspace is allowed to make this vma readable with
325 /// `mprotect()`.
326 ///
327 /// Note that this operation is irreversible. Once `VM_MAYREAD` has been cleared, it can never
328 /// be set again.
329 #[inline]
330 pub fn try_clear_mayread(&self) -> Result {
331 if self.readable() {
332 return Err(EINVAL);
333 }
334 // SAFETY: Clearing `VM_MAYREAD` is okay when `VM_READ` is not set.
335 unsafe { self.update_flags(0, flags::MAYREAD) };
336 Ok(())
337 }
338
339 /// Returns whether `VM_WRITE` is set.
340 ///
341 /// This flag indicates whether userspace is mapping this vma as writable.
342 #[inline]
343 pub fn writable(&self) -> bool {
344 (self.flags() & flags::WRITE) != 0
345 }
346
347 /// Try to clear the `VM_MAYWRITE` flag, failing if `VM_WRITE` is set.
348 ///
349 /// This flag indicates whether userspace is allowed to make this vma writable with
350 /// `mprotect()`.
351 ///
352 /// Note that this operation is irreversible. Once `VM_MAYWRITE` has been cleared, it can never
353 /// be set again.
354 #[inline]
355 pub fn try_clear_maywrite(&self) -> Result {
356 if self.writable() {
357 return Err(EINVAL);
358 }
359 // SAFETY: Clearing `VM_MAYWRITE` is okay when `VM_WRITE` is not set.
360 unsafe { self.update_flags(0, flags::MAYWRITE) };
361 Ok(())
362 }
363
364 /// Returns whether `VM_EXEC` is set.
365 ///
366 /// This flag indicates whether userspace is mapping this vma as executable.
367 #[inline]
368 pub fn executable(&self) -> bool {
369 (self.flags() & flags::EXEC) != 0
370 }
371
372 /// Try to clear the `VM_MAYEXEC` flag, failing if `VM_EXEC` is set.
373 ///
374 /// This flag indicates whether userspace is allowed to make this vma executable with
375 /// `mprotect()`.
376 ///
377 /// Note that this operation is irreversible. Once `VM_MAYEXEC` has been cleared, it can never
378 /// be set again.
379 #[inline]
380 pub fn try_clear_mayexec(&self) -> Result {
381 if self.executable() {
382 return Err(EINVAL);
383 }
384 // SAFETY: Clearing `VM_MAYEXEC` is okay when `VM_EXEC` is not set.
385 unsafe { self.update_flags(0, flags::MAYEXEC) };
386 Ok(())
387 }
388}
389
390/// The integer type used for vma flags.
391#[doc(inline)]
392pub use bindings::vm_flags_t;
393
394/// All possible flags for [`VmaRef`].
395pub mod flags {
396 use super::vm_flags_t;
397 use crate::bindings;
398
399 /// No flags are set.
400 pub const NONE: vm_flags_t = bindings::VM_NONE as vm_flags_t;
401
402 /// Mapping allows reads.
403 pub const READ: vm_flags_t = bindings::VM_READ as vm_flags_t;
404
405 /// Mapping allows writes.
406 pub const WRITE: vm_flags_t = bindings::VM_WRITE as vm_flags_t;
407
408 /// Mapping allows execution.
409 pub const EXEC: vm_flags_t = bindings::VM_EXEC as vm_flags_t;
410
411 /// Mapping is shared.
412 pub const SHARED: vm_flags_t = bindings::VM_SHARED as vm_flags_t;
413
414 /// Mapping may be updated to allow reads.
415 pub const MAYREAD: vm_flags_t = bindings::VM_MAYREAD as vm_flags_t;
416
417 /// Mapping may be updated to allow writes.
418 pub const MAYWRITE: vm_flags_t = bindings::VM_MAYWRITE as vm_flags_t;
419
420 /// Mapping may be updated to allow execution.
421 pub const MAYEXEC: vm_flags_t = bindings::VM_MAYEXEC as vm_flags_t;
422
423 /// Mapping may be updated to be shared.
424 pub const MAYSHARE: vm_flags_t = bindings::VM_MAYSHARE as vm_flags_t;
425
426 /// Page-ranges managed without `struct page`, just pure PFN.
427 pub const PFNMAP: vm_flags_t = bindings::VM_PFNMAP as vm_flags_t;
428
429 /// Memory mapped I/O or similar.
430 pub const IO: vm_flags_t = bindings::VM_IO as vm_flags_t;
431
432 /// Do not copy this vma on fork.
433 pub const DONTCOPY: vm_flags_t = bindings::VM_DONTCOPY as vm_flags_t;
434
435 /// Cannot expand with mremap().
436 pub const DONTEXPAND: vm_flags_t = bindings::VM_DONTEXPAND as vm_flags_t;
437
438 /// Lock the pages covered when they are faulted in.
439 pub const LOCKONFAULT: vm_flags_t = bindings::VM_LOCKONFAULT as vm_flags_t;
440
441 /// Is a VM accounted object.
442 pub const ACCOUNT: vm_flags_t = bindings::VM_ACCOUNT as vm_flags_t;
443
444 /// Should the VM suppress accounting.
445 pub const NORESERVE: vm_flags_t = bindings::VM_NORESERVE as vm_flags_t;
446
447 /// Huge TLB Page VM.
448 pub const HUGETLB: vm_flags_t = bindings::VM_HUGETLB as vm_flags_t;
449
450 /// Synchronous page faults. (DAX-specific)
451 pub const SYNC: vm_flags_t = bindings::VM_SYNC as vm_flags_t;
452
453 /// Architecture-specific flag.
454 pub const ARCH_1: vm_flags_t = bindings::VM_ARCH_1 as vm_flags_t;
455
456 /// Wipe VMA contents in child on fork.
457 pub const WIPEONFORK: vm_flags_t = bindings::VM_WIPEONFORK as vm_flags_t;
458
459 /// Do not include in the core dump.
460 pub const DONTDUMP: vm_flags_t = bindings::VM_DONTDUMP as vm_flags_t;
461
462 /// Not soft dirty clean area.
463 pub const SOFTDIRTY: vm_flags_t = bindings::VM_SOFTDIRTY as vm_flags_t;
464
465 /// Can contain `struct page` and pure PFN pages.
466 pub const MIXEDMAP: vm_flags_t = bindings::VM_MIXEDMAP as vm_flags_t;
467
468 /// MADV_HUGEPAGE marked this vma.
469 pub const HUGEPAGE: vm_flags_t = bindings::VM_HUGEPAGE as vm_flags_t;
470
471 /// MADV_NOHUGEPAGE marked this vma.
472 pub const NOHUGEPAGE: vm_flags_t = bindings::VM_NOHUGEPAGE as vm_flags_t;
473
474 /// KSM may merge identical pages.
475 pub const MERGEABLE: vm_flags_t = bindings::VM_MERGEABLE as vm_flags_t;
476}