From patchwork Tue Jul 23 14:32:03 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13740129 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 9CF4BC3DA49 for ; Tue, 23 Jul 2024 14:32:50 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E6DC66B00A9; Tue, 23 Jul 2024 10:32:49 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E1D626B00AA; Tue, 23 Jul 2024 10:32:49 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CBDB56B00AB; Tue, 23 Jul 2024 10:32:49 -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 A9EA86B00A9 for ; Tue, 23 Jul 2024 10:32:49 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 50FDC12018C for ; Tue, 23 Jul 2024 14:32:49 +0000 (UTC) X-FDA: 82371258858.16.27CE631 Received: from mail-yw1-f202.google.com (mail-yw1-f202.google.com [209.85.128.202]) by imf30.hostedemail.com (Postfix) with ESMTP id 6F39F80003 for ; Tue, 23 Jul 2024 14:32:46 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=PJTSNetT; spf=pass (imf30.hostedemail.com: domain of 3Db-fZgkKCEYitqkmz6ptowwotm.kwutqv25-uus3iks.wzo@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3Db-fZgkKCEYitqkmz6ptowwotm.kwutqv25-uus3iks.wzo@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=1721745143; 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: references:dkim-signature; bh=ne+E73cZIzdvC8HBsh9ZATcEqVNqX+vKMAYiS15qNLM=; b=IPtWQGAVK6k1GN2e7BU2qf1kZKbHZO2hZ5ti0z+tgC9rO6kmdq9+vv/lwtMRm8uJ0XNw9u lG5Ej3mLE6oaa3XYOsrQAjUj5GctC67O5KVxZAZJhg7Djoo4pagIovGvCx0MB09aGMrAjQ tuQGFdqjzHBszA9mhZ+9JL9kXBO0cLg= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=PJTSNetT; spf=pass (imf30.hostedemail.com: domain of 3Db-fZgkKCEYitqkmz6ptowwotm.kwutqv25-uus3iks.wzo@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3Db-fZgkKCEYitqkmz6ptowwotm.kwutqv25-uus3iks.wzo@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721745143; a=rsa-sha256; cv=none; b=rkg+e5+sxdS8rb+IjO8WemS+4yF3B1vMyGd/ASwVx0SXYsEvilnrLsE5TKhWXpiTcqwOAp srriOROvoO0IXlhTTR1OkN4ItHsUnlY3hKrfINt5kt1xGPkJ2+GthbiRBHrQtTkcuSexbo EAIc6iI3DT6u42ZM5UIUB5yaQvGidfw= Received: by mail-yw1-f202.google.com with SMTP id 00721157ae682-6648363b329so126805987b3.3 for ; Tue, 23 Jul 2024 07:32:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1721745165; x=1722349965; darn=kvack.org; h=cc:to:from:subject:message-id:mime-version:date:from:to:cc:subject :date:message-id:reply-to; bh=ne+E73cZIzdvC8HBsh9ZATcEqVNqX+vKMAYiS15qNLM=; b=PJTSNetTWhE3WsAyRywE3K9QmRTHb+/MihfpSQnt7h4/DtURUAvTTtYeYTA3hyjqDa JSibniB04syhPaVHv03cLQ4eCxy9qeKpWW5XHmSqgv7LTQKpHOCjUaJMo60bLbVa5IOf 2X7PXf5suw201XIK4wlr8ijKqlq6b9OF9kKB0A+Mshdd81KZqdb5yCjcalLpBfk91AxT mPVWof+Bkb2zjLTtkj7QBHguejALpq5xXUf/djAKnwf47FPbSS+rz0Kf53iaPp4N/eB3 wlSQKVAc/WjRv/Udu0I7CWEb7U4lSXIAIhbplw8U1kRzL35SY95n1KhGffjtn0HQAtEP OE9Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1721745165; x=1722349965; h=cc:to:from:subject:message-id:mime-version:date:x-gm-message-state :from:to:cc:subject:date:message-id:reply-to; bh=ne+E73cZIzdvC8HBsh9ZATcEqVNqX+vKMAYiS15qNLM=; b=MMHOCcTTB2uHOHsL0PRVrRPUEfpIARAK3SXYsqJAprN+q5RCKsRDqb5oNT+a23i7f4 MbkohP2Et8MCIEwIwafbLIF8YxybpSqgHHxOLPeI18v8qeNHbORVRzAO8ub3EkqjTi7b 8ydqsLgXG3O13jLRekiMtEqzhAbnENisAVRm2R+AgeLdeUeoWmx+8ysf7LSnKWMZidNC fDcfMNPLBXcBdKlws4ZMVmKQA2TnqakKn8PLlxSBRqVmCWfEw02VIMLoggdCqJFt8GOq HUoUCBkGfYuN90gDFIhmRewufUcY0GRZsIBpBVXo2DvVjw/JT3PhRClPWJYqHf/QB7zH TBKw== X-Forwarded-Encrypted: i=1; AJvYcCUN71mboVnMSAykRZR+gtTjihEPi6cthnYGdirqohwhQtGDtgOB2grn22w1BgCuyKTb7y+UYiTj45oUFOFKdn9WRak= X-Gm-Message-State: AOJu0YxR7gNWvLXFVnhWd2x+/bMEKJrb7KbgKXXMc2zSxft2CZsMUVCt izxj5PtDi+2jM6qkpz25RtwxZYHUUfBPO8+C2fqVuSBxxRVgOtU5I3XEWEFwLQbJ5md6Yjrxfbr hQQ8s71vRTB8T8Q== X-Google-Smtp-Source: AGHT+IHF5oVe92DsOypN0Y3BRqaU4NL6Eq3k2j9G0cH/aBV5sEtuLVZdC2lflxuxzsrHysGc+yG3LOwnKp1BVkY= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:690c:17:b0:62c:de05:5a78 with SMTP id 00721157ae682-66e4daea1fbmr1425317b3.6.1721745165115; Tue, 23 Jul 2024 07:32:45 -0700 (PDT) Date: Tue, 23 Jul 2024 14:32:03 +0000 Mime-Version: 1.0 X-B4-Tracking: v=1; b=H4sIAOK+n2YC/6tWKk4tykwtVrJSqFYqSi3LLM7MzwNyDHUUlJIzE vPSU3UzU4B8JSMDIxMDcyNj3bLcRN00CwNDQ8s0y7QkY1MloMqCotS0zAqwKdGxtbUAvnBzolU AAAA= X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=18847; i=aliceryhl@google.com; h=from:subject:message-id; bh=rhM49Jf+oB5vxe3ACPm1NzxU5oSsMrb4XkUjMRZ49vw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmn78AR514CAFu5Ug3SzeBT7oIWrTQrvnIYbSzQ 05ve0hfyiyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZp+/AAAKCRAEWL7uWMY5 RvFFD/9URR1d0jocH929Qz/s5PjMGT14Hsl2k6nBxN+j8FatdCF5c3CKsWEaVbpLjiXBrY5c6jd HLlLOgG1kXYVPn6FVCML1hYWvuiYtJL7fMBhtMnIoG34QC3H93VM8/jLptPJbSx8HHDyj+uA01n Y+omgVEGTUktfukyNVbb6tQKFyGjlzECDCHp/vLhjBmTZatjzAgHMkl20nZlVyoihZYJXFNGaRH oqMVutd/lCIxaYWsx/6uytfvVyyy32Qo0mxr/MCpI+WB+FTZiCMoB/llyoDu+1UX2rlYgYG3+UA CdzSnI3aZsbKmIBHdcqxvc91zOHEuLJrO0LKdpsRFPXdlmtM0tvuJ3IBRfFu6kawORLM/tQ2ypR 9Bp1RjeUhUlTZLYdDlYE1lQPVvd/Y+mJdUQxwr8+yvXmzY1U9guzSXfv4jNF8GLGCKH/wpBLvVN Icxz4/laHtZ23BoXATjku5ItBBy9hIf+Ogjp7WXstQU1F6IEp39SPcpR85iit/UV4ISycNZTJre OPEA3BtlO//TWX3zRBLNgddwvySBScnqs5UhEgj796bUtVN6/do29WN4pZfUEK8b6LYA2hH4+Ia IqOy9H6Xy7pBUAn3ktq2jOIx0GVyuk+0pa+7/WY61IQXEF5LhmarPdRqt/9yZYluVpESVralmNk QTGAaErcvYtwspA== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240723-vma-v1-1-32ad5a0118ee@google.com> Subject: [PATCH] rust: mm: add abstractions for mm_struct and vm_area_struct From: Alice Ryhl To: Miguel Ojeda , Andrew Morton Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , linux-kernel@vger.kernel.org, linux-mm@kvack.org, rust-for-linux@vger.kernel.org, Alice Ryhl X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 6F39F80003 X-Stat-Signature: c6tt9bhpj7xjxh3ni84hf1c9n5dfirdq X-HE-Tag: 1721745166-616745 X-HE-Meta: U2FsdGVkX19HiXJb/8jDKK293wF98E9QlHkmYjFx+4Y26qJ+CBCKAPLO3Xi4B/3vxiuGCecJ9YrJ+7cPoGvehblBr0dFtsPJ4jd7wkZivu1rxjxoK32VJWLotYXkDiXgPGclH7As+U3zx+nE2CbsTL0PQV1/eNp/AGmmEh4Mtao1h7qXfXO2qPr8DYtP+gxj/JHfTlit5VagvayD6W2jMe/tYCU4aiWcoN2l0+X/PJQ4anZzQAIUNIHsiPI4ojZ+hAm9b/jbqkX7A2OqzlrvUjcvMfd5CfIUVcYxTMQXKfSYT6jIxXQRNjVnZXRhTIRbQC5NUlLB9pi8qxpOtMC55bpc7GvMbjRzSOFslkg4b66rs2JbEbKuOtLuVDn9+QyJ9B0ImBEUDKE3yYcc15CVFQJ5yrgY2F0p91/RSMr/TzqyZinQA3y8nnbLdyNtCUw5gbMx/gFD7YLRJelrunagthDlTyJHfM3OEfhJWBLHiF+hy3UJSFpCpwODj82BelU9JjfBv4eeZFL4/X6CAaSYN3z5Gj9YMdxdR0eBRv7TsgbGS6qKtp+lHGodLKrm8qzAXw4ddxNwupq1mUdg4V1IvOGd4jfV9/hTjsc1+7ZqUtWapvAdbg8/JJ9ocjTzIRmgNMixwNkoqGRp6oTQZ+kFDdLIxVPcc7RB3Rs/GqG+1wE8SPEh8R//z1Bg/UJNyf5IWlEnbbdNMORGSHtL4Cru+CT6npo/ygtV++LAq7k2qKYFr7xWnVIiqWc7BFfXvhag0UrAtBYV2sbgodErOPDNZ+Ox6rYEsH0ume1vjsaD/gvKQjgCuKDLXoIyJX5sfqOxTKE9dnSLj9oTiwWYqXYe+hsQc6AkVEJpSCKsS8jRaNa5u2MSgWt6lx1afH7gO5oA1ggAoct+jmPHjA/ePH/LwIizVXMBlq1EcPrxfZiFQhLBzQkJ/lDjmy4mbT+3124hhXmUFhirbXrl3wfOYLm +QpJPWZb QwCWXWo2NFXlRC5WBAa5jlBgDFLHC7KzgLMb/VLQ+4CrLB45F2YbXNWh0LnlFRN/m7SFJoqB7aYfvQnn4xUMRGoPQ5x5Z8N5nFSwXmJRTRuZkSsVQSnIdxOV7Sg6fsJb4ouS8jO884PDr+KKR0kskMkDNQJEjgKiGalhlAEKIVP5DFEsgugwcew9LJHOzJwA8gDvF46TXRMrE5+12jklgDadHkBIeGunfhIk9mTVbwqWL8UlnAF9iwudqMTy+2Lg24pKaoRY6wpH3eepgEVP3yr0L8wrlDM9XrXGzDQnUUbXqLcQnI4zNf1bMyFMHCDWn84CYdcrwZPGkoeK6YO6noaK1JpKAx3cjIgLdsVFM8BP4SMv/ifYhsd0YLq87qYcF9GzuL9GKITnAQw9TjuGyMtY/1QRbLcX7YRsj54cjvJPTxL+2jYQXx9EDaM9/bxoWiYRttBcc4PtqN4lWVIy8r4m1Ve5xZ+vj19/2jEiJS8jHwgO3bmIzQDG25WCpkgh7TFC1PdCbuquVH0BsvW5+xXw5rKsULYC8mrhutW4W+Y3kzIq3QbAOHhsh8myRqbOcSWQtPDR08vI4aylWKB7kjOzqVQp3ClLwYBOGHdghOtPp4ddAWj1L/IpeT9Ek441uM0DSsXsIhbNul7t2ghplo/XI78YcPKExmyoUqIk0necmu+dLlPGzWy6nbZZjtNMZHooJQDsO4+CGly9DjiDzjsAep6j5jFExSNMz9msGKomW924= 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: This is a follow-up to the page abstractions [1] that were recently merged in 6.11. Rust Binder will need these abstractions to manipulate the vma in its implementation of the mmap fop on the Binder file. The ARef wrapper is not used for mm_struct because there are several different types of refcounts. This patch is based on Wedson's implementation on the old rust branch, but has been changed significantly. All mistakes are Alice's. Link: https://lore.kernel.org/r/20240528-alice-mm-v7-4-78222c31b8f4@google.com [1] Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Signed-off-by: Alice Ryhl --- rust/helpers.c | 49 ++++++++++ rust/kernel/lib.rs | 1 + rust/kernel/mm.rs | 259 +++++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/mm/virt.rs | 193 ++++++++++++++++++++++++++++++++++++ 4 files changed, 502 insertions(+) --- base-commit: b1263411112305acf2af728728591465becb45b0 change-id: 20240723-vma-f80119f9fb35 Best regards, diff --git a/rust/helpers.c b/rust/helpers.c index 305f0577fae9..9aa5150ebe26 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -199,6 +199,55 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_krealloc); +void rust_helper_mmgrab(struct mm_struct *mm) +{ + mmgrab(mm); +} +EXPORT_SYMBOL_GPL(rust_helper_mmgrab); + +void rust_helper_mmdrop(struct mm_struct *mm) +{ + mmdrop(mm); +} +EXPORT_SYMBOL_GPL(rust_helper_mmdrop); + +bool rust_helper_mmget_not_zero(struct mm_struct *mm) +{ + return mmget_not_zero(mm); +} +EXPORT_SYMBOL_GPL(rust_helper_mmget_not_zero); + +bool rust_helper_mmap_read_trylock(struct mm_struct *mm) +{ + return mmap_read_trylock(mm); +} +EXPORT_SYMBOL_GPL(rust_helper_mmap_read_trylock); + +void rust_helper_mmap_read_unlock(struct mm_struct *mm) +{ + mmap_read_unlock(mm); +} +EXPORT_SYMBOL_GPL(rust_helper_mmap_read_unlock); + +void rust_helper_mmap_write_lock(struct mm_struct *mm) +{ + mmap_write_lock(mm); +} +EXPORT_SYMBOL_GPL(rust_helper_mmap_write_lock); + +void rust_helper_mmap_write_unlock(struct mm_struct *mm) +{ + mmap_write_unlock(mm); +} +EXPORT_SYMBOL_GPL(rust_helper_mmap_write_unlock); + +struct vm_area_struct *rust_helper_vma_lookup(struct mm_struct *mm, + unsigned long addr) +{ + return vma_lookup(mm, addr); +} +EXPORT_SYMBOL_GPL(rust_helper_vma_lookup); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indices. diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 5d310e79485f..3cbc4cf847a2 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -33,6 +33,7 @@ pub mod ioctl; #[cfg(CONFIG_KUNIT)] pub mod kunit; +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..7fa1e2431944 --- /dev/null +++ b/rust/kernel/mm.rs @@ -0,0 +1,259 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Memory management. +//! +//! C header: [`include/linux/mm.h`](../../../../include/linux/mm.h) + +use crate::bindings; + +use core::{marker::PhantomData, mem::ManuallyDrop, ptr::NonNull}; + +pub mod virt; + +/// A smart pointer that references a `struct mm` and owns an `mmgrab` refcount. +/// +/// # Invariants +/// +/// An `MmGrab` owns an `mmgrab` refcount to the inner `struct mm_struct`. +pub struct MmGrab { + mm: NonNull, +} + +impl MmGrab { + /// 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 + }; + + let mm = NonNull::new(mm)?; + + // SAFETY: We just checked that `mm` is not null. + unsafe { bindings::mmgrab(mm.as_ptr()) }; + + // INVARIANT: We just created an `mmgrab` refcount. + Some(Self { mm }) + } + + /// Check whether this vma is associated with this mm. + #[inline] + pub fn is_same_mm(&self, area: &virt::Area) -> bool { + // SAFETY: The `vm_mm` field of the area is immutable, so we can read it without + // synchronization. + let vm_mm = unsafe { (*area.as_ptr()).vm_mm }; + + vm_mm == self.mm.as_ptr() + } + + /// Calls `mmget_not_zero` and returns a handle if it succeeds. + #[inline] + pub fn mmget_not_zero(&self) -> Option { + // SAFETY: We know that `mm` is still valid since we hold an `mmgrab` refcount. + let success = unsafe { bindings::mmget_not_zero(self.mm.as_ptr()) }; + + if success { + Some(MmGet { mm: self.mm }) + } else { + None + } + } +} + +// SAFETY: It is safe to call `mmdrop` on another thread than where `mmgrab` was called. +unsafe impl Send for MmGrab {} +// SAFETY: All methods on this struct are safe to call in parallel from several threads. +unsafe impl Sync for MmGrab {} + +impl Drop for MmGrab { + #[inline] + fn drop(&mut self) { + // SAFETY: This gives up an `mmgrab` refcount to a valid `struct mm_struct`. + // INVARIANT: We own an `mmgrab` refcount, so we can give it up. + unsafe { bindings::mmdrop(self.mm.as_ptr()) }; + } +} + +/// A smart pointer that references a `struct mm` and owns an `mmget` refcount. +/// +/// Values of this type are created using [`MmGrab::mmget_not_zero`]. +/// +/// # Invariants +/// +/// An `MmGet` owns an `mmget` refcount to the inner `struct mm_struct`. +pub struct MmGet { + mm: NonNull, +} + +impl MmGet { + /// Lock the mmap read lock. + #[inline] + pub fn mmap_write_lock(&self) -> MmapWriteLock<'_> { + // SAFETY: The pointer is valid since we hold a refcount. + unsafe { bindings::mmap_write_lock(self.mm.as_ptr()) }; + + // INVARIANT: We just acquired the write lock, so we can transfer to this guard. + // + // The signature of this function ensures that the `MmapWriteLock` will not outlive this + // `mmget` refcount. + MmapWriteLock { + mm: self.mm, + _lifetime: PhantomData, + } + } + + /// When dropping this refcount, use `mmput_async` instead of `mmput`. + #[inline] + pub fn use_async_put(self) -> MmGetAsync { + // Disable destructor of `self`. + let me = ManuallyDrop::new(self); + + MmGetAsync { mm: me.mm } + } +} + +impl Drop for MmGet { + #[inline] + fn drop(&mut self) { + // SAFETY: We acquired a refcount when creating this object. + unsafe { bindings::mmput(self.mm.as_ptr()) }; + } +} + +/// A smart pointer that references a `struct mm` and owns an `mmget` refcount, that will be +/// dropped using `mmput_async`. +/// +/// Values of this type are created using [`MmGet::use_async_put`]. +/// +/// # Invariants +/// +/// An `MmGetAsync` owns an `mmget` refcount to the inner `struct mm_struct`. +pub struct MmGetAsync { + mm: NonNull, +} + +impl MmGetAsync { + /// Lock the mmap write lock. + #[inline] + pub fn mmap_write_lock(&self) -> MmapWriteLock<'_> { + // SAFETY: The pointer is valid since we hold a refcount. + unsafe { bindings::mmap_write_lock(self.mm.as_ptr()) }; + + // INVARIANT: We just acquired the write lock, so we can transfer to this guard. + // + // The signature of this function ensures that the `MmapWriteLock` will not outlive this + // `mmget` refcount. + MmapWriteLock { + mm: self.mm, + _lifetime: PhantomData, + } + } + + /// Try to lock the mmap read lock. + #[inline] + pub fn mmap_read_trylock(&self) -> Option> { + // SAFETY: The pointer is valid since we hold a refcount. + let success = unsafe { bindings::mmap_read_trylock(self.mm.as_ptr()) }; + + if success { + // INVARIANT: We just acquired the read lock, so we can transfer to this guard. + // + // The signature of this function ensures that the `MmapReadLock` will not outlive this + // `mmget` refcount. + Some(MmapReadLock { + mm: self.mm, + _lifetime: PhantomData, + }) + } else { + None + } + } +} + +impl Drop for MmGetAsync { + #[inline] + fn drop(&mut self) { + // SAFETY: We acquired a refcount when creating this object. + unsafe { bindings::mmput_async(self.mm.as_ptr()) }; + } +} + +/// A guard for the mmap read lock. +/// +/// # Invariants +/// +/// This `MmapReadLock` guard owns the mmap read lock. For the duration of 'a, the `mmget` refcount +/// will remain positive. +pub struct MmapReadLock<'a> { + mm: NonNull, + _lifetime: PhantomData<&'a bindings::mm_struct>, +} + +impl<'a> MmapReadLock<'a> { + /// Look up a vma at the given address. + #[inline] + pub fn vma_lookup(&self, vma_addr: usize) -> Option<&virt::Area> { + // SAFETY: The `mm` pointer is known to be valid while this read lock is held. + let vma = unsafe { bindings::vma_lookup(self.mm.as_ptr(), vma_addr as u64) }; + + if vma.is_null() { + None + } else { + // SAFETY: We just checked that a vma was found, so the pointer is valid. Furthermore, + // the returned area will borrow from this read lock guard, so it can only be used + // while the read lock is still held. The returned reference is immutable, so the + // reference cannot be used to modify the area. + unsafe { Some(virt::Area::from_ptr(vma)) } + } + } +} + +impl Drop for MmapReadLock<'_> { + #[inline] + fn drop(&mut self) { + // SAFETY: We acquired the lock when creating this object. + unsafe { bindings::mmap_read_unlock(self.mm.as_ptr()) }; + } +} + +/// A guard for the mmap write lock. +/// +/// # Invariants +/// +/// This `MmapReadLock` guard owns the mmap write lock. For the duration of 'a, the `mmget` refcount +/// will remain positive. +pub struct MmapWriteLock<'a> { + mm: NonNull, + _lifetime: PhantomData<&'a mut bindings::mm_struct>, +} + +impl<'a> MmapWriteLock<'a> { + /// Look up a vma at the given address. + #[inline] + pub fn vma_lookup(&mut self, vma_addr: usize) -> Option<&mut virt::Area> { + // SAFETY: The `mm` pointer is known to be valid while this read lock is held. + let vma = unsafe { bindings::vma_lookup(self.mm.as_ptr(), vma_addr as u64) }; + + if vma.is_null() { + None + } else { + // SAFETY: We just checked that a vma was found, so the pointer is valid. Furthermore, + // the returned area will borrow from this write lock guard, so it can only be used + // while the write lock is still held. We hold the write lock, so mutable operations on + // the area are okay. + unsafe { Some(virt::Area::from_ptr_mut(vma)) } + } + } +} + +impl Drop for MmapWriteLock<'_> { + #[inline] + fn drop(&mut self) { + // SAFETY: We acquired the lock when creating this object. + unsafe { bindings::mmap_write_unlock(self.mm.as_ptr()) }; + } +} diff --git a/rust/kernel/mm/virt.rs b/rust/kernel/mm/virt.rs new file mode 100644 index 000000000000..f004a366445a --- /dev/null +++ b/rust/kernel/mm/virt.rs @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2024 Google LLC. + +//! Virtual memory. + +use crate::{ + bindings, + error::{to_result, Result}, + page::Page, + types::Opaque, +}; + +/// A wrapper for the kernel's `struct vm_area_struct`. +/// +/// It represents an area of virtual memory. +#[repr(transparent)] +pub struct Area { + vma: Opaque, +} + +impl Area { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is non-null and valid for the duration of the new area's + /// lifetime, with shared access. The caller must ensure that using the pointer for immutable + /// operations is okay. + #[inline] + pub unsafe fn from_ptr<'a>(vma: *const bindings::vm_area_struct) -> &'a Self { + // SAFETY: The caller ensures that the pointer is valid. + unsafe { &*vma.cast() } + } + + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is non-null and valid for the duration of the new area's + /// lifetime, with exclusive access. The caller must ensure that using the pointer for + /// immutable and mutable operations is okay. + #[inline] + pub unsafe fn from_ptr_mut<'a>(vma: *mut bindings::vm_area_struct) -> &'a mut Self { + // SAFETY: The caller ensures that the pointer is valid. + unsafe { &mut *vma.cast() } + } + + /// Returns a raw pointer to this area. + #[inline] + pub fn as_ptr(&self) -> *mut bindings::vm_area_struct { + self.vma.get() + } + + /// Returns the flags associated with the virtual memory area. + /// + /// The possible flags are a combination of the constants in [`flags`]. + #[inline] + pub fn flags(&self) -> usize { + // SAFETY: `self.vma` is valid by the type invariants. + unsafe { (*self.as_ptr()).__bindgen_anon_2.vm_flags as _ } + } + + /// Sets the flags associated with the virtual memory area. + /// + /// The possible flags are a combination of the constants in [`flags`]. + #[inline] + pub fn set_flags(&mut self, flags: usize) { + // SAFETY: `self.vma` is valid by the type invariants. + unsafe { (*self.as_ptr()).__bindgen_anon_2.vm_flags = flags as _ }; + } + + /// Returns the start address of the virtual memory area. + #[inline] + pub fn start(&self) -> usize { + // SAFETY: `self.vma` is valid by the type invariants. + unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_start as _ } + } + + /// Returns the end address of the virtual memory area. + #[inline] + pub fn end(&self) -> usize { + // SAFETY: `self.vma` is valid by the type invariants. + unsafe { (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.vm_end as _ } + } + + /// Make this vma anonymous. + #[inline] + pub fn set_anonymous(&mut self) { + // SAFETY: `self.vma` is valid by the type invariants. + unsafe { (*self.as_ptr()).vm_ops = core::ptr::null() }; + } + + /// Maps a single page at the given address within the virtual memory area. + #[inline] + pub fn vm_insert_page(&mut self, address: usize, page: &Page) -> Result { + // SAFETY: The page is guaranteed to be order 0. The range of `address` is already checked + // by `vm_insert_page`. `self.vma` and `page.as_ptr()` are guaranteed by their respective + // type invariants to be valid. + to_result(unsafe { bindings::vm_insert_page(self.as_ptr(), address as _, page.as_ptr()) }) + } + + /// Unmap pages in the given page range. + #[inline] + pub fn zap_page_range_single(&self, address: usize, size: usize) { + // SAFETY: The `vma` pointer is valid. + unsafe { + bindings::zap_page_range_single( + self.as_ptr(), + address as _, + size as _, + core::ptr::null_mut(), + ) + }; + } +} + +/// Container for [`Area`] flags. +pub mod flags { + use crate::bindings; + + /// No flags are set. + pub const NONE: usize = bindings::VM_NONE as _; + + /// Mapping allows reads. + pub const READ: usize = bindings::VM_READ as _; + + /// Mapping allows writes. + pub const WRITE: usize = bindings::VM_WRITE as _; + + /// Mapping allows execution. + pub const EXEC: usize = bindings::VM_EXEC as _; + + /// Mapping is shared. + pub const SHARED: usize = bindings::VM_SHARED as _; + + /// Mapping may be updated to allow reads. + pub const MAYREAD: usize = bindings::VM_MAYREAD as _; + + /// Mapping may be updated to allow writes. + pub const MAYWRITE: usize = bindings::VM_MAYWRITE as _; + + /// Mapping may be updated to allow execution. + pub const MAYEXEC: usize = bindings::VM_MAYEXEC as _; + + /// Mapping may be updated to be shared. + pub const MAYSHARE: usize = bindings::VM_MAYSHARE as _; + + /// Do not copy this vma on fork. + pub const DONTCOPY: usize = bindings::VM_DONTCOPY as _; + + /// Cannot expand with mremap(). + pub const DONTEXPAND: usize = bindings::VM_DONTEXPAND as _; + + /// Lock the pages covered when they are faulted in. + pub const LOCKONFAULT: usize = bindings::VM_LOCKONFAULT as _; + + /// Is a VM accounted object. + pub const ACCOUNT: usize = bindings::VM_ACCOUNT as _; + + /// should the VM suppress accounting. + pub const NORESERVE: usize = bindings::VM_NORESERVE as _; + + /// Huge TLB Page VM. + pub const HUGETLB: usize = bindings::VM_HUGETLB as _; + + /// Synchronous page faults. + pub const SYNC: usize = bindings::VM_SYNC as _; + + /// Architecture-specific flag. + pub const ARCH_1: usize = bindings::VM_ARCH_1 as _; + + /// Wipe VMA contents in child.. + pub const WIPEONFORK: usize = bindings::VM_WIPEONFORK as _; + + /// Do not include in the core dump. + pub const DONTDUMP: usize = bindings::VM_DONTDUMP as _; + + /// Not soft dirty clean area. + pub const SOFTDIRTY: usize = bindings::VM_SOFTDIRTY as _; + + /// Can contain "struct page" and pure PFN pages. + pub const MIXEDMAP: usize = bindings::VM_MIXEDMAP as _; + + /// MADV_HUGEPAGE marked this vma. + pub const HUGEPAGE: usize = bindings::VM_HUGEPAGE as _; + + /// MADV_NOHUGEPAGE marked this vma. + pub const NOHUGEPAGE: usize = bindings::VM_NOHUGEPAGE as _; + + /// KSM may merge identical pages. + pub const MERGEABLE: usize = bindings::VM_MERGEABLE as _; +}