From patchwork Fri Nov 29 16:32:39 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13888846 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 B2EDBD729E7 for ; Fri, 29 Nov 2024 16:33:09 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id BAF176B009A; Fri, 29 Nov 2024 11:33:08 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id B0F7F6B009B; Fri, 29 Nov 2024 11:33:08 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 93D2A6B009C; Fri, 29 Nov 2024 11:33:08 -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 6F5866B009A for ; Fri, 29 Nov 2024 11:33:08 -0500 (EST) Received: from smtpin24.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 006CF1A12B4 for ; Fri, 29 Nov 2024 16:33:07 +0000 (UTC) X-FDA: 82839677004.24.449997F Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) by imf21.hostedemail.com (Postfix) with ESMTP id 2C4401C0012 for ; Fri, 29 Nov 2024 16:32:49 +0000 (UTC) Authentication-Results: imf21.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="RpWjbO1/"; spf=pass (imf21.hostedemail.com: domain of 3wOxJZwkKCAMdolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3wOxJZwkKCAMdolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@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=1732897982; 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=FQmeIT5gOsUotOB7o6QXCtotwfAnfjr1q7Rp4w0i4JU=; b=mzHlnpBEMljGzLO3Y8iXj1i3qbsDxzQpczVauHHYEPhXPpg2ZH/SwUJ1J30uq/gfDaOV5a kod5Q8xulZDufo87b4T2hoEvGfgroRudO1lSb++/2NOjsJyDkfF1qzB0nFUTdmjUeKehft JKRf6aWJ2R+1YeCEVN6WK/fSGtE7Khg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1732897982; a=rsa-sha256; cv=none; b=f5PpZlv6L8RddAxrOMheEM9zoFBquMbeirthnV4lI+tdNHH7LSqM6bLviAfL91LPbCsPti d/H+z+q+MrUK5GFdIDQJapRuB4PoxmhbDhaHKUJs2S3lGYK5CZyGim6WEPvkjsGYo5Z6L1 iVDBhOApge5fXHufZ2PXB+0u5pxpoO8= ARC-Authentication-Results: i=1; imf21.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="RpWjbO1/"; spf=pass (imf21.hostedemail.com: domain of 3wOxJZwkKCAMdolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com designates 209.85.128.74 as permitted sender) smtp.mailfrom=3wOxJZwkKCAMdolfhu1kojrrjoh.frpolqx0-ppnydfn.ruj@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-4349c5e58a3so17384715e9.2 for ; Fri, 29 Nov 2024 08:33:05 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1732897985; x=1733502785; 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=FQmeIT5gOsUotOB7o6QXCtotwfAnfjr1q7Rp4w0i4JU=; b=RpWjbO1/7KfnVcYDeaaMdsJKtjK24gWxp91VaC6iIm5cEFjYV1S6xdmJ5orcANMuBp Rf5fWxNVMn6iHLuAAwevEhzpgrtXPnmwe9ba6S47bVwtNNhv3+dQTGqqOjRB9SMypO9j KoQlKjI3Py5nU/4mn8FX0VVQ6w1o1j0HXhbxLafKzeTfUnXBux4PSUs1afGOD/dh/u3M Ps4P3EfoDAszWUAQEiddRNY/A6bVWf5uEFJ9rRfL39ixYnUkGc6UPcu2OwVAT2w0Cyaq JyaJxtmCM37H6CgHdyRY40hmA1kGFVbhv7o4DBM8rh97GVYoRbWrM6IXSwEB74JsSnfN 7jGw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1732897985; x=1733502785; 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=FQmeIT5gOsUotOB7o6QXCtotwfAnfjr1q7Rp4w0i4JU=; b=xTyLEOaXcfMdnAA9M6D6nDJe/mznxKGwG+O/p82BKiSqHdWxPSncCKYYnD7egdlF1N PBm+kld7lB5I4jVL2fhweXeJ07FsqVirr7Vr/AWsidft5/mB9QUpSNr2qq8Qbu98lY0M ysT2HSGBKCgLfwAb0LTdwff77NVsXChX1tPenL66KasvSGbXE/khh8BnqdBF97UPKgbW lj9JP98dtdFq/GEmehQdznwSXfK0+VMxO6o3NCPkyNmFGX39a9r3Y/jqAoiI23cEM32g ywrPF/DS1CfFW07n9F3TpLiNVgrfbW7OE7Al4E2FXQugWFlqD1TMVK8rTnBxiJU1NNYq 3h2w== X-Forwarded-Encrypted: i=1; AJvYcCXQEtdfUVJ0uh4wXWoBszkXgugo1BmbjBCwcqXT9PXwuFy0AJAf1iDIISfvx1TMG1MTZAXTghKu/Q==@kvack.org X-Gm-Message-State: AOJu0Yx9mNhkuO9Bd6I2fGwmJf5gI8i8mxXlLoD/8NOTPzJ362oaU7eD Eegnk09TSQVjTKVCX1vIdk+Fr6YoXksu6dZCkk/hJhTiPu7XPmlv5uxCAvjCjSXCt+DFXY2PrI2 uaP6Xq5DoItGhBQ== X-Google-Smtp-Source: AGHT+IFsZCkak00uYhITnMwKRsDF3s5UKpxdm1Ck5P9OOToSqry0Xi4dvkplER8/UfrYyNysD4wuKqkPHmyCm60= X-Received: from wmbjx1.prod.google.com ([2002:a05:600c:5781:b0:42c:b2f6:e6dd]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:19cc:b0:42c:bb10:7292 with SMTP id 5b1f17b1804b1-434a9dbaee2mr101296295e9.1.1732897984863; Fri, 29 Nov 2024 08:33:04 -0800 (PST) Date: Fri, 29 Nov 2024 16:32:39 +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=8218; i=aliceryhl@google.com; h=from:subject:message-id; bh=gC7RalGfFyvdhxyetp0qLjWhd8M+19FgWoTk8eiPyqo=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBnSeyw5vs6i/9T0252bYqbEn7nkN41XOkM+MXze 3wvucuoTyGJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZ0nssAAKCRAEWL7uWMY5 RgTfEACfVuMxx1SnP/BL8wCAsPuxX5JGhXxnfaLz7ZZzUax2XN12bzlMqd5YfYKXzKdwcoYnEwV 94lofBlwvf6N8t5Sz959Mm2XikEzfX1OL3r9waiomQSC9WWgZcMbzlQSTFz64/ZuGS4bvAeRqA/ w4o+9qWe1CE89aDPwR6zabLo4hkqThpqUaSw2ubox3Tw29PgjTJFY6ka5juhsobw1jIEfrFROBl raa4dfyZER0pRuJ1XdHUybuXA/9fi+nPi5/Is8WVM/WYi8CTgPvZvfeyo7cUXZhqS6asQgNcGHx WoXQlaMbC80sDbMtIJp5sRe5Leub6xL0sDvG1mdsi9tUqJE4t/tc9c6BT4cj7UVRgqMkUI/nDUe yFZiNPPdWYxuAQV/uJxvU5ZcX9hyMErXL3I1i9KfGCeHEUAW2KYxFO4POdMd9SP8/P1GLrl70zk LOjgMq4yUyeO8bFwU76m0th2qEkPUF4SawjKMSR8PrenLElrz0JU7e1Dn4V5JWOX16FxM+DBt7f P13GF+rp0/nalQifLMrem7cwLe3VIwclC5uzajUOW6fFdfpbddG1Ae/FfgjrOp4M3a8W7sKFp49 8Vt+43lDn8Fe2EbwTiBlJqyMTRS5OYKfJIcFVvuybRRzWEGSiJQxlukqy2/sZHcTrI5MKdP3tnE gk+7FY2H7FGOs0w== X-Mailer: b4 0.13.0 Message-ID: <20241129-vma-v10-6-4dfff05ba927@google.com> Subject: [PATCH v10 6/8] mm: rust: add VmAreaNew for f_ops->mmap() 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-Server: rspam10 X-Rspamd-Queue-Id: 2C4401C0012 X-Stat-Signature: iw4unggrk7b7hn8iw6quozueki6ucd6j X-Rspam-User: X-HE-Tag: 1732897969-969154 X-HE-Meta: U2FsdGVkX1837UUzfNr7WmwT7V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Ed3Ph3k0l+Hg9i+JrfG+Kdoo19j6VLVpDVbNvmvuc3wd2nDSZkoFOeTD2onaQIsnQfRh+5zN0DdJ6PhKTuQPzDrGT5mHPZvsa0bwEO/1S7kuc4SJZ6m3+O6NsGevUW0T4gQtWmiPrVvzWKRL9x+ztqpn7EEqVOERxcuNu5ujxeCtYZy3Cwbh0ud9hjbvksdeFhtk+W8V/o4FhwUivrJSR0dldAwWaTljoEV5Thg+TOP+oFIADVXoMeIikqhTd5QZweL2ddEug3yEXYuYUlnE+wc8hkcNV1XCyXaXF/bqUOmXFJQzlyFwzov9D30Q6aJ4Tag2QO75hko0EWvCPkaTYNxgkW+7HkOMG1oY0vHuixVzabNWpPFukMr3Uhofcpt4zlmHsPfOaRdgJux3dB4g6jOCKhk0auJiPCdNLmHyk/6nCWe7GOyM+Hq9p3C1CoyZdy0LOgaO98j8guvf6lLNcpPmCI6PK7vKUsDtRItPDn+raQP+UtfUCVXCVJIc42aROvA+U6GUEdBP3l3m5qXtHAw9BCfMiIFCFjMyqo7CQ58Fxy/gwkl/WI3qJbknceRM7Ceb6xsXBfcAfaUuHXL4DfKTgOELkYQv+RTgrp3HA== 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 type will be used when setting up a new vma in an f_ops->mmap() hook. Using a separate type from VmAreaRef allows us to have a separate set of operations that you are only able to use during the mmap() hook. For example, the VM_MIXEDMAP flag must not be changed after the initial setup that happens during the f_ops->mmap() hook. To avoid setting invalid flag values, the methods for clearing VM_MAYWRITE and similar involve a check of VM_WRITE, and return an error if VM_WRITE is set. Trying to use `try_clear_maywrite` without checking the return value results in a compilation error because the `Result` type is marked #[must_use]. For now, there's only a method for VM_MIXEDMAP and not VM_PFNMAP. When we add a VM_PFNMAP method, we will need some way to prevent you from setting both VM_MIXEDMAP and VM_PFNMAP on the same vma. Acked-by: Lorenzo Stoakes (for mm bits) Reviewed-by: Jann Horn Signed-off-by: Alice Ryhl --- rust/kernel/mm/virt.rs | 181 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 180 insertions(+), 1 deletion(-) diff --git a/rust/kernel/mm/virt.rs b/rust/kernel/mm/virt.rs index fa1fd6aa703c..790b8cb91c27 100644 --- a/rust/kernel/mm/virt.rs +++ b/rust/kernel/mm/virt.rs @@ -6,7 +6,7 @@ use crate::{ bindings, - error::{to_result, Result}, + error::{code::EINVAL, to_result, Result}, page::Page, types::Opaque, }; @@ -161,6 +161,185 @@ pub fn vm_insert_page(&self, address: usize, page: &Page) -> Result { } } +/// A builder for setting up a vma in an `f_ops->mmap()` hook. +/// +/// # Invariants +/// +/// For the duration of 'a, the referenced vma must be undergoing initialization in an +/// `f_ops->mmap()` hook. +pub struct VmAreaNew { + vma: VmAreaRef, +} + +// Make all `VmAreaRef` methods available on `VmAreaNew`. +impl Deref for VmAreaNew { + type Target = VmAreaRef; + + #[inline] + fn deref(&self) -> &VmAreaRef { + &self.vma + } +} + +impl VmAreaNew { + /// Access a virtual memory area given a raw pointer. + /// + /// # Safety + /// + /// Callers must ensure that `vma` is undergoing initial vma setup for the duration of 'a. + #[inline] + pub unsafe fn from_raw<'a>(vma: *const bindings::vm_area_struct) -> &'a Self { + // SAFETY: The caller ensures that the invariants are satisfied for the duration of 'a. + unsafe { &*vma.cast() } + } + + /// Internal method for updating the vma flags. + /// + /// # Safety + /// + /// This must not be used to set the flags to an invalid value. + #[inline] + unsafe fn update_flags(&self, set: vm_flags_t, unset: vm_flags_t) { + let mut flags = self.flags(); + flags |= set; + flags &= !unset; + + // SAFETY: This is not a data race: the vma is undergoing initial setup, so it's not yet + // shared. Additionally, `VmAreaNew` is `!Sync`, so it cannot be used to write in parallel. + // The caller promises that this does not set the flags to an invalid value. + unsafe { (*self.as_ptr()).__bindgen_anon_2.__vm_flags = flags }; + } + + /// Set the `VM_MIXEDMAP` flag on this vma. + /// + /// This enables the vma to contain both `struct page` and pure PFN pages. Returns a reference + /// that can be used to call `vm_insert_page` on the vma. + #[inline] + pub fn set_mixedmap(&self) -> &VmAreaMixedMap { + // SAFETY: We don't yet provide a way to set VM_PFNMAP, so this cannot put the flags in an + // invalid state. + unsafe { self.update_flags(flags::MIXEDMAP, 0) }; + + // SAFETY: We just set `VM_MIXEDMAP` on the vma. + unsafe { VmAreaMixedMap::from_raw(self.vma.as_ptr()) } + } + + /// Set the `VM_IO` flag on this vma. + /// + /// This is used for memory mapped IO and similar. The flag tells other parts of the kernel to + /// avoid looking at the pages. For memory mapped IO this is useful as accesses to the pages + /// could have side effects. + #[inline] + pub fn set_io(&self) { + // SAFETY: Setting the VM_IO flag is always okay. + unsafe { self.update_flags(flags::IO, 0) }; + } + + /// Set the `VM_DONTEXPAND` flag on this vma. + /// + /// This prevents the vma from being expanded with `mremap()`. + #[inline] + pub fn set_dontexpand(&self) { + // SAFETY: Setting the VM_DONTEXPAND flag is always okay. + unsafe { self.update_flags(flags::DONTEXPAND, 0) }; + } + + /// Set the `VM_DONTCOPY` flag on this vma. + /// + /// This prevents the vma from being copied on fork. This option is only permanent if `VM_IO` + /// is set. + #[inline] + pub fn set_dontcopy(&self) { + // SAFETY: Setting the VM_DONTCOPY flag is always okay. + unsafe { self.update_flags(flags::DONTCOPY, 0) }; + } + + /// Set the `VM_DONTDUMP` flag on this vma. + /// + /// This prevents the vma from being included in core dumps. This option is only permanent if + /// `VM_IO` is set. + #[inline] + pub fn set_dontdump(&self) { + // SAFETY: Setting the VM_DONTDUMP flag is always okay. + unsafe { self.update_flags(flags::DONTDUMP, 0) }; + } + + /// Returns whether `VM_READ` is set. + /// + /// This flag indicates whether userspace is mapping this vma as readable. + #[inline] + pub fn get_read(&self) -> bool { + (self.flags() & flags::READ) != 0 + } + + /// Try to clear the `VM_MAYREAD` flag, failing if `VM_READ` is set. + /// + /// This flag indicates whether userspace is allowed to make this vma readable with + /// `mprotect()`. + /// + /// Note that this operation is irreversible. Once `VM_MAYREAD` has been cleared, it can never + /// be set again. + #[inline] + pub fn try_clear_mayread(&self) -> Result { + if self.get_read() { + return Err(EINVAL); + } + // SAFETY: Clearing `VM_MAYREAD` is okay when `VM_READ` is not set. + unsafe { self.update_flags(0, flags::MAYREAD) }; + Ok(()) + } + + /// Returns whether `VM_WRITE` is set. + /// + /// This flag indicates whether userspace is mapping this vma as writable. + #[inline] + pub fn get_write(&self) -> bool { + (self.flags() & flags::WRITE) != 0 + } + + /// Try to clear the `VM_MAYWRITE` flag, failing if `VM_WRITE` is set. + /// + /// This flag indicates whether userspace is allowed to make this vma writable with + /// `mprotect()`. + /// + /// Note that this operation is irreversible. Once `VM_MAYWRITE` has been cleared, it can never + /// be set again. + #[inline] + pub fn try_clear_maywrite(&self) -> Result { + if self.get_write() { + return Err(EINVAL); + } + // SAFETY: Clearing `VM_MAYWRITE` is okay when `VM_WRITE` is not set. + unsafe { self.update_flags(0, flags::MAYWRITE) }; + Ok(()) + } + + /// Returns whether `VM_EXEC` is set. + /// + /// This flag indicates whether userspace is mapping this vma as executable. + #[inline] + pub fn get_exec(&self) -> bool { + (self.flags() & flags::EXEC) != 0 + } + + /// Try to clear the `VM_MAYEXEC` flag, failing if `VM_EXEC` is set. + /// + /// This flag indicates whether userspace is allowed to make this vma executable with + /// `mprotect()`. + /// + /// Note that this operation is irreversible. Once `VM_MAYEXEC` has been cleared, it can never + /// be set again. + #[inline] + pub fn try_clear_mayexec(&self) -> Result { + if self.get_exec() { + return Err(EINVAL); + } + // SAFETY: Clearing `VM_MAYEXEC` is okay when `VM_EXEC` is not set. + unsafe { self.update_flags(0, flags::MAYEXEC) }; + Ok(()) + } +} + /// The integer type used for vma flags. #[doc(inline)] pub use bindings::vm_flags_t;