From patchwork Wed Jan 15 13:35:04 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13940444 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 3D4F7C02183 for ; Wed, 15 Jan 2025 13:36:11 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 90CA86B0085; Wed, 15 Jan 2025 08:36:10 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 86B6D6B0083; Wed, 15 Jan 2025 08:36:10 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 670B3280001; Wed, 15 Jan 2025 08:36:10 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 43F136B0082 for ; Wed, 15 Jan 2025 08:36:10 -0500 (EST) Received: from smtpin15.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id D80721A12CC for ; Wed, 15 Jan 2025 13:36:09 +0000 (UTC) X-FDA: 83009784858.15.4D4DE62 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) by imf02.hostedemail.com (Postfix) with ESMTP id E2B3580013 for ; Wed, 15 Jan 2025 13:36:07 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="jEzFa85/"; spf=pass (imf02.hostedemail.com: domain of 3xrmHZwkKCJs5GD79MTCGBJJBG9.7JHGDIPS-HHFQ57F.JMB@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3xrmHZwkKCJs5GD79MTCGBJJBG9.7JHGDIPS-HHFQ57F.JMB@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1736948168; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=bQZ8lzcN1AuRMo71v8cGYFa8tBipKd/jkKd39EV9lsM=; b=mTPjV5mfr/KUTFWZALelPHTk1QOeCUbmXGeHy1lIL5P06KxkJVal6n0zhbhBk02YG5DcCW OMWqTH36t4+JljB9KtPjre5of2z6VWByKAa+pxup/8faO62SoUjLHkL7QP2RgOPMsnxhHs 0L3W5MM/3ymc677/BjQW8F1jBe14D6s= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1736948168; a=rsa-sha256; cv=none; b=a9EgXiMRwPWWyAN+NFNkGL/tqldDIXmYy7draUDGBxLaLZfXsHTDXc708FBKfA7m3gLx6l YfJhBExeiCJ8q/oSROzws1fZSVEopmVXsv/+WBMC2ccu9nC+1FGvWJ/ZS72DfeuXTd5TyJ QEVjUDJFJinl6Cg3VCuWJYAyB5HC8jc= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="jEzFa85/"; spf=pass (imf02.hostedemail.com: domain of 3xrmHZwkKCJs5GD79MTCGBJJBG9.7JHGDIPS-HHFQ57F.JMB@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3xrmHZwkKCJs5GD79MTCGBJJBG9.7JHGDIPS-HHFQ57F.JMB@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-4359206e1e4so28585115e9.2 for ; Wed, 15 Jan 2025 05:36:07 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1736948166; x=1737552966; darn=kvack.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=bQZ8lzcN1AuRMo71v8cGYFa8tBipKd/jkKd39EV9lsM=; b=jEzFa85/NCNIS6Ghrs8En0Y6ptqAs/MPahzQwvX/+9qc4jsw0dh9bUEfdRgNR9+/70 XkunPuOzLW681xj60KTWpZsvQqOpO8cqNdD25vcr93MgvTyUnOjdZk/Dn0RgdTyzMg7V j6wFO2A8X1/pDZKAHMk6c5wec4kC/VIlTdiHQFcH3dDRvS1ck6ScC4qPQsoGEAg3+ABh hP3b8PZx2/ZWLdFfctXxLDwN0ybHXlJyLSp26rq1LOqWHhc13SB4GdZAN1T/P9yPCocP eJwV1DG8vrzdj6eNp8JA7aKmpdcMeZC0+1oKIX7jaw+MWYxpSQeV3ttBJVztlAyaK4pi mXWQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1736948166; x=1737552966; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=bQZ8lzcN1AuRMo71v8cGYFa8tBipKd/jkKd39EV9lsM=; b=Mp8jsG5MzaFCHFmrT9A1YS3d8kyRITa/+kInr38AS5Y1O7hjZ53UU4sbZlAsF5akn/ W+lw69hBZyjqgjwD4f/k9W0hqFTi7XiY2KtFC2snWDf1FDdRnMwZXawX10jZLmhuRvp7 bIGOkyJqpst1iCqT3LztqDRQ6jkET/nZXWCnMCYfFblD1VhGXed7p+NdM7oERNFOIIBk U5ATn+3z2I5LLZ3vglkkVaq992Vb43aNl7ZAaK89NTAafFMyrv6sH5pCsdS99CvGcer6 vbElZ1u0mC/WnkYToik65UGQwphvzsk1vtuiI9NJI/4owm/uBGZF011wuU54SUyEjnuu 48Pg== X-Forwarded-Encrypted: i=1; AJvYcCWtblIyRuH7sUK3I304ik7u44uxCOIJGlOkS6X15AQ1EQbX8lyvGowCj1p6rl32Y2COTrVV2rfyZw==@kvack.org X-Gm-Message-State: AOJu0YxeeKfMehLG1IKKrFNUIKwa/DwTj+KbNaI9ZS+yKlXMDVkXAkbE G6/ezl7jqCucRq6TTTHYKtCT1nc7qIF5trCJ+VykOa1M695Tu9qCw6WbBpDmXwE/sBtV0JNIAKl s+/0344l5ejDsqQ== X-Google-Smtp-Source: AGHT+IHXOHLVyrqG26bwXmWj7k8i+YHFx0v6XbhRNOb82HiwvIAwHIR5ct4HbEiTS1Vq5WpHBB+epRkGt5G9PeY= X-Received: from wmbfj4.prod.google.com ([2002:a05:600c:c84:b0:431:1903:8a3e]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:a09:b0:434:f753:6012 with SMTP id 5b1f17b1804b1-436e26aa593mr296902835e9.17.1736948166660; Wed, 15 Jan 2025 05:36:06 -0800 (PST) Date: Wed, 15 Jan 2025 13:35:04 +0000 In-Reply-To: <20250115-vma-v12-0-375099ae017a@google.com> Mime-Version: 1.0 References: <20250115-vma-v12-0-375099ae017a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=10172; i=aliceryhl@google.com; h=from:subject:message-id; bh=JTL2MUjztUWi2Edxe76W3MQbrbIY2frYdACvccKeGlM=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnh7m9buKTHoMGL2rWWFPKx8ZKzp9gRDt5AGFFP Y9srGjZLTmJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ4e5vQAKCRAEWL7uWMY5 RrciD/9qxvpMIi1Wfr9OCenml8/BizGBow4wxZKmGcU7Jf5ARM1DQFn7IAVl2OWQg5k+XXqWISD abUyA9sgSCR3fNBfQUlzc9oPDc8VFloaJX1eDitNJ9UuTGDQOdhqFnbHGSUBCHB7/KKwAKEFhPh Se8GxsL9Uy7GhqQr0DAXt0+LNvrthD8VFVPhUb81uxJ1NLWOwlKYLvmtfwDcvT7/18jAOYJ3o+3 LLBczHW/HHX51sFejN8tdnD8Uau2symCRFRznOxHVlepzvqs1L7DFqPa7Unq3T2n3WwbbihmiYW uF3bJ/iOXRuVYj3XuypBdZANoSg/vxZWaVkesGh1FepGgsVbNLMeANGCWWRBe5UmbzdvyXJXIFw r1eOgK26fKBljBTYe8OVeUBy2cJsr4dloKg1X8C9Gk2rgbOgQUqjDPqPVJ3CpqC1JmKDNfFs0jD N39u+9WgudH88D6MTFZ2ma9Ao3H3iS68gVHpLOIySe/rdlfB8fx/UKb0rMY0OzQA21lUL0PovdC TmyxJ9PQuXkTNQA0lOsDivCPLK9tSigtvjhqidQheZvMfeHeHagyWNoCUN4MieUKecVaLleVUsa YTtPtZwCxxq1ZzXJb7peMH4jnSX8yZe/lsBrQND4q5zTf62A+4jXJWVPaG19B4zwHCzbGpXPm0X LkC4SaR2OVHrQQQ== X-Mailer: b4 0.13.0 Message-ID: <20250115-vma-v12-1-375099ae017a@google.com> Subject: [PATCH v12 1/8] mm: rust: add abstraction for struct mm_struct From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl X-Rspamd-Server: rspam02 X-Rspamd-Queue-Id: E2B3580013 X-Stat-Signature: iyju7y56bwodrq9naiesbud9se3hkox5 X-Rspam-User: X-HE-Tag: 1736948167-176146 X-HE-Meta: U2FsdGVkX1+4P6IZoeu7I66ovfUZdtxN+Ndz1j6Wpj34RPuzPxC9Kgq1Kz/wmZ1Fj1IaDsrL3eXPUygEZMEKQvlCdhvWjofJl4cYIZKkC4Trkr0n0RBF9z09vghLt4O31783rT38oOpIAwFDngeEWBx7g+nOwritVXPjf7BxOV2/F0ukv370H4Rsy9Def2K+7neLsnfU+ZN11a3iaqHoHh0o4vq9a2/ebbFVNbKCGLrGxfyHIEMJmzw2JmgkMMceggkvJUPO7bYpKVfxWIR/Xg8gYZNqVWEV2AzVritpk+3WifQHPlOljoD1SZB1Xu8s0pfks1G4dlXWT3tB4WzUooQQRXI3XiH0kKhrlToU/v18e5KO+YdyvSHad/IEIsmn3CAdkmJenAW0nD9Wna4rkh/Krof2vy58BcRVLOUGErOs0NWEtEPnQu1ILP6+Eyponps0WUuDQwfu0wgtN9hSgp+l7pQtCPcwfnHBcRY/lEzVRkj4CTwtB7nVrQTyhGrn7RE3BnzPBEBUOAv/kiYIhivyrm4TEEp8GsKof5QF8o5J9BBi5vrZqGVS2zDBAJPdf7Tt0pF6/v8EwOf/ZSlg2USQ7pka7BfExH4jtkqIUiEb4BZYcx+IX9W+tc1M5Pg49yAqLN4go+jzDIVCz87IEwLbWs811tZSi17xuPlm7FXFYHZGYcephzbjX5Dt+wUwl+j6k/MSsE89SIoeWgwd2LWG8um/M1LCayTTc762pM/L8ApGs8bxFSdZCq+Rrm4jQ/amKxfldZOp6dsDxijbJ2YCwtzKG+T+hM3JOmHG6UJbAaAAqRlzaz3sRCcw57oNi2IjIZ8Mge91PhAkHwsU9N0qLr74+3cWyZDk2PtaJfIAgCj0DdO78/eHSQV49otZE6mWUb4ZoBqlLR2KiSjMEC6WrsmML2M5WAIKkxs1uwAGCyRn5vuEwkm3sQ83GuQ6FdZ8oWWRA5Ckqb4x5+t 6D25d6Hk E1Y0vxCMEZkJ4qko0pitJzOAegfcJJokLs1FktjVyweb6uD9HsU1Tke1h88fWSJhTgQdoJsjBke8fkSNs1bFNN1opGON5RS7IEl04aoaeifXUBJ32R+Z0ZW6bt4diYMpjXnZ+f0vCeeESiCxcY8slBreWx2PhTMwSBMNpUoRjfp3AoDiH2ZEjcryI/Ygpu9WRtlNrXK0Po5EDxOMdKpVVVC9jQoFIztEkWclwjGgChsaaFGirS+GIKa4fBLpb6CSC6hNAIsHhzgblJ7s0QwdmtNr1M85GfOnpfKxTrWNtknObCGSUTVepAQDcu2jW+QXg1X0dfuepg8vytWmZbxxPNUgRuASKF/IC6sOfM60m4LNu9H10NSsHhIwkPSlrTXqq6UPXNvgQThf9Kq/e4JMptbB16s5yNaY8XUtE6kdM+MO5Yt16OabhyfLmgYcX8x3TCDJHHRtxpo2HeNsPneo7UpqoFTLevjk/VCYcN33r90Lk0JNLWjNyKUI2ODX2AxNP9qra6VSz6Xsi3F4i7ZZHQwBsJE3p/oBAUWdRHI3iuyoGEKmsmcrRwt/CFl9n9HEC4OQPwx/wkf2MS/tAs5ZQbce1XqmY6mn1Aox+O/eBKpXf0xFk4kx8z1Bb2DMi6lFYNdo1mw5VXqlROxovP5YIq2CodgQrlM/PfO7/k4xVGiaBGTHgypByv9TvgPimjJ8ujUrOQfcjZVMsx1M= X-Bogosity: Unsure, tests=bogofilter, spamicity=0.474264, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: These abstractions allow you to reference a `struct mm_struct` using both mmgrab and mmget refcounts. This is done using two Rust types: * Mm - represents an mm_struct where you don't know anything about the value of mm_users. * MmWithUser - represents an mm_struct where you know at compile time that mm_users is non-zero. This allows us to encode in the type system whether a method requires that mm_users is non-zero or not. For instance, you can always call `mmget_not_zero` but you can only call `mmap_read_lock` when mm_users is non-zero. The struct is called Mm to keep consistency with the C side. The ability to obtain `current->mm` is added later in this series. Acked-by: Lorenzo Stoakes (for mm bits) Signed-off-by: Alice Ryhl --- rust/helpers/helpers.c | 1 + rust/helpers/mm.c | 39 +++++++++ rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 209 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 250 insertions(+) diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index dcf827a61b52..9d748ec845b3 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -16,6 +16,7 @@ #include "fs.c" #include "jump_label.c" #include "kunit.c" +#include "mm.c" #include "mutex.c" #include "page.c" #include "pid_namespace.c" diff --git a/rust/helpers/mm.c b/rust/helpers/mm.c new file mode 100644 index 000000000000..7201747a5d31 --- /dev/null +++ b/rust/helpers/mm.c @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include +#include + +void rust_helper_mmgrab(struct mm_struct *mm) +{ + mmgrab(mm); +} + +void rust_helper_mmdrop(struct mm_struct *mm) +{ + mmdrop(mm); +} + +void rust_helper_mmget(struct mm_struct *mm) +{ + mmget(mm); +} + +bool rust_helper_mmget_not_zero(struct mm_struct *mm) +{ + return mmget_not_zero(mm); +} + +void rust_helper_mmap_read_lock(struct mm_struct *mm) +{ + mmap_read_lock(mm); +} + +bool rust_helper_mmap_read_trylock(struct mm_struct *mm) +{ + return mmap_read_trylock(mm); +} + +void rust_helper_mmap_read_unlock(struct mm_struct *mm) +{ + mmap_read_unlock(mm); +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index e1065a7551a3..6555e0847192 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -46,6 +46,7 @@ pub mod kunit; pub mod list; pub mod miscdevice; +pub mod mm; #[cfg(CONFIG_NET)] pub mod net; pub mod page; diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs new file mode 100644 index 000000000000..2fb5f440af60 --- /dev/null +++ b/rust/kernel/mm.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Memory management. +//! +//! This module deals with managing the address space of userspace processes. Each process has an +//! instance of [`Mm`], which keeps track of multiple VMAs (virtual memory areas). Each VMA +//! corresponds to a region of memory that the userspace process can access, and the VMA lets you +//! control what happens when userspace reads or writes to that region of memory. +//! +//! C header: [`include/linux/mm.h`](srctree/include/linux/mm.h) + +use crate::{ + bindings, + types::{ARef, AlwaysRefCounted, NotThreadSafe, Opaque}, +}; +use core::{ops::Deref, ptr::NonNull}; + +/// A wrapper for the kernel's `struct mm_struct`. +/// +/// This represents the address space of a userspace process, so each process has one `Mm` +/// instance. It may hold many VMAs internally. +/// +/// There is a counter called `mm_users` that counts the users of the address space; this includes +/// the userspace process itself, but can also include kernel threads accessing the address space. +/// Once `mm_users` reaches zero, this indicates that the address space can be destroyed. To access +/// the address space, you must prevent `mm_users` from reaching zero while you are accessing it. +/// The [`MmWithUser`] type represents an address space where this is guaranteed, and you can +/// create one using [`mmget_not_zero`]. +/// +/// The `ARef` smart pointer holds an `mmgrab` refcount. Its destructor 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 `mmgrab` was called. +unsafe impl Send for Mm {} +// SAFETY: All methods on `Mm` can be called in parallel from several threads. +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 destructor 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 several 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 = Mm; + + #[inline] + fn deref(&self) -> &Mm { + &self.mm + } +} + +// These methods are safe to call even if `mm_users` is zero. +impl Mm { + /// Returns a raw pointer to the inner `mm_struct`. + #[inline] + pub fn as_raw(&self) -> *mut bindings::mm_struct { + self.mm.get() + } + + /// Obtain a reference from a raw pointer. + /// + /// # Safety + /// + /// The caller must ensure that `ptr` points at an `mm_struct`, and that 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. Layouts 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 = 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_raw().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 that `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 MmWithUser { + // SAFETY: Caller promises that the pointer is valid for 'a. The layout 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 = 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()) }; + } +}