From patchwork Wed Nov 20 14:49:55 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13881312 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 C6651D711A7 for ; Wed, 20 Nov 2024 14:56:22 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5030F6B0095; Wed, 20 Nov 2024 09:56:22 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 4B2FE6B0096; Wed, 20 Nov 2024 09:56:22 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 306F36B0098; Wed, 20 Nov 2024 09:56:22 -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 0D44C6B0095 for ; Wed, 20 Nov 2024 09:56:22 -0500 (EST) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 9FEB5C0CE4 for ; Wed, 20 Nov 2024 14:56:21 +0000 (UTC) X-FDA: 82806773616.02.D1F7E7F Received: from mail-wr1-f74.google.com (mail-wr1-f74.google.com [209.85.221.74]) by imf05.hostedemail.com (Postfix) with ESMTP id 0EABF100011 for ; Wed, 20 Nov 2024 14:54:41 +0000 (UTC) Authentication-Results: imf05.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=Dcb7Meui; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf05.hostedemail.com: domain of 3kfg9ZwkKCLofqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com designates 209.85.221.74 as permitted sender) smtp.mailfrom=3kfg9ZwkKCLofqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1732114394; a=rsa-sha256; cv=none; b=W+KcJ1DPsedb2DZGz4M5TpL/UgTKYkV6JqBUtbp9nks5rbjgkVVtbDksGRohJPIMp4EuO9 vthqBkf4kcr5AX54O+1B0MKM0oCmqjE/hsHBPdR3ib10rUe6tVlfGkqQrWILlhhXsCq650 PiKQGWKvaIrhA5Wa9l90ZTqe/NmUbJY= ARC-Authentication-Results: i=1; imf05.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=Dcb7Meui; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf05.hostedemail.com: domain of 3kfg9ZwkKCLofqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com designates 209.85.221.74 as permitted sender) smtp.mailfrom=3kfg9ZwkKCLofqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1732114394; 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=iRAvnS0IaCWBMzdRyDGxGfoX2WP3nXVUoH5LBPSc5Qs=; b=J+bDuZLzco3wGRc4x4qGrGRUsodjUGqfnSlGPP/uZULy6K9R0DCsat8K+ivXQUM0o/mDx0 QDgNVYHAUiTWpebnLdBKSPPxDFGFMKcl3Gc20ma5efaHu6zIHJwETQeE3Evh8QhR2jfBGx ZDziwHrHCN87hCqLqVadx/Be3GzULAo= Received: by mail-wr1-f74.google.com with SMTP id ffacd0b85a97d-38243a4ba5fso3103710f8f.2 for ; Wed, 20 Nov 2024 06:56:19 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732114578; x=1732719378; 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=iRAvnS0IaCWBMzdRyDGxGfoX2WP3nXVUoH5LBPSc5Qs=; b=Dcb7MeuiBQ5qWwZ15Scm1bFCa8Se+62MXIhVvOyCUCTEiGrkRQRXoAHFrYUlEbsj3V ooiWaoNExgTJbZjJ1EVRE6LE8mUOFvnIvE9U0LZuIj698pkjar7eLyFzog5F4kV5af9b c6w4LWgsD+gyfzW42fV73cb3axVe6rnci4+4jVMb4t8eK/JRiFpdXAHzgg+bmTpqO6rY ZAodf8Utg03dgLSWjndXcJ9lmkwgSMCVygpsLHfWOHZ+TtD/apMZ5AzB5K1Ge/HowI5i TB1WYCyW9d6CTIhNe3QFrTGoOSHo5RcNbqSpNdC4GGSEAGbMVKWOzdcL9AJhph6Jk6V9 5glw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732114578; x=1732719378; 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=iRAvnS0IaCWBMzdRyDGxGfoX2WP3nXVUoH5LBPSc5Qs=; b=QQ08kpn6ZFh7K0AuY+3rpyoX9x+R75mu92JkZC0MHZbvFHXf3YLLpMuV9eVcYUImJs z3vj8nAiuIH+4A6cnqhD3jMIUxRUPdHL6bCWHOVP+STIKYZsGJzb/RIL8HDjQpCrGF/P bG8P2Zgzh6bM9Vrh/jB2TmHKJXzBX+WQfBZJ017Q35bAylqJAHOFAmFqYbA92qFwtt5j D6i+xpbr+758mPq4my8H88SGfu5ZNAtNu9gdFfA+1xbQWLfirQC4rPtUw5I69VDFruo4 Tf5ka3DNZS43WVeLE+LEvHZGMt1zegB3rHBhmLe2YSjjwt/nOCwpzNt0/tWgkNgbe5g3 tPew== X-Forwarded-Encrypted: i=1; AJvYcCVS4kow23QELHVA/jU8L4eHL43aWc3tS4AfECCc8D0L5qUgmx5LYweOzdZtLC6jZtzcbnwKgRo0Tg==@kvack.org X-Gm-Message-State: AOJu0Yz6Dt0N2viVpBwmSRi1MUrLFJZvhqDS53aMvcSEeuN7bxwff0JE 7Al+cDIFa9Kba4YsnPXbjll986HdGiIySMBzT1sZHQnzOBTK9/EKr9wXAVjzQeyHkjP6oNFAQSz N3luwLUCaBWC3JQ== X-Google-Smtp-Source: AGHT+IGq/r3HGbbtFoFVRvHr1EOlzN/Wt8+om4kWd42V+YspQZes17Yps3LGccfMBIlhtc72415J8+GJZmwAm9s= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:68:fe9:ac10:f29e]) (user=aliceryhl job=sendgmr) by 2002:a05:6000:cf:b0:37d:5467:4008 with SMTP id ffacd0b85a97d-38254b18ad3mr818f8f.5.1732114577963; Wed, 20 Nov 2024 06:56:17 -0800 (PST) Date: Wed, 20 Nov 2024 14:49:55 +0000 In-Reply-To: <20241120-vma-v8-0-eb31425da66b@google.com> Mime-Version: 1.0 References: <20241120-vma-v8-0-eb31425da66b@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=9857; i=aliceryhl@google.com; h=from:subject:message-id; bh=thHW2hYjZXfFchwxaSHY31jS6Gxjf/8txx6XeVPPA40=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnPfiIPfGxtRmuM/beITcG2729I1pZZuD2y71Hm a5hLFdiTyWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZz34iAAKCRAEWL7uWMY5 RrM9EAChZwI5X5J59zvpP7My8BG3gVmNliYXLaMF7DdF13YYqlfRr6Nw3FK7e+/5u8oyjxwjLDq i3Aerdaf3lQlSYU3T8YKbVn4UKhByCAgIggWEbwvt8y0OPSLqBJ8gzZ8qYHcluaqHVB6En/S47l 7lsU2P1ozQStRB699rZdudrnMkzcxUw7oPTdb4oj33RV6AN3B7WuiPf/9FXT+L99Mz3fDdjhyu/ DZFg5TzMI7PXpxVysdNfctskP27Y+Z/4W/wr534zWMVNHWwURuyfzMFgxpA68y6YgmeIp7jBp80 h2+3Y4/WFCfH7dtvc2a3W7vdheRq8OqP3hIU7j85so4RpYZrLRFWJTsI6ksb8Tx6YatClhaN8xs QqZWzy67zmvq6CD9bNdc8iSGKicFWYqL3CRAK0dPh1iKzItCU/VYo6NDfKDVPKcJGCoeRa1mny2 klw3Ap8CxgCgpmRPo9MKuHZre8uhJo7HBYPJMqNjVqTzWUGkHHap3fIa/pW/02sBXfteKVY4BsY ixHgtqTqQsvDkUGNy7QnWKGvdDAWJel/bBeazpquvJIDptb99myFDl581bVHCit1O/7vW+4egEw CeMAkJ7joMJHpeK7O9KH0ek1UkNOypcg1cM4iLNqxpYvpGAVDO0IA41NZEWF3DyHOy4fl4KJhlt xSzwOusQ+/1n5aA== X-Mailer: b4 0.13.0 Message-ID: <20241120-vma-v8-1-eb31425da66b@google.com> Subject: [PATCH v8 1/7] 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 Cc: Alex Gaynor , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Andreas Hindborg X-Stat-Signature: 6qhbhmg3oqar6as8xekcw6dgzh7biq7z X-Rspamd-Queue-Id: 0EABF100011 X-Rspamd-Server: rspam08 X-Rspam-User: X-HE-Tag: 1732114481-96268 X-HE-Meta: U2FsdGVkX18Dun4iHuCp462bi9A/Kw6P1KyU/mriVP7rcGk3O6yjA10eE89xiMowjQuGMmLvnuhtHvvJLNzGVnDYDBRKkVIWsvdZSKw9ixewgNfpOn0jQYY6cYHYDBjkSVOyCRc9RPSs3Iq6c26tVzyBsCTnYBLUhhC06can+QJxI2R49zAgxAB/pIvxgcEMrCjWf3XgfHu4ZfnSLHEptTFGPfYockD7afwXO+SHiK1bXhLECYDBg5/qy3tIpt1WuuGuGLN6PA0kdrorhAle0OqdQJLROMjkzQOWJBxiFISbgiuQ0/2e36CMO241+Yp1VZLyxerZ5CLV4WHtmJIIFRTiqQ+ObbUcgXGXrDlIqfn4mSc0vcNhwi3rV4swwdcuIGGmfjCyjQIhRfT4mOKHuwQ3R5pM5hdhxo19UmSvi2Dwy8ASTayOE2UfnoLUbviR2wnuCv1FCZ2ffSeGDWyfpOHGipuLVKuUMxm+g7lQT86RoHesWPadkArNCnR3PCBzTGvudTbBS4TaNIYNe9f0JZYhQSe483FlTAtWW86MKEezZd0s8Hosd7CRpBqKPMBupbsZp1+tsCzVOWphw8QXxeBV0ywEOoPVudkVO9XQ59e93KaQp1feuvAMqv9dGQb0vZfsomFCBgpgwCT1ZVU5jmh7hN2IZfY3w/chMo81OX9AkjA/BCVhUgea2jacciBNshNM5kdwLJ8HjjrfEHXGOIWGUJDLdWZltpo+0v2r5cTyTlW2wJUsXROAyEHcQb9jGyfjlQqmPSOKR0VoWmnKDmK4dBSuE/8G8qkG6zvAEKDtFRz2lAMywKU1QbwLcFOVt2XJOK58OyRhpp/i06UGjl/ZzlmkINVaTvCka+f10X5HXsSTIfQJwLL9U9Xai+va8wbyeqfFQK18tYF7yfgWUtOEDcorwGi0OUmpoh7cRPewLfJ3f8v0lBAwHwBD1c8/Ttjk7Wzg6t+t8OSBTq4 oPVEfcMM QOJCGNEf94SrwwgTq3osXEBNDx2GxVvbgLwBMzwaojFLUUw2UZ4W8hNVJFE3ZOl/3fI3OCUOVhIBw5Bz0RCjNH54SR5scPByrvaf75m/Y/5immEOlYloJLQhetbdevI2OJQhTijMdX0av3JjYDerPAg+s4GQxv/mA8GDJE7zBMEmGtgnkGLuFUYUjt+rb6I7wvSAEgBolvZAFt6eOplYAMxqo1qLD0j1YFsztpNOCX4gVVTV0DcCdeu/Lf01lg9Aax2UMZxF0y0l0OavAZKwn2NcZyeRoKSyAlD/HShuHXFdaMmnakbNVVcvbA4lwSOD+IdqJ417iaDZrhxnL+q2y71GZwnT+JvOJZ0Z6Piu5HUC2jytig2kfy8fntlcMjiek2cpQSifPeHpnay3v7C4BmSHaZVGdEO7ciRfB+nngvCG5+jBMIhyYCPcSCMfLa0Tgvwoo/eO/x273phJQ5rbJJlVwTPKbjftlJi2lLn/bPQmiwRAI9Emnnt/n17UTbQkLk+Hm/ll3pBZBvb9gx9eDJBBE4+RqFXFzyfmRgr6MoTIXYAGxkxFQjWBJhyeYj4DfbPm1AeicvpL7x1vQUL+rR87WVj68vJIkCiUEhvuNSoYb7fkcIHi8okgv9V19K+K1eBeBYrKF6/2wTtxHGh3ZAhMPQW7aZTCPx6LVuBN346vHqcNQ85dotY6N1Q== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, 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. 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 20a0c69d5cc7..60a488eb4efe 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -13,6 +13,7 @@ #include "build_bug.c" #include "err.c" #include "kunit.c" +#include "mm.c" #include "mutex.c" #include "page.c" #include "rbtree.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 66f5cde7f322..cc1963510cdf 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -43,6 +43,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 exist anymore. You can use +/// [`mmget_not_zero`] to be able to access the address space. +/// +/// 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 { + /// Call `mmgrab` on `current.mm`. + #[inline] + pub fn mmgrab_current() -> Option> { + // SAFETY: It's safe to get the `mm` field from current. + let mm = unsafe { + let current = 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 for that long. + let mm = 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 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()) }; + } +}