From nobody Fri Dec 19 19:14:00 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 005C4204684 for ; Mon, 3 Feb 2025 12:15:15 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584920; cv=none; b=JKNZO8VIXdNY3dDbiwywq2qTsJ0d+fVRQgcUGSGIyrBzvQpCt5rt5LBdMmgCv8okhlMVZ4/ydubc6zZqzqDVsEkllETxr+KP3UVFyQ43PAHAUAbYa0TCQ2Mqx8DX4saurKpYtoCecR2UXugh0eKgExh5rqCOBLKvMlA1eLma7lE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584920; c=relaxed/simple; bh=SmRa0acQEuEADan3GdJe/hIPrJuPHtTw8z6DhPDiFqM=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=Y3qwU5j02VI7sB67e72yiB347sQAvIYZRHKx5qc4AOn5OHs4g7rPRgcMHv9HvewaSG1TvcxeHqP78BqHVSaf+V1vbnk4MhiZFMuEbI9zZvqmHpc7inliDAMuS2f0p5cc7toJFmRh3IydegZ8bdyy7mkKSdbRvCyBOBrJdJ/0SZ8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=4rm/DI27; arc=none smtp.client-ip=209.85.128.73 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="4rm/DI27" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-4362f893bfaso22687845e9.1 for ; Mon, 03 Feb 2025 04:15:15 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1738584914; x=1739189714; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=wQaS28cG6yW+ftNKFxNZP6eegjrIvFbvaYv5chLHbzg=; b=4rm/DI27PnFJm5fMOOm/QaN8a0nmHnJzL9jVawkWxCGHGOIKbQASGcr6CiI1lJLrH9 YrfGBCGf3LrxWw3kcxnZFfbJCko2h0ZVPvXsesjxrYWkhxSDcrlalL+xaKV6aeljtjzs TbuyX6VST6C9735YrH/DD+0e1d2RWR04941wRsRHbqmxO3x+bv/BfqPdnXC7gWphGxpD /DUEiR6XnnX7DiHFn/ZHNdgFQtNOcllzl0rvXbF9c2prKK5+agsPKFdGphAAySlhPPEe kRyabgkZzujRdTVSxmwr6h39yTxXVYqsc4vO+FWDbBfmOfRXNLS2+a3lFuqNmdG9sHMS lXSg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738584914; x=1739189714; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=wQaS28cG6yW+ftNKFxNZP6eegjrIvFbvaYv5chLHbzg=; b=kcMkzknJ9MWcw2pnzsWOdBaakFSupqVsANILyTivkqIfCjvJW5H9o+sdiiD4fFgYlM Hn0E1WaVFOUQMAzlW9kKroNmhxjl8aF7nHxkb5YHZHQ5c3lLdt+oiD6jn84ZvNJZXE4E dsloD5dqtrBL7JMY9zv2FEVr3ZetiCtLzk7t+ZrfpqMihWIO38Ls1Lh7HwbQ8kJ9SlRl 4SKkYKW7rtHC0eqvZt7ZobMbe2ZaZgq577rWpeqHZPrbaiwVzEX/wa4yICBpRpH0BL35 o5wdlq7sW9+vojmIlzReiOtxU9YvEVs47jbVM3NWMwwTzgQW933R/+43x8GIWfdTvZnZ 6EsQ== X-Forwarded-Encrypted: i=1; AJvYcCXjs//p7kJla4R7QOzBPTSMl2xaLUkVfTy65YbaAst20jG2o+bYZXwzF2XboYjGqSkC917txYeNDELeM70=@vger.kernel.org X-Gm-Message-State: AOJu0Ywlr8ADEqR24yPxIA98ESXW8CG4szBSb3mgFbnhkdhMZ/3aGC15 9u9wjby62dxWJT/8WB/zUOQ61sk375aFXyQUHwg4e1MoNJ3PIobTMuhJ+YcybJPYoxYG3X+7saj saYK9Kq7XwIqTSg== X-Google-Smtp-Source: AGHT+IGxJxBbT2D0jUH7PkoghvafmPAMvx3j15vJoonAlLH+FDpuc6DZ1HXcdNaeLgjK2m0GeHgRrPy+nOzkvHI= X-Received: from wmbbh25.prod.google.com ([2002:a05:600c:3d19:b0:436:e723:5be6]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:a089:b0:431:547e:81d0 with SMTP id 5b1f17b1804b1-438dc3bac30mr240516145e9.11.1738584914324; Mon, 03 Feb 2025 04:15:14 -0800 (PST) Date: Mon, 03 Feb 2025 12:14:36 +0000 In-Reply-To: <20250203-vma-v13-0-2b998268a396@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250203-vma-v13-0-2b998268a396@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=10247; i=aliceryhl@google.com; h=from:subject:message-id; bh=SmRa0acQEuEADan3GdJe/hIPrJuPHtTw8z6DhPDiFqM=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnoLNJtc+O9U//+xzFxHIwPIhQUQRbRxX/4wZxI dLTxDCumKyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ6CzSQAKCRAEWL7uWMY5 RocAEACJm1PYPEHpHiykEjJyFzPL4gv8/tCMYFkHQSopUImzpSVQlc7CE2mwY9GKpP8he2AbVHb wdGSI6KeAhnFzA4nPPBUG8c/VBuONn5+aS3fJY9TT4m6QgzccvQm+UuOx/rfiVdbSxPhJJ8u5Aq 9Dd/rpp9maEV2yx59n6I5tuf3jpvdLGkSQDTRghtBwhX00tMzU7PoCdlvYG39FpDjmfrAOU3JJe /Lxy+FoJvw+779h9exMd3sITMAp4X+ze3c7a9arfaro9GMqoFM5gxfx+lbKlKg+6lyzsFReMkCB gJwPMD0saRr4ndazh3/Yq3GbRceVIJkzpLhTYSoBbjmpMcpGLm3plmStKN09A0lJfosOxaMu26a HdyMEmRAcSXmfsZZnJf2DEv17YijbG4injaPUlqua6VYJydhNMeU50NbziZKK9po9oSBp84z9MR wgkjzCRsHrQX7A0OQh9Y50A5oQi4ICfAIqIEEPYfjO8esKtcH03cYVMwFEI8nzMKlsO/8yG2WkL MzBsyTuZfSPrQOc2eOz7OF6A2/0cvJwNFqXOrj2Zu34d8AKTGsPkAjg600u61nOEo6Co8SZQyop Wh8ybfPGSzR1QN6bFbnJlbnaot1NvB/ZPxTTiJYV0sX9Bzx3nb9KFyHgE5A4ocDkTta9pyy02ET 87mcDAXq6UUwpsw== X-Mailer: b4 0.13.0 Message-ID: <20250203-vma-v13-1-2b998268a396@google.com> Subject: [PATCH v13 1/8] mm: rust: add abstraction for struct mm_struct From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Balbir Singh Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable These abstractions allow you to reference a `struct mm_struct` using both mmgrab and mmget refcounts. This is done using two Rust types: * Mm - represents an mm_struct where you don't know anything about the value of mm_users. * MmWithUser - represents an mm_struct where you know at compile time that mm_users is non-zero. This allows us to encode in the type system whether a method requires that mm_users is non-zero or not. For instance, you can always call `mmget_not_zero` but you can only call `mmap_read_lock` when mm_users is non-zero. The struct is called Mm to keep consistency with the C side. The ability to obtain `current->mm` is added later in this series. Acked-by: Lorenzo Stoakes Acked-by: Balbir Singh Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl --- rust/helpers/helpers.c | 1 + rust/helpers/mm.c | 39 +++++++++ rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 209 +++++++++++++++++++++++++++++++++++++++++++++= ++++ 4 files changed, 250 insertions(+) diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 0640b7e115be..97cfc2d29f5e 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -18,6 +18,7 @@ #include "io.c" #include "jump_label.c" #include "kunit.c" +#include "mm.c" #include "mutex.c" #include "page.c" #include "platform.c" diff --git a/rust/helpers/mm.c b/rust/helpers/mm.c new file mode 100644 index 000000000000..7201747a5d31 --- /dev/null +++ b/rust/helpers/mm.c @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include +#include + +void rust_helper_mmgrab(struct mm_struct *mm) +{ + mmgrab(mm); +} + +void rust_helper_mmdrop(struct mm_struct *mm) +{ + mmdrop(mm); +} + +void rust_helper_mmget(struct mm_struct *mm) +{ + mmget(mm); +} + +bool rust_helper_mmget_not_zero(struct mm_struct *mm) +{ + return mmget_not_zero(mm); +} + +void rust_helper_mmap_read_lock(struct mm_struct *mm) +{ + mmap_read_lock(mm); +} + +bool rust_helper_mmap_read_trylock(struct mm_struct *mm) +{ + return mmap_read_trylock(mm); +} + +void rust_helper_mmap_read_unlock(struct mm_struct *mm) +{ + mmap_read_unlock(mm); +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 496ed32b0911..9cf35fbff356 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -57,6 +57,7 @@ pub mod kunit; pub mod list; pub mod miscdevice; +pub mod mm; #[cfg(CONFIG_NET)] pub mod net; pub mod of; diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs new file mode 100644 index 000000000000..2fb5f440af60 --- /dev/null +++ b/rust/kernel/mm.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Memory management. +//! +//! This module deals with managing the address space of userspace process= es. Each process has an +//! instance of [`Mm`], which keeps track of multiple VMAs (virtual memory= areas). Each VMA +//! corresponds to a region of memory that the userspace process can acces= s, and the VMA lets you +//! control what happens when userspace reads or writes to that region of = memory. +//! +//! C header: [`include/linux/mm.h`](srctree/include/linux/mm.h) + +use crate::{ + bindings, + types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque}, +}; +use core::{ops::Deref, ptr::NonNull}; + +/// A wrapper for the kernel's `struct mm_struct`. +/// +/// This represents the address space of a userspace process, so each proc= ess has one `Mm` +/// instance. It may hold many VMAs internally. +/// +/// There is a counter called `mm_users` that counts the users of the addr= ess space; this includes +/// the userspace process itself, but can also include kernel threads acce= ssing the address space. +/// Once `mm_users` reaches zero, this indicates that the address space ca= n be destroyed. To access +/// the address space, you must prevent `mm_users` from reaching zero whil= e you are accessing it. +/// The [`MmWithUser`] type represents an address space where this is guar= anteed, and you can +/// create one using [`mmget_not_zero`]. +/// +/// The `ARef` smart pointer holds an `mmgrab` refcount. Its destructo= r may sleep. +/// +/// # Invariants +/// +/// Values of this type are always refcounted using `mmgrab`. +/// +/// [`mmget_not_zero`]: Mm::mmget_not_zero +#[repr(transparent)] +pub struct Mm { + mm: Opaque, +} + +// SAFETY: It is safe to call `mmdrop` on another thread than where `mmgra= b` was called. +unsafe impl Send for Mm {} +// SAFETY: All methods on `Mm` can be called in parallel from several thre= ads. +unsafe impl Sync for Mm {} + +// SAFETY: By the type invariants, this type is always refcounted. +unsafe impl AlwaysRefCounted for Mm { + #[inline] + fn inc_ref(&self) { + // SAFETY: The pointer is valid since self is a reference. + unsafe { bindings::mmgrab(self.as_raw()) }; + } + + #[inline] + unsafe fn dec_ref(obj: NonNull) { + // SAFETY: The caller is giving up their refcount. + unsafe { bindings::mmdrop(obj.cast().as_ptr()) }; + } +} + +/// A wrapper for the kernel's `struct mm_struct`. +/// +/// This type is like [`Mm`], but with non-zero `mm_users`. It can only be= used when `mm_users` can +/// be proven to be non-zero at compile-time, usually because the relevant= code holds an `mmget` +/// refcount. It can be used to access the associated address space. +/// +/// The `ARef` smart pointer holds an `mmget` refcount. Its de= structor may sleep. +/// +/// # Invariants +/// +/// Values of this type are always refcounted using `mmget`. The value of = `mm_users` is non-zero. +#[repr(transparent)] +pub struct MmWithUser { + mm: Mm, +} + +// SAFETY: It is safe to call `mmput` on another thread than where `mmget`= was called. +unsafe impl Send for MmWithUser {} +// SAFETY: All methods on `MmWithUser` can be called in parallel from seve= ral threads. +unsafe impl Sync for MmWithUser {} + +// SAFETY: By the type invariants, this type is always refcounted. +unsafe impl AlwaysRefCounted for MmWithUser { + #[inline] + fn inc_ref(&self) { + // SAFETY: The pointer is valid since self is a reference. + unsafe { bindings::mmget(self.as_raw()) }; + } + + #[inline] + unsafe fn dec_ref(obj: NonNull) { + // SAFETY: The caller is giving up their refcount. + unsafe { bindings::mmput(obj.cast().as_ptr()) }; + } +} + +// Make all `Mm` methods available on `MmWithUser`. +impl Deref for MmWithUser { + type Target =3D Mm; + + #[inline] + fn deref(&self) -> &Mm { + &self.mm + } +} + +// These methods are safe to call even if `mm_users` is zero. +impl Mm { + /// Returns a raw pointer to the inner `mm_struct`. + #[inline] + pub fn as_raw(&self) -> *mut bindings::mm_struct { + self.mm.get() + } + + /// Obtain a reference from a raw pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` points at an `mm_struct`, and th= at it is not deallocated + /// during the lifetime 'a. + #[inline] + pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_struct) -> &'a Mm { + // SAFETY: Caller promises that the pointer is valid for 'a. Layou= ts are compatible due to + // repr(transparent). + unsafe { &*ptr.cast() } + } + + /// Calls `mmget_not_zero` and returns a handle if it succeeds. + #[inline] + pub fn mmget_not_zero(&self) -> Option> { + // SAFETY: The pointer is valid since self is a reference. + let success =3D unsafe { bindings::mmget_not_zero(self.as_raw()) }; + + if success { + // SAFETY: We just created an `mmget` refcount. + Some(unsafe { ARef::from_raw(NonNull::new_unchecked(self.as_ra= w().cast())) }) + } else { + None + } + } +} + +// These methods require `mm_users` to be non-zero. +impl MmWithUser { + /// Obtain a reference from a raw pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` points at an `mm_struct`, and th= at `mm_users` remains + /// non-zero for the duration of the lifetime 'a. + #[inline] + pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_struct) -> &'a MmW= ithUser { + // SAFETY: Caller promises that the pointer is valid for 'a. The l= ayout is compatible due + // to repr(transparent). + unsafe { &*ptr.cast() } + } + + /// Lock the mmap read lock. + #[inline] + pub fn mmap_read_lock(&self) -> MmapReadGuard<'_> { + // SAFETY: The pointer is valid since self is a reference. + unsafe { bindings::mmap_read_lock(self.as_raw()) }; + + // INVARIANT: We just acquired the read lock. + MmapReadGuard { + mm: self, + _nts: NotThreadSafe, + } + } + + /// Try to lock the mmap read lock. + #[inline] + pub fn mmap_read_trylock(&self) -> Option> { + // SAFETY: The pointer is valid since self is a reference. + let success =3D unsafe { bindings::mmap_read_trylock(self.as_raw()= ) }; + + if success { + // INVARIANT: We just acquired the read lock. + Some(MmapReadGuard { + mm: self, + _nts: NotThreadSafe, + }) + } else { + None + } + } +} + +/// A guard for the mmap read lock. +/// +/// # Invariants +/// +/// This `MmapReadGuard` guard owns the mmap read lock. +pub struct MmapReadGuard<'a> { + mm: &'a MmWithUser, + // `mmap_read_lock` and `mmap_read_unlock` must be called on the same = thread + _nts: NotThreadSafe, +} + +impl Drop for MmapReadGuard<'_> { + #[inline] + fn drop(&mut self) { + // SAFETY: We hold the read lock by the type invariants. + unsafe { bindings::mmap_read_unlock(self.mm.as_raw()) }; + } +} --=20 2.48.1.362.g079036d154-goog From nobody Fri Dec 19 19:14:00 2025 Received: from mail-wr1-f73.google.com (mail-wr1-f73.google.com [209.85.221.73]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1E5E6204689 for ; Mon, 3 Feb 2025 12:15:17 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584920; cv=none; b=Sfn/WDswBZ+2mQT3+Sb7z/OCLF04bX2vQ2ViKQPvKx3MesWLClICxE6Fczgfm7iSipRMb8Tcl6kLtHO7srFCjqMydQ+HUqT+d8N0bz6RlikdzYZ8sq85vDB21HtnqtZxhS9IVlzAorKlcd4ru7dXzrYhA6WkdE/SXOFfILeGQqc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584920; c=relaxed/simple; bh=/iebTH4KyLdhY2vEuCqOUZUvZGhbmsvxzfHd3W6xGAw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=sKEKkKNs1ra4UCvq2bSkYOYpdbrXYzKlPkRhHDRcLHWXXPw8BRWEj24Cgb7p8dUClgd19ST9vxpzmRMdmGViXOhj28pd7kyJsgUyKY38k6m38tE9r4DgPT9b1uymOh4WhrOnL26gPTdD+T83/SCVJkHVtyPsn2pmEUg0EN7w9vc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=ooMUGhUV; arc=none smtp.client-ip=209.85.221.73 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="ooMUGhUV" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-38634103b0dso2712855f8f.2 for ; Mon, 03 Feb 2025 04:15:17 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1738584916; x=1739189716; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=HsKBb44x7fv9WNumP7fvjTBcr8RrxO1zg/m2ciN2/Jk=; b=ooMUGhUVKcBmyVxGl2L/8wDPs3uL0GsXbUSVSSDD3k0VV5eAsNPqASv9ap1gMy5+Sh j4JqoKN/I4EtE73q1LoxoAu0P3kgKpcqJqF+fRM3Usz4DQevodJom0OdzfqNJeKuy5m/ eL5KLQu3erP0QJLWVn7vzOe6cpSSt9ZeWNb2PU4bwaW5wOG1OF8i394fD7sWIFSJge/N Q2ZVM2u7WkRZ2TRjPPeAW5dLrvOrbEhnrwjzutK622JFb54t9k0XZwK/ySGGirZ/M1Hg Pi4Gh7m1YmaFNYjDf3fnloX0XdLIAhfrL2x8AidmaGWvLpODF18jSca1NUubvUu9j+Gw K+dQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738584916; x=1739189716; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=HsKBb44x7fv9WNumP7fvjTBcr8RrxO1zg/m2ciN2/Jk=; b=jJTdKO0CdsgGfZyNDZNS16IeOUVBdqvYoy1swU4vTjaHEG6d2Fua1IbewTtM8529Jf /ooKAlGB6Lxh7GMxIZe2cHNiHv3HleOPdW0433owmL5ykNKDNrOcjAkrx2qAk6MCqHlX D+MQjImIxizl7MlZuC5QRPrFnn1OZrzBdu6tKXQEuO6lvx1gf7Y9HDY1CvZ+trocsCDE 20xxOkgO61uZCPs2YeMc7xIKrFnnlFpLXAoiJ+Z8eKCnyVf+WmvAwMsK1KaFwWVxJAdL 8KgoGfPWoUg+CaY6SZgh2KoJh4yqVzBszX9Sq0E6m/QaF7PvSc3vM4v7teuUK99Dx3nc 7tMA== X-Forwarded-Encrypted: i=1; AJvYcCUpweTvdKgLotKPsVsZQzb1eMQ3ZjTj80TJyApYG0bdDgEaXLnQHDFI2Vb6axAGQPPHFK437wTKiONuorY=@vger.kernel.org X-Gm-Message-State: AOJu0YxJAQ74L5t5Hp13FFK/ic4XB0lJrh5nhmf70Bwj8oFi5mTBDC+z GVi3Vb/kPeqr0L4g0BwlB5Dbdq2Vvm8MPI1+LswUHXa1cSRVdbfHDwNRJQJbS16lRaer5ctoVUL KFdAwg7wNbo9wdg== X-Google-Smtp-Source: AGHT+IGOresZtCVdJKJ16Ys67mlWuwAfUZhBuPWvVIUcEJB1FfKeHTp8NIO1djUpkZoFwaOzxSKnCdpKbygHPEE= X-Received: from wmbbd13.prod.google.com ([2002:a05:600c:1f0d:b0:436:d819:e4eb]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a5d:64e4:0:b0:38a:88b8:99af with SMTP id ffacd0b85a97d-38c51951c62mr17694566f8f.22.1738584916380; Mon, 03 Feb 2025 04:15:16 -0800 (PST) Date: Mon, 03 Feb 2025 12:14:37 +0000 In-Reply-To: <20250203-vma-v13-0-2b998268a396@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250203-vma-v13-0-2b998268a396@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=11755; i=aliceryhl@google.com; h=from:subject:message-id; bh=/iebTH4KyLdhY2vEuCqOUZUvZGhbmsvxzfHd3W6xGAw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnoLNJRZfEeR3BWa35+Ak8WITPcMAAKc+QWrycD kjuKVWdrXCJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ6CzSQAKCRAEWL7uWMY5 RrjdD/9d3vmLpQxCmf2tyIFTe9dQwpb1iBMSAvRFzmKu4O1tCa5YWfrnaXETZ4zvdhKTX3g2KKb 3ToivU/ExeDSdC3XpbFd2TrTitpNFUSYhuRbE3cVssUotjcfwhhJGblejNUYaxktpljVRyWObMD O5rGkdtaDB1BvhYoKzFlGK/3SwId0AmDQ29cFKVdYh28Uk+edlT8idXS0b46aRkmqvY39kjG2Gt b+HtofyaMg3gqzMGgfIv2avEIm2WGpcxrTMou87zLGpzfbpWknwXhLiOrX9zxtte6CyZPB5gNm6 rht0AEZXCEOPEN2ISN0zBoITZR7B5yrQJmlZ06JaRSzX5wfTObamyJbJmys9FCoLfAI2tQfQG5d 7t98kzkwdYl8XfmEBFT9e/7Kld5Hpa1XzQ+RSkBXYbjY3vmhKti5Ev7eX1YVMx42sGFgO7LvxNv cErtZCKMWoqxs6SfRz8WYi0ES19Ip63L1qWPda2Uu28USt3UBuPHHgxDgq1Vcbj+RmivpQaF/4I C7tBYlQevnitMD7q0YsGC6wMGRlLJ9ZbpVxOcw838c2tMn59KGT35NlRMzhzocKXlvnL9Nc7ndj /6FzQf6+ugL4N3/zCXMT1W1u6AaAoYY0WqgsLPNNQj3F0Prz2+BvJCloJ1aRSlhUBoquwK23CQ6 h5I822DNznDWZSg== X-Mailer: b4 0.13.0 Message-ID: <20250203-vma-v13-2-2b998268a396@google.com> Subject: [PATCH v13 2/8] mm: rust: add vm_area_struct methods that require read access From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This adds a type called VmAreaRef which is used when referencing a vma that you have read access to. Here, read access means that you hold either the mmap read lock or the vma read lock (or stronger). Additionally, a vma_lookup method is added to the mmap read guard, which enables you to obtain a &VmAreaRef in safe Rust code. This patch only provides a way to lock the mmap read lock, but a follow-up patch also provides a way to just lock the vma read lock. Acked-by: Lorenzo Stoakes Reviewed-by: Jann Horn Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl --- rust/helpers/mm.c | 6 ++ rust/kernel/mm.rs | 21 +++++ rust/kernel/mm/virt.rs | 215 +++++++++++++++++++++++++++++++++++++++++++++= ++++ 3 files changed, 242 insertions(+) diff --git a/rust/helpers/mm.c b/rust/helpers/mm.c index 7201747a5d31..7b72eb065a3e 100644 --- a/rust/helpers/mm.c +++ b/rust/helpers/mm.c @@ -37,3 +37,9 @@ void rust_helper_mmap_read_unlock(struct mm_struct *mm) { mmap_read_unlock(mm); } + +struct vm_area_struct *rust_helper_vma_lookup(struct mm_struct *mm, + unsigned long addr) +{ + return vma_lookup(mm, addr); +} diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs index 2fb5f440af60..bd6ff40f106f 100644 --- a/rust/kernel/mm.rs +++ b/rust/kernel/mm.rs @@ -17,6 +17,8 @@ }; use core::{ops::Deref, ptr::NonNull}; =20 +pub mod virt; + /// A wrapper for the kernel's `struct mm_struct`. /// /// This represents the address space of a userspace process, so each proc= ess has one `Mm` @@ -200,6 +202,25 @@ pub struct MmapReadGuard<'a> { _nts: NotThreadSafe, } =20 +impl<'a> MmapReadGuard<'a> { + /// Look up a vma at the given address. + #[inline] + pub fn vma_lookup(&self, vma_addr: usize) -> Option<&virt::VmAreaRef> { + // SAFETY: We hold a reference to the mm, so the pointer must be v= alid. Any value is okay + // for `vma_addr`. + let vma =3D unsafe { bindings::vma_lookup(self.mm.as_raw(), vma_ad= dr) }; + + if vma.is_null() { + None + } else { + // SAFETY: We just checked that a vma was found, so the pointe= r is valid. Furthermore, + // the returned area will borrow from this read lock guard, so= it can only be used + // while the mmap read lock is still held. + unsafe { Some(virt::VmAreaRef::from_raw(vma)) } + } + } +} + impl Drop for MmapReadGuard<'_> { #[inline] fn drop(&mut self) { diff --git a/rust/kernel/mm/virt.rs b/rust/kernel/mm/virt.rs new file mode 100644 index 000000000000..dfe147cafdb3 --- /dev/null +++ b/rust/kernel/mm/virt.rs @@ -0,0 +1,215 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Virtual memory. +//! +//! This module deals with managing a single VMA in the address space of a= userspace process. Each +//! VMA corresponds to a region of memory that the userspace process can a= ccess, and the VMA lets +//! you control what happens when userspace reads or writes to that region= of memory. +//! +//! The module has several different Rust types that all correspond to the= C type called +//! `vm_area_struct`. The different structs represent what kind of access = you have to the VMA, e.g. +//! [`VmAreaRef`] is used when you hold the mmap or vma read lock. Using t= he appropriate struct +//! ensures that you can't, for example, accidentally call a function that= requires holding the +//! write lock when you only hold the read lock. + +use crate::{bindings, mm::MmWithUser, types::Opaque}; + +/// A wrapper for the kernel's `struct vm_area_struct` with read access. +/// +/// It represents an area of virtual memory. +/// +/// # Invariants +/// +/// The caller must hold the mmap read lock or the vma read lock. +#[repr(transparent)] +pub struct VmAreaRef { + vma: Opaque, +} + +// Methods you can call when holding the mmap or vma read lock (or stronge= r). They must be usable +// no matter what the vma flags are. +impl VmAreaRef { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is valid for the duration of 'a, an= d that the mmap or vma + /// read lock (or stronger) is held for at least the duration of 'a. + #[inline] + pub unsafe fn from_raw<'a>(vma: *const bindings::vm_area_struct) -> &'= a Self { + // SAFETY: The caller ensures that the invariants are satisfied fo= r the duration of 'a. + unsafe { &*vma.cast() } + } + + /// Returns a raw pointer to this area. + #[inline] + pub fn as_ptr(&self) -> *mut bindings::vm_area_struct { + self.vma.get() + } + + /// Access the underlying `mm_struct`. + #[inline] + pub fn mm(&self) -> &MmWithUser { + // SAFETY: By the type invariants, this `vm_area_struct` is valid = and we hold the mmap/vma + // read lock or stronger. This implies that the underlying mm has = a non-zero value of + // `mm_users`. + unsafe { MmWithUser::from_raw((*self.as_ptr()).vm_mm) } + } + + /// Returns the flags associated with the virtual memory area. + /// + /// The possible flags are a combination of the constants in [`flags`]. + #[inline] + pub fn flags(&self) -> vm_flags_t { + // SAFETY: By the type invariants, the caller holds at least the m= map read lock, so this + // access is not a data race. + unsafe { (*self.as_ptr()).__bindgen_anon_2.vm_flags } + } + + /// Returns the (inclusive) start address of the virtual memory area. + #[inline] + pub fn start(&self) -> usize { + // SAFETY: By the type invariants, the caller holds at least the m= map read lock, so this + // access is not a data race. + unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_sta= rt } + } + + /// Returns the (exclusive) end address of the virtual memory area. + #[inline] + pub fn end(&self) -> usize { + // SAFETY: By the type invariants, the caller holds at least the m= map read lock, so this + // access is not a data race. + unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_end= } + } + + /// Zap pages in the given page range. + /// + /// This clears page table mappings for the range at the leaf level, l= eaving all other page + /// tables intact, and freeing any memory referenced by the VMA in thi= s range. That is, + /// anonymous memory is completely freed, file-backed memory has its r= eference count on page + /// cache folio's dropped, any dirty data will still be written back t= o disk as usual. + /// + /// It may seem odd that we clear at the leaf level, this is however a= product of the page + /// table structure used to map physical memory into a virtual address= space - each virtual + /// address actually consists of a bitmap of array indices into page t= ables, which form a + /// hierarchical page table level structure. + /// + /// As a result, each page table level maps a multiple of page table l= evels below, and thus + /// span ever increasing ranges of pages. At the leaf or PTE level, we= map the actual physical + /// memory. + /// + /// It is here where a zap operates, as it the only place we can be ce= rtain of clearing without + /// impacting any other virtual mappings. It is an implementation deta= il as to whether the + /// kernel goes further in freeing unused page tables, but for the pur= poses of this operation + /// we must only assume that the leaf level is cleared. + #[inline] + pub fn zap_page_range_single(&self, address: usize, size: usize) { + let (end, did_overflow) =3D address.overflowing_add(size); + if did_overflow || address < self.start() || self.end() < end { + // TODO: call WARN_ONCE once Rust version of it is added + return; + } + + // SAFETY: By the type invariants, the caller has read access to t= his VMA, which is + // sufficient for this method call. This method has no requirement= s on the vma flags. The + // address range is checked to be within the vma. + unsafe { + bindings::zap_page_range_single( + self.as_ptr(), + address, + size, + core::ptr::null_mut(), + ) + }; + } +} + +/// The integer type used for vma flags. +#[doc(inline)] +pub use bindings::vm_flags_t; + +/// All possible flags for [`VmAreaRef`]. +pub mod flags { + use super::vm_flags_t; + use crate::bindings; + + /// No flags are set. + pub const NONE: vm_flags_t =3D bindings::VM_NONE as _; + + /// Mapping allows reads. + pub const READ: vm_flags_t =3D bindings::VM_READ as _; + + /// Mapping allows writes. + pub const WRITE: vm_flags_t =3D bindings::VM_WRITE as _; + + /// Mapping allows execution. + pub const EXEC: vm_flags_t =3D bindings::VM_EXEC as _; + + /// Mapping is shared. + pub const SHARED: vm_flags_t =3D bindings::VM_SHARED as _; + + /// Mapping may be updated to allow reads. + pub const MAYREAD: vm_flags_t =3D bindings::VM_MAYREAD as _; + + /// Mapping may be updated to allow writes. + pub const MAYWRITE: vm_flags_t =3D bindings::VM_MAYWRITE as _; + + /// Mapping may be updated to allow execution. + pub const MAYEXEC: vm_flags_t =3D bindings::VM_MAYEXEC as _; + + /// Mapping may be updated to be shared. + pub const MAYSHARE: vm_flags_t =3D bindings::VM_MAYSHARE as _; + + /// Page-ranges managed without `struct page`, just pure PFN. + pub const PFNMAP: vm_flags_t =3D bindings::VM_PFNMAP as _; + + /// Memory mapped I/O or similar. + pub const IO: vm_flags_t =3D bindings::VM_IO as _; + + /// Do not copy this vma on fork. + pub const DONTCOPY: vm_flags_t =3D bindings::VM_DONTCOPY as _; + + /// Cannot expand with mremap(). + pub const DONTEXPAND: vm_flags_t =3D bindings::VM_DONTEXPAND as _; + + /// Lock the pages covered when they are faulted in. + pub const LOCKONFAULT: vm_flags_t =3D bindings::VM_LOCKONFAULT as _; + + /// Is a VM accounted object. + pub const ACCOUNT: vm_flags_t =3D bindings::VM_ACCOUNT as _; + + /// Should the VM suppress accounting. + pub const NORESERVE: vm_flags_t =3D bindings::VM_NORESERVE as _; + + /// Huge TLB Page VM. + pub const HUGETLB: vm_flags_t =3D bindings::VM_HUGETLB as _; + + /// Synchronous page faults. (DAX-specific) + pub const SYNC: vm_flags_t =3D bindings::VM_SYNC as _; + + /// Architecture-specific flag. + pub const ARCH_1: vm_flags_t =3D bindings::VM_ARCH_1 as _; + + /// Wipe VMA contents in child on fork. + pub const WIPEONFORK: vm_flags_t =3D bindings::VM_WIPEONFORK as _; + + /// Do not include in the core dump. + pub const DONTDUMP: vm_flags_t =3D bindings::VM_DONTDUMP as _; + + /// Not soft dirty clean area. + pub const SOFTDIRTY: vm_flags_t =3D bindings::VM_SOFTDIRTY as _; + + /// Can contain `struct page` and pure PFN pages. + pub const MIXEDMAP: vm_flags_t =3D bindings::VM_MIXEDMAP as _; + + /// MADV_HUGEPAGE marked this vma. + pub const HUGEPAGE: vm_flags_t =3D bindings::VM_HUGEPAGE as _; + + /// MADV_NOHUGEPAGE marked this vma. + pub const NOHUGEPAGE: vm_flags_t =3D bindings::VM_NOHUGEPAGE as _; + + /// KSM may merge identical pages. + pub const MERGEABLE: vm_flags_t =3D bindings::VM_MERGEABLE as _; +} --=20 2.48.1.362.g079036d154-goog From nobody Fri Dec 19 19:14:00 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 56B662045A2 for ; Mon, 3 Feb 2025 12:15:20 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584922; cv=none; b=E6YNeYu+EaTU0bHMe0/Y+PAwbKSLLnkiqkyq980C9egA/fpF5NjSmx86kpnRPiizTO4Oy0MMPL+/3uCOQoQNRfBP4FHPq3RG8uSPvlHLisJXX4SLMe/Rx7ZIXTTt2LcQ6vopMquJnFHSJGUXr4wIt8d+IJ7ZPtBYpsc8X2PUuJk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584922; c=relaxed/simple; bh=7WepNBMO3VHpBbUgOZ7CBvykk1H/XsDvQNuHzOoGaDg=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=JWTnXym9vyKGk6Wtp3IzXiivFf04DL+EdS5KC06Qlil5Jx69Mjoxk7sg3B7Aqy5c5/+UdBSfug9Ao8eiQ35Lwo75/1ITNlk0bTNLOQBlxCsjRxhUBEdbvDK7AFwgFs3ZgDZ43DP02IYTqha8yJR5tDy3MBMim/ILvQsiB7i/rGg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=3mNHeMXI; arc=none smtp.client-ip=209.85.128.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="3mNHeMXI" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43626224274so22352505e9.0 for ; Mon, 03 Feb 2025 04:15:20 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1738584919; x=1739189719; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=ghNopB/ovoE7UI8P7ondlQHgR2/c2oc3ISyJfF1pYKk=; b=3mNHeMXIm84vySPBXmfOpm7KEZmC20W5C9jWgB5LUdhQTaZEKCOohUJ8+Kbbl/ShPm Ee3jgSO89w1nemtIUb4UIFeXfCVXNly7QvBL7MRYhLadTPKv8VNS2hEichRb9JMITM5I Yc6W6fHp3MI9Mb8d8Ma9C1upxbSGUx4ydzhvcqf6h5yefLiVMt8a9xUMORZZPWq2m1dt +lrX2+Bm+UHcl6XyfFmuBAxlJljsot/P8l04tXtVwsbxC17KRQf+JcHeDK7kSSKgkS9G VwZAZeba8u2oab7wGAhz9O72gojtJG7fxIiNM2oRB9I5BeNtk5K3DBzBLdwzZ7PQnDIK iNjQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738584919; x=1739189719; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=ghNopB/ovoE7UI8P7ondlQHgR2/c2oc3ISyJfF1pYKk=; b=YXAR6mwjSa2Z0tMfqIHLULfb4Pyzr2ZhJxy3U3P2H8+tE0WxsKl2hBpMZIzdn/zN/p LPiZaQnl6XWz+t4U+XhKljRjtyRANBUwMPbDOosS67Qwlncy6L1x1aHntVkXfHhJHj/T xOklNDU9x2zWouiCMQX8HYQ2eBRAAFuITkrAluuF3aIgva+03jNk2ZV8jYvvs2FotXuC zV2Sk2Mv+/RU3Z0EDtwZeIZ+/qE/el/OFaVsfqJKoEjrwy0UpfqIur+n/z4LJbBjVYqh iyhRmcngohg3DvyfNntdXd+fk7kA4A8R5qGpcvZwAoShOrSlEVs9AWbt55ouUNnAg4Gk wsyA== X-Forwarded-Encrypted: i=1; AJvYcCURNBx9ZjlsYeopGOpZPJPPdp3PemeWfqHUxPnNM2XQI0mXD4FJsLyhjsNxwSkS4+drOqkLVvflZZ1u1Yo=@vger.kernel.org X-Gm-Message-State: AOJu0YyHeYOQ9mYHZkTqpgI+VnnwA1HKI3AXlSpmrGst4707jWbq5Hef aguvARh/n8Mm66iHf4f71ow54t+RKQeWlrVIG25++0iJT7gsfX7zLzvExr1+SmW1JRnxteZb/zg iBSwY6FUuW0AaCg== X-Google-Smtp-Source: AGHT+IHc83C8k0kWyFW4B7jVylfVU4gtl0Vj6eJsSbBowS4jYe9JFHSyrYsbEeWgcs2CoUj+GFAgp46bZhkRTJQ= X-Received: from wmqd12.prod.google.com ([2002:a05:600c:34cc:b0:435:21e:7bec]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:c12:b0:431:5aea:95f with SMTP id 5b1f17b1804b1-438dc3cc378mr206991585e9.16.1738584918711; Mon, 03 Feb 2025 04:15:18 -0800 (PST) Date: Mon, 03 Feb 2025 12:14:38 +0000 In-Reply-To: <20250203-vma-v13-0-2b998268a396@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250203-vma-v13-0-2b998268a396@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4198; i=aliceryhl@google.com; h=from:subject:message-id; bh=7WepNBMO3VHpBbUgOZ7CBvykk1H/XsDvQNuHzOoGaDg=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnoLNKxtxYKi99rKgHmqWkRH4nWkPittKx4tZr1 V2PKQs0+sWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ6CzSgAKCRAEWL7uWMY5 Rs6nD/9iQkAZn6Vn+uopIfzFcx5caHl87DWWgkBI+qGs0DLDUpqfdZDDlnPBuD/dIBc3jKZ+uo/ Lh/A/voziPGDymGXzHHnNm3JY90Ik7PLD0SLTpzLw2wr12kKYE7LB9Q/xjIVchr710cvfcBhhpn P20GzEcAMsY437I0tnAMaqFRIcIKMO5HVJiXPNJf4akkxzze/3S5i+I76xujCoQiwlO9hACF9x+ tw9+DxI+r62S0RiAUPYSKIEpHWeBCg86V+YKbjn8v50FOXF5ABV+2X8jb/AEVQC6JtVA6DoUNF0 K1+5WN0lBG+em72x4Vcyng5VBjsKX+mQcRpqPbf34ClRqkcbuTtHrDI5Epdwq+xqc5waUutF4Zt 8KBwkMqh9PdEKoFWBw1/6ERz52tmjV8oGdbf6tEgsDgorhKWMEy0HiAeTSLDE6kyujBfFGnCOFm N6eGYTpbEALKFem+VPN4SFR25IHNffR1fF2Pf/Al0m69SBcsOwtAffp5xdxC8au4qiF7nfhuSW7 MHl5N3G7w4IGSxRAlse7Oes7RJKU3nViNhOjCSncG6LfUE7Rf+O6eog2MP62j3dvJJ67znZCm+d EX1c6LqELEE0UFq/3MT9Sn8Qw9H1jmYZFsOFYY9hgAVSfYVUKSwpK17WB+dP17CvpWB3wwlVa/P KQKZVuibB3ekJag== X-Mailer: b4 0.13.0 Message-ID: <20250203-vma-v13-3-2b998268a396@google.com> Subject: [PATCH v13 3/8] mm: rust: add vm_insert_page From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable The vm_insert_page method is only usable on vmas with the VM_MIXEDMAP flag, so we introduce a new type to keep track of such vmas. The approach used in this patch assumes that we will not need to encode many flag combinations in the type. I don't think we need to encode more than VM_MIXEDMAP and VM_PFNMAP as things are now. However, if that becomes necessary, using generic parameters in a single type would scale better as the number of flags increases. Acked-by: Lorenzo Stoakes Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl --- rust/kernel/mm/virt.rs | 79 ++++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/rust/kernel/mm/virt.rs b/rust/kernel/mm/virt.rs index dfe147cafdb3..64a0a47070a8 100644 --- a/rust/kernel/mm/virt.rs +++ b/rust/kernel/mm/virt.rs @@ -14,7 +14,15 @@ //! ensures that you can't, for example, accidentally call a function that= requires holding the //! write lock when you only hold the read lock. =20 -use crate::{bindings, mm::MmWithUser, types::Opaque}; +use crate::{ + bindings, + error::{to_result, Result}, + mm::MmWithUser, + page::Page, + types::Opaque, +}; + +use core::ops::Deref; =20 /// A wrapper for the kernel's `struct vm_area_struct` with read access. /// @@ -124,6 +132,75 @@ pub fn zap_page_range_single(&self, address: usize, si= ze: usize) { ) }; } + + /// If the [`VM_MIXEDMAP`] flag is set, returns a [`VmAreaMixedMap`] t= o this VMA, otherwise + /// returns `None`. + /// + /// This can be used to access methods that require [`VM_MIXEDMAP`] to= be set. + /// + /// [`VM_MIXEDMAP`]: flags::MIXEDMAP + #[inline] + pub fn as_mixedmap_vma(&self) -> Option<&VmAreaMixedMap> { + if self.flags() & flags::MIXEDMAP !=3D 0 { + // SAFETY: We just checked that `VM_MIXEDMAP` is set. All othe= r requirements are + // satisfied by the type invariants of `VmAreaRef`. + Some(unsafe { VmAreaMixedMap::from_raw(self.as_ptr()) }) + } else { + None + } + } +} + +/// A wrapper for the kernel's `struct vm_area_struct` with read access an= d [`VM_MIXEDMAP`] set. +/// +/// It represents an area of virtual memory. +/// +/// This struct is identical to [`VmAreaRef`] except that it must only be = used when the +/// [`VM_MIXEDMAP`] flag is set on the vma. +/// +/// # Invariants +/// +/// The caller must hold the mmap read lock or the vma read lock. The `VM_= MIXEDMAP` flag must be +/// set. +/// +/// [`VM_MIXEDMAP`]: flags::MIXEDMAP +#[repr(transparent)] +pub struct VmAreaMixedMap { + vma: VmAreaRef, +} + +// Make all `VmAreaRef` methods available on `VmAreaMixedMap`. +impl Deref for VmAreaMixedMap { + type Target =3D VmAreaRef; + + #[inline] + fn deref(&self) -> &VmAreaRef { + &self.vma + } +} + +impl VmAreaMixedMap { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is valid for the duration of 'a, an= d that the mmap read lock + /// (or stronger) is held for at least the duration of 'a. The `VM_MIX= EDMAP` flag must be set. + #[inline] + pub unsafe fn from_raw<'a>(vma: *const bindings::vm_area_struct) -> &'= a Self { + // SAFETY: The caller ensures that the invariants are satisfied fo= r the duration of 'a. + unsafe { &*vma.cast() } + } + + /// Maps a single page at the given address within the virtual memory = area. + /// + /// This operation does not take ownership of the page. + #[inline] + pub fn vm_insert_page(&self, address: usize, page: &Page) -> Result { + // SAFETY: By the type invariant of `Self` caller has read access = and has verified that + // `VM_MIXEDMAP` is set. By invariant on `Page` the page has order= 0. + to_result(unsafe { bindings::vm_insert_page(self.as_ptr(), address= , page.as_ptr()) }) + } } =20 /// The integer type used for vma flags. --=20 2.48.1.362.g079036d154-goog From nobody Fri Dec 19 19:14:00 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C132D204C0C for ; Mon, 3 Feb 2025 12:15:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584924; cv=none; b=ngpynVPd6dS2ZlywyURZqWoniTVGvqGIuFAo+VzwMa9MZPj/d8ftZClv2A30mAaTe5+sHvEUE9iQ+4I5eRvTa2XF0BlcKPLF8tW0noYrV3cAtzln8u4eqVg7DuopMjfejZVAg7V0HstN9on0D4H/MZLizWMxd7rolR1nvEi5G7g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584924; c=relaxed/simple; bh=4KqYDSUVevSLVAAHd54nWgHt2kwwb2fi92Kf30lYrZA=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=iKD8RTE+Q/ETMs3AouT+oPzkIT4VfZKEH9z310vqP7yiTy0qJe5pSXfQ8ZBmpbP9Aasfe4my3dVJoThUGGf1d7qP0c4Uzrga3NRb+xWK2+8J+gD0oTSw0ZxyvBVs+OGhNnelc/q7p/fyp0JmM7xrrTJ+Y0No+V51bl7bcTUszt0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=Kr7d0Zpw; arc=none smtp.client-ip=209.85.128.73 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="Kr7d0Zpw" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-4362153dcd6so21013935e9.2 for ; Mon, 03 Feb 2025 04:15:22 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1738584921; x=1739189721; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=agGGNAI6dzqkGe48/M6YrHXUKPC4ck0xMNLxp3OFHVg=; b=Kr7d0ZpwSm0xDobeRnH5OJVkkXqP0jnuOV8ZmUy4yYJmwQJ5YcA+RUOUwmvKIvs6Cu 2f/C5BxqPmxYEiJYDz+gU0OjYpgFQSTaeXE3GHWxchwj0OLWTuf6zJaPPOt3UYwu/ovy 7Nkx8EksY0046Qm4h0sly3UKN9gJcoxF7QGFPswmYKK+ylNor8+4kxrWWLbKngcxReCg 8TqFw2GSwcDo5mm4F1R5Ql4Uqhh0wd4kPj7Rc6zQ7jOfvzYNKHAxM1tDqs1eU1za8gxj pAPymEclGnz3FipZm7s8XOJdVa3Afbv5UVPshjTTAfF7VzT2oCjRVXawqhpEdP9zTuXw 6qww== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738584921; x=1739189721; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=agGGNAI6dzqkGe48/M6YrHXUKPC4ck0xMNLxp3OFHVg=; b=XnbkJnd2S3cl5FQUvJw5xxgX/hq+OShd6w26ySmlTEwyu32ccdClyI4w79cJZMSTEe 6PrbK/oa3OYI3t3FPlChCdK6V571v+QhN6RjtsJwEPQN29YGqXpY0tGRVQL5Ld6NmOhN mPsXJlozulqog65NcaME5HgrcjRD1Lq2ExErvJivwAM4WMXAcKpBCtsAXePN5L/qdkLp jJQ33oP9YsN4ascYV6hBFwcmRkiqS4NO04C0RuymrhCJgATCqFNfV+x9apaUp80XBZAD WFVDeKeYRqM/iyZau3BV3k5TPrRcG+vnSlFnmMof25XV5GdyrQn4wBSK+jSzUc3bs3ig GX7g== X-Forwarded-Encrypted: i=1; AJvYcCUrClWWgJ6JAtjJ8GGWWtAhW2F90p0qyKxdDyvbtXnOe9xnz55dMddDKxAfKfl5NjxsBWJpsDdLFj0IHx8=@vger.kernel.org X-Gm-Message-State: AOJu0YwJNtK2OsZPovL+b6HWQBPGeQt0ljR+Pcub18T5PVsBdNrmdmN5 JK6bDiRHUGqT14PtufaWYOoA5dUksbw5bex6ArV1PYP8RjNzgjUv4RM7SWV05zMd3FM0nTZbDIq SUc6KqruNxOnv+A== X-Google-Smtp-Source: AGHT+IFE3v7o7/Sz3pTYj30D1OhHhtCVRBlS00wbtCjNS9IpojFNCzjRXbNgbN2xRkNUtsN78KvI86exjL/4/EU= X-Received: from wmgg2.prod.google.com ([2002:a05:600d:2:b0:434:a7ab:5eea]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:198b:b0:434:a468:4a57 with SMTP id 5b1f17b1804b1-438dc428740mr163084545e9.26.1738584921017; Mon, 03 Feb 2025 04:15:21 -0800 (PST) Date: Mon, 03 Feb 2025 12:14:39 +0000 In-Reply-To: <20250203-vma-v13-0-2b998268a396@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250203-vma-v13-0-2b998268a396@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4110; i=aliceryhl@google.com; h=from:subject:message-id; bh=4KqYDSUVevSLVAAHd54nWgHt2kwwb2fi92Kf30lYrZA=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnoLNLTSZ879yrBzzjRp+x2lwRObccwq8BnrIWd lf69cZ88PeJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ6CzSwAKCRAEWL7uWMY5 Rm5ND/9PWT1+Eh/dfNIY7NIkFk6+Vbw7I0kgRvqoHU1ZGmP6M+gJ8foSrPKQZqPleKcy7VGrBV+ xj9vOknJIzKNFILLuZE+BQjkcqJckAVx2VnWb+9Ow2q7nDrCa7cC914vve8qWv+6JFMvq6PqIyt 5/J875aL+HC1hE41ROziRZQWZZCwq7KW5n1Jn/CqrXkSfsIrBse+DFUhhp3JNGj55YQ9BzJ5ZdQ LKyXDblmpmH/npz8Sqx0/Ea0UuDEM0+MEYHzZ1XUjzJzwBjoO6eSuQBHyxCppe1CgarpUzRABWj 6f0ZsGQTIJbWK2IzLmYW++OoqjZZBghXwEM/uKfw/L6znFM6f1SMFwVG8OonHtPzKHdSPYZ+cUo 0BJor8b1WM/bhTiUvmWJlAclvh/NlrkoRvPrFHgs6RK3S3G4AC49XeIUzKyjA7h7x5sEV9/c7VX npGgaAfRUCrcrFd2Ba8zf7ctDYAS7JwPrBe3friwZvgJPpHcHs/mJ2Hsy3qQERz1HFBJCAA6+iq SqQ/Co+NxC4gMDJLQhKtexo6uuB4JJvSlDOGKTCkCa/UYE+YYkDozLx9k91TAbPQxTvLQHxLJxP +ZfsAY3m+RZ36I+d4hnDCouPrz0VkieyDtcs1aZ226wR/2fx7WmRm0X/EMFPmtbLonr2DAQm5va E2EB41wG9r8vPDQ== X-Mailer: b4 0.13.0 Message-ID: <20250203-vma-v13-4-2b998268a396@google.com> Subject: [PATCH v13 4/8] mm: rust: add lock_vma_under_rcu From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Currently, the binder driver always uses the mmap lock to make changes to its vma. Because the mmap lock is global to the process, this can involve significant contention. However, the kernel has a feature called per-vma locks, which can significantly reduce contention. For example, you can take a vma lock in parallel with an mmap write lock. This is important because contention on the mmap lock has been a long-term recurring challenge for the Binder driver. This patch introduces support for using `lock_vma_under_rcu` from Rust. The Rust Binder driver will be able to use this to reduce contention on the mmap lock. Acked-by: Lorenzo Stoakes Reviewed-by: Jann Horn Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl --- rust/helpers/mm.c | 5 +++++ rust/kernel/mm.rs | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 65 insertions(+) diff --git a/rust/helpers/mm.c b/rust/helpers/mm.c index 7b72eb065a3e..81b510c96fd2 100644 --- a/rust/helpers/mm.c +++ b/rust/helpers/mm.c @@ -43,3 +43,8 @@ struct vm_area_struct *rust_helper_vma_lookup(struct mm_s= truct *mm, { return vma_lookup(mm, addr); } + +void rust_helper_vma_end_read(struct vm_area_struct *vma) +{ + vma_end_read(vma); +} diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs index bd6ff40f106f..88167c0cbd93 100644 --- a/rust/kernel/mm.rs +++ b/rust/kernel/mm.rs @@ -18,6 +18,7 @@ use core::{ops::Deref, ptr::NonNull}; =20 pub mod virt; +use virt::VmAreaRef; =20 /// A wrapper for the kernel's `struct mm_struct`. /// @@ -160,6 +161,36 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_st= ruct) -> &'a MmWithUser { unsafe { &*ptr.cast() } } =20 + /// Attempt to access a vma using the vma read lock. + /// + /// This is an optimistic trylock operation, so it may fail if there i= s contention. In that + /// case, you should fall back to taking the mmap read lock. + /// + /// When per-vma locks are disabled, this always returns `None`. + #[inline] + pub fn lock_vma_under_rcu(&self, vma_addr: usize) -> Option> { + #[cfg(CONFIG_PER_VMA_LOCK)] + { + // SAFETY: Calling `bindings::lock_vma_under_rcu` is always ok= ay given an mm where + // `mm_users` is non-zero. + let vma =3D unsafe { bindings::lock_vma_under_rcu(self.as_raw(= ), vma_addr) }; + if !vma.is_null() { + return Some(VmaReadGuard { + // SAFETY: If `lock_vma_under_rcu` returns a non-null = ptr, then it points at a + // valid vma. The vma is stable for as long as the vma= read lock is held. + vma: unsafe { VmAreaRef::from_raw(vma) }, + _nts: NotThreadSafe, + }); + } + } + + // Silence warnings about unused variables. + #[cfg(not(CONFIG_PER_VMA_LOCK))] + let _ =3D vma_addr; + + None + } + /// Lock the mmap read lock. #[inline] pub fn mmap_read_lock(&self) -> MmapReadGuard<'_> { @@ -228,3 +259,32 @@ fn drop(&mut self) { unsafe { bindings::mmap_read_unlock(self.mm.as_raw()) }; } } + +/// A guard for the vma read lock. +/// +/// # Invariants +/// +/// This `VmaReadGuard` guard owns the vma read lock. +pub struct VmaReadGuard<'a> { + vma: &'a VmAreaRef, + // `vma_end_read` must be called on the same thread as where the lock = was taken + _nts: NotThreadSafe, +} + +// Make all `VmAreaRef` methods available on `VmaReadGuard`. +impl Deref for VmaReadGuard<'_> { + type Target =3D VmAreaRef; + + #[inline] + fn deref(&self) -> &VmAreaRef { + self.vma + } +} + +impl Drop for VmaReadGuard<'_> { + #[inline] + fn drop(&mut self) { + // SAFETY: We hold the read lock by the type invariants. + unsafe { bindings::vma_end_read(self.vma.as_ptr()) }; + } +} --=20 2.48.1.362.g079036d154-goog From nobody Fri Dec 19 19:14:00 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C144F204C3C for ; Mon, 3 Feb 2025 12:15:24 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584927; cv=none; b=PAehHDB7Z78JC6guF7uV991CToePwU8Sa8BmLlwLF7MaWEp2QFe8QdWpbSiatfGxafXztgn7sLKwIb3r5wKxuRKgH1MGE08G3Cu2YMzlgMX9O77qDhpMbVAZkR1wvo6QbTV5VqzC8201RaGXxRqNV9mcSRJETmLj+8sX5+dFJOE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584927; c=relaxed/simple; bh=ACsxo5nqWOfFud7GSbyxer8izfkYzgJ6Pryyu1sTy1I=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=C6f1UxzTHqZFKgr/L8BTku2SYNOTcEfP7BEoRLJ/qfU8iKPW5d2vd/uDWWsCC6Le7W49TBFqRkgZ6irtUwEEDQR/9Wcz/OLOUUXLr2IhTmzzJiV7/YjyRAbFTVJ4C9C+y/B+hacbS4z0MLMaV0KGFbqEGyIyDCVA0P74DyKH1Xk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=MQJqJ6dE; arc=none smtp.client-ip=209.85.128.73 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="MQJqJ6dE" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-4361b090d23so21079185e9.0 for ; Mon, 03 Feb 2025 04:15:24 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1738584923; x=1739189723; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=6wKw9Mczsy3GQd6f513sHnBPndDv3PUBzx6N+4yBSao=; b=MQJqJ6dExfCsOCrTdiPN/ieZA8/Tz6p63iYsRJeQcHQFLQ45CNCGPEHtBCurzgPiZo D2rfIU6if3WUdhRlpaJ9x7k60rWYssE6QcwYims6cUCt+wWQ9lIiP3BYyKFKLLSUXAvQ qsU/+bpcvktrTZZ5Ux6g4kS8scG18zdvjYtyVBE9+Xq41IhV3No74VZttFYzw6AgcVwY kXaHUry+xUSzUpqXf73znmuWf9QepOJuEaiVVk2uP0i8oyUDwr7qVRCcFZM5DkiAPVPr icNJKXFKVajVcCBQ1tZfT3qr7x4Eg4T8VhaPAsFPhg5zBANmgdSw6IhPLpbhDlv207Yu rn/Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738584923; x=1739189723; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=6wKw9Mczsy3GQd6f513sHnBPndDv3PUBzx6N+4yBSao=; b=m2unuGwwy+rpDdFdh1sUcopjWoXfW8qkbP/kTGklhE77bMrNXWtUz+2KQF/y5yYLmo WbP9zU93p+bvtcXSuoijfl2T6pcI1oNaPsWTX3an9TBihnI4/HG9XZImR8ZmJwzF/rQU 6UzK585e4JayKhhkfzCQfCZsLnydt0CoNYRELvM4hdGRiDt8RJjhupHCQsq0/HBMWdjs wraAFU0r64lw3rKiDgVX9M48KWLK/0AYlazpSfwQDfVyIiV60BcPtJsJc+YrhurEZi4B LyMYO6EcBOiYN7Y582QyvPbqOWu/tm52pZNXQyu7p//rX+bA5s9oxadSbI+muaeGCip6 b8JA== X-Forwarded-Encrypted: i=1; AJvYcCXpRenQsHisjKooLnewxnI3t2a/vzUdGwqqHtfY/LkhPAwFk52HVvjmQngpNf1nMaYEHZcZDKjg3LHlrMQ=@vger.kernel.org X-Gm-Message-State: AOJu0YwCj57icqMOv6csT98AFEP8HjoBgE2PDKpE8TMqi9dgnfaXacy3 /GC5UmzVsE27+tQNdrgogJmbaHcP7aa5fROKuzbof13n4231RVKW6tnCWQDAaDnpa4C3IKUvZmx 27RTI8v8Se2hMRw== X-Google-Smtp-Source: AGHT+IGCacv+6M717acz2TK1/3JVC+EAq8qtKNOoyAR0vAmx15aLEyGhA+8TxKSJtahX9auTkLFiUsit2j20Pw8= X-Received: from wmbay23.prod.google.com ([2002:a05:600c:1e17:b0:434:f299:5633]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3c89:b0:434:a7e7:a1ca with SMTP id 5b1f17b1804b1-438dc40ffaamr172046805e9.20.1738584923172; Mon, 03 Feb 2025 04:15:23 -0800 (PST) Date: Mon, 03 Feb 2025 12:14:40 +0000 In-Reply-To: <20250203-vma-v13-0-2b998268a396@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250203-vma-v13-0-2b998268a396@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3164; i=aliceryhl@google.com; h=from:subject:message-id; bh=ACsxo5nqWOfFud7GSbyxer8izfkYzgJ6Pryyu1sTy1I=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnoLNL4o53AT5ZPycfgR+LVXykH5mUGeHNBJb86 PLfYDNydpeJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ6CzSwAKCRAEWL7uWMY5 RiVkEACBiFS6xSL3eKzx6Ld9VzUml20GBqlKuHKgONIlsSMzAChjH+2qe05ePtG6sKfXIaQR9sZ 6iur0KMizrFbW7s66SOtt+cdm+p6Vnn6Jm+IoPzZqOMNZeAEbr7OHiO74Bg/ebwRHevUyCUQ7g+ 1l9CNSBR4la/6gY0ZZYVN/a9EqbCiwpXB6MppK0IOlZblODbko3NbpbCvd9+EMKcVf8M1pYnNgm rgZPCBrAeH2hb9hh1AhYJmD+iWtkVbFNtgkK8crLJahPfED5mGv3ezMmgO7XcZbsAvZh01mp5hb F+v1g99IzTWvWxgDmujStn9sSgS9lG1wRX0LAtY6MejBJZRZ+EZAnyjKvg42G626oq+Rw+S957Q LcOW34tMJGTKNF3PKuMoBzb6OFeeft3zZ3DBhDsJPG0mIX0YiJbYN5+ZGGO41yjBFghFja2Q+ZI W1BUhho9nvX97vcq/7OTzmWvx+aZ3p3Mlm70hNHAyWxqmhZ3lk5EmOKI9JOLSiLGz8aQiTqyPXy UNcZwUe/jh40mxP+WzrKbG/d+lx2DkhWKl1djkyMfavqjFB2zNF/B62kXjxJlrgEvOe0SCy11NM 2JBX2r9rPWoOIL4kLE5W6/emdo/nTlXLmInzZsmBNXGaTikC3bgIBqBIb/VbRetmQY0g1JXVL1Z 9+Xz+7ht6LLxR/g== X-Mailer: b4 0.13.0 Message-ID: <20250203-vma-v13-5-2b998268a396@google.com> Subject: [PATCH v13 5/8] mm: rust: add mmput_async support From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Adds an MmWithUserAsync type that uses mmput_async when dropped but is otherwise identical to MmWithUser. This has to be done using a separate type because the thing we are changing is the destructor. Rust Binder needs this to avoid a certain deadlock. See commit 9a9ab0d96362 ("binder: fix race between mmput() and do_exit()") for details. It's also needed in the shrinker to avoid cleaning up the mm in the shrinker's context. Reviewed-by: Andreas Hindborg Acked-by: Lorenzo Stoakes (for mm bits) Signed-off-by: Alice Ryhl --- rust/kernel/mm.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs index 88167c0cbd93..1c43e51c9cca 100644 --- a/rust/kernel/mm.rs +++ b/rust/kernel/mm.rs @@ -110,6 +110,48 @@ fn deref(&self) -> &Mm { } } =20 +/// A wrapper for the kernel's `struct mm_struct`. +/// +/// This type is identical to `MmWithUser` except that it uses `mmput_asyn= c` when dropping a +/// refcount. This means that the destructor of `ARef` is= safe to call in atomic +/// context. +/// +/// # Invariants +/// +/// Values of this type are always refcounted using `mmget`. The value of = `mm_users` is non-zero. +#[repr(transparent)] +pub struct MmWithUserAsync { + mm: MmWithUser, +} + +// SAFETY: It is safe to call `mmput_async` on another thread than where `= mmget` was called. +unsafe impl Send for MmWithUserAsync {} +// SAFETY: All methods on `MmWithUserAsync` can be called in parallel from= several threads. +unsafe impl Sync for MmWithUserAsync {} + +// SAFETY: By the type invariants, this type is always refcounted. +unsafe impl AlwaysRefCounted for MmWithUserAsync { + fn inc_ref(&self) { + // SAFETY: The pointer is valid since self is a reference. + unsafe { bindings::mmget(self.as_raw()) }; + } + + unsafe fn dec_ref(obj: NonNull) { + // SAFETY: The caller is giving up their refcount. + unsafe { bindings::mmput_async(obj.cast().as_ptr()) }; + } +} + +// Make all `MmWithUser` methods available on `MmWithUserAsync`. +impl Deref for MmWithUserAsync { + type Target =3D MmWithUser; + + #[inline] + fn deref(&self) -> &MmWithUser { + &self.mm + } +} + // These methods are safe to call even if `mm_users` is zero. impl Mm { /// Returns a raw pointer to the inner `mm_struct`. @@ -161,6 +203,13 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_st= ruct) -> &'a MmWithUser { unsafe { &*ptr.cast() } } =20 + /// Use `mmput_async` when dropping this refcount. + #[inline] + pub fn into_mmput_async(me: ARef) -> ARef= { + // SAFETY: The layouts and invariants are compatible. + unsafe { ARef::from_raw(ARef::into_raw(me).cast()) } + } + /// Attempt to access a vma using the vma read lock. /// /// This is an optimistic trylock operation, so it may fail if there i= s contention. In that --=20 2.48.1.362.g079036d154-goog From nobody Fri Dec 19 19:14:00 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9E6D82046A0 for ; Mon, 3 Feb 2025 12:15:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584928; cv=none; b=hthHXzJbUkXxuiyLL767oe3fehR/K05WFzsxHNlDlv8HEwNIcxQGBHgiXgwjJznb2euteCwgWVfl46T5mXYdhNMiqmnlh/AOGcXE+fgp5DE4SfKEzxTR3zGt7RQshKXorxwk+wPp1QfR3rbY1Rr1VgKLkgqFNT/s1iNOvv654Jc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584928; c=relaxed/simple; bh=10j5HcaR1gvtllAVfcw/qjMyimeHVca5LB2wpNGE6ec=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=gYKHel1Edo+iTGp+E9aop8BCkl+zM4BI9Y0TZ+bpQtK/WHgok7fEMKWo6cCKek5nhM6pKoSFjAPAF3Z9+12bYX1J+kXCVOF/Ty9dbEPCJ4Mz6Un0UEKOrovoXq11FjT+6Na5uddAeJf/K0d4GKtOYPtUA9ITgFEgRbq9s0L0MCU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=OmHVsz6T; arc=none smtp.client-ip=209.85.128.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="OmHVsz6T" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-4361f371908so31264115e9.0 for ; Mon, 03 Feb 2025 04:15:26 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1738584925; x=1739189725; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=XdP0aoyoQaJRQDN9af3Ddles1mdACdpk6p9g2zjPnwA=; b=OmHVsz6T4Dfmj3fZU4mhDG3v2i6aIX3pdIoVFokpkv5bIVbGXqhJFD7Rn10NL9hlrL MWW7gUZOBSjfKpny23p6C4XAfG2w50BjFzkL6lbnLiWlC/GXzadA4oswxp3slo4N7k7j kGGc+Cssh3FmzfWGK/dgRMATTVMbAmzVX1A+cC96zbTLJ3UrVe6hvrXW4lu4viYc/Htb w/WZGK+mUKV1shOze/HcD0xW8SXznftQPGtF2Y1QEqB8x4pvt/1eOUBuQpS6hje5T4u2 x+dMAEzwoLl3zYTEJq/Y1SkvCTkJOkQfKF5JJzpYXfOeYojCcJ27mLt53XtBay1EQoxJ kH/Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738584925; x=1739189725; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=XdP0aoyoQaJRQDN9af3Ddles1mdACdpk6p9g2zjPnwA=; b=A/ETvfyKWCs6CFmIwOm+ccGKHtqQOx/weqniLOTmssbmGrcZe8zrUlGwdX+6oMQfPL ftBgHNJ1pnCtmljvrYSTQgT3ylVa83b+VB1akYH7jA2rRAVHlCNV95Dg8B4hdCV1Q1WP jQA1np7uiB0xBp5o/ddwc548x7TNi9vJ9jIonKZMzqeV47OJLpUm89iVrMG0blPkJ/OX KfzNi5JsTJ7prybqkxX5FUDvcD53U2knLKl20P+rpyfMRnDWrqPklp00Z7YQSyA8PUA5 2RHcVgRGwTN6DiEPVuev6Jx/8+qafb8UXyMEt7FNeQkiuc2peYN1wasA3+87o8a0/JIg AElA== X-Forwarded-Encrypted: i=1; AJvYcCU1AJdr3jodA46gx+dp2f/NCbp4SGSyJPqSuWg3JMG4dk5KS0v8CW0KrQ6qkoErV8WoQOMwZFokQphCAw0=@vger.kernel.org X-Gm-Message-State: AOJu0Yzidtwcj59c+qmC0ilbPunsVRSQ12F6I6WeUafuC/5oX4P7Kzsw tMxAb+DGPAl1AnC9O+nN7CbrrIaXu2IE94lZW77VzTc0OYIMnLIvqcjJkgrmyX4oK2xSHuZIvV5 ZDcCXv4vU4lirwA== X-Google-Smtp-Source: AGHT+IGvdl8whkyeauBYNUqNHQEJqjDbvwD7qj3CFNWEf5tOxMDBlkY+hQX0TS488w7KyLPMULbm3wB/znwxHGc= X-Received: from wmbay13.prod.google.com ([2002:a05:600c:1e0d:b0:434:f1d0:7dc9]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1ca3:b0:438:a240:c55 with SMTP id 5b1f17b1804b1-438e70d1b20mr96862455e9.1.1738584925233; Mon, 03 Feb 2025 04:15:25 -0800 (PST) Date: Mon, 03 Feb 2025 12:14:41 +0000 In-Reply-To: <20250203-vma-v13-0-2b998268a396@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250203-vma-v13-0-2b998268a396@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8625; i=aliceryhl@google.com; h=from:subject:message-id; bh=10j5HcaR1gvtllAVfcw/qjMyimeHVca5LB2wpNGE6ec=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnoLNMGRlshE36N0K5bQLrRASBsrP6ARR+Odgs+ ZRuOZGqHeuJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ6CzTAAKCRAEWL7uWMY5 Ru4uD/wIeJ7LbTTgDF1gzPyLQNw3NUUI95FbT/5jn7qRcfoX1WIuDkkZOzAx1vYs7CH5cQ9owzG Df2TJ9K+7Lnxmo1G8FMuGTYh5EL9q+IY6BVZvKypIv4hcp2Y8CI4BxfLffxKc/5keD7pfrkfA12 QORea0pSlU8TnzABDyWYzGgBGd7pc49b3u58DEEEU1xM6UqVi++Xdme9jaaru5ZK5iGK4Fouk8c LVwgP/uUGgPED0mT8nIKkSY4oENMhC6ITdL3ZdKjIcB7ayb3xKWvLA9N9BNQd2TwawAUO7tcwwd a4YHEQOWCOkx/9Fnw1ajLC7Cq9mfKXSg96PgxyhBb808ZTOXnw+LVM0n2EtqMaK+HH125k8h9L5 DsV5Ip7u9knjAPBBeTiyaSGd6EtGrH7btLvu+vxgJcmbkKQDqPNM38uIcfuzoWV3K+S+o6+nAwa /Hybvrol1Px6fYI0hXEF27zCRnvNxdUyJmNjIMB4oUJ6uuCcrx6g2VpjBUsUUe1xU/CR6YpS2IL IFsf0kRTRS0745iCwntfsNMjQxuaeonqEIXNebvIoZC4CYSMOAUXlsJaYtAFudhrXEWCmWMOCqa 4PuWWNvljKGZJJHiaShbLSBOKTeAvIxcSGkhxMXN287wTwVCttn6nCpJgnyHSAUqwr7rcdhla7m ocD33DZ1yVXouqA== X-Mailer: b4 0.13.0 Message-ID: <20250203-vma-v13-6-2b998268a396@google.com> Subject: [PATCH v13 6/8] mm: rust: add VmAreaNew for f_ops->mmap() From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This type will be used when setting up a new vma in an f_ops->mmap() hook. Using a separate type from VmAreaRef allows us to have a separate set of operations that you are only able to use during the mmap() hook. For example, the VM_MIXEDMAP flag must not be changed after the initial setup that happens during the f_ops->mmap() hook. To avoid setting invalid flag values, the methods for clearing VM_MAYWRITE and similar involve a check of VM_WRITE, and return an error if VM_WRITE is set. Trying to use `try_clear_maywrite` without checking the return value results in a compilation error because the `Result` type is marked #[must_use]. For now, there's only a method for VM_MIXEDMAP and not VM_PFNMAP. When we add a VM_PFNMAP method, we will need some way to prevent you from setting both VM_MIXEDMAP and VM_PFNMAP on the same vma. Acked-by: Lorenzo Stoakes Reviewed-by: Jann Horn Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl --- rust/kernel/mm/virt.rs | 186 +++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 185 insertions(+), 1 deletion(-) diff --git a/rust/kernel/mm/virt.rs b/rust/kernel/mm/virt.rs index 64a0a47070a8..5847fe73db17 100644 --- a/rust/kernel/mm/virt.rs +++ b/rust/kernel/mm/virt.rs @@ -16,7 +16,7 @@ =20 use crate::{ bindings, - error::{to_result, Result}, + error::{code::EINVAL, to_result, Result}, mm::MmWithUser, page::Page, types::Opaque, @@ -203,6 +203,190 @@ pub fn vm_insert_page(&self, address: usize, page: &P= age) -> Result { } } =20 +/// A configuration object for setting up a VMA in an `f_ops->mmap()` hook. +/// +/// The `f_ops->mmap()` hook is called when a new VMA is being created, an= d the hook is able to +/// configure the VMA in various ways to fit the driver that owns it. Usin= g `VmAreaNew` indicates +/// that you are allowed to perform operations on the VMA that can only be= performed before the VMA +/// is fully initialized. +/// +/// # Invariants +/// +/// For the duration of 'a, the referenced vma must be undergoing initiali= zation in an +/// `f_ops->mmap()` hook. +pub struct VmAreaNew { + vma: VmAreaRef, +} + +// Make all `VmAreaRef` methods available on `VmAreaNew`. +impl Deref for VmAreaNew { + type Target =3D VmAreaRef; + + #[inline] + fn deref(&self) -> &VmAreaRef { + &self.vma + } +} + +impl VmAreaNew { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is undergoing initial vma setup for= the duration of 'a. + #[inline] + pub unsafe fn from_raw<'a>(vma: *mut bindings::vm_area_struct) -> &'a = Self { + // SAFETY: The caller ensures that the invariants are satisfied fo= r the duration of 'a. + unsafe { &*vma.cast() } + } + + /// Internal method for updating the vma flags. + /// + /// # Safety + /// + /// This must not be used to set the flags to an invalid value. + #[inline] + unsafe fn update_flags(&self, set: vm_flags_t, unset: vm_flags_t) { + let mut flags =3D self.flags(); + flags |=3D set; + flags &=3D !unset; + + // SAFETY: This is not a data race: the vma is undergoing initial = setup, so it's not yet + // shared. Additionally, `VmAreaNew` is `!Sync`, so it cannot be u= sed to write in parallel. + // The caller promises that this does not set the flags to an inva= lid value. + unsafe { (*self.as_ptr()).__bindgen_anon_2.__vm_flags =3D flags }; + } + + /// Set the `VM_MIXEDMAP` flag on this vma. + /// + /// This enables the vma to contain both `struct page` and pure PFN pa= ges. Returns a reference + /// that can be used to call `vm_insert_page` on the vma. + #[inline] + pub fn set_mixedmap(&self) -> &VmAreaMixedMap { + // SAFETY: We don't yet provide a way to set VM_PFNMAP, so this ca= nnot put the flags in an + // invalid state. + unsafe { self.update_flags(flags::MIXEDMAP, 0) }; + + // SAFETY: We just set `VM_MIXEDMAP` on the vma. + unsafe { VmAreaMixedMap::from_raw(self.vma.as_ptr()) } + } + + /// Set the `VM_IO` flag on this vma. + /// + /// This is used for memory mapped IO and similar. The flag tells othe= r parts of the kernel to + /// avoid looking at the pages. For memory mapped IO this is useful as= accesses to the pages + /// could have side effects. + #[inline] + pub fn set_io(&self) { + // SAFETY: Setting the VM_IO flag is always okay. + unsafe { self.update_flags(flags::IO, 0) }; + } + + /// Set the `VM_DONTEXPAND` flag on this vma. + /// + /// This prevents the vma from being expanded with `mremap()`. + #[inline] + pub fn set_dontexpand(&self) { + // SAFETY: Setting the VM_DONTEXPAND flag is always okay. + unsafe { self.update_flags(flags::DONTEXPAND, 0) }; + } + + /// Set the `VM_DONTCOPY` flag on this vma. + /// + /// This prevents the vma from being copied on fork. This option is on= ly permanent if `VM_IO` + /// is set. + #[inline] + pub fn set_dontcopy(&self) { + // SAFETY: Setting the VM_DONTCOPY flag is always okay. + unsafe { self.update_flags(flags::DONTCOPY, 0) }; + } + + /// Set the `VM_DONTDUMP` flag on this vma. + /// + /// This prevents the vma from being included in core dumps. This opti= on is only permanent if + /// `VM_IO` is set. + #[inline] + pub fn set_dontdump(&self) { + // SAFETY: Setting the VM_DONTDUMP flag is always okay. + unsafe { self.update_flags(flags::DONTDUMP, 0) }; + } + + /// Returns whether `VM_READ` is set. + /// + /// This flag indicates whether userspace is mapping this vma as reada= ble. + #[inline] + pub fn readable(&self) -> bool { + (self.flags() & flags::READ) !=3D 0 + } + + /// Try to clear the `VM_MAYREAD` flag, failing if `VM_READ` is set. + /// + /// This flag indicates whether userspace is allowed to make this vma = readable with + /// `mprotect()`. + /// + /// Note that this operation is irreversible. Once `VM_MAYREAD` has be= en cleared, it can never + /// be set again. + #[inline] + pub fn try_clear_mayread(&self) -> Result { + if self.readable() { + return Err(EINVAL); + } + // SAFETY: Clearing `VM_MAYREAD` is okay when `VM_READ` is not set. + unsafe { self.update_flags(0, flags::MAYREAD) }; + Ok(()) + } + + /// Returns whether `VM_WRITE` is set. + /// + /// This flag indicates whether userspace is mapping this vma as writa= ble. + #[inline] + pub fn writable(&self) -> bool { + (self.flags() & flags::WRITE) !=3D 0 + } + + /// Try to clear the `VM_MAYWRITE` flag, failing if `VM_WRITE` is set. + /// + /// This flag indicates whether userspace is allowed to make this vma = writable with + /// `mprotect()`. + /// + /// Note that this operation is irreversible. Once `VM_MAYWRITE` has b= een cleared, it can never + /// be set again. + #[inline] + pub fn try_clear_maywrite(&self) -> Result { + if self.writable() { + return Err(EINVAL); + } + // SAFETY: Clearing `VM_MAYWRITE` is okay when `VM_WRITE` is not s= et. + unsafe { self.update_flags(0, flags::MAYWRITE) }; + Ok(()) + } + + /// Returns whether `VM_EXEC` is set. + /// + /// This flag indicates whether userspace is mapping this vma as execu= table. + #[inline] + pub fn executable(&self) -> bool { + (self.flags() & flags::EXEC) !=3D 0 + } + + /// Try to clear the `VM_MAYEXEC` flag, failing if `VM_EXEC` is set. + /// + /// This flag indicates whether userspace is allowed to make this vma = executable with + /// `mprotect()`. + /// + /// Note that this operation is irreversible. Once `VM_MAYEXEC` has be= en cleared, it can never + /// be set again. + #[inline] + pub fn try_clear_mayexec(&self) -> Result { + if self.executable() { + return Err(EINVAL); + } + // SAFETY: Clearing `VM_MAYEXEC` is okay when `VM_EXEC` is not set. + unsafe { self.update_flags(0, flags::MAYEXEC) }; + Ok(()) + } +} + /// The integer type used for vma flags. #[doc(inline)] pub use bindings::vm_flags_t; --=20 2.48.1.362.g079036d154-goog From nobody Fri Dec 19 19:14:00 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2800C204C0C for ; Mon, 3 Feb 2025 12:15:28 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584931; cv=none; b=bK+m4zlVdUQxzyW3fmiQO/WyXQO1L/drGrrH8uWDn+klYLDKf7AqVGKkYO930creFkLGqwvopt/SbHzEHUGTRbwpjKXAxXER3P68pJb+tXvq/S3OffLFvYMEr6ay4MW03vnWD+ey4B8wMRNhHgUmDqdr4rR9MgBQ5WTFdrH//8o= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584931; c=relaxed/simple; bh=lOxibc3nuZLQi8BiPbjAzGGX8r7u+1l6+AedXlWTNQY=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=loJGd1ltnhgGTmQyEOIHX/2yNuzR1xvPcYhH6bGe0ZI8BlFoHQDdkyAKa0MhpG1Ctyldb9Qa/1IDlwZ3CPZt3BJ7rQhEFka6Jgxm6RD7SnKbxV+xquENT0CWUoJsulWhgU0DOaLMlTIXDls3dKo5OUcH2xMgcbK9VARQGIsRuaI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=U32EsQZ8; arc=none smtp.client-ip=209.85.128.73 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="U32EsQZ8" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43626224274so22353565e9.0 for ; Mon, 03 Feb 2025 04:15:28 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1738584927; x=1739189727; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=L5YAFJcoe9aWjiMWck/T3XsvxbQLU+eGKUV8qsjc/6o=; b=U32EsQZ8DM9DkrD1obqlLmfSI6gR2K1406+GmI8XfOwZtdM01fkEpGvMFEwtusdk2/ 9PISjVNhAAkosSU6CQlxLM3S4cGWrUTkKU5HZ5nauauoXjS+GqVSz4YeNOKV3VT/whMO m42uqLfX38uLJH9dVX2Nnbj3b/MIsVm64Py6tD8MF0VNRTaA+rbS6vczma3E6OjNF4q9 65JDDRA4/YZ5FeXzgxySnW1tPjvaAeQVvnltz7FXpCQ5AJWjlw6PA80i9JvotVeROxdq F/aSRUYheX7bCdAIvSMWs0NITPVnF5nF7xaT6cAX3VB6fSrddDTUL6bWGIhXJovhZpAG Z5UA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738584927; x=1739189727; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=L5YAFJcoe9aWjiMWck/T3XsvxbQLU+eGKUV8qsjc/6o=; b=Bp56/diOolsHW270OkuLIUGbwIsMGSpBftHqR5oM3xnljJgZ4w6NDEc+wN9tz8aani FTWLv1KkdWDe++jnTkQTiJ5tR/NfPiNFUVD5tpIAjEMbKTPTaxAPVSEpDvKyUfeV2kRD 5uMJDgCMywGWnl+mqzI7i3qApR1AemGsCxTbq4Na6IRSYF7dW6yaoQo7medvrzMFZcka sWy0oFmt9CtddLawXiazdnqdydEBYxUzuV1yG500vn6bZhBUzG2ODl3SXqJG88NreeKy CcwzysWwb48UAlkLm3fb7OaA7Qgtt3CkGs+dWatap4mkjVVu+Z1+/SCbYkwt+VkQR5PP 7AEA== X-Forwarded-Encrypted: i=1; AJvYcCWoa+u88p0OzIcaeOUc+wzHzZmFm44WUyhFkOJWV6bBaNEq4Gbc7h/Pjthc/dTmxK56kgOzDt7S+ygxq28=@vger.kernel.org X-Gm-Message-State: AOJu0YxOFQ5cWdiyq0xEOJgfYxSh5/Bpt/xzjXUUgpsgOC+a1rVIG1wF 323TrvIZaLk845+7FhYvpJu1ifSlER1eh/2qu/W0dD/ibZEiuOFu9s0BDAHWagZm/vNUYdVUic5 e9BRMddx112RV7w== X-Google-Smtp-Source: AGHT+IGRpqHAm8e8m8G19+Ggf+AlSBBiph12yce/Z46WS7aebCTZGTPSeXVYEmtSCMFpqP+rea7lVywnd8EwYTc= X-Received: from wmdd16.prod.google.com ([2002:a05:600c:a210:b0:434:f9da:44af]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1913:b0:434:ff9d:a3a1 with SMTP id 5b1f17b1804b1-438dc42f5ddmr193300145e9.2.1738584927497; Mon, 03 Feb 2025 04:15:27 -0800 (PST) Date: Mon, 03 Feb 2025 12:14:42 +0000 In-Reply-To: <20250203-vma-v13-0-2b998268a396@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250203-vma-v13-0-2b998268a396@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3871; i=aliceryhl@google.com; h=from:subject:message-id; bh=lOxibc3nuZLQi8BiPbjAzGGX8r7u+1l6+AedXlWTNQY=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnoLNNqHQ7JzZkQoXiERXxGW2E5JDKpE49JYLMB Rby6/PrLUOJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ6CzTQAKCRAEWL7uWMY5 RjLXD/95wijzWi48bnFkANglJrcsl0MrU+pyM7kJiSBNfVa3+Ct2A/y+4U1IlJACvWcFHqWajuC mL++v1+KfsbIKUcEfClZDikejXKtig8h2WFaYIQm/E6CYWyJ5grXcti+YF1/e/Ymydu2ZZ5bLZl KVNGyd0+Lp5tdcZ9T701aTiUnvu8O40oFHccZOQBH3oGo7eX7cGxvJtZKW4JUFLCKxWyfT7nbWG oFekPegNJE14QqSjpE3xPaHt/yip9D/Pj/IRd3hO9/C48NCSOJiSDMIExCktPYcoa8tK9iw3wW9 bjaTKYOY43WY6/QDxf9VhyMgCN+vL5VdIDWhlgbzUHPL5/XbQm/QjbtiNTSEPbcHLXBMOWTxMFt MX8mvoeWXJfUzM75hnM7+fVstYgWUNHecMpyfJytxrsBHvEoFaMxzf7WUPrsdtB9drPHSWXYveX aSYxWcLTDVwFHzjjFlWfmh+f40y92zSVPrSfosNfkqUSboZes0qIppDnhDEz0W17izMWFHv2Gxa F68fFyj86L6y+A9PxCnGfnge/0TFRWo1URk3iliqqMQn8PJPJaN2UeU+vAi6tfi9Nf5V+tvKBA6 uMul2VWCKKdy+/rCiIL4dXSTCpU3IQUl3ISSgKnZ9XRlFG1SqxF+m4iqFi+1PHBL9S9S0TbZUjx QyWDwCPrjbpztOg== X-Mailer: b4 0.13.0 Message-ID: <20250203-vma-v13-7-2b998268a396@google.com> Subject: [PATCH v13 7/8] rust: miscdevice: add mmap support From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Add the ability to write a file_operations->mmap hook in Rust when using the miscdevice abstraction. The `vma` argument to the `mmap` hook uses the `VmAreaNew` type from the previous commit; this type provides the correct set of operations for a file_operations->mmap hook. Acked-by: Greg Kroah-Hartman Acked-by: Lorenzo Stoakes Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl --- rust/kernel/miscdevice.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index e14433b2ab9d..97b2384f0816 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -14,6 +14,7 @@ error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR}, ffi::{c_int, c_long, c_uint, c_ulong}, fs::File, + mm::virt::VmAreaNew, prelude::*, seq_file::SeqFile, str::CStr, @@ -119,6 +120,22 @@ fn release(device: Self::Ptr, _file: &File) { drop(device); } =20 + /// Handle for mmap. + /// + /// This function is invoked when a user space process invokes the `mm= ap` system call on + /// `file`. The function is a callback that is part of the VMA initial= izer. The kernel will do + /// initial setup of the VMA before calling this function. The functio= n can then interact with + /// the VMA initialization by calling methods of `vma`. If the functio= n does not return an + /// error, the kernel will complete initialization of the VMA accordin= g to the properties of + /// `vma`. + fn mmap( + _device: ::Borrowed<'_>, + _file: &File, + _vma: &VmAreaNew, + ) -> Result { + kernel::build_error!(VTABLE_DEFAULT_ERROR) + } + /// Handler for ioctls. /// /// The `cmd` argument is usually manipulated using the utilties in [`= kernel::ioctl`]. @@ -176,6 +193,7 @@ impl VtableHelper { const VTABLE: bindings::file_operations =3D bindings::file_operati= ons { open: Some(fops_open::), release: Some(fops_release::), + mmap: maybe_fn(T::HAS_MMAP, fops_mmap::), unlocked_ioctl: maybe_fn(T::HAS_IOCTL, fops_ioctl::), #[cfg(CONFIG_COMPAT)] compat_ioctl: if T::HAS_COMPAT_IOCTL { @@ -257,6 +275,32 @@ impl VtableHelper { 0 } =20 +/// # Safety +/// +/// `file` must be a valid file that is associated with a `MiscDeviceRegis= tration`. +/// `vma` must be a vma that is currently being mmap'ed with this file. +unsafe extern "C" fn fops_mmap( + file: *mut bindings::file, + vma: *mut bindings::vm_area_struct, +) -> c_int { + // SAFETY: The mmap call of a file can access the private data. + let private =3D unsafe { (*file).private_data }; + // SAFETY: This is a Rust Miscdevice, so we call `into_foreign` in `op= en` and `from_foreign` in + // `release`, and `fops_mmap` is guaranteed to be called between those= two operations. + let device =3D unsafe { ::borrow(private) }; + // SAFETY: The caller provides a vma that is undergoing initial VMA se= tup. + let area =3D unsafe { VmAreaNew::from_raw(vma) }; + // SAFETY: + // * The file is valid for the duration of this call. + // * There is no active fdget_pos region on the file on this thread. + let file =3D unsafe { File::from_raw_file(file) }; + + match T::mmap(device, file, area) { + Ok(()) =3D> 0, + Err(err) =3D> err.to_errno(), + } +} + /// # Safety /// /// `file` must be a valid file that is associated with a `MiscDeviceRegis= tration`. --=20 2.48.1.362.g079036d154-goog From nobody Fri Dec 19 19:14:00 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6763C20550E for ; Mon, 3 Feb 2025 12:15:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584933; cv=none; b=iv6FGqkSR0ngooRujte5I1aiiNbyn+wr7mPhJTpuQkA8NPfqEKwgZiN7a013gyI2mvfh4KFvq4RHIbsc4XvJeIbIn5cY4XjvvXN+as92eLHORIY9nZ03TFvkqe/vPy0r9W4PHht8f/IsXuv42QxKZd3VhYB0p6hI1nVjvHLwTtg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738584933; c=relaxed/simple; bh=jIwDE0aeb3Nk4rOdUKVsAyevX0pk+IVA+2Vzq2nuP6o=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=tecDqI5bKeMaxcqX68k4ATTR2c/77d+y7k6M/45v91H7lyhx6RwP/v6+frj7qo3ipw8rPrIitygcMMSKCSDTaB87MTl4hQ7/QBVpgWcTb8fCJDoCExJQx37Ti30zUM8k47x1XtYji541T1zw8GNnu8iZU0YLsmL8c3nGgjoBVEc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=OuNDMJp2; arc=none smtp.client-ip=209.85.128.73 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="OuNDMJp2" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43626224274so22353835e9.0 for ; Mon, 03 Feb 2025 04:15:31 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1738584929; x=1739189729; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=tuxJJmxGW3goIRW/OgstRWONs45CMDMWq5FHoZQDXkU=; b=OuNDMJp2iGdUb7JsdH9LJL8J1sVsUNYi4jGQwdJErQyHOVj27dKPYJbpKSgl8x9Bkm 9AkVR0i9e8WEls3sEZHnFXwUDhtFOPYpNXNm7Ydg5wCL2sUtJoHFmsB2NgftgJCMynuy GdfKumLPBXn5B5nJTtixzHXJmtH0mZXVebmbyQJ/h5O0U/m4TfBrkImQRE72VNC8wrZl StMTKENijzNF7WqHuVuDowX7l5oREHGoiH0tVaazylVuAXmS6Vi31CvqlrjnHf+p6kOO 5yyzctOE7VWcP3oCroNABHLOGOcan45KzaBzTZ11QkOa2Ddw/XcZU9WF+H+0+C2QPNKj 08Aw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738584929; x=1739189729; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=tuxJJmxGW3goIRW/OgstRWONs45CMDMWq5FHoZQDXkU=; b=keyAsdnXMqnI3PDY7nezoKWwz2Wt144UyMc/ThFMpO/eeQe0JJVR+ydiVb/TW18q4p LIXLnMSdaN8O1NSWdXW+hvvqIGu7AEdGCIZnRoaRImFEznPGoUT/X1/YcIKv2akCunww Rgt0/kkvjijAt0GPXNaiXidO+PNPLjbUpXpGQXQrPsnkwsIdLUAodm9f9+lcdxvs3mlH NTnuFodsZLUVxnHqy+Vj1xuJybCk5RY5OxTb7iuqLU4D33jC56qhxcnNj6X4IyumIWiZ 8yfQF082GcUBuPlojO4jamwl0XJPbLCgx3+YFOaPZEkwkTdglButI1ezPoGpzRtPftsH P1mg== X-Forwarded-Encrypted: i=1; AJvYcCVaNd4h1Zh9KZqjZK2W4aK78PahtzOItozTRFrXtLFl0r5RpxYHkGwYN1sm0fcK31L5Dpxt6SKcx8YyX8g=@vger.kernel.org X-Gm-Message-State: AOJu0YyBHowzJFfxfVOhtkhFn+1Ej988uWe7s6S4/ogOWb10n6czqt2b 4Si8WBWHapu+mu7JlDW9QFZ593KCfTzD7Zx0d+99G7e63yPu2meyBP55jyj1KIRGa3BVnI9uuIw yoSI9+a5oMupbew== X-Google-Smtp-Source: AGHT+IEtylH7bvRes7JMpNdtE64LFjbyAC2YtB7jplur6VQCzvF0U0vbh8ldT62ynC0a//US8WEfo3Aje7QGZ3Q= X-Received: from wmbhc24.prod.google.com ([2002:a05:600c:8718:b0:436:6fa7:621]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:4e14:b0:438:a214:52f4 with SMTP id 5b1f17b1804b1-438dc428c0amr167641675e9.25.1738584929779; Mon, 03 Feb 2025 04:15:29 -0800 (PST) Date: Mon, 03 Feb 2025 12:14:43 +0000 In-Reply-To: <20250203-vma-v13-0-2b998268a396@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250203-vma-v13-0-2b998268a396@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=18134; i=aliceryhl@google.com; h=from:subject:message-id; bh=jIwDE0aeb3Nk4rOdUKVsAyevX0pk+IVA+2Vzq2nuP6o=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnoLNNeqAtXmMLVlY0CKjjlEfSuZg8MJHG97rok y5F/UZucyKJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ6CzTQAKCRAEWL7uWMY5 RjDXEACFNur39ucawOYdqsVf0qKC51ENYeHIbq6oH6d1K+wE1T+QGaXNS4KRzfhdvNcT1iqIBGB 1naDOr2c79uEmPeI2jbZE/kvmTgCm7zeUvU0VvdSmq3G52t70d6xodB3iEEu3J8EM9tMLpesY/B +YWmKpSLtDxhLQbZi4iGuJLkcJCUatqUPbnl4XgXDuO1zJl/KNXa0eTvsCza17FLNbmcboLkOuB N0hMY1nX7ubbATe1SMSapf0vKX9q6Sm3PHCfQATwrA6obXVCyi0VDl7S19H/iUk6wRRuXIvpotD lA9FCajNAKrLlcSfVczW5AZU//d52G03jhLSVyjnQ4K9LQLzZe0VfBiLLqeQxckraxr8UkpAJX6 SZtg+7W5nFDOhw4Vd/yB1qBH+7ts6VHfoLyjQABIGO92T4srgZqnpjgDD9eFLScaPxNKEZbNPzU GOScRm348hc9Bl64WlCej0XqnY7HUURRIrEKnGOc2g7vschV3sgf4UMAB0bwP5GuH0SNm8r6Zca 2V4ZGRSgygTtp5T5MJ33i9mB0TxeFiSUNBurnGapesi3y0IwI/iludS9kVwXh4+31Qev2ElRMmx Ks74GDM0El+394QF6hte28v7yoJu93eCRHe2zklBMaVlLjTxf0+a96hXaPqnrs7CV80iIVLQo5E SEl0y3MRD8KGT0A== X-Mailer: b4 0.13.0 Message-ID: <20250203-vma-v13-8-2b998268a396@google.com> Subject: [PATCH v13 8/8] task: rust: rework how current is accessed From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Introduce a new type called `CurrentTask` that lets you perform various operations that are only safe on the `current` task. Use the new type to provide a way to access the current mm without incrementing its refcount. With this change, you can write stuff such as let vma =3D current!().mm().lock_vma_under_rcu(addr); without incrementing any refcounts. This replaces the existing abstractions for accessing the current pid namespace. With the old approach, every field access to current involves both a macro and a unsafe helper function. The new approach simplifies that to a single safe function on the `CurrentTask` type. This makes it less heavy-weight to add additional current accessors in the future. That said, creating a `CurrentTask` type like the one in this patch requires that we are careful to ensure that it cannot escape the current task or otherwise access things after they are freed. To do this, I declared that it cannot escape the current "task context" where I defined a "task context" as essentially the region in which `current` remains unchanged. So e.g., release_task() or begin_new_exec() would leave the task context. If a userspace thread returns to userspace and later makes another syscall, then I consider the two syscalls to be different task contexts. This allows values stored in that task to be modified between syscalls, even if they're guaranteed to be immutable during a syscall. Ensuring correctness of `CurrentTask` is slightly tricky if we also want the ability to have a safe `kthread_use_mm()` implementation in Rust. To support that safely, there are two patterns we need to ensure are safe: // Case 1: current!() called inside the scope. let mm; kthread_use_mm(some_mm, || { mm =3D current!().mm(); }); drop(some_mm); mm.do_something(); // UAF and: // Case 2: current!() called before the scope. let mm; let task =3D current!(); kthread_use_mm(some_mm, || { mm =3D task.mm(); }); drop(some_mm); mm.do_something(); // UAF The existing `current!()` abstraction already natively prevents the first case: The `&CurrentTask` would be tied to the inner scope, so the borrow-checker ensures that no reference derived from it can escape the scope. Fixing the second case is a bit more tricky. The solution is to essentially pretend that the contents of the scope execute on an different thread, which means that only thread-safe types can cross the boundary. Since `CurrentTask` is marked `NotThreadSafe`, attempts to move it to another thread will fail, and this includes our fake pretend thread boundary. This has the disadvantage that other types that aren't thread-safe for reasons unrelated to `current` also cannot be moved across the `kthread_use_mm()` boundary. I consider this an acceptable tradeoff. Reviewed-by: Boqun Feng Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl --- rust/kernel/task.rs | 247 +++++++++++++++++++++++++++---------------------= ---- 1 file changed, 129 insertions(+), 118 deletions(-) diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs index 07bc22a7645c..0b6cb9a83a2e 100644 --- a/rust/kernel/task.rs +++ b/rust/kernel/task.rs @@ -7,6 +7,7 @@ use crate::{ bindings, ffi::{c_int, c_long, c_uint}, + mm::MmWithUser, pid_namespace::PidNamespace, types::{ARef, NotThreadSafe, Opaque}, }; @@ -31,22 +32,20 @@ #[macro_export] macro_rules! current { () =3D> { - // SAFETY: Deref + addr-of below create a temporary `TaskRef` that= cannot outlive the - // caller. + // SAFETY: This expression creates a temporary value that is dropp= ed at the end of the + // caller's scope. The following mechanisms ensure that the result= ing `&CurrentTask` cannot + // leave current task context: + // + // * To return to userspace, the caller must leave the current sco= pe. + // * Operations such as `begin_new_exec()` are necessarily unsafe = and the caller of + // `begin_new_exec()` is responsible for safety. + // * Rust abstractions for things such as a `kthread_use_mm()` sco= pe must require the + // closure to be `Send`, so the `NotThreadSafe` field of `Curren= tTask` ensures that the + // `&CurrentTask` cannot cross the scope in either direction. unsafe { &*$crate::task::Task::current() } }; } =20 -/// Returns the currently running task's pid namespace. -#[macro_export] -macro_rules! current_pid_ns { - () =3D> { - // SAFETY: Deref + addr-of below create a temporary `PidNamespaceR= ef` that cannot outlive - // the caller. - unsafe { &*$crate::task::Task::current_pid_ns() } - }; -} - /// Wraps the kernel's `struct task_struct`. /// /// # Invariants @@ -85,7 +84,7 @@ macro_rules! current_pid_ns { /// impl State { /// fn new() -> Self { /// Self { -/// creator: current!().into(), +/// creator: ARef::from(&**current!()), /// index: 0, /// } /// } @@ -105,6 +104,44 @@ unsafe impl Send for Task {} // synchronised by C code (e.g., `signal_pending`). unsafe impl Sync for Task {} =20 +/// Represents the [`Task`] in the `current` global. +/// +/// This type exists to provide more efficient operations that are only va= lid on the current task. +/// For example, to retrieve the pid-namespace of a task, you must use rcu= protection unless it is +/// the current task. +/// +/// # Invariants +/// +/// Each value of this type must only be accessed from the task context it= was created within. +/// +/// Of course, every thread is in a different task context, but for the pu= rposes of this invariant, +/// these operations also permanently leave the task context: +/// +/// * Returning to userspace from system call context. +/// * Calling `release_task()`. +/// * Calling `begin_new_exec()` in a binary format loader. +/// +/// Other operations temporarily create a new sub-context: +/// +/// * Calling `kthread_use_mm()` creates a new context, and `kthread_unuse= _mm()` returns to the +/// old context. +/// +/// This means that a `CurrentTask` obtained before a `kthread_use_mm()` c= all may be used again +/// once `kthread_unuse_mm()` is called, but it must not be used between t= hese two calls. +/// Conversely, a `CurrentTask` obtained between a `kthread_use_mm()`/`kth= read_unuse_mm()` pair +/// must not be used after `kthread_unuse_mm()`. +#[repr(transparent)] +pub struct CurrentTask(Task, NotThreadSafe); + +// Make all `Task` methods available on `CurrentTask`. +impl Deref for CurrentTask { + type Target =3D Task; + #[inline] + fn deref(&self) -> &Task { + &self.0 + } +} + /// The type of process identifiers (PIDs). type Pid =3D bindings::pid_t; =20 @@ -131,119 +168,29 @@ pub fn current_raw() -> *mut bindings::task_struct { /// /// # Safety /// - /// Callers must ensure that the returned object doesn't outlive the c= urrent task/thread. - pub unsafe fn current() -> impl Deref { - struct TaskRef<'a> { - task: &'a Task, - _not_send: NotThreadSafe, + /// Callers must ensure that the returned object is only used to acces= s a [`CurrentTask`] + /// within the task context that was active when this function was cal= led. For more details, + /// see the invariants section for [`CurrentTask`]. + pub unsafe fn current() -> impl Deref { + struct TaskRef { + task: *const CurrentTask, } =20 - impl Deref for TaskRef<'_> { - type Target =3D Task; + impl Deref for TaskRef { + type Target =3D CurrentTask; =20 fn deref(&self) -> &Self::Target { - self.task + // SAFETY: The returned reference borrows from this `TaskR= ef`, so it cannot outlive + // the `TaskRef`, which the caller of `Task::current()` ha= s promised will not + // outlive the task/thread for which `self.task` is the `c= urrent` pointer. Thus, it + // is okay to return a `CurrentTask` reference here. + unsafe { &*self.task } } } =20 - let current =3D Task::current_raw(); TaskRef { - // SAFETY: If the current thread is still running, the current= task is valid. Given - // that `TaskRef` is not `Send`, we know it cannot be transfer= red to another thread - // (where it could potentially outlive the caller). - task: unsafe { &*current.cast() }, - _not_send: NotThreadSafe, - } - } - - /// Returns a PidNamespace reference for the currently executing task'= s/thread's pid namespace. - /// - /// This function can be used to create an unbounded lifetime by e.g.,= storing the returned - /// PidNamespace in a global variable which would be a bug. So the rec= ommended way to get the - /// current task's/thread's pid namespace is to use the [`current_pid_= ns`] macro because it is - /// safe. - /// - /// # Safety - /// - /// Callers must ensure that the returned object doesn't outlive the c= urrent task/thread. - pub unsafe fn current_pid_ns() -> impl Deref { - struct PidNamespaceRef<'a> { - task: &'a PidNamespace, - _not_send: NotThreadSafe, - } - - impl Deref for PidNamespaceRef<'_> { - type Target =3D PidNamespace; - - fn deref(&self) -> &Self::Target { - self.task - } - } - - // The lifetime of `PidNamespace` is bound to `Task` and `struct p= id`. - // - // The `PidNamespace` of a `Task` doesn't ever change once the `Ta= sk` is alive. A - // `unshare(CLONE_NEWPID)` or `setns(fd_pidns/pidfd, CLONE_NEWPID)= ` will not have an effect - // on the calling `Task`'s pid namespace. It will only effect the = pid namespace of children - // created by the calling `Task`. This invariant guarantees that a= fter having acquired a - // reference to a `Task`'s pid namespace it will remain unchanged. - // - // When a task has exited and been reaped `release_task()` will be= called. This will set - // the `PidNamespace` of the task to `NULL`. So retrieving the `Pi= dNamespace` of a task - // that is dead will return `NULL`. Note, that neither holding the= RCU lock nor holding a - // referencing count to - // the `Task` will prevent `release_task()` being called. - // - // In order to retrieve the `PidNamespace` of a `Task` the `task_a= ctive_pid_ns()` function - // can be used. There are two cases to consider: - // - // (1) retrieving the `PidNamespace` of the `current` task - // (2) retrieving the `PidNamespace` of a non-`current` task - // - // From system call context retrieving the `PidNamespace` for case= (1) is always safe and - // requires neither RCU locking nor a reference count to be held. = Retrieving the - // `PidNamespace` after `release_task()` for current will return `= NULL` but no codepath - // like that is exposed to Rust. - // - // Retrieving the `PidNamespace` from system call context for (2) = requires RCU protection. - // Accessing `PidNamespace` outside of RCU protection requires a r= eference count that - // must've been acquired while holding the RCU lock. Note that acc= essing a non-`current` - // task means `NULL` can be returned as the non-`current` task cou= ld have already passed - // through `release_task()`. - // - // To retrieve (1) the `current_pid_ns!()` macro should be used wh= ich ensure that the - // returned `PidNamespace` cannot outlive the calling scope. The a= ssociated - // `current_pid_ns()` function should not be called directly as it= could be abused to - // created an unbounded lifetime for `PidNamespace`. The `current_= pid_ns!()` macro allows - // Rust to handle the common case of accessing `current`'s `PidNam= espace` without RCU - // protection and without having to acquire a reference count. - // - // For (2) the `task_get_pid_ns()` method must be used. This will = always acquire a - // reference on `PidNamespace` and will return an `Option` to forc= e the caller to - // explicitly handle the case where `PidNamespace` is `None`, some= thing that tends to be - // forgotten when doing the equivalent operation in `C`. Missing R= CU primitives make it - // difficult to perform operations that are otherwise safe without= holding a reference - // count as long as RCU protection is guaranteed. But it is not im= portant currently. But we - // do want it in the future. - // - // Note for (2) the required RCU protection around calling `task_a= ctive_pid_ns()` - // synchronizes against putting the last reference of the associat= ed `struct pid` of - // `task->thread_pid`. The `struct pid` stored in that field is us= ed to retrieve the - // `PidNamespace` of the caller. When `release_task()` is called `= task->thread_pid` will be - // `NULL`ed and `put_pid()` on said `struct pid` will be delayed i= n `free_pid()` via - // `call_rcu()` allowing everyone with an RCU protected access to = the `struct pid` acquired - // from `task->thread_pid` to finish. - // - // SAFETY: The current task's pid namespace is valid as long as th= e current task is running. - let pidns =3D unsafe { bindings::task_active_pid_ns(Task::current_= raw()) }; - PidNamespaceRef { - // SAFETY: If the current thread is still running, the current= task and its associated - // pid namespace are valid. `PidNamespaceRef` is not `Send`, s= o we know it cannot be - // transferred to another thread (where it could potentially o= utlive the current - // `Task`). The caller needs to ensure that the PidNamespaceRe= f doesn't outlive the - // current task/thread. - task: unsafe { PidNamespace::from_ptr(pidns) }, - _not_send: NotThreadSafe, + // CAST: The layout of `struct task_struct` and `CurrentTask` = is identical. + task: Task::current_raw().cast(), } } =20 @@ -326,6 +273,70 @@ pub fn wake_up(&self) { } } =20 +impl CurrentTask { + /// Access the address space of the current task. + /// + /// This function does not touch the refcount of the mm. + #[inline] + pub fn mm(&self) -> Option<&MmWithUser> { + // SAFETY: The `mm` field of `current` is not modified from other = threads, so reading it is + // not a data race. + let mm =3D unsafe { (*self.as_ptr()).mm }; + + if mm.is_null() { + return None; + } + + // SAFETY: If `current->mm` is non-null, then it references a vali= d mm with a non-zero + // value of `mm_users`. Furthermore, the returned `&MmWithUser` bo= rrows from this + // `CurrentTask`, so it cannot escape the scope in which the curre= nt pointer was obtained. + // + // This is safe even if `kthread_use_mm()`/`kthread_unuse_mm()` ar= e used. There are two + // relevant cases: + // * If the `&CurrentTask` was created before `kthread_use_mm()`, = then it cannot be + // accessed during the `kthread_use_mm()`/`kthread_unuse_mm()` s= cope due to the + // `NotThreadSafe` field of `CurrentTask`. + // * If the `&CurrentTask` was created within a `kthread_use_mm()`= /`kthread_unuse_mm()` + // scope, then the `&CurrentTask` cannot escape that scope, so t= he returned `&MmWithUser` + // also cannot escape that scope. + // In either case, it's not possible to read `current->mm` and kee= p using it after the + // scope is ended with `kthread_unuse_mm()`. + Some(unsafe { MmWithUser::from_raw(mm) }) + } + + /// Access the pid namespace of the current task. + /// + /// This function does not touch the refcount of the namespace or use = RCU protection. + /// + /// To access the pid namespace of another task, see [`Task::get_pid_n= s`]. + #[doc(alias =3D "task_active_pid_ns")] + #[inline] + pub fn active_pid_ns(&self) -> Option<&PidNamespace> { + // SAFETY: It is safe to call `task_active_pid_ns` without RCU pro= tection when calling it + // on the current task. + let active_ns =3D unsafe { bindings::task_active_pid_ns(self.as_pt= r()) }; + + if active_ns.is_null() { + return None; + } + + // The lifetime of `PidNamespace` is bound to `Task` and `struct p= id`. + // + // The `PidNamespace` of a `Task` doesn't ever change once the `Ta= sk` is alive. + // + // From system call context retrieving the `PidNamespace` for the = current task is always + // safe and requires neither RCU locking nor a reference count to = be held. Retrieving the + // `PidNamespace` after `release_task()` for current will return `= NULL` but no codepath + // like that is exposed to Rust. + // + // SAFETY: If `current`'s pid ns is non-null, then it references a= valid pid ns. + // Furthermore, the returned `&PidNamespace` borrows from this `Cu= rrentTask`, so it cannot + // escape the scope in which the current pointer was obtained, e.g= . it cannot live past a + // `release_task()` call. + Some(unsafe { PidNamespace::from_ptr(active_ns) }) + } +} + // SAFETY: The type invariants guarantee that `Task` is always refcounted. unsafe impl crate::types::AlwaysRefCounted for Task { fn inc_ref(&self) { --=20 2.48.1.362.g079036d154-goog