From patchwork Wed Jan 24 11:20:23 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13528938 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 CD640C46CD2 for ; Wed, 24 Jan 2024 11:20:58 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5645A8D0005; Wed, 24 Jan 2024 06:20:58 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 514A38D0003; Wed, 24 Jan 2024 06:20:58 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 340BF8D0005; Wed, 24 Jan 2024 06:20:58 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 1C8E08D0003 for ; Wed, 24 Jan 2024 06:20:58 -0500 (EST) Received: from smtpin05.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id ED99EA160D for ; Wed, 24 Jan 2024 11:20:57 +0000 (UTC) X-FDA: 81713962554.05.AEB4B11 Received: from mail-lj1-f201.google.com (mail-lj1-f201.google.com [209.85.208.201]) by imf18.hostedemail.com (Postfix) with ESMTP id 04C121C000F for ; Wed, 24 Jan 2024 11:20:55 +0000 (UTC) Authentication-Results: imf18.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=sNNWsaH4; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf18.hostedemail.com: domain of 3lvKwZQkKCHMRcZTVipYcXffXcV.TfdcZelo-ddbmRTb.fiX@flex--aliceryhl.bounces.google.com designates 209.85.208.201 as permitted sender) smtp.mailfrom=3lvKwZQkKCHMRcZTVipYcXffXcV.TfdcZelo-ddbmRTb.fiX@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1706095256; 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=nrRXgrslTecg1zPHQayAhfd4pFFDrfAYfBFQIHxLZuo=; b=7hhfvvmikJxgNyUrw+ZW+bkPRKna8hezDs53OcZ0fB3aGJZ9OjONd/FADOzgBoZ/tHTQSK TTdJ0Szyrv1oTUWVQhranO+kzqQM3ErPp/V6zOJNGr9Wh7Upl/pV+SQp3GKuvq190DWxHf d+Vjuwzkp1SXd4p5uFJ9Dcv1cmbbr2M= ARC-Authentication-Results: i=1; imf18.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=sNNWsaH4; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf18.hostedemail.com: domain of 3lvKwZQkKCHMRcZTVipYcXffXcV.TfdcZelo-ddbmRTb.fiX@flex--aliceryhl.bounces.google.com designates 209.85.208.201 as permitted sender) smtp.mailfrom=3lvKwZQkKCHMRcZTVipYcXffXcV.TfdcZelo-ddbmRTb.fiX@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1706095256; a=rsa-sha256; cv=none; b=fkCzOfa3yzs4D0ay5IBIeO+Sn/undY5G/CP+gm1Yv017j25Pmr5rJHIlF8Ti7o+jJXpPlT beyF7hncOfgEOsj/vxSyoWbfCNSXJLUIam+1X92jdLYJD/yrYTjghuNlMhODv+eU7BaCwE YoMgzpmKCgA3wV8qYzkq8k5A/p6jP5E= Received: by mail-lj1-f201.google.com with SMTP id 38308e7fff4ca-2cf2a356efdso2705431fa.3 for ; Wed, 24 Jan 2024 03:20:55 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1706095254; x=1706700054; 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=nrRXgrslTecg1zPHQayAhfd4pFFDrfAYfBFQIHxLZuo=; b=sNNWsaH44KnvwNEvdC56GA7p1F32P/wrl+iA8huRYx3TTM8Chig5P+LTp4Y30DZqNh jnZ3fiqlgw7YHhkN3cfWxG/8SVsorZunq6MInH4M1c7hShfI3StmSA6csIWwSoAuKvnf utB1oVM7dSHevf9FEt7CSpMt6uVXVRetR1NTGWFqv416ZVcg8ITtEgJZ5jB8J0rBfCCN GISZ0IoLOWPFi/pNFgOYGUoJqdYPTzPTXMf4r6ejw4viSQfU4aQnN4zlhmduR+PMhDGA twKS/eKVRMMfYG9BUILZ9moH+TXw0hZ5ffDiXxHld3nMY6iP/PfNnJ/u1zxxaQ0G6WdO bW2g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1706095254; x=1706700054; 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=nrRXgrslTecg1zPHQayAhfd4pFFDrfAYfBFQIHxLZuo=; b=ruaZyN3M+ce0arPi3wT1Sh28TMR90hxlkJwO6MkGVm+pdRpUQjWreNaCaVhsJMKumX pPeMqwXOgzS/0cf6qQE/UP8JUGeDDuajV5DsGKwVk70jy/14658GQGph/Ti5PhcOTxBK hRD/15q9B18F2yDvnm3oA8Y2BM2stwB/46is1/RbQvlCbc7brlw77rUNAslTi9WkL5Vh rbRXd9xBob6qwNztyIUXGcQtmsKx/EmoSltfrCE6wSz8vAruRjFXCyUvzOyh2l2+OSRg wNGFXdAczygQgc8/2B3kbDomXGzpzVMs7LV4aWfNlpGTLNPy3zLvppgPrCC7jiTcA9hh 43tw== X-Gm-Message-State: AOJu0YxEpZfrOlnQT7ZaYodb+Gp6WLA0ebqx28nOVHum10DhXWOn+tz9 lSu4brva8Qlya2+WUD3RChWDwazg3ArA4KARC4cxne0OIYYeXjTd5pWUvE/sQ18/seHvdmihZkh mRSfTUBTCQW9yEw== X-Google-Smtp-Source: AGHT+IFz9frXq/IIhNd/HhEZJVxc8Tq5uNg7IKRPCngg3LDmeiDJeDNzAUzhLqCkahqINQMfwt0C69cmE0H04Uk= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a2e:bb90:0:b0:2cd:3985:eda1 with SMTP id y16-20020a2ebb90000000b002cd3985eda1mr2768lje.2.1706095254370; Wed, 24 Jan 2024 03:20:54 -0800 (PST) Date: Wed, 24 Jan 2024 11:20:23 +0000 In-Reply-To: <20240124-alice-mm-v1-0-d1abcec83c44@google.com> Mime-Version: 1.0 References: <20240124-alice-mm-v1-0-d1abcec83c44@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=11163; i=aliceryhl@google.com; h=from:subject:message-id; bh=N81WtFNSKMRQnbGYXHdbc93PTVhG91qfzypfB7FfqFo=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBlsPKK0JA8Zn/8fTWeul7MILwvqo4hqE5J1nIUM axDWW8fwGKJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZbDyigAKCRAEWL7uWMY5 Rm0kD/0aSmWKR0JUq7UIpj7N3VtpSj7KrkXZdy1amJr0u1avQQjFq9yE/PIj38sEdEE1suDOToU dRI9djXHUYa3Nh1omuaW/T142IK4B9+JN7HTLnGCIi4mTmPc16/EcNgLldkFxnmW3mAEfB6FNyX SVkN/B4txu6t5Z3qwC8ON3dnErm5qj6Yd0bM51mbJxITOmtvHE3JlRMS5Mz05cNGj6fRgJnaHNC /8WwfKDyaRUzo1P5anOxC1bzYH8+dYB56TMycgeD8IL3deDWGgc3ovtO4bQKkalQqmtM1B+y2af DTj+YLCQYkmaQQxY6XjSPyaHL9ta8Myz5T1EXkVCN9UCadPuJai9NGDIHFjKmpsZ0kzlKg2KoJm EW4CONBVL2c+WiJ9VTzMZtV3OccEd1HUWAsOOHrELChSIDcvSnmVIM6WFG9iTasYpSiLQO6umLa DmChChXddgMdofdcGox6ge6O+qV3YjYSwjfpcwmxs6jzsGd0r7Cvf4N+3763HAKLvsnbAKfS6n9 wpvhKCYomus0rAeH0gL7aEzDUAbNn3ihEIHeUgAchMnyQpF9TeEhJT1t6XsN0OujjtBfKAB+zNO uPfVktRS/SNitORyjGF2i9fUAuCBBJ78T1nt0jctO6JOUfPMnV7nLAl1zN4GYMyspyHvL+1yFAc 0qDOIiO7uKOBrWA== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240124-alice-mm-v1-3-d1abcec83c44@google.com> Subject: [PATCH 3/3] rust: add abstraction for `struct page` From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Kees Cook , Al Viro , Andrew Morton Cc: Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=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-Server: rspam09 X-Rspamd-Queue-Id: 04C121C000F X-Stat-Signature: fctnid9ih6bwxi89yibu4w7wpxg45a1a X-Rspam-User: X-HE-Tag: 1706095255-584843 X-HE-Meta: U2FsdGVkX19+ypD5P+fZJmQYn/PIqGYpLihUv2dKL44d1YOOv1ilUmGZKPGA+DyMg8whugP19dqCk0dsXAUpA/LnDmC9NeqEluI8kjGZf4B8VvqcJJNAF2c02UMP1zcUm1rE5H8wv2TZXNuYovapqdStqboJm+hw7gQM5TNd/JQybbqqTrUAWllsNukcJLt/TZMnYwb/EZjzTWSclnTxI+GchJCzQTbCKPpoHNf/vtB2bmV00rywYhmAJBRbm0TfD0nmQZJIfS6SGBFAKXk5U81sOt3PnlJDaHZAQ+fr/cUSH/lxL+H0a99oUGMYUe2r2KA6QgrCP15GUkWpTW1cXJ12lUwcy4nNDJfzU+dcFFIRRnhgTAWM4hnu23IM5z3AYQUf4AcrRruRO5Bu4JZoRvs7+FYOWezfBxQR9oqOtXfbR8VhsyBJy0RKl37LAdQbLJxkpGG04Pla0DwfnZezwyotMNOdwqtOljqGRspvJELcbjtyrkcVF8lka58agL84ogY4mzi9+uIYFdQtN1BjvCH8Nbg5F9S75tdsPHa2L2nnZpmdsKonXTDp2YdNdxJpRTmIUXocu+20kasLWyV5+ZiHbWFeIhYYYqUBD6qlOYt7V439LXOjvdfj7mkPyyx1oFr1i1DqAgOrDUqJ0q6Y3cQqa92bJ56jXTCLskWqgWmAANJhbKfCyTE5Wm8Yuqj6HZDsXv5xtmZnfYfiltUdPzREDzbiYD75KCjgW4m7NEDvaP8vtcLFJSns+qxD6Hk2y0xbyB243wjw/8lCr92933z+JfDmtFIlx4MoGQadAdEf2d/YaxWgsXW8e866y27aCAJ8x7qz00L+/4fGPi+H2cRaKqHOSQ7fmoYstjjXIYJ9b9LUNUOtfbEhAwspwx5glr7XVO7GWEEcqTrBacMo2SDvZycwqJ5W6hdPAMWMAoQNE3OMFvTsNEE8JqJ2IyAJdgCKEFnTlTBt8Bcr/r3 UKyTdCBT IvT39SiBGOOea0g8bUpP/TWLSlro2QcOKGG6FNxkYfquTzRKkfPaZgyx+f4ew6Ibm8zMSpjzM0yuEoeYDQUrJiVlFCaqaH4B1xSLWVrwUz29hmxE36moakf5xBwxeqE2x80Myvaz8CGYweN14DMLAZRI+TLTmxI8Yx7mTND5aPJjkGvgQmw5/s4dBj+od3osMiQRKHEXzQne5gavS3pytQhkaL2O0yUch854kY1LHJady98pRDpBZwrGy35d7lmdTvc/lywMnesX8SCBwViiqG+/fImII3qXmVkaIXXPJqYdtL3FVkih44cThqRxeZAqDBm4BJIc5iiyxVoTwIHy8/tVRrzLmxUdXKSOzi5XX6LIeYsnCNlOMe/9zhvt49y2qKuvjDYjPUXSTsmXa/ZfNvzDcP14iya5fQPrjgeFWXsYPWreZxsTLEjvqhpnZ4dZtLfkzTUwOYLCW86QbnbyT5HWbZaYpAuhoZynDjPs0ySQRCMDwo3X1HbLEejz4aRBJAoZmRydw2yhlcjiK01S4oS8zU+hjjuKXLIXqpiPnTX60OC05y2ke5k1MsELD12GN5O9pCJ3ow/wryilPklsbLCcRIikWM7tJePMrOHbyvgDJzVlwBe4JnHP4hNX4dai8eN+t82AxzGBLsuE= 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, and by introducing the `with_*` helpers to consolidate the bounds checking logic into a single place. Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Signed-off-by: Alice Ryhl --- rust/bindings/bindings_helper.h | 1 + rust/helpers.c | 20 +++++ rust/kernel/lib.rs | 1 + rust/kernel/page.rs | 176 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 198 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index c0cb4b05b918..7698f5b349d3 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -21,3 +21,4 @@ const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN = ARCH_SLAB_MINALIGN; 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 187f445fbf19..e6541119160b 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include #include @@ -127,6 +129,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 041233305fda..9f31faf88973 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -41,6 +41,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..f83c889d39e3 --- /dev/null +++ b/rust/kernel/page.rs @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Kernel page allocation and management. + +use crate::{bindings, error::code::*, error::Result, user_ptr::UserSlicePtrReader}; +use core::{ + alloc::AllocError, + ffi::c_void, + 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 = 1 << PAGE_SHIFT; +/// A bitwise mask for the page size. +pub const PAGE_MASK: usize = PAGE_SIZE - 1; + +/// 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: Calling `&self` methods on this type in parallel is safe. It might +// allow you to perform a data race on bytes stored in the page, but we treat +// this like data races on user pointers. +unsafe impl Sync for Page {} + +impl Page { + /// Allocates a new set of contiguous pages. + pub fn new() -> Result { + // SAFETY: These are the correct arguments to allocate a single page. + let page = unsafe { + bindings::alloc_pages( + bindings::GFP_KERNEL | bindings::__GFP_ZERO | bindings::__GFP_HIGHMEM, + 0, + ) + }; + + match NonNull::new(page) { + // INVARIANT: We checked that the allocation above succeeded. + Some(page) => Ok(Self { page }), + None => Err(AllocError), + } + } + + /// 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. + /// + /// It is up to the caller to use the provided raw pointer correctly. + pub fn with_page_mapped(&self, f: impl FnOnce(*mut c_void) -> 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); + + // 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`. + 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.cast::().add(off) }) + }) + } else { + Err(EINVAL) + } + } + + /// Maps the page and reads from it into the given buffer. + /// + /// # Safety + /// + /// Callers must ensure that `dest` is valid for writing `len` bytes. + pub unsafe fn read(&self, dest: *mut u8, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |from_ptr| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then + // it has performed a bounds check and guarantees that `from_ptr` is + // valid for `len` bytes. + unsafe { ptr::copy(from_ptr, dest, len) }; + Ok(()) + }) + } + + /// Maps the page and writes into it from the given buffer. + /// + /// # Safety + /// + /// Callers must ensure that `src` is valid for reading `len` bytes. + pub unsafe fn write(&self, src: *const u8, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |to_ptr| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then + // it has performed a bounds check and guarantees that `to_ptr` is + // valid for `len` bytes. + unsafe { ptr::copy(src, to_ptr, len) }; + Ok(()) + }) + } + + /// Maps the page and zeroes the given slice. + pub fn fill_zero(&self, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |to_ptr| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then + // it has performed a bounds check and guarantees that `to_ptr` is + // valid for `len` bytes. + unsafe { ptr::write_bytes(to_ptr, 0u8, len) }; + Ok(()) + }) + } + + /// Copies data from userspace into this page. + pub fn copy_into_page( + &self, + reader: &mut UserSlicePtrReader, + offset: usize, + len: usize, + ) -> Result { + self.with_pointer_into_page(offset, len, move |to_ptr| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then + // it has performed a bounds check and guarantees that `to_ptr` is + // valid for `len` bytes. + unsafe { reader.read_raw(to_ptr, 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) }; + } +}