rust: mm: add abstractions for mm_struct and vm_area_struct
Subsystems (3)
Alice Ryhl
maintainerPATCH v4 1/1 rust: mm: add abstractions for mm_struct and vm_area_struct
This is a follow-up to the page abstractions [1] that were recently merged in 6.11. Rust Binder will need these abstractions to manipulate the vma in its implementation of the mmap fop on the Binder file.
This patch is based on Wedson's implementation on the old rust branch, but has been changed significantly. All mistakes are Alice's.
---
This change depends on:
https://lore.kernel.org/all/[email protected]/
---
Changes in v4:
- Pull out ARef::into_raw into a separate patch.
- Update invariants and struct documentation.
- Rename from_raw_mm to from_raw.
- Link to v3: https://lore.kernel.org/r/[email protected]
Changes in v3:
- Reorder entries in mm.rs.
- Use ARef for mmput_async helper.
- Clarify that VmArea requires you to hold the mmap read or write lock.
- Link to v2: https://lore.kernel.org/r/[email protected]
Changes in v2:
- mm.rs is redesigned from scratch making use of AsRef
- Add notes about whether destructors may sleep
- Rename Area to VmArea
- Link to v1: https://lore.kernel.org/r/[email protected]
--- rust/helpers.c | 61 +++++++++ rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 343 +++++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/mm/virt.rs | 204 +++++++++++++++++++++++++++++ 4 files changed, 609 insertions(+)
rust/helpers.c +61 -0
@@ -200,6 +200,67 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) }EXPORT_SYMBOL_GPL (rust_helper_krealloc); +void rust_helper_mmgrab (struct mm_struct *mm) +{ +mmgrab (mm); +} +EXPORT_SYMBOL_GPL (rust_helper_mmgrab); + +void rust_helper_mmdrop (struct mm_struct *mm) +{ +mmdrop (mm); +} +EXPORT_SYMBOL_GPL (rust_helper_mmdrop); + +void rust_helper_mmget (struct mm_struct *mm) +{ +mmget (mm); +} +EXPORT_SYMBOL_GPL (rust_helper_mmget); + +bool rust_helper_mmget_not_zero (struct mm_struct *mm) +{ +return mmget_not_zero (mm); +} +EXPORT_SYMBOL_GPL (rust_helper_mmget_not_zero); + +void rust_helper_mmap_read_lock (struct mm_struct *mm) +{ +mmap_read_lock (mm); +} +EXPORT_SYMBOL_GPL (rust_helper_mmap_read_lock); + +bool rust_helper_mmap_read_trylock (struct mm_struct *mm) +{ +return mmap_read_trylock (mm); +} +EXPORT_SYMBOL_GPL (rust_helper_mmap_read_trylock); + +void rust_helper_mmap_read_unlock (struct mm_struct *mm) +{ +mmap_read_unlock (mm); +} +EXPORT_SYMBOL_GPL (rust_helper_mmap_read_unlock); + +void rust_helper_mmap_write_lock (struct mm_struct *mm) +{ +mmap_write_lock (mm); +} +EXPORT_SYMBOL_GPL (rust_helper_mmap_write_lock); + +void rust_helper_mmap_write_unlock (struct mm_struct *mm) +{ +mmap_write_unlock (mm); +} +EXPORT_SYMBOL_GPL (rust_helper_mmap_write_unlock); + +struct vm_area_struct *rust_helper_vma_lookup (struct mm_struct *mm, +unsigned long addr) +{ +return vma_lookup (mm, addr); +} +EXPORT_SYMBOL_GPL (rust_helper_vma_lookup); +/* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indices.
rust/kernel/lib.rs +1 -0
@@ -38,6 +38,7 @@pub mod ioctl;#[cfg( CONFIG_KUNIT )] pub mod kunit; +pub mod mm;#[cfg( CONFIG_NET )] pub mod net;pub mod page;
rust/kernel/mm.rs new file +343 -0
343 lines not on this page · raw message
rust/kernel/mm/virt.rs new file +204 -0
204 lines not on this page · raw message
---
base-commit: ef0f6dbf36d56c3a72264b316e120e58e4805da6
change-id: 20240723-vma-f80119f9fb35
Best regards,
Signature · 1 line
Alice Ryhl <[email protected]>
Quoted 11 lines · Alice Ryhl
This is a follow-up to the page abstractions [1] that were recently merged in 6.11. Rust Binder will need these abstractions to manipulate the vma in its implementation of the mmap fop on the Binder file.
This patch is based on Wedson's implementation on the old rust branch, but has been changed significantly. All mistakes are Alice's.
Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
I have one nit below, with that fixed:
Quoted 31 lines
rust/kernel/mm/virt.rs new file +25
-0@@ -0,0 +1,204 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Virtual memory. + +use crate ::{ + bindings, + error::{to_result,Result }, + page::Page , + types::Opaque , +}; + +/// A wrapper for the kernel's `struct vm_area_struct`. +/// +/// It represents an area of virtual memory. +/// +/// # Invariants +/// +/// * If the caller has shared access to this type, then they must hold the mmap read lock. +/// * If the caller has exclusive access to this type, then they must hold the mmap write lock. +#[repr(transparent)] +pub struct VmArea { + vma:Opaque <bindings::vm_area_struct >, +}
rust/kernel/mm/virt.rs line 35
Quoted 10 lines
rust/kernel/mm/virt.rs new file +10
-0+ +impl VmArea { +/// Access a virtual memory area given a raw pointer. +/// +/// # Safety +/// +/// Callers must ensure that `vma` is valid for the duration of 'a, and that the mmap read lock +/// (or write lock) is held for at least the duration of 'a. +#[inline] +pub unsafe fn from_raw_vma <'a>(vma: *const bindings::vm_area_struct ) -> &'aSelf {
I think this also should be named from_raw.
I took a look at your conversation with Christian Brauner and I personally don't see the benefit of File::from_raw_file over File::from_raw. To me it's clear that this function takes some raw C structure that represents a File and turns it into a File. In the situation where there are multiple ways of creating something from different C structs, I think we should include the name. But if there is only one possible struct, then the name should be from_raw.
Do you think we should re-open that discussion/start a new one on a naming convention for this?
---
Cheers,
Benno
Quoted 3 lines
rust/kernel/mm/virt.rs new file +3
-0+// SAFETY: The caller ensures that the invariants are satisfied for the duration of 'a. +unsafe { &*vma.cast () } + }
Alice Ryhl
maintainerQuoted 70 lines · Benno Lossin
Quoted 11 lines · Alice Ryhl
This is a follow-up to the page abstractions [1] that were recently merged in 6.11. Rust Binder will need these abstractions to manipulate the vma in its implementation of the mmap fop on the Binder file.
This patch is based on Wedson's implementation on the old rust branch, but has been changed significantly. All mistakes are Alice's.
Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Alice Ryhl <[email protected]>I have one nit below, with that fixed:
Reviewed-by Benno Lossin <[email protected]>Quoted 31 lines
rust/kernel/mm/virt.rs new file +25
-0@@ -0,0 +1,204 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Virtual memory. + +use crate ::{ + bindings, + error::{to_result,Result }, + page::Page , + types::Opaque , +}; + +/// A wrapper for the kernel's `struct vm_area_struct`. +/// +/// It represents an area of virtual memory. +/// +/// # Invariants +/// +/// * If the caller has shared access to this type, then they must hold the mmap read lock. +/// * If the caller has exclusive access to this type, then they must hold the mmap write lock. +#[repr(transparent)] +pub struct VmArea { + vma:Opaque <bindings::vm_area_struct >, +}rust/kernel/mm/virt.rs line 35
Quoted 10 lines
rust/kernel/mm/virt.rs new file +10
-0+ +impl VmArea { +/// Access a virtual memory area given a raw pointer. +/// +/// # Safety +/// +/// Callers must ensure that `vma` is valid for the duration of 'a, and that the mmap read lock +/// (or write lock) is held for at least the duration of 'a. +#[inline] +pub unsafe fn from_raw_vma <'a>(vma: *const bindings::vm_area_struct ) -> &'aSelf {I think this also should be named
from_raw.I took a look at your conversation with Christian Brauner and I personally don't see the benefit of
File::from_raw_fileoverFile::from_raw. To me it's clear that this function takes some raw C structure that represents aFileand turns it into aFile. In the situation where there are multiple ways of creating something from different C structs, I think we should include the name. But if there is only one possible struct, then the name should befrom_raw.
Quoted 2 lines
Do you think we should re-open that discussion/start a new one on a naming convention for this?
Oh, I actually intended to rename it here too. I just forgot that VmArea also had a from_raw.
Alice
Quoted 11 lines · Alice Ryhl
This is a follow-up to the page abstractions [1] that were recently merged in 6.11. Rust Binder will need these abstractions to manipulate the vma in its implementation of the mmap fop on the Binder file.
This patch is based on Wedson's implementation on the old rust branch, but has been changed significantly. All mistakes are Alice's.
Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
On Fri, Aug 02, 2024 at 07:38:32AM +0000, Alice Ryhl wrote:
[...]
Quoted 9 lines
rust/kernel/mm.rs new file +9
-0+// These methods are safe to call even if `mm_users` is zero. +impl Mm { +/// Call `mmgrab` on `current.mm`. +#[inline] +pub fn mmgrab_current () ->Option <ARef <Mm >> { +// SAFETY: It's safe to get the `mm` field from current. +let mm =unsafe { +let current = bindings::get_current (); + (*current).mm
rust/kernel/mm.rs line 160
Quoted 10 lines
rust/kernel/mm.rs new file +10
-0+ }; + +let mm =NonNull ::new (mm)?; + +// SAFETY: We just checked that `mm` is not null. +unsafe { bindings::mmgrab (mm.as_ptr ()) }; + +// SAFETY: We just created an `mmgrab` refcount. Layouts are compatible due to +// repr(transparent). +Some (unsafe {ARef ::from_raw (mm.cast ()) })
We can use from_raw() + into() here. If a type impls AlwaysRefcounted, we should have no chance to call the "refcount increment" function directly.
Quoted 150 lines
rust/kernel/mm.rs new file +150
-0+ } + +/// Returns a raw pointer to the inner `mm_struct`. +#[inline] +pub fn as_raw (&self) -> *mut bindings::mm_struct { + self.mm.get () + } + +/// Obtain a reference from a raw pointer. +/// +/// # Safety +/// +/// The caller must ensure that `ptr` points at an `mm_struct`, and that it is not deallocated +/// during the lifetime 'a. +#[inline] +pub unsafe fn from_raw <'a>(ptr: *const bindings::mm_struct ) -> &'aMm { +// SAFETY: Caller promises that the pointer is valid for 'a. Layouts are compatible due to +// repr(transparent). +unsafe { &*ptr.cast () } + } + +/// Check whether this vma is associated with this mm. +#[inline] +pub fn is_same_mm (&self, area: &virt::VmArea ) ->bool { +// SAFETY: The `vm_mm` field of the area is immutable, so we can read it without +// synchronization. +let vm_mm =unsafe { (*area.as_ptr ()).vm_mm }; + + ptr::eq (vm_mm, self.as_raw ()) + } + +/// Calls `mmget_not_zero` and returns a handle if it succeeds. +#[inline] +pub fn mmget_not_zero (&self) ->Option <ARef <MmWithUser >> { +// SAFETY: The pointer is valid since self is a reference. +let success =unsafe { bindings::mmget_not_zero (self.as_raw ()) }; + +if success { +// SAFETY: We just created an `mmget` refcount. +Some (unsafe {ARef ::from_raw (NonNull ::new_unchecked (self.as_raw ().cast ())) }) + }else { +None + } + } +} + +// These methods require `mm_users` to be non-zero. +impl MmWithUser { +/// Obtain a reference from a raw pointer. +/// +/// # Safety +/// +/// The caller must ensure that `ptr` points at an `mm_struct`, and that `mm_users` remains +/// non-zero for the duration of the lifetime 'a. +#[inline] +pub unsafe fn from_raw <'a>(ptr: *const bindings::mm_struct ) -> &'aMmWithUser { +// SAFETY: Caller promises that the pointer is valid for 'a. The layout is compatible due +// to repr(transparent). +unsafe { &*ptr.cast () } + } + +/// Use `mmput_async` when dropping this refcount. +pub fn use_mmput_async (me:ARef <MmWithUser >) ->ARef <MmWithUserAsync > { +// SAFETY: The layouts and invariants are compatible. +unsafe {ARef ::from_raw (ARef ::into_raw (me).cast ()) } + } + +/// Lock the mmap write lock. +#[inline] +pub fn mmap_write_lock (&self) ->MmapWriteLock <'_> { +// SAFETY: The pointer is valid since self is a reference. +unsafe { bindings::mmap_write_lock (self.as_raw ()) }; + +// INVARIANT: We just acquired the write lock. +MmapWriteLock { mm: self } + } + +/// Lock the mmap read lock. +#[inline] +pub fn mmap_read_lock (&self) ->MmapReadLock <'_> { +// SAFETY: The pointer is valid since self is a reference. +unsafe { bindings::mmap_read_lock (self.as_raw ()) }; + +// INVARIANT: We just acquired the read lock. +MmapReadLock { mm: self } + } + +/// Try to lock the mmap read lock. +#[inline] +pub fn mmap_read_trylock (&self) ->Option <MmapReadLock <'_>> { +// SAFETY: The pointer is valid since self is a reference. +let success =unsafe { bindings::mmap_read_trylock (self.as_raw ()) }; + +if success { +// INVARIANT: We just acquired the read lock. +Some (MmapReadLock { mm: self }) + }else { +None + } + } +} + +impl MmWithUserAsync { +/// Use `mmput` when dropping this refcount. +pub fn use_mmput (me:ARef <MmWithUserAsync >) ->ARef <MmWithUser > { +// SAFETY: The layouts and invariants are compatible. +unsafe {ARef ::from_raw (ARef ::into_raw (me).cast ()) } + } +} + +/// A guard for the mmap read lock. +/// +/// # Invariants +/// +/// This `MmapReadLock` guard owns the mmap read lock. +pub struct MmapReadLock <'a> { + mm: &'aMmWithUser , +} + +impl <'a>MmapReadLock <'a> { +/// Look up a vma at the given address. +#[inline] +pub fn vma_lookup (&self, vma_addr:usize ) ->Option <&virt::VmArea > { +// SAFETY: We hold a reference to the mm, so the pointer must be valid. Any value is okay +// for `vma_addr`. +let vma =unsafe { bindings::vma_lookup (self.mm.as_raw (), vma_addras _ ) }; + +if vma.is_null () { +None + }else { +// SAFETY: We just checked that a vma was found, so the pointer is valid. Furthermore, +// the returned area will borrow from this read lock guard, so it can only be used +// while the read lock is still held. The returned reference is immutable, so the +// reference cannot be used to modify the area. +unsafe {Some (virt::VmArea ::from_raw_vma (vma)) } + } + } +} + +impl Drop for MmapReadLock <'_> { +#[inline] +fn drop (&mut self) { +// SAFETY: We hold the read lock by the type invariants. +unsafe { bindings::mmap_read_unlock (self.mm.as_raw ()) }; + } +} + +/// A guard for the mmap write lock. +/// +/// # Invariants
rust/kernel/mm.rs line 320
Quoted 10 lines
rust/kernel/mm.rs new file +10
-0+/// +/// This `MmapReadLock` guard owns the mmap write lock. +pub struct MmapWriteLock <'a> { + mm: &'aMmWithUser , +} + +impl <'a>MmapWriteLock <'a> { +/// Look up a vma at the given address. +#[inline] +pub fn vma_lookup (&mut self, vma_addr:usize ) ->Option <&mut virt::VmArea > {
I think this needs to be -> Option<Pin<&mut virt::VmArea>>, otherwise, you could swap two VMAs (from different MMs) while the address stability is required by themselves (list_head) or others (list_head and rb_node):
let vma1 = writer1.vma_lookup(x)?; let vma2 = writer2.vma_lookup(x)?; swap(vma1, vma2);
Quoted 13 lines
rust/kernel/mm.rs new file +13
-0+// SAFETY: We hold a reference to the mm, so the pointer must be valid. Any value is okay +// for `vma_addr`. +let vma =unsafe { bindings::vma_lookup (self.mm.as_raw (), vma_addras _ ) }; + +if vma.is_null () { +None + }else { +// SAFETY: We just checked that a vma was found, so the pointer is valid. Furthermore, +// the returned area will borrow from this write lock guard, so it can only be used +// while the write lock is still held. We hold the write lock, so mutable operations on +// the area are okay. +unsafe {Some (virt::VmArea ::from_raw_vma_mut (vma)) } + }
rust/kernel/mm.rs line 343
Quoted 10 lines
rust/kernel/mm.rs new file +10
-0+ } +} + +impl Drop for MmapWriteLock <'_> { +#[inline] +fn drop (&mut self) { +// SAFETY: We hold the write lock by the type invariants. +unsafe { bindings::mmap_write_unlock (self.mm.as_raw ()) }; + } +}
(Will review the locking part later)
Regards,
Boqun
[...]