Rust support for mm_struct, vm_area_struct, and mmap
Subsystems (4)
Alice Ryhl
maintainerv10 cover Rust support for mm_struct, vm_area_struct, and mmap
This updates the vm_area_struct support to use the approach we discussed at LPC where there are several different Rust wrappers for vm_area_struct depending on the kind of access you have to the vma. Each case allows a different set of operations on the vma.
This depends on several PULLs that have landed / are landing during the currently ongoing merge window.
To: Miguel Ojeda <[email protected]>
To: Matthew Wilcox <[email protected]>
To: Lorenzo Stoakes <[email protected]>
To: Vlastimil Babka <[email protected]>
To: John Hubbard <[email protected]>
To: Liam R. Howlett <[email protected]>
To: Andrew Morton <[email protected]>
To: Greg Kroah-Hartman <[email protected]>
To: Arnd Bergmann <[email protected]>
To: Christian Brauner <[email protected]>
To: Jann Horn <[email protected]>
To: Suren Baghdasaryan <[email protected]>
Cc: Alex Gaynor <[email protected]>
Cc: Boqun Feng <[email protected]>
Cc: Gary Guo <[email protected]>
Cc: Björn Roy Baron <[email protected]>
Cc: Benno Lossin <[email protected]>
Cc: Andreas Hindborg <[email protected]>
Cc: Trevor Gross <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: Alice Ryhl <[email protected]>
Changes in v10:
- Update docs for set_io.
- Check address in zap_page_range_single.
- Completely redo the last patch.
- Link to v9: https://lore.kernel.org/r/[email protected]
Changes in v9:
- Be more explicit about VmAreaNew being used with f_ops->mmap().
- Point out that clearing VM_MAYWRITE is irreversible.
- Use __vm_flags to set the flags.
- Use as_ and into_ prefixes for conversions.
- Update lock_vma_under_rcu docs and commit msg
- Mention that VmAreaRef::end is exclusive.
- Reword docs for zap_page_range_single.
- Minor fixes to flag docs.
- Add way to access current->mm without a refcount increment.
- Link to v8: https://lore.kernel.org/r/[email protected]
Changes in v8:
- Split series into more commits to ease review.
- Improve read locks based on Lorenzo's doc: either the mmap or vma lock can be used.
- Get rid of mmap write lock because it's possible to avoid the need for it.
- Do not allow invalid flag combinations on VmAreaNew.
- Link to v7: https://lore.kernel.org/r/[email protected]
Changes in v7:
- Make the mmap read/write lock guards respect strict owner semantics.
- Link to v6: https://lore.kernel.org/r/[email protected]
Changes in v6:
- Introduce VmArea{Ref,Mut,New} distinction.
- Add a second patchset for miscdevice.
- Rebase on char-misc-next (currently on v6.12-rc2).
- Link to v5: https://lore.kernel.org/r/[email protected]
Changes in v5:
- Rename VmArea::from_raw_vma to from_raw.
- Use Pin for mutable VmArea references.
- Go through ARef::from in mmgrab_current.
- Link to v4: https://lore.kernel.org/r/[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]
---
Alice Ryhl (8):
mm: rust: add abstraction for struct mm_struct
mm: rust: add vm_area_struct methods that require read access
mm: rust: add vm_insert_page
mm: rust: add lock_vma_under_rcu
mm: rust: add mmput_async support
mm: rust: add VmAreaNew for f_ops->mmap()
rust: miscdevice: add mmap support
task: rust: rework how current is accessed
rust/helpers/helpers.c | 1 + rust/helpers/mm.c | 50 ++++++ rust/kernel/lib.rs | 1 + rust/kernel/miscdevice.rs | 28 +++ rust/kernel/mm.rs | 323 ++++++++++++++++++++++++++++++++++ rust/kernel/mm/virt.rs | 429 ++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/task.rs | 284 +++++++++++++++++------------- 7 files changed, 999 insertions(+), 117 deletions(-)
---
base-commit: a62eb7bdef0b0009d1e141198e790fbc588ad0a1
change-id: 20240723-vma-f80119f9fb35
Best regards,
Signature · 1 line
Alice Ryhl <[email protected]>
Alice Ryhl
maintainerPATCH v10 1/8 mm: rust: add abstraction for struct mm_struct
These abstractions allow you to reference a struct mm_struct using both mmgrab and mmget refcounts. This is done using two Rust types:
* Mm - represents an mm_struct where you don't know anything about the value of mm_users.
* MmWithUser - represents an mm_struct where you know at compile time that mm_users is non-zero.
This allows us to encode in the type system whether a method requires that mm_users is non-zero or not. For instance, you can always call mmget_not_zero but you can only call mmap_read_lock when mm_users is non-zero.
It's possible to access current->mm without a refcount increment, but that is added in a later patch of this series.
--- rust/helpers/helpers.c | 1 + rust/helpers/mm.c | 39 +++++++++ rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 219 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 260 insertions(+)
rust/helpers/helpers.c +1 -0
@@ -16,6 +16,7 @@#include "fs.c" #include "jump_label.c" #include "kunit.c" +#include "mm.c" #include "mutex.c" #include "page.c" #include "pid_namespace.c"
rust/helpers/mm.c new file +39 -0
@@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/mm.h> +#include <linux/sched/mm.h> + +void rust_helper_mmgrab (struct mm_struct *mm) +{ +mmgrab (mm); +} + +void rust_helper_mmdrop (struct mm_struct *mm) +{ +mmdrop (mm); +} + +void rust_helper_mmget (struct mm_struct *mm) +{ +mmget (mm); +} + +bool rust_helper_mmget_not_zero (struct mm_struct *mm) +{ +return mmget_not_zero (mm); +} + +void rust_helper_mmap_read_lock (struct mm_struct *mm) +{ +mmap_read_lock (mm); +} + +bool rust_helper_mmap_read_trylock (struct mm_struct *mm) +{ +return mmap_read_trylock (mm); +} + +void rust_helper_mmap_read_unlock (struct mm_struct *mm) +{ +mmap_read_unlock (mm); +}
rust/kernel/lib.rs +1 -0
@@ -46,6 +46,7 @@pub mod kunit;pub mod list;pub mod miscdevice; +pub mod mm;#[cfg( CONFIG_NET )] pub mod net;pub mod page;
rust/kernel/mm.rs new file +219 -0
219 lines not on this page · raw message
Signature · 1 line
2.47.0.338.g60cca15819-goog
Alice Ryhl
maintainerPATCH v10 2/8 mm: rust: add vm_area_struct methods that require read access
In reply to Alice RyhlThis adds a type called VmAreaRef which is used when referencing a vma that you have read access to. Here, read access means that you hold either the mmap read lock or the vma read lock (or stronger).
Additionally, a vma_lookup method is added to the mmap read guard, which enables you to obtain a &VmAreaRef in safe Rust code.
This patch only provides a way to lock the mmap read lock, but a follow-up patch also provides a way to just lock the vma read lock.
--- rust/helpers/mm.c | 6 ++ rust/kernel/mm.rs | 21 ++++++ rust/kernel/mm/virt.rs | 182 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 209 insertions(+)
rust/helpers/mm.c +6 -0
@@ -37,3 +37,9 @@ void rust_helper_mmap_read_unlock(struct mm_struct *mm) {mmap_read_unlock (mm); } + +struct vm_area_struct *rust_helper_vma_lookup (struct mm_struct *mm, +unsigned long addr) +{ +return vma_lookup (mm, addr); +}
rust/kernel/mm.rs +21 -0
@@ -12,6 +12,8 @@ };use core::{ops::Deref , ptr::NonNull }; +pub mod virt; +/// A wrapper for the kernel's `struct mm_struct`. /// /// Since `mm_users` may be zero, the associated address space may not exist anymore. You can use
@@ -210,6 +212,25 @@ pub struct MmapReadGuard<'a> { _nts: NotThreadSafe, } +impl <'a>MmapReadGuard <'a> { +/// Look up a vma at the given address. +#[inline] +pub fn vma_lookup (&self, vma_addr:usize ) ->Option <&virt::VmAreaRef > { +// 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 mmap read lock is still held. +unsafe {Some (virt::VmAreaRef ::from_raw (vma)) } + } + } +} +impl Drop for MmapReadGuard <'_> {#[inline] fn drop (&mut self) {
rust/kernel/mm/virt.rs new file +182 -0
182 lines not on this page · raw message
Signature · 1 line
2.47.0.338.g60cca15819-goog
Alice Ryhl
maintainerRe: [PATCH v10 2/8] mm: rust: add vm_area_struct methods that require read access
Quoted 8 lines · Alice Ryhl
This adds a type called VmAreaRef which is used when referencing a vma that you have read access to. Here, read access means that you hold either the mmap read lock or the vma read lock (or stronger).
Additionally, a
vma_lookupmethod is added to the mmap read guard, which enables you to obtain a &VmAreaRef in safe Rust code.
Quoted 6 lines
This patch only provides a way to lock the mmap read lock, but a follow-up patch also provides a way to just lock the vma read lock.
Reviewed-by Jann Horn <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
It looks like binder needs a way to check whether a given vma is associated with a given mm. I guess we can do that by adding a method to VmAreaRef that returns a &MmWithUser.
This indicates that vma->vm_mm references an mm with non-zero mm_users whenever it's legal to have a reference to the vma.
Alice
Re: [PATCH v10 2/8] mm: rust: add vm_area_struct methods that require read access
Quoted 12 lines · Alice Ryhl
Quoted 11 lines · Alice Ryhl
This adds a type called VmAreaRef which is used when referencing a vma that you have read access to. Here, read access means that you hold either the mmap read lock or the vma read lock (or stronger).
Additionally, a
vma_lookupmethod is added to the mmap read guard, which enables you to obtain a &VmAreaRef in safe Rust code.This patch only provides a way to lock the mmap read lock, but a follow-up patch also provides a way to just lock the vma read lock.
Quoted 7 lines
Quoted 3 lines
Reviewed-by Jann Horn <[email protected]>Signed-off-by Alice Ryhl <[email protected]>It looks like binder needs a way to check whether a given vma is associated with a given mm. I guess we can do that by adding a method to VmAreaRef that returns a &MmWithUser.
Presumably this would be with a lock held to ensure the VMA doesn't disappear from under us?
I guess that's implied by possessing a VmAreaRef in the first place.
I also suppoes that the mm having users is implied by you having the VMA that implies a lock held on it :)
So that's probably fine then, as long as you can implement some sensible means of comparison between a known 'given mm' vs. the &MmWithUser.
Quoted 5 lines
This indicates that
vma->vm_mmreferences an mm with non-zeromm_userswhenever it's legal to have a reference to the vma.Alice
Alice Ryhl
maintainerRe: [PATCH v10 2/8] mm: rust: add vm_area_struct methods that require read access
Quoted 22 lines · Lorenzo Stoakes
Quoted 12 lines · Alice Ryhl
Quoted 11 lines · Alice Ryhl
This adds a type called VmAreaRef which is used when referencing a vma that you have read access to. Here, read access means that you hold either the mmap read lock or the vma read lock (or stronger).
Additionally, a
vma_lookupmethod is added to the mmap read guard, which enables you to obtain a &VmAreaRef in safe Rust code.This patch only provides a way to lock the mmap read lock, but a follow-up patch also provides a way to just lock the vma read lock.
Quoted 7 lines
Quoted 3 lines
Reviewed-by Jann Horn <[email protected]>Signed-off-by Alice Ryhl <[email protected]>It looks like binder needs a way to check whether a given vma is associated with a given mm. I guess we can do that by adding a method to VmAreaRef that returns a &MmWithUser.
Quoted 7 lines
Presumably this would be with a lock held to ensure the VMA doesn't disappear from under us?
I guess that's implied by possessing a VmAreaRef in the first place.
I also suppoes that the mm having users is implied by you having the VMA that implies a lock held on it :)
That was what I was thinking.
Quoted 2 lines
So that's probably fine then, as long as you can implement some sensible means of comparison between a known 'given mm' vs. the &MmWithUser.
We can use the stdlib function core::ptr::eq to compare the address.
Alice
Alice Ryhl
maintainerPATCH v10 3/8 mm: rust: add vm_insert_page
In reply to Alice RyhlThe vm_insert_page method is only usable on vmas with the VM_MIXEDMAP flag, so we introduce a new type to keep track of such vmas.
The approach used in this patch assumes that we will not need to encode many flag combinations in the type. I don't think we need to encode more than VM_MIXEDMAP and VM_PFNMAP as things are now. However, if that becomes necessary, using generic parameters in a single type would scale better as the number of flags increases.
--- rust/kernel/mm/virt.rs | 70 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-)
rust/kernel/mm/virt.rs +69 -1
@@ -4,7 +4,14 @@//! Virtual memory. -use crate ::{bindings, types::Opaque }; +use crate ::{ + bindings, + error::{to_result,Result }, + page::Page , + types::Opaque , +}; + +use core::ops::Deref ;/// A wrapper for the kernel's `struct vm_area_struct` with read access. ///
@@ -91,6 +98,67 @@ pub fn zap_page_range_single(&self, address: usize, size: usize) { ) }; } + +/// Check whether the `VM_MIXEDMAP` flag is set. +/// +/// This can be used to access methods that require `VM_MIXEDMAP` to be set. +#[inline] +pub fn as_mixedmap_vma (&self) ->Option <&VmAreaMixedMap > { +if self.flags () & flags::MIXEDMAP !=0 { +// SAFETY: We just checked that `VM_MIXEDMAP` is set. All other requirements are +// satisfied by the type invariants of `VmAreaRef`. +Some (unsafe {VmAreaMixedMap ::from_raw (self.as_ptr ()) }) + }else { +None + } + } +} + +/// A wrapper for the kernel's `struct vm_area_struct` with read access and `VM_MIXEDMAP` set. +/// +/// It represents an area of virtual memory. +/// +/// # Invariants +/// +/// The caller must hold the mmap read lock or the vma read lock. The `VM_MIXEDMAP` flag must be +/// set. +#[repr(transparent)] +pub struct VmAreaMixedMap { + vma:VmAreaRef , +} + +// Make all `VmAreaRef` methods available on `VmAreaMixedMap`. +impl Deref for VmAreaMixedMap { +type Target =VmAreaRef ; + +#[inline] +fn deref (&self) -> &VmAreaRef { + &self.vma + } +} + +impl VmAreaMixedMap { +/// 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 stronger) is held for at least the duration of 'a. The `VM_MIXEDMAP` flag must be set. +#[inline] +pub unsafe fn from_raw <'a>(vma: *const bindings::vm_area_struct ) -> &'aSelf { +// SAFETY: The caller ensures that the invariants are satisfied for the duration of 'a. +unsafe { &*vma.cast () } + } + +/// Maps a single page at the given address within the virtual memory area. +/// +/// This operation does not take ownership of the page. +#[inline] +pub fn vm_insert_page (&self, address:usize , page: &Page ) ->Result { +// SAFETY: The caller has read access and has verified that `VM_MIXEDMAP` is set. The page +// is order 0. The address is checked on the C side so it can take any value. +to_result (unsafe { bindings::vm_insert_page (self.as_ptr (), addressas _ , page.as_ptr ()) }) + } }/// The integer type used for vma flags.
Signature · 1 line
2.47.0.338.g60cca15819-goog
Alice Ryhl
maintainerPATCH v10 4/8 mm: rust: add lock_vma_under_rcu
In reply to Alice RyhlCurrently, the binder driver always uses the mmap lock to make changes to its vma. Because the mmap lock is global to the process, this can involve significant contention. However, the kernel has a feature called per-vma locks, which can significantly reduce contention. For example, you can take a vma lock in parallel with an mmap write lock. This is important because contention on the mmap lock has been a long-term recurring challenge for the Binder driver.
This patch introduces support for using lock_vma_under_rcu from Rust. The Rust Binder driver will be able to use this to reduce contention on the mmap lock.
--- rust/helpers/mm.c | 5 +++++ rust/kernel/mm.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+)
rust/helpers/mm.c +5 -0
@@ -43,3 +43,8 @@ struct vm_area_struct *rust_helper_vma_lookup(struct mm_struct *mm, {return vma_lookup (mm, addr); } + +void rust_helper_vma_end_read (struct vm_area_struct *vma) +{ +vma_end_read (vma); +}
rust/kernel/mm.rs +56 -0
71 lines not on this page · raw message
Signature · 1 line
2.47.0.338.g60cca15819-goog
Alice Ryhl
maintainerPATCH v10 5/8 mm: rust: add mmput_async support
In reply to Alice RyhlAdds an MmWithUserAsync type that uses mmput_async when dropped but is otherwise identical to MmWithUser. This has to be done using a separate type because the thing we are changing is the destructor.
Rust Binder needs this to avoid a certain deadlock. See commit 9a9ab0d96362 ("binder: fix race between mmput() and do_exit()") for details. It's also needed in the shrinker to avoid cleaning up the mm in the shrinker's context.
--- rust/kernel/mm.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+)
rust/kernel/mm.rs +49 -0
@@ -98,6 +98,48 @@ fn deref(&self) -> &Mm { } } +/// A wrapper for the kernel's `struct mm_struct`. +/// +/// This type is identical to `MmWithUser` except that it uses `mmput_async` when dropping a +/// refcount. This means that the destructor of `ARef<MmWithUserAsync>` is safe to call in atomic +/// context. +/// +/// # Invariants +/// +/// Values of this type are always refcounted using `mmget`. The value of `mm_users` is non-zero. +#[repr(transparent)] +pub struct MmWithUserAsync { + mm:MmWithUser , +} + +// SAFETY: It is safe to call `mmput_async` on another thread than where `mmget` was called. +unsafe impl Send for MmWithUserAsync {} +// SAFETY: All methods on `MmWithUserAsync` can be called in parallel from several threads. +unsafe impl Sync for MmWithUserAsync {} + +// SAFETY: By the type invariants, this type is always refcounted. +unsafe impl AlwaysRefCounted for MmWithUserAsync { +fn inc_ref (&self) { +// SAFETY: The pointer is valid since self is a reference. +unsafe { bindings::mmget (self.as_raw ()) }; + } + +unsafe fn dec_ref (obj:NonNull <Self >) { +// SAFETY: The caller is giving up their refcount. +unsafe { bindings::mmput_async (obj.cast ().as_ptr ()) }; + } +} + +// Make all `MmWithUser` methods available on `MmWithUserAsync`. +impl Deref for MmWithUserAsync { +type Target =MmWithUser ; + +#[inline] +fn deref (&self) -> &MmWithUser { + &self.mm + } +} +// These methods are safe to call even if `mm_users` is zero. impl Mm {/// Call `mmgrab` on `current.mm`.
@@ -171,6 +213,13 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_struct) -> &'a MmWithUser {unsafe { &*ptr.cast () } } +/// Use `mmput_async` when dropping this refcount. +#[inline] +pub fn into_mmput_async (me:ARef <MmWithUser >) ->ARef <MmWithUserAsync > { +// SAFETY: The layouts and invariants are compatible. +unsafe {ARef ::from_raw (ARef ::into_raw (me).cast ()) } + } +/// Attempt to access a vma using the vma read lock. /// /// This is an optimistic trylock operation, so it may fail if there is contention. In that
Signature · 1 line
2.47.0.338.g60cca15819-goog
Alice Ryhl
maintainerPATCH v10 6/8 mm: rust: add VmAreaNew for f_ops->mmap()
In reply to Alice RyhlThis type will be used when setting up a new vma in an f_ops->mmap() hook. Using a separate type from VmAreaRef allows us to have a separate set of operations that you are only able to use during the mmap() hook. For example, the VM_MIXEDMAP flag must not be changed after the initial setup that happens during the f_ops->mmap() hook.
To avoid setting invalid flag values, the methods for clearing VM_MAYWRITE and similar involve a check of VM_WRITE, and return an error if VM_WRITE is set. Trying to use try_clear_maywrite without checking the return value results in a compilation error because the Result type is marked #[must_use].
For now, there's only a method for VM_MIXEDMAP and not VM_PFNMAP. When we add a VM_PFNMAP method, we will need some way to prevent you from setting both VM_MIXEDMAP and VM_PFNMAP on the same vma.
--- rust/kernel/mm/virt.rs | 181 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 180 insertions(+), 1 deletion(-)
rust/kernel/mm/virt.rs +180 -1
@@ -6,7 +6,7 @@use crate ::{ bindings, - error::{to_result,Result }, + error::{code::EINVAL , to_result,Result }, page::Page , types::Opaque , };
@@ -161,6 +161,185 @@ pub fn vm_insert_page(&self, address: usize, page: &Page) -> Result { } } +/// A builder for setting up a vma in an `f_ops->mmap()` hook. +/// +/// # Invariants +/// +/// For the duration of 'a, the referenced vma must be undergoing initialization in an +/// `f_ops->mmap()` hook. +pub struct VmAreaNew { + vma:VmAreaRef , +} + +// Make all `VmAreaRef` methods available on `VmAreaNew`. +impl Deref for VmAreaNew { +type Target =VmAreaRef ; + +#[inline] +fn deref (&self) -> &VmAreaRef { + &self.vma + } +} + +impl VmAreaNew { +/// Access a virtual memory area given a raw pointer. +/// +/// # Safety +/// +/// Callers must ensure that `vma` is undergoing initial vma setup for the duration of 'a. +#[inline] +pub unsafe fn from_raw <'a>(vma: *const bindings::vm_area_struct ) -> &'aSelf { +// SAFETY: The caller ensures that the invariants are satisfied for the duration of 'a. +unsafe { &*vma.cast () } + } + +/// Internal method for updating the vma flags. +/// +/// # Safety +/// +/// This must not be used to set the flags to an invalid value. +#[inline] +unsafe fn update_flags (&self, set:vm_flags_t , unset:vm_flags_t ) { +let mut flags = self.flags (); + flags |= set; + flags &= !unset; + +// SAFETY: This is not a data race: the vma is undergoing initial setup, so it's not yet +// shared. Additionally, `VmAreaNew` is `!Sync`, so it cannot be used to write in parallel. +// The caller promises that this does not set the flags to an invalid value. +unsafe { (*self.as_ptr ()).__bindgen_anon_2.__vm_flags = flags }; + } + +/// Set the `VM_MIXEDMAP` flag on this vma. +/// +/// This enables the vma to contain both `struct page` and pure PFN pages. Returns a reference +/// that can be used to call `vm_insert_page` on the vma. +#[inline] +pub fn set_mixedmap (&self) -> &VmAreaMixedMap { +// SAFETY: We don't yet provide a way to set VM_PFNMAP, so this cannot put the flags in an +// invalid state. +unsafe { self.update_flags (flags::MIXEDMAP ,0 ) }; + +// SAFETY: We just set `VM_MIXEDMAP` on the vma. +unsafe {VmAreaMixedMap ::from_raw (self.vma.as_ptr ()) } + } + +/// Set the `VM_IO` flag on this vma. +/// +/// This is used for memory mapped IO and similar. The flag tells other parts of the kernel to +/// avoid looking at the pages. For memory mapped IO this is useful as accesses to the pages +/// could have side effects. +#[inline] +pub fn set_io (&self) { +// SAFETY: Setting the VM_IO flag is always okay. +unsafe { self.update_flags (flags::IO ,0 ) }; + } + +/// Set the `VM_DONTEXPAND` flag on this vma. +/// +/// This prevents the vma from being expanded with `mremap()`. +#[inline] +pub fn set_dontexpand (&self) { +// SAFETY: Setting the VM_DONTEXPAND flag is always okay. +unsafe { self.update_flags (flags::DONTEXPAND ,0 ) }; + } + +/// Set the `VM_DONTCOPY` flag on this vma. +/// +/// This prevents the vma from being copied on fork. This option is only permanent if `VM_IO` +/// is set. +#[inline] +pub fn set_dontcopy (&self) { +// SAFETY: Setting the VM_DONTCOPY flag is always okay. +unsafe { self.update_flags (flags::DONTCOPY ,0 ) }; + } + +/// Set the `VM_DONTDUMP` flag on this vma. +/// +/// This prevents the vma from being included in core dumps. This option is only permanent if +/// `VM_IO` is set. +#[inline] +pub fn set_dontdump (&self) { +// SAFETY: Setting the VM_DONTDUMP flag is always okay. +unsafe { self.update_flags (flags::DONTDUMP ,0 ) }; + } + +/// Returns whether `VM_READ` is set. +/// +/// This flag indicates whether userspace is mapping this vma as readable. +#[inline] +pub fn get_read (&self) ->bool { + (self.flags () & flags::READ ) !=0 + } + +/// Try to clear the `VM_MAYREAD` flag, failing if `VM_READ` is set. +/// +/// This flag indicates whether userspace is allowed to make this vma readable with +/// `mprotect()`. +/// +/// Note that this operation is irreversible. Once `VM_MAYREAD` has been cleared, it can never +/// be set again. +#[inline] +pub fn try_clear_mayread (&self) ->Result { +if self.get_read () { +return Err (EINVAL ); + } +// SAFETY: Clearing `VM_MAYREAD` is okay when `VM_READ` is not set. +unsafe { self.update_flags (0 , flags::MAYREAD ) }; +Ok (()) + } + +/// Returns whether `VM_WRITE` is set. +/// +/// This flag indicates whether userspace is mapping this vma as writable. +#[inline] +pub fn get_write (&self) ->bool { + (self.flags () & flags::WRITE ) !=0 + } + +/// Try to clear the `VM_MAYWRITE` flag, failing if `VM_WRITE` is set. +/// +/// This flag indicates whether userspace is allowed to make this vma writable with +/// `mprotect()`. +/// +/// Note that this operation is irreversible. Once `VM_MAYWRITE` has been cleared, it can never +/// be set again. +#[inline] +pub fn try_clear_maywrite (&self) ->Result { +if self.get_write () { +return Err (EINVAL ); + } +// SAFETY: Clearing `VM_MAYWRITE` is okay when `VM_WRITE` is not set. +unsafe { self.update_flags (0 , flags::MAYWRITE ) }; +Ok (()) + } + +/// Returns whether `VM_EXEC` is set. +/// +/// This flag indicates whether userspace is mapping this vma as executable. +#[inline] +pub fn get_exec (&self) ->bool { + (self.flags () & flags::EXEC ) !=0 + } + +/// Try to clear the `VM_MAYEXEC` flag, failing if `VM_EXEC` is set. +/// +/// This flag indicates whether userspace is allowed to make this vma executable with +/// `mprotect()`. +/// +/// Note that this operation is irreversible. Once `VM_MAYEXEC` has been cleared, it can never +/// be set again. +#[inline] +pub fn try_clear_mayexec (&self) ->Result { +if self.get_exec () { +return Err (EINVAL ); + } +// SAFETY: Clearing `VM_MAYEXEC` is okay when `VM_EXEC` is not set. +unsafe { self.update_flags (0 , flags::MAYEXEC ) }; +Ok (()) + } +} +/// The integer type used for vma flags. #[doc(inline)] pub use bindings::vm_flags_t;
Signature · 1 line
2.47.0.338.g60cca15819-goog
Alice Ryhl
maintainerPATCH v10 7/8 rust: miscdevice: add mmap support
In reply to Alice RyhlAdd the ability to write a file_operations->mmap hook in Rust when using the miscdevice abstraction. The vma argument to the mmap hook uses the VmAreaNew type from the previous commit; this type provides the correct set of operations for a file_operations->mmap hook.
--- rust/kernel/miscdevice.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+)
rust/kernel/miscdevice.rs +28 -0
@@ -11,6 +11,7 @@use crate ::{ bindings, error::{to_result,Error ,Result ,VTABLE_DEFAULT_ERROR }, + mm::virt::VmAreaNew , prelude::*, str::CStr , types::{ForeignOwnable ,Opaque },
@@ -110,6 +111,11 @@ fn release(device: Self::Ptr) {drop (device); } +/// Handle for mmap. +fn mmap (_device: <Self ::Ptr as ForeignOwnable >::Borrowed <'_>, _vma: &VmAreaNew ) ->Result { + kernel::build_error!(VTABLE_DEFAULT_ERROR ) + } +/// Handler for ioctls. /// /// The `cmd` argument is usually manipulated using the utilties in [`kernel::ioctl`].
@@ -156,6 +162,7 @@ impl<T: MiscDevice> VtableHelper<T> {const VTABLE : bindings::file_operations = bindings::file_operations { open:Some (fops_open ::<T >), release:Some (fops_release ::<T >), + mmap:maybe_fn (T ::HAS_MMAP ,fops_mmap ::<T >), unlocked_ioctl:maybe_fn (T ::HAS_IOCTL ,fops_ioctl ::<T >),#[cfg( CONFIG_COMPAT )] compat_ioctl:if T ::HAS_COMPAT_IOCTL {
@@ -216,6 +223,27 @@ impl<T: MiscDevice> VtableHelper<T> {0 } +/// # Safety +/// +/// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`. +/// `vma` must be a vma that is currently being mmap'ed with this file. +unsafe extern "C" fn fops_mmap <T :MiscDevice >( + file: *mut bindings::file , + vma: *mut bindings::vm_area_struct , +) ->c_int { +// SAFETY: The mmap call of a file can access the private data. +let private =unsafe { (*file).private_data }; +// SAFETY: Mmap calls can borrow the private data of the file. +let device =unsafe { <T ::Ptr as ForeignOwnable >::borrow (private) }; +// SAFETY: The caller provides a vma that is undergoing initial VMA setup. +let area =unsafe {VmAreaNew ::from_raw (vma) }; + +match T ::mmap (device, area) { +Ok (()) =>0 , +Err (err) => err.to_errno ()as c_int , + } +} +/// # Safety /// /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
Signature · 1 line
2.47.0.338.g60cca15819-goog
Alice Ryhl
maintainerPATCH v10 8/8 task: rust: rework how current is accessed
In reply to Alice RyhlIntroduce a new type called CurrentTask that lets you perform various operations that are only safe on the current task. Use the new type to provide a way to access the current mm without incrementing its refcount.
With this change, you can write stuff such as
let vma = current!().mm().lock_vma_under_rcu(addr);
without incrementing any refcounts.
This replaces the existing abstractions for accessing the current pid namespace. With the old approach, every field access to current involves both a macro and a unsafe helper function. The new approach simplifies that to a single safe function on the CurrentTask type. This makes it less heavy-weight to add additional current accessors in the future.
That said, creating a CurrentTask type like the one in this patch requires that we are careful to ensure that it cannot escape the current task or otherwise access things after they are freed. To do this, I declared that it cannot escape the current "task context" where I defined a "task context" as essentially the region in which current remains unchanged. So e.g., release_task() or begin_new_exec() would leave the task context.
If a userspace thread returns to userspace and later makes another syscall, then I consider the two syscalls to be different task contexts. This allows values stored in that task to be modified between syscalls, even if they're guaranteed to be immutable during a syscall.
Ensuring correctness of CurrentTask is slightly tricky if we also want the ability to have a safe kthread_use_mm() implementation in Rust. To support that safely, there are two patterns we need to ensure are safe:
// Case 1: current!() called inside the scope.
let mm;
kthread_use_mm(some_mm, || {
mm = current!().mm();
});
drop(some_mm);
mm.do_something(); // UAFand:
// Case 2: current!() called before the scope.
let mm;
let task = current!();
kthread_use_mm(some_mm, || {
mm = task.mm();
});
drop(some_mm);
mm.do_something(); // UAFThe existing current!() abstraction already natively prevents the first case: The &CurrentTask would be tied to the inner scope, so the borrow-checker ensures that no reference derived from it can escape the scope.
Fixing the second case is a bit more tricky. The solution is to essentially pretend that the contents of the scope execute on an different thread, which means that only thread-safe types can cross the boundary. Since CurrentTask is marked NotThreadSafe, attempts to move it to another thread will fail, and this includes our fake pretend thread boundary.
This has the disadvantage that other types that aren't thread-safe for reasons unrelated to current also cannot be moved across the kthread_use_mm() boundary. I consider this an acceptable tradeoff.
--- rust/kernel/mm.rs | 22 ---- rust/kernel/task.rs | 284 ++++++++++++++++++++++++++++++---------------------- 2 files changed, 167 insertions(+), 139 deletions(-)
rust/kernel/mm.rs +0 -22
@@ -142,28 +142,6 @@ fn deref(&self) -> &MmWithUser {// 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 - }; - -if mm.is_null () { -return None ; - } - -// SAFETY: The value of `current->mm` is guaranteed to be null or a valid `mm_struct`. We -// just checked that it's not null. Furthermore, the returned `&Mm` is valid only for the -// duration of this function, and `current->mm` will stay valid for that long. -let mm =unsafe {Mm ::from_raw (mm) }; - -// This increments the refcount using `mmgrab`. -Some (ARef ::from (mm)) - } -/// Returns a raw pointer to the inner `mm_struct`. #[inline] pub fn as_raw (&self) -> *mut bindings::mm_struct {
rust/kernel/task.rs +167 -117
326 lines not on this page · raw message
Signature · 1 line
2.47.0.338.g60cca15819-goog