From patchwork Tue Apr 8 09:22:38 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 14042480 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 32318C369A4 for ; Tue, 8 Apr 2025 09:24:05 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 9894D6B0008; Tue, 8 Apr 2025 05:24:03 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 95FD86B000A; Tue, 8 Apr 2025 05:24:03 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7DAB66B000C; Tue, 8 Apr 2025 05:24:03 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0012.hostedemail.com [216.40.44.12]) by kanga.kvack.org (Postfix) with ESMTP id 5B70E6B0008 for ; Tue, 8 Apr 2025 05:24:03 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 27BB8160985 for ; Tue, 8 Apr 2025 09:24:04 +0000 (UTC) X-FDA: 83310340008.03.D2DEC8B Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) by imf25.hostedemail.com (Postfix) with ESMTP id 2C5C0A000C for ; Tue, 8 Apr 2025 09:24:01 +0000 (UTC) Authentication-Results: imf25.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=fvP7kzoz; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf25.hostedemail.com: domain of 3MOv0ZwkKCCE7IF9BOVEIDLLDIB.9LJIFKRU-JJHS79H.LOD@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3MOv0ZwkKCCE7IF9BOVEIDLLDIB.9LJIFKRU-JJHS79H.LOD@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1744104242; 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=ki4H2x3bNdUZgaxD5TSjlFdpv0BBNOUt/zA8zBiktxo=; b=hGW+EXjo6vu2Tpy60Xs19FKCmR/dKkJEm/0WAOo4dGfENIRDJEgh3O+sy6mgTzwi1V84vO JpgmcwpuFfHT6NkFTnCh4R5LZ4TBVo2dz/Hy3lfX0rhMD1KQvcUsQc2mu45VenLeZ1pKfy qTKG99OHaBUJ/6xvG3IH9TS2wG5LdVI= ARC-Authentication-Results: i=1; imf25.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=fvP7kzoz; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf25.hostedemail.com: domain of 3MOv0ZwkKCCE7IF9BOVEIDLLDIB.9LJIFKRU-JJHS79H.LOD@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3MOv0ZwkKCCE7IF9BOVEIDLLDIB.9LJIFKRU-JJHS79H.LOD@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1744104242; a=rsa-sha256; cv=none; b=f1qkLem0KELwBuHvquv7FUwSMeknBRtGMJd25Dnet+o0GO1sK7gxsscN1eG7TkfLqguuJQ K2do5O/4+FQRNCh3Y0hYap6TQYUpvDHYUAnQZsD1nrODrTHyA+NIGt1EUFR7Lnnx5+PjPA BB9Z9iPnFb6vT6mfBF1+7v9zRKxvhWA= Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43ceb011ea5so35603855e9.2 for ; Tue, 08 Apr 2025 02:24:01 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1744104240; x=1744709040; 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=ki4H2x3bNdUZgaxD5TSjlFdpv0BBNOUt/zA8zBiktxo=; b=fvP7kzozSgM1aU7l25qfID5a1ZbGHxVp6+eI8v6LF9nJBF/jNxAgn1+Wq2p0B/2Hjk +YOqWIth6Ze9+8D8Ivt07Np/NAdR6aJx4S52teCJfgerSh0nJwLCz2dt80SdP/cvJbp6 Gm7jgy6qJwTsGhBTT0rUnAPxiMrmzcNjh9wHNN2lFzIONqudXaaPcS8QFVoo3fci2Ibt NhcpkoVZz+JTZuMJLLPQgHC4D8zq+VJPpEI6s8u++vKXzZc9sAhDRjkmugGqzatwLPXj tOM01uzkjLLrVYVFUEYGlsaXLObCb7zcC7NNtJspVoqSFiNLx7+jEsfXJUcyK3Z/Dcv1 tQVQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744104240; x=1744709040; 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=ki4H2x3bNdUZgaxD5TSjlFdpv0BBNOUt/zA8zBiktxo=; b=wwnXdXIuA+X8DousXhb4bLq7ZBu/hjnPzy26WE9djzr7da9EIQLGe2eK1YVEp/MKsM 6bTKKALLfuqA9T0L/155z+vpPhqsiZ5R9SDvNSUK/l84vsvtMBD7JKMREpiKDrolf5qp UjpxEuqFfNTsfOTUh62H1vwD5vzxQJXx8NnZciJjjZvV2LH/e3GI8pl0XxBxjX1uB1eV o6R1+p61PcVMszIap6jtki5bZQfEG7jaw2/fVhu9CNiNev8aO6ss2iTyH7k0V6DqBEyF j3ES6iiIuXraKhNWtyhLMLFpVO3u06LsPAFrBQnOVuFK1sXSwY3Ld/bMAsEZKhsIwUU8 bp7g== X-Forwarded-Encrypted: i=1; AJvYcCUQqx5q3u6LEvkscu+Zyxov/c5D9NNgbQWPAtK14CPTiMN3GdelyPhg8Pebl0rP+5SVqBlG83J+GQ==@kvack.org X-Gm-Message-State: AOJu0Yw8BJL2havhcDoPRz327x0ZCrLid0s3RHeqIpg1myJPIcsLRLBh 024n6LQz46Tk8NjcfUcASIBYpBS06B77ag95Yh6IT/l1uoVz+LWmqdSOelPe/yp0oA4p2Q0mXRj 2Y13fAwLN6BsugQ== X-Google-Smtp-Source: AGHT+IHYfn2jFMPzZbozv1znd+quFlDYUIdmNio1DMNMO7NMjqNG77qP6RfgBjCyxquhSAqEKulRpzj7mSohx+c= X-Received: from wmbh6.prod.google.com ([2002:a05:600c:a106:b0:43d:9035:df36]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1385:b0:43d:46de:b0eb with SMTP id 5b1f17b1804b1-43ecf85f4e8mr141716885e9.12.1744104240706; Tue, 08 Apr 2025 02:24:00 -0700 (PDT) Date: Tue, 08 Apr 2025 09:22:38 +0000 In-Reply-To: <20250408-vma-v16-0-d8b446e885d9@google.com> Mime-Version: 1.0 References: <20250408-vma-v16-0-d8b446e885d9@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=10913; i=aliceryhl@google.com; h=from:subject:message-id; bh=yxKBHgKEF0Pk92dXT07hzBYbzkqnu7N3MQCAKHqDQNA=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBn9OslaWj4W4zK8+NCEygrsxAUbocMAkAmSrImM xsssH4ZEoaJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ/TrJQAKCRAEWL7uWMY5 Rg9WEAC11iTd6isdQt5qWtvteId/5hP34edfgj8zeH/4CCCW00Sw4HXzTdwHcAegqA1muaKjn0f J9g0wzBZm1fKyRsYLajYxd5Z59jJLlnRrAE5QfbCH90AXUJdc6FftYwB/Jg/JubN3dPNeUYGScU 3ISw9I3xEMA11Px/O+Ai4VVQhN5aR6M44VEyeWxjUgIN2aj7S1pfgnhM+AfmSU2HAYhOHnIqqGe /sVoQtjoOWcfn4/4+Ghg4n5I9Fa3BB6UMd65UaRMBOm9sOzKe3pPw3zybomx1Pb48m/cr1jsJuC SF2dgkMwbO6tvcB5B9exQAD2f2mXfABlxB5KQMzrm9yUaNVYyYEeVU9bluKJIZpPgA/mXkL3NLu 2r0p7NITtj68BUpmG84+W+baaOb30suihSe42mN7lZ88HnlMBmjdk8X8wbt9hvqd5FuG+kYUmiO JJIXTk8EEz7zJ5QD8ZeS+M9vxo7Ut7u5dh9ysXcliHRqMkXioNnPn90W1qvICxl+Tmpz9ENOlwG khFeLyAnteQfbc1E2BSvhXJxziluA8Mq8jwVSWB8/EI7d/h2/a7AiIZJrV6DuwFBUVNaThNUegs A7dNpcPApjwoUJCn2UaYGBgaP3qBi8wES2xeBK2IpYNgpUA9i2MojX3EhyzyigwWiEoWdI7h5kx Ga+MA9pPHmxkk9w== X-Mailer: b4 0.14.2 Message-ID: <20250408-vma-v16-1-d8b446e885d9@google.com> Subject: [PATCH v16 1/9] 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-Server: rspam11 X-Rspamd-Queue-Id: 2C5C0A000C X-Stat-Signature: p8die7gi3azqxxqqsn6zzdutuhptfrbz X-Rspam-User: X-HE-Tag: 1744104241-325841 X-HE-Meta: U2FsdGVkX1+B2iZ80NYYd2Mkuxgbduu7fX4h9xBgM3ksR6ALlBA/nri8JogJb498tZPwx0oGFjAfUHJtDamQk1n9GGKiiK8vTXAKD9C35myTGoNmOUhAyOczJJCyU7qOTumLxW3up3eix67p2VIpNvLIdnHrU3bZxzIu9cEuE30sgiZZVHFayjss5j9yJDMiDxh9UcGPxzfTLz4GvP+nZ3xoD9V7LZEEMPf5DVQyZ5IlZ25K0MyvDGwKlVWBEmG2Y2bbtvkMGy8PB6SEn4pwa/euCZ+IRERnYHY/CeBIteUAOY5NVfcmWdwmUc6z0Xs57e1aX7Ubh2eIHNTGiihH6kXurDFQSGhiMBQ6eFqBFfCMxv+1u55lm1IbiDhQrqrLrpTjcw8iUVx8yt7ETuah6xSeIHNrBsuDJ3a9izS8tCuovn8D9D5aWHhHalrfBPHvIR3xmU8hSrALdx+4eTOnXTKghzz4pjdrA/BrvJzhf8tWhkAHz451n5kNI2CSP2mWMrtjPrLB448fU3rU65uOEHOhKYVR02dvt9Nojf9Llwf5f3Ns3S+f6EjSr0ODvBL/YP1hhd1sgXMRC9qHlpREYPychjGjkT05N90SfI4ZbbM8E56QU8kX0FbcO/KLj3yygUt1rN0HronpZYxQlJ+r+uChpann9ZDWF36gWE1hdBjR6LXtwKYeAezZ4YiS9TeYxzQjto+bEZtu1QeaMVaTT3DCbudSBSlqgtJTRQlqdj3z3ukXCorgZ+NOou4kHs5tTFXUFsP4cGXpiBXAKXU9UCRXqVo3GvFDobxCT+Uta8vvTHFeY4RW9QHg8ySfhTzn/dObRJsONrwN4F83cvZ16Swu3Xpi3WXRdh2bw5y5OhL63YqIj9OsLJdtbr7pv4pYJiClp7Urw0OU+CU2q3SmfKUoj77ywpR+9vFzFYmy2VerW5gVEXVR98Pq2uspkj2v0KLLhwLPo0+vMRvURC1 B+rwL3f/ o4lST6V/23bS5nrj83m/rEfZRZS3Rh+5Mb8NEkl+SYXjw58PTf0KyV2ChXWTjxPjTqCoky7XPLF3UlvLvUoeXVKxj6vrKwQgZIS2vzOs4MdRmUnxANAFKBsn5mTSRQOlT2rqnMJYlRbjy/DlmJ45J0AKnz30wx/kt2D3XOn7TVpaJuD5Ogu61kvd03NegnnIWeuhvDN40/zL/J2JweraJeXvhQExSQzpqFiwvt5yxCnYNFkf70koECynU3mTig+M0oTwtqi60u+/YUUhK1AhQ+jpPR/VZPpqP5TRpVIhBi0qo+krciPlp6i83FcYUypH0VohkfNKcW5jW7/bZC0ici8gpD7nqTZmS2HHwIQwHQWtAb/H64adUoWn2tm7pLZX4zPMAWuFSX5e6bAgS7F0BA0OyuFTqiVG3gtr94QBpJFj7aQjNKKhIZn8w/LfgdCZD8aPonMNzx/thBFEhQyAWMBsSbRJUVgNdBImSW9BV1sUsIbYcmgbq9E8MvJhSbh+hz1Zmk/JmEV/BLmDZZEUO0001fXpkLqu5qVc798li//tdnuk6FEbvNVRvEdNvNijQ0b18S+tvs1whnspDc+VwkgHKRudinhPHbOJGblwwsgcIhao/C7xKdcCehMEZ4mYznQ7P5eZ7p7OIi9/FBBU3DfgiQIoyZOXUX90aI9IBbB3+bHOsq1U7jSvRNx0//z0KtnjrZGScye74nmfLlMd83mbDFSIk68QmbzLLDDsNNhqWdAsZGeQBIhohumuPG9iAaJald/PtV/5BCyJi6Lc9ImwKrk43oqARLPjF1gdgoQax+mXx+VdeobfO2eulBI4Ffgj2JatudoyVcus= X-Bogosity: Ham, tests=bogofilter, spamicity=0.117842, 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. The mm module is defined to only exist when CONFIG_MMU is set. This avoids various errors due to missing types and functions when CONFIG_MMU is disabled. More fine-grained cfgs can be considered in the future. See the thread at [1] for more info. Acked-by: Lorenzo Stoakes Acked-by: Liam R. Howlett Acked-by: Balbir Singh Reviewed-by: Andreas Hindborg Reviewed-by: Gary Guo Link: https://lore.kernel.org/all/202503091916.QousmtcY-lkp@intel.com/ Signed-off-by: Alice Ryhl --- rust/helpers/helpers.c | 1 + rust/helpers/mm.c | 39 +++++++++ rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 210 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 251 insertions(+) diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index e1c21eba9b15b672c5e4ab10c4e4c01ed407fae6..48b80bbc0645b2f4abc2b8e28972b0550b5abfea 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -19,6 +19,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 0000000000000000000000000000000000000000..7201747a5d314b2b120b30c0b906715c04ca77a5 --- /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 de07aadd1ff5fe46fd89517e234b97a6590c8e93..42ab6cf4053f2cadff0a512b8645699bfa6ec568 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -61,6 +61,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 0000000000000000000000000000000000000000..eda7a479cff7e79760bb49eb4bb16209bbfc6147 --- /dev/null +++ b/rust/kernel/mm.rs @@ -0,0 +1,210 @@ +// 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) +#![cfg(CONFIG_MMU)] + +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()) }; + } +}