From nobody Fri Mar 14 08:10:24 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 0C940214201 for ; Thu, 13 Feb 2025 11:04:40 +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=1739444683; cv=none; b=vF5Rf0diP8YPiQNrC1BlgP5fndBP+dt18exokkEECyE3CscaIwWcluAijCoo0NUElOoY0BS5523K864wHCPmFTkFDJ45OYjRMYnSqYZGbC/Z6I0UBBxnAikMyvlMIL1PPht275fNSd6rVotpXOJlL/aTNcQShJO39mef/5HJnqk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739444683; c=relaxed/simple; bh=dLD6cHWVgf4Y0Wdnlt3dpV8a6zt+QppcLE+M4FISSKQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=Ax+O30lePkfB5/l5MqI5vY2HR8ITtEt5wdmePZ3MfM371mz6y5t9ONR2ma0ZWCTDEXXF2GXZ4BYSv7QMeoElvegk+6jPDVGEsWWc+C9Aln+jdAssAc5d/oT03rosmmkx+z+1G2sRCF8CNZRy8GbnvVRhmrAeApE8P0GT4e11AwM= 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=PVMAj98W; 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="PVMAj98W" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43961fb0bafso2749925e9.2 for ; Thu, 13 Feb 2025 03:04:40 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739444679; x=1740049479; 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=w9c//+puMEPIu02W9GqdsmxdftBKhgzEpRqTvLiOh1g=; b=PVMAj98W6nWrFb39qsdLZLTw5mxkM9NOSa+Hnb12iT20lZnVyQcpszluhHrq7iCK77 Qpqrvz+cmzNnr8gXWaUo0s3i5v3latcnxDECNWTdSXjv0GCBxjM9nKrgtTbdn9D0dyaC OfRvBpsFtX+udotCxg+lVNbpYz/9ZYhOL2gDEy79lqtAv6/UQCHR3v5h8BGotvSqcSrR d5CwIoeXV1mHehm/31ldkTWOQLxDUZtoholZnr9ZLbqKQNFYaCyT582zlqzZ445yzbcB SPCxtYlA3+a66ejJ40w1bUWsNPIsdYRFpgBcYamWTGBSE9sAXTzQH53LrJR0YQjKcFdX LWAw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739444679; x=1740049479; 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=w9c//+puMEPIu02W9GqdsmxdftBKhgzEpRqTvLiOh1g=; b=MbA+1TF1mOD2i+Rade58FRiU9UoTdQQ26ucp9StDSveg6Cp5nvXf8oMqrMHZIo6pgK zqOO7oLcpx1VSSpiLzxtTZb0PS3NnEPxOKvxFeLpJhkgb7ATYhWQYD9LufibIXG2OaF5 juProimOIk1qh3t07wT6Zgq9cE2MYSzsfiEn7o2t9DlqC28vElYjdHdV+RdkqBUODZcS hEchBBvdUr5eXMyqDyfdRSmhTjudDkytRJoo4jt7pIoEyOSTy+72lyT6oOa6t1WmSJtk VukWBr+pvnRWA8jvV5h2+gBFeRauCOeyYALkklalNyprABAA3/M4H9lfhbVyQ+Iin/pl Z64g== X-Forwarded-Encrypted: i=1; AJvYcCXRdWmArsKnrRUCS3NRfaYN97nthpd4RxuniCZ7xOsk9D7yp4A4ZgXoopvuRCEz3UswXOUUo6ko47a9F0s=@vger.kernel.org X-Gm-Message-State: AOJu0YyUuxzguzQib/CzzKn/BG4ghAn5JYnm4ueyJqQkP+/0tveG8B2s PZTDPwCgK6LeSirXrhDFOoTM+k+K1KYG+ouMGqfQrYteNS31Vr7GdRm9zQegBbFiQCffrw9yGH4 oveEhLNV4svX/Dg== X-Google-Smtp-Source: AGHT+IHbYFtzmogXBg9MKVnhQ13dP/0PgnaMmx1EqoIKBkmnDNwv9gD8FAc5s4pngUmvqFUXCOowllHdgVlDphw= X-Received: from wmbay19.prod.google.com ([2002:a05:600c:1e13:b0:439:5636:735f]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:46cc:b0:439:54d3:d076 with SMTP id 5b1f17b1804b1-439601694e7mr26033985e9.1.1739444679495; Thu, 13 Feb 2025 03:04:39 -0800 (PST) Date: Thu, 13 Feb 2025 11:04:00 +0000 In-Reply-To: <20250213-vma-v14-0-b29c47ab21f5@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250213-vma-v14-0-b29c47ab21f5@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=10247; i=aliceryhl@google.com; h=from:subject:message-id; bh=dLD6cHWVgf4Y0Wdnlt3dpV8a6zt+QppcLE+M4FISSKQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnrdG+XF/CRGicj29lFaft2zXQGBxQrOuGoT+gX gCTVXTMW2yJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ63RvgAKCRAEWL7uWMY5 RowED/9wPP/m0yVmu3CtDvLxBZkr/NFB0Ykbc1trzp07J536Dy+CvTd4+mxPHKf7fjYyQ5yOM67 420cGv5bXr9WLCKJAlouRfe5bWz3QrQeT0kRtlomkO4/viLZkkLwSfsmaocEtLFgAIrfZ3nDgFU sYPUKgV3lbeNpk4vVKgea0YwsSOKvH1Kx7sC0p/Yv0TfAbpFAn4MKggcxL0KCP28+zgYn9Bw3hX qFZlZwxn3XNw5lbYN0B1GQWH+vmFl3AJapms3E2pO0ekZkB1PiM56H6PWgvRuc8OkEmVqeWDfpe AQbUuB2ydzSyVu7Xjh+yUCRDp+VxH580NVduHrptwMC1jKjkHrKQB8aaISG5c74kxzOocK5QlRL 9cDzGyIwxfpwczktY7Ks5MnuM2b9F5FfqbnscuSsIqSuciGngIbCDaLTTMRlyuMMini0aQ20PIf vTi7zYUQ6sRQcbiWLiOZakX7PUOAc9ZkdMcc0HegaWwMuyrr62twXCl5ScjEZC1UcRi+AKuV9i9 sUx0YkYqewiFtH8vl5Ti+MDgN/+R70XAxjlNPy4ri51cde1yYBM+QKU0YZgvkN+y1g5g9TPevK6 1vZwENcZYQN87Fxomcqn+JTXGIcpA/B2+47TeuwP4LcOmTzuJqK9C136EQdqGpBJsL3lf0OWQV/ VxK2B9Fk9lXYRFQ== X-Mailer: b4 0.13.0 Message-ID: <20250213-vma-v14-1-b29c47ab21f5@google.com> Subject: [PATCH v14 1/8] mm: rust: add abstraction for struct mm_struct From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Balbir Singh Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable These abstractions allow you to reference a `struct mm_struct` using both mmgrab and mmget refcounts. This is done using two Rust types: * Mm - represents an mm_struct where you don't know anything about the value of mm_users. * MmWithUser - represents an mm_struct where you know at compile time that mm_users is non-zero. This allows us to encode in the type system whether a method requires that mm_users is non-zero or not. For instance, you can always call `mmget_not_zero` but you can only call `mmap_read_lock` when mm_users is non-zero. The struct is called Mm to keep consistency with the C side. The ability to obtain `current->mm` is added later in this series. Acked-by: Lorenzo Stoakes Acked-by: Balbir Singh Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl Acked-by: Liam R. Howlett Reviewed-by: Gary Guo --- rust/helpers/helpers.c | 1 + rust/helpers/mm.c | 39 +++++++++ rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 209 +++++++++++++++++++++++++++++++++++++++++++++= ++++ 4 files changed, 250 insertions(+) diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 0640b7e115be..97cfc2d29f5e 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -18,6 +18,7 @@ #include "io.c" #include "jump_label.c" #include "kunit.c" +#include "mm.c" #include "mutex.c" #include "page.c" #include "platform.c" diff --git a/rust/helpers/mm.c b/rust/helpers/mm.c new file mode 100644 index 000000000000..7201747a5d31 --- /dev/null +++ b/rust/helpers/mm.c @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include +#include + +void rust_helper_mmgrab(struct mm_struct *mm) +{ + mmgrab(mm); +} + +void rust_helper_mmdrop(struct mm_struct *mm) +{ + mmdrop(mm); +} + +void rust_helper_mmget(struct mm_struct *mm) +{ + mmget(mm); +} + +bool rust_helper_mmget_not_zero(struct mm_struct *mm) +{ + return mmget_not_zero(mm); +} + +void rust_helper_mmap_read_lock(struct mm_struct *mm) +{ + mmap_read_lock(mm); +} + +bool rust_helper_mmap_read_trylock(struct mm_struct *mm) +{ + return mmap_read_trylock(mm); +} + +void rust_helper_mmap_read_unlock(struct mm_struct *mm) +{ + mmap_read_unlock(mm); +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 496ed32b0911..9cf35fbff356 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -57,6 +57,7 @@ pub mod kunit; pub mod list; pub mod miscdevice; +pub mod mm; #[cfg(CONFIG_NET)] pub mod net; pub mod of; diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs new file mode 100644 index 000000000000..2fb5f440af60 --- /dev/null +++ b/rust/kernel/mm.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Memory management. +//! +//! This module deals with managing the address space of userspace process= es. Each process has an +//! instance of [`Mm`], which keeps track of multiple VMAs (virtual memory= areas). Each VMA +//! corresponds to a region of memory that the userspace process can acces= s, and the VMA lets you +//! control what happens when userspace reads or writes to that region of = memory. +//! +//! C header: [`include/linux/mm.h`](srctree/include/linux/mm.h) + +use crate::{ + bindings, + types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque}, +}; +use core::{ops::Deref, ptr::NonNull}; + +/// A wrapper for the kernel's `struct mm_struct`. +/// +/// This represents the address space of a userspace process, so each proc= ess has one `Mm` +/// instance. It may hold many VMAs internally. +/// +/// There is a counter called `mm_users` that counts the users of the addr= ess space; this includes +/// the userspace process itself, but can also include kernel threads acce= ssing the address space. +/// Once `mm_users` reaches zero, this indicates that the address space ca= n be destroyed. To access +/// the address space, you must prevent `mm_users` from reaching zero whil= e you are accessing it. +/// The [`MmWithUser`] type represents an address space where this is guar= anteed, and you can +/// create one using [`mmget_not_zero`]. +/// +/// The `ARef` smart pointer holds an `mmgrab` refcount. Its destructo= r may sleep. +/// +/// # Invariants +/// +/// Values of this type are always refcounted using `mmgrab`. +/// +/// [`mmget_not_zero`]: Mm::mmget_not_zero +#[repr(transparent)] +pub struct Mm { + mm: Opaque, +} + +// SAFETY: It is safe to call `mmdrop` on another thread than where `mmgra= b` was called. +unsafe impl Send for Mm {} +// SAFETY: All methods on `Mm` can be called in parallel from several thre= ads. +unsafe impl Sync for Mm {} + +// SAFETY: By the type invariants, this type is always refcounted. +unsafe impl AlwaysRefCounted for Mm { + #[inline] + fn inc_ref(&self) { + // SAFETY: The pointer is valid since self is a reference. + unsafe { bindings::mmgrab(self.as_raw()) }; + } + + #[inline] + unsafe fn dec_ref(obj: NonNull) { + // SAFETY: The caller is giving up their refcount. + unsafe { bindings::mmdrop(obj.cast().as_ptr()) }; + } +} + +/// A wrapper for the kernel's `struct mm_struct`. +/// +/// This type is like [`Mm`], but with non-zero `mm_users`. It can only be= used when `mm_users` can +/// be proven to be non-zero at compile-time, usually because the relevant= code holds an `mmget` +/// refcount. It can be used to access the associated address space. +/// +/// The `ARef` smart pointer holds an `mmget` refcount. Its de= structor may sleep. +/// +/// # Invariants +/// +/// Values of this type are always refcounted using `mmget`. The value of = `mm_users` is non-zero. +#[repr(transparent)] +pub struct MmWithUser { + mm: Mm, +} + +// SAFETY: It is safe to call `mmput` on another thread than where `mmget`= was called. +unsafe impl Send for MmWithUser {} +// SAFETY: All methods on `MmWithUser` can be called in parallel from seve= ral threads. +unsafe impl Sync for MmWithUser {} + +// SAFETY: By the type invariants, this type is always refcounted. +unsafe impl AlwaysRefCounted for MmWithUser { + #[inline] + fn inc_ref(&self) { + // SAFETY: The pointer is valid since self is a reference. + unsafe { bindings::mmget(self.as_raw()) }; + } + + #[inline] + unsafe fn dec_ref(obj: NonNull) { + // SAFETY: The caller is giving up their refcount. + unsafe { bindings::mmput(obj.cast().as_ptr()) }; + } +} + +// Make all `Mm` methods available on `MmWithUser`. +impl Deref for MmWithUser { + type Target =3D Mm; + + #[inline] + fn deref(&self) -> &Mm { + &self.mm + } +} + +// These methods are safe to call even if `mm_users` is zero. +impl Mm { + /// Returns a raw pointer to the inner `mm_struct`. + #[inline] + pub fn as_raw(&self) -> *mut bindings::mm_struct { + self.mm.get() + } + + /// Obtain a reference from a raw pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` points at an `mm_struct`, and th= at it is not deallocated + /// during the lifetime 'a. + #[inline] + pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_struct) -> &'a Mm { + // SAFETY: Caller promises that the pointer is valid for 'a. Layou= ts are compatible due to + // repr(transparent). + unsafe { &*ptr.cast() } + } + + /// Calls `mmget_not_zero` and returns a handle if it succeeds. + #[inline] + pub fn mmget_not_zero(&self) -> Option> { + // SAFETY: The pointer is valid since self is a reference. + let success =3D unsafe { bindings::mmget_not_zero(self.as_raw()) }; + + if success { + // SAFETY: We just created an `mmget` refcount. + Some(unsafe { ARef::from_raw(NonNull::new_unchecked(self.as_ra= w().cast())) }) + } else { + None + } + } +} + +// These methods require `mm_users` to be non-zero. +impl MmWithUser { + /// Obtain a reference from a raw pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` points at an `mm_struct`, and th= at `mm_users` remains + /// non-zero for the duration of the lifetime 'a. + #[inline] + pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_struct) -> &'a MmW= ithUser { + // SAFETY: Caller promises that the pointer is valid for 'a. The l= ayout is compatible due + // to repr(transparent). + unsafe { &*ptr.cast() } + } + + /// Lock the mmap read lock. + #[inline] + pub fn mmap_read_lock(&self) -> MmapReadGuard<'_> { + // SAFETY: The pointer is valid since self is a reference. + unsafe { bindings::mmap_read_lock(self.as_raw()) }; + + // INVARIANT: We just acquired the read lock. + MmapReadGuard { + mm: self, + _nts: NotThreadSafe, + } + } + + /// Try to lock the mmap read lock. + #[inline] + pub fn mmap_read_trylock(&self) -> Option> { + // SAFETY: The pointer is valid since self is a reference. + let success =3D unsafe { bindings::mmap_read_trylock(self.as_raw()= ) }; + + if success { + // INVARIANT: We just acquired the read lock. + Some(MmapReadGuard { + mm: self, + _nts: NotThreadSafe, + }) + } else { + None + } + } +} + +/// A guard for the mmap read lock. +/// +/// # Invariants +/// +/// This `MmapReadGuard` guard owns the mmap read lock. +pub struct MmapReadGuard<'a> { + mm: &'a MmWithUser, + // `mmap_read_lock` and `mmap_read_unlock` must be called on the same = thread + _nts: NotThreadSafe, +} + +impl Drop for MmapReadGuard<'_> { + #[inline] + fn drop(&mut self) { + // SAFETY: We hold the read lock by the type invariants. + unsafe { bindings::mmap_read_unlock(self.mm.as_raw()) }; + } +} --=20 2.48.1.502.g6dc24dfdaf-goog From nobody Fri Mar 14 08:10:24 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 2A46E2144A0 for ; Thu, 13 Feb 2025 11:04:42 +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=1739444685; cv=none; b=krXG3VFuQA2sOHqpkTuwaPb2UYis0xOGmR5teaidk2jbroO76dFPSNztqo2RPnS8pif3Z7BbqAzpevgEJQNkof/IjB1u34JntL5BS96n4HtOrXh0TUapoiNkSuC7iNFGG1nbAuZZH7xyy5aGXK0wWJdlOBvhX+zofbcoelVfBHo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739444685; c=relaxed/simple; bh=Q0RIStyPwKILnX2Vrxa7XEF9eaYk5DS6vlU3U+wI2SI=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=SMSfJDvVnB1GNGrFov1OatauvbidWeVM7O/i3o/2el1c8w3fO81CKDUDc6evN0n9XEtbRoqAvD+f4CPnCZcat6XoZMuCHfebCsRAshxjsO5OSsqsT4cX/plkN58X3hQyewQ+BbEgJRdfHhIeq9bQUpA/eU/H7l8ywsD6bMOOvNw= 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=xHzhgZ4s; 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="xHzhgZ4s" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43935e09897so5399745e9.1 for ; Thu, 13 Feb 2025 03:04:42 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739444681; x=1740049481; 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=za3474x0ZF8AMlWXSEpyVL59vkrxbiA4YbQOJZDWTjE=; b=xHzhgZ4slyL4IiMwPNyHdkuTs6geuUXsF127YGxxJXOPc0nwkEpVpL07Jmaedwnaay QKKLp28qNkZfqpmJ8ywqzwDQs6toJbESJgBzW5lwYCO1LWwTISaQzk2uR7ObEWba6eXu gquNlCBy2geTKrSaycxjoWVlx2KE4KSujXeIjo6LtsZRsr1yFgpW60jHZe461DKWPsXA BrnpHWR8v4CEd0tAgAYn3wa/66jmn1hSsxgQHSttup0sLBP39TIzCZdxDZ3aMP8sBhH1 XEOSwqkHFZDj2zBqA7Zow6iRMmhsp126PE3n47AxdABc1OAuhORiVVxzLD/kPuI+ot1x tH4A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739444681; x=1740049481; 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=za3474x0ZF8AMlWXSEpyVL59vkrxbiA4YbQOJZDWTjE=; b=GH/IY/sIwnH+uoODEyu79ujuuQ5RUAsC1qOxio3dytcU65OegTw/ZTIpT8lk+J1CGS p8492Z+Jz2lE1CSeOfWxTZz15Dele9mi441Jsv8ivj0ftHL4I9hVUlLHkHaN3HX8f+Wc Q+zEjSjjXOTlKh3Vf4DwTtHHZ47AUFKXhvFvUSPILc3+cft3s8FL2/nwcDolhbY/LX79 G6LWKIVJX7evO7RnbXqb7fl/Rh3vxAocTm/k0M1Fj/viFnus9VwXB4nHljKCnJC3vpvm qObxcLLpdcwKau+vXM97DlGu7A2KK4tPxS2TQxFnI0areie/SWN4bL/i/5IiU6JXTUId HXBw== X-Forwarded-Encrypted: i=1; AJvYcCXG7rTmvXZHNarjGqBrjmT9KQF9bBpl5lIYMWJ4jGRiMOyAbfxqKl5UrjJVVUKF3EF/Ze0pZ0zPc0VkY8E=@vger.kernel.org X-Gm-Message-State: AOJu0YwOXQH+C9l3nV8Sr92yESbJ6yjLqmQGg+sdHExZBSU8GpQoCHqg a08Niian4KcTPvdcUcjb6a7kxlwQzR8JtvDiQlaADU5CANhuIkKLdNjYPGh3uJ25mr99sR4gcYp xpV09zQJ6I2twJQ== X-Google-Smtp-Source: AGHT+IFqQez3BgoQ7uNF4wdhzNnxr+PJ45L8RFg6wDi/c48ndpBoPVBo6FJ8W7vBko0MJMPWmUUseOsLeSI1Ix8= X-Received: from wmbhg21.prod.google.com ([2002:a05:600c:5395:b0:438:e219:3af5]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a5d:6d02:0:b0:38d:e092:3d18 with SMTP id ffacd0b85a97d-38dea2fa0bemr6387327f8f.50.1739444681571; Thu, 13 Feb 2025 03:04:41 -0800 (PST) Date: Thu, 13 Feb 2025 11:04:01 +0000 In-Reply-To: <20250213-vma-v14-0-b29c47ab21f5@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250213-vma-v14-0-b29c47ab21f5@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=11820; i=aliceryhl@google.com; h=from:subject:message-id; bh=Q0RIStyPwKILnX2Vrxa7XEF9eaYk5DS6vlU3U+wI2SI=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnrdG+2HO72aNkovdBvp3nh2Z3b2jBiNHTe+tqw Gxn7dLgjsyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ63RvgAKCRAEWL7uWMY5 RhIKD/4whgGT2Jm8XqQ/u4jOaeumFx8NScl5ogOyGNK8zZE+jXjy8Oz+TgqxjHe7H+HRKfu8i28 aWz7Dyts7C3Lv2/bxafa2+6D5UZXQJ9cCjCp+iv0sExbz481iaIgCOQRrv+avMXzxfg+UYOo6ze WukLXyjJP6Xmj1kCLPJL9g95WYH/mAR3r36vfW5RmHGX5m5hjfXglA5NE1sguHGUat+pOZxv8qM VMDq3nbd4/O7WNNJVmc613d2m4I6FotyyRKP0PN2N/7IVeQoZ6vyZkHR6CjI6eYaXRSTsYy2XzY LybS//m56IDMY2S2M0Z3yhwdGQG41gk7xTPOP2ELlCnUE0nKaaKaWV2y1tcV7dBNVOj4ZTNaspE 5i0UBvdaGyalGeYgXIPuTZJZXNR/oN+PHQgl1Dw6gPlyUqo3tP7gvH8Ce2fm0ai4wLD86dSSwp/ X3T1BTVLHbciDkzEUIiifAQrcKGJrdrh3f06rdAia4sozXdSuy4dyC5Bvl/qKhpGCQGKHCzycSO xEulzrYlQ3LLIOlIZDm7FlBg5gCj3zvHr00N8MoPCHaRqVsZUCwIkIEunqQVmQHMtyoYK6GZVcA 8Y6w0K0NXKvzaAEnSiIDTYMm2Euiwq2Otr7WgG1rPyYYp6zpPNAH8meEf2gXp/zC2VMziO3GutN eonf2T4A+n0jtbw== X-Mailer: b4 0.13.0 Message-ID: <20250213-vma-v14-2-b29c47ab21f5@google.com> Subject: [PATCH v14 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 VmaRef 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 &VmaRef in safe Rust code. This patch only provides a way to lock the mmap read lock, but a follow-up patch also provides a way to just lock the vma read lock. Acked-by: Lorenzo Stoakes Reviewed-by: Jann Horn Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl Acked-by: Liam R. Howlett Reviewed-by: Gary Guo --- rust/helpers/mm.c | 6 ++ rust/kernel/mm.rs | 23 ++++++ rust/kernel/mm/virt.rs | 210 +++++++++++++++++++++++++++++++++++++++++++++= ++++ 3 files changed, 239 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..8b19dde24978 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,27 @@ 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::VmaRef> { + // SAFETY: By the type invariants we hold the mmap read guard, so = we can safely call this + // method. Any value is okay for `vma_addr`. + let vma =3D unsafe { bindings::vma_lookup(self.mm.as_raw(), vma_ad= dr) }; + + if vma.is_null() { + None + } else { + // SAFETY: We just checked that a vma was found, so the pointe= r references a valid vma. + // + // Furthermore, the returned vma is still under the protection= of the read lock guard + // and can be used while the mmap read lock is still held. Tha= t the vma is not used + // after the MmapReadGuard gets dropped is enforced by the bor= row-checker. + unsafe { Some(virt::VmaRef::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..a66be649f0b8 --- /dev/null +++ b/rust/kernel/mm/virt.rs @@ -0,0 +1,210 @@ +// 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. +//! [`VmaRef`] is used when you hold the mmap or vma read lock. Using the = 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 VmaRef { + 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 VmaRef { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is valid for the duration of 'a, an= d that the mmap or vma + /// read lock (or stronger) is held for at least the duration of 'a. + #[inline] + pub unsafe fn from_raw<'a>(vma: *const bindings::vm_area_struct) -> &'= a Self { + // SAFETY: The caller ensures that the invariants are satisfied fo= r the duration of 'a. + unsafe { &*vma.cast() } + } + + /// Returns a raw pointer to this area. + #[inline] + pub fn as_ptr(&self) -> *mut bindings::vm_area_struct { + self.vma.get() + } + + /// Access the underlying `mm_struct`. + #[inline] + pub fn mm(&self) -> &MmWithUser { + // SAFETY: By the type invariants, this `vm_area_struct` is valid = and we hold the mmap/vma + // read lock or stronger. This implies that the underlying mm has = a non-zero value of + // `mm_users`. + unsafe { MmWithUser::from_raw((*self.as_ptr()).vm_mm) } + } + + /// Returns the flags associated with the virtual memory area. + /// + /// The possible flags are a combination of the constants in [`flags`]. + #[inline] + pub fn flags(&self) -> vm_flags_t { + // SAFETY: By the type invariants, the caller holds at least the m= map read lock, so this + // access is not a data race. + unsafe { (*self.as_ptr()).__bindgen_anon_2.vm_flags } + } + + /// Returns the (inclusive) start address of the virtual memory area. + #[inline] + pub fn start(&self) -> usize { + // SAFETY: By the type invariants, the caller holds at least the m= map read lock, so this + // access is not a data race. + unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_sta= rt } + } + + /// Returns the (exclusive) end address of the virtual memory area. + #[inline] + pub fn end(&self) -> usize { + // SAFETY: By the type invariants, the caller holds at least the m= map read lock, so this + // access is not a data race. + unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_end= } + } + + /// Zap pages in the given page range. + /// + /// This clears page table mappings for the range at the leaf level, l= eaving all other page + /// tables intact, and freeing any memory referenced by the VMA in thi= s range. That is, + /// anonymous memory is completely freed, file-backed memory has its r= eference count on page + /// cache folio's dropped, any dirty data will still be written back t= o disk as usual. + /// + /// It may seem odd that we clear at the leaf level, this is however a= product of the page + /// table structure used to map physical memory into a virtual address= space - each virtual + /// address actually consists of a bitmap of array indices into page t= ables, which form a + /// hierarchical page table level structure. + /// + /// As a result, each page table level maps a multiple of page table l= evels below, and thus + /// span ever increasing ranges of pages. At the leaf or PTE level, we= map the actual physical + /// memory. + /// + /// It is here where a zap operates, as it the only place we can be ce= rtain of clearing without + /// impacting any other virtual mappings. It is an implementation deta= il as to whether the + /// kernel goes further in freeing unused page tables, but for the pur= poses of this operation + /// we must only assume that the leaf level is cleared. + #[inline] + pub fn zap_page_range_single(&self, address: usize, size: usize) { + let (end, did_overflow) =3D address.overflowing_add(size); + if did_overflow || address < self.start() || self.end() < end { + // TODO: call WARN_ONCE once Rust version of it is added + return; + } + + // SAFETY: By the type invariants, the caller has read access to t= his VMA, which is + // sufficient for this method call. This method has no requirement= s on the vma flags. The + // address range is checked to be within the vma. + unsafe { + bindings::zap_page_range_single(self.as_ptr(), address, size, = core::ptr::null_mut()) + }; + } +} + +/// The integer type used for vma flags. +#[doc(inline)] +pub use bindings::vm_flags_t; + +/// All possible flags for [`VmaRef`]. +pub mod flags { + use super::vm_flags_t; + use crate::bindings; + + /// No flags are set. + pub const NONE: vm_flags_t =3D bindings::VM_NONE as _; + + /// Mapping allows reads. + pub const READ: vm_flags_t =3D bindings::VM_READ as _; + + /// Mapping allows writes. + pub const WRITE: vm_flags_t =3D bindings::VM_WRITE as _; + + /// Mapping allows execution. + pub const EXEC: vm_flags_t =3D bindings::VM_EXEC as _; + + /// Mapping is shared. + pub const SHARED: vm_flags_t =3D bindings::VM_SHARED as _; + + /// Mapping may be updated to allow reads. + pub const MAYREAD: vm_flags_t =3D bindings::VM_MAYREAD as _; + + /// Mapping may be updated to allow writes. + pub const MAYWRITE: vm_flags_t =3D bindings::VM_MAYWRITE as _; + + /// Mapping may be updated to allow execution. + pub const MAYEXEC: vm_flags_t =3D bindings::VM_MAYEXEC as _; + + /// Mapping may be updated to be shared. + pub const MAYSHARE: vm_flags_t =3D bindings::VM_MAYSHARE as _; + + /// Page-ranges managed without `struct page`, just pure PFN. + pub const PFNMAP: vm_flags_t =3D bindings::VM_PFNMAP as _; + + /// Memory mapped I/O or similar. + pub const IO: vm_flags_t =3D bindings::VM_IO as _; + + /// Do not copy this vma on fork. + pub const DONTCOPY: vm_flags_t =3D bindings::VM_DONTCOPY as _; + + /// Cannot expand with mremap(). + pub const DONTEXPAND: vm_flags_t =3D bindings::VM_DONTEXPAND as _; + + /// Lock the pages covered when they are faulted in. + pub const LOCKONFAULT: vm_flags_t =3D bindings::VM_LOCKONFAULT as _; + + /// Is a VM accounted object. + pub const ACCOUNT: vm_flags_t =3D bindings::VM_ACCOUNT as _; + + /// Should the VM suppress accounting. + pub const NORESERVE: vm_flags_t =3D bindings::VM_NORESERVE as _; + + /// Huge TLB Page VM. + pub const HUGETLB: vm_flags_t =3D bindings::VM_HUGETLB as _; + + /// Synchronous page faults. (DAX-specific) + pub const SYNC: vm_flags_t =3D bindings::VM_SYNC as _; + + /// Architecture-specific flag. + pub const ARCH_1: vm_flags_t =3D bindings::VM_ARCH_1 as _; + + /// Wipe VMA contents in child on fork. + pub const WIPEONFORK: vm_flags_t =3D bindings::VM_WIPEONFORK as _; + + /// Do not include in the core dump. + pub const DONTDUMP: vm_flags_t =3D bindings::VM_DONTDUMP as _; + + /// Not soft dirty clean area. + pub const SOFTDIRTY: vm_flags_t =3D bindings::VM_SOFTDIRTY as _; + + /// Can contain `struct page` and pure PFN pages. + pub const MIXEDMAP: vm_flags_t =3D bindings::VM_MIXEDMAP as _; + + /// MADV_HUGEPAGE marked this vma. + pub const HUGEPAGE: vm_flags_t =3D bindings::VM_HUGEPAGE as _; + + /// MADV_NOHUGEPAGE marked this vma. + pub const NOHUGEPAGE: vm_flags_t =3D bindings::VM_NOHUGEPAGE as _; + + /// KSM may merge identical pages. + pub const MERGEABLE: vm_flags_t =3D bindings::VM_MERGEABLE as _; +} --=20 2.48.1.502.g6dc24dfdaf-goog From nobody Fri Mar 14 08:10:24 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 4EA6A214200 for ; Thu, 13 Feb 2025 11:04:45 +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=1739444687; cv=none; b=Yxyutim5GETNDltcEhfE4YeefrK34ndzu9oQPG7EE2xQ/wCksUG/dzjMDLMWlmER+wAGa5H6Fm5t/kq0FXACzvdtjlpFBZWdrxiNChNt30/EbUMD+4FdXaaRzUcSdG02eOeA+1TaDjZI5Z34ewQ6bbTB3/+MHkGh5jElSXNqVx0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739444687; c=relaxed/simple; bh=7ZqqtUDXsP1Gbf5JFgD6mksdBLRaKifIQkb0l8YZdwQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=ZlH5UypxM00S4/HH9le8awngn4vBYU27SYa/6jkPUy8PVmCNVwBLpCFlOgk/w24NZaQ7EI4JE/4xZlhfFZDoQfr1RXDJZAIn6Ykizq+eF1Fvaw7tZoJqEw+k3da81hHi5B7i+OR8WuNUXnL2eY28Tvk3YUx0I2Nw+rDnP53egm4= 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=3lj0YoAi; 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="3lj0YoAi" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-4394b8bd4e1so4018335e9.0 for ; Thu, 13 Feb 2025 03:04:45 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739444684; x=1740049484; 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=k8n2CzMf4Ztdvpb33CNEbhu5gkerbPNLl9WXyFXHMr8=; b=3lj0YoAiEJ+rvFY7cJz6x79dNMDH0iIuMS6LRUmzPkO40jq/EA6czkj+GW7/NRKNjT YXGhFx13EKin/m1h/djMk+e1d60/o8XuHCE+9262jd94wqGugkN3KLG4LAqF3US8ILev vzzr8lZHuGkgJh3w5s6OYPkrKFkRtJxlzHu2iAYXMe5FHVXGfgXqOSs3HR+AlATYtR0M 0Gdl6+N7opkGovHWZ7KGYZjhawapQ4VZEAWHLLaoN6oP+0ouOjIocNEycLXC37CEg1jz XRZS+c5vKzNk2xqIxf8qwY3IS+zkNmeyVxvkOCxToWoKQroCnPqQL6ZiRZvKXnQhWcZv dtrg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739444684; x=1740049484; 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=k8n2CzMf4Ztdvpb33CNEbhu5gkerbPNLl9WXyFXHMr8=; b=YCHE876oqkl6CModF+kBqD3XcDSBAHw4Ef8o8NSKpt9hK+TT2UUgx3yryqSOA70dzC 3lARpzaSegtSn7frar3kNMGQMaSzdON48fm/WcOimlpJGoAkgHNGsLGsuSAc8pWUd3/P gDs2/zh76acGXb5jxg8w6aZxEA7lf0cJi1TeNBrD/HYGpQq7ercn3v6wIvYi0Fvj9ztx 8BUpEuUKRvXJ90SIgl+HShzJ1FbpP8WygD0F25SEH90m1iVWlWBQ9jeA1y5+vY1ObrFt f3gjcrUC/2wJBs9FyXnFJR/wRgKIuiCV+jTu3cMGqL+OJqls34dUAIcRB6dfj0i20X9x fYGQ== X-Forwarded-Encrypted: i=1; AJvYcCXBTi62Gi1qLA9mOyt5kPil9d2bMB0Js2UmjFDyELaXTawKLTGJkoxY3F79n9TGhT7JHfZRn3QzNE69VRg=@vger.kernel.org X-Gm-Message-State: AOJu0YybhoSAKexo1dSMddRXvdjSUlsQfOQJaLzxkFVmxYIOMMs5rwlx oN9mVGtCYcsvvW9xpl0c4NHYezwafVPJFwm/5Gbfa7/7cSu6DZ5T0Rc4EvHq+Dr3gtedKt7lH7y z1mAW+wxvk9WPjg== X-Google-Smtp-Source: AGHT+IG/p1umuQ0eJvKQbofKR2QTqEeXJEbd0YG5yn6XEcTENIpdxL45h7o3jCh3ZD60eJkyCoDKaBabKC0ULTw= X-Received: from wmbbh11.prod.google.com ([2002:a05:600c:3d0b:b0:439:45fc:d36d]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:5246:b0:439:643a:c8c4 with SMTP id 5b1f17b1804b1-439643ad059mr10276655e9.22.1739444683950; Thu, 13 Feb 2025 03:04:43 -0800 (PST) Date: Thu, 13 Feb 2025 11:04:02 +0000 In-Reply-To: <20250213-vma-v14-0-b29c47ab21f5@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250213-vma-v14-0-b29c47ab21f5@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4242; i=aliceryhl@google.com; h=from:subject:message-id; bh=7ZqqtUDXsP1Gbf5JFgD6mksdBLRaKifIQkb0l8YZdwQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnrdG/lIDQqsozko862Oxdr+bH9Os+BAM98CkzW TQa1IBfCNyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ63RvwAKCRAEWL7uWMY5 RkmVEACn0Bt1SGwPL8suuc+/47buudaTvg3C0yzMa/mLK3qz1QtjJ/vbqRpsG+2npghIgyqGybL /aoGakDA+MpjDEuSZ48Sj8+IfzZKx2S5QjUFbKImceVUBQ74kG0KaRiwRZ5QDm1AwbnVy+YOTzj s2UHHoDn/+zj5ohSQj084UIiOIW8diiANWVf1SFI3MHTSK92oXMVUUIINrDxr2MHo1QYUaP6upr aXnJ36ntw7Rr04VgFHD54PDsGPqLHO5Re9WOxKQ9dYfibQt6IfQPKOc1qapGkRz33ZzFGnZRmYo igPauwx2md2jJ7jtq4eGsnNcbd4aq5GjD8Yc/mIO63CmITjOlPHq3UdvFDeDRHtC+r+yqFJXN2r gq1yAD+iXjILo4u1V25wO8369fHEMYGWa736PP63qiVSnHYTfY5bPhuuR6hGdEvBAXBjRkvOrvI uK1Papa5R28mD6UPHrUa/KSpUmu8jQQCnqs8hkSXpgpR+sZuLCvQDOq2PZ/KYcf16GPokj1XBrb kdu4UYkD3b+aorFabaCod8DPGo31Koml+GsGR53OQCg6WiKYIZJFbw1IFzh+M3p8HDPei63VpvW cMFE2AmzaRijV5Lv1oxBWfyrJOfMOjBLg7JHzgDODBxphjEiCAXDvR97INrlToJlCDR4oRIt5Ao HuTGjipQymChgVA== X-Mailer: b4 0.13.0 Message-ID: <20250213-vma-v14-3-b29c47ab21f5@google.com> Subject: [PATCH v14 3/8] mm: rust: add vm_insert_page From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable The vm_insert_page method is only usable on vmas with the VM_MIXEDMAP flag, so we introduce a new type to keep track of such vmas. The approach used in this patch assumes that we will not need to encode many flag combinations in the type. I don't think we need to encode more than VM_MIXEDMAP and VM_PFNMAP as things are now. However, if that becomes necessary, using generic parameters in a single type would scale better as the number of flags increases. Acked-by: Lorenzo Stoakes Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl Acked-by: Liam R. Howlett Reviewed-by: Gary Guo --- 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 a66be649f0b8..3e2eabcc2145 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. /// @@ -119,6 +127,75 @@ pub fn zap_page_range_single(&self, address: usize, si= ze: usize) { bindings::zap_page_range_single(self.as_ptr(), address, size, = core::ptr::null_mut()) }; } + + /// If the [`VM_MIXEDMAP`] flag is set, returns a [`VmaMixedMap`] to t= his 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<&VmaMixedMap> { + 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 `VmaRef`. + Some(unsafe { VmaMixedMap::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 [`VmaRef`] except that it must only be use= d 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 VmaMixedMap { + vma: VmaRef, +} + +// Make all `VmaRef` methods available on `VmaMixedMap`. +impl Deref for VmaMixedMap { + type Target =3D VmaRef; + + #[inline] + fn deref(&self) -> &VmaRef { + &self.vma + } +} + +impl VmaMixedMap { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is valid for the duration of 'a, an= d that the mmap read lock + /// (or stronger) is held for at least the duration of 'a. The `VM_MIX= EDMAP` flag must be set. + #[inline] + pub unsafe fn from_raw<'a>(vma: *const bindings::vm_area_struct) -> &'= a Self { + // SAFETY: The caller ensures that the invariants are satisfied fo= r the duration of 'a. + unsafe { &*vma.cast() } + } + + /// Maps a single page at the given address within the virtual memory = area. + /// + /// This operation does not take ownership of the page. + #[inline] + pub fn vm_insert_page(&self, address: usize, page: &Page) -> Result { + // SAFETY: By the type invariant of `Self` caller has read access = and has verified that + // `VM_MIXEDMAP` is set. By invariant on `Page` the page has order= 0. + to_result(unsafe { bindings::vm_insert_page(self.as_ptr(), address= , page.as_ptr()) }) + } } =20 /// The integer type used for vma flags. --=20 2.48.1.502.g6dc24dfdaf-goog From nobody Fri Mar 14 08:10:24 2025 Received: from mail-wr1-f74.google.com (mail-wr1-f74.google.com [209.85.221.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 B20B421481D for ; Thu, 13 Feb 2025 11:04:47 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739444689; cv=none; b=CU84D4p5i+By5E2z3BtGsAcESKZxryXOiJh3+QnD0xi6bib7SgEHEx+uwl9mED3GaThIWZSoPDcsU9FqsJwRh51PABAd20rlxzBo77mbZWYb7ZzvvTv0LZCv5/T4IWr6l8N8/TWtDafkzK3Wfum5FsjH+1Jog+Qf1IaJLVtH5zc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739444689; c=relaxed/simple; bh=7YH1vGH4J5NrwgKxb07UMrGiCmpjxEls6xw94mytwWs=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=hCqbXDKnGAEXIQhx22QCVYmQcqlTmHz4nFkXWF5dSq7NixzqKHasm+bdHP0X3Y82algWVW+l8m0hipc7YC5IT4YqJHxq1Z1/1Nd3P+JbY90t5Q3lMrDbcd11Mzr6WZczELzshj66OLe6EarA8XjeN9w8MlUuuoSOf3JZCqT5hd8= 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=iH27nHe6; arc=none smtp.client-ip=209.85.221.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="iH27nHe6" Received: by mail-wr1-f74.google.com with SMTP id ffacd0b85a97d-38f28a4647eso145971f8f.1 for ; Thu, 13 Feb 2025 03:04:47 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739444686; x=1740049486; 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=/uyBvvUIBqhEGg3k1MSKl3P/NCSf2A+x8xfYmCFIPos=; b=iH27nHe6lHnqVr1/loBq8AkqzfZVPaBixskq5+kuxyCzuh9GBI5dzOJl14bxHBnGbJ 3bqOAUYKVlUC99gLQgQAf3l4cWApVxx0i7aOH4AVjJSeczjxqNOcOliWuI3/WIecQvBJ OhpOOAwZnB85SAbv4n/pEYhsotibWVNwOeYsssxhNXcD0wngydGW8dyoarG6BE9VzHFT XUxCcr8mKBtQWfYANCCfbO/jkpttRMVLq59thlKllBaOUs83Wag1Ix6OJULV6sll1eL2 HTqA073+fGjvQ4yzuiYdXtekNPY2EsZauGMqa+RU05oZ5QjfSp/qb40vRE9odm+R9zUh AJYQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739444686; x=1740049486; 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=/uyBvvUIBqhEGg3k1MSKl3P/NCSf2A+x8xfYmCFIPos=; b=ObFktPQfA8PBDZDdQArB3XcIfTRlg+mlEpSxmpFrVe7PWtURbzEYsQpBKqt/vBETMt zFq4GArIFc4+M2EWL22c/tozrf2Vx3HKhs9RpgDJf5KEFN98PR6Te3GKOkuf0P8cmxGQ NO+T7jsG4UD6GDuNMwSVsVntfh/Wsfoe/Y+kCOJ4v+tAQ1tmlWdgpcvU0PT7lCIaMMPU DY5eVfwfVH3jH7K+diUnYM4Fx/PCK9X/BAlPQdTIG3b7CL+jf0jBelVbKn6jmrvG10oE JrCl2uzCHxirpqzKm8oEr/VkM2Q7lRRsBetF32rv/fZpPKTR83h32O+6N3HLIbnUSOUo ENrQ== X-Forwarded-Encrypted: i=1; AJvYcCVoUiZcE0dozzrqtHMQHfXNAbYjTc7AcHJt27g9aUicrdu7k/KNQuMs5b0uZh9sUKXoyqEdrcKvEu0SufE=@vger.kernel.org X-Gm-Message-State: AOJu0YzIyiGlQi/lMpgGKzR//Ff8N8bMIEWUqHacyklhLxQJfDOEQn7c +b0wm4CMlaq46flQ2yxd/wNXmITM6/2DRZTET9ZgKi5H9G51oxSW4pXBUjU26oESIRuzlPyaps6 unGL3YdmUOkuvXw== X-Google-Smtp-Source: AGHT+IHfpu4LwUir1xs0IVZCM1IC0uXcvmusDtyLHlflipwlekCf6G6k2n3LWvqP3SiylhkkpqKNBH+Ir9bJCqU= X-Received: from wmbay19.prod.google.com ([2002:a05:600c:1e13:b0:439:5636:735f]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3b9e:b0:439:3dc0:29b6 with SMTP id 5b1f17b1804b1-43960169525mr31940045e9.2.1739444686140; Thu, 13 Feb 2025 03:04:46 -0800 (PST) Date: Thu, 13 Feb 2025 11:04:03 +0000 In-Reply-To: <20250213-vma-v14-0-b29c47ab21f5@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250213-vma-v14-0-b29c47ab21f5@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4092; i=aliceryhl@google.com; h=from:subject:message-id; bh=7YH1vGH4J5NrwgKxb07UMrGiCmpjxEls6xw94mytwWs=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnrdHAisosHMy/OP18+ZFSNrfkNK5udMfSbyYBd /UYV8VUP0+JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ63RwAAKCRAEWL7uWMY5 Rto2D/9a3RX0gRbzHxMqA63smy2e5oFZ4X2tYbSXIkyIwN6VWd8YZtH1PcFwUa5wK0pU8XdojFd AYyeERKnFDljzjTqnvwqBfphg0liowGbNq23niy2uCffaJxJo4UFB/Drit3FPKggtxzHYqlSPSs 7luyMeiT/YiEiq1s08asYDvnPjbigsK7Vl5UaX+i6F1pHlNeaJ750Ohu+Z8Ts3OEu/MyCC69Oso 9buHg7+vnmGaOGJHFS4eDB16eYOTTcvgOIZ2ChRuao5jPRoBo2GjNWXxjy4vV7QfGrE4Ji5AqUn IyBvpRKcct/CWYF5YcWkNEDGIvx5sqofRxhE3uhD2+JdwrCefrkQYizdTzFxvFfh7VAAue0FLUa GNmYd2K0SvmP1Oikt07eoNMllm+se3DMiQdMea/I/HQYLf4vH/zEd09fKFYz8O4vsAl/nsIGGyw ulMOzd64acCq2XDNQH9O4ocWZM0V905RHEID9LA86bKDSVZiyp+fgDpbmDkwTMfYhKgTi3hUlVM O+oKYcf9ikY3RTB2rW+zZRdXGN+6G39veH40gcvbcFon8yw4J7Q/gd61g5QGdnKCz+a4skqrcrQ rW24zBO2XYUM9mStTg2QYQbtyTURioRrsA18aFyqz3iWziTvzshu0DHWgtkaeah3hggl6BIqBfb DtcnZcK0amgnBGA== X-Mailer: b4 0.13.0 Message-ID: <20250213-vma-v14-4-b29c47ab21f5@google.com> Subject: [PATCH v14 4/8] mm: rust: add lock_vma_under_rcu From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Currently, the binder driver always uses the mmap lock to make changes to its vma. Because the mmap lock is global to the process, this can involve significant contention. However, the kernel has a feature called per-vma locks, which can significantly reduce contention. For example, you can take a vma lock in parallel with an mmap write lock. This is important because contention on the mmap lock has been a long-term recurring challenge for the Binder driver. This patch introduces support for using `lock_vma_under_rcu` from Rust. The Rust Binder driver will be able to use this to reduce contention on the mmap lock. Acked-by: Lorenzo Stoakes Reviewed-by: Jann Horn Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl Acked-by: Liam R. Howlett Reviewed-by: Gary Guo --- 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 8b19dde24978..618aa48e00a4 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::VmaRef; =20 /// A wrapper for the kernel's `struct mm_struct`. /// @@ -160,6 +161,36 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_st= ruct) -> &'a MmWithUser { unsafe { &*ptr.cast() } } =20 + /// Attempt to access a vma using the vma read lock. + /// + /// This is an optimistic trylock operation, so it may fail if there i= s contention. In that + /// case, you should fall back to taking the mmap read lock. + /// + /// When per-vma locks are disabled, this always returns `None`. + #[inline] + pub fn lock_vma_under_rcu(&self, vma_addr: usize) -> Option> { + #[cfg(CONFIG_PER_VMA_LOCK)] + { + // SAFETY: Calling `bindings::lock_vma_under_rcu` is always ok= ay given an mm where + // `mm_users` is non-zero. + let vma =3D unsafe { bindings::lock_vma_under_rcu(self.as_raw(= ), vma_addr) }; + if !vma.is_null() { + return Some(VmaReadGuard { + // SAFETY: If `lock_vma_under_rcu` returns a non-null = ptr, then it points at a + // valid vma. The vma is stable for as long as the vma= read lock is held. + vma: unsafe { VmaRef::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<'_> { @@ -230,3 +261,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 VmaRef, + // `vma_end_read` must be called on the same thread as where the lock = was taken + _nts: NotThreadSafe, +} + +// Make all `VmaRef` methods available on `VmaReadGuard`. +impl Deref for VmaReadGuard<'_> { + type Target =3D VmaRef; + + #[inline] + fn deref(&self) -> &VmaRef { + self.vma + } +} + +impl Drop for VmaReadGuard<'_> { + #[inline] + fn drop(&mut self) { + // SAFETY: We hold the read lock by the type invariants. + unsafe { bindings::vma_end_read(self.vma.as_ptr()) }; + } +} --=20 2.48.1.502.g6dc24dfdaf-goog From nobody Fri Mar 14 08:10:24 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 D5F9021422E for ; Thu, 13 Feb 2025 11:04:49 +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=1739444691; cv=none; b=GXOH9stTHXuHdA8PiO9rkStuos0U2nAfsBnuEooypuIiOqop2X4AeO0y63nDNDOXiiN3iTyT37hz+AtW3laJXLYPIZ2wfmgs9AZ9WwAAsusfMKOP6K2MMlmVscyPm3ZajxPGE5tJgXAnusarE0v1G16X/DJ0Lr5uo5nq7G88LdQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739444691; c=relaxed/simple; bh=Y+J2tVj51QjuipDpR/j89prtBvkMX66gHrDq3YgpYsQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=Ws05inAFbeKszpk3SRClcKBCtm6wqzCNtTMn+XCjzCHQsjPgpn6vC7BPd65JeA+zh7Rmv0MyCEH6eH/9FUZitDF9KPg1x1NdR6yOMEsGOw8uczoqqhyC7vxqQ+03Dzzhhy7a6UJVt0N+2OG+xqesj7CFVWH29RTt2XxRXFCQoy8= 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=LR41BsWb; 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="LR41BsWb" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43945f32e2dso5520025e9.2 for ; Thu, 13 Feb 2025 03:04:49 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739444688; x=1740049488; 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=CgLb6B+K0IFKSCneh1iu8CxwdcsXLyqW6hdJtG80sPw=; b=LR41BsWb9ipBoHjJV/HB6jwj0jZ4DSOCsJk9hLW9ynxyhTR5JtwwBFH71Ulxv/y4o/ O0Cz9GW/SeBehw7aXiGX6OAcQPpNV27Lectj/BFm7Y8CHQjKs09nC+m2WfUE5yAqnCVJ 8NYw9YmVp8utd9u5ZV1oAOfk2H750n9Hg6Hm676MCxIKu62WDrZcGEJrZRRKEhC0USMe awrz1FwxYuNyhMxJ02pVehzEMvB9QiuS6S7mjCl8RkhpvPnyRllL1vyslZs2vNZ2uhQn o2iHfviXd8iD/YGu+wh8KvQWu/Omrg23CTkCXn41QV+DZMX8J2kozhwaqtJwOTXwO0xM 6QYQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739444688; x=1740049488; 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=CgLb6B+K0IFKSCneh1iu8CxwdcsXLyqW6hdJtG80sPw=; b=RhmsD2kgQ5HLVCigRrCgU8yB/tN61b/Qh325XS+dY1TM+8S9sW0uRQrQJ6LGRZ3u1A InX4OnU8jHiRpX/aizhhRQ7yVGaEH8dK3bjjxbyBfeRJIxL68OQ+59KYVlAVycA5DYX6 LjbxlkdZactPt1pmgo1WlcTLWprIxL40PN8r00Rko08hHMv+xs59/RQEXatJuo0+ZWC/ lIEtnuPIeulXKC+okqoIW3/EmY4Yoprkd/DETX9P4kuc1BaZ7W4UOeyflVph+RtbjzBC WdoWL+jyg90NKHR1H+MfRzKM7TircLYlaVxTTX1um76D+cfaWIwjL+offZDqV7qWDpMt Wing== X-Forwarded-Encrypted: i=1; AJvYcCU9kgsAOg6aDfdwcLEm1bExBB8gX+chkmWVlEQGTAAXzdHjZWYOoiiBUI1HiiNN7jKc4dBcV1puS4ldSLM=@vger.kernel.org X-Gm-Message-State: AOJu0YxD+iZDOSw1FyIxCPyiESUuwisAsVo+zZin0CurgEbsfBpnBlb1 q3IN9n54m63VfqDOUUBPeg40f8bb8dUh6VYU9dc7rlva1QIlFC1S75T8El+uJliMLKZktxyLvkR olab1GWw5o2UWVw== X-Google-Smtp-Source: AGHT+IEE4mERgLHcPxh4Z0XFIOmAvsYP5lm1mfa5000wNXTddJEmQQVgk4sP9gXH2gaDBiy234o63CvPhb4kDSo= X-Received: from wmrn40.prod.google.com ([2002:a05:600c:5028:b0:439:5d9c:5d7e]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:46cc:b0:436:18d0:aa6e with SMTP id 5b1f17b1804b1-43960185e92mr36208335e9.5.1739444688303; Thu, 13 Feb 2025 03:04:48 -0800 (PST) Date: Thu, 13 Feb 2025 11:04:04 +0000 In-Reply-To: <20250213-vma-v14-0-b29c47ab21f5@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250213-vma-v14-0-b29c47ab21f5@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3164; i=aliceryhl@google.com; h=from:subject:message-id; bh=Y+J2tVj51QjuipDpR/j89prtBvkMX66gHrDq3YgpYsQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnrdHABUIA7xn4otWDfLthBx/LSs7Na9aVE8qME MbIMzywdJOJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ63RwAAKCRAEWL7uWMY5 RjJsD/9N/t+Xpj0ZBHju/OxddzbE+XEa6J7uMG5lNLfo03HNmsU7+6msxBvBQJ5vmKKjXjm3x9c oQ6hTWK6bPKhSrlen4dQyjRbw9cwqTxkxsgiLMGpqYZsYazH+ZkFqGJ/jfsq4gKS8grIm0Rj2G+ D10/6vhw9ak557lgN3VdinlGRP3uz2TAMd3uiMGmlNInXAPtA58zBnPDFgrNmvoFWahp559WW6I 20YGQWCPZKHjnbkMUCKsvkUbV18BxMTsLDTA0RIic2VyHQPOn2hB7hkCZOmdSzYtn0wBwZaCwjD ceaujq4uwhd+WV5miM++gFGrD9oJCHg8/ZOkc4ktS3GEoYRLvOVVzfFgCbNuP9YAnCercllEqfY GpfkQhzlFm+//Jxpm4fvqK7SVcfK/wbHpnXqx24ZgF2e+rJRoCrORcAttWL1atKC4oLtF96Q4GY /eZdG2B1Lep6R4PMqWwNOJ0oA7sOd1VvPSpKMs9k8B7dPLICaYDyu/9LWb6Gy47AyIlT2q5i4XD 31iiqx+C7U8sGa0Z9N3uV28UyrkCD9qSFEJZc/0iTVZwnPn9tjuRtmOu5y5iaItpLQn+Wnxv7UL svXiQQz4GpRz1fQx3xZJrfYl8541aByQWVHo//K0h2RGgCSJV55vtoHEr5dKkxDfGptyf/REv5J Q+YfAvaP2OZ/9Vg== X-Mailer: b4 0.13.0 Message-ID: <20250213-vma-v14-5-b29c47ab21f5@google.com> Subject: [PATCH v14 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 Acked-by: Liam R. Howlett Reviewed-by: Gary Guo --- rust/kernel/mm.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs index 618aa48e00a4..42decd311740 100644 --- a/rust/kernel/mm.rs +++ b/rust/kernel/mm.rs @@ -110,6 +110,48 @@ fn deref(&self) -> &Mm { } } =20 +/// A wrapper for the kernel's `struct mm_struct`. +/// +/// This type is identical to `MmWithUser` except that it uses `mmput_asyn= c` when dropping a +/// refcount. This means that the destructor of `ARef` is= safe to call in atomic +/// context. +/// +/// # Invariants +/// +/// Values of this type are always refcounted using `mmget`. The value of = `mm_users` is non-zero. +#[repr(transparent)] +pub struct MmWithUserAsync { + mm: MmWithUser, +} + +// SAFETY: It is safe to call `mmput_async` on another thread than where `= mmget` was called. +unsafe impl Send for MmWithUserAsync {} +// SAFETY: All methods on `MmWithUserAsync` can be called in parallel from= several threads. +unsafe impl Sync for MmWithUserAsync {} + +// SAFETY: By the type invariants, this type is always refcounted. +unsafe impl AlwaysRefCounted for MmWithUserAsync { + fn inc_ref(&self) { + // SAFETY: The pointer is valid since self is a reference. + unsafe { bindings::mmget(self.as_raw()) }; + } + + unsafe fn dec_ref(obj: NonNull) { + // SAFETY: The caller is giving up their refcount. + unsafe { bindings::mmput_async(obj.cast().as_ptr()) }; + } +} + +// Make all `MmWithUser` methods available on `MmWithUserAsync`. +impl Deref for MmWithUserAsync { + type Target =3D MmWithUser; + + #[inline] + fn deref(&self) -> &MmWithUser { + &self.mm + } +} + // These methods are safe to call even if `mm_users` is zero. impl Mm { /// Returns a raw pointer to the inner `mm_struct`. @@ -161,6 +203,13 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_st= ruct) -> &'a MmWithUser { unsafe { &*ptr.cast() } } =20 + /// Use `mmput_async` when dropping this refcount. + #[inline] + pub fn into_mmput_async(me: ARef) -> ARef= { + // SAFETY: The layouts and invariants are compatible. + unsafe { ARef::from_raw(ARef::into_raw(me).cast()) } + } + /// Attempt to access a vma using the vma read lock. /// /// This is an optimistic trylock operation, so it may fail if there i= s contention. In that --=20 2.48.1.502.g6dc24dfdaf-goog From nobody Fri Mar 14 08:10:24 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 CC893215195 for ; Thu, 13 Feb 2025 11:04:51 +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=1739444696; cv=none; b=KLTzJ0Jj5DTEmy5nhrPwAHw7GMmitxH3EUPmv9Un94W3N8KFpJ86uGER3m/CcEGRjUi/c0jMuxZZEZIAKcKw4VELpkefRxrbG0oGWTYuKK6/NiVCk//1GPb93G2MxFEvE4cWeFdQciKIYWv8416/zpc6TI5j5REiSff5uwtjRPk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739444696; c=relaxed/simple; bh=7pYVDkxLGS09DigBqO6pbnQoHpQKADY37T16seVY/5M=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=Oat/decdzkyq/Yrkc96MCd/fAufz6yDs8Y20coEtUQ5zG6t6Eq8nGQWnIu8CFRZKutCrDe/GITG8HRfxE+weowXHtJhdVCNeXvy0MmdwLV8kjnv/usF92juMf7B3o/Wy4KxehnPPK0eCgahzvMfLgEBXdH8evChIdmQgFunhWIs= 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=1d5Hjtbx; 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="1d5Hjtbx" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-38dbdc2926eso644181f8f.2 for ; Thu, 13 Feb 2025 03:04:51 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739444690; x=1740049490; 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=uW/Ty2fOlXPxtDtxLZmFYWp7FZLpKD6TeMqqX/rT2JY=; b=1d5HjtbxRHQLSwemcoIEjR1BD9d8D2ChXvdZ8x4+3g4pq21dR/vL148F1NUPSGe86K KyqGIOx5mvSb5WAKl9dzInKKvYvJD66XBYZgbMZtE3zy6ui7GW4zaL3XoHi5D7zWiHqm 8fBVPnYC0Up8Cr/4gsQYs0lCiqKpJkjWUNHkQRk9o/a+/FCt1ZPD8VU9kC9sz9ck++T0 q2HRI3PiK9aaXIbRfsciYP9h4SDXV8V8gnWvzWTTNymwnm26fKj7YinCIE1vEjBSSDUt qY7zkD0yHz+aj+k/+aZJ8OFI4GnMcfnhEIgavh/2FyJtPHv8GW0vp1EhqP/vCkBwCt+R og6g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739444690; x=1740049490; 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=uW/Ty2fOlXPxtDtxLZmFYWp7FZLpKD6TeMqqX/rT2JY=; b=MffwGcEa91Up4Fl6PIoUAEft2wIFQhqiuVUKMs9v+PaKQaaJkl2ZXaoTbgYA5Mxw4e uWrCKE/bXzoTF8tzSJLQbSBZj6/is9mjlyJBB5XHWloyBWCihyBJtkIYvnRexHuo81iu HeOYMkv4grI9YHHtGX/659UoYgeQaM+QcuQiyAbiw3vazQIvSonkIsnhMX1HKerFxShK upVqs6SByc7OuPxueUloDYouVVAzqQVPPMkgV3lOMyuNwbVWOqSVt4qRtMAPAfGVI1vL 1ujDGN97WFOZ+eTMHKrCVME2nx02xqPYQ7C9Q1SY5YZNMyBZD8C5f/+vMPw+fJgn5azp HAJg== X-Forwarded-Encrypted: i=1; AJvYcCUV+xuUABMHA6P5jyUhXBur03FlpRc1I1PCw7YEsJ9h1tx3flMQd1ZFACAxw+z/sdszlv399pz75RHC9Uk=@vger.kernel.org X-Gm-Message-State: AOJu0YyTZdPBAjLViM+KJJ63sFRBOk35HbBFdrVSUyO9Gv7NplfmzVhx KDUX1HpoHn91zUNvgiG+mgjN+IiIMslFe57jbaoiwtaboARVQQA8LCsZW/kMh6m8k+dQs9aGHNP 0KppqlAbqgGiswg== X-Google-Smtp-Source: AGHT+IFf80WLAYmWuMESuCsRlEKC2D4+AWF643A9VnDB796H1Sc9MR5GfacRO+WmOsDE1DcsoXPNr2jsbgDj6bM= X-Received: from wmpz19.prod.google.com ([2002:a05:600c:a13:b0:439:468e:a94b]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a5d:584c:0:b0:38f:28a1:501d with SMTP id ffacd0b85a97d-38f28a15761mr1140823f8f.25.1739444690305; Thu, 13 Feb 2025 03:04:50 -0800 (PST) Date: Thu, 13 Feb 2025 11:04:05 +0000 In-Reply-To: <20250213-vma-v14-0-b29c47ab21f5@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250213-vma-v14-0-b29c47ab21f5@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8586; i=aliceryhl@google.com; h=from:subject:message-id; bh=7pYVDkxLGS09DigBqO6pbnQoHpQKADY37T16seVY/5M=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnrdHBPqs4jQruLh6dcALn9+kKABa5Ht3oQjY1+ +vcelNnxJGJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ63RwQAKCRAEWL7uWMY5 RoegD/9QReh2ab4/0o7RdV9QbH4EgO9m6OwqpDj+W9QmyXARO7Ruo0kO/4TqUdNIaMCj3jla/KV 30nO+8ABp6pB+ytxxCEuWSbUNhYggNXvQ8yeOS6lQ+cZt4ltoU1HWlPUCLpqof8/DUXQwJxI0ZP gGmJzLTu3akLT46yhxKz2RbPo3uY5snGt2qFQ/dTg88bzz0+t2rQkwv43PkW829KZaCUq1kvflL DWvf3KjhbasZ4O29c89f/lJO4HDBt35g6SeDWNVOSTxZmQrqqkaB9crY+tSORD/SiCR5uYV9lpt gFXf3IJ8vx3toO1pJ4yHzYA3uA+HEzYi4OQyUebkScsjgOAlnLucnMjvl11NfcSbz0qtTVpMrsr A6K/o4ByC4bf4ZVMpf1bDcntvhlu+FGy8rPUr4QJ2GI62qz01/Zbg9lccJw6llQbYQGOh9WAIq8 FLGwqlNQnDw3a1xEkSMstwXjBXg3ZHlnznMRV+m/P0VWp8aKx8hocFESO15ruq2Hbt8HYOeZkMe cSfm0aG4pe8B0ym7ao4oRSJXjupndKzMh/ukacbJJQ9J9QJqTP0Scxdvln6WlUf8uIXAhTyNjcR 5d3V4cdKI9NhwmF3IqQVTbPvb269/pa4lnxzsbulPSkhqs7GzDlnjLgOJcI7sNXHr8kSu0RfPn6 EenvfoAFmtQcfdA== X-Mailer: b4 0.13.0 Message-ID: <20250213-vma-v14-6-b29c47ab21f5@google.com> Subject: [PATCH v14 6/8] mm: rust: add VmaNew 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 VmaRef allows us to have a separate set of operations that you are only able to use during the mmap() hook. For example, the VM_MIXEDMAP flag must not be changed after the initial setup that happens during the f_ops->mmap() hook. To avoid setting invalid flag values, the methods for clearing VM_MAYWRITE and similar involve a check of VM_WRITE, and return an error if VM_WRITE is set. Trying to use `try_clear_maywrite` without checking the return value results in a compilation error because the `Result` type is marked #[must_use]. For now, there's only a method for VM_MIXEDMAP and not VM_PFNMAP. When we add a VM_PFNMAP method, we will need some way to prevent you from setting both VM_MIXEDMAP and VM_PFNMAP on the same vma. Acked-by: Lorenzo Stoakes Reviewed-by: Jann Horn Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl Acked-by: Liam R. Howlett --- 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 3e2eabcc2145..31803674aecc 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, @@ -198,6 +198,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 `VmaNew` indicates that +/// you are allowed to perform operations on the VMA that can only be perf= ormed 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 VmaNew { + vma: VmaRef, +} + +// Make all `VmaRef` methods available on `VmaNew`. +impl Deref for VmaNew { + type Target =3D VmaRef; + + #[inline] + fn deref(&self) -> &VmaRef { + &self.vma + } +} + +impl VmaNew { + /// 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, `VmaNew` is `!Sync`, so it cannot be used= 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) -> &VmaMixedMap { + // 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 { VmaMixedMap::from_raw(self.vma.as_ptr()) } + } + + /// Set the `VM_IO` flag on this vma. + /// + /// This is used for memory mapped IO and similar. The flag tells othe= r parts of the kernel to + /// avoid looking at the pages. For memory mapped IO this is useful as= accesses to the pages + /// could have side effects. + #[inline] + pub fn set_io(&self) { + // SAFETY: Setting the VM_IO flag is always okay. + unsafe { self.update_flags(flags::IO, 0) }; + } + + /// Set the `VM_DONTEXPAND` flag on this vma. + /// + /// This prevents the vma from being expanded with `mremap()`. + #[inline] + pub fn set_dontexpand(&self) { + // SAFETY: Setting the VM_DONTEXPAND flag is always okay. + unsafe { self.update_flags(flags::DONTEXPAND, 0) }; + } + + /// Set the `VM_DONTCOPY` flag on this vma. + /// + /// This prevents the vma from being copied on fork. This option is on= ly permanent if `VM_IO` + /// is set. + #[inline] + pub fn set_dontcopy(&self) { + // SAFETY: Setting the VM_DONTCOPY flag is always okay. + unsafe { self.update_flags(flags::DONTCOPY, 0) }; + } + + /// Set the `VM_DONTDUMP` flag on this vma. + /// + /// This prevents the vma from being included in core dumps. This opti= on is only permanent if + /// `VM_IO` is set. + #[inline] + pub fn set_dontdump(&self) { + // SAFETY: Setting the VM_DONTDUMP flag is always okay. + unsafe { self.update_flags(flags::DONTDUMP, 0) }; + } + + /// Returns whether `VM_READ` is set. + /// + /// This flag indicates whether userspace is mapping this vma as reada= ble. + #[inline] + pub fn readable(&self) -> bool { + (self.flags() & flags::READ) !=3D 0 + } + + /// Try to clear the `VM_MAYREAD` flag, failing if `VM_READ` is set. + /// + /// This flag indicates whether userspace is allowed to make this vma = readable with + /// `mprotect()`. + /// + /// Note that this operation is irreversible. Once `VM_MAYREAD` has be= en cleared, it can never + /// be set again. + #[inline] + pub fn try_clear_mayread(&self) -> Result { + if self.readable() { + return Err(EINVAL); + } + // SAFETY: Clearing `VM_MAYREAD` is okay when `VM_READ` is not set. + unsafe { self.update_flags(0, flags::MAYREAD) }; + Ok(()) + } + + /// Returns whether `VM_WRITE` is set. + /// + /// This flag indicates whether userspace is mapping this vma as writa= ble. + #[inline] + pub fn writable(&self) -> bool { + (self.flags() & flags::WRITE) !=3D 0 + } + + /// Try to clear the `VM_MAYWRITE` flag, failing if `VM_WRITE` is set. + /// + /// This flag indicates whether userspace is allowed to make this vma = writable with + /// `mprotect()`. + /// + /// Note that this operation is irreversible. Once `VM_MAYWRITE` has b= een cleared, it can never + /// be set again. + #[inline] + pub fn try_clear_maywrite(&self) -> Result { + if self.writable() { + return Err(EINVAL); + } + // SAFETY: Clearing `VM_MAYWRITE` is okay when `VM_WRITE` is not s= et. + unsafe { self.update_flags(0, flags::MAYWRITE) }; + Ok(()) + } + + /// Returns whether `VM_EXEC` is set. + /// + /// This flag indicates whether userspace is mapping this vma as execu= table. + #[inline] + pub fn executable(&self) -> bool { + (self.flags() & flags::EXEC) !=3D 0 + } + + /// Try to clear the `VM_MAYEXEC` flag, failing if `VM_EXEC` is set. + /// + /// This flag indicates whether userspace is allowed to make this vma = executable with + /// `mprotect()`. + /// + /// Note that this operation is irreversible. Once `VM_MAYEXEC` has be= en cleared, it can never + /// be set again. + #[inline] + pub fn try_clear_mayexec(&self) -> Result { + if self.executable() { + return Err(EINVAL); + } + // SAFETY: Clearing `VM_MAYEXEC` is okay when `VM_EXEC` is not set. + unsafe { self.update_flags(0, flags::MAYEXEC) }; + Ok(()) + } +} + /// The integer type used for vma flags. #[doc(inline)] pub use bindings::vm_flags_t; --=20 2.48.1.502.g6dc24dfdaf-goog From nobody Fri Mar 14 08:10:24 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 B51552153DF for ; Thu, 13 Feb 2025 11:04:53 +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=1739444695; cv=none; b=TDn3GjLHFVol9bMa4blvDGaYP1MqaLJrTLrWA2M3+CI1lO5XVvY92PfRjrFB4QJCO3HrcnAzfetVuANvBvMgqRZjoQo6cVVhrp5OImI+27VjzpWrAUdTsCBVroVvtv9B4eAdmStBsRetSWWoXQz/TKB0SYNNEYNXBQgNxFSPN08= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739444695; c=relaxed/simple; bh=2M89B3p91FPP25Gw8Y6SiWDXagycK/dpbfENE1t2aLQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=pmaYVvcgW/HXWcFAyD7fDm5fr3TZ/qbKdU7rmqmb2YqM/SQgFtUSp71RYRcntIaNz/Qa9bIjw6viPE1P8+shzGdzbgkvmv2Yb0+QeEGAsMZHk73MJYr7SEjmMl1KjMJma/J0PsFS8PoXRIYoThm43t5vWJBPErgd4h1gfq6jE5A= 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=Wa6jmLKm; 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="Wa6jmLKm" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-4394b2c19ccso5659255e9.1 for ; Thu, 13 Feb 2025 03:04:53 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739444692; x=1740049492; 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=m2sxvAYKNr0+htAaMCuMZG0BVvvnjrhzSWzEt2rFCZM=; b=Wa6jmLKm9aMrO3rEu72QUgUbIYWOHlJzVY0ND1bFkkiD06lGvxSOWD7uKhsJhjYCKL QgB3SlBpm0O3PlZa/jldUvZT9LdKFP9cPVdC8jAOUIWnhx5GNirfs2qO8mcBtLBHuq9V vRMlgBVOZCg1PcOA6aR1NfDptK4nOtMb4s3fQpzg7O7DnXpWfV5faPpbGOPH0SinLSTq qJRZNRhAfNGJq9s+CPuPALmrjW1Sdw0BSuGoXgVWxUXVQhTzN/ekoS9ryRzEm+NXNUdl loexXsGFsByW30Cn+ab3G/uuE7qckoam2yxsLVye6/9n7Q9mYJ04IocMzKC8cxDBY22S p15w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739444692; x=1740049492; 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=m2sxvAYKNr0+htAaMCuMZG0BVvvnjrhzSWzEt2rFCZM=; b=Vf9uy1uui4uabtgEfQ28iXKeWSDtUijYHfFeUZECpJBFGixY+cDKdmBt5+ChMVJzZz TKn3jNc/QDui7T7s6HauvkLFQICMleGcslhBIg3AaESqByoupW+mwH58Nv4vE2tbYAtE QJnd9bi+y63gKBrhrZQf44nCvdPzPK3rh4g1zeZluq3Q7mIwhCfkWsGmRrpFwQWuOOu4 F+MdFzsQeWJeg9of6oGKdq5jpOFQTiubfsz7MQJ/weAHsVxZvjgd6hTL+nk8yr2Rc8Py ry2F1kexlcypVIOT5/DAT+T/++Qj9iM/CDpiNrzY1hsNAtAqglmx9sxjjSnTyxiS1v6m 7W2Q== X-Forwarded-Encrypted: i=1; AJvYcCW4buRYZPTxscEbGhNwXE0U+vkdlPo8rC8z2ceuqZDRxAQi2PAlxgVHxl/z1eNG+3eiIDmd+TGasJz0uRA=@vger.kernel.org X-Gm-Message-State: AOJu0YxlyxQjq/ql3gAT44RWYKR0SwyfnT9fivjWOml0JFd0hjh4rxCF +2vdxWRXs355WSTVrYC08KXvJ0nWBLjuMkzFmUAXOvbVC3IFBe/MJtqbvAXaFEpijDALYp5Ei7r xQxhGtPK67zfEaA== X-Google-Smtp-Source: AGHT+IEB3aP700Hf+T0Y9hXFswWx+oBLY+WAVsjCa34dg3231EVe8adDYbhQ2hlUMA3P7Xrq6PWzNabIh7UH2D4= X-Received: from wmgg21.prod.google.com ([2002:a05:600d:15:b0:439:3c3e:f0e8]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3f12:b0:439:45ce:15da with SMTP id 5b1f17b1804b1-439601c10a2mr29099955e9.25.1739444692374; Thu, 13 Feb 2025 03:04:52 -0800 (PST) Date: Thu, 13 Feb 2025 11:04:06 +0000 In-Reply-To: <20250213-vma-v14-0-b29c47ab21f5@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250213-vma-v14-0-b29c47ab21f5@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3859; i=aliceryhl@google.com; h=from:subject:message-id; bh=2M89B3p91FPP25Gw8Y6SiWDXagycK/dpbfENE1t2aLQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnrdHBNVpj/HCfF1bMPs0sT3j/Jo2hPFWd70C3l iOXvQTr0YyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ63RwQAKCRAEWL7uWMY5 RtHcEACcBTXyAj1CXLqb0ECe7oLoK6K8Pl+NeXmHTuMk/Ev7mlbfXpB1nTJjbWRsYCabctv6mkD G9xvp3vC3cneN8bB44qp9x+ebNayRdV32qqfyi8cfv/2t5alAL3cKGTErJW6gEeIGyTAi7Mmyem stGNNElApGyVgVocm3n6dDGebZ5GQgXMWmtUzojC+mhcF7jIE00ry3mrPAxCQA/Q4SgFWZE2Uhy HasbIcqybKe2sgVO1R2tJ2sA2ba6ybalTf2ORz3h4PheSouXcsG51HIepwvqn/mhb9nyocthl88 bZIptuUR1O79gMUyLSpctcApRDnt8YbFqX/DCLY3mVxCq55sbcHRT3caJ+bCIsGG0a/vsONgeaX /jdSt0JbUYbE9+PpBd7IHqjgZxw9z6HRZITmoLhIUaQa00mEbtASKRL0pCOLFK093wxdw2Gy5BO V8rsvOruaOrT6AIdS4sDOtMyRXbp6TjKq6EioB92dhZnRPmb1a0Xwv6Td7GifsTVOa6msSoYugx DF/+4YZOrTawLkkY/1b4vb/8cgLTehGuS4ASNFFHBbOPFjhWh1PRCvnapev05NtEZ1A+JYbrBSj QDyex48V5rO7SbbnmgPgMbO5gTtVde02PpFkw2+qxRX88cQiVaOaFOODzsaMmVS/zYWyz+FXlaz MAB1NXQrXMto4PQ== X-Mailer: b4 0.13.0 Message-ID: <20250213-vma-v14-7-b29c47ab21f5@google.com> Subject: [PATCH v14 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 `VmaNew` type from the previous commit; this type provides the correct set of operations for a file_operations->mmap hook. Acked-by: Greg Kroah-Hartman Acked-by: Lorenzo Stoakes Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl Acked-by: Liam R. Howlett Reviewed-by: Gary Guo --- rust/kernel/miscdevice.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index e14433b2ab9d..e4a2c5996832 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -14,6 +14,7 @@ error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR}, ffi::{c_int, c_long, c_uint, c_ulong}, fs::File, + mm::virt::VmaNew, prelude::*, seq_file::SeqFile, str::CStr, @@ -119,6 +120,22 @@ fn release(device: Self::Ptr, _file: &File) { drop(device); } =20 + /// Handle for mmap. + /// + /// This function is invoked when a user space process invokes the `mm= ap` system call on + /// `file`. The function is a callback that is part of the VMA initial= izer. The kernel will do + /// initial setup of the VMA before calling this function. The functio= n can then interact with + /// the VMA initialization by calling methods of `vma`. If the functio= n does not return an + /// error, the kernel will complete initialization of the VMA accordin= g to the properties of + /// `vma`. + fn mmap( + _device: ::Borrowed<'_>, + _file: &File, + _vma: &VmaNew, + ) -> Result { + kernel::build_error!(VTABLE_DEFAULT_ERROR) + } + /// Handler for ioctls. /// /// The `cmd` argument is usually manipulated using the utilties in [`= kernel::ioctl`]. @@ -176,6 +193,7 @@ impl VtableHelper { const VTABLE: bindings::file_operations =3D bindings::file_operati= ons { open: Some(fops_open::), release: Some(fops_release::), + mmap: maybe_fn(T::HAS_MMAP, fops_mmap::), unlocked_ioctl: maybe_fn(T::HAS_IOCTL, fops_ioctl::), #[cfg(CONFIG_COMPAT)] compat_ioctl: if T::HAS_COMPAT_IOCTL { @@ -257,6 +275,32 @@ impl VtableHelper { 0 } =20 +/// # Safety +/// +/// `file` must be a valid file that is associated with a `MiscDeviceRegis= tration`. +/// `vma` must be a vma that is currently being mmap'ed with this file. +unsafe extern "C" fn fops_mmap( + file: *mut bindings::file, + vma: *mut bindings::vm_area_struct, +) -> c_int { + // SAFETY: The mmap call of a file can access the private data. + let private =3D unsafe { (*file).private_data }; + // SAFETY: This is a Rust Miscdevice, so we call `into_foreign` in `op= en` and `from_foreign` in + // `release`, and `fops_mmap` is guaranteed to be called between those= two operations. + let device =3D unsafe { ::borrow(private) }; + // SAFETY: The caller provides a vma that is undergoing initial VMA se= tup. + let area =3D unsafe { VmaNew::from_raw(vma) }; + // SAFETY: + // * The file is valid for the duration of this call. + // * There is no active fdget_pos region on the file on this thread. + let file =3D unsafe { File::from_raw_file(file) }; + + match T::mmap(device, file, area) { + Ok(()) =3D> 0, + Err(err) =3D> err.to_errno(), + } +} + /// # Safety /// /// `file` must be a valid file that is associated with a `MiscDeviceRegis= tration`. --=20 2.48.1.502.g6dc24dfdaf-goog From nobody Fri Mar 14 08:10:24 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 1F1B52153FA for ; Thu, 13 Feb 2025 11:04:56 +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=1739444698; cv=none; b=svcUGVGz6BVDCz8z/ctbPUOc/lxseqU6SnJKdTQQLfHo++oPxMWl7/ijGXu3OvaFQVHEkKIwjff/vXd9ClUbuC+2VaEGj0Luu2ptso9joKpD1+iv0OEcKsCPFxc1tV2ZQ/+nbdEsuIAt+CgRtK3o/mdNWat9yVmh8zgiRNKle2g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1739444698; c=relaxed/simple; bh=1zv+hEEHUtoRrSeYtVG9cnUb/jaHdXXVk6Pmq2XF4w4=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=oSsnw8gV9s51t8emJkUrhUqwFQsMuoBoBdeK3Uc30ygCBrcmZJF3rAgr4HrHeyY6w70dbqlJqSZHnUapeq3MXRZSB/0AgQxEyEqD/gJ/vvgoJubfVCSwi6G7EknbTAoUwhMe3tMkGlw+2dt1+MWRqvCVCmYocxvjcWNVJKZ4dNA= 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=ONBjn6hG; 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="ONBjn6hG" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-38ddee8329eso407468f8f.1 for ; Thu, 13 Feb 2025 03:04:56 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739444695; x=1740049495; 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=pggCn+rSttrAyFGqOyOJWEZwQTAFQJ/uxRrTgaYt6Zw=; b=ONBjn6hGa6JtXpgnJ6zN8yEaRMzHlBfdmFHBjKxPeVYPmfMlDAwtft7EK4lOUO7Jb/ 6PimiXdkPK3DS7xzpiKXBEOa+lZh4kEFAayI1DAkkG+/0Sf1Z5wVA4a2k3LGn7ZyCKEz robkYchdw5RRhZDHI50NB4VgiP1p5bL9CW2e7rteU35MEbYQ3h2sEFLDcMBTbtMxTCsz ffphDdAF6Abr+7212uLIVGrufcYWZgu2N+kjWt/WG+oUK2rbyJCsgPjJdH+rwCDXYYTh CxqujGdjZeUdNEhC3TbkgD0WD6IQW9rZs1OdoSQT4gKI2H/qS5CsBHvCg1pqjQJooOz1 DoAg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739444695; x=1740049495; 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=pggCn+rSttrAyFGqOyOJWEZwQTAFQJ/uxRrTgaYt6Zw=; b=ZQe+wxY6jtjAbOmO8/YlMRtgeRFwF5B9BMv4MkaPWDXgLjTrCy2fWuFq0J6RtiNaDq Lvqtm3NHuc9TBf8eIbkhxM5Ec5zvRe6gDkT61ARTbp/ZdMU13+fmsYISaQGlgJ8raC8s hxbiYlNooaJBv9SaMKNZBTvWG3fCUYir1qNp2jZhbcLzXg2WVaiDbTlB0zwQgf1iOz39 P1qtBloy1d7btsIJ1anr7+9MvvKXdRyARVIR0f9ldyNmPcq3Chhcu9YQ3KrcfvNZeU1s nTtcjir61qAOpHA57bCgFXyTrn2HV0n2jIoeH1oOFPQ9+/QbMHcS1XdcfZYnumxVSHEb yY7Q== X-Forwarded-Encrypted: i=1; AJvYcCXriguTIVi1JRC551YAt6YtVpysOspqhnQuksk5K/J9EkHwNRNjUxaO9uzqZSsynULNa/36xkNEyhn4js8=@vger.kernel.org X-Gm-Message-State: AOJu0YxSUNV5gf6Rw1Ysda5+bwPLt4/OeRcHfJbrL4T7p1wXDw0pi13+ IlvRcToSNA20aUtix2/WGcLtB0hdgyS9x3gkGNMhS11haROljF8/G2BSBLdlEoi32ZXF/Re0TEv M0qnXzBZLIKn0sA== X-Google-Smtp-Source: AGHT+IGOn6Mt66bw64HQ0WkAveH41wrxH69hatXUdAVol6d4fHE/vHEGMWR2wYfjVsRWmOaT0jjiIajQSSSAjtc= X-Received: from wmsp21.prod.google.com ([2002:a05:600c:1d95:b0:439:4829:ec32]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6000:e4d:b0:38d:e61a:bc7 with SMTP id ffacd0b85a97d-38f24512decmr2550555f8f.40.1739444694761; Thu, 13 Feb 2025 03:04:54 -0800 (PST) Date: Thu, 13 Feb 2025 11:04:07 +0000 In-Reply-To: <20250213-vma-v14-0-b29c47ab21f5@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250213-vma-v14-0-b29c47ab21f5@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=18134; i=aliceryhl@google.com; h=from:subject:message-id; bh=1zv+hEEHUtoRrSeYtVG9cnUb/jaHdXXVk6Pmq2XF4w4=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnrdHChHUOhGpI4kDYpztj4GO15xSiXl+k7bnvp CTKdHXzRLWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ63RwgAKCRAEWL7uWMY5 RpsID/9IhzcWTdhOJEwojq4rxoACbbWSGPJnIkg4Xqt8Z7jN+BB8275YLTeMQ2fTbUkO1YnoB3d Sx9n5XV7G6Qma/705uZT7hBgknowr8Xo4FTFBbq1fwvQL7ejohMfGL5AwIvq1JnwYVE+zTSMgIi XKB9Ns+kQptPUcCoUkh1QjAAeG6V2z+8CXWmGhUOvERJykv993uwCUoGCLbvrAiwRAXdOEjcAV7 kA6o7e2+YfzICSW5bH1oknNqqL0k1Dp3xGKhyyjAdHLOX2zE8EVa4YLc29kD48DsQxPfwLzaRE9 wD9uxsXNC4P334w28jai5myCnwLGpz/5tIoikO+c1xVGBKnT301+jPVpyDLjllPZ3ZOdoFcJsVu zlIkdsCh7NZ3SQ2ig+hWlxKxnSzNolA+nVZb1XVGhkKD/65ibdie4XhsChw5PFnNzSxsDYDww7q 9BIuzwUZhlz/D2khqvYzGvxkUinoljisuNHOXnGzeJgxcWCHHE+znWlzkQ096dVVwiW80hNLVaH rg5XXmvACrFBh2NXLfYjf1hJk4e+nEWq7eqLKb9aa1cwFRDOTW+otUz0mwQD/v70U2IhITltU1E dykuskCSfHuXfjozqyyMPBI46BoAvm/3+rSIz8cXlsfGPaSummi/Mf3wCn1IZ/wYyox67ikph9q u/9avX3d36Gpqfg== X-Mailer: b4 0.13.0 Message-ID: <20250213-vma-v14-8-b29c47ab21f5@google.com> Subject: [PATCH v14 8/8] task: rust: rework how current is accessed From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Introduce a new type called `CurrentTask` that lets you perform various operations that are only safe on the `current` task. Use the new type to provide a way to access the current mm without incrementing its refcount. With this change, you can write stuff such as let vma =3D current!().mm().lock_vma_under_rcu(addr); without incrementing any refcounts. This replaces the existing abstractions for accessing the current pid namespace. With the old approach, every field access to current involves both a macro and a unsafe helper function. The new approach simplifies that to a single safe function on the `CurrentTask` type. This makes it less heavy-weight to add additional current accessors in the future. That said, creating a `CurrentTask` type like the one in this patch requires that we are careful to ensure that it cannot escape the current task or otherwise access things after they are freed. To do this, I declared that it cannot escape the current "task context" where I defined a "task context" as essentially the region in which `current` remains unchanged. So e.g., release_task() or begin_new_exec() would leave the task context. If a userspace thread returns to userspace and later makes another syscall, then I consider the two syscalls to be different task contexts. This allows values stored in that task to be modified between syscalls, even if they're guaranteed to be immutable during a syscall. Ensuring correctness of `CurrentTask` is slightly tricky if we also want the ability to have a safe `kthread_use_mm()` implementation in Rust. To support that safely, there are two patterns we need to ensure are safe: // Case 1: current!() called inside the scope. let mm; kthread_use_mm(some_mm, || { mm =3D current!().mm(); }); drop(some_mm); mm.do_something(); // UAF and: // Case 2: current!() called before the scope. let mm; let task =3D current!(); kthread_use_mm(some_mm, || { mm =3D task.mm(); }); drop(some_mm); mm.do_something(); // UAF The existing `current!()` abstraction already natively prevents the first case: The `&CurrentTask` would be tied to the inner scope, so the borrow-checker ensures that no reference derived from it can escape the scope. Fixing the second case is a bit more tricky. The solution is to essentially pretend that the contents of the scope execute on an different thread, which means that only thread-safe types can cross the boundary. Since `CurrentTask` is marked `NotThreadSafe`, attempts to move it to another thread will fail, and this includes our fake pretend thread boundary. This has the disadvantage that other types that aren't thread-safe for reasons unrelated to `current` also cannot be moved across the `kthread_use_mm()` boundary. I consider this an acceptable tradeoff. Reviewed-by: Boqun Feng Reviewed-by: Andreas Hindborg Signed-off-by: Alice Ryhl Acked-by: Liam R. Howlett Reviewed-by: Gary Guo --- rust/kernel/task.rs | 247 +++++++++++++++++++++++++++---------------------= ---- 1 file changed, 129 insertions(+), 118 deletions(-) diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs index 07bc22a7645c..0b6cb9a83a2e 100644 --- a/rust/kernel/task.rs +++ b/rust/kernel/task.rs @@ -7,6 +7,7 @@ use crate::{ bindings, ffi::{c_int, c_long, c_uint}, + mm::MmWithUser, pid_namespace::PidNamespace, types::{ARef, NotThreadSafe, Opaque}, }; @@ -31,22 +32,20 @@ #[macro_export] macro_rules! current { () =3D> { - // SAFETY: Deref + addr-of below create a temporary `TaskRef` that= cannot outlive the - // caller. + // SAFETY: This expression creates a temporary value that is dropp= ed at the end of the + // caller's scope. The following mechanisms ensure that the result= ing `&CurrentTask` cannot + // leave current task context: + // + // * To return to userspace, the caller must leave the current sco= pe. + // * Operations such as `begin_new_exec()` are necessarily unsafe = and the caller of + // `begin_new_exec()` is responsible for safety. + // * Rust abstractions for things such as a `kthread_use_mm()` sco= pe must require the + // closure to be `Send`, so the `NotThreadSafe` field of `Curren= tTask` ensures that the + // `&CurrentTask` cannot cross the scope in either direction. unsafe { &*$crate::task::Task::current() } }; } =20 -/// Returns the currently running task's pid namespace. -#[macro_export] -macro_rules! current_pid_ns { - () =3D> { - // SAFETY: Deref + addr-of below create a temporary `PidNamespaceR= ef` that cannot outlive - // the caller. - unsafe { &*$crate::task::Task::current_pid_ns() } - }; -} - /// Wraps the kernel's `struct task_struct`. /// /// # Invariants @@ -85,7 +84,7 @@ macro_rules! current_pid_ns { /// impl State { /// fn new() -> Self { /// Self { -/// creator: current!().into(), +/// creator: ARef::from(&**current!()), /// index: 0, /// } /// } @@ -105,6 +104,44 @@ unsafe impl Send for Task {} // synchronised by C code (e.g., `signal_pending`). unsafe impl Sync for Task {} =20 +/// Represents the [`Task`] in the `current` global. +/// +/// This type exists to provide more efficient operations that are only va= lid on the current task. +/// For example, to retrieve the pid-namespace of a task, you must use rcu= protection unless it is +/// the current task. +/// +/// # Invariants +/// +/// Each value of this type must only be accessed from the task context it= was created within. +/// +/// Of course, every thread is in a different task context, but for the pu= rposes of this invariant, +/// these operations also permanently leave the task context: +/// +/// * Returning to userspace from system call context. +/// * Calling `release_task()`. +/// * Calling `begin_new_exec()` in a binary format loader. +/// +/// Other operations temporarily create a new sub-context: +/// +/// * Calling `kthread_use_mm()` creates a new context, and `kthread_unuse= _mm()` returns to the +/// old context. +/// +/// This means that a `CurrentTask` obtained before a `kthread_use_mm()` c= all may be used again +/// once `kthread_unuse_mm()` is called, but it must not be used between t= hese two calls. +/// Conversely, a `CurrentTask` obtained between a `kthread_use_mm()`/`kth= read_unuse_mm()` pair +/// must not be used after `kthread_unuse_mm()`. +#[repr(transparent)] +pub struct CurrentTask(Task, NotThreadSafe); + +// Make all `Task` methods available on `CurrentTask`. +impl Deref for CurrentTask { + type Target =3D Task; + #[inline] + fn deref(&self) -> &Task { + &self.0 + } +} + /// The type of process identifiers (PIDs). type Pid =3D bindings::pid_t; =20 @@ -131,119 +168,29 @@ pub fn current_raw() -> *mut bindings::task_struct { /// /// # Safety /// - /// Callers must ensure that the returned object doesn't outlive the c= urrent task/thread. - pub unsafe fn current() -> impl Deref { - struct TaskRef<'a> { - task: &'a Task, - _not_send: NotThreadSafe, + /// Callers must ensure that the returned object is only used to acces= s a [`CurrentTask`] + /// within the task context that was active when this function was cal= led. For more details, + /// see the invariants section for [`CurrentTask`]. + pub unsafe fn current() -> impl Deref { + struct TaskRef { + task: *const CurrentTask, } =20 - impl Deref for TaskRef<'_> { - type Target =3D Task; + impl Deref for TaskRef { + type Target =3D CurrentTask; =20 fn deref(&self) -> &Self::Target { - self.task + // SAFETY: The returned reference borrows from this `TaskR= ef`, so it cannot outlive + // the `TaskRef`, which the caller of `Task::current()` ha= s promised will not + // outlive the task/thread for which `self.task` is the `c= urrent` pointer. Thus, it + // is okay to return a `CurrentTask` reference here. + unsafe { &*self.task } } } =20 - let current =3D Task::current_raw(); TaskRef { - // SAFETY: If the current thread is still running, the current= task is valid. Given - // that `TaskRef` is not `Send`, we know it cannot be transfer= red to another thread - // (where it could potentially outlive the caller). - task: unsafe { &*current.cast() }, - _not_send: NotThreadSafe, - } - } - - /// Returns a PidNamespace reference for the currently executing task'= s/thread's pid namespace. - /// - /// This function can be used to create an unbounded lifetime by e.g.,= storing the returned - /// PidNamespace in a global variable which would be a bug. So the rec= ommended way to get the - /// current task's/thread's pid namespace is to use the [`current_pid_= ns`] macro because it is - /// safe. - /// - /// # Safety - /// - /// Callers must ensure that the returned object doesn't outlive the c= urrent task/thread. - pub unsafe fn current_pid_ns() -> impl Deref { - struct PidNamespaceRef<'a> { - task: &'a PidNamespace, - _not_send: NotThreadSafe, - } - - impl Deref for PidNamespaceRef<'_> { - type Target =3D PidNamespace; - - fn deref(&self) -> &Self::Target { - self.task - } - } - - // The lifetime of `PidNamespace` is bound to `Task` and `struct p= id`. - // - // The `PidNamespace` of a `Task` doesn't ever change once the `Ta= sk` is alive. A - // `unshare(CLONE_NEWPID)` or `setns(fd_pidns/pidfd, CLONE_NEWPID)= ` will not have an effect - // on the calling `Task`'s pid namespace. It will only effect the = pid namespace of children - // created by the calling `Task`. This invariant guarantees that a= fter having acquired a - // reference to a `Task`'s pid namespace it will remain unchanged. - // - // When a task has exited and been reaped `release_task()` will be= called. This will set - // the `PidNamespace` of the task to `NULL`. So retrieving the `Pi= dNamespace` of a task - // that is dead will return `NULL`. Note, that neither holding the= RCU lock nor holding a - // referencing count to - // the `Task` will prevent `release_task()` being called. - // - // In order to retrieve the `PidNamespace` of a `Task` the `task_a= ctive_pid_ns()` function - // can be used. There are two cases to consider: - // - // (1) retrieving the `PidNamespace` of the `current` task - // (2) retrieving the `PidNamespace` of a non-`current` task - // - // From system call context retrieving the `PidNamespace` for case= (1) is always safe and - // requires neither RCU locking nor a reference count to be held. = Retrieving the - // `PidNamespace` after `release_task()` for current will return `= NULL` but no codepath - // like that is exposed to Rust. - // - // Retrieving the `PidNamespace` from system call context for (2) = requires RCU protection. - // Accessing `PidNamespace` outside of RCU protection requires a r= eference count that - // must've been acquired while holding the RCU lock. Note that acc= essing a non-`current` - // task means `NULL` can be returned as the non-`current` task cou= ld have already passed - // through `release_task()`. - // - // To retrieve (1) the `current_pid_ns!()` macro should be used wh= ich ensure that the - // returned `PidNamespace` cannot outlive the calling scope. The a= ssociated - // `current_pid_ns()` function should not be called directly as it= could be abused to - // created an unbounded lifetime for `PidNamespace`. The `current_= pid_ns!()` macro allows - // Rust to handle the common case of accessing `current`'s `PidNam= espace` without RCU - // protection and without having to acquire a reference count. - // - // For (2) the `task_get_pid_ns()` method must be used. This will = always acquire a - // reference on `PidNamespace` and will return an `Option` to forc= e the caller to - // explicitly handle the case where `PidNamespace` is `None`, some= thing that tends to be - // forgotten when doing the equivalent operation in `C`. Missing R= CU primitives make it - // difficult to perform operations that are otherwise safe without= holding a reference - // count as long as RCU protection is guaranteed. But it is not im= portant currently. But we - // do want it in the future. - // - // Note for (2) the required RCU protection around calling `task_a= ctive_pid_ns()` - // synchronizes against putting the last reference of the associat= ed `struct pid` of - // `task->thread_pid`. The `struct pid` stored in that field is us= ed to retrieve the - // `PidNamespace` of the caller. When `release_task()` is called `= task->thread_pid` will be - // `NULL`ed and `put_pid()` on said `struct pid` will be delayed i= n `free_pid()` via - // `call_rcu()` allowing everyone with an RCU protected access to = the `struct pid` acquired - // from `task->thread_pid` to finish. - // - // SAFETY: The current task's pid namespace is valid as long as th= e current task is running. - let pidns =3D unsafe { bindings::task_active_pid_ns(Task::current_= raw()) }; - PidNamespaceRef { - // SAFETY: If the current thread is still running, the current= task and its associated - // pid namespace are valid. `PidNamespaceRef` is not `Send`, s= o we know it cannot be - // transferred to another thread (where it could potentially o= utlive the current - // `Task`). The caller needs to ensure that the PidNamespaceRe= f doesn't outlive the - // current task/thread. - task: unsafe { PidNamespace::from_ptr(pidns) }, - _not_send: NotThreadSafe, + // CAST: The layout of `struct task_struct` and `CurrentTask` = is identical. + task: Task::current_raw().cast(), } } =20 @@ -326,6 +273,70 @@ pub fn wake_up(&self) { } } =20 +impl CurrentTask { + /// Access the address space of the current task. + /// + /// This function does not touch the refcount of the mm. + #[inline] + pub fn mm(&self) -> Option<&MmWithUser> { + // SAFETY: The `mm` field of `current` is not modified from other = threads, so reading it is + // not a data race. + let mm =3D unsafe { (*self.as_ptr()).mm }; + + if mm.is_null() { + return None; + } + + // SAFETY: If `current->mm` is non-null, then it references a vali= d mm with a non-zero + // value of `mm_users`. Furthermore, the returned `&MmWithUser` bo= rrows from this + // `CurrentTask`, so it cannot escape the scope in which the curre= nt pointer was obtained. + // + // This is safe even if `kthread_use_mm()`/`kthread_unuse_mm()` ar= e used. There are two + // relevant cases: + // * If the `&CurrentTask` was created before `kthread_use_mm()`, = then it cannot be + // accessed during the `kthread_use_mm()`/`kthread_unuse_mm()` s= cope due to the + // `NotThreadSafe` field of `CurrentTask`. + // * If the `&CurrentTask` was created within a `kthread_use_mm()`= /`kthread_unuse_mm()` + // scope, then the `&CurrentTask` cannot escape that scope, so t= he returned `&MmWithUser` + // also cannot escape that scope. + // In either case, it's not possible to read `current->mm` and kee= p using it after the + // scope is ended with `kthread_unuse_mm()`. + Some(unsafe { MmWithUser::from_raw(mm) }) + } + + /// Access the pid namespace of the current task. + /// + /// This function does not touch the refcount of the namespace or use = RCU protection. + /// + /// To access the pid namespace of another task, see [`Task::get_pid_n= s`]. + #[doc(alias =3D "task_active_pid_ns")] + #[inline] + pub fn active_pid_ns(&self) -> Option<&PidNamespace> { + // SAFETY: It is safe to call `task_active_pid_ns` without RCU pro= tection when calling it + // on the current task. + let active_ns =3D unsafe { bindings::task_active_pid_ns(self.as_pt= r()) }; + + if active_ns.is_null() { + return None; + } + + // The lifetime of `PidNamespace` is bound to `Task` and `struct p= id`. + // + // The `PidNamespace` of a `Task` doesn't ever change once the `Ta= sk` is alive. + // + // From system call context retrieving the `PidNamespace` for the = current task is always + // safe and requires neither RCU locking nor a reference count to = be held. Retrieving the + // `PidNamespace` after `release_task()` for current will return `= NULL` but no codepath + // like that is exposed to Rust. + // + // SAFETY: If `current`'s pid ns is non-null, then it references a= valid pid ns. + // Furthermore, the returned `&PidNamespace` borrows from this `Cu= rrentTask`, so it cannot + // escape the scope in which the current pointer was obtained, e.g= . it cannot live past a + // `release_task()` call. + Some(unsafe { PidNamespace::from_ptr(active_ns) }) + } +} + // SAFETY: The type invariants guarantee that `Task` is always refcounted. unsafe impl crate::types::AlwaysRefCounted for Task { fn inc_ref(&self) { --=20 2.48.1.502.g6dc24dfdaf-goog