From patchwork Wed Dec 11 10:37:05 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13903322 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 7F2FEE77182 for ; Wed, 11 Dec 2024 10:37:39 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D0C166B0112; Wed, 11 Dec 2024 05:37:38 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id C95526B0113; Wed, 11 Dec 2024 05:37:38 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9FC576B0114; Wed, 11 Dec 2024 05:37:38 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0017.hostedemail.com [216.40.44.17]) by kanga.kvack.org (Postfix) with ESMTP id 7BB536B0112 for ; Wed, 11 Dec 2024 05:37:38 -0500 (EST) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 3372AAE97B for ; Wed, 11 Dec 2024 10:37:38 +0000 (UTC) X-FDA: 82882326282.10.48212D7 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) by imf08.hostedemail.com (Postfix) with ESMTP id ECC0B160002 for ; Wed, 11 Dec 2024 10:37:20 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=uo96PtYS; spf=pass (imf08.hostedemail.com: domain of 3bmtZZwkKCOsNYVPRelUYTbbTYR.PbZYVahk-ZZXiNPX.beT@flex--aliceryhl.bounces.google.com designates 209.85.128.73 as permitted sender) smtp.mailfrom=3bmtZZwkKCOsNYVPRelUYTbbTYR.PbZYVahk-ZZXiNPX.beT@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=1733913431; 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=eeSYOeE5pMMeyg7ZhXQAlvtxanJpaTuPefZQ5vxq80o=; b=dUwIM6UKzFz1zTYJ9Dnpw6xV/ElSf98EWW3qehIavytTNuOQtRcrrL9cnVxNZ/HN3zsjKT A0KiDOWUiPP/fOQNZIY0OJYovnp1uVOzhk4qoEMlhgV5wWcLZX/8aqlgEcFOr0HC4s18bq aULgtT7ScbE/HuwjztIOmna7VS8KahQ= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=uo96PtYS; spf=pass (imf08.hostedemail.com: domain of 3bmtZZwkKCOsNYVPRelUYTbbTYR.PbZYVahk-ZZXiNPX.beT@flex--aliceryhl.bounces.google.com designates 209.85.128.73 as permitted sender) smtp.mailfrom=3bmtZZwkKCOsNYVPRelUYTbbTYR.PbZYVahk-ZZXiNPX.beT@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1733913432; a=rsa-sha256; cv=none; b=jwQGG/VBeDZsl44EkgTqkQt3fc8boq2nNrdFv156hHbuN+5dL+F0nJWmAD1EpA0HeMDXBr U+A15ObC4Japw7AGEr+9YCwdIUC83Ye5pY0u/xJe5bMQrew7MscoZp3j9lJmwZlsYFR/Bg 13fKZPL4J5MBm354UKqlDUn4NSLy4nc= Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-434f852cb35so2245185e9.0 for ; Wed, 11 Dec 2024 02:37:35 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1733913455; x=1734518255; 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=eeSYOeE5pMMeyg7ZhXQAlvtxanJpaTuPefZQ5vxq80o=; b=uo96PtYSpX3U9Gx7sqNHT+wIo7h5tk8x3IFcF2eeXmQ/dCU1VOs5z1MN0+OylDAnS1 gtVfhq1mQY0wFgpTmI22VrLG7bpIGLEkFL+TfpnEMUFJ1BGRNfx5CjIuUco3nzVMPC6v EVkhQmLoxKvRveHirb4jDPVw1twmJWbDxMCWOF8Du3V8+1rIRtHfXtlPrd8teuzeJDe3 oVbZ/r6M/oru23Dit3nrjRZpZu5fArOGx+rEyjHGCbhgrnIhuBhFXECkPqWX4GoWTvxv MwlfFhV3kuAl1yDyUZe/SFZlmCiBQIvbqG4Bv2uTilibU6F8obHfVAxV1GcKEyRoBS+j xA6A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1733913455; x=1734518255; 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=eeSYOeE5pMMeyg7ZhXQAlvtxanJpaTuPefZQ5vxq80o=; b=uDl5BrKSllsLQMzY1ecJeaoQ9OC271MPAqOQDd4qi415HswtZ1Ny4REiB7RXuJ7/aD mP/9+ulnyLXGv8FI2nsJ0yAQSSp2nSZOJZbCt+5BY/dOAv7ps2T4KdvJ8X/i4X4bQQwI m+QMVirfaQTXS2rW3+3R+DwAndWFmadh9Sw9i/Uf4JveQCobvc++PmKx97uyWg9pHNRa QlJQTmjSqM1jP6y5wZ8GTL+5ycbnLWmBB4QAadPGQMVHB6WIAHqMRq3kvmxNTFhiEmuO VOzTn9SQc0Rr8B+7+0yydAVpnbaArryoZUeqtDadLUHkFiMWDzulkKoR8lJsNu+zncuG shfw== X-Forwarded-Encrypted: i=1; AJvYcCU8ae75MG28uVim7lPI1EV8Eaki12AL+f6R8CZ7Ri4xp7HbhOP2I3i52iCIxdUVVHeEtSSf1icIBA==@kvack.org X-Gm-Message-State: AOJu0YzBWLvqcraMaainiDDq5TR8gOIbxO/vPDZwMyniHBTlLmx+Mt1j MFOfvNvW2a5smm35RrzrceBAFNT9hKZrNhzQ7PhxS/Pm7PyKDaedv1Th4JJFsbpEwbybV8sXPX7 1uL5MpX5khtdelg== X-Google-Smtp-Source: AGHT+IGlVGDsXAS8QTt20ZhjhUvb4+iLhx6imu5M/qvMwlRkpVFZ0hN9qToGEpQgPFG5rFlBMfq0S5s6OEGbDoM= X-Received: from wmbd2.prod.google.com ([2002:a05:600c:58c2:b0:434:f513:bb24]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:b86:b0:434:f623:9ff3 with SMTP id 5b1f17b1804b1-4361c382ce3mr18383385e9.15.1733913454954; Wed, 11 Dec 2024 02:37:34 -0800 (PST) Date: Wed, 11 Dec 2024 10:37:05 +0000 In-Reply-To: <20241211-vma-v11-0-466640428fc3@google.com> Mime-Version: 1.0 References: <20241211-vma-v11-0-466640428fc3@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=BP0rHFtdcn3zxhmWpCsC4fRZsGWpHTVijKhPN/V33Gw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnWWtmTO1N1K8DUC6NoDXf02ue/qobHQiKrkrWy Qgkt4oEYx2JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ1lrZgAKCRAEWL7uWMY5 Rk37D/wKqutxvgqTXRQSIuDKk6I9CScFzIL8g8BqDE1KNEKiN6wrIWLFEcpw9BSH85DoRLdm0y2 XGydQAJ5iIJzfHWTw4k5RvMDkr8JHrdMTYTNLo9w49UHdABMFkiSk2ZRQ4p97t2rcPk4DciGYtB LYzQdCJPLhvlnk4j125r3wgO+8a1PgVElFmYrZZG42nFk3Do3gamix8Db9R8M6/l5Zl9o2uObsA ONIlvWmIedb1NJ5V/LfYc/HhYoSZT3wYNQRjET2d0352qRxyipt4oXDJfEOnf4PUc9WElAfZaEo Itha4cyfEjOZjky9RLsKXWzEQFyadVxgjxdtYQwzOScECwI9iVKIvRhYYHdjLqmmjwW0rkktYVb DDUuSOD3u9KPp1UEtAxW/wWaPN3JUFL2Ng+nkc5V7nbSzlMXF22g5ytMA0rpK1QOC5NIhqVXDup SbLgi25Ot6vGwTcrGyxuBbQjXTVfV51yZpVQPW96b3IF30Pd8OHeMa2bCusmjZU+Po5vkEtOpoY 8GLg8cf1on2Jt21bMRjq6S4gH4r9TLiZ5WgNBhTp1CAc443b92p/AVEzZshjGavyrKiMhSkBnbR j7QpB7Q3pSWCg1HJHzVSwr/MX9VStblyNEDSRZL9+R4YR7h3FeeWbC+qJWw7PscIJWVRRd+QSWf a+c0FhQRhWjjrTg== X-Mailer: b4 0.13.0 Message-ID: <20241211-vma-v11-1-466640428fc3@google.com> Subject: [PATCH v11 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 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: ECC0B160002 X-Rspam-User: X-Stat-Signature: 3ogud9wobss5dqb874bftkacuyn6njdt X-HE-Tag: 1733913440-6392 X-HE-Meta: U2FsdGVkX1+q4/tTdIPyIGT62HQFtHV3e/NL/dL82ICnpdNkZRSEs4RDDL1mxrKYz0AyollF8+2w4qRK1tGonUy+xWwH+KzvYMyfWpviqL2fL3lZ0rhzbENsbtBwlQxvprsfjhvi+bmbRDF+n2IHTUsbf85HG4axYpKUQ1zaSF3B6AUSkjWYDf49DwvGmxMypzlSCC9BQwXLUKqs0VDt+cznlclhJFgDhtFMMpKBEQy6rN4cTFH1BUiauWiB4fEoRP6Obn24pPq/LDIbeSp41lVgdiBSKkIVm/mrdPwNdsDVBowScV4P6WfCUIwHijvB7WE4MgzbcthZc4YKwSoZ64os85DE/mslbIWbRV+9JLQQAw4MzA9MrqnPN/JC31IyS9S9GKSDQ3J764kUrCWoAWntOye5J02ns19s+R8ZB/PTaSsBvto1m7l/c5NCbYmZhDtEEdCantkHkl+yvqQt+jwv6i+aTi5JzTVCHEHxs2a9eePdoJ0f5ucVG0/MjAaM1W7ctZ2/vpLNBU/vAKs2IEAt2kg8R0wZZheWD+ANo883OMnGur72dPL9ZmtFG79+HBrK7HQQwSltIZ+XMl8Ou2MfRifkYXyf7AAHva9KA92aNqdaWSg5hNVz5oNmQblHkEVx4W69hiOaJXRdvViaHBwKlUqH4jvjG0qM/wj1m22qZ3oK+0v9ar9/Vk9SErgltzgOdz4WNQfUZyKrvg6Riw14x3zhQwK1+jOZ4i37IXifJzqlVxZSQ/bMhaxkSDilmVQXY2zcJE1YW2E+QGpnBZ7eumkcslBQ9qhWmcjES/ATKM3BZb9Cr3Se+VtxgIcTTtO+IVUVLZtOJXoA5Emn5vDllv4fpFC2DC8uO50fS1Gbift2tFUbhCz3uFthVYdSWHFfMJ0g3aQMDPZlD2FaFpsP0YM4Zh2T1GKoMNy9q17hnCRuDn4vGcWFNb0yQ/b/eo+bLuQtcHgXwME/cNK WreiORmh NbG6JMxzG3VN3WWOPfIS1hAB1TwXRxMvSeuEsjJmXaeWPvufCBfP+zuHnOuVkFaDa9KL2+faGmEBXZ/acDGJ/1+rNivaoW/laK0RR5e7JCts4GWb1+ggs6QdYMyCbIuDPzerV1MbVWaJEuCGaFaTzOGHcUJgo283zJTa0FkhBXgmTIlx1FEQXu56TyhAPygRJy8dPsQhJ2AjQXtwoMpT64fZuR0NCh1Hq50yRx8kxRaPlg7hAbLsU126+MVGypqMfD8YzTydl91biZeKfIyPUmIf+GfnYgTxm9y+D9OJR3e03CHJzg0/7w53xKbD5maFR8z8GAs3uSKvhSp3HP5KP5HwR8CwYkvFsZ+g3y3w8t7FFVchUCJDeOuqPIUTHQoSrW9Y6mVvxwleICYrgtVL+Hkg4UDOA2J9Ny2nvNzfvz8BtPAr4ws8zRgJrIYVTUMUPhdk1LMQ68nds7gLqDGLeIB+S18Gq9vHGG2Izr1JHb/SbConB8nrBz5BUuK7AIjoHrgeK2ilRi5Dz176bUCb1cbDLO9agkiiW/c2P2d4KsIPWdIW7w2bcz8ijhu7/cIuuRrvMOh5usNvTnxZP8HhaCJ0uQA51N661O+VHiQPhnRsJDfxsnz9yr1nDjAQwuX+bQUnkWX4UBcHcHTdvn8a5Ktd9jMo/kNub2pEesibXRXD1KI5xtSq9AWoPETALqBnYD3JhUy68Y2mzVQA= X-Bogosity: Unsure, tests=bogofilter, spamicity=0.499547, 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. 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 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()) }; + } +}