From patchwork Mon Feb 3 12:14:36 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13957351 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 EE83DC02196 for ; Mon, 3 Feb 2025 12:15:28 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 44DF0280005; Mon, 3 Feb 2025 07:15:28 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 4243E280001; Mon, 3 Feb 2025 07:15:28 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 29DFE280005; Mon, 3 Feb 2025 07:15:28 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id EB9EB280001 for ; Mon, 3 Feb 2025 07:15:27 -0500 (EST) Received: from smtpin07.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id AC2AEC291D for ; Mon, 3 Feb 2025 12:15:17 +0000 (UTC) X-FDA: 83078528274.07.CBFF7EB Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) by imf08.hostedemail.com (Postfix) with ESMTP id AAEB216000E for ; Mon, 3 Feb 2025 12:15:15 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=BL5ODJ42; spf=pass (imf08.hostedemail.com: domain of 3UrOgZwkKCH8dolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3UrOgZwkKCH8dolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@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=1738584915; 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=wQaS28cG6yW+ftNKFxNZP6eegjrIvFbvaYv5chLHbzg=; b=mBZGf4kd03DEFD+A+I/qbTdiEarN15y87ZBwJLjQyJjd/qcc4uF5IDJg5xC+TpvjjchKqL aW9dnAmx2XBDDaqkjn11DCUycQHN+v5w6vuX1YElLs6XWa41VFcPGXTfqPLpSzu9b8S9RJ zY2aL1oLbNRZ/6EpycK6sgtx1qwAVzs= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=BL5ODJ42; spf=pass (imf08.hostedemail.com: domain of 3UrOgZwkKCH8dolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3UrOgZwkKCH8dolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1738584915; a=rsa-sha256; cv=none; b=4psTOg2Ep0VjA51JKXNn9eaWdy4bbnK8CjxfX1RDV3kr6UcWH8GQR2SuCbTJjA43hI4dA3 HRoeYND24awLjXdXz5gT8vQHqkh4F5y8i0/zdHzyaEjrh8D+QR+h6SE8/OMXH7BXy8c5K2 iYScP9APk35pibICwlHA/R0gRgF/Fgo= Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43625ceae52so22730125e9.0 for ; Mon, 03 Feb 2025 04:15:15 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1738584914; x=1739189714; 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=wQaS28cG6yW+ftNKFxNZP6eegjrIvFbvaYv5chLHbzg=; b=BL5ODJ42hypts5C8DSpNsxTfhIGM70dvqb3b14aRCEsW571g9mKVBj14yHspa0piFT jWQtKRVxRkon4ANKDFwkgy5EWLqt7xqtxvZxeEYxQTZx/cevcaMVFlDW8DAKePMiTSp2 aHiLbOmwYhDmSN/ZdVfLqTxGl5LBXNrrBahwUPYVex7B8UEpDztBMBeVfW/1Hqe5EZSZ 2dsUYSKYS7qtOfXYFlxOGePvPDZUmecihUoxby1LIN+OrPAVv8ajFmZFTiVOoat6+Axh S1Z27Vb5sR0CvL7EDJcirNBQsqgZEyPyOUTSp3IeNGdfWw/+G9VPPNDwJCkDLSwjyK49 dfGA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1738584914; x=1739189714; 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=wQaS28cG6yW+ftNKFxNZP6eegjrIvFbvaYv5chLHbzg=; b=G7n55stzdTeJuhGFIEA5PNZmHzxRp6CJGNx4UPUvJK+lv+ckA1/Eh3qvBM85J8fJnt DvjUF3puavb5dnEDZzxSH8tVQEuGL87BdXzP3Fq9FCceAAp9mRN1ZmggiDdNvwFMgXgd Y3c6Sgud0FnceOvKmI3Fl6lO3N57c1EwjwdpPNLZ3AjyS3otDLO8Ua4gnCd/JU+WaCPE khVVoneIBItUNWbcW/+7dnvOpOoPi3OpwpIy8T7or5OoRxAHggXfvak+TzC+OaAiWp7K q5x60NE1BB92UAbFJbQXKq/PUt501KD2NnByM8oQlS/1oUlYCYK7Dp3lYqSuKLiyoS4j 1pTw== X-Forwarded-Encrypted: i=1; AJvYcCVb71KSQ0NFpwm5HNmM+/5iZETVx8e4e4TiLq9Zywu89JF+HACAO7CechbhidotuFUrufWn5StQDg==@kvack.org X-Gm-Message-State: AOJu0YxJchnIRlIM9bqcze9nLtXdPWqLD7bS0+cjEdGHhzvhnWzXHEGB x9XES/ZNCsd/cbwW3ycE31pdsLEgB1X2KT7TWxjWzBPpilbpnPawy5uTeuOLWH8DavRzEvyHU8t Y+cGsguVXBe+GzA== X-Google-Smtp-Source: AGHT+IGxJxBbT2D0jUH7PkoghvafmPAMvx3j15vJoonAlLH+FDpuc6DZ1HXcdNaeLgjK2m0GeHgRrPy+nOzkvHI= X-Received: from wmbbh25.prod.google.com ([2002:a05:600c:3d19:b0:436:e723:5be6]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:a089:b0:431:547e:81d0 with SMTP id 5b1f17b1804b1-438dc3bac30mr240516145e9.11.1738584914324; Mon, 03 Feb 2025 04:15:14 -0800 (PST) Date: Mon, 03 Feb 2025 12:14:36 +0000 In-Reply-To: <20250203-vma-v13-0-2b998268a396@google.com> Mime-Version: 1.0 References: <20250203-vma-v13-0-2b998268a396@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=10247; i=aliceryhl@google.com; h=from:subject:message-id; bh=SmRa0acQEuEADan3GdJe/hIPrJuPHtTw8z6DhPDiFqM=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnoLNJtc+O9U//+xzFxHIwPIhQUQRbRxX/4wZxI dLTxDCumKyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ6CzSQAKCRAEWL7uWMY5 RocAEACJm1PYPEHpHiykEjJyFzPL4gv8/tCMYFkHQSopUImzpSVQlc7CE2mwY9GKpP8he2AbVHb wdGSI6KeAhnFzA4nPPBUG8c/VBuONn5+aS3fJY9TT4m6QgzccvQm+UuOx/rfiVdbSxPhJJ8u5Aq 9Dd/rpp9maEV2yx59n6I5tuf3jpvdLGkSQDTRghtBwhX00tMzU7PoCdlvYG39FpDjmfrAOU3JJe /Lxy+FoJvw+779h9exMd3sITMAp4X+ze3c7a9arfaro9GMqoFM5gxfx+lbKlKg+6lyzsFReMkCB gJwPMD0saRr4ndazh3/Yq3GbRceVIJkzpLhTYSoBbjmpMcpGLm3plmStKN09A0lJfosOxaMu26a HdyMEmRAcSXmfsZZnJf2DEv17YijbG4injaPUlqua6VYJydhNMeU50NbziZKK9po9oSBp84z9MR wgkjzCRsHrQX7A0OQh9Y50A5oQi4ICfAIqIEEPYfjO8esKtcH03cYVMwFEI8nzMKlsO/8yG2WkL MzBsyTuZfSPrQOc2eOz7OF6A2/0cvJwNFqXOrj2Zu34d8AKTGsPkAjg600u61nOEo6Co8SZQyop Wh8ybfPGSzR1QN6bFbnJlbnaot1NvB/ZPxTTiJYV0sX9Bzx3nb9KFyHgE5A4ocDkTta9pyy02ET 87mcDAXq6UUwpsw== X-Mailer: b4 0.13.0 Message-ID: <20250203-vma-v13-1-2b998268a396@google.com> Subject: [PATCH v13 1/8] mm: rust: add abstraction for struct mm_struct From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Lorenzo Stoakes , Vlastimil Babka , John Hubbard , "Liam R. Howlett" , Andrew Morton , Greg Kroah-Hartman , Arnd Bergmann , Jann Horn , Suren Baghdasaryan Cc: Alex Gaynor , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Trevor Gross , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Balbir Singh X-Rspamd-Queue-Id: AAEB216000E X-Rspam-User: X-Rspamd-Server: rspam11 X-Stat-Signature: 4pi6cmqd1dzawbc3x3gaae8tqnse6xhr X-HE-Tag: 1738584915-918903 X-HE-Meta: U2FsdGVkX191q7FwVSYIbOaDYgJUHm6UUYEJFVY/Wu8RPzWSwquviTlcMAu5HQUgbTF4TAuFMJvpYPyPTqBBqIGAuR9cLpAh8piH72Du3Y9KNYw4i82PkMQ0FpKYOqPdzL5+PT79GZMjyRiODYGmF1cnI9gUIyreg3tIYcPbuqvA4j13AiL2yMbomjipNTpLcGU680UyJrLA5Z0at3Ipsm/O1niEKimh0l0CuFi80Ahv7dvVv/hEz07zM1xBhiHIxakquxQWg14oQeV4IhTrD3+9bqd3HJQLXGIXwQFfJwb9GTrh64jdn0vOZkZ3gM0KrvR/4mejvc8EhyaowF/A7+O/F94N4oyKlDSB3J69AZOUmHenCVkyd6HtO5H3CJ+gBys+K7ZV8VAFZsxPBtKPe9u6cfU3TYOnShlOmHgFRXbF0klCPgerCZ/NGFlqT+Vue1eBmd1hwbRdxl3hVHfxH1UCiUIJ0g0DqQepcgd1LyitYn3Y71BA/vUHQ9DzQdg0LoF9Sx/SIg3QTu7AOQrQVy1iyZFslqJuU5Et71Uxi7ARVAVY0l8IKodb1CHyl4iasQ7cKX9RPVn9XrNoJ8owA9BQX8SkTc46VYHg845oYh7UChyo+D2L8Xrejb/X6tRwuwS/C0gcJQaEL9id5bW4apkarpZI6N4Ntv8hPG2fMJcerVWK8KvUAiuvjmbXPbEDat2Jj0IuXcyLEcX7Sas1uqWOXL/rDPgIEkDoRGx3Ordwknu0G0e5nEMxhqvpJJf8U66vCkjkxiru3zxuAxDdWWCWzMEm6so+znr9KLcDOnvHyV+ZbXOMgOlIEopzarxcHxs53htDGKwWwxUGE4ZFvFqWdDJ2Dn4owoELHGrFhw8HBg/GrkpoB6GM1xbEvwvxmPANG/RzXx15npYbjE7MKqTThcqF/24OHSXJeeh042RttTTaY2kEZUmYDSW48dGJ6IIVmbnc1K4lj8R4kva TtgDMpzy 6IrF9r9tNRZ4Y7r60onYuTpUrB+T7Jh83L0WSHcUlkWwL2WtLq1rmoP0y2LLc6ex6+4idSIVbB/A4d+C5gxqUUx7IgdWM5Lqh+OY5DG7o5+BFrEb/9v6tBCprj2zlRvKgyOQtz75VY20frIIm0aAV7HlC9mzmM+FGOUfOhJ21gaLUDi8ZuRL0dpJtp6agKeiiL9/2afAorS+ihSd0gGuXpmRTgLZm+0WCCXylP6p7ncXe6+QgJUIJH17dnFq7ObvK+PEynDJTGDLHICcYVXTflX80rzmDjO06HE5E6kX7GzfcLMTAigwr39SBsIr+qm6X1aVTq9SyzayryDAz5rp3xv3PHZbxf2ETh5eQLGLYa9zMorb5Y2ogXEbf/qSdIR5u8zTNhK0vbytTe4NUddhBQdkXJthK+KiNGooi5F0h3rThfhJYVVhyH/1KdaM4qDk0WYjWJB4JBrZwmhpaishVGm4sIQVz6mKNJzEFyXvs7wMeig6No9+PSJpmoNK8Iy+I3/CjtRuzqVuqj8OrQbTLIjz2BxJimSF6Cqb0wJ/e+LYgLLr3mgkUg4pln4H1aPTva/AZWyWL2IvxWC2kqUiz8ZUeMBaw4iHijvslI7w4w9KqC5l76trKdpBRvbb1I0U85DX9UADjyQ/PR0kxKpkqOYaZHDxpyMODtNpd/M0OwQj2cQoy7+77ZgjnoDKN7WZa+bRApRk0YklNAI4CItRL6bxhdeV5ZPs2VZjqyvZ89h8HjHBQZzrb6+b3Fp0PiXCGaQoa X-Bogosity: Ham, tests=bogofilter, spamicity=0.408146, 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 Acked-by: Balbir Singh Reviewed-by: Andreas Hindborg 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 0640b7e115be..97cfc2d29f5e 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -18,6 +18,7 @@ #include "io.c" #include "jump_label.c" #include "kunit.c" +#include "mm.c" #include "mutex.c" #include "page.c" #include "platform.c" diff --git a/rust/helpers/mm.c b/rust/helpers/mm.c new file mode 100644 index 000000000000..7201747a5d31 --- /dev/null +++ b/rust/helpers/mm.c @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include +#include + +void rust_helper_mmgrab(struct mm_struct *mm) +{ + mmgrab(mm); +} + +void rust_helper_mmdrop(struct mm_struct *mm) +{ + mmdrop(mm); +} + +void rust_helper_mmget(struct mm_struct *mm) +{ + mmget(mm); +} + +bool rust_helper_mmget_not_zero(struct mm_struct *mm) +{ + return mmget_not_zero(mm); +} + +void rust_helper_mmap_read_lock(struct mm_struct *mm) +{ + mmap_read_lock(mm); +} + +bool rust_helper_mmap_read_trylock(struct mm_struct *mm) +{ + return mmap_read_trylock(mm); +} + +void rust_helper_mmap_read_unlock(struct mm_struct *mm) +{ + mmap_read_unlock(mm); +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 496ed32b0911..9cf35fbff356 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -57,6 +57,7 @@ pub mod kunit; pub mod list; pub mod miscdevice; +pub mod mm; #[cfg(CONFIG_NET)] pub mod net; pub mod of; diff --git a/rust/kernel/mm.rs b/rust/kernel/mm.rs new file mode 100644 index 000000000000..2fb5f440af60 --- /dev/null +++ b/rust/kernel/mm.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Memory management. +//! +//! This module deals with managing the address space of userspace 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()) }; + } +}