From mboxrd@z Thu Jan 1 00:00:00 1970 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 40CCDC282D3 for ; Tue, 4 Mar 2025 11:51:45 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id C9C996B0088; Tue, 4 Mar 2025 06:51:44 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id C2647280001; Tue, 4 Mar 2025 06:51:44 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id A82A16B008A; Tue, 4 Mar 2025 06:51:44 -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 82A2A6B0088 for ; Tue, 4 Mar 2025 06:51:44 -0500 (EST) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 31187B0EF8 for ; Tue, 4 Mar 2025 11:51:44 +0000 (UTC) X-FDA: 83183704128.03.A00513E Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) by imf29.hostedemail.com (Postfix) with ESMTP id 3094D12000C for ; Tue, 4 Mar 2025 11:51:41 +0000 (UTC) Authentication-Results: imf29.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=Fu5Av0tb; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf29.hostedemail.com: domain of 3TOnGZwkKCH8dolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3TOnGZwkKCH8dolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1741089102; 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=rtpRIxx42872somy5qq2iJF3BQOMcuJJhy/hljffTA4=; b=HQFVUy4qJ8/WjND5gpJIaknHvsPt9H+OvUOBVSUjOmx0Y+UAkRMzcd1FXS3FPviK5PojCK q8xtuAcDmqBcy7artDQ/+bSNBksAHIapaHapBxI1EKwXTxB5PKOonoP/eo/evsHqlm1P4w Ss0jWmdW1pHyEIfNlZhcVMvX/E8IBKM= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1741089102; a=rsa-sha256; cv=none; b=f8GWMJ1SqzB9YFXdLQvCE/rteK/l3/hu8N5qLG2ni+GfKrJuMyCB1RnKIV5vGVwL3UsV+D mXbvtQPWLtg+ruSm2WzVevMn71q7QCrJ2thZU86sJeeQB3crRB/d7V3k7cfLUB1dVnvKWe up9M2gTfe4cJYu4GlaKtTas+p1CERkc= ARC-Authentication-Results: i=1; imf29.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=Fu5Av0tb; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf29.hostedemail.com: domain of 3TOnGZwkKCH8dolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3TOnGZwkKCH8dolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-4398ed35b10so25531335e9.1 for ; Tue, 04 Mar 2025 03:51:41 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1741089101; x=1741693901; 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=rtpRIxx42872somy5qq2iJF3BQOMcuJJhy/hljffTA4=; b=Fu5Av0tbuB/OJ8sjQ1OB163H6jqonm/n/HSuX8o3o2sOjhf+2lnBlo/VbEZ3yMXtdh EAjZu61ZhirryFaJOdqylxM4qUp0q19qChzA3BHv3Lr6YwgPEdMPbK9LEZyTSqbID4/H CAUTLiJAnE1iFz8nbQAAcnWYagQsIWsZuzhDaczoYpjoIXUB9MNwFfe6FQey/YkWDpX4 vzC2fPcYUKFXe7fG+aZDafXHl8KlvbSzTfRnuPb0djIzFtHaAZUrYreHRLiNWKFqklZS /LtJoAxSP/yxzLmI1957Dyu2SRt3O7rJgBea7BQmQqu6x6CEhSrMOb3XYwJpTq7KMAZ+ zb6Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1741089101; x=1741693901; 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=rtpRIxx42872somy5qq2iJF3BQOMcuJJhy/hljffTA4=; b=dU0Y1bhLHCLS50eAXKDb443tx53ggMt5RXOARYq/1xXUN4VB/fNAEdyXwJk+jNRDb0 kaQQTBjhKLvOSGECtRKFOrQnCzeZQzKvN0KWyI1pkB7LYEwSD8+I2K8CP+zJjCs4/8gC 3+JMgyomNvlpVpmR6DG0+UGjAp7ZimCphjzHZfttggUsCa+aNvPJ8mfVSkVHuNKOh0ub 9F8hiU4+NnNCEVoTZoAs9rU9VkYPKidB00Gvtdw/Y92/RxchGlHfRXpNbpTV9Sr4CG6n Cx2F3n3vpLrKy2IdkifyDJ/glVO497I1OoJomEQ+Ujf3f6717y7lNtD0/GzdB01H5QjI z6Bg== X-Forwarded-Encrypted: i=1; AJvYcCXt8py1RNC1ixPOyLIZJDMHdy+MYdR2CfI6P8d3Ty5AFOonRlxqpr/SH4QzOul+4g4VBKskSmdV6A==@kvack.org X-Gm-Message-State: AOJu0Yzk4ALWK5JAeXf7xbNAKC9m5wgXYbxgb8ruMTPNXVvLgkOvesd7 nDZk/4/tFj5sbZSQdAsxyAEK++vlPlp0GLNHjyTwPDg+Pq5JlIqtuSZ+bGaOsGTvAuaw7nrk/9/ LFs+krO5nJ9QfaQ== X-Google-Smtp-Source: AGHT+IHlUF2Y1FCXfZXQcZcMyFwY5URSZ23cxaBgnZhVnZxZTqV97wv1ql//rGPCHGKdrPhgQEJhXp8AASDto4k= X-Received: from wmqd21.prod.google.com ([2002:a05:600c:34d5:b0:43b:be5c:fa60]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:2292:b0:43b:c0fa:f9ce with SMTP id 5b1f17b1804b1-43bc0fafff1mr60163805e9.14.1741089100845; Tue, 04 Mar 2025 03:51:40 -0800 (PST) Date: Tue, 04 Mar 2025 11:49:52 +0000 In-Reply-To: <20250304-vma-v15-0-5c641b31980a@google.com> Mime-Version: 1.0 References: <20250304-vma-v15-0-5c641b31980a@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=10566; i=aliceryhl@google.com; h=from:subject:message-id; bh=5g1f5dMZCyZ6+tFXqiaiFdfk/BOnjeMVoZy7cJs1yY4=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnxulCVzX3HsDZPl7M5T70FyzmQ2tx0HLT9aAtg e19ypLVE4mJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ8bpQgAKCRAEWL7uWMY5 Rm8VD/9tH5QNHgdGrbVG2V3uDy0kANpOyxihVNhtOmvDHngryy9HuUJFTng9Z2BkA6E+NChBY2s 53lkwzW7kfsuQWQ0oMerGsObvacknou1rcCpHLLIsly36iRs25U3Vz84fBd+U+StUuhg8Uk6+h5 1h/EZ6/sSF1eG0m0w2yiax2yj/HTINsEC25+TuBhRDMkZHmKtS7SO5yut+x5ZzI6M5zZgtT47Wf VOUDxz+L5terinAvPshZjyz1kMs/zfN5b3iFLGQFYFLqwzZmU3RP4CuMIu+ZSyTTszoChwxpUcX MY8VSh+wGZ2Uer6PIiD4ONDNo1DEGBQyO0vfKpm4ontRarGl+GTbd+mrOLD7xTr8GyLppbYtSfE pnqJxNQUJUuFPz/8amz4qBZeiDdYWpAjTp4X8mEte3TACM+EbMMjmdltvEsx/13fspJnQO0g7kl P9Xv8AgHft/YyL5EBWP8wYaW8Eaz0QE/Rdj8AeNhcJ+85IJu2CGXH8EhZG6kvnO9rVKxknmmDbU KYyYTcGHF0skUIscUs2Y7LLczzoWmKJ+dq04JGDzErOW/xzN/EwOpH8In6N9MAP0QBVOwdk3wuk XobJIiA4tfsuqwNpEY9KLYikZMw1Av6FccBk4FrXRiEJXUX4HAU3xqllzbE96TKvncjNAljfmd4 CQf93I0YNg5Zjzw== X-Mailer: b4 0.14.2 Message-ID: <20250304-vma-v15-1-5c641b31980a@google.com> Subject: [PATCH v15 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 , Linus Torvalds , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Balbir Singh Content-Type: text/plain; charset="utf-8" X-Rspam-User: X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 3094D12000C X-Stat-Signature: 558g9opjbxyysn4y81cyh1ogeb44u4g8 X-HE-Tag: 1741089101-422222 X-HE-Meta: U2FsdGVkX19ekZdTC8IXHGlWRlrECNO4KpNfaK7lmpxO6KQAziDfS3R2UACgxbWKsIp8grUFvgzoOHhptSgiXpXOf0AbYS3cTVfiRXNTy1Mn3QcSrrQoblQGF3NC15z+NVd755IKPf+AGWCn5wTPDOxpA0OiDXkT8QRK71MXfI06w5CeF2kA/hdAW4JbBL7gccdq42yz0qKxhoVeWIyqPEC8om2kskusjbfFqxohV295SRjn4G/+x1Ytu/wLfDS+jIVzjQ5YMQVj+pNwTKKvTYxQ+k+bWpNUURx+PFJKyR/iG72D/o2gdp0uViFSVrGTR+KHipb0gGt7AgNipgtJMoAEWlOyeN+CkcO9w3+j30a4gvlvwoZKK3q722o09aYv1meeZL7lpS9AkCsSpeD6IYAbeg2K8A+FAFHkOIgsGSbVhrQfFAZ66j/39DD5WNTU2u1FjHXwrZScgIEZdq64uGsFL/DpfSlq5x65srsfx7EpsrjVOGs8dRc0ZHA4v51mp3DxTUGp4Gx71D+DuzCx5qVFMAklUgmpIjH2jneVPvK9CFCzENApV8NtvwuY28Hs700AU8zAAdJoO0FFpkROqGRHxV98loGJrBVNzEbpfZQez8RFzrOK/WbuayC+0qtpKPRgWF0TH+m5FvhESp4H9RkKAEGPBFtJAaIc2aSHWXVdbfbduoYBSKNkpEhS9QFTqc31B2FmzPqwZ6XM6OAfx9/VCLQzylmQeWzN8I+W1jpw0GmvTc1bE7VfoDNgmDfHR6t8/2mmyNqE7qaRLQ/fsmw/BYdsaUDKnaFxbIlsy3a3HeSyuvJLTyjfSrqfJswal0EIkiSZ+KaWyE2eaKXel7QIlt4BHo5qsRRh++KR7ZT8/dgV+KgeQ8Elhw0/ldeRhtkBNGHLYur3nPrUAmmAmE9UqS9kFbX4kGM35YJSS/A/Wqs8qtV1X/nI5m2XzJGHSk0H72QDRJZ/z74ohYo vsjPO/dy zpk20vC3pZTJfhHH9HbLhgp+WDYamCUiiQjvEjxLb2yqvUIlaG31JmI/eEaUhy//05FxvujTENgYO3dXdr5uwiaxsyfeLNtPnBIQdO0cV0wPyGvgDG9xSdtZ0NXXc6Xjz4yh/eHB72IsudcZ1RkJMw8P0Rdy+ZuRbU58ZXbRqENLYA0WLlnUlIQDnuaRQNtpqOaFfBaUI/VUH5mkGX3PAhGPwybNLZoZUgPI1AWMq/hoJ951gBxC/tlfrBX0JMt30OJNjrNuuj7CtPcJIWDgmDtYtRxonZ4bmtRjlttmgTG9JQYZmd3h1niPgerkbBsSqooel4e6xYECkhiyHc2zN2ddjezey23p1cfTImIXtOVhJen7I7A3/EMumHXhCXTuqIpXxHyq2FwhbbgCxi5AvHQEzBSsoqwiuOm5vd0xtkk6ZC+oqJixrIa3t2wx6tQxOiyXP4gsXtVkg7uADAotRmfpw4Wvzbp4sLx/cRKiH3ejk5v8o3UBUb01x5W0qd8XsXFD9Tsgreoz1aFsYo9qPUymhRuFBYgOHgUVh6vLlEeCcVsQDdFktXTHuqpDCh/0FugX7oCNDW6bnddAlYNXaUkBJPyoiGBivxSlIDMznquWWFYMCEx8qAwTZyrz68ZaZ/S0DKOPSLywV4/CKgmqIZohoSmTdvVA3RL+VrivHwsYB1FnizjiGwJ3W7lWPccC2g3EoXdcap4cht9tu/+au1Mq2QYa4GJaDrPkfAKGBvoz/ciPe/UWSJqoFCKiIBW33uF60eO4mzhX0ZZWWzLB6Z7Z9ZlYPEQbGq/NfxcITSTuibBdWNsTtW379Nw== X-Bogosity: Ham, tests=bogofilter, spamicity=0.329234, 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: Liam R. Howlett Acked-by: Balbir Singh Reviewed-by: Andreas Hindborg Reviewed-by: Gary Guo 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 0640b7e115be1553549312dcfdf842bcae3bde1b..97cfc2d29f5ee0441a5938eb6b39c51dfa337cb4 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 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 496ed32b0911a9fdbce5d26738b9cf7ef910b269..9cf35fbff356d2b12a104dbf0ecda96c168b185f 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 0000000000000000000000000000000000000000..2fb5f440af602cc9a89a040edaee60d88d54168b --- /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()) }; + } +} -- 2.48.1.711.g2feabab25a-goog