From patchwork Fri Nov 22 15:40:26 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13883302 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 A0CB2E6916D for ; Fri, 22 Nov 2024 15:41:08 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 30DFC8D000B; Fri, 22 Nov 2024 10:41:08 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 2BF1F8D0007; Fri, 22 Nov 2024 10:41:08 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1117F8D000B; Fri, 22 Nov 2024 10:41:08 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id DB4128D0007 for ; Fri, 22 Nov 2024 10:41:07 -0500 (EST) Received: from smtpin13.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 929D51A16DD for ; Fri, 22 Nov 2024 15:41:07 +0000 (UTC) X-FDA: 82814141802.13.49809DB Received: from mail-yw1-f202.google.com (mail-yw1-f202.google.com [209.85.128.202]) by imf07.hostedemail.com (Postfix) with ESMTP id 3AA2740010 for ; Fri, 22 Nov 2024 15:39:51 +0000 (UTC) Authentication-Results: imf07.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=FUAmD4qB; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf07.hostedemail.com: domain of 3EKZAZwkKCJ89KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3EKZAZwkKCJ89KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1732289972; 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=ZJFWlPcRbAWY+HnVngOyCc1o+97QXNSOMi5+R+xDQr4=; b=h42Ik8TeFGIxxCWjbhiUDhuLHGDfPJ2RrWOfs15Rl9gg+5o5KY2hb+KLfaBdJtyItqrCS/ 3VsiAitig1+JjZTnM5jTZHZGK5XBj8S3FyszuvplyylAY4Lgfo9JwuNbzQaWv0T1HvYazQ PvCqKm4TExkLdmhA+xDLsw3FSBiFvXo= ARC-Authentication-Results: i=1; imf07.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=FUAmD4qB; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf07.hostedemail.com: domain of 3EKZAZwkKCJ89KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3EKZAZwkKCJ89KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1732289972; a=rsa-sha256; cv=none; b=JlBFQt+ZjCaQePJ5DKpzNsLM26BBcWPgpf3kVMniKFBn8yGpooBFf5KmdH2pwo7JDwrSTn k58pXgCnasBjrQrWmaCGmtr5KXUOPOObeKyNRsZml7zh8gMy/QHo26BOsJXMUBbSPiWdZ2 OEZdZZQSfaosgHGX6nP8+khgtQTWDJA= Received: by mail-yw1-f202.google.com with SMTP id 00721157ae682-6ee65ae21b9so37253747b3.3 for ; Fri, 22 Nov 2024 07:41:05 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732290064; x=1732894864; 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=ZJFWlPcRbAWY+HnVngOyCc1o+97QXNSOMi5+R+xDQr4=; b=FUAmD4qBQkPnP8socnAYdEepYzm47g8kC2MWA7CLdZDndHPBwdVJhfCfF9JN7yjOEW QPoavnKi5EwNvBpR2QJIomrmS9MnkAGPzt7O4AjEuHLIIfuEtG79qjlKdqShFcdgxpAl auMg/N7YDzc49A9u1BZK3cnY3fd/ZZ8WJiP6bf38EdNUSB71DzN99DgJSfEEGQtn5Fu1 GfdPq1wiqhhylLm64XSGFfWJczb12L8BgWENH6g0FGd7wS33ky8QC47QpfFzc6kCb+q7 ohg11jCOfp5zNltX1eFzDyY4f/PUQc1AE32xvSl2g2NKGILuMwEz2JEvuckivRMhtzDv wmNA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732290064; x=1732894864; 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=ZJFWlPcRbAWY+HnVngOyCc1o+97QXNSOMi5+R+xDQr4=; b=wfe3pPz0wI6y5U1cvNHOnQcuVvs97s1+aPvpLDgLluPBCcz69Aa8XY5FZ2+4PfWzLK mLSnoqmrCTGswizGrRclluy3Xewtn48V27REHdKvjtUk+2fr8mSgPhIy9KDaPZelS8T5 4p+T0Upi17yRX0YlR5kmGnqOz8JosmXWQcT7BhrAe6LbpHFi52BVoDmWTdY3s5qQ9ggK ml89YS3KY+lEEJZI7nD/VJFwnj5z+BrdvX0/x6OJHf6IEJrcU7d3g/rz4MrcSvEx/KlU mRkWj3izULQIfMYCwrwRc/6lER+RgUwZ74NHDpAMMyx3L6u3Mh9J93M+/UvRPxTvbFXG UGAg== X-Forwarded-Encrypted: i=1; AJvYcCXMh39GKMXDsN6RKtpjo6zajj3zbJiPIhEBwfcrBjT/qoLqV3/RVyfCqTXhm3b2OUYjSxaAMIDkcw==@kvack.org X-Gm-Message-State: AOJu0YyJQOSox+ZbIzN5El7gFjKPPc4SnYhooS1A9WP8OuJtN6kQ6Dkx e8G3AsUQCeTZE13ninzzK4DL3rJfKrw0+l6HSYe9he3SXk2NJnr/Buv5f4gCLlDsZaWlpqrXFUP ORwn32hoQo7rpeg== X-Google-Smtp-Source: AGHT+IFkONJC35kmfVY70U61nS/i2+8qUNS80u+/hoQsPbcnJf4FyJ3hfmZEVlFS1n5cWkqU0f6+UfL+LNXTVJs= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:68:fe9:ac10:f29e]) (user=aliceryhl job=sendgmr) by 2002:a05:690c:680d:b0:6ee:b693:f752 with SMTP id 00721157ae682-6eee0777adfmr474527b3.0.1732290064561; Fri, 22 Nov 2024 07:41:04 -0800 (PST) Date: Fri, 22 Nov 2024 15:40:26 +0000 In-Reply-To: <20241122-vma-v9-0-7127bfcdd54e@google.com> Mime-Version: 1.0 References: <20241122-vma-v9-0-7127bfcdd54e@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=9971; i=aliceryhl@google.com; h=from:subject:message-id; bh=ZPc1KRKfoIOZWtqnzIede0sGQwVP3YDeDd6Hc6TOsWM=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnQKYHu02lowltad/mpq8VFaO/SbmENjK7ouQqb BP+7GBjeceJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0CmBwAKCRAEWL7uWMY5 RtBIEACzoJXZvz8inFVeNuo4OnCxriwsgPHZvem8VJonDGvKOqY3hV8gdgEW0K8ZCRVi3FxkX6Q rhi2LU17e0tNyuNS/fPXzgTVtlQ+uePX+T16VcOwD6Tok3wwoFlgJFYP9rkgdXCwPbTP1RDxVZI O0KP5gnzotaIObWIAXjiInjRdZzTbu3YtmSadyCpxmsvplUP30jlZPPQEtB8IdO9lXBfN+aoekT 8ol3fX/5me6J/ORV/A9ejQWpWz3GgcyhCfe7Z+y/+7cvWVFPxs3arcjCc0HMHPLabcK0RClafYY JiNexDK8yqS0gGZ+aYr+2c7FhCwv+6Klck+F9LsSSLgiXKK3VxKaFYAqAt/H5ketvAtoyPYcwIf Jjv6yuP4SQ9Js1cuTPVfq+ecqT60ApH2hc8GZnQ4Kd9UjBnMePsRewrTf5Osa1l9sfU4RCT8Wtx V6epoDSENmIwUkovL8UmHv18xLKpQCWU7aWYAxZuyjsBx8wxUpBAh+sDxz1MHYXLAiYqfNPDeyZ GoQ0KMDpW3H2jq+9YhKTCXVo+6Q85RXhvMNZcA5+oj1eki94TSGdEl13UC6kuaNaME/ROr2jR0N ljH+qZ+PVCKuKW6ETcGvkIkZ3tCYAlCN4p1AtzRwK5nz1lGdMpgjtgc77S7WlWJXRLmw0AIzo2M B1pjqpbr9pI51IQ== X-Mailer: b4 0.13.0 Message-ID: <20241122-vma-v9-1-7127bfcdd54e@google.com> Subject: [PATCH v9 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 , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Andreas Hindborg X-Rspam-User: X-Rspamd-Server: rspam03 X-Rspamd-Queue-Id: 3AA2740010 X-Stat-Signature: xqfyt6ow5mqd445fhjt86dn9sgscog7o X-HE-Tag: 1732289991-490230 X-HE-Meta: U2FsdGVkX18dsPHajGWjcKbrKpdxhzNkSSti9ojd3YPFvIdpZ6Rkv8UK88/4MfH/Ceep0utzuI6apoUor01up7vGyW5RWrcWWapsk5cajxw07VxN7JsD3TJCKIXRz1DKYQMVLJRHQbM92kO1NfvB5PPEHNlK/PvILZy9sHFeTq5vWEgzhM02Ol85yt4MpGDP1grjZsXF/CjmBb/IcuL0Dt4cJ9++yZYq9EYCdxVkwZ9HTiAJi2Jb37AkUgEhUfr7ebeTN+uZtqb27fR+B7GsU94b6OHhlf+QO5jC/zbqDv/Gv7RkHKoiDZUtBVkAGUclGTsKCvOKu4sR3r777QsmshjaFV9YnkwlJH8lzjWuAOGtr1wVTicvxn5F3VomHAq4AtrxwKns6aVfIBlfLwq4r2ixJM3U+zRlCjSg8uc9I2t+WBbMu5Tbn0eOcHptmpcfXmcAAHdDSNQKsXzl+LRAjTl4u7dKiJd0/+4VAHd+Qg+lB330ShkGPYlCogOqYyJUXYJO5NBl9p1Rn7jJ7kls0s74kCxgvkGRwgXh+17/IJE+9E1Cw5GExjvpSp6M4WP+Kwul/qWhv278OrxiSpw/WFCR+rDuh2XoWHUtvw16oDXPv3mxjPitXmBm3QTCMIf+RC81y5Q4AAML8d1gCGMZ9pb6rdX3dg+RYwLy3AGqadPFYrxKEgRR6plNf/jifoOi6+he5vzRYoRJ92fqyvjn7eKW7RFHgQGX/NBtL3Z6MdBhhG9Tj5gRLICZLwL6TBFxHcD7ZHdlVteJEJpSx1sRPBj9+2tybNV9VMuXyT1mGwH0WCu07fVeanzVk400Q8ZcVWML8JZcnV58zTuDKHyxULYi+6vS1XCLllZzQ/xH9wOgBGCrO4xNh57jsO4v1e4BaNbuEVR5MCr9Tm8RIixBDcqVJeynV6qTd2s+2aCLqGpe31i94e1D67N7t3IHXTG/7wGd29qrz/GQJPzB7Yq ycjj66U9 S/4APtZrWX2TkJKGalqo3252B8jZqdGyF6p8CyX8271NmDl32QVXbYhChwZ5W86Z2zf6sK9AVxSzTCAiETJhvwGbW4K04Lh5Ii4xgerkjz2KQmeScTBJTuHlQZKNjv5yHV5KbW+d1bU+CSMbu8ap5+d04KynLi6gri4B3+wqBnk26xX5g5pQ3K7TTwF+FBOQtShy2M6+ZshufxreNtRpT0JuBh4E+WXOZzU6ovyr2gszcNjovdFSG6zhJUjs+oiNKUsGXyudszOvJEJZE7oCr4v28uFq5sAGkYPtgRNKCdgByeEyyqWK0/zBQgasWMPhwokM+6X09wlGZk1CPc+UKbQhcw/pBSozbo7F+xNN93UqLrmM3bz0ppk6s7NW8PV2hl2weSk2g2Y1ltmv9ix2HLn5lSbXdBysn26Vhem9/dYP52242VRuN0AvPNfkGc2z8Kz93WIMY7JuQQ9ByedboKWOYbQlb7zfwb1mUuVk2Xtq7reJIfMNSrUeQeebi8gQhrRkywbL3i87ON8ijHAE5ptG8U3YfD3JeOIBtTx63h+c7Uyz1lbjNTxzKHcFzOEdZwy6V8HrIhZ2fFVz8YsVuCG4mEBVmAvsPDPIvzPJuqqCwcIksp4G6G9C/zUZMvrfTKIcD0SSK20TqorF+ELbwthVijirf15/WpJWKkIlNE4XFAM9KX8ApMmP1LQ== 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. It's possible to access current->mm without a refcount increment, but that is added in a later patch of this series. Signed-off-by: Alice Ryhl Acked-by: Lorenzo Stoakes (for mm bits) --- 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 6d90afd38c40..2ee3af594633 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -15,6 +15,7 @@ #include "err.c" #include "fs.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 bf98caa6d6a5..104e619f5dbd 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -45,6 +45,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()) }; + } +}