From nobody Wed Jan 15 08:44:33 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 1060D14831E for ; Fri, 29 Nov 2024 16:32:55 +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=1732897978; cv=none; b=QNUYEcCyynUMH+org1b9SEpXInTAYk9MoLA+eP+CbnmyM9eYSxhD0BNX0Ux1xOCjHeBM4nxdERpZpYCSH1mErPA/Mn7VKS2rflzEYp6KiUhCV46Xy7Tm3ooY2+evzrMvD5xvi3SIUSIhFl18dYBVjdyI5CTHZ0J233nMmpQcd00= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1732897978; c=relaxed/simple; bh=9dPy033+czHjobcXs31YH34rNSge6iKWvSxm8dMkcKg=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=n98YiVzyOS8K5OGEJSiPMk/X0Ilq9UblU7Nkjo2b1Cy77cSzRIZf9sQsypT7nTjjh6uUox/15JMP/qRRYVY+OOqq4+7aCBa+qe1UsrCWGECRXXazBpWgC128f7N0eMXX9UgFBVlr3M77Fyt3y4GjII/UKCMGpvY1xyuql3ulM7Y= 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=3F1c2URJ; 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="3F1c2URJ" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43498af79a6so12265895e9.0 for ; Fri, 29 Nov 2024 08:32:55 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897974; x=1733502774; 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=j9X1mSWROln1wrDBMjuahPQZdYG+tTYafJBbOIpF/U8=; b=3F1c2URJv6gGNr79vdF9/hBaeMZwEO0xDONaUbz2ETZtbNCuvBqE06mGEpzGgJa+6j TRxtq6S6vv5EISOzgmAOhMgaMMFFrfFJW+6GpEwLxN07C6p+OOAGWqYFPP2JTFazGhUH S9jYhbM1U9iOAsORbwW72URfQquFqw/IRUTZamQaqmOQa3/u/HV299kXLshucLYn87mK EsFyjn+Mk4aR/NTXFXOEYS3+eBOYUIJ7beGJYE/642J0U0KxSw2nrZ5np0/988h/kCUj Q1uTOLMK3cgSh61aBP9g+P0Rpo21REMGmoKQ/dLN9tbR1eNQqpkrR7e/JFB61sdyOrqH 1PCg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897974; x=1733502774; 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=j9X1mSWROln1wrDBMjuahPQZdYG+tTYafJBbOIpF/U8=; b=dLUB9eJ00Zy7TmPSGdmqMW6JEziA8Z5Dfc+jWLQOF96VM+dglynM9FgSnEZHDaAqbS v5tjDLzrWGMHMdc3hnr77kyDN4Qvw2CkripyPOvd+lHlKjJS2+aXRxHtl0j85yv2g3xq ZSwf16HfbjdcFpt/HWJxbnckqFRpK9tcJTmq9TCpbhPPRdXJzNnNhTLurVNMcwDnXfq4 NWPyiNgHnCPcLGHRyN3QapSSx9b/bsfvJfVc4wiQ/Zf4MB8NLb2KjRfkIyxB6OlyqGEZ o8Z2nHQLy2lBl+e8g9bTJ/LxRHfa+n4znVt0KLgYfmClFtHs1/mYOTyfEk0sUkA4PzJu 15CA== X-Forwarded-Encrypted: i=1; AJvYcCUESes8KxHdLb9A6je4g9ftIFFR6HApvenRTXoH8/oa0Z/rPE2seI03FNrc3w4sxw+ncuUDqxgdtZAJpv4=@vger.kernel.org X-Gm-Message-State: AOJu0YyiD+hfNOixnvngdH0WPMkFs2waSbqvITbF/PxAb6MXa5SryIiB p9ZqXJqZ2+q7IpVpnU6Vp1jJrgxohFPTxC1cUVrs7Qj07yzuza9B1bW9P0ea+VF3m4ZxeBPtOMe nI62X0Io4USBQ0g== X-Google-Smtp-Source: AGHT+IG1Q9DtpcqFchzTEpT4t81tXHCjVZL4m+DlejQopKd4Dv0OkuXm1Htn/deYdYiYHN+thVzGQZM8rcROeaE= X-Received: from wmjy22.prod.google.com ([2002:a7b:cd96:0:b0:434:9322:f580]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3589:b0:434:a4d3:31f0 with SMTP id 5b1f17b1804b1-434afb9533fmr77447825e9.3.1732897974563; Fri, 29 Nov 2024 08:32:54 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:34 +0000 In-Reply-To: <20241129-vma-v10-0-4dfff05ba927@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20241129-vma-v10-0-4dfff05ba927@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=10055; i=aliceryhl@google.com; h=from:subject:message-id; bh=9dPy033+czHjobcXs31YH34rNSge6iKWvSxm8dMkcKg=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeytYAQEEiK6whr+TrOU4N31iHFdV607MGM6c jNKDH8RODmJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nsrQAKCRAEWL7uWMY5 Rl1BD/43K0CD3qubFqV+QMRL/6t3UCee4q4QUSFTTg5qJ7tu57qKFhi+Z5+h/98/rPE11mSQVnv fYVg0nh5ueazDKhTrdTjPqDDeP8J71WHLI2yDJpy9m/DEbtqHQjFi4Ev/ROD3Npv0ASTYYdhJ1Q N+Zdfdftn+jufRt3v3P0n631vzB/nKT+cTYg2is2VYOlthxxbg0z1CtgLpQ3wI1aOt4bgQ+IjC3 rBsVW/lx+D9CBKhMT6z+IZ9eXnCA6WF4Qs6nDe9CrBaKZWwlKxouff8zXtNnIfXntvQFb6Sx4ow v5uwVIjipKvKDEX7X/6URnX7sK93JbXcr63Dx4w3LYt/EcKFPCuECZ22T+HQ2+uznUOxICWI4MD 3RiM7iPMRNEV1h5Fv8JrqJUhpXtHeydK5iUL85qfjSVLeZNQs5OoWRWaCvzCs/Vyeji0aFob9S0 b44YQjzgcZlt71l5KwAz+yijXWgWzwbHXt0Mz0of2EP9WlhHEGH5cVEMGwNdv+lASz+s7hh4+iS aqHdqyjijCQLduXH1+7cDDfUfnepdbF3q9yAQ682CbbGM25oiDhGPY8I1vi+HAhVeHfeL9tEKMK 68mqnN0SeyMqOkYmDQ4deL+V4WAiCfBb/pm7+k/rXYPINeo6hFfAchVChGNWIge2r3lvRLuqPBt Egg70NbRZv5rQ4g== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-1-4dfff05ba927@google.com> Subject: [PATCH v10 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 , Christian Brauner , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable These abstractions allow you to reference a `struct mm_struct` using both mmgrab and mmget refcounts. This is done using two Rust types: * Mm - represents an mm_struct where you don't know anything about the value of mm_users. * MmWithUser - represents an mm_struct where you know at compile time that mm_users is non-zero. This allows us to encode in the type system whether a method requires that mm_users is non-zero or not. For instance, you can always call `mmget_not_zero` but you can only call `mmap_read_lock` when mm_users is non-zero. It's possible to access current->mm without a refcount increment, but that is added in a later patch of this series. Acked-by: Lorenzo Stoakes (for mm bits) Signed-off-by: Alice Ryhl --- rust/helpers/helpers.c | 1 + rust/helpers/mm.c | 39 +++++++++ rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 219 +++++++++++++++++++++++++++++++++++++++++++++= ++++ 4 files changed, 260 insertions(+) diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index dcf827a61b52..9d748ec845b3 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -16,6 +16,7 @@ #include "fs.c" #include "jump_label.c" #include "kunit.c" +#include "mm.c" #include "mutex.c" #include "page.c" #include "pid_namespace.c" diff --git a/rust/helpers/mm.c b/rust/helpers/mm.c new file mode 100644 index 000000000000..7201747a5d31 --- /dev/null +++ b/rust/helpers/mm.c @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include +#include + +void rust_helper_mmgrab(struct mm_struct *mm) +{ + mmgrab(mm); +} + +void rust_helper_mmdrop(struct mm_struct *mm) +{ + mmdrop(mm); +} + +void rust_helper_mmget(struct mm_struct *mm) +{ + mmget(mm); +} + +bool rust_helper_mmget_not_zero(struct mm_struct *mm) +{ + return mmget_not_zero(mm); +} + +void rust_helper_mmap_read_lock(struct mm_struct *mm) +{ + mmap_read_lock(mm); +} + +bool rust_helper_mmap_read_trylock(struct mm_struct *mm) +{ + return mmap_read_trylock(mm); +} + +void rust_helper_mmap_read_unlock(struct mm_struct *mm) +{ + mmap_read_unlock(mm); +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index e1065a7551a3..6555e0847192 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -46,6 +46,7 @@ pub mod kunit; pub mod list; pub mod miscdevice; +pub mod mm; #[cfg(CONFIG_NET)] pub mod net; pub mod page; diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs new file mode 100644 index 000000000000..84cba581edaa --- /dev/null +++ b/rust/kernel/mm.rs @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Memory management. +//! +//! 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`. +/// +/// Since `mm_users` may be zero, the associated address space may not exi= st anymore. You can use +/// [`mmget_not_zero`] to be able to access the address space. +/// +/// 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 { + /// Call `mmgrab` on `current.mm`. + #[inline] + pub fn mmgrab_current() -> Option> { + // SAFETY: It's safe to get the `mm` field from current. + let mm =3D unsafe { + let current =3D bindings::get_current(); + (*current).mm + }; + + if mm.is_null() { + return None; + } + + // SAFETY: The value of `current->mm` is guaranteed to be null or = a valid `mm_struct`. We + // just checked that it's not null. Furthermore, the returned `&Mm= ` is valid only for the + // duration of this function, and `current->mm` will stay valid fo= r that long. + let mm =3D unsafe { Mm::from_raw(mm) }; + + // This increments the refcount using `mmgrab`. + Some(ARef::from(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.47.0.338.g60cca15819-goog From nobody Wed Jan 15 08:44:33 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 EDC2119ADA6 for ; Fri, 29 Nov 2024 16:32:57 +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=1732897980; cv=none; b=dPSZbgd3ys9qQx3lZKsXxqfKv+U3gitWXC7GwrI61jiSIkFbbvm1RRmxMx2Oq5frygVEo1qDn8l3mZkclSkZW8yNDechN2KhkJcy0NFU33As5+aZ/KU8RZyfyd/6R/rt9qecdI/99Dg6fhU1JUEm7+1H+pYaNBZ/4y48wexr6ZI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1732897980; c=relaxed/simple; bh=qfqYB5CY+zrrWoF1p5PA1wE61kagKg3f8qMfUMwrH2s=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=i3k7vZ9rsjn+0ojM6E+3jiSw83CGNYAXiY6Q+MDAIjkH8zp1K8tDQysHaESbp9iuDpi4H8avvfg6W+av0ssBGK/c9omC7kwSbkk3Ogh3I2ydldGfM9fLpD/U3Eszhbt6pSUL7riXqgeLOpLtFyJ+iRDZ/F28xRZmbHiu0UfpmJA= 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=Dql8t/Ma; 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="Dql8t/Ma" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-434a73651e2so14102585e9.1 for ; Fri, 29 Nov 2024 08:32:57 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897976; x=1733502776; 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=a5YzoZTIOzo/0986DnSppxfBI0p8rQsJVoOP2q6LCvk=; b=Dql8t/Ma5WmemoqP8zsSfv7xLdd6OWEpELWAx9/45cSK4bX2aEUCh/7mA/aMBsQVh9 rXR4r/Qib2NjWY8ZZ6yC05ba6tfx+uczyYJ3rGKRmkxYUv++R2U90oFfNLxYKfwilcrx 8cPlT8YqfuWuNFPumz9G1VVmiFsErxN7ZsWDpWR5vUD/80ei816BLdLSeFHfiE0xN5dt +aPJ29NLd2M0nV+dLU+mfGuGdb1x6GETNRTseadw8wU8A1fr8wd2vGvSUmtpeLEqwRo9 m3OX5o0EVd/fcH/9HIW5fPB9kRyUmr8Rg+xBVT+tFA+qmFMTI/kAkS21lyoqtVs5yfPk lzqg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897976; x=1733502776; 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=a5YzoZTIOzo/0986DnSppxfBI0p8rQsJVoOP2q6LCvk=; b=PUMhViLOu1jQuN6NiKqQ1fS+RyaxDJJ5YsIYB+TuMLajj3I96Y4u/iLkXNyTIq30Yw y8KsrlwyC6oHluxfdunND1TJ7lP0uVnayeknun55pFrI6J9t21roIl0UU5weTDiHJjWT qkqGkcY0IHc41Slyag6Txpl4ToQ1LefabIBFOSV7xvGkbSewnxCr77/L+AJ0EbD/z8vL 1MCAELR5PJo8ZIFmZMYnQVdFkvnfWK9/YX+Tn8Xiph5LzzLswEDKIdYO0S57CRF7ZmWA lAtYUEm5q+ixQ4yhYz42eGpj1eHoWmdk+VHs6KWNRMYAli314iBpA96juSG5VEBA8qb0 vXug== X-Forwarded-Encrypted: i=1; AJvYcCXJ9K3IxFVUfj10LI3enFgHsULvS25gfbeSXWTKUs7qs7TtZrDwDj5x8hOhnq7Ol4zvtJEGdC/7BsQJWCs=@vger.kernel.org X-Gm-Message-State: AOJu0YwaUgiTupT/xvePW8BFKXBnVfnNVEPLlVEtPIkNUJEgnMzvAWsd Xrei0m5/xa8AQfc8axkqViivuPFkJiFcoEE+WUtBFaEIpOfYGs3HtYaep6y/WnXS+0PTt+oqML0 3NX4+M5bp+N0mjA== X-Google-Smtp-Source: AGHT+IHze4h565Aoh2DoHrp99j4LSl0kVAIFqSGJmgywq3dMrDmKMH3RGZw03PbIllpNmKnyBzK6/JzPDiaVmPE= X-Received: from wmoq13.prod.google.com ([2002:a05:600c:46cd:b0:431:1260:2444]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3146:b0:434:a169:6ff8 with SMTP id 5b1f17b1804b1-434a9db8423mr128388385e9.3.1732897976603; Fri, 29 Nov 2024 08:32:56 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:35 +0000 In-Reply-To: <20241129-vma-v10-0-4dfff05ba927@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20241129-vma-v10-0-4dfff05ba927@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=9643; i=aliceryhl@google.com; h=from:subject:message-id; bh=qfqYB5CY+zrrWoF1p5PA1wE61kagKg3f8qMfUMwrH2s=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeyunSmy45C3+dwg4sTBb0910JzVks9XKF/WA HFj/FmBAwyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nsrgAKCRAEWL7uWMY5 Ro6+D/0eS03pE3ZODh9XPuyPKCvsQdzzedfXMU5VED+gXAd+veD/s0mctxSF5+dCrZH/WzcSeG0 E0wvbKQGYvTYjDOrABcB4VUKPw13cEX5BB5FFhslBKJaVfKdQjRib4r2lFNk8nm2hDydoigQEf5 Necf6GOJbCrOgVx9Rkn6E2leJwlSrSiobggvnXvvPuJjEcyVX02iG/xj9eaQBwg8R9x2cozehqe 5AZsxJl9JZqNPPCvnMquL3HhnS51Tx9OzpfikrhsWXxOYqQMbaSYCsq3JREbXVut+Wyf8plCNvF 8sUwhycV5tQES/p36rGUFikzr7Z4qUmQbkCF8XX/gOJshCUGnlnMOfXLf3cZQAUn7/FZWVwIVe2 07m+UyPyzz2M5AMMEaGHizR1WiL1I09EhEDgdNrnAqTA+LPowkPYhRE+urCovOVmwG2KEVjlu+B 6sNpFxFnHDbpUAMnIR+WBFeG6+ZeDfSrrC46g59620JfvBYSBcS17v0TvqAIsHsPC8w41FLcPPD O/6dcaOE9l5QO27XYeCm2uOSGn8Mn4SemMv9PK7a7V4ECtf9kuFUJ7CBD0KjnZwz94CrvGAxwPq dkZ21D6ljWsx+KrHr5XkZ4KglFbqxP/ZE6f8FCSkOH/53QWrOW//QlkjLpp08wULZs6JDDB43rw bJ2rL11wZz/I6WQ== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-2-4dfff05ba927@google.com> Subject: [PATCH v10 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 , Christian Brauner , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This adds a type called VmAreaRef which is used when referencing a vma that you have read access to. Here, read access means that you hold either the mmap read lock or the vma read lock (or stronger). Additionally, a vma_lookup method is added to the mmap read guard, which enables you to obtain a &VmAreaRef in safe Rust code. This patch only provides a way to lock the mmap read lock, but a follow-up patch also provides a way to just lock the vma read lock. Acked-by: Lorenzo Stoakes (for mm bits) Reviewed-by: Jann Horn Signed-off-by: Alice Ryhl --- rust/helpers/mm.c | 6 ++ rust/kernel/mm.rs | 21 ++++++ rust/kernel/mm/virt.rs | 182 +++++++++++++++++++++++++++++++++++++++++++++= ++++ 3 files changed, 209 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 84cba581edaa..ace8e7d57afe 100644 --- a/rust/kernel/mm.rs +++ b/rust/kernel/mm.rs @@ -12,6 +12,8 @@ }; use core::{ops::Deref, ptr::NonNull}; =20 +pub mod virt; + /// A wrapper for the kernel's `struct mm_struct`. /// /// Since `mm_users` may be zero, the associated address space may not exi= st anymore. You can use @@ -210,6 +212,25 @@ pub struct MmapReadGuard<'a> { _nts: NotThreadSafe, } =20 +impl<'a> MmapReadGuard<'a> { + /// Look up a vma at the given address. + #[inline] + pub fn vma_lookup(&self, vma_addr: usize) -> Option<&virt::VmAreaRef> { + // SAFETY: We hold a reference to the mm, so the pointer must be v= alid. Any value is okay + // for `vma_addr`. + let vma =3D unsafe { bindings::vma_lookup(self.mm.as_raw(), vma_ad= dr as _) }; + + if vma.is_null() { + None + } else { + // SAFETY: We just checked that a vma was found, so the pointe= r is valid. Furthermore, + // the returned area will borrow from this read lock guard, so= it can only be used + // while the mmap read lock is still held. + unsafe { Some(virt::VmAreaRef::from_raw(vma)) } + } + } +} + impl Drop for MmapReadGuard<'_> { #[inline] fn drop(&mut self) { diff --git a/rust/kernel/mm/virt.rs b/rust/kernel/mm/virt.rs new file mode 100644 index 000000000000..032eea4d4690 --- /dev/null +++ b/rust/kernel/mm/virt.rs @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Virtual memory. + +use crate::{bindings, types::Opaque}; + +/// A wrapper for the kernel's `struct vm_area_struct` with read access. +/// +/// It represents an area of virtual memory. +/// +/// # Invariants +/// +/// The caller must hold the mmap read lock or the vma read lock. +#[repr(transparent)] +pub struct VmAreaRef { + vma: Opaque, +} + +// Methods you can call when holding the mmap or vma read lock (or strong)= . They must be usable no +// matter what the vma flags are. +impl VmAreaRef { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is valid for the duration of 'a, an= d that the mmap or vma + /// read lock (or stronger) is held for at least the duration of 'a. + #[inline] + pub unsafe fn from_raw<'a>(vma: *const bindings::vm_area_struct) -> &'= a Self { + // SAFETY: The caller ensures that the invariants are satisfied fo= r the duration of 'a. + unsafe { &*vma.cast() } + } + + /// Returns a raw pointer to this area. + #[inline] + pub fn as_ptr(&self) -> *mut bindings::vm_area_struct { + self.vma.get() + } + + /// Returns the flags associated with the virtual memory area. + /// + /// The possible flags are a combination of the constants in [`flags`]. + #[inline] + pub fn flags(&self) -> vm_flags_t { + // SAFETY: By the type invariants, the caller holds at least the m= map read lock, so this + // access is not a data race. + unsafe { (*self.as_ptr()).__bindgen_anon_2.vm_flags as _ } + } + + /// Returns the (inclusive) start address of the virtual memory area. + #[inline] + pub fn start(&self) -> usize { + // SAFETY: By the type invariants, the caller holds at least the m= map read lock, so this + // access is not a data race. + unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_sta= rt as _ } + } + + /// Returns the (exclusive) end address of the virtual memory area. + #[inline] + pub fn end(&self) -> usize { + // SAFETY: By the type invariants, the caller holds at least the m= map read lock, so this + // access is not a data race. + unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_end= as _ } + } + + /// Zap pages in the given page range. + /// + /// This clears page table mappings for the range at the leaf level, l= eaving all other page + /// tables intact, and freeing any memory referenced by the VMA in thi= s range. That is, + /// anonymous memory is completely freed, file-backed memory has its r= eference count on page + /// cache folio's dropped, any dirty data will still be written back t= o disk as usual. + #[inline] + pub fn zap_page_range_single(&self, address: usize, size: usize) { + let (end, did_overflow) =3D address.overflowing_add(size); + if did_overflow || address < self.start() || self.end() < end { + // TODO: call WARN_ONCE once Rust version of it is added + return; + } + + // SAFETY: By the type invariants, the caller has read access to t= his VMA, which is + // sufficient for this method call. This method has no requirement= s on the vma flags. The + // address range is checked to be within the vma. + unsafe { + bindings::zap_page_range_single( + self.as_ptr(), + address as _, + size as _, + core::ptr::null_mut(), + ) + }; + } +} + +/// The integer type used for vma flags. +#[doc(inline)] +pub use bindings::vm_flags_t; + +/// All possible flags for [`VmAreaRef`]. +pub mod flags { + use super::vm_flags_t; + use crate::bindings; + + /// No flags are set. + pub const NONE: vm_flags_t =3D bindings::VM_NONE as _; + + /// Mapping allows reads. + pub const READ: vm_flags_t =3D bindings::VM_READ as _; + + /// Mapping allows writes. + pub const WRITE: vm_flags_t =3D bindings::VM_WRITE as _; + + /// Mapping allows execution. + pub const EXEC: vm_flags_t =3D bindings::VM_EXEC as _; + + /// Mapping is shared. + pub const SHARED: vm_flags_t =3D bindings::VM_SHARED as _; + + /// Mapping may be updated to allow reads. + pub const MAYREAD: vm_flags_t =3D bindings::VM_MAYREAD as _; + + /// Mapping may be updated to allow writes. + pub const MAYWRITE: vm_flags_t =3D bindings::VM_MAYWRITE as _; + + /// Mapping may be updated to allow execution. + pub const MAYEXEC: vm_flags_t =3D bindings::VM_MAYEXEC as _; + + /// Mapping may be updated to be shared. + pub const MAYSHARE: vm_flags_t =3D bindings::VM_MAYSHARE as _; + + /// Page-ranges managed without `struct page`, just pure PFN. + pub const PFNMAP: vm_flags_t =3D bindings::VM_PFNMAP as _; + + /// Memory mapped I/O or similar. + pub const IO: vm_flags_t =3D bindings::VM_IO as _; + + /// Do not copy this vma on fork. + pub const DONTCOPY: vm_flags_t =3D bindings::VM_DONTCOPY as _; + + /// Cannot expand with mremap(). + pub const DONTEXPAND: vm_flags_t =3D bindings::VM_DONTEXPAND as _; + + /// Lock the pages covered when they are faulted in. + pub const LOCKONFAULT: vm_flags_t =3D bindings::VM_LOCKONFAULT as _; + + /// Is a VM accounted object. + pub const ACCOUNT: vm_flags_t =3D bindings::VM_ACCOUNT as _; + + /// Should the VM suppress accounting. + pub const NORESERVE: vm_flags_t =3D bindings::VM_NORESERVE as _; + + /// Huge TLB Page VM. + pub const HUGETLB: vm_flags_t =3D bindings::VM_HUGETLB as _; + + /// Synchronous page faults. (DAX-specific) + pub const SYNC: vm_flags_t =3D bindings::VM_SYNC as _; + + /// Architecture-specific flag. + pub const ARCH_1: vm_flags_t =3D bindings::VM_ARCH_1 as _; + + /// Wipe VMA contents in child on fork. + pub const WIPEONFORK: vm_flags_t =3D bindings::VM_WIPEONFORK as _; + + /// Do not include in the core dump. + pub const DONTDUMP: vm_flags_t =3D bindings::VM_DONTDUMP as _; + + /// Not soft dirty clean area. + pub const SOFTDIRTY: vm_flags_t =3D bindings::VM_SOFTDIRTY as _; + + /// Can contain `struct page` and pure PFN pages. + pub const MIXEDMAP: vm_flags_t =3D bindings::VM_MIXEDMAP as _; + + /// MADV_HUGEPAGE marked this vma. + pub const HUGEPAGE: vm_flags_t =3D bindings::VM_HUGEPAGE as _; + + /// MADV_NOHUGEPAGE marked this vma. + pub const NOHUGEPAGE: vm_flags_t =3D bindings::VM_NOHUGEPAGE as _; + + /// KSM may merge identical pages. + pub const MERGEABLE: vm_flags_t =3D bindings::VM_MERGEABLE as _; +} --=20 2.47.0.338.g60cca15819-goog From nobody Wed Jan 15 08:44:33 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 2EC7319F117 for ; Fri, 29 Nov 2024 16:32:59 +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=1732897981; cv=none; b=k8h15Ps1nF29oBDQJujag+HjR+UKbS+5I88IoQBR45siTWtB+f62tGgqWL4RFsP7HDVMWGFazr83dfdC7CqG0rjcF+gI+wNUamspK5Ij9nJlzl79lLo8eflEDVfbfert8hf15YZetjkhZVLJBH/hR9vKluRRdycNLCIFEgUfk1E= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1732897981; c=relaxed/simple; bh=d5PVsjv5Dk2wDmJvfAYSWwtPELYfnKxOPm05AGfN2t4=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=LB3ECB2Iv8wbhQRwtnUfLj8ObMJszl8N/4sC2rIjspRNZy4YFg/bzuBqOeU20DFXM9hYDsuKev4fLJJr9soAVbq6V5UkI1vv0hjRNqq46R5s1D7KZMruM1/2g7eXfqIhIbTgZx/ihXHPPec3OoOjbIJbQ2m0RW0iwyvy1aP7BIM= 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=JWGnJR/2; 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="JWGnJR/2" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-434a27c9044so12060065e9.0 for ; Fri, 29 Nov 2024 08:32:59 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897978; x=1733502778; 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=94NYmr5c9ppvPDgAeOeEOikiVfAFQj6mOJl+8qXFwoY=; b=JWGnJR/2P7cmk0YSYHSXWZzFlGct2/eQ05YrtauHoEkTWV7HmhoOLr8PlyptV+jMBO /ykDowJmSlFVaDZl5F8ua0Dcqxx3VYGMArsoLP2efnEjLhb4h9/gXLDuHeGcDk0H99RW XUG+acVpx/XfA3gLyZ8klvCIdZrf+eDuSrhuGJ03IRLO2Dq8/UMxIPvVGE34VxQ069ty qNEmgn+W80hD0+r/1z5cEgPgcQuKXkuCTA5uxbf5cAYsOO07Eh+ZLpSm2civNckDnTc1 uxPrC9HNFEdjwLor2AGKheKdXKQjppaOGMuN2Hq/lx2Kv16IgUexzfrMo0gTfmUnoubg 61FQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897978; x=1733502778; 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=94NYmr5c9ppvPDgAeOeEOikiVfAFQj6mOJl+8qXFwoY=; b=PoW0jsuZcPk1u4ZH18sDmMhERP/s+eH9QdO9BvQKHkqZnpVJYsQRZGaKOC6BtaMWod /2HvGmndaXKsQwXssq1Pi2CqAErzDU7r6J16KCXYGBng+F+w3NmSVuLqPU/qP+00PtJg 6crRJh85wyqh2Ak7YtG+zjI4WnmzYHWjzXge5JqaQySd9tgb9LnSEeJluugvil8AENWd UjjxRsabRLWN61LtkWjsIgVwgswJQ6ceJOebmuxS1c9Fb6DZoFiIt0eDPCRqc8tgI9fx LjJlP6GAUsUFkZ9V/LWu7uKS3BSgzFq01nMbkpfZaWRksLniwGDA3RqEQKGrGrinobeF Q+IA== X-Forwarded-Encrypted: i=1; AJvYcCXhi9jLbLBiD8us0g/UToCLvhn8lYc31TxbpD49QiWCBCcu0pJ7bEbV2XOsN6CRlkJwn773vrzPbmBC+n8=@vger.kernel.org X-Gm-Message-State: AOJu0YwbUhOhrlgnlKPess78MFsa0h/9ASEgqOk1EyW1n5Ms9NAb/MFL B5YIdvSotE4QHfO/IL9sGXStxhKYME3qNvdQEQph8hfuChV0L+vyxBmvxJy22ZCXWr5tIEAZBFA dHUe4oBGAagNo/A== X-Google-Smtp-Source: AGHT+IGrQvjMp3red6jWsR1GGii7AoihEDmHs9z4agdmTgk8GW6+jX/m+iq6oJEN70Cr+c0nxG1Xp0i1oBsbhdE= X-Received: from wmpq23.prod.google.com ([2002:a05:600c:3317:b0:42c:b336:8685]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:4750:b0:431:5871:6c5d with SMTP id 5b1f17b1804b1-434a9dbbd1amr138602905e9.3.1732897978665; Fri, 29 Nov 2024 08:32:58 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:36 +0000 In-Reply-To: <20241129-vma-v10-0-4dfff05ba927@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20241129-vma-v10-0-4dfff05ba927@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3694; i=aliceryhl@google.com; h=from:subject:message-id; bh=d5PVsjv5Dk2wDmJvfAYSWwtPELYfnKxOPm05AGfN2t4=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeyuYNpPwhGV89bUWs5GRH8aX7HH6P4Ztr1U0 bGuq73pEJ2JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nsrgAKCRAEWL7uWMY5 RqU2EACmE2VsGq4kuy2dH1HczWotSUGlrvZA17ocbWpWcLJh0JQ6N+LZjV0Xu6m6TTovT5IofyS XcN7yaQjwdI9oGmRkOFB1oRLjjAxEUwr46P/sjxC1UgiuiQaJv0auLW8LP5QiGKA+UaNqGQCcdO eGQMKqM4TikGluAykvFlxukfGrYNYTU6sQOVfaZLY2t+/SVMUva/uwFPQh1gpv9vTB9D/Sgi5Wo UCvQFh3JwkBvVaijNJoF6ONbRTdCbLiMDc9dVRNzZfDRw0uR4fQDzMEkSRkJ3v5+fScreYBljBK k0B1DXlJBNp212kQGxXIA0aC32E2UwuKNb9dHMPpBko8yZwn7Rrf3sbMU1fcfiXhneXaFOUprO9 H1v5/MRfiqsXXQpFiPQP1+SRjuHSlQ1wJnCOKaViw++5mXvDilf2gbMZO8HhXVGSB55HaS0a3U/ NjQPkNTFXTBDV8r76dThH5WrcX+Es5A2yJ9gVfTy+Busr0pH9IgPXxO6lorkt4eOoKXvgD1pto7 kfaSTKS+sHsPqpcgAJeI8RikZWbszcU+qzT2Z0y1akLeFVehqY5O7oMjESLS16mMpy4ui+8Dkc5 wDnJuzljFqHjFo7j68LGNQ7CVPHglJvW6OslNF4+CePBEE/j1kEWVjZl4+WoxVFvU+zMzj8t4cw YUSBsw9j8CvU+QQ== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-3-4dfff05ba927@google.com> Subject: [PATCH v10 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 , Christian Brauner , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable The vm_insert_page method is only usable on vmas with the VM_MIXEDMAP flag, so we introduce a new type to keep track of such vmas. The approach used in this patch assumes that we will not need to encode many flag combinations in the type. I don't think we need to encode more than VM_MIXEDMAP and VM_PFNMAP as things are now. However, if that becomes necessary, using generic parameters in a single type would scale better as the number of flags increases. Acked-by: Lorenzo Stoakes (for mm bits) Signed-off-by: Alice Ryhl --- rust/kernel/mm/virt.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/rust/kernel/mm/virt.rs b/rust/kernel/mm/virt.rs index 032eea4d4690..fa1fd6aa703c 100644 --- a/rust/kernel/mm/virt.rs +++ b/rust/kernel/mm/virt.rs @@ -4,7 +4,14 @@ =20 //! Virtual memory. =20 -use crate::{bindings, types::Opaque}; +use crate::{ + bindings, + error::{to_result, Result}, + page::Page, + types::Opaque, +}; + +use core::ops::Deref; =20 /// A wrapper for the kernel's `struct vm_area_struct` with read access. /// @@ -91,6 +98,67 @@ pub fn zap_page_range_single(&self, address: usize, size= : usize) { ) }; } + + /// Check whether the `VM_MIXEDMAP` flag is set. + /// + /// This can be used to access methods that require `VM_MIXEDMAP` to b= e set. + #[inline] + pub fn as_mixedmap_vma(&self) -> Option<&VmAreaMixedMap> { + if self.flags() & flags::MIXEDMAP !=3D 0 { + // SAFETY: We just checked that `VM_MIXEDMAP` is set. All othe= r requirements are + // satisfied by the type invariants of `VmAreaRef`. + Some(unsafe { VmAreaMixedMap::from_raw(self.as_ptr()) }) + } else { + None + } + } +} + +/// A wrapper for the kernel's `struct vm_area_struct` with read access an= d `VM_MIXEDMAP` set. +/// +/// It represents an area of virtual memory. +/// +/// # Invariants +/// +/// The caller must hold the mmap read lock or the vma read lock. The `VM_= MIXEDMAP` flag must be +/// set. +#[repr(transparent)] +pub struct VmAreaMixedMap { + vma: VmAreaRef, +} + +// Make all `VmAreaRef` methods available on `VmAreaMixedMap`. +impl Deref for VmAreaMixedMap { + type Target =3D VmAreaRef; + + #[inline] + fn deref(&self) -> &VmAreaRef { + &self.vma + } +} + +impl VmAreaMixedMap { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is valid for the duration of 'a, an= d that the mmap read lock + /// (or stronger) is held for at least the duration of 'a. The `VM_MIX= EDMAP` flag must be set. + #[inline] + pub unsafe fn from_raw<'a>(vma: *const bindings::vm_area_struct) -> &'= a Self { + // SAFETY: The caller ensures that the invariants are satisfied fo= r the duration of 'a. + unsafe { &*vma.cast() } + } + + /// Maps a single page at the given address within the virtual memory = area. + /// + /// This operation does not take ownership of the page. + #[inline] + pub fn vm_insert_page(&self, address: usize, page: &Page) -> Result { + // SAFETY: The caller has read access and has verified that `VM_MI= XEDMAP` is set. The page + // is order 0. The address is checked on the C side so it can take= any value. + to_result(unsafe { bindings::vm_insert_page(self.as_ptr(), address= as _, page.as_ptr()) }) + } } =20 /// The integer type used for vma flags. --=20 2.47.0.338.g60cca15819-goog From nobody Wed Jan 15 08:44:33 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 3B84F1A070E for ; Fri, 29 Nov 2024 16:33:02 +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=1732897984; cv=none; b=gl1GQTBbfeA1GAPlduHYltR5bR+7+WOqgQc08HrAWxkxk95k8J+hIJ0vzvXL8Qy0l2ZprtqW2Y6Ucy/qG39rt2sOWkPp7uRGqyNteHbXMgiPYnVf3j+yhp7xWFBHrttOiw04PKaVcs7USasLCuWaB9kP51bhm+sVjdca/VhSSYU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1732897984; c=relaxed/simple; bh=Vj+fM1HEWgk9zeZ3nCQftraSe6z/pjvOnZ1xL1atMIA=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=n59IozzAFkFoTOPzJFLu0Vrl2AAFUWcgy8vsr0UA6Eo7CuF/lezP9cGWUSnqeBd6F6MBC7db73XngyzGPgeErp6AHZ7CP5QFktzqIJXy2f9600qh8cLDJnDsb2mI1BTm1X2qMXvQ1wRNGQWI42Lixd/sH00Ik448B9NYtBtiPUQ= 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=wenG2ZNV; 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="wenG2ZNV" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-385d7611ad3so847436f8f.2 for ; Fri, 29 Nov 2024 08:33:01 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897980; x=1733502780; 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=XEZERPJwfgVL12T7CsV2RsjLJQFd2+FhD7A3aSN4nWQ=; b=wenG2ZNVg0Umvn6dI7GN1vmcCxnJs5jyB/DMk5/dBqHlO5zp27WwvnWu9n0TjSLB+X uPe3VdIzRVtavft/ysPUiWA4IkLKEnd2zbXCECWm545v0tMT4+oSDIeo52FYivq2qi3X QtLuv4TwYN5ZLJB/sAjGC1t/sedN8bN+nSmRH7yxaaF4ZxAobBAYjmzNdrnQSKkeRlsS 1rQOpACmZr+IO7bvFrE+OjuQA0j3dW+5VwzlOIoolmA6hMNXgNLkzJTi36DtOkpIkgGo dai/kaEGY3cK2frLV0iQ6c2qIYg6/ZdUdu+8T7izPe9SwOobNhuzYP/XPLpREQDOvHMK KDLA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897980; x=1733502780; 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=XEZERPJwfgVL12T7CsV2RsjLJQFd2+FhD7A3aSN4nWQ=; b=ch9cY0XPwLk+54Ypf8XOqStk3A3HVjx1ioLjiE1bYc5+tGBnPj48OFEyhZYaU4J69h tdbHPGr14KmZze1ZBKybJYudIpgx8ZlkW6/gnwK2dIXIFEN1uLD2cziXg4NTSLQZ3goP GtZ1S69YQC/aR0gWPDVh4Aytw+JULeguBeBt4On8d9bJQmnMDeye02lYc2rQKPDQA2Y/ p2BXl1Pen2lY8mUW8SrZVjvxy+d/dRp0KRnaJf75AemDFz3XRULkp5NYAA5Y2xD/lQ71 57wK4ZxxCOEaFCOsbbP7I9qOfhbaumADUp4ch30VMpAfMNScQPyCIZclhpdcdnl7B8bC vBPA== X-Forwarded-Encrypted: i=1; AJvYcCUaxf60P1J+0k057XInO7g+nPVRZJZU6fIYn+Xg/jHHuR447x1LyZLO7iWt8m+VpQOm/KfXZyLUZInr6Uk=@vger.kernel.org X-Gm-Message-State: AOJu0YzeXccsk7bdXMYhmyT+cEHSNcokhK++qHVB3QS08s4Vm/1c6PxB UoLC8AOtKZrmUf+OZH76JCd2Gh4YwVMm8XaM/eaXxbyLBdAVW47pE/IuDb4U5wSQ1AAUe6nqvGz ogvvZLYjA+SAyNw== X-Google-Smtp-Source: AGHT+IEtMdEbBKfTi44I0hQxKs9SwxHv8NrQJqJsf3ce8ASa6YkaH62l4mchnBzjtU1EUoOkexS5OiFPJNiqBPU= X-Received: from wrbeh6.prod.google.com ([2002:a05:6000:4106:b0:382:30eb:98f7]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6000:491a:b0:385:bc42:52e4 with SMTP id ffacd0b85a97d-385c6eba8bemr11919119f8f.24.1732897980729; Fri, 29 Nov 2024 08:33:00 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:37 +0000 In-Reply-To: <20241129-vma-v10-0-4dfff05ba927@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20241129-vma-v10-0-4dfff05ba927@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3946; i=aliceryhl@google.com; h=from:subject:message-id; bh=Vj+fM1HEWgk9zeZ3nCQftraSe6z/pjvOnZ1xL1atMIA=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeyve8NrjNvn5/AdaiW267/FN/DvoteK61Oo4 9jv/idgWVyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nsrwAKCRAEWL7uWMY5 RpxAEACz7Q3Z15K9yn6UUnABmC93QguEXyoGn4fILedLcdfZiuIXMtFqpbgt30kuS+yGQJL41+B 1GNgFO57jYNMEHUZv87T8ItmFDJ2mKpQ7kteUR7+MXAXcpwOYI80gz695ogwkssoeMvfrllsf8c N+HTsQlzoRBWcwek+nZnh0RG5ZSR3KEsKtLBZ49/gqJi5p+7SNJnuvR5k6EJC75DGtQw7vYbmxe p+5Hqd2L/mzOLVGo3cBp53uEcawKUUU1NBCBlOI3pPhOssdZb2CETukZ5ZUbOQcACHFLeyOyt1Z MI/FAqyGKDlSINeXZsUn1izy/oxYKx+6bH/ldZ4G9/2+ffHrhgx0Z4vKQ2MCqrONvgsRM3t5U/h 13ldm0DP7VL6NEMeZ1EFquTl9VOWVd48ThVZgEOgK+BMN41A0S4mu2SkL+lOu7hnX+WtI8NWEJS DQ+5Nr1CLoaGxIEDMWfAs2ojsL6eW5NXDoVpmX+EG3dX69N95evSpj4kGm+Op6PKwMSTD8vbmtf 5h4v8zcXVcN5EFehLmSy+UqhnFASNEFy6uSDCZiEN2TZ6cgwWdNkhV+bu7OtvnwUViqGSts+rG2 44LoVmhzRJZhOZbXtPq+CGaRyvxebiBx35ZsGXGC4nQVfZz4wjyrRIfU3H2pHHhAYuG8JkqrETk HrhIta1iCfIzR/Q== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-4-4dfff05ba927@google.com> Subject: [PATCH v10 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 , Christian Brauner , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Currently, the binder driver always uses the mmap lock to make changes to its vma. Because the mmap lock is global to the process, this can involve significant contention. However, the kernel has a feature called per-vma locks, which can significantly reduce contention. For example, you can take a vma lock in parallel with an mmap write lock. This is important because contention on the mmap lock has been a long-term recurring challenge for the Binder driver. This patch introduces support for using `lock_vma_under_rcu` from Rust. The Rust Binder driver will be able to use this to reduce contention on the mmap lock. Acked-by: Lorenzo Stoakes (for mm bits) Reviewed-by: Jann Horn Signed-off-by: Alice Ryhl --- rust/helpers/mm.c | 5 +++++ rust/kernel/mm.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 61 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 ace8e7d57afe..425b73a9dfe6 100644 --- a/rust/kernel/mm.rs +++ b/rust/kernel/mm.rs @@ -13,6 +13,7 @@ use core::{ops::Deref, ptr::NonNull}; =20 pub mod virt; +use virt::VmAreaRef; =20 /// A wrapper for the kernel's `struct mm_struct`. /// @@ -170,6 +171,32 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_st= ruct) -> &'a MmWithUser { unsafe { &*ptr.cast() } } =20 + /// Attempt to access a vma using the vma read lock. + /// + /// This is an optimistic trylock operation, so it may fail if there i= s contention. In that + /// case, you should fall back to taking the mmap read lock. + /// + /// When per-vma locks are disabled, this always returns `None`. + #[inline] + pub fn lock_vma_under_rcu(&self, vma_addr: usize) -> Option> { + #[cfg(CONFIG_PER_VMA_LOCK)] + { + // SAFETY: Calling `bindings::lock_vma_under_rcu` is always ok= ay given an mm where + // `mm_users` is non-zero. + let vma =3D unsafe { bindings::lock_vma_under_rcu(self.as_raw(= ), vma_addr as _) }; + if !vma.is_null() { + return Some(VmaReadGuard { + // SAFETY: If `lock_vma_under_rcu` returns a non-null = ptr, then it points at a + // valid vma. The vma is stable for as long as the vma= read lock is held. + vma: unsafe { VmAreaRef::from_raw(vma) }, + _nts: NotThreadSafe, + }); + } + } + + None + } + /// Lock the mmap read lock. #[inline] pub fn mmap_read_lock(&self) -> MmapReadGuard<'_> { @@ -238,3 +265,32 @@ fn drop(&mut self) { unsafe { bindings::mmap_read_unlock(self.mm.as_raw()) }; } } + +/// A guard for the vma read lock. +/// +/// # Invariants +/// +/// This `VmaReadGuard` guard owns the vma read lock. +pub struct VmaReadGuard<'a> { + vma: &'a VmAreaRef, + // `vma_end_read` must be called on the same thread as where the lock = was taken + _nts: NotThreadSafe, +} + +// Make all `VmAreaRef` methods available on `VmaReadGuard`. +impl Deref for VmaReadGuard<'_> { + type Target =3D VmAreaRef; + + #[inline] + fn deref(&self) -> &VmAreaRef { + self.vma + } +} + +impl Drop for VmaReadGuard<'_> { + #[inline] + fn drop(&mut self) { + // SAFETY: We hold the read lock by the type invariants. + unsafe { bindings::vma_end_read(self.vma.as_ptr()) }; + } +} --=20 2.47.0.338.g60cca15819-goog From nobody Wed Jan 15 08:44:33 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 54FB51A0BCA for ; Fri, 29 Nov 2024 16:33:04 +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=1732897986; cv=none; b=qHtWTDFNWy5+w6yel60XM85cc6rM0Dlr2iE9iR8BAg2EqfjFYq6+KPcC9aeeQ4ROxWFM9SgLPKrLykoCyvxJEfbrRX2bbuqwqSdjlzQaQaoYs6AuuQQpFj2YbUskkwHCI8m61Xa8ELAH6eTiuEP3fIAqdcUXkQwdTL/yg+JdXqQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1732897986; c=relaxed/simple; bh=rBEGLc7KJG1nI+I3PCkS6QqEUHC7WTE77ZFEyztUDIc=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=kWqFOPIr/0srko/JVAdhLCElxxBdj0g+EEkc3ipnwFuhHrL8DzxR1CSw4ln6FD2U982U89xR2Ym19L9kRC3znnUyBMuulSVUvEE+Ui17scpf8EK1+OnqnpuogsztVUbsC+BXBVOLlEWPS2PyE4LjGwMv2r+OnEVrP6jgks4guss= 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=hWqOxIlD; 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="hWqOxIlD" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-38256b20f5fso1442485f8f.1 for ; Fri, 29 Nov 2024 08:33:04 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897983; x=1733502783; 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=NxiAaOQixinTmMpuFlr9Z7Cs/OKNMeW1CE1Bg5Rf1Zc=; b=hWqOxIlD7vG5pd4lsDxI+x8sLdVFcI2YqsNskLtWGk5Zix4f5Es1PfJ3j2k6WriogO WTjK/BnCgV340HfVvQFxyssGmNQ7ksslZx3h8oRZ8Ire3RMCPTUduDQ9plWAZebU1ijH 9io07cXjMSvROzrjyPElqrzFDWSXDNbQmEuNNZU+S8hbu3Mz+rH/w6wVck+c/Y5BtMVB zA/46uM9ISAibnZXwrD1Vrhpj5gRX7TWKaTjB6kZOkkCE03uH9g88Y6+jhYE2yESG/W9 sIZH11TP/umTfHVorBfY7SNDnyuGVW9GTmUFiNPXCbQt+CDeElEqAQ0EiCLKbIQuQ5v6 k90Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897983; x=1733502783; 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=NxiAaOQixinTmMpuFlr9Z7Cs/OKNMeW1CE1Bg5Rf1Zc=; b=NtJ6Rhxt15SiIjQEL+6TQI4/NRgvSUyxbZLNWujLfMRLR0FnAogaVjnJDBOHTEnzPH C6eoN5Epena6a7lh/0jaW/v3SvqTkl1UL2uQRS2QG+sfg7bTzDFc3samq2hYYwW8/GMl iYTafTBFPsmsTrFKwxIL2zYHRNgvNW0dsvlH1Kb/nShUDc7ZFde85J6Xnj2QIR78KF5u r+Ien59Rj9fDryWr8d5Dz9HWVM7+eMqfDOmuqUXp4S7MCy2qqU/VYkIoNkjRmQk/AFHL VnxmJxP3Y9rbZqLTrOub6CV6Jip/iI7QRAelyhS1xbZmMkyQOU9bG9O2sbL8qzRCUudk 0rrw== X-Forwarded-Encrypted: i=1; AJvYcCUi9v9RBTGF1Xn8NqJwgJ/HAeE7ECM3CIYWa7cT9O6jYAkFADZB2aSftVdTJ0ft6FOP2DDEX7pDLt5Vxi4=@vger.kernel.org X-Gm-Message-State: AOJu0YxB9MLRM2ed+p2PBOjV3DH5LmjmOrba0qEJaWxs1AN7B9JlF5Xm IeniOXacPftxG4raJFlHDarDqRqA8e8pDwQhdCQYd1OhrRacQFHoc4l5wTkMGAaTYMji0oRav28 xE6hQEeSPJK2oLA== X-Google-Smtp-Source: AGHT+IGYb3T/wZgxg6wvfixNQvKu7OW4dXOoNjGb+FLVFT5jRj0xJ7uK1bZMJYsE5nPmUYdm2iSLsb9tE8N9Qhw= X-Received: from wmbjw2.prod.google.com ([2002:a05:600c:5742:b0:434:a4bc:534f]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6000:400b:b0:382:486f:1360 with SMTP id ffacd0b85a97d-385c6ed9824mr13201148f8f.44.1732897982795; Fri, 29 Nov 2024 08:33:02 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:38 +0000 In-Reply-To: <20241129-vma-v10-0-4dfff05ba927@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20241129-vma-v10-0-4dfff05ba927@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3090; i=aliceryhl@google.com; h=from:subject:message-id; bh=rBEGLc7KJG1nI+I3PCkS6QqEUHC7WTE77ZFEyztUDIc=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeywnZuEoxDobqs4lWzeHdYCGEpayHKpr1Fk9 ltPcXjwVWmJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nssAAKCRAEWL7uWMY5 Rn6LD/9y8AHiDmndnB+qvZq4H5F9U2hmnc+pviQiE0r46f7JiYFx/m2fKqG1YdHnt/8lz0N/DOU 3Z11N+ebn5UZJO4QiuZExGBwoDzEonp95mZYKWwSEM5lYWr/tIPZPlrN4jY2tULm1UvEFZ6S/R5 otdlUsOhvEE3MOTA7EjE9pTiZ2vMp+i/hjeTCBqWzywDv3hAML9oTk/16e00eFdrY0mtCvLQxk0 2alwCGptjDvpQOvmUvELwBFKJtlVeTdIZ7RO617X6WtZaKBDvAKXnAxTyCaMPfFyfY6qjVQJgQ+ kbCteUJ0B9ryxuzxddA4Te9UE/wGptVhi8MF39q/huixQByiX9OPDdXnHo4vOoBJA3kahq1AgLl /oH4XHgOxJCX52Cqr9BaqgW7xTfMru7F3cijFzKaoeOzFZwuIamuH0x8a/OdpXML//YwQ80AY73 uz42oob1f8bbvTTPjmtA+wLBZW9ieYSDvbdWno+UOkAR3c8TFWnT/k9kluifCzxlwRN+gJGNkrP 4Ibj7905Fxe4hcKeErmMbzpalPlgTm0K7ERQN6XrD1aasl+GImueaArIqjEKrggKMJxZzl1boRd /CVUyTwmyJOHFEPjEahnBOGSWpVnqa2V18wURAduN8jAF8xde9A7xARVv9ZLP1pmo8kgeukX4f6 sVuweJAEgw6IiCg== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-5-4dfff05ba927@google.com> Subject: [PATCH v10 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 , Christian Brauner , 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. Acked-by: Lorenzo Stoakes (for mm bits) Signed-off-by: Alice Ryhl --- rust/kernel/mm.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs index 425b73a9dfe6..50f4861ae4b9 100644 --- a/rust/kernel/mm.rs +++ b/rust/kernel/mm.rs @@ -98,6 +98,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 { /// Call `mmgrab` on `current.mm`. @@ -171,6 +213,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.47.0.338.g60cca15819-goog From nobody Wed Jan 15 08:44:33 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 2CFC51A256E for ; Fri, 29 Nov 2024 16:33:06 +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=1732897988; cv=none; b=G+6nKkAQUy7qgYR2nPuoAXoO9jcxXelRIWtaBUNJe1QtrzMe20+kMDLgu2qY12POoGqiYFZhvaqgpI+oRe4Z4aR8Gz6ia4dANUUhlDoLFHknC8qZCpP/ZtBH8fz9rir1ESAjjboo7q/ArYT088Fr5GU6lrRwnv0mof38kej3oT4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1732897988; c=relaxed/simple; bh=gC7RalGfFyvdhxyetp0qLjWhd8M+19FgWoTk8eiPyqo=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=k7XuKuNiFHyqRc+FLMZ/2aPvSucdKfK2hirfdM9V/6okY9jcPrQLoHXWL7FokAiDmC6zG02lbz4YjaVS+MdIBVxiX0MR94ReYjWpt3nbYGU+yYW4CjhE4bnYb8JEyJf/2hHOia8oq0OvYf6bYBHO6GDxRhngwK8SaF46lowfMAE= 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=PM1QYGz6; 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="PM1QYGz6" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-434a37a57dfso17489375e9.0 for ; Fri, 29 Nov 2024 08:33:06 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897985; x=1733502785; 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=FQmeIT5gOsUotOB7o6QXCtotwfAnfjr1q7Rp4w0i4JU=; b=PM1QYGz6HpxWdrFKeEuuz7tj//0xKw8z4SrNqugh96q0NcUSCvIodwsobAx80uDF54 ai3PgNAyHiD7SnJmaCpFf4aTmOIhWX1Xc+fPOOvKlQ9LbRH3HbCC45un0M3kR/gdf2Ig AhraUTjX4eqe3pBaStBeC808Bh1laRt/elK1TXLL9xPvip9zZow1p8v5GICEF/4UMAa5 Yocn8A+5+GrQeFu0ECR6JFSHp/F/aC4mr6U287rfFvHtArLY9YkyaGUshv+IKl22F0Co zVeHRp323rJDzqyBaDaeMO/hjUdWA8XKIWYlPd4qbFVvaSCPOd0HlCA9i/eC34Ihflnr xzYw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897985; x=1733502785; 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=FQmeIT5gOsUotOB7o6QXCtotwfAnfjr1q7Rp4w0i4JU=; b=ji+BKTQ2aC+DCVFdsBMs7R7IgiKMj2/cZfQDCIm7NSVpCuTIBcbHWdqppAJHrV9FJ+ 11n/b4DXAqFe4f3Vr6g8E4rlA/aKe8Ed9h0mkTheZNZmZ5FIUXR2eXOFhMBYmwCcIoDK f6o1bJHweuqwT5WkejFtgLnPcm9k59/6eRUS0Ne3m+y/ddQ5p0gfQDMGC3ThiOwCo2Yy mchsjjdT+Yh79srslSK5hbJ8WmTI9QUyLVq1uVVgYDKnf1EQx3SJJuGgtqQcnP88hAHO FPG+SqphsOavoHc5Gdxc5s1RD2x8FE2t0/NJLwBtGUXpw5MHmx0Za5AwTGx+rPnmYJ8N TqKA== X-Forwarded-Encrypted: i=1; AJvYcCWfFnfdPNtVBFYfDkYHN4g09SslSSvKCfcdjoQwgYGgszWL5H1GiJzOrOrHu7vPFPLiXWaDQns//7PecOM=@vger.kernel.org X-Gm-Message-State: AOJu0YwqveBo38B17HisUiI3/GtUIeuwVQu8WCxG0e3pQCUXFlyhlN+4 FD90cn24pLFmkILo0ztvEiQuSVZKwHkzW7RuaRuzXtno2+ISGJTyMbrYO1WLbSAyESollXmLl9m mOQlrwWkPv9FOtg== X-Google-Smtp-Source: AGHT+IFsZCkak00uYhITnMwKRsDF3s5UKpxdm1Ck5P9OOToSqry0Xi4dvkplER8/UfrYyNysD4wuKqkPHmyCm60= X-Received: from wmbjx1.prod.google.com ([2002:a05:600c:5781:b0:42c:b2f6:e6dd]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:19cc:b0:42c:bb10:7292 with SMTP id 5b1f17b1804b1-434a9dbaee2mr101296295e9.1.1732897984863; Fri, 29 Nov 2024 08:33:04 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:39 +0000 In-Reply-To: <20241129-vma-v10-0-4dfff05ba927@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20241129-vma-v10-0-4dfff05ba927@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8218; i=aliceryhl@google.com; h=from:subject:message-id; bh=gC7RalGfFyvdhxyetp0qLjWhd8M+19FgWoTk8eiPyqo=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeyw5vs6i/9T0252bYqbEn7nkN41XOkM+MXze 3wvucuoTyGJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nssAAKCRAEWL7uWMY5 RgTfEACfVuMxx1SnP/BL8wCAsPuxX5JGhXxnfaLz7ZZzUax2XN12bzlMqd5YfYKXzKdwcoYnEwV 94lofBlwvf6N8t5Sz959Mm2XikEzfX1OL3r9waiomQSC9WWgZcMbzlQSTFz64/ZuGS4bvAeRqA/ w4o+9qWe1CE89aDPwR6zabLo4hkqThpqUaSw2ubox3Tw29PgjTJFY6ka5juhsobw1jIEfrFROBl raa4dfyZER0pRuJ1XdHUybuXA/9fi+nPi5/Is8WVM/WYi8CTgPvZvfeyo7cUXZhqS6asQgNcGHx WoXQlaMbC80sDbMtIJp5sRe5Leub6xL0sDvG1mdsi9tUqJE4t/tc9c6BT4cj7UVRgqMkUI/nDUe yFZiNPPdWYxuAQV/uJxvU5ZcX9hyMErXL3I1i9KfGCeHEUAW2KYxFO4POdMd9SP8/P1GLrl70zk LOjgMq4yUyeO8bFwU76m0th2qEkPUF4SawjKMSR8PrenLElrz0JU7e1Dn4V5JWOX16FxM+DBt7f P13GF+rp0/nalQifLMrem7cwLe3VIwclC5uzajUOW6fFdfpbddG1Ae/FfgjrOp4M3a8W7sKFp49 8Vt+43lDn8Fe2EbwTiBlJqyMTRS5OYKfJIcFVvuybRRzWEGSiJQxlukqy2/sZHcTrI5MKdP3tnE gk+7FY2H7FGOs0w== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-6-4dfff05ba927@google.com> Subject: [PATCH v10 6/8] mm: rust: add VmAreaNew for f_ops->mmap() From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Christian Brauner , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This type will be used when setting up a new vma in an f_ops->mmap() hook. Using a separate type from VmAreaRef allows us to have a separate set of operations that you are only able to use during the mmap() hook. For example, the VM_MIXEDMAP flag must not be changed after the initial setup that happens during the f_ops->mmap() hook. To avoid setting invalid flag values, the methods for clearing VM_MAYWRITE and similar involve a check of VM_WRITE, and return an error if VM_WRITE is set. Trying to use `try_clear_maywrite` without checking the return value results in a compilation error because the `Result` type is marked #[must_use]. For now, there's only a method for VM_MIXEDMAP and not VM_PFNMAP. When we add a VM_PFNMAP method, we will need some way to prevent you from setting both VM_MIXEDMAP and VM_PFNMAP on the same vma. Acked-by: Lorenzo Stoakes (for mm bits) Reviewed-by: Jann Horn Signed-off-by: Alice Ryhl --- rust/kernel/mm/virt.rs | 181 +++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 180 insertions(+), 1 deletion(-) diff --git a/rust/kernel/mm/virt.rs b/rust/kernel/mm/virt.rs index fa1fd6aa703c..790b8cb91c27 100644 --- a/rust/kernel/mm/virt.rs +++ b/rust/kernel/mm/virt.rs @@ -6,7 +6,7 @@ =20 use crate::{ bindings, - error::{to_result, Result}, + error::{code::EINVAL, to_result, Result}, page::Page, types::Opaque, }; @@ -161,6 +161,185 @@ pub fn vm_insert_page(&self, address: usize, page: &P= age) -> Result { } } =20 +/// A builder for setting up a vma in an `f_ops->mmap()` hook. +/// +/// # Invariants +/// +/// For the duration of 'a, the referenced vma must be undergoing initiali= zation in an +/// `f_ops->mmap()` hook. +pub struct VmAreaNew { + vma: VmAreaRef, +} + +// Make all `VmAreaRef` methods available on `VmAreaNew`. +impl Deref for VmAreaNew { + type Target =3D VmAreaRef; + + #[inline] + fn deref(&self) -> &VmAreaRef { + &self.vma + } +} + +impl VmAreaNew { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is undergoing initial vma setup for= the duration of 'a. + #[inline] + pub unsafe fn from_raw<'a>(vma: *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() } + } + + /// Internal method for updating the vma flags. + /// + /// # Safety + /// + /// This must not be used to set the flags to an invalid value. + #[inline] + unsafe fn update_flags(&self, set: vm_flags_t, unset: vm_flags_t) { + let mut flags =3D self.flags(); + flags |=3D set; + flags &=3D !unset; + + // SAFETY: This is not a data race: the vma is undergoing initial = setup, so it's not yet + // shared. Additionally, `VmAreaNew` is `!Sync`, so it cannot be u= sed to write in parallel. + // The caller promises that this does not set the flags to an inva= lid value. + unsafe { (*self.as_ptr()).__bindgen_anon_2.__vm_flags =3D flags }; + } + + /// Set the `VM_MIXEDMAP` flag on this vma. + /// + /// This enables the vma to contain both `struct page` and pure PFN pa= ges. Returns a reference + /// that can be used to call `vm_insert_page` on the vma. + #[inline] + pub fn set_mixedmap(&self) -> &VmAreaMixedMap { + // SAFETY: We don't yet provide a way to set VM_PFNMAP, so this ca= nnot put the flags in an + // invalid state. + unsafe { self.update_flags(flags::MIXEDMAP, 0) }; + + // SAFETY: We just set `VM_MIXEDMAP` on the vma. + unsafe { VmAreaMixedMap::from_raw(self.vma.as_ptr()) } + } + + /// Set the `VM_IO` flag on this vma. + /// + /// This is used for memory mapped IO and similar. The flag tells othe= r parts of the kernel to + /// avoid looking at the pages. For memory mapped IO this is useful as= accesses to the pages + /// could have side effects. + #[inline] + pub fn set_io(&self) { + // SAFETY: Setting the VM_IO flag is always okay. + unsafe { self.update_flags(flags::IO, 0) }; + } + + /// Set the `VM_DONTEXPAND` flag on this vma. + /// + /// This prevents the vma from being expanded with `mremap()`. + #[inline] + pub fn set_dontexpand(&self) { + // SAFETY: Setting the VM_DONTEXPAND flag is always okay. + unsafe { self.update_flags(flags::DONTEXPAND, 0) }; + } + + /// Set the `VM_DONTCOPY` flag on this vma. + /// + /// This prevents the vma from being copied on fork. This option is on= ly permanent if `VM_IO` + /// is set. + #[inline] + pub fn set_dontcopy(&self) { + // SAFETY: Setting the VM_DONTCOPY flag is always okay. + unsafe { self.update_flags(flags::DONTCOPY, 0) }; + } + + /// Set the `VM_DONTDUMP` flag on this vma. + /// + /// This prevents the vma from being included in core dumps. This opti= on is only permanent if + /// `VM_IO` is set. + #[inline] + pub fn set_dontdump(&self) { + // SAFETY: Setting the VM_DONTDUMP flag is always okay. + unsafe { self.update_flags(flags::DONTDUMP, 0) }; + } + + /// Returns whether `VM_READ` is set. + /// + /// This flag indicates whether userspace is mapping this vma as reada= ble. + #[inline] + pub fn get_read(&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.get_read() { + 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 get_write(&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.get_write() { + 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 get_exec(&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.get_exec() { + 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.47.0.338.g60cca15819-goog From nobody Wed Jan 15 08:44:33 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 675F11A3056 for ; Fri, 29 Nov 2024 16:33:08 +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=1732897990; cv=none; b=MVGhBTWN8O6IHTdix7qKcdMwm1emAVnBzViFvleFlp0OGPhaXYgDvurl+w3BINIeOzvIe1rhey6caYD75PVir9O8qzTPdAVjEYu5rTVTQA7LLVe6ClhTCh5NvLPjEuS6pOg8kbq9cNbV8wKYzjcIh+LH+woORNzNoGjQr/ETOEU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1732897990; c=relaxed/simple; bh=IrZvUF0XzNLQMwbfZ0pN4UXzZJ4vVLLu+S9qv3H24zI=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=GV085SnjxL3Hw/hogF0LnYWFOQYU694GO4DiIE4seiUk3kyNvUr5cKXiW9TyzEHwRhiVdY5m/uBnVCb6KEg7jDa8rrlzbJIXl6szsNcl0qhO8r4k5XNv2B8LgixeNzKjyKTSNXBTIc6I9KxjPmTfbSqRlRCxQqwCNWjMXucHyNQ= 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=mAFngJ98; 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="mAFngJ98" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-434a4ad78a1so16457985e9.0 for ; Fri, 29 Nov 2024 08:33:08 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897987; x=1733502787; 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=UnhyEorAiAZu+6K7VI1xMGROpYDgIW3AxkwRW5dHmBI=; b=mAFngJ98XJGkitYMf9/9Ry8J3xaTIfRhJdrgzSF/b8IbYhyy0qOI/PIbCzsYc6Db8r rkM465v1QwzelgEd3M2zordSFlqdNpRUGkYG5KCDf68M/zQRcsG3uid0AaGAXPXUuI6T AlXjIcoCRTBOq2NVju1hZNhGuSspUbwfS1p0Gf+dO/WppifTOL0uxydQiEFZAV5ak+iM E/fAuSpDBO1okQ56JUeluBzFmmM7khs9Mr4he0Qqi/XAcdxyojHwWHd7nG/gXx9uZ5XH bslhAwiMDhhf2iDXXqnmIk00hUA2MOJkn0/bv4NZBasF65icQEM8O6O0kj2X4/lof/u0 oKlg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897987; x=1733502787; 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=UnhyEorAiAZu+6K7VI1xMGROpYDgIW3AxkwRW5dHmBI=; b=QTMlQTGLXcyg01leYOtuPPvL4WhyTJ0ZcYQ8/fsgWw9lz46ouplLUI8REVQp3CJYDo M52qwTaKTvfj2d5dvJxy81xChAQ3TlZXo9KOqULVrQb5lVzKYvx9O4K1+BexJ3Rcy64G IGX5gg2C8VOvM5B88x82Tr+buC0ZE7IJ3Ke5/Wnbefs6E46PwALxXJVntH5dj+iMxhfR yXYNci5Hiqhtzl7I1bmVv03oxlQfRGsMXWRY9/eKG+DWXQFqRdUCD7MAUCejuj3q8Uyn jjeSAldYJaZe6LUWvNZlB63m1KpdSVwGlcX3AYKcAzpUea9rYzJtC+r8F1RghlvQ3tjf j7JA== X-Forwarded-Encrypted: i=1; AJvYcCV26k+k62V9cj4IqwdJC6ZJmasp4JV8DgWzBz53sdqBSQGHYwGVplpwEnwRpyVGd3/Xu/+bM4IlCEG9uwU=@vger.kernel.org X-Gm-Message-State: AOJu0YxcWwMdSkGq36th1oeLCjJhT2XOXfsQBYCOwEtk6vaGtl6ELF6Z r9Q08bbRwZJX5wN4X+WY4HJGgz++oZb0+1UAF3tDhMi/VSIwXVn0u5CWYJhHdXeJFPdDgAd581N EJVg6e714DLsenw== X-Google-Smtp-Source: AGHT+IEIkhciFv/SoLFFHF6Vxq9iGEQEsrBvyMo5yav6t96an9Wy9B+lJz1jJamwd+Gu4sliNPoz0+xpNLIZ01E= X-Received: from wmlv12.prod.google.com ([2002:a05:600c:214c:b0:434:9de6:413a]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3b24:b0:434:a754:661c with SMTP id 5b1f17b1804b1-434a9db83acmr109938695e9.7.1732897987022; Fri, 29 Nov 2024 08:33:07 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:40 +0000 In-Reply-To: <20241129-vma-v10-0-4dfff05ba927@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20241129-vma-v10-0-4dfff05ba927@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=2822; i=aliceryhl@google.com; h=from:subject:message-id; bh=IrZvUF0XzNLQMwbfZ0pN4UXzZJ4vVLLu+S9qv3H24zI=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeyx3XZetGy5dEQOShQaSbbMRUwJxGEEMjLw8 9RdWQXDUSaJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nssQAKCRAEWL7uWMY5 Ri8ZD/wLIEpXUXaIuGN7hRbJCy7O1J4CbcrlTxrSVyF9E7xofr8DGwiW2NYtspHF6JvEA9vEbKZ VEUdDED+X/G1IXI86Qv4eEGCrNHUL6+idMjPfMaYJw55Rci+8r0Ewi+h9QePeYJNaw53q74kjpT szaSueywBq6/KA0AMbekbkpvM/Mlz3sBAqf0pd4McgQOuj3tp0+ApxmJf6lh4+52AoMeKLT2HdV ceUq8pZjoh+KV4CJIX5olRuJzxOgYXDI3Dtg/eMH/XM8EjyEzWTBUmdFn2REX8ei8h4BqWYrX3A ztvAOHVQjzOO8cHP1ew5/ExWAXiOZGn5/ZYVpWMQngFnorTAyaag3wK17LHrOZUbkx7YffpqrBN +97cJ1Myn4/bRhJoAB1V1MYxrQG+8hsaoddXg0IjCtfQi2p1o1aLqkjw6QO3U3q+q5v3ONXSzV3 K65OLwOalr42aJNfyYeQJafHoTzHvpeJ56/O0bGWqaxqVVd59t/l4NjCAb3vHdZasnVmz4W6Ag1 pcPQWa5L+SzCdE2TxRKYKm5+WXtXUbtC30SMhq+MoPqmFStspXIk/CJ60nyzvxG0hgL8P+ji6Po U7yv2fwSlp1YrDsHbvR2mQe0lh39+/0PLppp8PGqkRDBRuKk8s3ccdhTh6/8QiMsuyTda/Hp5g4 rC86Q3qz2t7SDcA== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-7-4dfff05ba927@google.com> Subject: [PATCH v10 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 , Christian Brauner , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Add the ability to write a file_operations->mmap hook in Rust when using the miscdevice abstraction. The `vma` argument to the `mmap` hook uses the `VmAreaNew` type from the previous commit; this type provides the correct set of operations for a file_operations->mmap hook. Acked-by: Lorenzo Stoakes (for mm bits) Signed-off-by: Alice Ryhl --- rust/kernel/miscdevice.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index 7e2a79b3ae26..99e076338f39 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -11,6 +11,7 @@ use crate::{ bindings, error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR}, + mm::virt::VmAreaNew, prelude::*, str::CStr, types::{ForeignOwnable, Opaque}, @@ -110,6 +111,11 @@ fn release(device: Self::Ptr) { drop(device); } =20 + /// Handle for mmap. + fn mmap(_device: ::Borrowed<'_>, _vma: &V= mAreaNew) -> Result { + kernel::build_error!(VTABLE_DEFAULT_ERROR) + } + /// Handler for ioctls. /// /// The `cmd` argument is usually manipulated using the utilties in [`= kernel::ioctl`]. @@ -156,6 +162,7 @@ impl VtableHelper { const VTABLE: bindings::file_operations =3D bindings::file_operati= ons { open: Some(fops_open::), release: Some(fops_release::), + mmap: maybe_fn(T::HAS_MMAP, fops_mmap::), unlocked_ioctl: maybe_fn(T::HAS_IOCTL, fops_ioctl::), #[cfg(CONFIG_COMPAT)] compat_ioctl: if T::HAS_COMPAT_IOCTL { @@ -216,6 +223,27 @@ 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: Mmap calls can borrow the private data of the file. + let device =3D unsafe { ::borrow(private) }; + // SAFETY: The caller provides a vma that is undergoing initial VMA se= tup. + let area =3D unsafe { VmAreaNew::from_raw(vma) }; + + match T::mmap(device, area) { + Ok(()) =3D> 0, + Err(err) =3D> err.to_errno() as c_int, + } +} + /// # Safety /// /// `file` must be a valid file that is associated with a `MiscDeviceRegis= tration`. --=20 2.47.0.338.g60cca15819-goog From nobody Wed Jan 15 08:44:33 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 C35651A4F19 for ; Fri, 29 Nov 2024 16:33:10 +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=1732897993; cv=none; b=SPbRkq91qMo+9jV6rflGr9YKz8pBcCMJGKQjkIt5L3JEAtOc3/Lo+fn3hByWzu4D589ffkvEsFWHcsv6piLF5eYHCqw6BJE9pRq1UfIDcW3ljBjEvJmBTyHWTt0O9fETkBfNWrltbuWlVfKXKI0F7Uak66ww250cew0XjalIpWc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1732897993; c=relaxed/simple; bh=UOgti2W3w5pdDKaneEZaDc7ZRGkpusBY1HuaqkaxSYQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=hp2S1GfS0I4GSbv7uFWozWc6OdQL0uS7okjqDyBcXYT+storPG9NlDSSANSuKjerNSZtOnni6HHhRWTlYVYYYUxDOwMCINgYnSrvUI16DjDbWt8GOuxFnoONlxxuk7AoZRPBPjzCuw4Q11ZEgitdhQMmg5HKBt2OqgKKOdqDfOM= 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=K1DsrMgB; 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="K1DsrMgB" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-434a195814fso15050535e9.3 for ; Fri, 29 Nov 2024 08:33:10 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897989; x=1733502789; 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=khaQBcubSs8zPXHk0UASzgDi1+R5RW3CVTJj7OV4mlM=; b=K1DsrMgBOAY468+c8rbOcUOBRAUl/trQxfZJhrMf4IldaIOda1BaDJjMPmzORGH07o GBAQh8wchc4s/fiRC9Bk3daCVmkKHgHduM5TpJjj36QGrdECQuUbNxqZQlEyCbAOiqya teI8L3+iqAEwm9pJzvl8QAspP47cj3QnvlWiac2PpQ3PlzzfaPowjyvgq+04LqtlJsDK UuoeGPHaJIYYTeFcdZb0DfiFFRnu1PZUol5Fz4sa8qTD/4ZTg4cerHRvOdr0sOrflck6 1AN13Hoa/Io+2NeJKEeReyL7Bxxxwd94n9HRth8MtxNiqeT9nSNaiLO+uKEVQ8LV37dO WXdw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897989; x=1733502789; 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=khaQBcubSs8zPXHk0UASzgDi1+R5RW3CVTJj7OV4mlM=; b=Q+OKHlYLD37lPyA5csb4fUtFq+a6oxY+/+XSDFRI3e9XrVIMijm4/xHki/zXhIfmcZ GC0z+V/3FlnyMR9fhhaWFX0O/VeWX6Nw4KPl4k0r9VH6tECNoVw8UU+oUBe9VVnunVFS jx2Mmi5XX/8h/EeBR6oUPwbALyusblH11BJe9Fpd3WTn3j+VmicYiiYuL7/SWc8xva4t tyWE7apnJvi9nbD78uNkjeWlbIvl0i0eJqp3ACtM1D1fRII/4+V3qP/G9lg9HxFdzNVe Yf827l8xoPkyIvKPPVctzj+B6xtVnLBY6An049tjL5jUtJTTX76301lBL6M6U68ZcO3s vzRA== X-Forwarded-Encrypted: i=1; AJvYcCUKV0ovfKanRIEK36NRROZqrDFYtwsX6vOkv+ranZrj/lLfzSUxFNaSJWSbw8nPYFFqCKPxEya5uU5kGy4=@vger.kernel.org X-Gm-Message-State: AOJu0YxjYiIPC355unDj9ZzyGrkJ0XeY5qR+16Gjppe9QeVP9Aju8Xsl vEgS6K9tq5lbGFZADmFJQOUHvO+Ajc0uWPogUuRd07IFZn/DxZVpBJsN9Nxeag+onrRWyax6OXZ fEsZHr8113h1tCw== X-Google-Smtp-Source: AGHT+IEBCg9KJJDJe7VoW4ZdyHwyebrajmoBgyf09TNJjFSpDvZZB+3u8dCYzcG1MDbxDRLvGSfQivBbzvIPAko= X-Received: from wmoi4.prod.google.com ([2002:a05:600c:4804:b0:431:4c36:d336]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:458b:b0:431:5f1c:8359 with SMTP id 5b1f17b1804b1-434a9dcfd5emr120555635e9.15.1732897989312; Fri, 29 Nov 2024 08:33:09 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:41 +0000 In-Reply-To: <20241129-vma-v10-0-4dfff05ba927@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20241129-vma-v10-0-4dfff05ba927@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=22122; i=aliceryhl@google.com; h=from:subject:message-id; bh=UOgti2W3w5pdDKaneEZaDc7ZRGkpusBY1HuaqkaxSYQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeyys/aPXUMqJz2reACEhC4F6C968B9ndJ6+v TtfUjZpYQCJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nssgAKCRAEWL7uWMY5 RsyPEACl6aaN3iihdjb3Lukz8wuBKhz9hO4mUk4ShWSq1Gpm8ui6yPKbk7FwrE7JRP1d+z4oyqX Ag6s7Vc6MWOSon5OgspWo9ddAWb/LGo+KkA8q7N2mhDrckQKdxIK7roASRVIUCH86nSSGEQdFUW tSv8ZBtT0UbQQ7OpTt/6iCzUEDNxx0UsWXRnkgya3zoeOktB/WFkJ4waQyQqxpQ2rB81nJKIXWm QJNGX4yatpPYp8gQ0QHtpeaArKJOIOCZgX6qeevc9UArg3n4hGcIIf9oZkG8xWeszpoue4XftpD mypcBaFsy12CTFh5Dq36HI3UqSZlZDwQWWCdhRIyBRFhAQ1COjZsxlvTTS180MBmYPREbunV4Lx IAIiOnCg0UOrOZG1PnnTnsPQj/VUBKqs+v0zTGyaKZcBYaKuD2fF7J/VvvmWeP9c0XS6yGHgM2p XEoicgR0hnK1BYVISv1pD7CVyDhYK9A9M40ICECur+GMwggsOCP+iWLd2+dVylN2QGpVQTYySCc BJOkxjWrDU7BHOT++OsYZZ8GtddUuVNZLKkbv1MKEy6dpaHYi3/g5i2uN2agLiaxYPRneEsteLa dX+Upt/nbs3CnGjySWD2cGfEI5e4nCPAeCY1dXAiVt05L0DObOG1EpIyZqC/JtfYdEqv1zapIGX JOeRJO5wY+7nO8A== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-8-4dfff05ba927@google.com> Subject: [PATCH v10 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 , Christian Brauner , 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. Cc: Christian Brauner Signed-off-by: Alice Ryhl --- rust/kernel/mm.rs | 22 ---- rust/kernel/task.rs | 284 ++++++++++++++++++++++++++++++------------------= ---- 2 files changed, 167 insertions(+), 139 deletions(-) diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs index 50f4861ae4b9..f7d1079391ef 100644 --- a/rust/kernel/mm.rs +++ b/rust/kernel/mm.rs @@ -142,28 +142,6 @@ fn deref(&self) -> &MmWithUser { =20 // These methods are safe to call even if `mm_users` is zero. impl Mm { - /// Call `mmgrab` on `current.mm`. - #[inline] - pub fn mmgrab_current() -> Option> { - // SAFETY: It's safe to get the `mm` field from current. - let mm =3D unsafe { - let current =3D bindings::get_current(); - (*current).mm - }; - - if mm.is_null() { - return None; - } - - // SAFETY: The value of `current->mm` is guaranteed to be null or = a valid `mm_struct`. We - // just checked that it's not null. Furthermore, the returned `&Mm= ` is valid only for the - // duration of this function, and `current->mm` will stay valid fo= r that long. - let mm =3D unsafe { Mm::from_raw(mm) }; - - // This increments the refcount using `mmgrab`. - Some(ARef::from(mm)) - } - /// Returns a raw pointer to the inner `mm_struct`. #[inline] pub fn as_raw(&self) -> *mut bindings::mm_struct { diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs index 07bc22a7645c..8c1ee46c03eb 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 @@ -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,109 @@ 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. + #[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. 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()` b= eing 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 `&CurrentTask` type should be used which en= sures that the returned + // `PidNamespace` cannot outlive the current task context. The `Cu= rrentTask::active_pid_ns` + // function allows Rust to handle the common case of accessing `cu= rrent`'s `PidNamespace` + // without RCU protection and without having to acquire a referenc= e 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: 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. + 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.47.0.338.g60cca15819-goog