From patchwork Mon Mar 11 10:47:16 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13588582 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 131D0C5475B for ; Mon, 11 Mar 2024 10:47:37 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 69EB86B0083; Mon, 11 Mar 2024 06:47:36 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6003B6B0085; Mon, 11 Mar 2024 06:47:36 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 405056B0087; Mon, 11 Mar 2024 06:47:36 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 2BCA16B0083 for ; Mon, 11 Mar 2024 06:47:36 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 0840CA1460 for ; Mon, 11 Mar 2024 10:47:36 +0000 (UTC) X-FDA: 81884432112.17.6DD932F Received: from mail-yw1-f202.google.com (mail-yw1-f202.google.com [209.85.128.202]) by imf25.hostedemail.com (Postfix) with ESMTP id 32158A0009 for ; Mon, 11 Mar 2024 10:47:33 +0000 (UTC) Authentication-Results: imf25.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=g7DG7XTL; spf=pass (imf25.hostedemail.com: domain of 3ReHuZQkKCPgfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3ReHuZQkKCPgfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@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=1710154054; 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=a3rgQ6OTM36YDirL+P3CRmpv1dVQxJgazAx/ZBhtsKE=; b=N+tUwAprN/ZNQ1fiFRjFq8J12YqhF+hknwNihMA0z56hxAZcnTlNd/0F9dSCn7YsTrw0t4 4xfdbTRHBauxmxip9ZT+T3RNvqC4GjYmbbcC1E134kchi0dZbWcgKqlyOKbQwYw1oT/wwZ BgBs+OXqnHzwA4LiSzGUe0gz8XztH+c= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1710154054; a=rsa-sha256; cv=none; b=7byiOcJOXDVnLDEPV12jnZ3M0+in0oJ/rQe3lXBX4YOKct+LFqr4FNu2zqnhbbGySyrhW9 avxGGsF/2pD+zDRBacmgAg2diXSkrIhn5MEONGAi8PpOxpc9od+C5fF/47021vXMoYWkli 1DSKCv0GTQVrmCBQ/wTYNmjxMVmc6Jo= ARC-Authentication-Results: i=1; imf25.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=g7DG7XTL; spf=pass (imf25.hostedemail.com: domain of 3ReHuZQkKCPgfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3ReHuZQkKCPgfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com Received: by mail-yw1-f202.google.com with SMTP id 00721157ae682-609fb4fc058so52952937b3.3 for ; Mon, 11 Mar 2024 03:47:33 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1710154053; x=1710758853; 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=a3rgQ6OTM36YDirL+P3CRmpv1dVQxJgazAx/ZBhtsKE=; b=g7DG7XTLHNm4eVlHgfbexadIfC2i98CdAOnqE098z41Jg3xI7JwXwZRbYsmLvGgUmB zTvidkdNAOHKhmCuSkYXnes/jPoCyJJ3BEtoGBxevdANAInAqRSGF0xEENCtw0P2mtYG K2Y7GdK8jB4BV4FUlSQco+PLxZNtPKy0lQFvQRcO1TAko/kG9i70S2Wl3M958zWZg9yV 6PKJ4gsbRQxeHEFVej31Vy551DyhjMEmvDW7vb8GjodggWwoMrrPy0Po0Ak1LutkBunu yrHm0j5dS0AWiufXnw0+2OLLd9vo/82/yJRErknjM+3gmbOeyYbwqc/R3iFy7JV5HiLl cpdQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1710154053; x=1710758853; 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=a3rgQ6OTM36YDirL+P3CRmpv1dVQxJgazAx/ZBhtsKE=; b=qPaLurh59miGEyzMx1/mjM3QEF1KmzNoJC6HCzI4d7QSmjvViDIWlQFc+TyUWR42ao BqkjqJFWvD6HuDHQVeskpDBx6YABDgMWHsYoDpre1scPcIro1xpYwptSvQ/BqnljuKZ/ FBBAlFreANpReSpjaUo80gklGFU2Wr70xAzd4fNkiqVBM5Ye6gmLP/0RlOy5YqyOo4Wb 17RHRyAb0Rtn0zRGXh+YEcpLQ/inGcF0c25QD5HFYTBpTAfoT+hMX+baTybznLIaQp3f 3395cdLDzD6I8lqmZIKzQILcmE8lIvk9drC/kMYu9RY3RGhpMvXhzw0KxVSQ0BbNdg9p J9Uw== X-Forwarded-Encrypted: i=1; AJvYcCUGonuSYS3Hp2Ug80r27yV32XhuIc6JKXZvsF1uLYoYmX9hfe0T7yH1cXzXljnXMmEIPi0PoBVzvK3/q7zQ4+DbxBg= X-Gm-Message-State: AOJu0YzEHvLemUSZVbi7SkADKApyuhgjekFydXSlfsnm2rrVTj0pvJm5 XECbxGgjWr+VKfBDnFkT0eepzwx7+hZC/WCbeh1Oaksye5emjSDqbrxp6R4yX8i3MeHo7t0zdcL pnAElGVYQlUEwkA== X-Google-Smtp-Source: AGHT+IGGexGpdfDtIhCShg6eUatPr5rS/mCdR8LuVUYXldx2rgtDy1e66KzQBWuleQC3NjqJS6NJkv3lPfTQxck= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:f07:b0:dcf:f526:4cc6 with SMTP id et7-20020a0569020f0700b00dcff5264cc6mr328765ybb.11.1710154053262; Mon, 11 Mar 2024 03:47:33 -0700 (PDT) Date: Mon, 11 Mar 2024 10:47:16 +0000 In-Reply-To: <20240311-alice-mm-v3-0-cdf7b3a2049c@google.com> Mime-Version: 1.0 References: <20240311-alice-mm-v3-0-cdf7b3a2049c@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=13889; i=aliceryhl@google.com; h=from:subject:message-id; bh=RqqYo8Xwakoq53YPU2GZeGJPFs6BA+Ric3Um8ZRej8k=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBl7uE1v/lyWXqmRMi7zcm+0EN/VPFicekl+mqlB zgG2I528fGJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZe7hNQAKCRAEWL7uWMY5 RjuXD/4j6zTA/pUDR4mY4dMVnQrE7UQxfslBQujKYedFfxV8P8MB4VT9nBQlzTye8G1GF5oVQPo mhnmtK25dHQp4INUApVFhKLZTRJOsOSrAG396vsukMIL63SixlKwkJhCRPnGeC25zqvCMKoPQF8 mJyjNnhA9Kexqv4l9RI6yD/yDX5EdWW7g1ireNoQdDGh8ZZK7QodL9MG9klwn9isq39jHwbdz0n 3QwUqC/HpK+HY2g5R91mGWFrlwXxC9ha2sY3hY20P+PFUJqU3gb+Tdzp0koLxvBRSwHbxwqrvF6 rHhKY9aJPd4PwBl87M3ptnxQZX+iO+ypaQRUch7fAqlt3QkPuEscr4k6skSY8czT2IODfTdjA1w 7TIzzy87ruidKT9XIdMrzfJPzn+TFh7lhjzLWVF+LOEMes8tregbk4w1WJNH/bteXWMuvDJj9Hf 7cLL2ldlFuhR43ikqEYjOCd/VcUaq/HfyvrcJ0dZawgUl/ka0OQwmiXk2T3r6TNOm6ypquziQ8K 5zCrp/TC2oPurX03F6u/QqPNN/XK7F85opPnTA39ZZ0SUQlmC+3dmEwdcLZdfwawxW0wcfbluDT vE+XzWzGfiRCV//XocT3nuXQfZ6V7vQj6uea45c/qr9aLqbYmIU4aQBTfO0JSSUCo4KHiRcAbm4 WD4Go7lIqtG9USw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240311-alice-mm-v3-4-cdf7b3a2049c@google.com> Subject: [PATCH v3 4/4] rust: add abstraction for `struct page` From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj=C3=B8?= =?utf-8?q?nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspamd-Queue-Id: 32158A0009 X-Rspam-User: X-Rspamd-Server: rspam11 X-Stat-Signature: oa6qs9a5piye153oj96oqkyu68dowxzi X-HE-Tag: 1710154053-291352 X-HE-Meta: U2FsdGVkX18A8gCZQto4cWnbplvQJta0bsyWVtbdWCp5SsF5Zn/fau2JRBmatyxrufNMgFknUuiLj4G13Xf4wxZGxof/udmway0GtPAg0KFb7qj1HWGJUV1VwbljlQxnZ8Mp94ET/KO3U6voMIOYJhxkGpnDphg7c/USRxFd99D+/HNSzv4gHX/WhuYhyknyLrGuKd9cL5X4WS7HUmvvKPmEgpNWrthgIWr0R6cT75y0drIwhD+HIFAFWLL+BUEzfpfnDuhDFrZu1iQ+gQs9XzDU/YIm2U+IsHW/UwLpvcg0JIoV8eZTXZj4t9QeAkzWvv98UEGsI2b+kkPS8ZEJbf1alYJEswW843hugllUiYaMT9QQ8ucBqQPm2gdYF3q1nxN/1GRLGoOIvSbn9UwbNWI41AO/YMu2EsMnXWy/phrRyCqOxvnfMcR4pKRJSOBFN8gORoJfKsLQM9KkIc87AVJ7o2CknrHvOsjidrdNOpNcRBZNNylWP0ymOmRHsvqEr8y49Kb7s/VZp/aSlA9pWvxa6wil8GOgbig7gKGHqj5L6XCBm5itFGmqpl1RAhp5PBG75jlu9vGSlgtR+fP2s6VAhKnaOPQGpaDZF7SreF0DT+cfViwSpxLnWsxNCEfeCrgHywyZOgjSX9FNXxmJUDYy6lsPA0/Vl5qRqTxZSa+xjbcpAjmdMdDqwpjbFftY8fyx6gbZ7QzvLcrhnhe6oEsvFp3Zx3Da0U4IN77kytiqvGMbVT4v8CtkKu+tR/VYujypfbmPkuXE3P9HpIPZ0aZzv5r1MW0l5olaykTGuPQ89Ii9see8uNcv8Ihod/Jd0B5dAKHOrDl++e8Kc25yaElq/JHjtHKvMNMq0q213ySMyNKtyO2of/nZ8iFfgmiFXwbBrV60r0gd1gV7ssf8eo9DqhkGN790ntV04v63p9eDa5/fOI+roHDjn4EsbIkbz/8/rZccv0a9IJ00D8H nqv5aV8C 604edoAQhyep3DGkYSjrhsWXCAptYkIFnFh/neIm37eIPXjuQWkYojTF64ZRB5KBt1TYGLGDLS0dIh6C+rlSNbhD9eJDYWL+SVmf99OKJSy6m6Ehb2oCt7Xw4o5OPfGp8hMXEke5d4zZSdkN8Ac3JfogOwZcanD1sOFUi6NQP12jBczH6+ybQwC7E5B/5s8Hv4hRHAAsWDPn0JE3khVx8juGEZf8bS4Bzp4c4f7KJaA3qGyxeifHfVqZlYSTCFzxPLvN7hqOFzhGqJ4O/l5I2vWHWvd3OVCIfNfmaYIaxXyB3a2ioFUjQ+qOhjblaz2XDFXOkozAWx6dVk+qkaz33+wjsPvx/iMb2PM5elUAInnunCQaawe4NgNg9zVKmF9lgzucFNX9Qwq5zYOXoi9BOdCABFtbQ17DGLm/j0taCv/XkJi7+DX52EtYZiu/RtJ6ET2P1 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: Adds a new struct called `Page` that wraps a pointer to `struct page`. This struct is assumed to hold ownership over the page, so that Rust code can allocate and manage pages directly. The page type has various methods for reading and writing into the page. These methods will temporarily map the page to allow the operation. All of these methods use a helper that takes an offset and length, performs bounds checks, and returns a pointer to the given offset in the page. This patch only adds support for pages of order zero, as that is all Rust Binder needs. However, it is written to make it easy to add support for higher-order pages in the future. To do that, you would add a const generic parameter to `Page` that specifies the order. Most of the methods do not need to be adjusted, as the logic for dealing with mapping multiple pages at once can be isolated to just the `with_pointer_into_page` method. Finally, the struct can be renamed to `Pages`, and the type alias `Page = Pages<0>` can be introduced. Rust Binder needs to manage pages directly as that is how transactions are delivered: Each process has an mmap'd region for incoming transactions. When an incoming transaction arrives, the Binder driver will choose a region in the mmap, allocate and map the relevant pages manually, and copy the incoming transaction directly into the page. This architecture allows the driver to copy transactions directly from the address space of one process to another, without an intermediate copy to a kernel buffer. This code is based on Wedson's page abstractions from the old rust branch, but it has been modified by Alice by removing the incomplete support for higher-order pages, by introducing the `with_*` helpers to consolidate the bounds checking logic into a single place, and by introducing gfp flags. Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Signed-off-by: Alice Ryhl --- rust/bindings/bindings_helper.h | 3 + rust/helpers.c | 20 ++++ rust/kernel/lib.rs | 1 + rust/kernel/page.rs | 223 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 247 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 65b98831b975..1073005ca449 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -20,5 +20,8 @@ /* `bindgen` gets confused at certain things. */ const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN = ARCH_SLAB_MINALIGN; +const size_t RUST_CONST_HELPER_PAGE_SIZE = PAGE_SIZE; +const size_t RUST_CONST_HELPER_PAGE_MASK = PAGE_MASK; const gfp_t RUST_CONST_HELPER_GFP_KERNEL = GFP_KERNEL; const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO; +const gfp_t RUST_CONST_HELPER___GFP_HIGHMEM = ___GFP_HIGHMEM; diff --git a/rust/helpers.c b/rust/helpers.c index 312b6fcb49d5..298d2ee16e61 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include #include @@ -93,6 +95,24 @@ int rust_helper_signal_pending(struct task_struct *t) } EXPORT_SYMBOL_GPL(rust_helper_signal_pending); +struct page *rust_helper_alloc_pages(gfp_t gfp_mask, unsigned int order) +{ + return alloc_pages(gfp_mask, order); +} +EXPORT_SYMBOL_GPL(rust_helper_alloc_pages); + +void *rust_helper_kmap_local_page(struct page *page) +{ + return kmap_local_page(page); +} +EXPORT_SYMBOL_GPL(rust_helper_kmap_local_page); + +void rust_helper_kunmap_local(const void *addr) +{ + kunmap_local(addr); +} +EXPORT_SYMBOL_GPL(rust_helper_kunmap_local); + refcount_t rust_helper_REFCOUNT_INIT(int n) { return (refcount_t)REFCOUNT_INIT(n); diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 37f84223b83f..667fc67fa24f 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -39,6 +39,7 @@ pub mod kunit; #[cfg(CONFIG_NET)] pub mod net; +pub mod page; pub mod prelude; pub mod print; mod static_assert; diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs new file mode 100644 index 000000000000..02d25b142fc8 --- /dev/null +++ b/rust/kernel/page.rs @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Kernel page allocation and management. + +use crate::{bindings, error::code::*, error::Result, uaccess::UserSliceReader}; +use core::{ + alloc::AllocError, + ptr::{self, NonNull}, +}; + +/// A bitwise shift for the page size. +pub const PAGE_SHIFT: usize = bindings::PAGE_SHIFT as usize; +/// The number of bytes in a page. +pub const PAGE_SIZE: usize = bindings::PAGE_SIZE as usize; +/// A bitmask that can be used to get the page containing a given address by masking away the lower +/// bits. +pub const PAGE_MASK: usize = bindings::PAGE_MASK as usize; + +/// Flags for the "get free page" function that underlies all memory allocations. +pub mod flags { + pub type gfp_t = bindings::gfp_t; + + /// `GFP_KERNEL` is typical for kernel-internal allocations. The caller requires `ZONE_NORMAL` + /// or a lower zone for direct access but can direct reclaim. + pub const GFP_KERNEL: gfp_t = bindings::GFP_KERNEL; + /// `GFP_ZERO` returns a zeroed page on success. + pub const __GFP_ZERO: gfp_t = bindings::__GFP_ZERO; + /// `GFP_HIGHMEM` indicates that the allocated memory may be located in high memory. + pub const __GFP_HIGHMEM: gfp_t = bindings::__GFP_HIGHMEM; +} + +/// A pointer to a page that owns the page allocation. +/// +/// # Invariants +/// +/// The pointer points at a page, and has ownership over the page. +pub struct Page { + page: NonNull, +} + +// SAFETY: It is safe to transfer page allocations between threads. +unsafe impl Send for Page {} + +// SAFETY: As long as the safety requirements for `&self` methods on this type +// are followed, there is no problem with calling them in parallel. +unsafe impl Sync for Page {} + +impl Page { + /// Allocates a new page. + pub fn alloc_page(gfp_flags: flags::gfp_t) -> Result { + // SAFETY: The specified order is zero and we want one page. + let page = unsafe { bindings::alloc_pages(gfp_flags, 0) }; + let page = NonNull::new(page).ok_or(AllocError)?; + // INVARIANT: We checked that the allocation succeeded. + Ok(Self { page }) + } + + /// Returns a raw pointer to the page. + pub fn as_ptr(&self) -> *mut bindings::page { + self.page.as_ptr() + } + + /// Runs a piece of code with this page mapped to an address. + /// + /// The page is unmapped when this call returns. + /// + /// It is up to the caller to use the provided raw pointer correctly. + pub fn with_page_mapped(&self, f: impl FnOnce(*mut u8) -> T) -> T { + // SAFETY: `page` is valid due to the type invariants on `Page`. + let mapped_addr = unsafe { bindings::kmap_local_page(self.as_ptr()) }; + + let res = f(mapped_addr.cast()); + + // SAFETY: This unmaps the page mapped above. + // + // Since this API takes the user code as a closure, it can only be used + // in a manner where the pages are unmapped in reverse order. This is as + // required by `kunmap_local`. + // + // In other words, if this call to `kunmap_local` happens when a + // different page should be unmapped first, then there must necessarily + // be a call to `kmap_local_page` other than the call just above in + // `with_page_mapped` that made that possible. In this case, it is the + // unsafe block that wraps that other call that is incorrect. + unsafe { bindings::kunmap_local(mapped_addr) }; + + res + } + + /// Runs a piece of code with a raw pointer to a slice of this page, with + /// bounds checking. + /// + /// If `f` is called, then it will be called with a pointer that points at + /// `off` bytes into the page, and the pointer will be valid for at least + /// `len` bytes. The pointer is only valid on this task, as this method uses + /// a local mapping. + /// + /// If `off` and `len` refers to a region outside of this page, then this + /// method returns `EINVAL` and does not call `f`. + /// + /// It is up to the caller to use the provided raw pointer correctly. + pub fn with_pointer_into_page( + &self, + off: usize, + len: usize, + f: impl FnOnce(*mut u8) -> Result, + ) -> Result { + let bounds_ok = off <= PAGE_SIZE && len <= PAGE_SIZE && (off + len) <= PAGE_SIZE; + + if bounds_ok { + self.with_page_mapped(move |page_addr| { + // SAFETY: The `off` integer is at most `PAGE_SIZE`, so this pointer offset will + // result in a pointer that is in bounds or one off the end of the page. + f(unsafe { page_addr.add(off) }) + }) + } else { + Err(EINVAL) + } + } + + /// Maps the page and reads from it into the given buffer. + /// + /// This method will perform bounds checks on the page offset. If `offset .. + /// offset+len` goes outside ot the page, then this call returns `EINVAL`. + /// + /// # Safety + /// + /// * Callers must ensure that `dst` is valid for writing `len` bytes. + /// * Callers must ensure that this call does not race with a write to the + /// same page that overlaps with this read. + pub unsafe fn read_raw(&self, dst: *mut u8, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |src| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then + // it has performed a bounds check and guarantees that `src` is + // valid for `len` bytes. + // + // There caller guarantees that there is no data race. + unsafe { ptr::copy_nonoverlapping(src, dst, len) }; + Ok(()) + }) + } + + /// Maps the page and writes into it from the given buffer. + /// + /// This method will perform bounds checks on the page offset. If `offset .. + /// offset+len` goes outside ot the page, then this call returns `EINVAL`. + /// + /// # Safety + /// + /// * Callers must ensure that `src` is valid for reading `len` bytes. + /// * Callers must ensure that this call does not race with a read or write + /// to the same page that overlaps with this write. + pub unsafe fn write_raw(&self, src: *const u8, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |dst| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then + // it has performed a bounds check and guarantees that `dst` is + // valid for `len` bytes. + // + // There caller guarantees that there is no data race. + unsafe { ptr::copy_nonoverlapping(src, dst, len) }; + Ok(()) + }) + } + + /// Maps the page and zeroes the given slice. + /// + /// This method will perform bounds checks on the page offset. If `offset .. + /// offset+len` goes outside ot the page, then this call returns `EINVAL`. + /// + /// # Safety + /// + /// Callers must ensure that this call does not race with a read or write to + /// the same page that overlaps with this write. + pub unsafe fn fill_zero(&self, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |dst| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then + // it has performed a bounds check and guarantees that `dst` is + // valid for `len` bytes. + // + // There caller guarantees that there is no data race. + unsafe { ptr::write_bytes(dst, 0u8, len) }; + Ok(()) + }) + } + + /// Copies data from userspace into this page. + /// + /// This method will perform bounds checks on the page offset. If `offset .. + /// offset+len` goes outside ot the page, then this call returns `EINVAL`. + /// + /// Like the other `UserSliceReader` methods, data races are allowed on the + /// userspace address. However, they are not allowed on the page you are + /// copying into. + /// + /// # Safety + /// + /// Callers must ensure that this call does not race with a read or write to + /// the same page that overlaps with this write. + pub unsafe fn copy_from_user_slice( + &self, + reader: &mut UserSliceReader, + offset: usize, + len: usize, + ) -> Result { + self.with_pointer_into_page(offset, len, move |dst| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then + // it has performed a bounds check and guarantees that `dst` is + // valid for `len` bytes. + // + // There caller guarantees that there is no data race when writing + // to `dst`. + unsafe { reader.read_raw(dst, len) } + }) + } +} + +impl Drop for Page { + fn drop(&mut self) { + // SAFETY: By the type invariants, we have ownership of the page and can + // free it. + unsafe { bindings::__free_pages(self.page.as_ptr(), 0) }; + } +}