Skip to contentSkip to conversation

rust: page: add page kinds

PATCH In review Andreas Hindborg 3 participants 13 messages Nov 18 – Nov 20

Subsystems (8)
lore
Share & tools
lore

Andreas Hindborg

author reviewer
#0 lore raw

v22 cover rust: page: add page kinds

Note: The page patches were part of the Ownable series [1] until v21. This series continues the version numbering of that series, and it depends on v22 of that series for Ownable, Owned and the split of RefCounted and AlwaysRefCounted.

Not all pages can be treated the same way. A page allocated with alloc_pages() is managed by the page reference count, and kernel C code routinely takes its own references to such a page. A page owned by the slab allocator must not have references taken to it, but it can still show up in places such as a bio vector. A frozen page has a reference count of zero and is exclusively owned by the party that allocated it.

A single Page type cannot describe all of these. This series makes Page generic over a sealed PageKind that describes what is known about the page:

- Page<Base> is the base kind. Nothing is known about the page beyond the validity of the struct page.
- Page<RefCounted> is the default kind. The page is managed by the page reference count, and Page<RefCounted> implements AlwaysRefCounted.
- Page<Exclusive> is a uniquely owned frozen page whose data area follows standard Rust aliasing rules, so the data is available as &[u8] and &mut [u8]. It is handled through Owned<Page<Exclusive>> and is the first in-tree user of Owned.
- Page<Frozen> is a frozen page whose allocation is uniquely owned. Unlike for Page<Exclusive>, nothing is known about who accesses the data of the page, so the data is only available through the unsafe raw accessors.

Operations that are valid for any page are available for all page kinds. All other page kinds dereference to Page<Base>. The purpose of the dereference is coercion: a reference to a page of any kind can be passed to code that takes a &Page<Base>.

Page<Exclusive> is backed by a frozen page, as suggested by Matthew Wilcox in the review of v21. References cannot be taken to a frozen page, so the exclusive ownership is upheld by mm rather than only by the Rust type system.

Patch 1 adds the page kinds Base and RefCounted, makes Page<RefCounted> reference counted, and updates the users of Page.

Patch 2 adds Page::from_raw().

Patch 3 makes alloc_frozen_pages() and free_frozen_pages() available outside of mm. The choice of include/linux/gfp.h as the new home of the declarations is open for discussion.

Patch 4 adds the page kind Exclusive.

Patch 5 adds the page kind Frozen. It has no user in this series and can be dropped if it is not wanted at this time.

Patch 6 adds slice access to the data of a Page<Exclusive>, and tightens the safety requirements of the raw data accessors accordingly.

[1] https://msgid.link/[email protected]

---
Changes in v22:
- Split the Page patches out of the Ownable series.
- Make Page generic over a PageKind, with the kinds Base, RefCounted, Frozen and Exclusive. Page<Exclusive> replaces the ExclusivePage type (Andreas).
- Back Page<Exclusive> by a frozen page (Matthew).
- Add a patch that makes alloc_frozen_pages() and free_frozen_pages() available outside of mm.
- Add the page kind Frozen in a separate patch (Andreas).
- Return &Page<Base> from Vmalloc::to_page() and AsPageIter, as these pages are not known to be reference counted.
- Make Page::from_raw() available for all page kinds. The caller selects the kind and upholds its invariants.
- Rename ExclusivePage::alloc_page() to Page::alloc_exclusive() (Andreas).
- Let Page<Exclusive> dereference to Page<Base> (Andreas).
- Add Page::as_slice() and Page::as_mut_slice() for Page<Exclusive> in a separate patch. Always zero the page and never allocate it from highmem, and require callers of the raw data accessors to ensure that no conflicting reference to the data exists. Update the safety comments of the existing callers (Andreas).
- Justify the AlwaysRefCounted implementation for Page by all instances of the type being reference counted, rather than by the type not implementing Ownable (Alice, Gary).
- Tighten the safety requirements of Page::from_raw() to require, for Page<RefCounted>, that the page is reference counted and that taking additional references is permitted (Sashiko).
- Mark Page::alloc_exclusive() as #[inline] (Sashiko).
- Drop the Reviewed-by tag from the Page::from_raw() patch, as its safety requirements changed.
- Link to v21: https://msgid.link/[email protected]

The entries below are the Page related changes from the change log of the Ownable series.

Changes in v21:
- Import Page directly in allocator.rs instead of using the page::Page path (Danilo).
- Convert Page to AlwaysRefCounted backed by get_page() and put_page() instead of Ownable, and return ARef<Page> from Page::alloc_page() (Alice).
- Update Rust Binder to store ARef<Page> instead of Owned<Page> (Alice).
- Add ExclusivePage as the in-tree Owned user, without Deref<Target = Page> as that would break its aliasing invariant. The type was previously posted as SafePage and is renamed here (Alice).
- Link to v20: https://msgid.link/[email protected]

Changes in v20:
- Use self.page.get() rather than Opaque::cast_into (Alice).
- Link to v19: https://msgid.link/[email protected]

Changes in v18:
- Remove BorrowedPage; use &Page directly (Alice).
- Update Rust Binder for the Owned<Page> conversion (Alice).
- Fix stale Page docs (Sashiko).
- Link to v17: https://msgid.link/[email protected]

Changes in v16:
- Simplify pointer to reference cast in Page::from_raw.
- Use NonNull<Page> rather than Owned<Page> for BorrowedPage internals.
- Fix formatting for Page::from_raw docs.
- Link to v15: https://msgid.link/[email protected]

Changes in v14:
- Add patch: rust: page: convert to Ownable.
- Add patch: rust: page: add from_raw().
- Link to v13: https://lore.kernel.org/r/[email protected]

---
Andreas Hindborg (6):
rust: page: add page kinds and make Page reference counted
rust: page: add from_raw()
mm/page_alloc: make alloc_frozen_pages() available outside of mm
rust: page: add Exclusive page kind for race-free page access
rust: page: add Frozen page kind
rust: page: add slice access to Page<Exclusive>

 drivers/android/binder/page_range.rs |  24 +-
 include/linux/gfp.h                  |   9 +
 mm/mempolicy.c                       |   1 +
 mm/page_alloc.c                      |  10 +
 mm/page_alloc.h                      |  14 -
 rust/helpers/page.c                  |  21 ++
 rust/kernel/alloc/allocator.rs       |  29 ++-
 rust/kernel/alloc/allocator/iter.rs  |   7 +-
 rust/kernel/alloc/kbox.rs            |   3 +-
 rust/kernel/alloc/kvec.rs            |   3 +-
 rust/kernel/page.rs                  | 481 ++++++++++++++++++++++++++++-------
 11 files changed, 474 insertions(+), 128 deletions(-)

---
base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
change-id: 20261112-page-ownable-2e97941a83b2
prerequisite-change-id: 20250305-unique-ref-29fcd675f9e9:v22
prerequisite-patch-id: 4e3c7a1a2077aaa0ece2d557fa73486355903ae5
prerequisite-patch-id: d1073c5dcd6287fbcba7848a5d182108930230c1
prerequisite-patch-id: 3244def11bbdf2eabaa6e94e15ce06540b2f5814
prerequisite-patch-id: cef14c5bef5ba519ceaf0a0e7c9e93ef974db7b3
prerequisite-patch-id: 56410da35ed8dbe7b210adae0985af705cc0b5b0

Best regards,

Signature · 1 line
Andreas Hindborg <[email protected]>
author reviewer
#1 lore raw

PATCH v22 1/6 rust: page: add page kinds and make `Page` reference counted

A struct page has a reference count, and the lifetime of most pages is managed by it. Kernel C code routinely takes its own references to such pages, for example when a page is inserted into a VMA with vm_insert_page().

However, not every page is managed by its reference count, and not every page may have references taken. For instance, a frozen page has a reference count of zero, and get_page() must not be used on pages owned by the slab allocator. Thus, a single Page type cannot represent both pages that are known to be reference counted and pages for which this is not known.

Make Page generic over a sealed PageKind, and add two page kinds:

- Base is the base kind. Nothing is known about a Page<Base> beyond the validity of the struct page.
- RefCounted is the default kind. A Page<RefCounted> is managed by the page reference count, and taking additional references to it is permitted.

Implement the RefCounted trait for Page<RefCounted>, backed by get_page() and put_page(), mark it AlwaysRefCounted, and return ARef<Page> from Page::alloc_page(). The page is freed when the last reference to it is dropped; for the order-0 pages allocated here, this is equivalent to __free_pages().

The RefCounted page kind shares its name with the RefCounted trait. The name matches the mm term for a page that is not frozen, and the kind is the default, so it is rarely spelled out. In page.rs, the trait is referred to as aref::RefCounted.

Operations that are valid for any page are available for all page kinds.

Let Page<RefCounted> dereference to Page<Base>. The purpose of the dereference is coercion: a &Page<RefCounted> can be passed to code that takes a &Page<Base>.

This also allows pages to be handed out as plain references without owning the struct page. Remove BorrowedPage and update users:
Vmalloc::to_page() and AsPageIter hand out &Page<Base>, and binder uses &Page and ARef<Page>.

---
 drivers/android/binder/page_range.rs |   8 +-
 rust/helpers/page.c                  |  10 ++
 rust/kernel/alloc/allocator.rs       |  26 ++---
 rust/kernel/alloc/allocator/iter.rs  |   7 +-
 rust/kernel/page.rs                  | 195 ++++++++++++++++++++---------------
 5 files changed, 142 insertions(+), 104 deletions(-)
drivers/android/binder/page_range.rs +4 -4
index b0c797523bc2..451369e07e7f 100644
@@ -198,7 +198,7 @@ unsafe impl Send for Inner {}
 #[repr(C)]
 struct PageInfo {
     lru: bindings::list_head,
-    page: Option<Page>,
+    page: Option<ARef<Page>>,
     range: *const ShrinkablePageRange,
 }
 
@@ -206,7 +206,7 @@ impl PageInfo {
     /// # Safety
     ///
     /// The caller ensures that writing to `me.page` is ok, and that the page is not currently set.
-    unsafe fn set_page(me: *mut PageInfo, page: Page) {
+    unsafe fn set_page(me: *mut PageInfo, page: ARef<Page>) {
         // SAFETY: This pointer offset is in bounds.
         let ptr = unsafe { &raw mut (*me).page };
 
@@ -229,13 +229,13 @@ unsafe fn get_page<'a>(me: *const PageInfo) -> Option<&'a Page> {
         let ptr = unsafe { &raw const (*me).page };
 
         // SAFETY: The pointer is valid for reading.
-        unsafe { (*ptr).as_ref() }
+        unsafe { (*ptr).as_deref() }
     }
 
     /// # Safety
     ///
     /// The caller ensures that writing to `me.page` is ok for the duration of 'a.
-    unsafe fn take_page(me: *mut PageInfo) -> Option<Page> {
+    unsafe fn take_page(me: *mut PageInfo) -> Option<ARef<Page>> {
         // SAFETY: This pointer offset is in bounds.
         let ptr = unsafe { &raw mut (*me).page };
 
rust/helpers/page.c +10 -0
index f8463fbed2a2..906eb4b18f02 100644
@@ -10,6 +10,16 @@ __rust_helper struct page *rust_helper_alloc_pages(gfp_t gfp_mask,
 	return alloc_pages(gfp_mask, order);
 }
 
+__rust_helper void rust_helper_get_page(struct page *page)
+{
+	get_page(page);
+}
+
+__rust_helper void rust_helper_put_page(struct page *page)
+{
+	put_page(page);
+}
+
 __rust_helper void *rust_helper_kmap_local_page(struct page *page)
 {
 	return kmap_local_page(page);
rust/kernel/alloc/allocator.rs +14 -12
index cd4203f27aed..bf20714156c5 100644
@@ -17,7 +17,10 @@
 
 use crate::{
     bindings,
-    page, //
+    page::{
+        Base,
+        Page, //
+    }, //
 };
 
 use core::{
@@ -169,7 +172,7 @@ unsafe fn realloc(
 }
 
 impl Vmalloc {
-    /// Convert a pointer to a [`Vmalloc`] allocation to a [`page::BorrowedPage`].
+    /// Convert a pointer to a [`Vmalloc`] allocation to a [`Page<Base>`] reference.
     ///
     /// # Examples
     ///
@@ -202,20 +205,19 @@ impl Vmalloc {
     ///
     /// - `ptr` must be a valid pointer to a [`Vmalloc`] allocation.
     /// - `ptr` must remain valid for the entire duration of `'a`.
-    pub unsafe fn to_page<'a>(ptr: NonNull<u8>) -> page::BorrowedPage<'a> {
+    pub unsafe fn to_page<'a>(ptr: NonNull<u8>) -> &'a Page<Base> {
         // SAFETY: `ptr` is a valid pointer to `Vmalloc` memory.
         let page = unsafe { bindings::vmalloc_to_page(ptr.as_ptr().cast()) };
 
-        // SAFETY: `vmalloc_to_page` returns a valid pointer to a `struct page` for a valid pointer
-        // to `Vmalloc` memory.
-        let page = unsafe { NonNull::new_unchecked(page) };
-
+        // INVARIANT: `Base` has no invariants in addition to the validity of the `struct page`,
+        // which is argued below.
         // SAFETY:
-        // - `page` is a valid pointer to a `struct page`, given that by the safety requirements of
-        //   this function `ptr` is a valid pointer to a `Vmalloc` allocation.
-        // - By the safety requirements of this function `ptr` is valid for the entire lifetime of
-        //   `'a`.
-        unsafe { page::BorrowedPage::from_raw(page) }
+        // - `vmalloc_to_page` returns a valid, non-null pointer to a `struct page` for a valid
+        //   pointer to `Vmalloc` memory, given that by the safety requirements of this function
+        //   `ptr` is a valid pointer to a `Vmalloc` allocation.
+        // - By the safety requirements of this function `ptr`, and hence the `struct page`, is
+        //   valid for the entire lifetime of `'a`.
+        unsafe { &*page.cast() }
     }
 }
 
rust/kernel/alloc/allocator/iter.rs +4 -3
index 02fda3ea5cae..7c69ef31fb0c 100644
@@ -9,7 +9,8 @@
     ptr::NonNull, //
 };
 
-/// An [`Iterator`] of [`page::BorrowedPage`] items owned by a [`Vmalloc`] allocation.
+/// An [`Iterator`] of [`Page<Base>`](page::Page) references to the pages of a [`Vmalloc`]
+/// allocation.
 ///
 /// # Guarantees
 ///
@@ -28,11 +29,11 @@ pub struct VmallocPageIter<'a> {
     size: usize,
     /// The current page index of the [`Iterator`].
     index: usize,
-    _p: PhantomData<page::BorrowedPage<'a>>,
+    _p: PhantomData<&'a page::Page<page::Base>>,
 }
 
 impl<'a> Iterator for VmallocPageIter<'a> {
-    type Item = page::BorrowedPage<'a>;
+    type Item = &'a page::Page<page::Base>;
 
     fn next(&mut self) -> Option<Self::Item> {
         let offset = self.index.checked_mul(page::PAGE_SIZE)?;
rust/kernel/page.rs +110 -85

254 lines not on this page · raw message

Signature · 1 line
2.54.0
#2 lore raw

Re: [PATCH v22 1/6] rust: page: add page kinds and make `Page` reference counted

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] rust: page: missing #[inline] on Vmalloc::to_page() and Page::as_ptr() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] rust: page: missing #[inline] on Vmalloc::to_page() and Page::as_ptr()
--

commit 36a035122eaf9c7ebb69272cab04826c581553f8
Author: Andreas Hindborg <[email protected]>

rust: page: add page kinds and make Page reference counted

This commit makes Page generic over a sealed PageKind trait with Base and RefCounted kinds, implements RefCounted and AlwaysRefCounted for Page<RefCounted>, and replaces BorrowedPage with references to Page<Base>.

Quoted 4 lines
rust/kernel/alloc/allocator.rs +0 -0
index cd4203f27aed0..bf20714156c53 100644

[ ... ]

Quoted 29 lines
rust/kernel/alloc/allocator.rs +9 -10
@@ -202,20 +205,19 @@ impl Vmalloc {
     ///
     /// - `ptr` must be a valid pointer to a [`Vmalloc`] allocation.
     /// - `ptr` must remain valid for the entire duration of `'a`.
-    pub unsafe fn to_page<'a>(ptr: NonNull<u8>) -> page::BorrowedPage<'a> {
+    pub unsafe fn to_page<'a>(ptr: NonNull<u8>) -> &'a Page<Base> {
         // SAFETY: `ptr` is a valid pointer to `Vmalloc` memory.
         let page = unsafe { bindings::vmalloc_to_page(ptr.as_ptr().cast()) };
 
-        // SAFETY: `vmalloc_to_page` returns a valid pointer to a `struct page` for a valid pointer
-        // to `Vmalloc` memory.
-        let page = unsafe { NonNull::new_unchecked(page) };
-
+        // INVARIANT: `Base` has no invariants in addition to the validity of the `struct page`,
+        // which is argued below.
         // SAFETY:
-        // - `page` is a valid pointer to a `struct page`, given that by the safety requirements of
-        //   this function `ptr` is a valid pointer to a `Vmalloc` allocation.
-        // - By the safety requirements of this function `ptr` is valid for the entire lifetime of
-        //   `'a`.
-        unsafe { page::BorrowedPage::from_raw(page) }
+        // - `vmalloc_to_page` returns a valid, non-null pointer to a `struct page` for a valid
+        //   pointer to `Vmalloc` memory, given that by the safety requirements of this function
+        //   `ptr` is a valid pointer to a `Vmalloc` allocation.
+        // - By the safety requirements of this function `ptr`, and hence the `struct page`, is
+        //   valid for the entire lifetime of `'a`.
+        unsafe { &*page.cast() }
     }
 }

[ ... ]

Quoted 4 lines
rust/kernel/page.rs +0 -0
index 1c0796ea229f0..b2a17c86e7de0 100644

[ ... ]

Quoted 1 line
rust/kernel/page.rs +0 -0
@@ -185,19 +192,22 @@ impl Page {

[ ... ]

rust/kernel/page.rs impl Page { · line 211

Quoted 6 lines
rust/kernel/page.rs +2 -1
+impl<Kind: PageKind> Page<Kind> {
     /// Returns a raw pointer to the page.
     pub fn as_ptr(&self) -> *mut bindings::page {
-        self.page.as_ptr()
+        self.page.get()
     }

[Severity: Low]
Should Vmalloc::to_page() and Page::as_ptr() be marked #[inline]? Vmalloc::to_page() is a non-generic wrapper in the kernel crate that forwards directly to bindings::vmalloc_to_page(), and Page::as_ptr() is a one-line accessor called by #[inline] methods such as Page::nid() and Page::inc_ref().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author reviewer
#3 lore raw

PATCH v22 2/6 rust: page: add `from_raw()`

In reply to Andreas Hindborg

Add a method to Page that allows construction of a reference from a struct page pointer.

The method is available for all page kinds. The caller selects the page kind and must ensure that the invariants of that kind hold for the page.

A &Page<RefCounted> can be converted to an ARef<Page>. Thus, for Page<RefCounted>, the page must be managed by the page reference count and taking additional references to it must be permitted. This is not the case for all pages, for instance pages owned by the slab allocator. Such pages can be referenced as Page<Base>.

---
 rust/kernel/page.rs | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)
rust/kernel/page.rs +24 -0
index b2a17c86e7de..2ceeac0237d5 100644
@@ -217,6 +217,30 @@ pub fn nid(&self) -> i32 {
         unsafe { bindings::page_to_nid(self.as_ptr()) }
     }
 
+    /// Create a `&Page<Kind>` from a raw `struct page` pointer.
+    ///
+    /// It is up to the caller to select the correct [`PageKind`] for the page.
+    ///
+    /// # Safety
+    ///
+    /// Callers must ensure that, for the duration of `'a`:
+    /// - `ptr` is convertible to a shared reference.
+    /// - The invariants of `Kind` hold for the page pointed to by `ptr`, see the documentation of
+    ///   the [`PageKind`] types.
+    ///
+    /// Note that the invariants of [`RefCounted`] do not hold for all pages. For instance, pages
+    /// owned by the slab allocator are not managed by the page reference count. Use [`Base`] for
+    /// pages where nothing is known beyond their validity.
+    #[inline]
+    pub unsafe fn from_raw<'a>(ptr: *const bindings::page) -> &'a Self {
+        // INVARIANT: By the function safety requirements, `ptr` refers to a valid `struct page`
+        // for which the invariants of `Kind` hold, so the returned reference upholds the type
+        // invariants of `Page<Kind>`.
+        // SAFETY: By function safety requirements, `ptr` is not null and is convertible to a shared
+        // reference.
+        unsafe { &*ptr.cast() }
+    }
+
     /// Runs a piece of code with this page mapped to an address.
     ///
     /// The page is unmapped when this call returns.
Signature · 1 line
2.54.0
author reviewer
#4 lore raw

PATCH v22 3/6 mm/page_alloc: make alloc_frozen_pages() available outside of mm

In reply to Andreas Hindborg

alloc_frozen_pages() and free_frozen_pages() are declared in the private header mm/page_alloc.h, and free_frozen_pages() is not exported. Thus, frozen pages cannot be allocated outside of mm, and not from modules.

The Rust page abstractions need frozen pages. The reference count of a frozen page is zero and references to it cannot be taken, so the caller that allocates a frozen page is guaranteed by mm to be its only owner. The Rust abstractions rely on this to hand out the data of a page as a Rust reference.

Move the declarations of alloc_frozen_pages(), alloc_frozen_pages_noprof() and free_frozen_pages() to include/linux/gfp.h, and export alloc_frozen_pages_noprof() and free_frozen_pages() with EXPORT_SYMBOL_GPL().

For !CONFIG_NUMA, alloc_frozen_pages_noprof() is a static inline function that passes ALLOC_DEFAULT to __alloc_frozen_pages_noprof(). ALLOC_DEFAULT is private to mm, so the function cannot move to the public header as it is. Move it out of line to mm/page_alloc.c instead. This adds a function call to the existing callers in mm/slub.c on !CONFIG_NUMA kernels.

---
 include/linux/gfp.h |  9 +++++++++
 mm/mempolicy.c      |  1 +
 mm/page_alloc.c     | 10 ++++++++++
 mm/page_alloc.h     | 14 --------------
 4 files changed, 20 insertions(+), 14 deletions(-)
include/linux/gfp.h +9 -0
index 63a7654c725f..7e1f24658f9e 100644
@@ -302,6 +302,15 @@ static inline struct folio *vma_alloc_folio_noprof(gfp_t gfp, int order,
 
 #define alloc_page(gfp_mask) alloc_pages(gfp_mask, 0)
 
+/*
+ * Allocate frozen pages. The reference count of a frozen page is zero, and
+ * references to it cannot be taken. The caller owns the pages and frees them
+ * with free_frozen_pages().
+ */
+struct page *alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order);
+#define alloc_frozen_pages(...)			alloc_hooks(alloc_frozen_pages_noprof(__VA_ARGS__))
+void free_frozen_pages(struct page *page, unsigned int order);
+
 static inline struct page *alloc_page_vma_noprof(gfp_t gfp,
 		struct vm_area_struct *vma, unsigned long addr)
 {
mm/mempolicy.c +1 -0
index 0cb6da1c47a4..6d872db9fc6a 100644
@@ -2582,6 +2582,7 @@ struct page *alloc_frozen_pages_noprof(gfp_t gfp, unsigned order)
 	return alloc_pages_mpol(gfp, order, pol, NO_INTERLEAVE_INDEX,
 				       numa_node_id());
 }
+EXPORT_SYMBOL_GPL(alloc_frozen_pages_noprof);
 
 /**
  * alloc_pages - Allocate pages.
mm/page_alloc.c +10 -0
index eb4f02617f53..d6284cf965cf 100644
@@ -2993,6 +2993,7 @@ void free_frozen_pages(struct page *page, unsigned int order)
 {
 	__free_frozen_pages(page, order, FPI_NONE);
 }
+EXPORT_SYMBOL_GPL(free_frozen_pages);
 
 void free_frozen_pages_nolock(struct page *page, unsigned int order)
 {
@@ -5491,6 +5492,15 @@ struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order,
 }
 EXPORT_SYMBOL(__alloc_frozen_pages_noprof);
 
+#ifndef CONFIG_NUMA
+struct page *alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order)
+{
+	return __alloc_frozen_pages_noprof(gfp, order, numa_node_id(), NULL,
+					   ALLOC_DEFAULT);
+}
+EXPORT_SYMBOL_GPL(alloc_frozen_pages_noprof);
+#endif
+
 struct page *__alloc_pages_noprof(gfp_t gfp, unsigned int order,
 		int preferred_nid, nodemask_t *nodemask, unsigned int alloc_flags)
 {
mm/page_alloc.h +0 -14
index 7097ea1805f6..541fa8b3f532 100644
@@ -237,22 +237,8 @@ struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order, int nid,
 		nodemask_t *nodemask, unsigned int alloc_flags);
 #define __alloc_frozen_pages(...) \
 	alloc_hooks(__alloc_frozen_pages_noprof(__VA_ARGS__))
-void free_frozen_pages(struct page *page, unsigned int order);
 void free_unref_folios(struct folio_batch *fbatch);
 
-#ifdef CONFIG_NUMA
-struct page *alloc_frozen_pages_noprof(gfp_t, unsigned int order);
-#else
-static inline struct page *alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order)
-{
-	return __alloc_frozen_pages_noprof(gfp, order, numa_node_id(), NULL,
-					   ALLOC_DEFAULT);
-}
-#endif
-
-#define alloc_frozen_pages(...) \
-	alloc_hooks(alloc_frozen_pages_noprof(__VA_ARGS__))
-
 struct page *alloc_frozen_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order);
 #define alloc_frozen_pages_nolock(...) \
 	alloc_hooks(alloc_frozen_pages_nolock_noprof(__VA_ARGS__))
Signature · 1 line
2.54.0
author reviewer
#5 lore raw

PATCH v22 4/6 rust: page: add `Exclusive` page kind for race-free page access

In reply to Andreas Hindborg

Add the page kind Exclusive. A Page<Exclusive> is a page that is uniquely owned through an Owned<Page<Exclusive>>, with the added invariant that the page data area does not incur data races. This means a Page<Exclusive> cannot be mapped to user space or shared with devices, and it becomes simpler to directly reference the contents of the page.

Back Page<Exclusive> by a frozen page, allocated with alloc_frozen_pages() and freed with free_frozen_pages(). The reference count of a frozen page is zero and references to it cannot be taken, so the exclusive ownership is upheld by mm and not only by the Rust type system.

Add Page::alloc_exclusive() to allocate a Page<Exclusive>. The function is not named alloc_page(), because inherent functions of the same name on two page kinds would make the call Page::alloc_page() ambiguous.

Page<Exclusive> dereferences to Page<Base>. This does not allow safe code to break the aliasing invariant of Page<Exclusive>:
Page<Base> does not implement AlwaysRefCounted, so no ARef to the page can be obtained, and the raw data accessors are unsafe and already require their callers to rule out races with all other accesses to the page.

---
 rust/helpers/page.c |  6 ++++
 rust/kernel/page.rs | 96 +++++++++++++++++++++++++++++++++++++++++++++++++++--
 2 files changed, 100 insertions(+), 2 deletions(-)
rust/helpers/page.c +6 -0
index 906eb4b18f02..8f9f624ea141 100644
@@ -10,6 +10,12 @@ __rust_helper struct page *rust_helper_alloc_pages(gfp_t gfp_mask,
 	return alloc_pages(gfp_mask, order);
 }
 
+__rust_helper struct page *rust_helper_alloc_frozen_pages(gfp_t gfp_mask,
+							  unsigned int order)
+{
+	return alloc_frozen_pages(gfp_mask, order);
+}
+
 __rust_helper void rust_helper_get_page(struct page *page)
 {
 	get_page(page);
rust/kernel/page.rs +94 -2

117 lines not on this page · raw message

Signature · 1 line
2.54.0
author reviewer
#6 lore raw

PATCH v22 5/6 rust: page: add `Frozen` page kind

In reply to Andreas Hindborg

Add the page kind Frozen. A Page<Frozen> is a frozen page that is uniquely owned through an Owned<Page<Frozen>>. The reference count of a frozen page is zero and references to it cannot be taken, so the ownership is exclusive.

In contrast to Page<Exclusive>, a Page<Frozen> has no invariant on who accesses the data of the page. The owner can share the data with a device, and thus the data is accessed through the unsafe raw accessors only.

Add Page::alloc_frozen() to allocate a Page<Frozen>, and let Page<Frozen> dereference to Page<Base>.

---

This currently has no users, but I add it here for completeness. Let's discuss if we should keep it or not.

---
 rust/kernel/page.rs | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 89 insertions(+), 1 deletion(-)
rust/kernel/page.rs +89 -1
index c885bcf4f886..c629764f773b 100644
@@ -93,7 +93,7 @@ pub trait Sealed {}
 /// Marker trait for the kinds of a [`Page`].
 ///
 /// A page kind describes what is known about a `struct page`, and thereby what a [`Page`] of that
-/// kind can be used for. See [`Base`], [`RefCounted`] and [`Exclusive`].
+/// kind can be used for. See [`Base`], [`RefCounted`], [`Frozen`] and [`Exclusive`].
 ///
 /// A [`Page`] of any other kind dereferences to a [`Page`] of the base kind [`Base`]. The
 /// purpose of the dereference is coercion: a reference to a page of any kind can be passed to code
@@ -138,6 +138,7 @@ impl PageKind for RefCounted {}
 ///
 /// - `Page<Base>` is a page for which nothing is known beyond its validity.
 /// - `Page<RefCounted>`, or just `Page`, is a page that is managed by the page reference count.
+/// - `Page<Frozen>` is a uniquely owned page that references cannot be taken to.
 /// - `Page<Exclusive>` is a uniquely owned page whose data follows standard Rust aliasing rules.
 ///
 /// Operations that are valid for any page are available for all page kinds. All other page kinds
@@ -435,6 +436,93 @@ unsafe fn dec_ref(obj: NonNull<Self>) {
 // non-zero and it is okay to obtain an `ARef<Page>` from it.
 unsafe impl AlwaysRefCounted for Page {}
 
+/// A [`PageKind`] for a frozen page.
+///
+/// The reference count of a frozen page is zero, and references to it cannot be taken. A
+/// [`Page<Frozen>`] is accessed through an owning [`Owned<Page<Frozen>>`], and the page is freed
+/// when the [`Owned<Page<Frozen>>`] is dropped.
+///
+/// Unlike for a [`Page<Exclusive>`], nothing is known about who accesses the data of a
+/// [`Page<Frozen>`]. For instance, the owner can share the data of the page with a device. Thus,
+/// the data is accessed through the unsafe raw accessors of [`Page`] only.
+///
+/// # Invariants
+///
+/// For a [`Page<Frozen>`]:
+///
+/// - The page is an order 0 frozen page: it was allocated with `alloc_frozen_pages()`, and its
+///   reference count is zero for as long as the [`Page<Frozen>`] exists.
+/// - The page is owned by a unique [`Owned<Page<Frozen>>`]. No references to the page exist
+///   together with the [`Owned<Page<Frozen>>`], other than the ones borrowed from it.
+pub struct Frozen;
+
+impl private::Sealed for Frozen {}
+impl PageKind for Frozen {}
+
+impl Deref for Page<Frozen> {
+    type Target = Page<Base>;
+
+    #[inline]
+    fn deref(&self) -> &Self::Target {
+        // SAFETY: `Page` is transparent over `struct page` for all page kinds, so the pointer cast
+        // is valid. `Base` has no invariants in addition to the ones of `Page`, which hold for
+        // `self`.
+        unsafe { &*ptr::from_ref(self).cast() }
+    }
+}
+
+impl Page<Frozen> {
+    /// Allocates a new frozen page.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::page::{
+    ///     Page,
+    ///     PAGE_SIZE, //
+    /// };
+    ///
+    /// let page = Page::alloc_frozen(GFP_KERNEL)?;
+    ///
+    /// // SAFETY: The page was just allocated and is not shared, so there are no concurrent reads
+    /// // or writes to the page.
+    /// unsafe { page.fill_zero_raw(0, PAGE_SIZE)? };
+    /// # Ok::<(), Error>(())
+    /// ```
+    #[inline]
+    pub fn alloc_frozen(flags: Flags) -> Result<Owned<Self>, AllocError> {
+        // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
+        // is always safe to call this method.
+        let page = unsafe { bindings::alloc_frozen_pages(flags.as_raw(), 0) };
+        let page = NonNull::new(page).ok_or(AllocError)?;
+
+        // INVARIANT: The page was just allocated with `alloc_frozen_pages()`, so it is frozen and
+        // we own it.
+        // SAFETY:
+        // - We just successfully allocated the page, so `page` points to a valid `struct page`.
+        //   Since `Page` is transparent over `struct page`, we can cast the pointer directly.
+        // - The page was just allocated, so no other `Owned` exists for it.
+        // - A `struct page` is never moved, so the page is pinned.
+        // - `Page<Frozen>` allows no other references to exist together with the `Owned`, and
+        //   none exist, as the page is newly allocated and references cannot be taken to a frozen
+        //   page. Thus, it is sound to hand out `&Page<Frozen>` and `Pin<&mut Page<Frozen>>`.
+        // - Pages have no logic that relies on them staying on a given thread or on them not being
+        //   accessed concurrently.
+        Ok(unsafe { Owned::from_raw(page.cast()) })
+    }
+}
+
+impl Ownable for Page<Frozen> {
+    #[inline]
+    unsafe fn release(this: NonNull<Self>) {
+        // SAFETY: By the function safety requirements, we have exclusive ownership of the page, and
+        // by the type invariant the page is an order 0 frozen page, so we can free it with
+        // `free_frozen_pages()`. Since `Page` is transparent over `struct page`, we can cast the
+        // pointer directly.
+        unsafe { bindings::free_frozen_pages(this.cast().as_ptr(), 0) };
+    }
+}
+
 /// A [`PageKind`] for a page whose data area follows standard Rust aliasing rules.
 ///
 /// A [`Page<Exclusive>`] is accessed through an owning [`Owned<Page<Exclusive>>`]. It has the same
Signature · 1 line
2.54.0
author reviewer
#7 lore raw

PATCH v22 6/6 rust: page: add slice access to `Page<Exclusive>`

In reply to Andreas Hindborg

The data of a Page<Exclusive> follows standard Rust aliasing rules, so it can be handed out as a slice. Add Page::as_slice() and Page::as_mut_slice() for Page<Exclusive>, which return the data of the page as &[u8] and &mut [u8] respectively.

For this to be sound, add two invariants to the Exclusive page kind:

- The data of the page is initialized. Thus, always allocate the page with __GFP_ZERO.
- The page is not a highmem page. The data of the page is then permanently mapped in the kernel address space, and a slice can refer to it without a temporary mapping. Thus, never allocate the page with __GFP_HIGHMEM.

A Page<Exclusive> dereferences to Page<Base>, so the unsafe raw data accessors can be called on it. These only required their callers to rule out data races, which does not prevent a write to the page while a slice to the data of the page exists. Thus, tighten the safety requirements of the raw accessors: no reference to the data that is written may exist, no mutable reference to the data that is read may exist, and data written to a Page<Exclusive> with write_raw() must be initialized.

Update the safety comments of the existing callers of the raw accessors, in the binder driver and in the allocator documentation examples, to cover the new requirements.

Add the helper rust_helper_page_address(), as page_address() is a macro in some configurations.

---
 drivers/android/binder/page_range.rs | 16 ++++--
 rust/helpers/page.c                  |  5 ++
 rust/kernel/alloc/allocator.rs       |  3 +-
 rust/kernel/alloc/kbox.rs            |  3 +-
 rust/kernel/alloc/kvec.rs            |  3 +-
 rust/kernel/page.rs                  | 98 +++++++++++++++++++++++++++++++-----
 6 files changed, 110 insertions(+), 18 deletions(-)
drivers/android/binder/page_range.rs +13 -3
index 451369e07e7f..db0853751993 100644
@@ -538,7 +538,9 @@ pub(crate) unsafe fn copy_from_user_slice(
         offset: usize,
         size: usize,
     ) -> Result {
-        // SAFETY: `self.iterate` has the same safety requirements as `copy_from_user_slice`.
+        // SAFETY: `self.iterate` has the same safety requirements as `copy_from_user_slice`. The
+        // pages of this range are `Page<RefCounted>` pages, and this driver never creates a
+        // reference to their data, so no reference to the data that is written exists.
         unsafe {
             self.iterate(offset, size, |page, offset, to_copy| {
                 page.copy_from_user_slice_raw(reader, offset, to_copy)
@@ -560,6 +562,9 @@ pub(crate) unsafe fn read<T: FromBytes>(&self, offset: usize) -> Result<T> {
                 // SAFETY: The sum of `offset` and `to_copy` is bounded by the size of T.
                 let obj_ptr = out.as_mut_ptr().cast::<u8>().add(out_offset);
                 // SAFETY: The pointer points is in-bounds of the `out` variable, so it is valid.
+                // The pages of this range are `Page<RefCounted>` pages, and this driver never
+                // creates a reference to their data, so no mutable reference to the data that is
+                // read exists.
                 page.read_raw(obj_ptr, offset, to_copy)?;
                 out_offset += to_copy;
                 Ok(())
@@ -581,7 +586,10 @@ pub(crate) unsafe fn write<T: ?Sized>(&self, offset: usize, obj: &T) -> Result {
             self.iterate(offset, size_of_val(obj), |page, offset, to_copy| {
                 // SAFETY: The sum of `offset` and `to_copy` is bounded by the size of T.
                 let obj_ptr = ptr::from_ref(obj).cast::<u8>().add(obj_offset);
-                // SAFETY: We have a reference to the object, so the pointer is valid.
+                // SAFETY: We have a reference to the object, so the pointer is valid. The pages
+                // of this range are `Page<RefCounted>` pages, and this driver never creates a
+                // reference to their data, so no reference to the data that is written exists. As
+                // the page is not a `Page<Exclusive>`, the object does not have to be initialized.
                 page.write_raw(obj_ptr, offset, to_copy)?;
                 obj_offset += to_copy;
                 Ok(())
@@ -595,7 +603,9 @@ pub(crate) unsafe fn write<T: ?Sized>(&self, offset: usize, obj: &T) -> Result {
     ///
     /// All pages touched by this operation must be in use for the duration of this call.
     pub(crate) unsafe fn fill_zero(&self, offset: usize, size: usize) -> Result {
-        // SAFETY: `self.iterate` has the same safety requirements as `copy_into`.
+        // SAFETY: `self.iterate` has the same safety requirements as `fill_zero`. The pages of
+        // this range are `Page<RefCounted>` pages, and this driver never creates a reference to
+        // their data, so no reference to the data that is written exists.
         unsafe {
             self.iterate(offset, size, |page, offset, len| {
                 page.fill_zero_raw(offset, len)
rust/helpers/page.c +5 -0
index 8f9f624ea141..313a3a3b30b7 100644
@@ -26,6 +26,11 @@ __rust_helper void rust_helper_put_page(struct page *page)
 	put_page(page);
 }
 
+__rust_helper void *rust_helper_page_address(const struct page *page)
+{
+	return page_address(page);
+}
+
 __rust_helper void *rust_helper_kmap_local_page(struct page *page)
 {
 	return kmap_local_page(page);
rust/kernel/alloc/allocator.rs +2 -1
index bf20714156c5..5d13dd1a8942 100644
@@ -195,7 +195,8 @@ impl Vmalloc {
     ///     // `ptr` is valid for the entire lifetime of `page`.
     ///     let page = unsafe { Vmalloc::to_page(ptr.cast()) };
     ///
-    ///     // SAFETY: There is no concurrent read or write to the same page.
+    ///     // SAFETY: There is no concurrent read or write to the same page, and no reference to
+    ///     // the data of the page exists.
     ///     unsafe { page.fill_zero_raw(0, page::PAGE_SIZE)? };
     /// }
     /// # Ok::<(), Error>(())
rust/kernel/alloc/kbox.rs +2 -1
index 7e8ce3b36673..0d02b95b219e 100644
@@ -745,7 +745,8 @@ fn drop(&mut self) {
 ///
 /// let page = vbox.page_iter().next().expect("At least one page should be available.\n");
 ///
-/// // SAFETY: There is no concurrent read or write to the same page.
+/// // SAFETY: There is no concurrent read or write to the same page, and no reference to the
+/// // data of the page exists.
 /// unsafe { page.fill_zero_raw(0, PAGE_SIZE)? };
 /// # Ok::<(), Error>(())
 /// ```
rust/kernel/alloc/kvec.rs +2 -1
index c7546b9da4fa..57e0242a1dde 100644
@@ -1230,7 +1230,8 @@ fn into_iter(self) -> Self::IntoIter {
 ///
 /// let page = vec.page_iter().next().expect("At least one page should be available.\n");
 ///
-/// // SAFETY: There is no concurrent read or write to the same page.
+/// // SAFETY: There is no concurrent read or write to the same page, and no reference to the
+/// // data of the page exists.
 /// unsafe { page.fill_zero_raw(0, PAGE_SIZE)? };
 /// # Ok::<(), Error>(())
 /// ```
rust/kernel/page.rs +86 -12

177 lines not on this page · raw message

Signature · 1 line
2.54.0
reviewer
#8 lore raw
In reply to Andreas Hindborg
Quoted 16 lines · Andreas Hindborg

Note: The page patches were part of the Ownable series [1] until v21. This series continues the version numbering of that series, and it depends on v22 of that series for Ownable, Owned and the split of RefCounted and AlwaysRefCounted.

Not all pages can be treated the same way. A page allocated with alloc_pages() is managed by the page reference count, and kernel C code routinely takes its own references to such a page. A page owned by the slab allocator must not have references taken to it, but it can still show up in places such as a bio vector. A frozen page has a reference count of zero and is exclusively owned by the party that allocated it.

A single Page type cannot describe all of these. This series makes Page generic over a sealed PageKind that describes what is known about the page:

Quoted 13 lines

- Page<Base> is the base kind. Nothing is known about the page beyond the validity of the struct page.
- Page<RefCounted> is the default kind. The page is managed by the page reference count, and Page<RefCounted> implements AlwaysRefCounted.
- Page<Exclusive> is a uniquely owned frozen page whose data area follows standard Rust aliasing rules, so the data is available as &[u8] and &mut [u8]. It is handled through Owned<Page<Exclusive>> and is the first in-tree user of Owned.
- Page<Frozen> is a frozen page whose allocation is uniquely owned. Unlike for Page<Exclusive>, nothing is known about who accesses the data of the page, so the data is only available through the unsafe raw accessors.

Why do we need to allocate Page<Frozen> when we can allocate Page<Exclusive>? To me, Page<Frozen> is an observed page state from a non-owner point of view.

In core-mm, a page is frozen, when its refcount == 0. The code looking at the page knows the page is exclusively owned by others. If the code allocates a frozen page, it will not check its refcount, because the code knows it has the exclusive ownership of the page. To reflect this, the code calling alloc_frozen_pages() should just get Page<Exclusive> and if the code encounters a Page<Base> and finds it has no refcount, it should convert it to Page<Frozen> or there should be a method that accepts PFN and return Page<Frozen> if the page of the PFN has no refcount, for PFN walkers.

“the data” mentioned in Page<Exclusive> and Page<Frozen> is struct page data or the data in the physical frame pointed by Page<...>? If it is the former, is it better to use metadata?

I am new to Rust, so feel free to correct me. Thanks. :)

Quoted 11 lines

Operations that are valid for any page are available for all page kinds. All other page kinds dereference to Page<Base>. The purpose of the dereference is coercion: a reference to a page of any kind can be passed to code that takes a &Page<Base>.

Page<Exclusive> is backed by a frozen page, as suggested by Matthew Wilcox in the review of v21. References cannot be taken to a frozen page, so the exclusive ownership is upheld by mm rather than only by the Rust type system.

Best Regards,
Yan, Zi

author reviewer
#9 lore raw
Quoted 32 lines · Zi Yan
Quoted 16 lines · Andreas Hindborg

Note: The page patches were part of the Ownable series [1] until v21. This series continues the version numbering of that series, and it depends on v22 of that series for Ownable, Owned and the split of RefCounted and AlwaysRefCounted.

Not all pages can be treated the same way. A page allocated with alloc_pages() is managed by the page reference count, and kernel C code routinely takes its own references to such a page. A page owned by the slab allocator must not have references taken to it, but it can still show up in places such as a bio vector. A frozen page has a reference count of zero and is exclusively owned by the party that allocated it.

A single Page type cannot describe all of these. This series makes Page generic over a sealed PageKind that describes what is known about the page:

Quoted 13 lines

- Page<Base> is the base kind. Nothing is known about the page beyond the validity of the struct page.
- Page<RefCounted> is the default kind. The page is managed by the page reference count, and Page<RefCounted> implements AlwaysRefCounted.
- Page<Exclusive> is a uniquely owned frozen page whose data area follows standard Rust aliasing rules, so the data is available as &[u8] and &mut [u8]. It is handled through Owned<Page<Exclusive>> and is the first in-tree user of Owned.
- Page<Frozen> is a frozen page whose allocation is uniquely owned. Unlike for Page<Exclusive>, nothing is known about who accesses the data of the page, so the data is only available through the unsafe raw accessors.

Quoted 3 lines

Why do we need to allocate Page<Frozen> when we can allocate Page<Exclusive>? To me, Page<Frozen> is an observed page state from a non-owner point of view.

I'm not sure we need it, which is why I added this note:

This currently has no users, but I add it here for completeness. Let's discuss if we should keep it or not.

The difference between the Page<Frozen> and Page<Exclusive> is that Page<Exclusive> has stronger invariants. Namely that the (physical) memory region of the page does not incur data races, and that the page not in highmem. From a Rust point of view, this allows us to obtain a reference to the page contents without jumping through any hoops.

I do not have a user for a frozen page without these invariants, but I would assume there are use cases?

Quoted 6 lines

In core-mm, a page is frozen, when its refcount == 0. The code looking at the page knows the page is exclusively owned by others. If the code allocates a frozen page, it will not check its refcount, because the code knows it has the exclusive ownership of the page. To reflect this, the code calling alloc_frozen_pages() should just get Page<Exclusive>

Is it always the case that users of frozen pages will use them in such a way that they can guarantee no races to the page contents (physical memory)? They cannot be mapped for DMA access or anything like that - that always requires a refcount?

Quoted 4 lines

and if the code encounters a Page<Base> and finds it has no refcount, it should convert it to Page<Frozen> or there should be a method that accepts PFN and return Page<Frozen> if the page of the PFN has no refcount, for PFN walkers.

We can add conversion functions, that makes sense.

Quoted 4 lines

“the data” mentioned in Page<Exclusive> and Page<Frozen> is struct page data or the data in the physical frame pointed by Page<...>? If it is the former, is it better to use metadata?

I'm referring to the actual physical memory region that the struct page describes.

Quoted 3 lines

I am new to Rust, so feel free to correct me. Thanks. :)

I'm new to mm, I really appreciate your eyes on this.

Best regards,
Andreas Hindborg

reviewer
#10 lore raw
Quoted 40 lines · Andreas Hindborg
Quoted 32 lines · Zi Yan
Quoted 16 lines · Andreas Hindborg

Note: The page patches were part of the Ownable series [1] until v21. This series continues the version numbering of that series, and it depends on v22 of that series for Ownable, Owned and the split of RefCounted and AlwaysRefCounted.

Not all pages can be treated the same way. A page allocated with alloc_pages() is managed by the page reference count, and kernel C code routinely takes its own references to such a page. A page owned by the slab allocator must not have references taken to it, but it can still show up in places such as a bio vector. A frozen page has a reference count of zero and is exclusively owned by the party that allocated it.

A single Page type cannot describe all of these. This series makes Page generic over a sealed PageKind that describes what is known about the page:

Quoted 13 lines

- Page<Base> is the base kind. Nothing is known about the page beyond the validity of the struct page.
- Page<RefCounted> is the default kind. The page is managed by the page reference count, and Page<RefCounted> implements AlwaysRefCounted.
- Page<Exclusive> is a uniquely owned frozen page whose data area follows standard Rust aliasing rules, so the data is available as &[u8] and &mut [u8]. It is handled through Owned<Page<Exclusive>> and is the first in-tree user of Owned.
- Page<Frozen> is a frozen page whose allocation is uniquely owned. Unlike for Page<Exclusive>, nothing is known about who accesses the data of the page, so the data is only available through the unsafe raw accessors.

Quoted 3 lines

Why do we need to allocate Page<Frozen> when we can allocate Page<Exclusive>? To me, Page<Frozen> is an observed page state from a non-owner point of view.

I'm not sure we need it, which is why I added this note:

Quoted 8 lines

This currently has no users, but I add it here for completeness. Let's discuss if we should keep it or not.

The difference between the Page<Frozen> and Page<Exclusive> is that Page<Exclusive> has stronger invariants. Namely that the (physical) memory region of the page does not incur data races, and that the page not in highmem. From a Rust point of view, this allows us to obtain a reference to the page contents without jumping through any hoops.

But access to memory region of the page is associated with page table mapping or IOMMU mapping (for device, and I assume devices are accessing data via virtual addresses instead of physical addresses to avoid further complication). It seems that you are trying to use page refcount == 0 to infer that no page table mapping exists for the page. But how about kernel direct map? Anyone with struct page can use kmap_local*() to get kernel direct map and access the page content. kmap_local*() does not reject frozen pages.

Quoted 3 lines

I do not have a user for a frozen page without these invariants, but I would assume there are use cases?

For the above reason, everything is Page<Frozen>?

Quoted 8 lines
Quoted 7 lines

In core-mm, a page is frozen, when its refcount == 0. The code looking at the page knows the page is exclusively owned by others. If the code allocates a frozen page, it will not check its refcount, because the code knows it has the exclusive ownership of the page. To reflect this, the code calling alloc_frozen_pages() should just get Page<Exclusive>

Quoted 4 lines

Is it always the case that users of frozen pages will use them in such a way that they can guarantee no races to the page contents (physical memory)? They cannot be mapped for DMA access or anything like that - that always requires a refcount?

See kmap_local*() case above.

Quoted 13 lines
Quoted 5 lines

and if the code encounters a Page<Base> and finds it has no refcount, it should convert it to Page<Frozen> or there should be a method that accepts PFN and return Page<Frozen> if the page of the PFN has no refcount, for PFN walkers.

We can add conversion functions, that makes sense.

Quoted 4 lines

“the data” mentioned in Page<Exclusive> and Page<Frozen> is struct page data or the data in the physical frame pointed by Page<...>? If it is the former, is it better to use metadata?

Quoted 8 lines

I'm referring to the actual physical memory region that the struct page describes.

Quoted 3 lines

I am new to Rust, so feel free to correct me. Thanks. :)

I'm new to mm, I really appreciate your eyes on this.

Do you mind describing the high level workflow around Page in Rust? From my point of view, exclusive page content access is more related to page table (including IOMMU page table) than struct page itself. struct page ownership is more about the metadata stored in struct page for physical memory maintenance.

Best Regards,
Yan, Zi

author reviewer
#11 lore raw
Quoted 51 lines · Zi Yan
Quoted 40 lines · Andreas Hindborg
Quoted 32 lines · Zi Yan
Quoted 16 lines · Andreas Hindborg

Note: The page patches were part of the Ownable series [1] until v21. This series continues the version numbering of that series, and it depends on v22 of that series for Ownable, Owned and the split of RefCounted and AlwaysRefCounted.

Not all pages can be treated the same way. A page allocated with alloc_pages() is managed by the page reference count, and kernel C code routinely takes its own references to such a page. A page owned by the slab allocator must not have references taken to it, but it can still show up in places such as a bio vector. A frozen page has a reference count of zero and is exclusively owned by the party that allocated it.

A single Page type cannot describe all of these. This series makes Page generic over a sealed PageKind that describes what is known about the page:

Quoted 13 lines

- Page<Base> is the base kind. Nothing is known about the page beyond the validity of the struct page.
- Page<RefCounted> is the default kind. The page is managed by the page reference count, and Page<RefCounted> implements AlwaysRefCounted.
- Page<Exclusive> is a uniquely owned frozen page whose data area follows standard Rust aliasing rules, so the data is available as &[u8] and &mut [u8]. It is handled through Owned<Page<Exclusive>> and is the first in-tree user of Owned.
- Page<Frozen> is a frozen page whose allocation is uniquely owned. Unlike for Page<Exclusive>, nothing is known about who accesses the data of the page, so the data is only available through the unsafe raw accessors.

Quoted 3 lines

Why do we need to allocate Page<Frozen> when we can allocate Page<Exclusive>? To me, Page<Frozen> is an observed page state from a non-owner point of view.

I'm not sure we need it, which is why I added this note:

Quoted 8 lines

This currently has no users, but I add it here for completeness. Let's discuss if we should keep it or not.

The difference between the Page<Frozen> and Page<Exclusive> is that Page<Exclusive> has stronger invariants. Namely that the (physical) memory region of the page does not incur data races, and that the page not in highmem. From a Rust point of view, this allows us to obtain a reference to the page contents without jumping through any hoops.

Quoted 6 lines

But access to memory region of the page is associated with page table mapping or IOMMU mapping (for device, and I assume devices are accessing data via virtual addresses instead of physical addresses to avoid further complication). It seems that you are trying to use page refcount == 0 to infer that no page table mapping exists for the page. But how about kernel direct map?

Page<Exclusive> has the invariant that it must not be in highmem, and as such is always accessible in the kernel virtual address space. As far as I understand, this means we do not need kmap_local before accessing the contents.

Quoted 3 lines

Anyone with struct page can use kmap_local*()
to get kernel direct map and access the page content. kmap_local*() does not reject frozen pages.

Page<Exclusive> is a unique handle. Nobody can get a hold of the underlying struct page to perform mapping operations on the page.

Quoted 6 lines
Quoted 4 lines

I do not have a user for a frozen page without these invariants, but I would assume there are use cases?

For the above reason, everything is Page<Frozen>?

Pages that are part of user space process vmas are not frozen? We see these in system calls for IO.

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines

In core-mm, a page is frozen, when its refcount == 0. The code looking at the page knows the page is exclusively owned by others. If the code allocates a frozen page, it will not check its refcount, because the code knows it has the exclusive ownership of the page. To reflect this, the code calling alloc_frozen_pages() should just get Page<Exclusive>

Quoted 6 lines
Quoted 4 lines

Is it always the case that users of frozen pages will use them in such a way that they can guarantee no races to the page contents (physical memory)? They cannot be mapped for DMA access or anything like that - that always requires a refcount?

See kmap_local*() case above.

Right. Both Page<Frozen> and Page<Exclusive> are guaranteed to be the only reference the underlying struct page, and so nobody can do mapping operations from under us. The difference of the two is that Page<Exclusive> provides guarantees about placement out of highmem and no races on the page contents.

Quoted 21 lines
Quoted 21 lines
Quoted 6 lines

and if the code encounters a Page<Base> and finds it has no refcount, it should convert it to Page<Frozen> or there should be a method that accepts PFN and return Page<Frozen> if the page of the PFN has no refcount, for PFN walkers.

We can add conversion functions, that makes sense.

Quoted 4 lines

“the data” mentioned in Page<Exclusive> and Page<Frozen> is struct page data or the data in the physical frame pointed by Page<...>? If it is the former, is it better to use metadata?

I'm referring to the actual physical memory region that the struct page describes.

Quoted 3 lines

I am new to Rust, so feel free to correct me. Thanks. :)

Quoted 7 lines
Quoted 1 line

I'm new to mm, I really appreciate your eyes on this.

Do you mind describing the high level workflow around Page in Rust? From my point of view, exclusive page content access is more related to page table (including IOMMU page table) than struct page itself. struct page ownership is more about the metadata stored in struct page for physical memory maintenance.

Just as in C code, there are many workflows around Page. Three main ones I have seen in Rust code are:

- Pages that are part of io buffers during a syscall. The pages are mapped in at least one user space process and the kernel may want to read or write from/to them. These would be Page<RefCounted>.

- Pages that hit the block device driver API via the block layer. These can be anything, so we model them as Page<Base>.

- Pages used for backing storage like in the null block driver. These are modeled as Page<Exclusive>.

I think for the first one, binder is inserting and removing pages from vmas to do it's IPC thing.

If someone were to write an allocator of some kind, they would probably reach for the Page<Frozen>, as they would like to have ownership of the metadata, but not the contents.

Best regards,
Andreas Hindborg

reviewer
#12 lore raw
Quoted 65 lines · Andreas Hindborg
Quoted 51 lines · Zi Yan
Quoted 40 lines · Andreas Hindborg
Quoted 32 lines · Zi Yan
Quoted 16 lines · Andreas Hindborg

Note: The page patches were part of the Ownable series [1] until v21. This series continues the version numbering of that series, and it depends on v22 of that series for Ownable, Owned and the split of RefCounted and AlwaysRefCounted.

Not all pages can be treated the same way. A page allocated with alloc_pages() is managed by the page reference count, and kernel C code routinely takes its own references to such a page. A page owned by the slab allocator must not have references taken to it, but it can still show up in places such as a bio vector. A frozen page has a reference count of zero and is exclusively owned by the party that allocated it.

A single Page type cannot describe all of these. This series makes Page generic over a sealed PageKind that describes what is known about the page:

Quoted 13 lines

- Page<Base> is the base kind. Nothing is known about the page beyond the validity of the struct page.
- Page<RefCounted> is the default kind. The page is managed by the page reference count, and Page<RefCounted> implements AlwaysRefCounted.
- Page<Exclusive> is a uniquely owned frozen page whose data area follows standard Rust aliasing rules, so the data is available as &[u8] and &mut [u8]. It is handled through Owned<Page<Exclusive>> and is the first in-tree user of Owned.
- Page<Frozen> is a frozen page whose allocation is uniquely owned. Unlike for Page<Exclusive>, nothing is known about who accesses the data of the page, so the data is only available through the unsafe raw accessors.

Quoted 3 lines

Why do we need to allocate Page<Frozen> when we can allocate Page<Exclusive>? To me, Page<Frozen> is an observed page state from a non-owner point of view.

I'm not sure we need it, which is why I added this note:

Quoted 8 lines

This currently has no users, but I add it here for completeness. Let's discuss if we should keep it or not.

The difference between the Page<Frozen> and Page<Exclusive> is that Page<Exclusive> has stronger invariants. Namely that the (physical) memory region of the page does not incur data races, and that the page not in highmem. From a Rust point of view, this allows us to obtain a reference to the page contents without jumping through any hoops.

Quoted 6 lines

But access to memory region of the page is associated with page table mapping or IOMMU mapping (for device, and I assume devices are accessing data via virtual addresses instead of physical addresses to avoid further complication). It seems that you are trying to use page refcount == 0 to infer that no page table mapping exists for the page. But how about kernel direct map?

Page<Exclusive> has the invariant that it must not be in highmem, and as such is always accessible in the kernel virtual address space. As far as I understand, this means we do not need kmap_local before accessing the contents.

Quoted 7 lines
Quoted 3 lines

Anyone with struct page can use kmap_local*()
to get kernel direct map and access the page content. kmap_local*() does not reject frozen pages.

Page<Exclusive> is a unique handle. Nobody can get a hold of the underlying struct page to perform mapping operations on the page.

Right, but if kernel direct map exists, how can you claim “the (physical) memory region of the page does not incur data races”? At least, “assuming no one is accessing the region via kernel direct map” could be added.

Quoted 9 lines
Quoted 6 lines
Quoted 4 lines

I do not have a user for a frozen page without these invariants, but I would assume there are use cases?

For the above reason, everything is Page<Frozen>?

Pages that are part of user space process vmas are not frozen? We see these in system calls for IO.

Sorry I was too vague. I mean Page<Exclusive> and Page<Frozen> should be Page<Frozen> given that kernel direct map exists. Strictly speaking, Page<Exclusive> should be pages allocated without kernel direct mapping.

Quoted 15 lines
Quoted 15 lines
Quoted 14 lines
Quoted 9 lines

In core-mm, a page is frozen, when its refcount == 0. The code looking at the page knows the page is exclusively owned by others. If the code allocates a frozen page, it will not check its refcount, because the code knows it has the exclusive ownership of the page. To reflect this, the code calling alloc_frozen_pages() should just get Page<Exclusive>

Is it always the case that users of frozen pages will use them in such a way that they can guarantee no races to the page contents (physical memory)? They cannot be mapped for DMA access or anything like that - that always requires a refcount?

Quoted 8 lines
Quoted 1 line

See kmap_local*() case above.

Right. Both Page<Frozen> and Page<Exclusive> are guaranteed to be the only reference the underlying struct page, and so nobody can do mapping operations from under us. The difference of the two is that Page<Exclusive> provides guarantees about placement out of highmem and no races on the page contents.

Sorry for being pedantic, but IMHO “no races on the page content” is too strong. LLM tells me, let me know if it is wrong, that DMA map code does not check page refcount and currently gives a dma_addr_t for slab and kmalloc pages, which are frozen. This means a Page<Exclusive> can be mapped via dma map C code. What is the plan to prevent that?

Quoted 29 lines
Quoted 21 lines
Quoted 21 lines
Quoted 6 lines

and if the code encounters a Page<Base> and finds it has no refcount, it should convert it to Page<Frozen> or there should be a method that accepts PFN and return Page<Frozen> if the page of the PFN has no refcount, for PFN walkers.

We can add conversion functions, that makes sense.

Quoted 4 lines

“the data” mentioned in Page<Exclusive> and Page<Frozen> is struct page data or the data in the physical frame pointed by Page<...>? If it is the former, is it better to use metadata?

I'm referring to the actual physical memory region that the struct page describes.

Quoted 3 lines

I am new to Rust, so feel free to correct me. Thanks. :)

Quoted 7 lines
Quoted 1 line

I'm new to mm, I really appreciate your eyes on this.

Do you mind describing the high level workflow around Page in Rust? From my point of view, exclusive page content access is more related to page table (including IOMMU page table) than struct page itself. struct page ownership is more about the metadata stored in struct page for physical memory maintenance.

Quoted 6 lines

Just as in C code, there are many workflows around Page. Three main ones I have seen in Rust code are:

- Pages that are part of io buffers during a syscall. The pages are mapped in at least one user space process and the kernel may want to read or write from/to them. These would be Page<RefCounted>.

Is RefCounted too broad for this? A refcounted page might or might not be mapped and a mapped page might not might not be mapped into userspace. Is UserMapped more descriptive?

FYI, I am working on adding PG_folio to distinguish user rmappable folios from general mapped pages. In terms of pages mapped into userspace process, they can be either rmappable or vm_insert*() into userspace.

Quoted 3 lines

- Pages that hit the block device driver API via the block layer. These can be anything, so we model them as Page<Base>.

Even they can be frozen without a refcount?

Quoted 3 lines

- Pages used for backing storage like in the null block driver. These are modeled as Page<Exclusive>.

null_alloc_page() uses alloc_pages() and gets refcount == 1 pages. unless you mean struct nullb_page.

Quoted 7 lines

I think for the first one, binder is inserting and removing pages from vmas to do it's IPC thing.

If someone were to write an allocator of some kind, they would probably reach for the Page<Frozen>, as they would like to have ownership of the metadata, but not the contents.

Probably.

Best Regards,
Yan, Zi