Linux-mm Archive on lore.kernel.org
 help / color / mirror / Atom feed
From: sashiko-bot@kernel.org
To: "Vitaly Wool" <vitaly.wool@konsulko.se>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Jens Axboe" <axboe@kernel.dk>, "Miguel Ojeda" <ojeda@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>
Cc: "Boqun Feng" <boqun@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>,
	"Lorenzo Stoakes" <ljs@kernel.org>,
	"Liam R . Howlett" <liam@infradead.org>,
	linux-mm@kvack.org, "Igor B" <igor.b@beldev.am>
Subject: Re: [PATCH 2/3] rust: page: add reference counting, raw pointers and a private bit lock
Date: Wed, 18 Nov 2026 23:36:24 +0000	[thread overview]
Message-ID: <sashiko-outbox-222197@kernel.org> (raw)
In-Reply-To: <20261117233211.3137168-3-vitaly.wool@konsulko.se>

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [High] rust: page: unsound speculative ref and __free_pages() drop in
  try_get_raw()
- [Medium] rust: page: BorrowedPage lifetime escape via Deref to
  Page::get()
--

commit ce2ee3f082c492cf922004e652ef173e3c507e27
Author: Igor B <igor.b@beldev.am>

rust: page: add reference counting, raw pointers and a private bit lock

This commit adds reference counting, raw pointer conversion helpers, and a
private bit spinlock to the Rust Page abstraction, along with the
underlying C helpers.

> diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs
> index 1c0796ea229f0..e75d9efbcce63 100644
> --- a/rust/kernel/page.rs
> +++ b/rust/kernel/page.rs
[ ... ]
> @@ -200,6 +205,139 @@ pub fn as_ptr(&self) -> *mut bindings::page {
>          self.page.as_ptr()
>      }
>  
> +    /// Takes an additional reference on this page.
[ ... ]
> +    #[inline]
> +    pub fn get(&self) -> Self {
> +        // SAFETY: `self.page` is valid by the type invariant, and calling `get_page` on a page
> +        // that is kept alive by `self` is always safe.
> +        unsafe { bindings::get_page(self.page.as_ptr()) };
> +        // INVARIANT: We just took a new reference to the page pointed to by `self.page`, so the
> +        // new `Page` has ownership over that reference.
> +        Self { page: self.page }
> +    }

[Severity: Medium]
Does taking &self in Page::get() allow a non-owning BorrowedPage<'a> to
escape its borrow lifetime 'a in safe code?

BorrowedPage<'a> implements Deref<Target = Page>, so safe callers can call
borrowed_page.get() to obtain an owned Page with no lifetime bound.
For example, VBox::page_iter() and VVec::page_iter() yield BorrowedPage<'a>
items tied to a mutable borrow of the container; calling .get() lets safe
code retain and access the underlying physical page after 'a ends while
VBox/VVec holds exclusive mutable access or frees the memory.  In addition,
BorrowedPage::from_raw() only requires a valid struct page pointer for 'a,
not a refcounted order-0 page: if it wraps a slab or large_kmalloc page,
get_page() warns and returns without incrementing the refcount, and
dropping the returned Page calls __free_pages() without owning a reference.

> +
> +    /// Consumes the [`Page`], returning the raw pointer to its `struct page`.
[ ... ]
> +    /// Attempts to take ownership of a page from a raw, possibly stale pointer.
> +    ///
> +    /// On success, returns a new [`Page`] that owns one reference to the page. On failure
> +    /// (meaning the page's reference count had already reached zero, i.e. its last owner had
> +    /// already released it), returns `None` without otherwise touching the page.
> +    ///
> +    /// This is the kernel's usual way of giving a lock-free, concurrent lookup (such as one
> +    /// protected by the RCU read lock; see [`kernel::sync::rcu`](crate::sync::rcu)) a safe way to
> +    /// turn a pointer it found into an owned reference, without taking any lock: unlike
> +    /// [`get`](Self::get), this does not assume `ptr` is already known to be alive.
> +    ///
> +    /// # Safety
> +    ///
> +    /// `ptr` must point at a valid `struct page`. Note that, unlike most kernel objects, a
> +    /// `struct page` is never freed or reused for a different purpose for as long as the system
> +    /// is running: only the memory it describes is freed and may be reused once its reference
> +    /// count drops to zero. It is therefore always safe to inspect and modify the reference count
> +    /// through a `struct page` pointer that was, at some point, validly obtained, even if the
> +    /// page has since been fully released by its last owner, as long as the pointer has not since
> +    /// been reused to mean something other than a `struct page` pointer (which can only happen if
> +    /// the caller itself reinterprets it as something else).
> +    #[inline]
> +    pub unsafe fn try_get_raw(ptr: NonNull<bindings::page>) -> Option<Self> {
> +        // SAFETY: By the safety requirements of this function, `ptr` points at a valid
> +        // `struct page`.
> +        //
> +        // INVARIANT: If this call returns `true`, then it has just incremented the reference
> +        // count of the page pointed to by `ptr`, and we have ownership over that new reference.
> +        if unsafe { bindings::get_page_unless_zero(ptr.as_ptr()) } {
> +            Some(Self { page: ptr })
> +        } else {
> +            None
> +        }
> +    }

[Severity: High]
Can Page::try_get_raw() acquire a speculative reference to a page that was
freed and reallocated to another kernel subsystem, and then release it with
__free_pages(ptr, 0) instead of put_page()?

CPU0                              CPU1
----                              ----
ptr = load page slot
                                  drop(last_page_owner)
                                    __free_pages(ptr, 0)
                                  page reallocated (e.g. compound
                                  or LRU folio, refcount >= 1)
Page::try_get_raw(ptr)
  get_page_unless_zero(ptr) -> true
                                  new owner drops its ref
slot check fails:
drop(page)
  __free_pages(ptr, 0)  <-- VM_BUG_ON_PAGE / bad_page()

Because Page::drop() frees pages immediately via __free_pages(ptr, 0)
without an RCU grace period, the struct page at ptr can be reallocated to
an unrelated user (such as a higher-order compound folio or an LRU/memcg
folio) before get_page_unless_zero() runs.  get_page_unless_zero() then
succeeds on the new allocation.  Unlike C's brd_lookup_page(), which
releases a mismatched speculative reference with put_page() (calling
folio_put()), dropping the returned Page calls __free_pages(ptr, 0):

rust/kernel/page.rs:<Page as Drop>::drop() {
    unsafe { bindings::__free_pages(self.page.as_ptr(), 0) };
}

As noted on __free_pages() in mm/page_alloc.c, speculative references must
be dropped with put_page() rather than __free_pages(); calling
__free_pages(ptr, 0) on a compound or LRU folio triggers VM_BUG_ON_PAGE(
compound && compound_order(page) != order) in __free_pages_prepare() or
bad_page() when freeing a page still on an LRU list.

In addition, the Safety contract of try_get_raw() does not require the
caller to re-validate the lookup slot after get_page_unless_zero() succeeds
before accessing the returned Page.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261117233211.3137168-1-vitaly.wool@konsulko.se?part=2


  parent reply	other threads:[~2026-11-18 23:36 UTC|newest]

Thread overview: 11+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-17 23:32 [PATCH 0/3] rust: block: add rbrd, a RAM backed block driver Vitaly Wool
2026-11-17 23:32 ` [PATCH 1/3] rust: block: add bio segment iteration and request accessors Vitaly Wool
2026-11-18 15:19   ` Andreas Hindborg
2026-11-18 23:36   ` sashiko-bot
2026-11-17 23:32 ` [PATCH 2/3] rust: page: add reference counting, raw pointers and a private bit lock Vitaly Wool
2026-11-18 15:23   ` Andreas Hindborg
2026-11-18 23:36   ` sashiko-bot [this message]
2026-11-17 23:32 ` [PATCH 3/3] rust: block: add rbrd, a RAM backed block driver Vitaly Wool
2026-11-18 23:36   ` sashiko-bot
2026-11-18 11:43 ` [PATCH 0/3] " Jan Engelhardt
2026-11-18 14:48   ` Vitaly Wool

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=sashiko-outbox-222197@kernel.org \
    --to=sashiko-bot@kernel.org \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=axboe@kernel.dk \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=gary@garyguo.net \
    --cc=igor.b@beldev.am \
    --cc=liam@infradead.org \
    --cc=linux-mm@kvack.org \
    --cc=ljs@kernel.org \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=sashiko-reviews@lists.linux.dev \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=vitaly.wool@konsulko.se \
    --cc=work@onurozkan.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox