From patchwork Fri Nov 29 16:32:34 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13888842 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 E586AD729E7 for ; Fri, 29 Nov 2024 16:32:58 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 78DFD6B0085; Fri, 29 Nov 2024 11:32:58 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 73E436B008C; Fri, 29 Nov 2024 11:32:58 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5BA006B0092; Fri, 29 Nov 2024 11:32:58 -0500 (EST) 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 3F1186B0085 for ; Fri, 29 Nov 2024 11:32:58 -0500 (EST) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id DBE8F161288 for ; Fri, 29 Nov 2024 16:32:57 +0000 (UTC) X-FDA: 82839676710.28.323A4EE Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) by imf29.hostedemail.com (Postfix) with ESMTP id AAE5D120016 for ; Fri, 29 Nov 2024 16:32:43 +0000 (UTC) Authentication-Results: imf29.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=mv7FhHJw; spf=pass (imf29.hostedemail.com: domain of 3tuxJZwkKCPcZkhbdqxgkfnnfkd.bnlkhmtw-lljuZbj.nqf@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3tuxJZwkKCPcZkhbdqxgkfnnfkd.bnlkhmtw-lljuZbj.nqf@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=1732897969; 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=j9X1mSWROln1wrDBMjuahPQZdYG+tTYafJBbOIpF/U8=; b=NsjBL42Nhnl2qZ+stJY8pGfOagh7W8tIkmAM0Ona5Wifh+5tzqvbwDkLDJWpW/BNWuBPA0 NxsGbXFQf+c2fXssqqptas49z95FUlilFm15ixgA1KBLIgdPrLNf+f4qBA4YCs/cHHIHZ2 vSitWESf6KmWWqfmD2Hgwi1HbitrYWI= ARC-Authentication-Results: i=1; imf29.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=mv7FhHJw; spf=pass (imf29.hostedemail.com: domain of 3tuxJZwkKCPcZkhbdqxgkfnnfkd.bnlkhmtw-lljuZbj.nqf@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3tuxJZwkKCPcZkhbdqxgkfnnfkd.bnlkhmtw-lljuZbj.nqf@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1732897969; a=rsa-sha256; cv=none; b=rSOZnzb5TAMzCmHvRAWmlSWthaclPMLrKPNxbywhmk6PuWKQuUK3FBMUrqJY2oW1Sulk7J uevKlE3OZhW8/UYAjn6ciGRHR8YqF25GH2/1JSpBv8l0aJXm3SK8MNFCimxcCNnIKaL8PP 3EGlYK57ogoThbQuvIdtYg6dHsmQ6nA= Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-434ad71268dso12152605e9.1 for ; Fri, 29 Nov 2024 08:32:55 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897974; x=1733502774; 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=j9X1mSWROln1wrDBMjuahPQZdYG+tTYafJBbOIpF/U8=; b=mv7FhHJwW249MIHVmjkqhpOwq+cMiqS8m7NAx4PG8TX98yAzGA2WIkAimFESSp5ADC NjQL09MnzgMq5Z+5e7xBc1jWyKZA9eSIQdrilaNsJ7mrrvdUwsD7vyn5Qt9C/NkCWJhi uDb+aR5We4yCBC84OO7sPGf8Cy+P8vF4OWQxH2Ygd+QPdq2dDWrw+tlJDT55qi/J4IKg /mN+AWrge05oN5pKHPIUJ5c5UITgM1lWLTmy/nFfsp5KGoNqlS7L0RGCOMWX+fP5Cbp4 TL9ZcpVZwCvkaOeGEFFN+I5x/Lt3RKbFt3AHnmorNBJn/B9wj9KuyVw8Sju2iUyZ5YZk AICw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897974; x=1733502774; 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=j9X1mSWROln1wrDBMjuahPQZdYG+tTYafJBbOIpF/U8=; b=kgEr2jrng1U+f8tQh2Igi0MScKq1yW/mLsX1/7sTCOM3Q4QMTF1BCvEomij2YqFVb5 yWPyxYaxXy95sLNHQjjB2HmgtlyIcY59xa0NynYpUxBGeoIx4EJdSAB9aeWspXfwTOCU zNF+a+NzI0i4J58zBQ81vH3UWqqdIbciaEPw6SYfq1IOnMtH3jssYsTYkvxZIwTuryMs XE7YGX+Tc2vGdYJvWjwnP2vC3p/v4BzlzNNovmtzVTZl37uVHISHdT78l1ii5dX3S9zv +iJQ5OfT+S7PTyGEii+DZNAwXm0QSlzkRyKcsGzzFS7ijVMNzUKIfJeNW8ew93Z7vGpQ coJw== X-Forwarded-Encrypted: i=1; AJvYcCUOT4oLM1jG+eoXYO1lQa4ITBD+Kdh17FpYOsKItE0xrZVKvmhoa1BJMEUY7/OEcn2DgwJ3Kf5QYA==@kvack.org X-Gm-Message-State: AOJu0Yy+RymidbctEDRQZkEoqU0ou6OnV32m1D+UkaiPp1k9PPVVW/lm BUBR/eedelXc+CAVfEik7PXd1XRgymWlMrW8r32SKtBJxJhUkSuZh3HW4aKezwjtHCdIWJadNRC rRUoztYcSv47MKA== X-Google-Smtp-Source: AGHT+IG1Q9DtpcqFchzTEpT4t81tXHCjVZL4m+DlejQopKd4Dv0OkuXm1Htn/deYdYiYHN+thVzGQZM8rcROeaE= X-Received: from wmjy22.prod.google.com ([2002:a7b:cd96:0:b0:434:9322:f580]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3589:b0:434:a4d3:31f0 with SMTP id 5b1f17b1804b1-434afb9533fmr77447825e9.3.1732897974563; Fri, 29 Nov 2024 08:32:54 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:34 +0000 In-Reply-To: <20241129-vma-v10-0-4dfff05ba927@google.com> Mime-Version: 1.0 References: <20241129-vma-v10-0-4dfff05ba927@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=9dPy033+czHjobcXs31YH34rNSge6iKWvSxm8dMkcKg=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeytYAQEEiK6whr+TrOU4N31iHFdV607MGM6c jNKDH8RODmJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nsrQAKCRAEWL7uWMY5 Rl1BD/43K0CD3qubFqV+QMRL/6t3UCee4q4QUSFTTg5qJ7tu57qKFhi+Z5+h/98/rPE11mSQVnv fYVg0nh5ueazDKhTrdTjPqDDeP8J71WHLI2yDJpy9m/DEbtqHQjFi4Ev/ROD3Npv0ASTYYdhJ1Q N+Zdfdftn+jufRt3v3P0n631vzB/nKT+cTYg2is2VYOlthxxbg0z1CtgLpQ3wI1aOt4bgQ+IjC3 rBsVW/lx+D9CBKhMT6z+IZ9eXnCA6WF4Qs6nDe9CrBaKZWwlKxouff8zXtNnIfXntvQFb6Sx4ow v5uwVIjipKvKDEX7X/6URnX7sK93JbXcr63Dx4w3LYt/EcKFPCuECZ22T+HQ2+uznUOxICWI4MD 3RiM7iPMRNEV1h5Fv8JrqJUhpXtHeydK5iUL85qfjSVLeZNQs5OoWRWaCvzCs/Vyeji0aFob9S0 b44YQjzgcZlt71l5KwAz+yijXWgWzwbHXt0Mz0of2EP9WlhHEGH5cVEMGwNdv+lASz+s7hh4+iS aqHdqyjijCQLduXH1+7cDDfUfnepdbF3q9yAQ682CbbGM25oiDhGPY8I1vi+HAhVeHfeL9tEKMK 68mqnN0SeyMqOkYmDQ4deL+V4WAiCfBb/pm7+k/rXYPINeo6hFfAchVChGNWIge2r3lvRLuqPBt Egg70NbRZv5rQ4g== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-1-4dfff05ba927@google.com> Subject: [PATCH v10 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-Queue-Id: AAE5D120016 X-Rspamd-Server: rspam12 X-Stat-Signature: b8h5gr7hkzpwzgrn9zq684n6mmmxwqyh X-Rspam-User: X-HE-Tag: 1732897963-556679 X-HE-Meta: U2FsdGVkX19dPD1fjvnl3fos4ICcoIkvLdoBETrKjW8V/Ul/R2usuahJGUDbjIiybdH4VwSjoRG/DZWp4E1jW5v6Sx9BsqS2SAqYlGBk4EpyfPiBh8kpFjDbms4F6E7pmK2RJ0ihFOiNw2K52mbnpVO68wfK2TpS2Jn+c3DI17BCNJx8kgc7wYNhQOiTrNzd6/U/sa6GVvgUReEK2VtvRERkd6fX2BGP9U0XYbT7qtFUPkBNHaQTMhQ6XqO0ndPjUzWaV0w00eMZrAq/MgGK9+nFs9Avtc2PPm/BlgbwQa4PxAujOOBiSb02WvuxXpWFqsVwV+9i/yt+Dze2wOo5H5fjSCLKmSR8uA/tNI+UWX3s0dqva7nbGeoxwxoB51SUzD/afIQVJ4d4fnUIOY6DaHeJjyfiMLWtlymF1USSiTug+u+gJ5A6/jrrNikFH2iLBF8QR44w9r3ErHCHepG4pL76As/KRubsjgdlW5SNPw3nvk9Mp/v7ut6hNFa5Y98rOPbGfbkVsNdtiBWwTzJSQdQsz9o06bRzmRVLu7mcpRamdMwtMqwubNJJJLt6Kg8MO0bI37zKcWDKD/Q1YPhot6uhoISpQM6lEcjt4nBA9DN6oCWTFUt093NYbJIrCX5oLBp3uEFYNdF6rN/39WV9hSiYR77XTgIGluDoNHQ7fSAewLZEShbGDa+Ly+mex/U3nhpxi6qeCzHCUDbofuywEIUdcFCGbt964Z/NvafElCZsQdBlPK1oYcsjqx+6g21Sr9OPQytkcRG9KWZTNmM2tT1Bo5irxIZfPFOA6oIi8URlxhPMLy6ntDzqRN4Tn/O4hf6W1ljdM9QcrjN89dBZGtSccHggWFJaQQjpj0z/6ZiB1HuYo+alI+Bva6vK++7u6C6ZKrZ8bBz4QpW5x8wHpjjhZpXsCjv8I3OSs/zVmzM5N3ycqWlL5o0xUKaJLztR8PGpg3Syz+sTlzdfNyC 26h31n03 kvmf9rJavFhLZ6ZS7rQt/Tmuss2VINMdjGdwibt7bulsQQCA5c2BNtZprJ6luDJIRlSifTVNmkks8FOsQC3rTmYDj+oTxEk6YpXq+P5qBfAAR0Fpk1fEGhuzbu7yRYxXf5VVuwC4Ami8MOd/Uzfra5qdY/7YYM1kPl8Q9znxT1SVJERnr8+j6nJDHb6iPH8lAudoPh6JdaU/CxFbATvSw8yUgiKvMiX44ZbzLX71TNhd7WJMurzIRu0t9PoSjp1pxUVgaPXOER8FpaZMV05Cq3GE6djdHjSztV9XqANSbQ5/MMs3Ov4uwfAXpy4FqOvSnjKISNCnL2QTz3pBHvYhlQIRTMb9/XgVZfQQTfEiR6eFAmjrGKM3m131rt2bJh7JH7cmSwhKlcdnCNuytPj8LtY7e1q4QvkYCWj315JR+TNR7ad9S7ktekFOe6obAopsql+1abJSG9fSup3ILJK2oeceBhWfvYn8HMEOtkpjoxd1aJk6fbQzi5F5z9BmJ8hon2MgW3qHr6BTqrHKP6GB5hjIBUB21Epzj0ty8DxZ9kjOgNeO9s4tkkM3RclMFJ/KT3fkDDbx7vii/ATrcoi6hHpg9t3DlMkr3IijPMuJM8nZqvytcS/97xED0VifG2O4e/Bom32tuOSLWcAntla/z71EvkQfwwSmAsQBZmeqaBGX0ALQb2A+L0L8GrhnDa6G+U2ACtscq1KX5pNw= 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. 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()) }; + } +}