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 E8064C02194 for ; Tue, 4 Feb 2025 11:44:04 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7DD3C6B0085; Tue, 4 Feb 2025 06:44:04 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 766A16B0088; Tue, 4 Feb 2025 06:44:04 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5E0266B008A; Tue, 4 Feb 2025 06:44:04 -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 3BE0F6B0085 for ; Tue, 4 Feb 2025 06:44:04 -0500 (EST) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id B6EE9B0DB6 for ; Tue, 4 Feb 2025 11:44:03 +0000 (UTC) X-FDA: 83082078366.10.2CA6287 Received: from mail.marcansoft.com (marcansoft.com [212.63.210.85]) by imf11.hostedemail.com (Postfix) with ESMTP id C834540008 for ; Tue, 4 Feb 2025 11:44:01 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=asahilina.net header.s=default header.b=XxCoVoGC; spf=pass (imf11.hostedemail.com: domain of lina@asahilina.net designates 212.63.210.85 as permitted sender) smtp.mailfrom=lina@asahilina.net; dmarc=pass (policy=quarantine) header.from=asahilina.net ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1738669442; 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:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=idr1/Yp+jgiIRRsqXZX9hO0TIjhrE5OdheZH6kEuguM=; b=3WtfJX2zzQfBTqJJ/dDVu/alUMUmN3oKVGKklkwlsxeY2wczVcFJUJj6hKbyhl6NxT0Mfs jsIwQjgea/wmXASxgX1XXKOiG6DRxlAjsd5BvZSbVgoY4djFRr4+YyCS00RctTYGYEbQQC W18vZN3LDlspAt5FxRV/QRd1A1+cjEU= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=asahilina.net header.s=default header.b=XxCoVoGC; spf=pass (imf11.hostedemail.com: domain of lina@asahilina.net designates 212.63.210.85 as permitted sender) smtp.mailfrom=lina@asahilina.net; dmarc=pass (policy=quarantine) header.from=asahilina.net ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1738669442; a=rsa-sha256; cv=none; b=wC0V8pnJ0Cs1OGSf44fAATHrg78cHRQrnH3pshevFk0TmpA8k5QNl1tCnLX4/xaw38XRrj UKmv+NPKgLMbHJEJYHPMGtRwbMUpg1ynrRHBMSK9U8qUMwIbLeDnNSARTOAX5TDUIXXgXL YvOJb7yXbKQsTEeJCyBYfCOJMFGvGj8= Received: from [127.0.0.1] (localhost [127.0.0.1]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) (Authenticated sender: lina@asahilina.net) by mail.marcansoft.com (Postfix) with ESMTPSA id 274C8431CA; Tue, 4 Feb 2025 11:43:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=asahilina.net; s=default; t=1738669440; bh=/F/9xibC0lRtfjQqqtMiCSlXX6j4n6Vdw/S7nmMVlaA=; h=Date:Subject:To:Cc:References:From:In-Reply-To; b=XxCoVoGC8Rb0Dpe/lvOUlgAlE4LvivGAMAazZeHLZWkg5irGrpVKJ/sKTJmIXpkiM ARYrTMYtea0lOb/VLDkjfjN82tR9TZhZrZBPSVaNlzEKleIPCkyj7nXCHCr7xxT7hx y0+lFcg4xVfcwmMDOzC8QBXwy3DYL/gvKiUBzF8TZOqXGlKYMtze1H4lPFSrUd6kJG SqR3tR/9Q5l4K0TGHbWey0KJes5tTrxMbE4UVSqmtpXE572tqSBTuoWT5e6JlUv41r f2BCi8QC/FvaIY4v2ooZDiMcjMV06UGLRazRVhFMC1u/8jiogEsc4Fx8p2/mUVfnXh fzSUoXdHyhajQ== Message-ID: Date: Tue, 4 Feb 2025 20:43:57 +0900 MIME-Version: 1.0 User-Agent: Mozilla Thunderbird Subject: Re: [PATCH 5/6] rust: page: Add physical address conversion functions To: Alice Ryhl Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?Q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Jann Horn , Matthew Wilcox , Paolo Bonzini , Danilo Krummrich , Wedson Almeida Filho , Valentin Obst , Andrew Morton , linux-mm@kvack.org, airlied@redhat.com, Abdiel Janulgue , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, asahi@lists.linux.dev References: <20250202-rust-page-v1-0-e3170d7fe55e@asahilina.net> <20250202-rust-page-v1-5-e3170d7fe55e@asahilina.net> Content-Language: en-US From: Asahi Lina In-Reply-To: Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Rspamd-Server: rspam05 X-Rspamd-Queue-Id: C834540008 X-Stat-Signature: xohkwmzwtzgiagqwknstp7f8nrosc5h9 X-Rspam-User: X-HE-Tag: 1738669441-610821 X-HE-Meta: U2FsdGVkX1/voe7+LrSIb3fLVCo+7Lb75ZYK8HBpIUvR3pUnT2MRu5Ordpe87Zfl08PYsQBx3qBkUWPK8dVyJ96n1FUczv+k/e9hdgfr7D1eymuRjGHhJE2T9cLUM5XDlVU5/vza0yLASQ5HvoY8xWivk13ygLMHh5vG9ZIGdDfXbN6fziGr7jQK8VQH+bebt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vLvdvsssKKGTjx1clqCrPGVQo2hmn/FtT7243xATlQd1c6K0wJx83nY599edIj92UH7yToxePutSnqXVEfCagEluZPiZX0v6BgcuDj8l4HEloIEEXX2Z9MbFvMS6XHp2uTgGbGbvYcXaPT8V0Frcr2k88eDmfKZavPGXYbZNaog4CJqK7IjY05gmXoap8t1CnsUyp7Q61G8mU336q9bjVshwxXyurJ0= X-Bogosity: Unsure, tests=bogofilter, spamicity=0.498582, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: On 2/3/25 6:35 PM, Alice Ryhl wrote: > On Sun, Feb 2, 2025 at 2:06 PM Asahi Lina wrote: >> >> Add methods to allow code using the Page type to obtain the physical >> address of a page, convert to and from an (owned) physical address, and >> borrow a Page from a physical address. Most of these operations are, as >> you might expect, unsafe. >> >> These primitives are useful to implement page table structures in Rust, >> and to implement arbitrary physical memory access (as needed to walk >> arbitrary page tables and dereference through them). These mechanisms >> are, of course, fraught with danger, and are only expected to be used >> for core memory management code (in e.g. drivers with their own device >> page table implementations) and for debug features such as crash dumps >> of device memory. >> >> Signed-off-by: Asahi Lina >> --- >> rust/helpers/page.c | 26 +++++++++++++++++++++ >> rust/kernel/page.rs | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++ >> 2 files changed, 91 insertions(+) >> >> diff --git a/rust/helpers/page.c b/rust/helpers/page.c >> index b3f2b8fbf87fc9aa89cb1636736c52be16411301..1c3bd68818d77f7ce7806329b8f040a7d4205bb3 100644 >> --- a/rust/helpers/page.c >> +++ b/rust/helpers/page.c >> @@ -1,5 +1,6 @@ >> // SPDX-License-Identifier: GPL-2.0 >> >> +#include >> #include >> #include >> >> @@ -17,3 +18,28 @@ void rust_helper_kunmap_local(const void *addr) >> { >> kunmap_local(addr); >> } >> + >> +struct page *rust_helper_phys_to_page(phys_addr_t phys) >> +{ >> + return phys_to_page(phys); >> +} >> + >> +phys_addr_t rust_helper_page_to_phys(struct page *page) >> +{ >> + return page_to_phys(page); >> +} >> + >> +unsigned long rust_helper_phys_to_pfn(phys_addr_t phys) >> +{ >> + return __phys_to_pfn(phys); >> +} >> + >> +struct page *rust_helper_pfn_to_page(unsigned long pfn) >> +{ >> + return pfn_to_page(pfn); >> +} >> + >> +bool rust_helper_pfn_valid(unsigned long pfn) >> +{ >> + return pfn_valid(pfn); >> +} >> diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs >> index fe5f879f9d1a86083fd55c682fad9d52466f79a2..67cd7006fa63ab5aed4c4de2be639ed8e1fbc2ba 100644 >> --- a/rust/kernel/page.rs >> +++ b/rust/kernel/page.rs >> @@ -3,6 +3,7 @@ >> //! Kernel page allocation and management. >> >> use crate::{ >> + addr::*, >> alloc::{AllocError, Flags}, >> bindings, >> error::code::*, >> @@ -10,6 +11,7 @@ >> types::{Opaque, Ownable, Owned}, >> uaccess::UserSliceReader, >> }; >> +use core::mem::ManuallyDrop; >> use core::ptr::{self, NonNull}; >> >> /// A bitwise shift for the page size. >> @@ -249,6 +251,69 @@ pub unsafe fn copy_from_user_slice_raw( >> reader.read_raw(unsafe { core::slice::from_raw_parts_mut(dst.cast(), len) }) >> }) >> } >> + >> + /// Returns the physical address of this page. >> + pub fn phys(&self) -> PhysicalAddr { >> + // SAFETY: `page` is valid due to the type invariants on `Page`. >> + unsafe { bindings::page_to_phys(self.as_ptr()) } >> + } >> + >> + /// Converts a Rust-owned Page into its physical address. >> + /// >> + /// The caller is responsible for calling [`Page::from_phys()`] to avoid leaking memory. >> + pub fn into_phys(this: Owned) -> PhysicalAddr { >> + ManuallyDrop::new(this).phys() >> + } >> + >> + /// Converts a physical address to a Rust-owned Page. >> + /// >> + /// # Safety >> + /// The caller must ensure that the physical address was previously returned by a call to >> + /// [`Page::into_phys()`], and that the physical address is no longer used after this call, >> + /// nor is [`Page::from_phys()`] called again on it. >> + pub unsafe fn from_phys(phys: PhysicalAddr) -> Owned { >> + // SAFETY: By the safety requirements, the physical address must be valid and >> + // have come from `into_phys()`, so phys_to_page() cannot fail and >> + // must return the original struct page pointer. >> + unsafe { Owned::from_raw(NonNull::new_unchecked(bindings::phys_to_page(phys)).cast()) } >> + } >> + >> + /// Borrows a Page from a physical address, without taking over ownership. >> + /// >> + /// If the physical address does not have a `struct page` entry or is not >> + /// part of a System RAM region, returns None. >> + /// >> + /// # Safety >> + /// The caller must ensure that the physical address, if it is backed by a `struct page`, >> + /// remains available for the duration of the borrowed lifetime. >> + pub unsafe fn borrow_phys(phys: &PhysicalAddr) -> Option<&Self> { >> + // SAFETY: This is always safe, as it is just arithmetic >> + let pfn = unsafe { bindings::phys_to_pfn(*phys) }; >> + // SAFETY: This function is safe to call with any pfn >> + if !unsafe { bindings::pfn_valid(pfn) && bindings::page_is_ram(pfn) != 0 } { >> + None >> + } else { >> + // SAFETY: We have just checked that the pfn is valid above, so it must >> + // have a corresponding struct page. By the safety requirements, we can >> + // return a borrowed reference to it. >> + Some(unsafe { &*(bindings::pfn_to_page(pfn) as *mut Self as *const Self) }) >> + } >> + } >> + >> + /// Borrows a Page from a physical address, without taking over ownership >> + /// nor checking for validity. >> + /// >> + /// # Safety >> + /// The caller must ensure that the physical address is backed by a `struct page` and >> + /// corresponds to System RAM. This is true when the address was returned by >> + /// [`Page::into_phys()`]. >> + pub unsafe fn borrow_phys_unchecked(phys: &PhysicalAddr) -> &Self { > > Should this be > > pub unsafe fn borrow_phys_unchecked<'a>(phys: PhysicalAddr) -> &'a Self > > ? That's how the signature of these raw methods usually goes, and then > your safety requirements say that the requirements must hold for the > duration of 'a. The idea was to have *some* lifetime bound on an incoming variable instead of just being able to return any arbitrary lifetime, but I don't know if that's something worth doing / idiomatic in any way. Obviously we can't stop a caller from doing something wrong if they really want to. > >> + // SAFETY: This is always safe, as it is just arithmetic >> + let pfn = unsafe { bindings::phys_to_pfn(*phys) }; >> + // SAFETY: The caller guarantees that the pfn is valid. By the safety >> + // requirements, we can return a borrowed reference to it. >> + unsafe { &*(bindings::pfn_to_page(pfn) as *mut Self as *const Self) } > > Can this just be > > &*bindings::pfn_to_page(pfn).cast() Yeah, I'll fix it for v2! > > ? > > Alice > >> + } >> } >> >> // SAFETY: `Owned` objects returned by Page::alloc_page() follow the requirements of >> >> -- >> 2.47.1 >> > ~~ Lina