Skip to contentSkip to conversation

rust: mm: add abstractions for mm_struct and vm_area_struct

PATCH Superseded Alice Ryhl 3 participants 10 messages Jul 23, 2024 – Jul 26, 2024

Subsystems (3)

v1 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Alice Ryhl

author maintainer
#0 lore raw

PATCH 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.

The ARef wrapper is not used for mm_struct because there are several different types of refcounts.

This patch is based on Wedson's implementation on the old rust branch, but has been changed significantly. All mistakes are Alice's.

---
 rust/helpers.c         |  49 ++++++++++
 rust/kernel/lib.rs     |   1 +
 rust/kernel/mm.rs      | 259 +++++++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/mm/virt.rs | 193 ++++++++++++++++++++++++++++++++++++
 4 files changed, 502 insertions(+)
rust/helpers.c +49 -0
index 305f0577fae9..9aa5150ebe26 100644
@@ -199,6 +199,55 @@ 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);
+
+bool rust_helper_mmget_not_zero(struct mm_struct *mm)
+{
+	return mmget_not_zero(mm);
+}
+EXPORT_SYMBOL_GPL(rust_helper_mmget_not_zero);
+
+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
index 5d310e79485f..3cbc4cf847a2 100644
@@ -33,6 +33,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 +259 -0

259 lines not on this page · raw message

rust/kernel/mm/virt.rs new file +193 -0

193 lines not on this page · raw message

---
base-commit: b1263411112305acf2af728728591465becb45b0
change-id: 20240723-vma-f80119f9fb35

Best regards,

Signature · 1 line
Alice Ryhl <[email protected]>
#1 lore raw
Quoted 1 line · Alice Ryhl

+// SAFETY: It is safe to call mmdrop on another thread than where mmgrab was called.

If I were reading the documentation, I might want to know if it's safe to call in interrupt context (either soft or hard). ie can mmdrop sleep (if it turns out to be the last owner of the mm).

rust/kernel/mm/virt.rs line 20

Quoted 7 lines
rust/kernel/mm/virt.rs new file +7 -0
+/// A wrapper for the kernel's `struct vm_area_struct`.
+///
+/// It represents an area of virtual memory.
+#[repr(transparent)]
+pub struct Area {
+    vma: Opaque<bindings::vm_area_struct>,
+}

That seems like a very generic name! MMArea? VMA? Certainly when I'm talking to people, I say VMA. struct vm_area_struct is a terrible name and I'd be happy to change it if we could stomach that churn. If I were naming it today, I'd want to call it struct mm_area.

author maintainer
#2 lore raw
Quoted 7 lines · Matthew Wilcox
Quoted 1 line · Alice Ryhl

+// SAFETY: It is safe to call mmdrop on another thread than where mmgrab was called.

If I were reading the documentation, I might want to know if it's safe to call in interrupt context (either soft or hard). ie can mmdrop sleep (if it turns out to be the last owner of the mm).

I'll add some information on that.

Quoted 4 lines
Quoted 4 lines
rust/kernel/mm/virt.rs new file +4 -0
+/// A wrapper for the kernel's `struct vm_area_struct`.
+///
+/// It represents an area of virtual memory.
+#[repr(transparent)]
Quoted 8 lines

rust/kernel/mm/virt.rs line 20

Quoted 3 lines
rust/kernel/mm/virt.rs new file +3 -0
+pub struct Area {
+    vma: Opaque<bindings::vm_area_struct>,
+}

That seems like a very generic name! MMArea? VMA? Certainly when I'm talking to people, I say VMA. struct vm_area_struct is a terrible name and I'd be happy to change it if we could stomach that churn. If I were naming it today, I'd want to call it struct mm_area.

Yeah, you're right. I should change it. Renaming the C struct seems like it would be a lot of work. For now, I'll rename it to VmArea to match C.

Alice

#3 lore raw
In reply to Alice Ryhl
Quoted 6 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.

The ARef wrapper is not used for mm_struct because there are several different types of refcounts.

I am confused, why can't you use the ARef wrapper for the different types that you create below?

Quoted 101 lines

This patch is based on Wedson's implementation on the old rust branch, but has been changed significantly. All mistakes are Alice's.

---
 rust/helpers.c         |  49 ++++++++++
 rust/kernel/lib.rs     |   1 +
 rust/kernel/mm.rs      | 259 +++++++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/mm/virt.rs | 193 ++++++++++++++++++++++++++++++++++++
 4 files changed, 502 insertions(+)
rust/helpers.c +49 -0
index 305f0577fae9..9aa5150ebe26 100644
@@ -199,6 +199,55 @@ 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);
+
+bool rust_helper_mmget_not_zero(struct mm_struct *mm)
+{
+	return mmget_not_zero(mm);
+}
+EXPORT_SYMBOL_GPL(rust_helper_mmget_not_zero);
+
+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
index 5d310e79485f..3cbc4cf847a2 100644
@@ -33,6 +33,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 +9 -0
new file mode 100644
index 000000000000..7fa1e2431944
@@ -0,0 +1,259 @@
+// SPDX-License-Identifier: GPL-2.0
+
+// Copyright (C) 2024 Google LLC.
+
+//! Memory management.
+//!
+//! C header: [`include/linux/mm.h`](../../../../include/linux/mm.h)
+
+use crate::bindings;

rust/kernel/mm.rs line 19

Quoted 10 lines
rust/kernel/mm.rs new file +10 -0
+
+use core::{marker::PhantomData, mem::ManuallyDrop, ptr::NonNull};
+
+pub mod virt;
+
+/// A smart pointer that references a `struct mm` and owns an `mmgrab` refcount.
+///
+/// # Invariants
+///
+/// An `MmGrab` owns an `mmgrab` refcount to the inner `struct mm_struct`.

You also need that mm is a valid pointer.

Quoted 47 lines
rust/kernel/mm.rs new file +47 -0
+pub struct MmGrab {
+    mm: NonNull<bindings::mm_struct>,
+}
+
+impl MmGrab {
+    /// Call `mmgrab` on `current.mm`.
+    #[inline]
+    pub fn mmgrab_current() -> Option<Self> {
+        // SAFETY: It's safe to get the `mm` field from current.
+        let mm = unsafe {
+            let current = bindings::get_current();
+            (*current).mm
+        };
+
+        let mm = NonNull::new(mm)?;
+
+        // SAFETY: We just checked that `mm` is not null.
+        unsafe { bindings::mmgrab(mm.as_ptr()) };
+
+        // INVARIANT: We just created an `mmgrab` refcount.
+        Some(Self { mm })
+    }
+
+    /// Check whether this vma is associated with this mm.
+    #[inline]
+    pub fn is_same_mm(&self, area: &virt::Area) -> 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 };
+
+        vm_mm == self.mm.as_ptr()
+    }
+
+    /// Calls `mmget_not_zero` and returns a handle if it succeeds.
+    #[inline]
+    pub fn mmget_not_zero(&self) -> Option<MmGet> {
+        // SAFETY: We know that `mm` is still valid since we hold an `mmgrab` refcount.
+        let success = unsafe { bindings::mmget_not_zero(self.mm.as_ptr()) };
+
+        if success {
+            Some(MmGet { mm: self.mm })
+        } else {
+            None
+        }
+    }
+}
+

rust/kernel/mm.rs line 76

Quoted 10 lines
rust/kernel/mm.rs new file +10 -0
+// SAFETY: It is safe to call `mmdrop` on another thread than where `mmgrab` was called.
+unsafe impl Send for MmGrab {}
+// SAFETY: All methods on this struct are safe to call in parallel from several threads.
+unsafe impl Sync for MmGrab {}
+
+impl Drop for MmGrab {
+    #[inline]
+    fn drop(&mut self) {
+        // SAFETY: This gives up an `mmgrab` refcount to a valid `struct mm_struct`.
+        // INVARIANT: We own an `mmgrab` refcount, so we can give it up.

This INVARIANT comment seems out of place and the SAFETY comment should probably be "By the type invariant of Self, we own an mmgrab refcount and self.mm is valid.".

rust/kernel/mm.rs line 87

Quoted 11 lines
rust/kernel/mm.rs new file +11 -0
+        unsafe { bindings::mmdrop(self.mm.as_ptr()) };
+    }
+}
+
+/// A smart pointer that references a `struct mm` and owns an `mmget` refcount.
+///
+/// Values of this type are created using [`MmGrab::mmget_not_zero`].
+///
+/// # Invariants
+///
+/// An `MmGet` owns an `mmget` refcount to the inner `struct mm_struct`.

Ditto with the valid pointer here and below.

Quoted 12 lines
rust/kernel/mm.rs new file +12 -0
+pub struct MmGet {
+    mm: NonNull<bindings::mm_struct>,
+}
+
+impl MmGet {
+    /// Lock the mmap read lock.
+    #[inline]
+    pub fn mmap_write_lock(&self) -> MmapWriteLock<'_> {
+        // SAFETY: The pointer is valid since we hold a refcount.
+        unsafe { bindings::mmap_write_lock(self.mm.as_ptr()) };
+
+        // INVARIANT: We just acquired the write lock, so we can transfer to this guard.

rust/kernel/mm.rs line 109

Quoted 10 lines
rust/kernel/mm.rs new file +10 -0
+        //
+        // The signature of this function ensures that the `MmapWriteLock` will not outlive this
+        // `mmget` refcount.
+        MmapWriteLock {
+            mm: self.mm,
+            _lifetime: PhantomData,
+        }
+    }
+
+    /// When dropping this refcount, use `mmput_async` instead of `mmput`.

I don't get this comment.

rust/kernel/mm.rs line 122

Quoted 13 lines
rust/kernel/mm.rs new file +13 -0
+    #[inline]
+    pub fn use_async_put(self) -> MmGetAsync {
+        // Disable destructor of `self`.
+        let me = ManuallyDrop::new(self);
+
+        MmGetAsync { mm: me.mm }
+    }
+}
+
+impl Drop for MmGet {
+    #[inline]
+    fn drop(&mut self) {
+        // SAFETY: We acquired a refcount when creating this object.

You can just copy-paste the SAFETY comment from above (if you don't use the ARef pattern). Ditto below.

---
Cheers,
Benno

Quoted 4 lines
rust/kernel/mm.rs new file +4 -0
+        unsafe { bindings::mmput(self.mm.as_ptr()) };
+    }
+}
+
author maintainer
#4 lore raw
Quoted 18 lines · Benno Lossin
Quoted 16 lines · Alice Ryhl
rust/kernel/mm.rs new file +16 -0
+pub struct MmGet {
+    mm: NonNull<bindings::mm_struct>,
+}
+
+impl MmGet {
+    /// Lock the mmap read lock.
+    #[inline]
+    pub fn mmap_write_lock(&self) -> MmapWriteLock<'_> {
+        // SAFETY: The pointer is valid since we hold a refcount.
+        unsafe { bindings::mmap_write_lock(self.mm.as_ptr()) };
+
+        // INVARIANT: We just acquired the write lock, so we can transfer to this guard.
+        //
+        // The signature of this function ensures that the `MmapWriteLock` will not outlive this
+        // `mmget` refcount.
+        MmapWriteLock {
Quoted 8 lines

rust/kernel/mm.rs line 109

Quoted 6 lines
rust/kernel/mm.rs new file +6 -0
+            mm: self.mm,
+            _lifetime: PhantomData,
+        }
+    }
+
+    /// When dropping this refcount, use `mmput_async` instead of `mmput`.

I don't get this comment.

The C side provides two ways to decrement the mmget refcount. One is mmput and the other is mmput_async. The difference is that when the refcount hits zero, mmput_async cleans up the mm_struct on the workqueue, whereas mmput cleans it up immediately. This means that mmput_async is safe in atomic context, but mmput is not.

Alice

#5 lore raw
Quoted 28 lines · Alice Ryhl
Quoted 18 lines · Benno Lossin
Quoted 16 lines · Alice Ryhl
rust/kernel/mm.rs new file +16 -0
+pub struct MmGet {
+    mm: NonNull<bindings::mm_struct>,
+}
+
+impl MmGet {
+    /// Lock the mmap read lock.
+    #[inline]
+    pub fn mmap_write_lock(&self) -> MmapWriteLock<'_> {
+        // SAFETY: The pointer is valid since we hold a refcount.
+        unsafe { bindings::mmap_write_lock(self.mm.as_ptr()) };
+
+        // INVARIANT: We just acquired the write lock, so we can transfer to this guard.
+        //
+        // The signature of this function ensures that the `MmapWriteLock` will not outlive this
+        // `mmget` refcount.
+        MmapWriteLock {
Quoted 8 lines

rust/kernel/mm.rs line 109

Quoted 6 lines
rust/kernel/mm.rs new file +6 -0
+            mm: self.mm,
+            _lifetime: PhantomData,
+        }
+    }
+
+    /// When dropping this refcount, use `mmput_async` instead of `mmput`.

I don't get this comment.

Quoted 5 lines

The C side provides two ways to decrement the mmget refcount. One is mmput and the other is mmput_async. The difference is that when the refcount hits zero, mmput_async cleans up the mm_struct on the workqueue, whereas mmput cleans it up immediately. This means that mmput_async is safe in atomic context, but mmput is not.

I see, IMO this would be a better comment:

/// Converts to this MmGet to MmGetAsync.
///
/// MmGetAsync uses mmput_async instead of mmput for decrementing /// the refcount.

Since from a Rust perspective, this is just a conversion function. Maybe the name should also reflect that ie to_mm_get_async or similar.

---
Cheers,
Benno

author maintainer
#6 lore raw
Quoted 38 lines · Benno Lossin
Quoted 28 lines · Alice Ryhl
Quoted 18 lines · Benno Lossin
Quoted 16 lines · Alice Ryhl
rust/kernel/mm.rs new file +16 -0
+pub struct MmGet {
+    mm: NonNull<bindings::mm_struct>,
+}
+
+impl MmGet {
+    /// Lock the mmap read lock.
+    #[inline]
+    pub fn mmap_write_lock(&self) -> MmapWriteLock<'_> {
+        // SAFETY: The pointer is valid since we hold a refcount.
+        unsafe { bindings::mmap_write_lock(self.mm.as_ptr()) };
+
+        // INVARIANT: We just acquired the write lock, so we can transfer to this guard.
+        //
+        // The signature of this function ensures that the `MmapWriteLock` will not outlive this
+        // `mmget` refcount.
+        MmapWriteLock {
Quoted 8 lines

rust/kernel/mm.rs line 109

Quoted 6 lines
rust/kernel/mm.rs new file +6 -0
+            mm: self.mm,
+            _lifetime: PhantomData,
+        }
+    }
+
+    /// When dropping this refcount, use `mmput_async` instead of `mmput`.

I don't get this comment.

Quoted 5 lines

The C side provides two ways to decrement the mmget refcount. One is mmput and the other is mmput_async. The difference is that when the refcount hits zero, mmput_async cleans up the mm_struct on the workqueue, whereas mmput cleans it up immediately. This means that mmput_async is safe in atomic context, but mmput is not.

I see, IMO this would be a better comment:

Quoted 7 lines

/// Converts to this MmGet to MmGetAsync.
///
/// MmGetAsync uses mmput_async instead of mmput for decrementing /// the refcount.

Since from a Rust perspective, this is just a conversion function. Maybe the name should also reflect that ie to_mm_get_async or similar.

That sounds good to me.

Alice

author maintainer
#7 lore raw
In reply to Benno Lossin
Quoted 11 lines · Benno Lossin
Quoted 6 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.

The ARef wrapper is not used for mm_struct because there are several different types of refcounts.

I am confused, why can't you use the ARef wrapper for the different types that you create below?

Well, maybe I can, but it means we have several wrapper structs of Opaque<mm_struct>. Would it not be confusing? Could you suggest a naming scheme for the structs I should have?

Alice

#8 lore raw
Quoted 10 lines · Alice Ryhl
Quoted 9 lines · Benno Lossin
Quoted 6 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.

The ARef wrapper is not used for mm_struct because there are several different types of refcounts.

Quoted 6 lines
Quoted 2 lines

I am confused, why can't you use the ARef wrapper for the different types that you create below?

Well, maybe I can, but it means we have several wrapper structs of Opaque<mm_struct>. Would it not be confusing? Could you suggest a naming scheme for the structs I should have?

I don't know of a good way to avoid that, IMO your current implementation has the same issue (multiple wrappers). So I don't think it's that bad to have multiple wrappers for one C struct.
We could also use generics to solve this, right? I am not sure about the ergonomics/looks, so for example:
- ARef<Mm<Grab>>
- ARef<Mm<Get>>
- ARef<Mm<Async>>

I think it looks fine, then you also only have one struct wrapper.

BTW what does "mm" stand for? Memory management?

---
Cheers,
Benno

author maintainer
#9 lore raw
Quoted 28 lines · Benno Lossin
Quoted 10 lines · Alice Ryhl
Quoted 9 lines · Benno Lossin
Quoted 6 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.

The ARef wrapper is not used for mm_struct because there are several different types of refcounts.

Quoted 6 lines
Quoted 2 lines

I am confused, why can't you use the ARef wrapper for the different types that you create below?

Well, maybe I can, but it means we have several wrapper structs of Opaque<mm_struct>. Would it not be confusing? Could you suggest a naming scheme for the structs I should have?

I don't know of a good way to avoid that, IMO your current implementation has the same issue (multiple wrappers). So I don't think it's that bad to have multiple wrappers for one C struct.
We could also use generics to solve this, right? I am not sure about the ergonomics/looks, so for example:
- ARef<Mm<Grab>>
- ARef<Mm<Get>>
- ARef<Mm<Async>>

Quoted 3 lines

I think it looks fine, then you also only have one struct wrapper.

BTW what does "mm" stand for? Memory management?

mm stands for memory management. Basically, an mm_struct keeps track of the address space of a process, as far as I understand.

Alice