From patchwork Thu Feb 13 11:04:00 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13973102 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 BEDEDC021A4 for ; Thu, 13 Feb 2025 11:04:43 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 515A46B0088; Thu, 13 Feb 2025 06:04:43 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 4C6306B0089; Thu, 13 Feb 2025 06:04:43 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 367C66B008A; Thu, 13 Feb 2025 06:04:43 -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 13E0B6B0088 for ; Thu, 13 Feb 2025 06:04:43 -0500 (EST) Received: from smtpin13.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id C823BC0B9E for ; Thu, 13 Feb 2025 11:04:42 +0000 (UTC) X-FDA: 83114638404.13.5C62117 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) by imf19.hostedemail.com (Postfix) with ESMTP id C47B81A0008 for ; Thu, 13 Feb 2025 11:04:40 +0000 (UTC) Authentication-Results: imf19.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=a+ZqSKrD; spf=pass (imf19.hostedemail.com: domain of 3x9GtZwkKCGYEPMGIVcLPKSSKPI.GSQPMRYb-QQOZEGO.SVK@flex--aliceryhl.bounces.google.com designates 209.85.128.73 as permitted sender) smtp.mailfrom=3x9GtZwkKCGYEPMGIVcLPKSSKPI.GSQPMRYb-QQOZEGO.SVK@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=1739444680; 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=w9c//+puMEPIu02W9GqdsmxdftBKhgzEpRqTvLiOh1g=; b=BC1EM22wXhe7rm+dwbTzyFIsrHZB78J8eyFkBEFmFAWvsgWy8L8Vrx5C5hBef2oUf5T7iO KqcK5vA8tNjDICfYejMSCcLxAg1M3CC8UySkt0rkX2bgeKnu774tLXtHxaSYvwADwzcxt0 mYmz9m5gJH5XUGxcRQ0J3CLwLQ8sjNY= ARC-Authentication-Results: i=1; imf19.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=a+ZqSKrD; spf=pass (imf19.hostedemail.com: domain of 3x9GtZwkKCGYEPMGIVcLPKSSKPI.GSQPMRYb-QQOZEGO.SVK@flex--aliceryhl.bounces.google.com designates 209.85.128.73 as permitted sender) smtp.mailfrom=3x9GtZwkKCGYEPMGIVcLPKSSKPI.GSQPMRYb-QQOZEGO.SVK@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1739444680; a=rsa-sha256; cv=none; b=FmUt1AOmtDpvIM98rH1GOMawHLqPGLDrRTlSMESsvBx4x1AxNNLxbfqFYKF3PFMy7JsONC u4dR0P8rxj3aec7rY6BbQqR1gMScg8Z3thRhGank4juvxaIvJ9JWtwLV20da9FC9VBusI8 fA6GT97ftujC9i/JvXiD7Vsf4isezzY= Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-4394c489babso3973965e9.1 for ; Thu, 13 Feb 2025 03:04:40 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1739444679; x=1740049479; 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=w9c//+puMEPIu02W9GqdsmxdftBKhgzEpRqTvLiOh1g=; b=a+ZqSKrDYhihOR5Lg8G93iJw1UA3YRtvUsafmouhusSr+WrxMuREtyJYVYvzWRg2rr Y3Yh0Z3kbrYnZT0ieWTfL9vs90RLwNPQaK8noKMMXTRlfsgI7R6bPsCGBAgKc6df7UD7 Bh1gTvAWbzPxyD6O4gjgZcWRng1jP4nKB3etPp2vMuVG8JBh369wUhMo+1xVzAq++6BK zPMG1vMiTmYoJ22lmap+J+9q+pZ6Nf3wd9HnpRUesFCMvSylPEHQVF2WtvCmCjtabGxN aweg2os3/eC9QmHIbfs5Iah1jsGHh5KSYd4Wkab+QZ8AKB+FSSsSMUEBmWqSiPisCnND pthw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1739444679; x=1740049479; 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=w9c//+puMEPIu02W9GqdsmxdftBKhgzEpRqTvLiOh1g=; b=PQKV4cqruMzaql+dsdDo5GEpJgY3eGRGmFzBvcX0uxhUVXbATgZZsj0KyDel0OkSZc SZkFU5Sm/Xh7WfmosXc9g7Hy05b5eqPHVF7yxTbQ78TWHUPSGQ4/M9eMLRnB1KEn82fP zV2ZMNlsCy9KFn4FYKnJry0RTUsxaDM+BbDWWA9880lrtvBGzdbYoLYeiSMdZOr4IxjX RIow5x7L4+0wIi5IewFFrP1ZsJFXb0HIcbkbJWL8BduKjnqEXGUnXX242kP9xhn32zK0 VqOyMNEJIDYMWqFBhHMx7/TuqF73BLvVayA2rVy9oFVXmKOXOwlnHhK5EvpGEE88Pvn0 rxeA== X-Forwarded-Encrypted: i=1; AJvYcCXivJbhSkT0NzMUWnyxstLEtkzQeUO9LA2VzlTAOwLRkmZuf0IYjU6MxOVhBeG66794fqG4AqbBuw==@kvack.org X-Gm-Message-State: AOJu0YyiUB845WR4LtyEkVhsVhd7ve0G0c76pyAdLi2p31PrQkEtD0A7 Kbt1StgjMTO0H9BUoP2xLCevaTM7QPynm58HCgleXJvIRB+WMpyprR9NIGKN8PTvDk8vMhRihzB opohuHIy7cI079Q== X-Google-Smtp-Source: AGHT+IHbYFtzmogXBg9MKVnhQ13dP/0PgnaMmx1EqoIKBkmnDNwv9gD8FAc5s4pngUmvqFUXCOowllHdgVlDphw= X-Received: from wmbay19.prod.google.com ([2002:a05:600c:1e13:b0:439:5636:735f]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:46cc:b0:439:54d3:d076 with SMTP id 5b1f17b1804b1-439601694e7mr26033985e9.1.1739444679495; Thu, 13 Feb 2025 03:04:39 -0800 (PST) Date: Thu, 13 Feb 2025 11:04:00 +0000 In-Reply-To: <20250213-vma-v14-0-b29c47ab21f5@google.com> Mime-Version: 1.0 References: <20250213-vma-v14-0-b29c47ab21f5@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=dLD6cHWVgf4Y0Wdnlt3dpV8a6zt+QppcLE+M4FISSKQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnrdG+XF/CRGicj29lFaft2zXQGBxQrOuGoT+gX gCTVXTMW2yJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ63RvgAKCRAEWL7uWMY5 RowED/9wPP/m0yVmu3CtDvLxBZkr/NFB0Ykbc1trzp07J536Dy+CvTd4+mxPHKf7fjYyQ5yOM67 420cGv5bXr9WLCKJAlouRfe5bWz3QrQeT0kRtlomkO4/viLZkkLwSfsmaocEtLFgAIrfZ3nDgFU sYPUKgV3lbeNpk4vVKgea0YwsSOKvH1Kx7sC0p/Yv0TfAbpFAn4MKggcxL0KCP28+zgYn9Bw3hX qFZlZwxn3XNw5lbYN0B1GQWH+vmFl3AJapms3E2pO0ekZkB1PiM56H6PWgvRuc8OkEmVqeWDfpe AQbUuB2ydzSyVu7Xjh+yUCRDp+VxH580NVduHrptwMC1jKjkHrKQB8aaISG5c74kxzOocK5QlRL 9cDzGyIwxfpwczktY7Ks5MnuM2b9F5FfqbnscuSsIqSuciGngIbCDaLTTMRlyuMMini0aQ20PIf vTi7zYUQ6sRQcbiWLiOZakX7PUOAc9ZkdMcc0HegaWwMuyrr62twXCl5ScjEZC1UcRi+AKuV9i9 sUx0YkYqewiFtH8vl5Ti+MDgN/+R70XAxjlNPy4ri51cde1yYBM+QKU0YZgvkN+y1g5g9TPevK6 1vZwENcZYQN87Fxomcqn+JTXGIcpA/B2+47TeuwP4LcOmTzuJqK9C136EQdqGpBJsL3lf0OWQV/ VxK2B9Fk9lXYRFQ== X-Mailer: b4 0.13.0 Message-ID: <20250213-vma-v14-1-b29c47ab21f5@google.com> Subject: [PATCH v14 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-Rspam-User: X-Rspamd-Server: rspam08 X-Rspamd-Queue-Id: C47B81A0008 X-Stat-Signature: rc5f4dbot8ogik9prsapwkinoyjdby9e X-HE-Tag: 1739444680-470061 X-HE-Meta: U2FsdGVkX18SAsnePgqufTVe6Csx6Mq3Sg/DsjPPY3Ao++tKQEf8NhwSGdEeZHfX4CJ6j6f85d+Y/HNPXUE/TyuPlgubGUp8wmf+PadqI8XObNNp4JcALmVI7USNvzSmS7wG1WBP5Nkqtcqu68BgxcTN3t//J4JKZwE0qvywiEX9wJMdgsCF6tf/WGCW5SXKpElNWHkupBwouQpX/FlE2dgR3GRrqJ3r17PIN9w9dQRuUMt3IENuKz2mPxCyCO6pfxjbdrem2KKvKkqnTugS6c0YGQ/j4C9C1lwuXsz2hxM+py9IMNyeEBasEvmzPuCMLFtkVC7i4v09CLtko0avRl+4/PBMfq4AAfBYInpgwn7m6XucTXzfzJLM/Q6wi7Tn9LM9bFdmktNaF8gkYHfcnPPFF9/NzdhVrMI3ebhysH2xJSqCU0d6EmWtk/GBNKHr7y3mfHzCBZ8nZws8D/zRrAj/M3x84sZoKQ77ErqLKlh7v3bZzj4tSF8u88w5CFjqFYlmHf7gib0CBAdESY6UNJJm7aJuPKuCgJofknxJhU0QzL6/4EqYQcQolW4tmjT3lsNuqSEFe/VVKgK+qOpnWg9l8zDXQ24C2cEYZno2bcIrakA8bTyWLOL2nBeR6GniG1qEbn9C8HdVU78n2OVlCayU2kRD8YnNuUGPTNPXHNuPMLQ91yHXm68D3K1MJPch+ZPuxnijWYg4cqe5ZY0hoSAEQ8Moh7V56qhHvrszwGyamTnpNcyewwLEk4SHRiBj3wIe2yrwB5BMZ71EgxxvPM+G4eWsjAZT6QbC0FbiVJlw2+9ENr30HG9WwU0c9S9mmrqImf0MRa7sJx3rDqLUT5pnfG4Y9+ZtpsP2GnbzHZbD6TnaAqdPd9GbEa6dmPHYnUmz2x079KyijXuPEqJGvzVw/XDzsys1rGVPxHhf/S1a+kL7LG3JRr4e5QEUnTRvkz01tQ9kEjQ/gG4soLv WpUZn2iB RFOxvd3KhHYMmBRW6LVd2wKsPWlN//1A5ePugFcXZD9dDEUg35G1U+oeQeSuvx6d2fZbnCJ2eYHWj7eFE2gCgYDm7WGYW49bRqy8qFlBsU+fQ/lycf6xKCSNNFX21S9B7ciktoOy580zMeFd2lkg4vLX1hBsnWXFcV8ZJc3ZQrg/dYqzqIIkMUoDn0kpiTvOYE7BAoMoe1ijUBJQARL3FNXFM+KXQaajQIghb8O3yJiCeIvTspm0TgyUmx7sMtqNzfTceHVMy6m6bdxH+jGL8e2mztKoe0ntDZC3wns2mJBfa89bdu7gBHPSW91AJ6iNc9JSF0S7VwOjIT+zBxtpGiauQORBf0bMxhUASYCPM6C7av9hbNqiFHnvCofx5zAP2GxnpOltfG0j6zrsxJGzO2T7L+XJ+wKrXxbF2jrsuVDDHNC/4Xge0eS/eGYSbPdi5qqLffUXCEYBIqb4hSKryML1BflMY0FRx5vZXYiLdB/2EV8h6snRg+/4PQHl/LDKj10Uw5F91SvrGtB1Tj9Ztl63SZcRWlDYUCOz31jbGDt3bM3VQ9hdwAqQ1x9DTKOHNwq+BsKmYA0MXs1QpFtYVckOZsFWRC0JKvwU7CQVnbLcPF359EE0jMUDYDESyouMNQTagNkvrlIOMym7jOuMFFtxbiQH/WVPU0EgKkE0vaaEn7InUhrNZ2o0/zO+P+KxxshqBSQmgZKdh5SXVOMTsU5qQrIigSs6PY2ACD3yC5xp2Qncu6gA9DKJlP1JTwYVp1QzT X-Bogosity: Ham, tests=bogofilter, spamicity=0.375410, 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 Reviewed-by: Gary Guo --- 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()) }; + } +}