From nobody Sun Dec 14 21:54:09 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 286362416A2 for ; Wed, 15 Jan 2025 13:36:07 +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=1736948170; cv=none; b=UxdUiMy239FoTczN7aqPmZDIkL6M16Ptmo8/eP7ERATTYyAspspovTEd5hzO7/HheRxC5hNJkUSidobtQ2RWK5dtS3LtLlbGbmT0+cFjAiTWR+6hTph7LQDdCStm9/E6PMAVXokBLlkjza+BidfGu2OVyAK7nzbCJ1l2mYk79Mo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736948170; c=relaxed/simple; bh=JTL2MUjztUWi2Edxe76W3MQbrbIY2frYdACvccKeGlM=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=E/DgEZy4GKAl+65fhR38wX66dVix6NdTQIidLfXL3dDhIfYnqzZp+FqN7t2+UdxLw5uN1BkUrgYqASiVyXFFarReNY88wxoM7p6xHnAeAqZKNgMD2mZaaJYiBKw1foKEDvw1EwmvuOPVQC8ZHVAq8x1nglUSzSTS8v4+N5e2HiE= 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=jv3OGILa; 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="jv3OGILa" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43621907030so28585285e9.1 for ; Wed, 15 Jan 2025 05:36:07 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1736948166; x=1737552966; 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=bQZ8lzcN1AuRMo71v8cGYFa8tBipKd/jkKd39EV9lsM=; b=jv3OGILaeRP6DA5bIh0laEFOT1hKJdDeQxt+jiRcVZyBEgdvQjBk0/R9aZOzmrLdv7 43p+NHnXjC3zBU3EuDB5caVmlZfhVmWX5pvWBlG3O98JCcT84ONAprXJqm8p/XMSnAUy 2+qDvFBxnjNakaTi2JJ/nQfBvZBQlnIaSV9OKrY4rmXTmDSuGQF7J19RFbZb367j+qZ/ yfL3qeoDt10WNSJZcS9Qlp21voDSiQKAQKyHT1c36/nYYMk4BX05Oa8++uOfqHPpn4y3 W7+N5gueSj8J5Z0LT/BnGvvURfcPgQZUekHI0YTbpEMhK6Sv3HaGih39enEUXMxH0q19 RA0w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736948166; x=1737552966; 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=bQZ8lzcN1AuRMo71v8cGYFa8tBipKd/jkKd39EV9lsM=; b=vtUbWCfKdqEhM2OH81EtCqWfvw3w1xWNcXSFZkmtNG0e2q0mHulwbep986et2leUGQ gKpS+7nTEUhj3SOypXljU2/GHVuwIoe7+tEuZdfceu3TIlOrRRDpMP/Po10nOzT6MJI+ mDRwU9MjJUKQUTlmLyu+5tvgkvdthbD2cCvdr9u173kZHObW6EHWjm4cr2zkStqOHnxH xNI+R4GWmYhJSCS12qOsfhl3DVkzukTYXRY8cuHDORVGhTrsFKGLpe9+Sv0Jar9hzLHV wyFTbczx7jNuEJrYHHjGJyWJtpMhEsnyDinq28v7q6/jwbwDbvFb/0OYjKianKju3rAx W9Rg== X-Forwarded-Encrypted: i=1; AJvYcCWz6hNBH1m6CcO2luphQ3uQS+wv7Y+ooiDY4Nxfdm9JViC0YV0Bl0xsbDrhWBqi6kXJxPLqWV9NPlSMr28=@vger.kernel.org X-Gm-Message-State: AOJu0YygTX2s1DqswxlDDsdSZYV71MjRVzGYqk3QsnAv0miydLvB/5SN NSJHAW8ohOGAnQJ4FshXZSeSE7GBuY3nXp1fSdyUKxvhowsa36RnUA7zZD3rT4POsQmPlwimyBu wHeUZiigBNFnSKg== X-Google-Smtp-Source: AGHT+IHXOHLVyrqG26bwXmWj7k8i+YHFx0v6XbhRNOb82HiwvIAwHIR5ct4HbEiTS1Vq5WpHBB+epRkGt5G9PeY= X-Received: from wmbfj4.prod.google.com ([2002:a05:600c:c84:b0:431:1903:8a3e]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:a09:b0:434:f753:6012 with SMTP id 5b1f17b1804b1-436e26aa593mr296902835e9.17.1736948166660; Wed, 15 Jan 2025 05:36:06 -0800 (PST) Date: Wed, 15 Jan 2025 13:35:04 +0000 In-Reply-To: <20250115-vma-v12-0-375099ae017a@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250115-vma-v12-0-375099ae017a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=10172; i=aliceryhl@google.com; h=from:subject:message-id; bh=JTL2MUjztUWi2Edxe76W3MQbrbIY2frYdACvccKeGlM=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnh7m9buKTHoMGL2rWWFPKx8ZKzp9gRDt5AGFFP Y9srGjZLTmJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ4e5vQAKCRAEWL7uWMY5 RrciD/9qxvpMIi1Wfr9OCenml8/BizGBow4wxZKmGcU7Jf5ARM1DQFn7IAVl2OWQg5k+XXqWISD abUyA9sgSCR3fNBfQUlzc9oPDc8VFloaJX1eDitNJ9UuTGDQOdhqFnbHGSUBCHB7/KKwAKEFhPh Se8GxsL9Uy7GhqQr0DAXt0+LNvrthD8VFVPhUb81uxJ1NLWOwlKYLvmtfwDcvT7/18jAOYJ3o+3 LLBczHW/HHX51sFejN8tdnD8Uau2symCRFRznOxHVlepzvqs1L7DFqPa7Unq3T2n3WwbbihmiYW uF3bJ/iOXRuVYj3XuypBdZANoSg/vxZWaVkesGh1FepGgsVbNLMeANGCWWRBe5UmbzdvyXJXIFw r1eOgK26fKBljBTYe8OVeUBy2cJsr4dloKg1X8C9Gk2rgbOgQUqjDPqPVJ3CpqC1JmKDNfFs0jD N39u+9WgudH88D6MTFZ2ma9Ao3H3iS68gVHpLOIySe/rdlfB8fx/UKb0rMY0OzQA21lUL0PovdC TmyxJ9PQuXkTNQA0lOsDivCPLK9tSigtvjhqidQheZvMfeHeHagyWNoCUN4MieUKecVaLleVUsa YTtPtZwCxxq1ZzXJb7peMH4jnSX8yZe/lsBrQND4q5zTf62A+4jXJWVPaG19B4zwHCzbGpXPm0X LkC4SaR2OVHrQQQ== X-Mailer: b4 0.13.0 Message-ID: <20250115-vma-v12-1-375099ae017a@google.com> Subject: [PATCH v12 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 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 (for mm bits) Signed-off-by: Alice Ryhl Reviewed-by: Andreas Hindborg --- 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 dcf827a61b52..9d748ec845b3 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -16,6 +16,7 @@ #include "fs.c" #include "jump_label.c" #include "kunit.c" +#include "mm.c" #include "mutex.c" #include "page.c" #include "pid_namespace.c" 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 e1065a7551a3..6555e0847192 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -46,6 +46,7 @@ pub mod kunit; pub mod list; pub mod miscdevice; +pub mod mm; #[cfg(CONFIG_NET)] pub mod net; pub mod page; 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.0.rc2.279.g1de40edade-goog From nobody Sun Dec 14 21:54:09 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 9EB51242261 for ; Wed, 15 Jan 2025 13:36:10 +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=1736948172; cv=none; b=g9F1fFFh/5MGwqWGpr5jCsMJESc6uXHtMOBjPqQCTO820YecovkrpFAYgvHbTRAgy2LXcG3WD1PASMHB7K45Hs4PEx+riP+Q2X882GFqUpRCyTSEF0mELoeolrOaN72rzRdpDGmow1fC0pALXjrxir3Vf3DpUE4twfIgNzsDY7k= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736948172; c=relaxed/simple; bh=QOlRN108XsMWfGHd4EUDmGqdXLByOcXjEpSpb+5Nkxw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=LAdZdyxDlqNzxH1T756R2kbSTp5hu5IAm4XYMRotqeaXtk0nyNbg/JWdlffUTZ/9dKlY8Oahf9SNzM5A05eeHzb+GBdCijzmV+N9Y6unP4F1GzqNJuD9DkuvKfRzgVSPzL4tWia+H1RktRbYALSzNKkBg33EtpI5KvEAvO56Yf0= 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=Hxafh0az; 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="Hxafh0az" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-3862e986d17so2637145f8f.3 for ; Wed, 15 Jan 2025 05:36:10 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1736948169; x=1737552969; 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=Ya/fxaSnf1SEqFKMY4TDHESa1dZdTGioTOn3JAAXwI4=; b=Hxafh0az4QBe9D7ZQOEjhhjdlg7mg2O9ChK/2Oa4UcmArPtHrjjAqxG9cpJWlaSCOQ PXDnY0JMwj94e2GLcjiVzkCGTFuo5oqwln/d4QuydWCHV9JPH4e+txC4LzhwRQCyCE6f u8gU9Nia0/SnWhxxbAA5SNMpVRK4DdCkWdx1OpdLIstXOpfqX1tGJmA+hH8f4obTrO3R rcX/jiyxd/+h8V3jC7hN1b3+htOson2dDGZrlTzKZo5AV+dIxW7JfoJBYYcAf2rtH2c2 dO14UonxFlJ7cVbKtEicOPuDM2urT2kjs/x/Ok0Z8oTYv1VIX1X70PbMLlTDnJEb1OPq MK8w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736948169; x=1737552969; 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=Ya/fxaSnf1SEqFKMY4TDHESa1dZdTGioTOn3JAAXwI4=; b=RUo8NzZbRtOirirjj23pdfl1gsI/MRsGko2uVlVd+QslBUjpX3iSw4o8sFZ+0+QUsP jlF6wgSu5JKwMogBCEfsYKJWq9euY3DUspGUM0fArn1qX95jsISrItvXbP/ID6+FFJny A9HvmhnoQUjUwW+ulHBMgddX+RD6G77w3+Uco0Ca465cfahfMhUucVYyN50fEJMHrSqS hs9XBs/UEOrhnW4yAbVzQLBU52Symo5RRnDFwvfHG6eyqSMDPWtw6zyNLVx6qFy993k0 0CDodQQoIqQitkNhbxBS75rB2ZvE18GTvfQcLIYhKUbkS6otZFRZDMdLhjpxZYZz3Dp6 uwDg== X-Forwarded-Encrypted: i=1; AJvYcCWYkV13sWnF1OMDjiez2zO89pNSqH4Vcp08qYpImGwg2AXuiEtRmId15MP+qmpYBmrS0Pr8qerWdGMOxX0=@vger.kernel.org X-Gm-Message-State: AOJu0YzDJ4KNjU7y7sk6ZYwGD941+t9uOk/foBSAp+75S7Cv8qTSiTAV 4dD37p+QtI4marwcP4y/FxTzATKGfwwMSB6LaFk2stSPQw8zX6sLwFcQmbmprB4Vdtb2CXKcZVL uYmjyYmQ7MwkuKQ== X-Google-Smtp-Source: AGHT+IEEOUuyOBCf8IcyxS1o5uyy5iTIdNXcjMWrtrUVHUECJs06QuKQ9EcQ4AA8mLcrc83eTJVAQLiN4y8LWyQ= X-Received: from wmbez6.prod.google.com ([2002:a05:600c:83c6:b0:434:fe2b:fea7]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6000:1acf:b0:385:e2c4:1f8d with SMTP id ffacd0b85a97d-38a87303f90mr22556236f8f.19.1736948169055; Wed, 15 Jan 2025 05:36:09 -0800 (PST) Date: Wed, 15 Jan 2025 13:35:05 +0000 In-Reply-To: <20250115-vma-v12-0-375099ae017a@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250115-vma-v12-0-375099ae017a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=11748; i=aliceryhl@google.com; h=from:subject:message-id; bh=QOlRN108XsMWfGHd4EUDmGqdXLByOcXjEpSpb+5Nkxw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnh7m9WvlRbZQObnak5+wtq7CgBZq7hLM/eCfTF lPZEeBo+IWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ4e5vQAKCRAEWL7uWMY5 Rm6yD/wP0UVoOG6bmiLYU6Qqhm25x+hZZB6dLvh4LLNZv7LLVM/H3ISW6cX7v8OttgZnVscdXBZ FJczNPPcDy0+wTAt8TScAmi1hE6+c9c4jn0dxHD6uAmwkK4LM1TmHzvZ9Pof6BsAICdqdLO0OtX Ahp+0oMGUjXonkRgsKkxdBb01kIKLJAYbn7F5dU1lcXci7Kigjp17uSrp0zUvLaZQpBATnOscW7 Y0LAEpfiWW/VWokrxjJ7SghmqmTmQb1D+muAUO862QlkMwazGG1VwMHrZqvMiXgi3xA4x3YTDbF iZCUjoG54SpHUs/HEYMBRqFf4Q6pWVBgHwVPlc+9OliIEapK1l+pCfDaRnaCBSCP6oNo4Mejv27 fS0AwXvap2o7b4crb+/HfxWbmQugSDmmeHvGWSU1de0Y+0rBiPx9weLukK6E3MrnJ7bJv+QeVUx +T9f/xdj8GcqK66LTI/YtjWBSEmBQoF0pQ4l5IJLZt+vN7X6y8dJxrNLvhQUe2M2idOSbTuoxSJ lIPgS9Rd5Q1y8VrIpl0tx34H8y0E6CN9Pk/Ks5ZkVT6+E9nBYJhNiYKOMhB9j2JDPzyWtLbON/q tH/fN1d/Dfni4vUv6L3OYcwjEBncMZr03OtqdKlVbSFF9OQVGDdZLxJSZCjrsKqNgCEiNP3qnUM O8kV99e5k87/X0g== X-Mailer: b4 0.13.0 Message-ID: <20250115-vma-v12-2-375099ae017a@google.com> Subject: [PATCH v12 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 (for mm bits) Reviewed-by: Jann Horn Signed-off-by: Alice Ryhl Reviewed-by: Andreas Hindborg --- 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..ee1a062ec7d7 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 as _) }; + + 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..2c7de0460e0a --- /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 as _ } + } + + /// 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 as _ } + } + + /// 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= as _ } + } + + /// 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 as _, + size as _, + 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.0.rc2.279.g1de40edade-goog From nobody Sun Dec 14 21:54:09 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 A7031246A23 for ; Wed, 15 Jan 2025 13:36:12 +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=1736948175; cv=none; b=rgqJpYJwY0SO79IymZz6au2G5E0UrLIWYQWV+pZiCCgk648rszq4kaX+WeXoVv+QajtOg+v3DBFI75jJb5pgyKdfmphQ/1VUkfjEbaR8QAB9K7Ji50yyfjADmmopgUSBDlEpP+tViSlPyAGKWAN8jNmz85CAUJ2qH+SMXj8M/mc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736948175; c=relaxed/simple; bh=DkijNTCWjzL+GZ9A/ngSiwPnkdD9yqoZbhkXBZ1FzqQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=ES6Hqoh2vEoS+cI+D8ywHbz7jKBXoBByFv4kvPc5EOkErnVlUG88NJdmrkT1oWJ0xk6UpO/jR9QKl+eYq6+7l8CIdcNeIPKFtBb9V8wm8ioJNAR0LChaWDDN5hriN0Q0rN4OA+qDROMoxq3CVgL96/r9RehkYfvYzF1g883vNLI= 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=opLg9mkD; 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="opLg9mkD" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-4362f893bfaso36067175e9.1 for ; Wed, 15 Jan 2025 05:36:12 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1736948171; x=1737552971; 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=iAB5+MkDlqluj6B7QpzdYLJZpgBLqkqOo5ngR0sMgMc=; b=opLg9mkDHwaQoqtDK2mwhQgsLfl0LQvgnE89WgEE6JcyIk5GjjdRohX+2euhBI2ExR YGHcNmvA6Or6imGH1Pz4/DPSR6P4oencSU7opvKwn7IUxLadCuBnFT/qkPbkTSsTy0m7 eurCE+oaHCYoxhdqi2ASpPmuubMYgIRrwc+a8udzjkyyw8a4NsaqZIjt4x7ESkj6GgIX 99KO0Qlr987Y9K3hgEAWRX+auH99IR3Myl7bd0e+omEKDu7zNWVFVAPDM1gMyWLciQTb HE61Rx/x7ZtLKisybQyyWJ3sm0v2U/Wh9cW3gkrZND1HfayoCgPhDGoESdZH1hn7Y1Bq x/Iw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736948171; x=1737552971; 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=iAB5+MkDlqluj6B7QpzdYLJZpgBLqkqOo5ngR0sMgMc=; b=gwlVVX69rbBH1fb8DE1C70WBBsyiqZwsHMmwLz8tkwMqLd18B+HIwkZ14CuPewQ6OJ q0qvL3fu3taxyVPRRBeQmrPyjqjJdiKWITQSeKU+ZAmSrnqUGQVFjrw/rn61Oa9RoWBL kSRXfD3+shl+XsD0ZwRKHq5bZhJTjI5butjlQNU3CbLVnBulYAAC1N7AzzY3l7XMIT8R qCgOm/RD17Jpi4tMnqF9SgwV/abbddcTH15Ke8vMvCs6w39TS7/3PmRm9dPBq3bstycU Zsp59W4bjI1Axe+lCh0+KFnWGYTE85co+/ciUomliNMdhqSc0Zn5RWWOL/7ZT5fisFip oQYw== X-Forwarded-Encrypted: i=1; AJvYcCWivqvx8NMA1Ux4Fa2QSAsLBN1MtX7t/fQzIjHf9BXswrDoEEpILs+ubv8adbPpCEkE61LeyrBATv1xff0=@vger.kernel.org X-Gm-Message-State: AOJu0Yx+FYwqqS7mO8FDcUMcYDtouqVTfpjSxl+GxoFkzBj8jj5gqz93 1m0TNSWni5elQsSaaGfvWe9VfGs44Ngj3HGjGvZGOGXAD3258rKDxOiDi3Pc8rvBjBbi/HNKDP0 XtHodMhE2gRBdbA== X-Google-Smtp-Source: AGHT+IH4/tFhizC0Tlbso0pfJWClZ8vsinv7fWPPpakyMd1YYPpuWimTTutI9DYbU8xxDHrbDqgJ8v0xT0gjcNQ= X-Received: from wmbhj18.prod.google.com ([2002:a05:600c:5292:b0:434:fd4d:ffad]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:314e:b0:434:a5bc:70fc with SMTP id 5b1f17b1804b1-436e269aad7mr260754245e9.8.1736948171131; Wed, 15 Jan 2025 05:36:11 -0800 (PST) Date: Wed, 15 Jan 2025 13:35:06 +0000 In-Reply-To: <20250115-vma-v12-0-375099ae017a@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250115-vma-v12-0-375099ae017a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4166; i=aliceryhl@google.com; h=from:subject:message-id; bh=DkijNTCWjzL+GZ9A/ngSiwPnkdD9yqoZbhkXBZ1FzqQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnh7m+n+HRp6TVitWGzxTZmNyfMlBYn2nHJh85c gF39+HKacqJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ4e5vgAKCRAEWL7uWMY5 RkLSD/4hAr6ppSvTg25k4E1epqUVJqhwKwShK0kGDC2daG1PTdOf7HHIv2izh6j3qOiJU5pgh3e JBpHueh/ss+r9ARsw5Vp0y8VmJRhMphbTUgNJe6+f/TzTmBbwi5FWj36eKetwmB+6x32ApYd3bW b9zGR5ekfUIHCUKnn4ybbKv/+eO4qkmegPEzNpFE6ZemT/1bvOscQtuiU+1zEXtE6oMK6MhHrWM 0ntaU/0JSoLHdsCRv2kkmLI741cNl9wpplYF17izNbhn2hbCXHOtqpuzPXyfbqr9Frte5i6Ea8p FJTF4wJ3KRxwb52DoikPJXCzUprqFedDHjaPo9NB9eXQcXDTktrviZs74nlCx2IVINhEQW9NFqT lxiyxB059onff3iZax0SYVxFr+jH4w/YdiPd4rrpf0s3eMtOPQ3rYVPOK8dA5JP8uxiYhOJHFO5 XjQeCofzoPVvwKq5HLsa+/pMaIXrSQoDJ0SmdYtAAsQKCpI4XUrrXS9PVDisEsGcL+r9i3CrlCz jZwa2hoidoGaAip0/tCOyZPxeW9uO9X220T4m1wQeIzUS06ggzIWX3dbrSd7HpHg2/0U3OyZ4Zj l/0rq57Zp7TS9fPY2JWKtz2TEpyegxfM/AOuhYGKPzf6OTraPQnjWNhd8ncJL6WAWj0Zai8jcPC 0zsvqbfT7/0ElCg== X-Mailer: b4 0.13.0 Message-ID: <20250115-vma-v12-3-375099ae017a@google.com> Subject: [PATCH v12 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 (for mm bits) Signed-off-by: Alice Ryhl Reviewed-by: Andreas Hindborg --- 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 2c7de0460e0a..ab89a526d3e4 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= as _, page.as_ptr()) }) + } } =20 /// The integer type used for vma flags. --=20 2.48.0.rc2.279.g1de40edade-goog From nobody Sun Dec 14 21:54:09 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 054472475DE for ; Wed, 15 Jan 2025 13:36:14 +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=1736948176; cv=none; b=hgkv+14Pk05e7Q6hlOLS6ToS5KI2wwzwvBIkDwGEIszO8iCKcocvF4fC6C5WAtZeiD9BS9kA3nl4QE0Dd/o7zORDagcDFv9zM084Tau7nVqVqoAfyLnz2X52X/s04Abm+AUGyRyfm6MtSAjYLxrLDXwlvkAgUxO8hT7MBl0E5Qs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736948176; c=relaxed/simple; bh=fLfkFNdLYfHgKfZa0dsXjtc9votv5zCA9qLsVLeeLkE=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=mlpZvFqshAsInWokxe2TGfIlsTclEuFVAKIlbCg7xI5mf2slxxwpxwzeORrR3JSIdLnm4/qQR79DbUlGqFdEGU769Rw+PNtPR9mgEvS5NAzPF1Ko35Lb8w4ue5D2P3FNi6pJsV2iAK6ohFS+WcmBNVk+dVNbkG50Py5lTwuR6Gs= 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=UbID/AhC; 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="UbID/AhC" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-385e1339790so4317247f8f.2 for ; Wed, 15 Jan 2025 05:36:14 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1736948173; x=1737552973; 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=WyGEiOkhmdNY/fU37LXSLgzBjmVwObw0G8SyyivcNjI=; b=UbID/AhCU5wGAdmP8a9yEH+ARVYetQUbaV316StcVGsm48Zj9nACuFSB6YMpxQsjIP 7put3y7fPNJ61fsM1Inm/MiB+KFmYV8XH2FshVKDbv2fxAa9qE0nLbsDTbGvz5JpI4zY 2NCM2Pb5ZFPnE1YcLvqc2HeyDPjYwNP38LQ9EPb2xKo7gRA3Vn+e7P4L7wxkymkDUvw/ 91Pqd2micGLS9WCmnhfLoKoIOTFCWP8TUE7Mu7D6Gjx0eQa2pjNZBP3kICoS2AFBDpbP mF8qFUJ9CetmQbXDq8W2aOuvLdcdpsdDXBBRyptR3epB0CA6umMMUEiHa0u2/rmr8XT0 SaIg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736948173; x=1737552973; 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=WyGEiOkhmdNY/fU37LXSLgzBjmVwObw0G8SyyivcNjI=; b=ItStWhw9ubA1Iy1eeGQzA8c91DYSqyCJ+5i5FFF9BWVV3/oCq9pIy4IAKkuO7DCeW4 fugTxsTPQhD7oGZCkqW4PsqoZM5dbYHZBw6L4cpTClbcOvGrZIsAA4OifC/lQreX8an6 TSYjUlzl8eYuiH3S8acFR8DDXRgu2HGgZoLb6NtrU1mHCB9WPKRNU8hto7UechdbYRJy QCo2aEExboPkrquhOR48Mwgi5rEI/3Jttr2wBv9kwWUqoI4HeBAnUCNkNB++JCcOyKLp tWWu9+OW9MRaUIT+zsgFBGlIZTmBzaEZwEBZ66jtDT5ycnuFQGbubwhtCcuHMncfDijM Arxw== X-Forwarded-Encrypted: i=1; AJvYcCWDmNw50iCs/hLh/zRsG0so8L0X5EEUNEyAPJ72HMmT2Uc/fgpZr9hS0VWSlGM+dojD/lPxoJEpT2MGrtI=@vger.kernel.org X-Gm-Message-State: AOJu0YyR9WMhZMUaFbTJlBMysnTccjzJWtMIKFKOyY04rc6LaA2FYJ2H bkHhkZRR9Z9ewlFZ91h8rr9m39KpojMPT91uPc1Hh8xMPz1s6EmZqpO/EDn5mp0IjyvA6Shp934 VlxiEs1Kv5dTYMg== X-Google-Smtp-Source: AGHT+IH6kBJKdmdDV5w19iOE843iDVldxJ9in2s0SPbV23iN1Txz+OJHqSf7ZYmSD6HRC4mZ8sg2KRgO82avk5s= X-Received: from wmbfl11.prod.google.com ([2002:a05:600c:b8b:b0:436:e755:a053]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6000:184e:b0:382:46ea:113f with SMTP id ffacd0b85a97d-38a872fc1b3mr27766198f8f.10.1736948173574; Wed, 15 Jan 2025 05:36:13 -0800 (PST) Date: Wed, 15 Jan 2025 13:35:07 +0000 In-Reply-To: <20250115-vma-v12-0-375099ae017a@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250115-vma-v12-0-375099ae017a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4078; i=aliceryhl@google.com; h=from:subject:message-id; bh=fLfkFNdLYfHgKfZa0dsXjtc9votv5zCA9qLsVLeeLkE=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnh7m/l8GboGpN/qusvnLxbok1uTnWuhzUiY+SS PCNfbEvgfSJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ4e5vwAKCRAEWL7uWMY5 Rg80D/9JzLVe2s09/Ey8IChe2f9AxrZWGc5rUDwgfHi/y8u+2zvnVesQGWFxUhTaCR435B8OVxl Ytf7xmAkpx69EK9ykOXhedM7v8VjGiD4aQDdY6PVvJPSn2MqV1yR+vLN6qIFWT6yBAVpVIkP1td +w5eKL6SIUPPOy8Soh/Dc4TAsEXq+JL9JEW80gfxcGXh3wsQzWc13ckoRPk5LdcT5GCVnLiaKYN wfkm3PWmgvVayaKk2PLF1RmN3hzwu9K2dn8BVptE+M6Fr0SafY6i8Oi0VE1ofzMxxUX29xyFkhZ uQWnNU/gdc93rgpgmNxxmRznFlMnBmEtNTH4kmI6YlrR8xXpdMPx2VIXTpg9vFHzrrcRI4c9dLD TiqK5aexQj6lRpVzWPdj7Sv6HE0sfCR+Orv7MPYgn8EGY+X69KmsutvARRFIvuCesfCmmBwHwfV Gfk2+CiL4ynj6qx9lZDg5DmW+68O3r/5DMyFtqB7uevUcSZ/HPmC9i5KcWTAtvVS3uL0EmKPePb fd8Gi72oo1oQ3OjvzaS0SBeHHlVE0FWz1n+TAOa+uPSShuMSx+4ki2JShfkmUWc2kfYxZYPNTpq lsHyUCXtL46uBkw221SbwO0R/tyz+0ABzNVR7dKEpjkbktYrrQ0dYY4V32dS0IsS1gpv0UJnqli M1k0GU7PNicgsmg== X-Mailer: b4 0.13.0 Message-ID: <20250115-vma-v12-4-375099ae017a@google.com> Subject: [PATCH v12 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 (for mm bits) Reviewed-by: Jann Horn Signed-off-by: Alice Ryhl Reviewed-by: Andreas Hindborg --- 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 ee1a062ec7d7..60dc66972576 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 as _) }; + 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.0.rc2.279.g1de40edade-goog From nobody Sun Dec 14 21:54:09 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 3ACD924816F for ; Wed, 15 Jan 2025 13:36:17 +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=1736948179; cv=none; b=b5Kp3GS36DZqBVXNxD2VnG5tvkOm8GK8Lj2P0L+AKX8eA91D6pkp1dMEFXMXnpP4qYKT/ih89t0OgwNgCZbhDGshRTOTuIcUKC/HSRFkgffqrmIlIkN43NhNAh6+tPcVnQSmNdHvzkDyzYf+AL9wyhIXRXIg+S6DkxrE7zDuTls= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736948179; c=relaxed/simple; bh=30XR2NvyOSBS+jDMS4+B8d4GBDe/RpEg1dR1knprL04=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=AW+TW8njJMmFR8Ag6uU6eAh+hP/U6oivhtxr8L2pRMbnE62EHdqVxOe1IFYRXZirGZmUFO1XudYQV20yqdXjdJKzA88X0kGBUlhHKueEGrPgfV0cttTQh0q3+m1kunO4mlB3C8xfb3EyByIWN2sfkfgF8wmHij1k97RlB7S8udM= 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=I7prBL8M; 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="I7prBL8M" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-436328fcfeeso53659715e9.1 for ; Wed, 15 Jan 2025 05:36:17 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1736948176; x=1737552976; 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=9rKypNB63ajEZUNiwKcfWGkLNs9kznO8TMtZ1K+RxGI=; b=I7prBL8MiSVSMVcPydgc/pJklFjdw2e4djeXk/kA0sOq2GYeXq2kJyaK0SDUoiiZDk 0Mjlcejle6SZ2p2tnS792G5n6e9kEO+5szlBLuMZV+WQ7SOdDYg/iIUGSBjc9gJ29jPm 8Cc2S01FR025MDRzTpV0aSfnXBwMDHu7PxL54EhftuxjLVuymqIvNDhdocXkN/SolUUP XD3siPS2wbd3Bs40puLCprgxH71bHBRn2AT4y3x85TYDxniK/UD4BNjnEw9V469APgNk zX+rPfO2xX3iouElCsKA3qBfqazCY80q1OQuaGPXzx8kURZNSN1zFKdqSrkxoD1AvvaN 57DQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736948176; x=1737552976; 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=9rKypNB63ajEZUNiwKcfWGkLNs9kznO8TMtZ1K+RxGI=; b=ZczcCmdBGZFbwyFn8hpf0wUMMfKVt3Y0hHfhPCQUM47I/5HkNOvSPdCb3XUt0Ngdmc Li+4Wekxi1gWygoranazaqSXdA/4q86C37hNpG12R/y1ZH2fYLCDVLkomOdN4fPEMNhd 2JJjsCRmNpyeEJsYjb/1PWFyzw71Y7UtKnIJ2xJXKiyZwMMUSNHUopgkWcw+3W1QN2xG tDIuyek4oS43k/pi6gVqIlV1rRLI+SvUPh003rJfJ8aUZ0oMz9b3qVBq7KrpNsS/IJZm MgHP74K6av+4HGwKVXcywKURro107k5Oiami6fuORga4gfGZR5rFMgIykMMkFOS1O7wA GCkA== X-Forwarded-Encrypted: i=1; AJvYcCXMs5YNRsdfBRN2pHnqE/145vUfB5+iXBzBKf13aCu2bVZj+tXDeKTksSQ+M3Rw5oVN507+nX87i0GLq2U=@vger.kernel.org X-Gm-Message-State: AOJu0YwEBzxdn9XJ+qreQnVYIhaKLh6WTlaijuns/arzPbIDGf2EAP8n Ftzzx6qqMnkhiI9PYZzt3+C32Igl13e4g7RbIwThHwHa9juypdtxCbRp75ljVGpwvEwRSPpFkqu S8rf+GDn8kgWE+Q== X-Google-Smtp-Source: AGHT+IGsuwZ1l0g4W3y3Qu+FgJ8iww+9A3FLFIVNNL+wg7yBLfHHRHUpzUWCiouwB9ZiGGEoPnqIBOqi1jWjsVE= X-Received: from wmbfp18.prod.google.com ([2002:a05:600c:6992:b0:434:9fab:eb5]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:348c:b0:436:ed33:1535 with SMTP id 5b1f17b1804b1-436ed3316a4mr227011565e9.12.1736948175968; Wed, 15 Jan 2025 05:36:15 -0800 (PST) Date: Wed, 15 Jan 2025 13:35:08 +0000 In-Reply-To: <20250115-vma-v12-0-375099ae017a@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250115-vma-v12-0-375099ae017a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3168; i=aliceryhl@google.com; h=from:subject:message-id; bh=30XR2NvyOSBS+jDMS4+B8d4GBDe/RpEg1dR1knprL04=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnh7m/n84l75cPhMeQdlYkKqGCd0G/G16B/EPtL 8EOZEg0z1eJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ4e5vwAKCRAEWL7uWMY5 Rh8YD/0UTFeQviTFRZ0rYolNkH7u7m9ndG6cRTDSh6VUOR6SOTsz3T0HZAXgaIzUB4ansQZ5FZa Hj2AfkIysDwMHYRE792KZNGtY4D5HnhPG0UvY3yCPTVplkT7QXvyCE+/xmFL0Nd8aoJGRKv25M0 hpm0ihktW9H6xXBBuHgGiF2IVx2QRxsUIWDMw8b+1sByiPrjMoc8QhkOcAxiG5bPrTtgdyjuwkz HbFI8TvbCblTU5qgb1syg8w5crYZiXH3RAnZWA4Nykd1csEn6iNepKikxxADNbht3qjj2/owiAQ TXs26xwpbh5H6M3dwl0QOArMRffQ602vtsmTd2zeAjCpSas1BGt/e141lB2pzMImtmmCM7OFu7J 1OeELsA671/xBaQLwFxqyOhI349LfXixRgGleNTwTdzOfMq3bUvzUEcAenXA6N5fxv78lee6klv OmtUgXTkopsrc7fV/IMu+mvhxVBEVYbflPUoPEeNW6R76MEldQR8HoDvmmKweZt3bGRpuR2F7kL Wo6Q27nXpOZsknq2dCGwxH9Y1DyuIT3y0ah+dYMulo2AQy5jM5iZZBM2Yp5xqHJUPW9tazwd6/8 H63sV0iAZhbIci7jP6KlcVGERq6kLTyAfsz3NBmmfedhmfaLo5Ph0qm3v0+wRTr3c9YIljrqHLT qOJ+CFShyk701OA== X-Mailer: b4 0.13.0 Message-ID: <20250115-vma-v12-5-375099ae017a@google.com> Subject: [PATCH v12 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 60dc66972576..3bb2ccd5fda1 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.0.rc2.279.g1de40edade-goog From nobody Sun Dec 14 21:54:09 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 832FF2500A5 for ; Wed, 15 Jan 2025 13:36:19 +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=1736948181; cv=none; b=uvIeOwz2AuDiPcdPjG0ax/2duHyik72Bpv9aqDLWht6Enl55RIMPaUEgEBrogWwEeWXYSScvNiFgxmgW75kVAYgyK8hyZYZWBv4Hd52BNWklcQ4/XwL2jBddz3a8CFWZJLd1jTc46pTvMCvBiEGsJ2TlgYhRxtsld37ht2adHq0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736948181; c=relaxed/simple; bh=XaI6NH0XnJmRP4+EcHKB+RqgempmG+WN3YGnzXiE0G8=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=hGDsZh5lJIRwYFAxdOTfjuzieRXBCCVZSQ5QK9oacEHI65JOAoke3MjPRv54HE6oI5jFERHkLfhYu/NIpPl/XAFgPyMqrwoAFOvHWcOLqPK0z3RN8m0G0WuhvzEAt8Y+sLgnKTj7xceWCHzbLaPjU5O3biO4PFuweNfodyo8UxE= 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=qnFKc0jD; 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="qnFKc0jD" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43631d8d9c7so4407745e9.1 for ; Wed, 15 Jan 2025 05:36:19 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1736948178; x=1737552978; 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=DamytgltoVfeocbQeMx8nCBv52GuJHF7pCRdLZ/tNgc=; b=qnFKc0jDEl7R9p9iHwVeQMsvoDht8BxbRTxZrbycNdL1aWzK6OtH7rZfAB5luvaLfC qy4ev3qZ5SIYRDNF2Fd0iNnyn3v6dLoZsq1fRBonDFzwCp1aOtN0EkoHq6CE2HaA1UFW /8+WxrYbYvq0+JrkzYJJU2c612GOM3jtQMaRwKbtXW4G6ukThb1E59Tw2lt1uvCigi3N rDEtnxc9QQ1bLWK+/5Ljtl4ycVW2f7HWod6PHWEP4azvnaoVv99fUnoirQSlIZOCMNXJ UFsW9zjj8qmXSOpddFQJlzjADaeFZGh2Raj+Oo+GGRY9wwGWLLrPHfevG5+mszPbsZyl PkPA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736948178; x=1737552978; 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=DamytgltoVfeocbQeMx8nCBv52GuJHF7pCRdLZ/tNgc=; b=Hc7j14XOUGS7/z8Ow8sjOW5/NtAmdmyERVlNEIiiHtdPBDOTYJB0qAc+Vqo/l0ePHw KVEn4vnDh3VB7u8OjWYg0utwDNAerYUcn6kGsWuuKHWOyzfcHWVSKOQmlPKl07+woPMH Cmyse2vC/72i5qrHYkpCGjMtZguoAo6YZyF0NumFI1hWtM4xcXCkE4zo8w9sZVj/nPWV jIjYw04StTga7UZeiAXGgrkT4/Xd13e0/wMry0JDkvs9tWP4fXL1kZ3upTZFM/uq95SC Rfr6aLqq6F2BDMltbOBkj2IlKVGc+5+AVQdcLHecaNeF1gJIGQKigAdsegVETnY1iq6R AzoA== X-Forwarded-Encrypted: i=1; AJvYcCWB6VRs6URfGiwMA7FsWfkLYt5Q+x+CGRMpco7/8W5IDHtUtGZB8/8qJILpS8wZix3BEgeW//Qn8nwzDu0=@vger.kernel.org X-Gm-Message-State: AOJu0Ywhzk7DkHpBlgzmNxTe+7EgcQoIV59g58XI7Y5twjCcjyP49/r6 d39enMy+T6XCP02a5ZATcKdrXQ8e3BT+slLAOFbJ3v4c4Y+xUbkhLgoGIEMg183lZj2ziQPvSk1 /DngSNETFCU2ZVg== X-Google-Smtp-Source: AGHT+IELx9AJKZV8sItrJFa+G/e/yL/ebbqw7wwoZFqBDXagGmIfBN3Ggcgo9ka6F5wgyrAjnxYDVlZBAHgwK54= X-Received: from wmbez6.prod.google.com ([2002:a05:600c:83c6:b0:434:fe2b:fea7]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:5cc:b0:42c:baf1:4c7 with SMTP id 5b1f17b1804b1-437c6af202cmr25099885e9.4.1736948177970; Wed, 15 Jan 2025 05:36:17 -0800 (PST) Date: Wed, 15 Jan 2025 13:35:09 +0000 In-Reply-To: <20250115-vma-v12-0-375099ae017a@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250115-vma-v12-0-375099ae017a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8588; i=aliceryhl@google.com; h=from:subject:message-id; bh=XaI6NH0XnJmRP4+EcHKB+RqgempmG+WN3YGnzXiE0G8=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnh7nAGt/I2v83P5iCzUqj5ZXeXUI8e+dMSkVQz nx0HwcJCmOJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ4e5wAAKCRAEWL7uWMY5 RjcSD/47K/3DO60B2Djq16CVAghmS7WUkxL/INITcyHRwb6oJ8YyJhj8TK4JqkPdRZkgehr6WpE UqWj8HfVf2ETduU02zEMH7DeWGL0InDF98h6k1ceM5BxZJZv3YkLzK/RHzERmuSBXNAjSh6dvLX 61fnzSxecO8s+2Wpew8AmqVgWbBGAjYEi+3VElElWycZMHTQqsu4s4Y3/9wnRBXF68JnTcaDPvI L/yuifcqD1EC8/mF6NiQkoW5S+gXPUOSUefteN9/S+ShXCUtGla0pyK2RzzAJqt1l6kP3p/nyzO OtLgYmlG7lSBWtX3opa/E1iQFE81tTvgbN1VGWVfp+ZW+HsGc8+Nij/6GNrobLS4GI98/75fpEj WRB78vEl0vEgcfRMi8GXtPKFWr0wwj7jhGbRpGutntjl46DzYxn4/lVriP/oGiGGPQHKXYc7LHU S3IuTdyr5eU5x9otUQ7z46m3ppB8ZooIYC/KFEUisOz9qkL4CSyyViR6UyM7AdpTrxG4gZOFCqg BNcWZr2LtyQm1HNI6UX61cMFt2zWQawXDoraJ1vfiImRSjc+IAZnDYnEKFyfoblOnhgLKv4SWGT +aE4UhZ5F9fPg5rnIYwlrOLeEhbbZ+f2FYtfsvVCemJTdoE5MikdWKLFvmu1AF7yL3LKhnDJ4S+ wcRVfT/ozzI9kkA== X-Mailer: b4 0.13.0 Message-ID: <20250115-vma-v12-6-375099ae017a@google.com> Subject: [PATCH v12 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 (for mm bits) Reviewed-by: Jann Horn 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 ab89a526d3e4..ef940973e231 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.0.rc2.279.g1de40edade-goog From nobody Sun Dec 14 21:54:09 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 A41CD28EC73 for ; Wed, 15 Jan 2025 13:36:21 +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=1736948183; cv=none; b=lDyf+f87kCiQoSVf/jVlsJTW2V3YHNwdShUxw5Wk4bwdAWhcYtoetzpAL+l9kaGY8yyT40vXRwaMDcFtNgg/TjvJLdiwcprTnCHFDBMBMynFUKSVw7HVurt2ugTIdSVSPO/1gPI4N5D0soTFd416dhRdvA+HcVZTECCtoODNGLI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736948183; c=relaxed/simple; bh=YABlKOR4s3jcHAdrd+4knVVhbkpmpWt8xx350u7Y5JI=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=YZ0wjIdq7G15QUYxHRaw9ACIyDg3drJomgLBo4yw0oMfWxlZBw4/cZj5fmDvo2uhJjuESydjfEsBwPM2fg7PCfyDfuyA8PFHJFxU6FGKHIcxvuIlzRuoOgKuAz4zclyb4V11b/YH5Gd8sfd9t00CgYkW6AlqJBrMsLH+iXl9y6A= 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=4dIIkpTj; 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="4dIIkpTj" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43631d8d9c7so4407975e9.1 for ; Wed, 15 Jan 2025 05:36:21 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1736948180; x=1737552980; 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=81ZLKD3ogzg79yEJn00+1Q3wr2cvrl13TETNOCjT2u4=; b=4dIIkpTjJGO6LYcPZjpxsUmCfvxeqfS5x9BnJ3PTkDkpktvuMijnlCgWyLta44O1SA bWXfDKi1Sz+Mae01aT9NXKNqExObxyb4ngE8oKkDsHsb78Zyw0dfxaXLyIDXGRxNFHUA faCnO/VbrhpgE6JOPNbvPi9TQmp27dazl47Eqc9ldNCOibVKbCuExnoJjH9a24BUcW4m lWIySeUgG0OuaSt2SNSP8MsKs9pxffWGZlGTG7az1PkWhF9Q9LWrxYlBbD39RyVyAdkh 6BdMmvxUwyu16UjXnDsiHJEg37yIPV3eIZLvaB0anhG8KSfjR+PDRTBD0xJAPWWxsY1q asTw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736948180; x=1737552980; 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=81ZLKD3ogzg79yEJn00+1Q3wr2cvrl13TETNOCjT2u4=; b=Ug4Qs5vlg32s2UPYQK7pB7m8idKSS/3jK1QqQtcamyNYGoOyXYKajtoQqglfzY5W6d mOtGPCeVEkjEw8J1iOsJeMEn6N+vSCA0ETtJ58kRDpBwRM/VBibSQtnIBXNzhXKoF2Mn pJn6foHGbotawaYz+9lEdclcb45MHO/pNv4+b4Z57YIszQM9omKF0+xrwh9ILnMWHdXO GGmGndBNZe8hqjrV5VoAgN4TkCLVkh6+qyUI3AWw4w8dBfjem8MHdMh+h9rJBURAltKL Jaqh3N4vrJI7NvGxYoURE4jIPG0u4Em6l+cAwlregqpgzlUo8C6bc+zy0VQamAliNjaD /pZA== X-Forwarded-Encrypted: i=1; AJvYcCUDeksGCh9OlbGxcyUg0gE6hwc7OlUV0Oyzi20c3UhCqLoEZN0s6szs6BUHrlGQrDxK1t7mDHQre/RFtF4=@vger.kernel.org X-Gm-Message-State: AOJu0Yw0sTBXtzi4kxT33CTEEa2pi0CO8rAjg1xtw5iPNSGUQBQA6jhN FMosXit1FNQWYn6FghmIGlINreFPIddj7ZZUETZbz9VMacFrM+CDqDwisAuuOu1engvCEAic+ss yN+B3IWsjVY39+Q== X-Google-Smtp-Source: AGHT+IHgYgEKSPDdi2P+oyelNydwykWpCSvtY+CbLbji5X9hWCVjK6MNYOAiA3I1gSkw4AjTEKFL2AALGCdOpWg= X-Received: from wmpz18.prod.google.com ([2002:a05:600c:a12:b0:434:f299:5633]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1e29:b0:434:e892:1033 with SMTP id 5b1f17b1804b1-437c6b7b184mr26161955e9.2.1736948180099; Wed, 15 Jan 2025 05:36:20 -0800 (PST) Date: Wed, 15 Jan 2025 13:35:10 +0000 In-Reply-To: <20250115-vma-v12-0-375099ae017a@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250115-vma-v12-0-375099ae017a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3771; i=aliceryhl@google.com; h=from:subject:message-id; bh=YABlKOR4s3jcHAdrd+4knVVhbkpmpWt8xx350u7Y5JI=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnh7nAleiDJcaQtJuPa+I8hS1lU1tl1JfuAuv6C fM9qXyv8SiJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ4e5wAAKCRAEWL7uWMY5 RjKWD/963spEQDrIssZkZ3POnDl7uN2xDsLrbFE7PWw0knySvUIAaNYgn/o5eNYUfpxiQLaCKkD CXGxsKIuf60CrxosESAo+b4ZUrA3IUYF+nX7NShS9KEgo62sv6MnBwZclUyx1Gj55nj3aNveugE fy0OodhenOJTHWSU7N4gbqJlMKsNFxFMoLCMphn2Mle3wqHMGd4jGi9IRXspxNU3pWa6ccMfYo3 LqkkBCs65pX3GBKgCt9OByOiUNBtC84SEfpNjTar6ZqPx1wR+7nJO6U8hxO+jc1KdErXJ1KwxZS mSQXRQDKLpBln8f9ZazAF73LtchsKtETNLrTD18PNCkfZkh5wxnb7cHNkK8CC9ULX6quxyPzmCH QO0rDKnCD2fPfoyJWdf1xnjS4Z4PKm+TesBB3ihfWES2VoSsoD34cnbq6uE/opRmhvNYUhQvfAu CV1nQnnDyugFYDTO4gGC3FmJ8dWJNPy2DYEtQSMhbyHFqI/pGeTc2+CLwWlrsBob7NPgw+KPJR1 vwl2jg1bbS0MmLM0UKpUFO+RYxBg6HaNBwdr0R5RLmkmuJkqWdEk3wOajCyuMxCP1IWmmLymZya qtAJCN8TF+CkyYnG99EOWqEe/MlfaHTX38XNA0sreMyoYwYAsBgayLu4dFvPIME3w8Cko/T6+o8 +ejB8bK+Cslj+dw== X-Mailer: b4 0.13.0 Message-ID: <20250115-vma-v12-7-375099ae017a@google.com> Subject: [PATCH v12 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: Lorenzo Stoakes (for mm bits) Signed-off-by: Alice Ryhl --- rust/kernel/miscdevice.rs | 45 +++++++++++++++++++++++++++++++++++++++++++= ++ 1 file changed, 45 insertions(+) diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index 7e2a79b3ae26..0a0ef172304c 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -11,6 +11,8 @@ use crate::{ bindings, error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR}, + fs::File, + mm::virt::VmAreaNew, prelude::*, str::CStr, types::{ForeignOwnable, Opaque}, @@ -110,6 +112,22 @@ fn release(device: Self::Ptr) { 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`]. @@ -156,6 +174,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 { @@ -216,6 +235,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() as c_int, + } +} + /// # Safety /// /// `file` must be a valid file that is associated with a `MiscDeviceRegis= tration`. --=20 2.48.0.rc2.279.g1de40edade-goog From nobody Sun Dec 14 21:54:09 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 E56783DABF0 for ; Wed, 15 Jan 2025 13:36:23 +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=1736948186; cv=none; b=dIxd5MLpKK0KLV2UmsTNEJijj/g1wXTimwmLx5lqJtmDhA5XutM6DMpacYAa1Rwo0IlE4wDncKzV7LpTkDK2OU1/qzdAgnNsWX76COVt65Xe9Q3Xn0V8Py0wIbkuS+y8xTYl8/tnYYvYXoHRJUOrFtsDMa86B36qx+reoo2LHQA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1736948186; c=relaxed/simple; bh=8+9yOLbQvy2W2D3bb6/KIfbQXKfIeZCeNeOPvjLjO40=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=kc8cFZvSibUjib2WK3SUl6oj7lBEB8jd7AB19ys5qly+bdZwV8OrVGVZSIzJYSUmshD66YVrtndFYqiHk24eKnVyyureKpsbfMBE+8HnVW3gnkDN3R4zAc065lGNxyT6+bbxWHRp6pOFJSC25HS5QCFaVtJYbtjGn8Tg9leiSNc= 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=vS9lAPas; 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="vS9lAPas" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43624b08181so4454485e9.0 for ; Wed, 15 Jan 2025 05:36:23 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1736948182; x=1737552982; 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=YDhR0wZS7ts5Hgraw2zWBvxuj4q+PFH0DkTWwrU34Og=; b=vS9lAPashqlT7EygAD+Oo8zY7cJ/pvo4j7ByHNfa9eI/BHWa396OexZGW471Ukbl88 vK5VvQ1cgm5BAhhKjQ4h0o8b+qkvwiWWQjHWZdbzrAh9iPm9MN3VTsdlKFSRVTjmITyO GqesH+hIarnjrjikMaeysB8pcpM3saqRF4wUc5AYewFE6s/A8HatPlEoGAZse8eS9+zc ynhxvxjzN3Fi1h4Y3gbIgJt4+B9o5+DYXqSK9j+pMwaLZIIKGrnNiuuDcmFxm8VFAZMA fYbOTnvaTMy70l8wJEKs4smfobL5zvu7rspWr/mqyw/S7Ggzo3z+DnkIsypvjRRgmZ7j 9Edg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736948182; x=1737552982; 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=YDhR0wZS7ts5Hgraw2zWBvxuj4q+PFH0DkTWwrU34Og=; b=bTWJRmXH27dmKN2TL+kIQjW3dWh3rKCgsW6FZox+Z+zgjHqp9wX0nmQLrfNOtHyoQ0 VPRma4swF13/oTR36Vz+wPTTSHAZiVsbSF6kDMY/Duv52B+dWG2ca63rI8tKZt3dHuK5 iDPErp8a1AMHQG29pljz77WO0EcTo1Tv3GPY6S+/0N3SYYvsRI/v9zwmABa9Bog3orM8 ZpoDfSKmirOvqbYVko5Jo/5iekT1zCmhtC9cfiZA17MnIFYV11ZAVi8iVL03l6k4fVKZ 66/qQJFumNQGfU1RKtH3NpYaqeqOCbXdbR2CxZrbVjs+gFbHOXFuum03qzzi2xYaASdW nLkA== X-Forwarded-Encrypted: i=1; AJvYcCUcZquq9oijxh9Zz7DqfA7S+tQ4ksDgfKFSP3SdlfhtbfIgRpzln+BkEnLaxvl5FALQkp4fsMDdSnYZ6+g=@vger.kernel.org X-Gm-Message-State: AOJu0YyvBZkIAWA2z1EX8ce60R2D1loAjKkk6rXjp9+CoPi0kh+r3yjG xBNUIyrC80k86rq/XVH340yNBiT8Gmz4g6kXRd1fCf/4AuvbopKomK1ig6WIpADINUXNBkQohjU u2Hu3KzN84dFXOg== X-Google-Smtp-Source: AGHT+IGFHQJdwt5YPoPxZfBaIutfQ8q4HgoaMKHTjrC0thoiPd+KnDkvpCu6E3x9F6CpQFEGaWKYx3hHr0HQTaA= X-Received: from wmqa11.prod.google.com ([2002:a05:600c:348b:b0:434:a8d7:e59b]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1588:b0:436:747d:55c9 with SMTP id 5b1f17b1804b1-437c6af20d2mr23578795e9.5.1736948182452; Wed, 15 Jan 2025 05:36:22 -0800 (PST) Date: Wed, 15 Jan 2025 13:35:11 +0000 In-Reply-To: <20250115-vma-v12-0-375099ae017a@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250115-vma-v12-0-375099ae017a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=18083; i=aliceryhl@google.com; h=from:subject:message-id; bh=8+9yOLbQvy2W2D3bb6/KIfbQXKfIeZCeNeOPvjLjO40=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnh7nB4k4e6GSUVjgK9NZzvzQOqImChi4oNAUub MRzxgN0iamJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ4e5wQAKCRAEWL7uWMY5 Ri1iD/47/BY10kHU19L8JbN8KWkVyDiDY0mn9KC60V92hs44qQhmMFGFVpYGuixI4cFmAId3ZYa 0cBeFxMG2RRWp0UYQqaPdkXv0laWFtK3CsgFaM79vu0cNHOIYNM+JM6R2pGzy/fonmaNJ6+jbpp +r+idgCFwJkGC3XAzP81VEfY5dE20IvewCYxgUIp9tv4h7NC1zUl1FjZx0Vu9wgdKzEUuDgg/bq UZTSjkDhZ4znhzzEJExfS6lKyWYgnWNS8snn5wcifGJxYrn2Qq3XnGohPvDoqrZIQXyvjcxkmqL aglzC5KFH729r95zSCmwCg1QcQb/1u5l0P1Yl5Dfh4b3867lQ8crRMgPbdIt68loMTCzzsG8vED HjqcnYiJ+84cGw4BPAHPZ4wx7HVLnwNy3qkAijje86EAktfeYnSofOCTlc7s8+tHzts1RvWBaa3 TsGO4QDBjJ+Wj14aZXr43rYzZ+fupGJeyf0PITxZoZY5NkjFqGmMe1umOVZuQZuo/GJC9hwds7z jFoHtOOlfWZBEk007a3/xV0Kt6smk3yr9TSlJ32bRurWpFKJRiQKQdJkttbmCK1+6rl5U+xYBfQ FEwR4s4vsoFBUdzRWn0CDcX/2vZ3qshm4TVtoTjEV3WunEPngnUCMpnIfZkcPeIWhgt4Y8i9zlP D/MoHcva98F0DUg== X-Mailer: b4 0.13.0 Message-ID: <20250115-vma-v12-8-375099ae017a@google.com> Subject: [PATCH v12 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 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.0.rc2.279.g1de40edade-goog