From patchwork Thu Feb 8 15:47:51 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13549981 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 D6AB1C4828F for ; Thu, 8 Feb 2024 15:48:47 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 56E106B0082; Thu, 8 Feb 2024 10:48:47 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 4F5546B0081; Thu, 8 Feb 2024 10:48:47 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3702D6B0082; Thu, 8 Feb 2024 10:48:47 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0013.hostedemail.com [216.40.44.13]) by kanga.kvack.org (Postfix) with ESMTP id 25A286B0080 for ; Thu, 8 Feb 2024 10:48:47 -0500 (EST) Received: from smtpin19.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id D4D521C1968 for ; Thu, 8 Feb 2024 15:48:46 +0000 (UTC) X-FDA: 81769069452.19.9147D14 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.202]) by imf14.hostedemail.com (Postfix) with ESMTP id 02B30100023 for ; Thu, 8 Feb 2024 15:48:44 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=kjTY0GVu; spf=pass (imf14.hostedemail.com: domain of 32vfEZQkKCBMt41vxAH04z77z4x.v75416DG-553Etv3.7Az@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=32vfEZQkKCBMt41vxAH04z77z4x.v75416DG-553Etv3.7Az@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=1707407325; 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=MZxfREqmJLVb5yZOS5o3jZQJUZjkOkdbEVLWBie4ZLY=; b=gj5DPWX2tSDgdFKkWaNzKoITXT3HDxP9tg1h4ehox7XEueRzODuFsFhf9P7qkKmeerOlxh W562fRJ3o6yVa6Blg1c4GFGbas+LlbGiuc4rlvtSMklaafekt/HTkMM4vstGL1vQWsVQSj +PBrm6WaTBsVlsqgmiCs3sHZKr9GCPc= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=kjTY0GVu; spf=pass (imf14.hostedemail.com: domain of 32vfEZQkKCBMt41vxAH04z77z4x.v75416DG-553Etv3.7Az@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=32vfEZQkKCBMt41vxAH04z77z4x.v75416DG-553Etv3.7Az@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1707407325; a=rsa-sha256; cv=none; b=R7vF8p9r0EtqKiVciy+QCGYcDDLIDFCQR4a3YXkIyQnO5Q5HEbubXoK4dDWK/5jsUedExZ x3jY2S4Ios+239MDUMQGLLBDcESi9WRAhr2h6WETAeNxrY+M30GSiMhYgrIRv7DWo1p7Ow aSY3qdvHfiFUIsqItTHJ/TWU5kqLbWE= Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2d0a7ab562eso184111fa.0 for ; Thu, 08 Feb 2024 07:48:44 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1707407323; x=1708012123; 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=MZxfREqmJLVb5yZOS5o3jZQJUZjkOkdbEVLWBie4ZLY=; b=kjTY0GVuugwjMm5mh9oLNcT8LN2V89+NRBJfgjN1tUUVWdW0keANmmrB9rAGw8e4ig aC9aEYbL3VVqt5khImEgH52mA3exb0yrUIWRNV9Uo+HUHuuCCKGk+qtwSmSGX9UtkQKI Y283JySlTOyRf5HCsYv5yTnQVCwnLsO7qrdMZAbvMlUYXzIL4K0zW2oxK8tb8ZjqpCYo w3/iqyv8zh3fhQoaUR8QclkQwrz7b32KKWHzy8p/a/AJFfMUPYojH6OWkJuE7CWq4/sY E1yt5QJDfaWNrQtn0qi6F6afQfkpkr668bwdOJHzDMDikQGnBwDRzy2ROw7rMnuZkLE3 CXKQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1707407323; x=1708012123; 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=MZxfREqmJLVb5yZOS5o3jZQJUZjkOkdbEVLWBie4ZLY=; b=A+CjbLpQOchU6EOfiqJ5HCVRdA5ubSGnKodKfMFZTZRxORBhK6hsbbLv8FtuKw2vzi MJMEVNZP6f+aVeKJBvnwJ/qMZpXfGjASXjhCMuHKcx82NZicvJg6+7h9ZVTA2chFhJjf r/pbRozTf2YVxFLCHP0QyYKUtMdK53VflUdjz3DsSfCZIc4Skxi1INeHwjy/kNRmbQZB Kmst5V64oFrx+3PvqtotMZ/yXvDN4Nda0+ajjWoQku3TEnk0Xx7WKMGrZ4zK8Z9XImI/ B9wz7dhn+0QKxioqmVRl5UNPvJ3fe7Nb/82DWqEAp3VWdtS8z/buTn6ZLtlT9iZIANrV D5SQ== X-Gm-Message-State: AOJu0Yy6UGLCOn60tC9zV80FZ0FcXYrrTto/XOIHZza7Fkbh992b18WZ QH55HC3qJpWPDNYQD1jJJJecpqEmPa+n/oN0I5Df8G+3kYBxZZ6EVCQBfioPwaxxPshJHejltKI WZ8YqUbVpi3SpzQ== X-Google-Smtp-Source: AGHT+IHoGrfQzs+9yE0464QzK+HqTUKqSxG8JmHBnPR1HAtK83lpXzvLfwmFqpdg5OICpSu+CEBC8v6oauXpx0A= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:651c:542:b0:2d0:9072:e938 with SMTP id q2-20020a05651c054200b002d09072e938mr5249ljp.0.1707407322927; Thu, 08 Feb 2024 07:48:42 -0800 (PST) Date: Thu, 08 Feb 2024 15:47:51 +0000 In-Reply-To: <20240208-alice-mm-v2-0-d821250204a6@google.com> Mime-Version: 1.0 References: <20240208-alice-mm-v2-0-d821250204a6@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=15018; i=aliceryhl@google.com; h=from:subject:message-id; bh=9c+X+VCQkxS1WdW6d5i+iI8c8KAsrHFSOj7xqDOlk7Q=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBlxPfSev0FxgN6ijmdsQvYOv+UnwaPgSq7w41oD 9TKOdwIkJOJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZcT30gAKCRAEWL7uWMY5 RkD0D/9h4bQNWcQlVOexF5lW5P/AI5hzsNTtH8Hr3J45XHedWS8SEIyplKt5EgQsvWIyGObonCL qcFbtebNXaiTSayagTAtB7xc+ny4V7zKFPTI48Sac9Lls3gXzwbgc0udsb8tifotCF+1azMqb9P du2OXQ5UqzgBaLexCpjuPn0jTcgRw/zJwKwGR40+KnLON4ZYNtkt7Xo7K3Y60tbD4RU2k1btkNW qIV7VOwxmKg/80a/t2JHXkukZriX8j4Bo7vT2RWhRT18yybsn1nxLE8EPyj7gfyygf3tvxwHDkp ovt+SWNhO6KT8wo+IaYg8hDYpf9WNPlQf40A3ruWsn2Vfw9QwZCoJW/upYvvGqtTxJ65AWpTiUX GGNfpJcm0qLrCHa5DvMY20zQNw+yukGhF0+Bl6BJPXaAtMz5wq0guQDXNAxtYLBukKPOa47Skad jxTWuO45co3cDY0EqSA4r3Ve4il9NCetzpkDWUVISRU2s6OB56VC6fWbK1getbVrkDuMnSfY7xC S6mrQ7kj5a5MZkKFqcxeAnESQWcid/GqtfrERlzo22tFebTmst8e61T7uwEgBxeAfBwmwyE4p/1 qwitm1RdHnmKppq30Fq/bNdqNdTQHKt7SKqV3VnGtVol/zujHw4RUpNi4bfeCBLD7JzWVtdGCGG xoAGwzviOliOB0g== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240208-alice-mm-v2-1-d821250204a6@google.com> Subject: [PATCH v2 1/4] rust: uaccess: add userspace pointers 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-Queue-Id: 02B30100023 X-Rspam-User: X-Stat-Signature: qmkjd5wxjaxymqkc6d998gctfhy1i8nx X-Rspamd-Server: rspam01 X-HE-Tag: 1707407324-437801 X-HE-Meta: U2FsdGVkX1847tAS8ZTUMH9bkrEcDlUCZGQbXxmk0CLxrw41k7u/p6IeZVuDGfvnCgs2LWVGi8CZ5YOn0+IIvGJWoCuIfiFXkMeC4iQ2ygIcYG7dLEmYVWpFsnch9jfXZuyUBoNrPkV+Q9f2zY9UWRBKh6fR3i1bDqxRPS/XjZRozrwPZNErxXhTUHswesZCCtNMDl4CoC3N97cj5qOipgzIlg+AS3X2Vp7TQ2XXua55A6j0avgW31PfejIcOCZBabgWnLRydm2QzmEzemAA+2W9VTqiTQmGhQ4kV8HGkxy5eyymJlqomTTUc3zF4tFo1V/q855Wyh69/zHsI/Ljst7hUOTJlL8RlkttFyjQDFCsGFpwZB+D+Bc9sqrbWV5+lEadXGigTij/Ub2cPP8kjx8y7Z1HppZws2MK0uuP0VBrehxmkkIvTClDa7n3M4N2Pjz6XNMqgzER63h12Xl81gPf22MkSfbJ+0s6eiyBlRTa06hf6M1cPlCdaXUd5eVvZDvEfxKR4cYVv8elzs9pvoYxWMKeVIcvyeF/Hm9SyIt3WnF6UEmQ8b7ADmHTiIw4zqxOUlF6wPJeQnlz//GAhepCK49PBdZu/FiGinjsg0PmkHphMTZiZTeTO5dsvJFX3VZXZpzJIQmLJouzgHEcNPMXAZPKRuZUtkXZKuHHF6CQE0rbnpPOLcXaDu60B0MZVljGN2Ru5+vxsxWpoyZbCoM3rs05Jwktu3KnpclIMppeHpy/vN7KXhi9ea9kRqqFc/sIOf7eaV0Fc63yb5FpC3nuUq7HzgIG7wVJOhy8LxdYQdoG+zvNFbG4X/EH1QozJUEK+KUkGKNMNlAPIw0pVP2lLvuUcFuldAOMyovwxz14GK2A/ORqsdB2q6QDVhoX1vmQE7l9sA4MlbmISrm3bu9ks1kxyD8qxS7YIS4JA3NNBCy4OWeqzNUqzUSlTVKXfRaE06MrMOPXv1jSQtY IBXtmIyM Sb+9ctFDRv8hqKY8rdr14iP7OZxgFJjwIer6frvfwjmuYbaOusqfleovNjtoMboumnajMafBZvFAPSZYnlC29OtF95Rk+eNaS5oKuvC66FsBrD1d2e9l/34BdiQPVL0OyqPbqdMDQYQ7Zxm2zOlhKJWnfuIa+DqM4D6kP1e/8aNQUaTuyvp0qtsj/2PzDDxGxICEuLjwMEEzaqbRtefre26ax9DBPGP/T7sLkLOSVypWktbdBCz+YoKYiIkTyJohxGK90On5fCx4Wmf8zlKAe7EgokOOwDbYcm6IrC0RB698hWpIj8gjFZNjpVy+QahfIAyXH3jbXObIbK3MaiNaVBKXM7HB3ZegaJ8UY 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: From: Wedson Almeida Filho A pointer to an area in userspace memory, which can be either read-only or read-write. All methods on this struct are safe: invalid pointers return `EFAULT`. Concurrent access, *including data races to/from userspace memory*, is permitted, because fundamentally another userspace thread/process could always be modifying memory at the same time (in the same way that userspace Rust's `std::io` permits data races with the contents of files on disk). In the presence of a race, the exact byte values read/written are unspecified but the operation is well-defined. Kernelspace code should validate its copy of data after completing a read, and not expect that multiple reads of the same address will return the same value. These APIs are designed to make it difficult to accidentally write TOCTOU bugs. Every time you read from a memory location, the pointer is advanced by the length so that you cannot use that reader to read the same memory location twice. Preventing double-fetches avoids TOCTOU bugs. This is accomplished by taking `self` by value to prevent obtaining multiple readers on a given `UserSlicePtr`, and the readers only permitting forward reads. If double-fetching a memory location is necessary for some reason, then that is done by creating multiple readers to the same memory location. Constructing a `UserSlicePtr` performs no checks on the provided address and length, it can safely be constructed inside a kernel thread with no current userspace process. Reads and writes wrap the kernel APIs `copy_from_user` and `copy_to_user`, which check the memory map of the current process and enforce that the address range is within the user range (no additional calls to `access_ok` are needed). This code is based on something that was originally written by Wedson on the old rust branch. It was modified by Alice by removing the `IoBufferReader` and `IoBufferWriter` traits, introducing the `MAX_USER_OP_LEN` constant, and various changes to the comments and documentation. Signed-off-by: Wedson Almeida Filho Co-developed-by: Alice Ryhl Signed-off-by: Alice Ryhl --- rust/helpers.c | 14 +++ rust/kernel/lib.rs | 1 + rust/kernel/uaccess.rs | 314 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 329 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 70e59efd92bc..312b6fcb49d5 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -38,6 +38,20 @@ __noreturn void rust_helper_BUG(void) } EXPORT_SYMBOL_GPL(rust_helper_BUG); +unsigned long rust_helper_copy_from_user(void *to, const void __user *from, + unsigned long n) +{ + return copy_from_user(to, from, n); +} +EXPORT_SYMBOL_GPL(rust_helper_copy_from_user); + +unsigned long rust_helper_copy_to_user(void __user *to, const void *from, + unsigned long n) +{ + return copy_to_user(to, from, n); +} +EXPORT_SYMBOL_GPL(rust_helper_copy_to_user); + void rust_helper_mutex_lock(struct mutex *lock) { mutex_lock(lock); diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index b89ecf4e97a0..5a03aafcbb69 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -50,6 +50,7 @@ pub mod task; pub mod time; pub mod types; +pub mod uaccess; pub mod workqueue; #[doc(hidden)] diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs new file mode 100644 index 000000000000..f07821184bd6 --- /dev/null +++ b/rust/kernel/uaccess.rs @@ -0,0 +1,314 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! User pointers. +//! +//! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) + +use crate::{bindings, error::code::*, error::Result}; +use alloc::vec::Vec; +use core::ffi::{c_ulong, c_void}; + +/// A pointer to an area in userspace memory, which can be either read-only or +/// read-write. +/// +/// All methods on this struct are safe: attempting to read or write invalid +/// pointers will return `EFAULT`. Concurrent access, *including data races +/// to/from userspace memory*, is permitted, because fundamentally another +/// userspace thread/process could always be modifying memory at the same time +/// (in the same way that userspace Rust's [`std::io`] permits data races with +/// the contents of files on disk). In the presence of a race, the exact byte +/// values read/written are unspecified but the operation is well-defined. +/// Kernelspace code should validate its copy of data after completing a read, +/// and not expect that multiple reads of the same address will return the same +/// value. +/// +/// These APIs are designed to make it difficult to accidentally write TOCTOU +/// (time-of-check to time-of-use) bugs. Every time a memory location is read, +/// the reader's position is advanced by the read length and the next read will +/// start from there. This helps prevent accidentally reading the same location +/// twice and causing a TOCTOU bug. +/// +/// Creating a [`UserSliceReader`] and/or [`UserSliceWriter`] consumes the +/// `UserSlice`, helping ensure that there aren't multiple readers or writers to +/// the same location. +/// +/// If double-fetching a memory location is necessary for some reason, then that +/// is done by creating multiple readers to the same memory location, e.g. using +/// [`clone_reader`]. +/// +/// # Examples +/// +/// Takes a region of userspace memory from the current process, and modify it +/// by adding one to every byte in the region. +/// +/// ```no_run +/// use alloc::vec::Vec; +/// use core::ffi::c_void; +/// use kernel::error::Result; +/// use kernel::uaccess::UserSlice; +/// +/// pub fn bytes_add_one(uptr: *mut c_void, len: usize) -> Result<()> { +/// let (read, mut write) = UserSlice::new(uptr, len).reader_writer(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf)?; +/// +/// for b in &mut buf { +/// *b = b.wrapping_add(1); +/// } +/// +/// write.write_slice(&buf)?; +/// Ok(()) +/// } +/// ``` +/// +/// Example illustrating a TOCTOU (time-of-check to time-of-use) bug. +/// +/// ```no_run +/// use alloc::vec::Vec; +/// use core::ffi::c_void; +/// use kernel::error::{code::EINVAL, Result}; +/// use kernel::uaccess::UserSlice; +/// +/// /// Returns whether the data in this region is valid. +/// fn is_valid(uptr: *mut c_void, len: usize) -> Result { +/// let read = UserSlice::new(uptr, len).reader(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf)?; +/// +/// todo!() +/// } +/// +/// /// Returns the bytes behind this user pointer if they are valid. +/// pub fn get_bytes_if_valid(uptr: *mut c_void, len: usize) -> Result> { +/// if !is_valid(uptr, len)? { +/// return Err(EINVAL); +/// } +/// +/// let read = UserSlice::new(uptr, len).reader(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf)?; +/// +/// // THIS IS A BUG! The bytes could have changed since we checked them. +/// // +/// // To avoid this kind of bug, don't call `UserSlice::new` multiple +/// // times with the same address. +/// Ok(buf) +/// } +/// ``` +/// +/// [`std::io`]: https://doc.rust-lang.org/std/io/index.html +/// [`clone_reader`]: UserSliceReader::clone_reader +pub struct UserSlice { + ptr: *mut c_void, + length: usize, +} + +impl UserSlice { + /// Constructs a user slice from a raw pointer and a length in bytes. + /// + /// Constructing a [`UserSlice`] performs no checks on the provided address + /// and length, it can safely be constructed inside a kernel thread with no + /// current userspace process. Reads and writes wrap the kernel APIs + /// `copy_from_user` and `copy_to_user`, which check the memory map of the + /// current process and enforce that the address range is within the user + /// range (no additional calls to `access_ok` are needed). + /// + /// Callers must be careful to avoid time-of-check-time-of-use + /// (TOCTOU) issues. The simplest way is to create a single instance of + /// [`UserSlice`] per user memory block as it reads each byte at + /// most once. + pub fn new(ptr: *mut c_void, length: usize) -> Self { + UserSlice { ptr, length } + } + + /// Reads the entirety of the user slice, appending it to the end of the + /// provided buffer. + /// + /// Fails with `EFAULT` if the read encounters a page fault. + pub fn read_all(self, buf: &mut Vec) -> Result<()> { + self.reader().read_all(buf) + } + + /// Constructs a [`UserSliceReader`]. + pub fn reader(self) -> UserSliceReader { + UserSliceReader { + ptr: self.ptr, + length: self.length, + } + } + + /// Constructs a [`UserSliceWriter`]. + pub fn writer(self) -> UserSliceWriter { + UserSliceWriter { + ptr: self.ptr, + length: self.length, + } + } + + /// Constructs both a [`UserSliceReader`] and a [`UserSliceWriter`]. + /// + /// Usually when this is used, you will first read the data, and then + /// overwrite it afterwards. + pub fn reader_writer(self) -> (UserSliceReader, UserSliceWriter) { + ( + UserSliceReader { + ptr: self.ptr, + length: self.length, + }, + UserSliceWriter { + ptr: self.ptr, + length: self.length, + }, + ) + } +} + +/// A reader for [`UserSlice`]. +/// +/// Used to incrementally read from the user slice. +pub struct UserSliceReader { + ptr: *mut c_void, + length: usize, +} + +impl UserSliceReader { + /// Skip the provided number of bytes. + /// + /// Returns an error if skipping more than the length of the buffer. + pub fn skip(&mut self, num_skip: usize) -> Result { + // Update `self.length` first since that's the fallible part of this + // operation. + self.length = self.length.checked_sub(num_skip).ok_or(EFAULT)?; + self.ptr = self.ptr.wrapping_byte_add(num_skip); + Ok(()) + } + + /// Create a reader that can access the same range of data. + /// + /// Reading from the clone does not advance the current reader. + /// + /// The caller should take care to not introduce TOCTOU issues, as described + /// in the documentation for [`UserSlice`]. + pub fn clone_reader(&self) -> UserSliceReader { + UserSliceReader { + ptr: self.ptr, + length: self.length, + } + } + + /// Returns the number of bytes left to be read from this reader. + /// + /// Note that even reading less than this number of bytes may fail. + pub fn len(&self) -> usize { + self.length + } + + /// Returns `true` if no data is available in the io buffer. + pub fn is_empty(&self) -> bool { + self.length == 0 + } + + /// Reads raw data from the user slice into a raw kernel buffer. + /// + /// Fails with `EFAULT` if the read encounters a page fault. + /// + /// # Safety + /// + /// The `out` pointer must be valid for writing `len` bytes. + pub unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result { + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: The caller promises that `out` is valid for writing `len` bytes. + let res = unsafe { bindings::copy_from_user(out.cast::(), self.ptr, len_ulong) }; + if res != 0 { + return Err(EFAULT); + } + // Userspace pointers are not directly dereferencable by the kernel, so + // we cannot use `add`, which has C-style rules for defined behavior. + self.ptr = self.ptr.wrapping_byte_add(len); + self.length -= len; + Ok(()) + } + + /// Reads the entirety of the user slice, appending it to the end of the + /// provided buffer. + /// + /// Fails with `EFAULT` if the read encounters a page fault. + pub fn read_all(mut self, buf: &mut Vec) -> Result<()> { + buf.try_reserve(self.length)?; + + // SAFETY: The call to `try_reserve` was successful, so the spare + // capacity is at least `self.length` bytes long. + unsafe { self.read_raw(buf.spare_capacity_mut().as_mut_ptr().cast(), self.length)? }; + + // SAFETY: Since the call to `read_raw` was successful, so the next + // `len` bytes of the vector have been initialized. + unsafe { buf.set_len(buf.len() + self.length) }; + Ok(()) + } +} + +/// A writer for [`UserSlice`]. +/// +/// Used to incrementally write into the user slice. +pub struct UserSliceWriter { + ptr: *mut c_void, + length: usize, +} + +impl UserSliceWriter { + /// Returns the amount of space remaining in this buffer. + /// + /// Note that even writing less than this number of bytes may fail. + pub fn len(&self) -> usize { + self.length + } + + /// Returns `true` if no more data can be written to this buffer. + pub fn is_empty(&self) -> bool { + self.length == 0 + } + + /// Writes raw data to this user pointer from a raw kernel buffer. + /// + /// Fails with `EFAULT` if the write encounters a page fault. + /// + /// # Safety + /// + /// The `data` pointer must be valid for reading `len` bytes. + pub unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> Result { + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + let res = unsafe { bindings::copy_to_user(self.ptr, data.cast::(), len_ulong) }; + if res != 0 { + return Err(EFAULT); + } + // Userspace pointers are not directly dereferencable by the kernel, so + // we cannot use `add`, which has C-style rules for defined behavior. + self.ptr = self.ptr.wrapping_byte_add(len); + self.length -= len; + Ok(()) + } + + /// Writes the provided slice to this user pointer. + /// + /// Fails with `EFAULT` if the write encounters a page fault. + pub fn write_slice(&mut self, data: &[u8]) -> Result { + let len = data.len(); + let ptr = data.as_ptr(); + // SAFETY: The pointer originates from a reference to a slice of length + // `len`, so the pointer is valid for reading `len` bytes. + unsafe { self.write_raw(ptr, len) } + } +} From patchwork Thu Feb 8 15:47:52 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13549982 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 8CAF6C48260 for ; Thu, 8 Feb 2024 15:48:49 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 066A86B0080; Thu, 8 Feb 2024 10:48:49 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 015176B0081; Thu, 8 Feb 2024 10:48:48 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id DD4776B0083; Thu, 8 Feb 2024 10:48:48 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id C9AFC6B0080 for ; Thu, 8 Feb 2024 10:48:48 -0500 (EST) Received: from smtpin30.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 89A311A0EFC for ; Thu, 8 Feb 2024 15:48:48 +0000 (UTC) X-FDA: 81769069536.30.865EC35 Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) by imf23.hostedemail.com (Postfix) with ESMTP id A342C140002 for ; Thu, 8 Feb 2024 15:48:46 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=IkguGe7J; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf23.hostedemail.com: domain of 33ffEZQkKCBYw74y0DK372AA270.yA8749GJ-886Hwy6.AD2@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=33ffEZQkKCBYw74y0DK372AA270.yA8749GJ-886Hwy6.AD2@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1707407326; 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=1MPoST0g8AYkDBhG2VsbV1sslw+0urv81QcaeUn+juw=; b=Jzmy0Guu83K7UDNLue33TE5qP/wHW/Ol5UjdqGD/lPhNEGK/ZSqMTiQ3LXUyeAIZ/Ll1Na AHX920sjUqLWVxzxXIqptWlT2IunlJNuLWNLHim5biIir2uKU+0CN2Og+mwx+1l5D6Qchx 1IiD63KQ0w9GDouiVL0ZrXCjzOivbwQ= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=IkguGe7J; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf23.hostedemail.com: domain of 33ffEZQkKCBYw74y0DK372AA270.yA8749GJ-886Hwy6.AD2@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=33ffEZQkKCBYw74y0DK372AA270.yA8749GJ-886Hwy6.AD2@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1707407326; a=rsa-sha256; cv=none; b=uksQSr7P970gETxHw/SnI2qcYfvGFVUil7ZJZbHwF8JcLEAj3ppJhTwtzq8qVhO54xKRka Yc8Jer+53zoQoVMeBTTXzNncvOztbwsvDzrcHwBAZuofp4jZ2oTjMXA+ynbGt6iRgCW2Ru 5AgKz8eVjvzXCAw/7rFb5ckGsM1aglc= Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-dc6b269686aso3248283276.1 for ; Thu, 08 Feb 2024 07:48:46 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1707407326; x=1708012126; 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=1MPoST0g8AYkDBhG2VsbV1sslw+0urv81QcaeUn+juw=; b=IkguGe7J9Ekbj55ulSzTJq1Itu5gt3LqJHTKgTBHbiFk+oHDWg7br68FkEQdpPPF/M Hp6fN4zH8FttGHfpQOMTb2QOrmoStQZg9odwPlIKjannqN+8DqKLfgLk0rMYahqHT/Oz bUc2qABHSNEWHKZEEh4NkiqGtbuNLBdT9LjYw/+qY+jluJk59vyxc8cS6hZmrts6tqNq 1bwwKTBbcr6kUIPEDFGJ+i1yRM8vpkwkQoB9w719VnSr3uqqbvbgzPKo2oi4O0wfWbch /74rVbJw7RY8s/VyQWteGq6374U67L52Rsr10cPUm/Qyud8LVMpUB+aqgpCwjBnD0vLp Wj4Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1707407326; x=1708012126; 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=1MPoST0g8AYkDBhG2VsbV1sslw+0urv81QcaeUn+juw=; b=Q1mhMqtQF+SZ9R36B+u7dJoqgRjGoNysekNq9dnp7zJohNgHmVkCwvJyuNFWvMQNjm LSb+qSHunSWLs+p0a4fCVad4qFus/cCLRl7fXsZx800/0kcW1DRPYASM3i7YRpr8uDZQ clGpssLt/zLqhx37O3D2V3myzPCAlnSFUIT5yTWgfHsiKAn5DXAqDzVo3IKNj6zPJTNB sDXp+FotaRx8JDbHWMwn5khQeLgZ3vnnqE+V4BRkk5TNMbHpY1PIUEHEyeo5n1OHco3y CRcbpMvOfVG3cEiQxv7vzAE/6qK3JuGyC/9+IAulB2tfRoQLRh0T1TVeI80lvAkiuEI/ AwVg== X-Forwarded-Encrypted: i=1; AJvYcCWr6O0Uyy5mTec0vaY4GYmRs7j1LhHRRLylocpLA4awrvJ6B+sNmN2Kq2SUl9q1PuotcjfIa69B0XVhIJHWdEtl3Ns= X-Gm-Message-State: AOJu0Yza9Zqinjp2vmHxrQwtQwJUOHYI6StKHYTMWo2mjb5LvJAENigW Qw9OtP24v7YB3BbTIE1VdFPIEeqraM32EENwJRxx4eXXzJklw48bJsaRJbhFVltuNoXAMWIaBCB vyeOBE3yL9Fz6dw== X-Google-Smtp-Source: AGHT+IE8Nan1uCaJHug2RBjceERk4R9+9qTdLW2q08muXcPrNhxeAussQfhnPOBYaHjyNRTtMgh/P0qbCDqR2bA= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:1b88:b0:dc6:ec15:5f6f with SMTP id ei8-20020a0569021b8800b00dc6ec155f6fmr340204ybb.6.1707407325732; Thu, 08 Feb 2024 07:48:45 -0800 (PST) Date: Thu, 08 Feb 2024 15:47:52 +0000 In-Reply-To: <20240208-alice-mm-v2-0-d821250204a6@google.com> Mime-Version: 1.0 References: <20240208-alice-mm-v2-0-d821250204a6@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4643; i=aliceryhl@google.com; h=from:subject:message-id; bh=5Gt2wgkxBTJYGkfZMpeUeH1SE3k+76BKAUtR156EeQ0=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBlxPfTuQDsKBYaMhTNxSmNY7PLIkKVkVnXBgh2h FRUyBw0ZDOJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZcT30wAKCRAEWL7uWMY5 RrCTEAC0DaTqeHguZBQPjq0PPyT3rF4dgf8yp7QxrvoiztTXntK43kWYjtU6x4CoxRG+Lfp6NCx ahAklS4wQAQLPnwFB7n84XdxDQiFmRKJNiDdfrZtYj9+37q3KZnmt4B0N9TU2/tv2596QUrr7g5 8FHFh2cgpuJV3O8Gb9U2movzF0Y0EBrHeg7p8AhkHNs9taPgH7S885BL8gs2rLzgkPYKf1sNY/C 5hA4aJH/a9yzOjOWaRmFlkB1kZRm4KiftHLzWE3u3ZMHhfwXiLR9fMIvCjoKUcGfYAYHunM3gkc guKnoQhyh9Jo/b2AwXr5KVNQFbWpKIpRAFkieNgtgtxoFyYag+hQzN+8zEukWaMv/Tcw5nn2l7G fTgEJjZLgfS18WZg8tIiwBGCpb7CGApvnSE6czD3O116L7MaFZgsyQ18xEcrnwnisEh8jGkEpRS mcAYoaxEnBgCGDCF7wRrOWQGk60Sl2TD38A8wJYuhuz/XZ5kzXa0TAu7H4id2ZqjQ2Vt4E+07s6 ObN4KfrT1dPCAm9M80Bn1u4Emonb0v4S5nykU0Awlen1fu+wttxiLdNlG+zwcaHELAt39pm2Spf PfDE4plBBAgcYG75I1TyaKWvyIb0JcNlLzTdXEskioQXW+n0ByNOrNohTMoZoXiY2vxVWX0YcK/ CE7RtNd2PYweYRQ== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240208-alice-mm-v2-2-d821250204a6@google.com> Subject: [PATCH v2 2/4] uaccess: always export _copy_[from|to]_user with CONFIG_RUST 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-Queue-Id: A342C140002 X-Rspam-User: X-Rspamd-Server: rspam02 X-Stat-Signature: x55kycnhnndfzwyn7oyjeqj6bgufmkk6 X-HE-Tag: 1707407326-624538 X-HE-Meta: U2FsdGVkX19mZnrDVd0z4KGjDorjQ48F0eZAALL3kKTCqSIP1EzFwzRrbmIjUS/CrAxSbD/mEuVgy0v6ZtdWH//eC0xPfqT4wl+QIi/m89r/ydgJfCVILvcU8RmvPW+8g6FfVXHucBPgzOS5olP+H0SX6O618r5Eg3+FHotXZ1K27bNDHFyweNgn1lnpD1/H/+fyQOMlSvhY3+B8FeeIcVYIU9bUWKMLvmi+v0qgSHeVGZY48Dd1TmFBV6wnX2aNbmord8JZInrdoQJrxHtGURbakAYaXtHeVt/We+xJyDKYTb/oCDlh7U3dqj4DNqsSJPMvdhMCM9jsrwhDNpdfx36MdGiAVscLPpOdL14VkcDFM2+32K4oJORZY5KLeHrZMMu33mR5Ht83d3wsLKR0Q0UxnY86Fz6NzaPnQA+MnmJs2SDmaCqRjXS14VGjJRSIPWxMD5KFu37dVPvyRRqCk+JoDBfQbqytjuyxD0phq9YZTZLl+M+kMpRelrLQvpgT8e/NhujOJ7P5h3JV6XIJYr1HlmaKNjs+srB6jQ9ayd0C5Q0To8xHkP/xrPfrFGuDoL89sBQanKZMokSHhWvnnZxRyt3tY+SCjvMq63emcMYpZS52v3Y/mV7fk/fVa0r1Fha3V6pFT6Cp3DOINp05tq4uWprZA4/FDXvdBX4aRqYbquooCXYWSZU5CICmu6a4Ncaf54oPfjq/TSnr8ooFO+Ff4vnb+s1lmeYmxKX/7Ai9XR0pIlqgzOMAl02TU127ogf1O9Kxgj9ufhIUsFGFTgux+s1x05aeNMRdWdOUvt3wvo4dfwH4G2ps9yc9x2HML0mHK7vWtKYCQ9iop4w1uJ2PB1KTMNVK//NgQo6AuLsSbVs7LnDIA1c+6cgls0oMcnkonNvvbElUr1oZTOXz5KqX2NHCJqIwLuit68ihUVViijo4m6J3PokHwfrXUTK+wLSBKVgg9zsq6np4HRX WExIGryj wJ4cvsWAqBhf9hJKJTwfYCO4VvXssZBKgeO/nsOfbo561aSUWCuTWYXzC4bI1kbZ36iAuKS6YLHN09VOyCDqySJjs9bUnAoZbzXkSn29VMgvYjtHlCj9lE/0Ft1dWrbrU2kdMyDgKW1mH6yvb9fiVfgE2BuA7zeCahbotcdRtx4klhNYFb2YVbKoFQCAxqeEi1KdAAelen5TJJLWnCNv9JN05tlsGUO6D3GL6qdGqCM1t1JiTrH89SJC6Vd1e5ysMl3H73/iaX7SUwaP0BJDeaAZnxEQFfcGwZI+6DeXJIZFjxEgDb/hYIFGv31Hq2qtfv9kIBBCJGa8D1vcyoBG26/a26V/UnuFEAosalHLeZ3s4ikoC4+x1RmK9LUWWYVk2bwVNESZfMNb148fcC51Cy1bs++9LEVozll4IOdbLxDSRWFJ2qoW8DWHwKIO8LRRNtn2d+M+B1oLD2Tf0iFOOZhDvrfWBSctYzlgzkQDuo3xnNLHrnyPWuc9F7UxLh/IXKavxoTb/YLjiVzQbdbAA7pZmiqUXk/UUrpSmVRkYZoC0PImwwyxbmDQkriedvX/ZwXPJCJCVppAS7lGzfU5pMX9dpnV5aNzgWiNbWA+Ze6Lb9tuTb01U9lN8aQ6VTvfLkEaYaqbJr0WrGqBHZD4sVQKZLeBetWLbdjVCk4BcyAUTJgHaMAlQ1uqicD6JUgDwQSbdrWPAgSGxc5nMEfacgo04CLooVuN15L2jLDYhWSJy/i5lOKAOEamNCQ== 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: From: Arnd Bergmann Rust code needs to be able to access _copy_from_user and _copy_to_user so that it can skip the check_copy_size check in cases where the length is known at compile-time, mirroring the logic for when C code will skip check_copy_size. To do this, we ensure that exported versions of these methods are available when CONFIG_RUST is enabled. Signed-off-by: Arnd Bergmann Signed-off-by: Alice Ryhl --- include/linux/uaccess.h | 37 +++++++++++++++++++++++-------------- lib/usercopy.c | 30 ++++-------------------------- 2 files changed, 27 insertions(+), 40 deletions(-) diff --git a/include/linux/uaccess.h b/include/linux/uaccess.h index 3064314f4832..835aa175d0ee 100644 --- a/include/linux/uaccess.h +++ b/include/linux/uaccess.h @@ -138,13 +138,18 @@ __copy_to_user(void __user *to, const void *from, unsigned long n) return raw_copy_to_user(to, from, n); } -#ifdef INLINE_COPY_FROM_USER static inline __must_check unsigned long -_copy_from_user(void *to, const void __user *from, unsigned long n) +_inline_copy_from_user(void *to, const void __user *from, unsigned long n) { unsigned long res = n; might_fault(); if (!should_fail_usercopy() && likely(access_ok(from, n))) { + /* + * Ensure that bad access_ok() speculation will not + * lead to nasty side effects *after* the copy is + * finished: + */ + barrier_nospec(); instrument_copy_from_user_before(to, from, n); res = raw_copy_from_user(to, from, n); instrument_copy_from_user_after(to, from, n, res); @@ -153,14 +158,11 @@ _copy_from_user(void *to, const void __user *from, unsigned long n) memset(to + (n - res), 0, res); return res; } -#else extern __must_check unsigned long _copy_from_user(void *, const void __user *, unsigned long); -#endif -#ifdef INLINE_COPY_TO_USER static inline __must_check unsigned long -_copy_to_user(void __user *to, const void *from, unsigned long n) +_inline_copy_to_user(void __user *to, const void *from, unsigned long n) { might_fault(); if (should_fail_usercopy()) @@ -171,25 +173,32 @@ _copy_to_user(void __user *to, const void *from, unsigned long n) } return n; } -#else extern __must_check unsigned long _copy_to_user(void __user *, const void *, unsigned long); -#endif static __always_inline unsigned long __must_check copy_from_user(void *to, const void __user *from, unsigned long n) { - if (check_copy_size(to, n, false)) - n = _copy_from_user(to, from, n); - return n; + if (!check_copy_size(to, n, false)) + return n; +#ifdef INLINE_COPY_FROM_USER + return _inline_copy_from_user(to, from, n); +#else + return _copy_from_user(to, from, n); +#endif } static __always_inline unsigned long __must_check copy_to_user(void __user *to, const void *from, unsigned long n) { - if (check_copy_size(from, n, true)) - n = _copy_to_user(to, from, n); - return n; + if (!check_copy_size(from, n, true)) + return n; + +#ifdef INLINE_COPY_TO_USER + return _inline_copy_to_user(to, from, n); +#else + return _copy_to_user(to, from, n); +#endif } #ifndef copy_mc_to_kernel diff --git a/lib/usercopy.c b/lib/usercopy.c index d29fe29c6849..de7f30618293 100644 --- a/lib/usercopy.c +++ b/lib/usercopy.c @@ -7,40 +7,18 @@ /* out-of-line parts */ -#ifndef INLINE_COPY_FROM_USER +#if !defined(INLINE_COPY_FROM_USER) || defined(CONFIG_RUST) unsigned long _copy_from_user(void *to, const void __user *from, unsigned long n) { - unsigned long res = n; - might_fault(); - if (!should_fail_usercopy() && likely(access_ok(from, n))) { - /* - * Ensure that bad access_ok() speculation will not - * lead to nasty side effects *after* the copy is - * finished: - */ - barrier_nospec(); - instrument_copy_from_user_before(to, from, n); - res = raw_copy_from_user(to, from, n); - instrument_copy_from_user_after(to, from, n, res); - } - if (unlikely(res)) - memset(to + (n - res), 0, res); - return res; + return _inline_copy_from_user(to, from, n); } EXPORT_SYMBOL(_copy_from_user); #endif -#ifndef INLINE_COPY_TO_USER +#if !defined(INLINE_COPY_TO_USER) || defined(CONFIG_RUST) unsigned long _copy_to_user(void __user *to, const void *from, unsigned long n) { - might_fault(); - if (should_fail_usercopy()) - return n; - if (likely(access_ok(to, n))) { - instrument_copy_to_user(to, from, n); - n = raw_copy_to_user(to, from, n); - } - return n; + return _inline_copy_to_user(to, from, n); } EXPORT_SYMBOL(_copy_to_user); #endif From patchwork Thu Feb 8 15:47:53 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13549983 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 40456C4829C for ; Thu, 8 Feb 2024 15:48:52 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id BFD6B6B0083; Thu, 8 Feb 2024 10:48:51 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id B88036B0085; Thu, 8 Feb 2024 10:48:51 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 963C56B0087; Thu, 8 Feb 2024 10:48:51 -0500 (EST) 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 7F7916B0083 for ; Thu, 8 Feb 2024 10:48:51 -0500 (EST) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 3EA69A0F51 for ; Thu, 8 Feb 2024 15:48:51 +0000 (UTC) X-FDA: 81769069662.10.76F7433 Received: from mail-yb1-f201.google.com (mail-yb1-f201.google.com [209.85.219.201]) by imf11.hostedemail.com (Postfix) with ESMTP id 584964001B for ; Thu, 8 Feb 2024 15:48:49 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="e0/Qz4Jv"; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf11.hostedemail.com: domain of 34PfEZQkKCBkzA713GN6A5DD5A3.1DBA7CJM-BB9Kz19.DG5@flex--aliceryhl.bounces.google.com designates 209.85.219.201 as permitted sender) smtp.mailfrom=34PfEZQkKCBkzA713GN6A5DD5A3.1DBA7CJM-BB9Kz19.DG5@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1707407329; a=rsa-sha256; cv=none; b=NCGdO2oV0F1tgZfsjk225FOwUW1xDsp5OSg+5FLUKN7ae1Hdvuaer/QuDZo3lD3WJ2UAuH 0Y5FdWiCUpAAHxSw+TdMO6NRLQbx716125FkorB4Oahhj+zr/DbtNaJKYDYZGTyY8MxBEI 65hgtyW3bD4316PwUx6fyBLNyhMivK0= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="e0/Qz4Jv"; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf11.hostedemail.com: domain of 34PfEZQkKCBkzA713GN6A5DD5A3.1DBA7CJM-BB9Kz19.DG5@flex--aliceryhl.bounces.google.com designates 209.85.219.201 as permitted sender) smtp.mailfrom=34PfEZQkKCBkzA713GN6A5DD5A3.1DBA7CJM-BB9Kz19.DG5@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1707407329; 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=flngb/LA8uzIdl5igbJEwBtu/PZHJPBIGQxF8CY4PhE=; b=XwSZAYjDMkzgJgB1SvXW0A/Mel9oyfRBHamX9SOOxpLIPK4x7xbcPTPu3wqYESx3vPU/WT eHCgQHdPGaMm41w67P6ORXQEbyN1W6b2sJuUvU3sLov07/xJNT8jeJVkzKXXZfrrw+kl97 eXee9f1lKoRL525GLixKdtVgI2C4U2c= Received: by mail-yb1-f201.google.com with SMTP id 3f1490d57ef6-dc64b659a9cso3506215276.3 for ; Thu, 08 Feb 2024 07:48:49 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1707407328; x=1708012128; 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=flngb/LA8uzIdl5igbJEwBtu/PZHJPBIGQxF8CY4PhE=; b=e0/Qz4JveqDRf8LzupWNsmg1wTxfDcgUZ6O20Bs4Ln3Lkxt/928DG3wnO13qlTYQY1 X0MJKEfjO5JVMroWlptlRoKE0aKwN3vzJobLbmdQHS55duCcDjFhVL4XmZJ9GafL23Nd 6lVYLOALoa1T8EeRK30CeH9iyFrwIoUEZbwjBtn6KI+4exY1ryADlUZBXciSEEV6UD7y pUBtzDGmBFdgFJDMHZYb8BiETrPgGbWaWH6pMZ9/5tFF3FJbS4XxE7dWVkacJSmShhTI GkfmE4f0tZX/18NenLye+eL9MJyDh9h5VZEa/wcsFBU+l/mvKGbTMG2HKE7tdzh19ymk vh4Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1707407328; x=1708012128; 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=flngb/LA8uzIdl5igbJEwBtu/PZHJPBIGQxF8CY4PhE=; b=s8R8WbBmpXr/+bR/G+GF/f1pHdyOaq8EGrPhV4KJGiJnFBTlRkHgDq99GTPK8mGLqP YUSdDUx8K58xWhOjF2+P303ajPMAGd9jA58/C7zbG6lOUmfYD619IhJhhkJXRtPcLeD2 JRTLayXkobEV0/hGzjkac+8LA/EgFqg2GoZLhN3+4aIz3OjbvV0RMrk8MbDVeyMgnBFz RRYwX8cmQRGLCg2UjrBLjERXLferAyypkeITxDfIhEa4Nj6/i0Co2CsYglLI1N4pzn4X U3S/vZxlTO+xgDyVbk6pfB1IAPTsceyLpaVp3QonmCxLlsZUn3XEqLvXYJZUWnBjMeiJ 0ryg== X-Forwarded-Encrypted: i=1; AJvYcCVt7Cd+bOLAjvsBGsqHK+MXm1xwbsr9i3HhkFlb3R2tsg+YF7HCk+YEccwji1ZAone3WJbhf3qA5++if/nqu91PE7Y= X-Gm-Message-State: AOJu0YxN6zVgBWBGWHG5CdDKwv8M6Aix5eeiX6kh177CsJV05z91zahn eJ2r5roAyFBjx+DLxY1rKy5lW1J3xtAGKqxJ//Pzm6rsai3hQVGkV1BSQP+X/dB+jbR8qaLt8yl 4PneFxuSTcTTFFw== X-Google-Smtp-Source: AGHT+IHMYibPwpZ1RVGfZRX8AKyfUjB+V8DP1294a1PT4LdcHAG0vKr/hwfx2FdORpWP56VfcaTlftChXStJdqM= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:2186:b0:dc6:eea0:1578 with SMTP id dl6-20020a056902218600b00dc6eea01578mr2142900ybb.13.1707407328528; Thu, 08 Feb 2024 07:48:48 -0800 (PST) Date: Thu, 08 Feb 2024 15:47:53 +0000 In-Reply-To: <20240208-alice-mm-v2-0-d821250204a6@google.com> Mime-Version: 1.0 References: <20240208-alice-mm-v2-0-d821250204a6@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8719; i=aliceryhl@google.com; h=from:subject:message-id; bh=0g42SIX3ikqPGex8zhN70IRWhPIkHg4UCYLIFxFrPfU=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBlxPfTuOB96U/Lj40fHe9/xmDSElLomqfJO0cdJ oS0DmyNDKGJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZcT30wAKCRAEWL7uWMY5 RhsAEACE9BLmNvDC79FcWLHl6NT6PpjTFGYzMx6E6caaaLeVuWDJ6hhRZ+WM5x1fY68NMh4jTze sSCcxDNl9i1VJtQx5DN5Dvxw8ZOheHmix6sYH2u6nzHLQB+ka5eT56u/j1JvtGhjDE+JN/FtLLi Ku7kHIhYAmrNWQ71Ccpdl9TmLyg9b+F3CewVZsPpMR8BiA7M8IMyElJgb2Qy8QK+2UyagQNkNck vUAOTl7XVhllYkzh7aNkH++irEYMD7l1Pzq6i0ark1Oh5QLENHbz6p9GrtKtibC8Y31d+5ahqGQ ofpIQmg4DLhYUbcdbSgHuvaSvA2aNvb3I4hI/CHF3ItH5GKHeZ1II37sZzwtQIDhW/jx3tI7cM7 8fyu+b1eAvqo91GJyU9GKh6nyq+s/ft37vk5y7EsOCZVStX5wJkMW/fhvtHOQOQhIYU+yta/+3l gstUIDdyj8IP4sslt6FxHuMV/LEvQYzA/gw6mcz3plT02alcLP8CCjofOcmuw2A0U4BQkqvt4vf gdBiHa/nU9fHplEV10UtrZrwIchhpw29NoAzW9Log+xqOYBfvEJED/LBawfR0KQXivClAID7XvG 9u9w6oeJ6ZDYHCsI/brqznI4Um6gkWFG6YsPqFD1HyYPlG6VCo28FcfELn8as/Nz5rkkkTm8zjW 7WgDIC5F4sLMOdA== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240208-alice-mm-v2-3-d821250204a6@google.com> Subject: [PATCH v2 3/4] rust: uaccess: add typed accessors for userspace pointers 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-Rspam-User: X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 584964001B X-Stat-Signature: q53x4xdgoyi6cgiuj4wpfsoq7xymupc3 X-HE-Tag: 1707407329-30750 X-HE-Meta: U2FsdGVkX1+2GHhBdhgLMihiQRgMsdZNDy6Vuk8T30jetP0kuAXFL8x+lVbFhBnY6UvBFH96V0d6f02Qv6IW+0EqfuDs3pJJwGBoElvoZ8lxocreARDs7YffmE0tTTmfpxz5Zs+Aus885I88WSLLULfqP/ZYoBgg0oAIK2NcDYN3V0fH5BKqfrgPmGuGXdOWRxFM6BXs88QnyXFF266QgUrqZt8r+lYr4wQaGZLQh3qPzB+5wKqXPlL+Vnlf+W1cFQQ697X9jiiemh/QJKHiAfCOIlsDLpJ1dpzgXZgkK6KilxR3rg8LB3rcIQ8aCo9ObJSs3NdhUuv5sqDLvjkrW3jhn6JKK++VjwGzQ8Bwk1qESPJZv8xgk0nZWsgPzf6xXkqXZvA5MWUVgovDpt9THBG0gXp4VkoY6RDr2lGBl2OAx8n1s6AueFAnloAAwT8dJk7DfcMxHfSLLuNhyTipydTMp3+HFsi/97PED6NXKwIhvMpbcLdyPAIZ+DTHlt22gHQ97Wll4la437oRyN9QOwQ51d5KfZJEpfG9hB36O5c1mawI7F82ipoXlJGP2sro6B8LOXI0v96QrQDHa7s6OAqaVl5URU0o0XW0bDTDdFjcP/+EsJE2wOWlI5BjfUx0tmdasg73x+nG/z0nM0VJlcvXaoprlAwztQaCNlfaubnHKsRZ9iklWCo/Yasg9z8CTMqLBPGQWy+peOvIhAjdqLmaVjdDhAT6n8F6TgK2vGo8sGPN9FLdRFTHQRMKKGCYfFflNad4ehACD2VjZJH8sON6yzUeZ+c4L1zTkpTguyUGGSHb8RKdril4lsvF6HO8vOrumr2f/a0EAzvBemO9FSiBtgKORrOWoz3NcrUZZ2DPRRiKt4S5ESvO7H2ouEZhsJlsYbPyl6hRiXxB0lreQ/MEEIMVMdoLsBkhLev2zvTG3aCGPhY5CoZWA9TQxy6XQjKDsDrowiPJg0xqP65 BInetNDV 0jqhZTuLvXOpDaVRRoAe9BTm0PyNyTN04McKsMkzOrWY5Q3h+YbRo0yoiC+ZyIGrhdHVZdyQLVQK2Geckoo4CMSwNSewWraXLMPm3uXWPMOBKqv7VKS2UYac+NziF2a3WrkuWSpo5DWHCeMSa+RaBG0bcpN61HxPqUPuysBTeuDw6nF+gU3oU/ulkIOEppaQ5oT2SrRWRVibAi+1bjSUbp1MXr1bYtPCUiU+k0808Hm17Iqv8TKbF9PMHKE11hsaRL0D814wzJMPmgz+whjEXSYIKhWPTKMby65nbzzNWA4IuEWOlfQUZs1ijoLQD6InqGLDcPn6Yjbpwa7rzIQ6db3nxKPn490UtFxrEEUMMZxTjg3iQOHJQPj1eL9KIFs+9FTDOc5hXIPHTyax2/OBO+7wizyDb1rjMZRuDj+NMXLigajyzepYmjlI0oRlDLMzVgqctgNbCPmZh6OvJeAZLzZ1Wf/KZRSMcaQi24qGbNQM35V3ZlySj/Puh+VzyOiE+RCCjB0SOsF/4huM7GaM53FgTd2t+LxOJMyBHBi1sieYBnBXkXIz7jbmSSe3ur1AkdLve6wEzfkvkctz+PMtgdyo0NmxqDL6Vox6sLfVRQ+oiILQ3IACmGG/ClTsQfdP7jfNq8ugD+ITFqUgQFWskl0X7oUzarJ+LmKcnuxMfnfM9KY6z8kfViGt6NJkEEjX5nzJhJuYxPXP3HMRC89mH2yBpqBaCKFGe6VMx 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: Add safe methods for reading and writing Rust values to and from userspace pointers. The C methods for copying to/from userspace use a function called `check_object_size` to verify that the kernel pointer is not dangling. However, this check is skipped when the length is a compile-time constant, with the assumption that such cases trivially have a correct kernel pointer. In this patch, we apply the same optimization to the typed accessors. For both methods, the size of the operation is known at compile time to be size_of of the type being read or written. Since the C side doesn't provide a variant that skips only this check, we create custom helpers for this purpose. The majority of reads and writes to userspace pointers in the Rust Binder driver uses these accessor methods. Benchmarking has found that skipping the `check_object_size` check makes a big difference for the cases being skipped here. (And that the check doesn't make a difference for the cases that use the raw read/write methods.) This code is based on something that was originally written by Wedson on the old rust branch. It was modified by Alice to skip the `check_object_size` check, and to update various comments, including the notes about kernel pointers in `WritableToBytes`. Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Signed-off-by: Alice Ryhl --- rust/kernel/types.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/uaccess.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 141 insertions(+), 1 deletion(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index fdb778e65d79..33d175a3a6ed 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -387,3 +387,70 @@ pub enum Either { /// Constructs an instance of [`Either`] containing a value of type `R`. Right(R), } + +/// Types for which any bit pattern is valid. +/// +/// Not all types are valid for all values. For example, a `bool` must be either +/// zero or one, so reading arbitrary bytes into something that contains a +/// `bool` is not okay. +/// +/// It's okay for the type to have padding, as initializing those bytes has no +/// effect. +/// +/// # Safety +/// +/// All bit-patterns must be valid for this type. +pub unsafe trait FromBytes {} + +// SAFETY: All bit patterns are acceptable values of the types below. +unsafe impl FromBytes for u8 {} +unsafe impl FromBytes for u16 {} +unsafe impl FromBytes for u32 {} +unsafe impl FromBytes for u64 {} +unsafe impl FromBytes for usize {} +unsafe impl FromBytes for i8 {} +unsafe impl FromBytes for i16 {} +unsafe impl FromBytes for i32 {} +unsafe impl FromBytes for i64 {} +unsafe impl FromBytes for isize {} +// SAFETY: If all bit patterns are acceptable for individual values in an array, +// then all bit patterns are also acceptable for arrays of that type. +unsafe impl FromBytes for [T] {} +unsafe impl FromBytes for [T; N] {} + +/// Types that can be viewed as an immutable slice of initialized bytes. +/// +/// If a struct implements this trait, then it is okay to copy it byte-for-byte +/// to userspace. This means that it should not have any padding, as padding +/// bytes are uninitialized. Reading uninitialized memory is not just undefined +/// behavior, it may even lead to leaking sensitive information on the stack to +/// userspace. +/// +/// The struct should also not hold kernel pointers, as kernel pointer addresses +/// are also considered sensitive. However, leaking kernel pointers is not +/// considered undefined behavior by Rust, so this is a correctness requirement, +/// but not a safety requirement. +/// +/// # Safety +/// +/// Values of this type may not contain any uninitialized bytes. +pub unsafe trait AsBytes {} + +// SAFETY: Instances of the following types have no uninitialized portions. +unsafe impl AsBytes for u8 {} +unsafe impl AsBytes for u16 {} +unsafe impl AsBytes for u32 {} +unsafe impl AsBytes for u64 {} +unsafe impl AsBytes for usize {} +unsafe impl AsBytes for i8 {} +unsafe impl AsBytes for i16 {} +unsafe impl AsBytes for i32 {} +unsafe impl AsBytes for i64 {} +unsafe impl AsBytes for isize {} +unsafe impl AsBytes for bool {} +unsafe impl AsBytes for char {} +unsafe impl AsBytes for str {} +// SAFETY: If individual values in an array have no uninitialized portions, then +// the the array itself does not have any uninitialized portions either. +unsafe impl AsBytes for [T] {} +unsafe impl AsBytes for [T; N] {} diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index f07821184bd6..71a00177a4b9 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -4,9 +4,15 @@ //! //! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) -use crate::{bindings, error::code::*, error::Result}; +use crate::{ + bindings, + error::code::*, + error::Result, + types::{AsBytes, FromBytes}, +}; use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; +use core::mem::{size_of, MaybeUninit}; /// A pointer to an area in userspace memory, which can be either read-only or /// read-write. @@ -237,6 +243,41 @@ pub unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result { Ok(()) } + /// Reads a value of the specified type. + /// + /// Fails with `EFAULT` if the read encounters a page fault. + pub fn read(&mut self) -> Result { + let len = size_of::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + let mut out: MaybeUninit = MaybeUninit::uninit(); + // SAFETY: The local variable `out` is valid for writing `size_of::()` bytes. + // + // By using the _copy_from_user variant, we skip the check_object_size + // check that verifies the kernel pointer. This mirrors the logic on the + // C side that skips the check when the length is a compile-time + // constant. + let res = unsafe { + bindings::_copy_from_user(out.as_mut_ptr().cast::(), self.ptr, len_ulong) + }; + if res != 0 { + return Err(EFAULT); + } + // Since this is not a pointer to a valid object in our program, + // we cannot use `add`, which has C-style rules for defined + // behavior. + self.ptr = self.ptr.wrapping_byte_add(len); + self.length -= len; + // SAFETY: The read above has initialized all bytes in `out`, and since + // `T` implements `FromBytes`, any bit-pattern is a valid value for this + // type. + Ok(unsafe { out.assume_init() }) + } + /// Reads the entirety of the user slice, appending it to the end of the /// provided buffer. /// @@ -311,4 +352,36 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result { // `len`, so the pointer is valid for reading `len` bytes. unsafe { self.write_raw(ptr, len) } } + + /// Writes the provided Rust value to this userspace pointer. + /// + /// Fails with `EFAULT` if the write encounters a page fault. + pub fn write(&mut self, value: &T) -> Result { + let len = size_of::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: The reference points to a value of type `T`, so it is valid + // for reading `size_of::()` bytes. + // + // By using the _copy_to_user variant, we skip the check_object_size + // check that verifies the kernel pointer. This mirrors the logic on the + // C side that skips the check when the length is a compile-time + // constant. + let res = unsafe { + bindings::_copy_to_user(self.ptr, (value as *const T).cast::(), len_ulong) + }; + if res != 0 { + return Err(EFAULT); + } + // Since this is not a pointer to a valid object in our program, + // we cannot use `add`, which has C-style rules for defined + // behavior. + self.ptr = self.ptr.wrapping_byte_add(len); + self.length -= len; + Ok(()) + } } From patchwork Thu Feb 8 15:47:54 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13549984 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 17F4AC4828F for ; Thu, 8 Feb 2024 15:48:55 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 9B4A86B0087; Thu, 8 Feb 2024 10:48:54 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 967126B0088; Thu, 8 Feb 2024 10:48:54 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7DEB76B0089; Thu, 8 Feb 2024 10:48:54 -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 6899C6B0087 for ; Thu, 8 Feb 2024 10:48:54 -0500 (EST) Received: from smtpin19.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 3C68EA25FE for ; Thu, 8 Feb 2024 15:48:54 +0000 (UTC) X-FDA: 81769069788.19.3350185 Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) by imf08.hostedemail.com (Postfix) with ESMTP id 5C54E160006 for ; Thu, 8 Feb 2024 15:48:52 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=Bvya9TdZ; spf=pass (imf08.hostedemail.com: domain of 34_fEZQkKCBw2DA46JQ9D8GG8D6.4GEDAFMP-EECN24C.GJ8@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=34_fEZQkKCBw2DA46JQ9D8GG8D6.4GEDAFMP-EECN24C.GJ8@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=1707407332; 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=GkurjLr2KJ06Z3QEBJTajcXp1Fe9o6FdUY3dEd+eNLc=; b=qDbdLjSgG8OQXHIyw9mgXJMuuG06Y/MAxwNZyIESvMzwe6aD228l2KEzImMclKjgK47BU7 sD0SPSbT5XE64JjSkyD2drEu6EPrwJ17jZRltLtlmVDQgXX/xZYmIwd12TOmveeMwkL+hX /KNomZ7myGvcoP5EOdavCnzCTtdkouo= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1707407332; a=rsa-sha256; cv=none; b=TVubYKzgc7nkOD3dR6dpq991dq7VU+gbZc/R/HmCX9R8KBMvURWQFxpwAy6DPgxqfNPLDv Argxoy1JxY+6oziHQpyL6dsHyjZmMt5haDAFgAbNiBr/vGDY2iW98SW2u/G2SB/BJ/7TOm YmyIq/bsTTCJHrwQxpjk0N1kF2ueRvU= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=Bvya9TdZ; spf=pass (imf08.hostedemail.com: domain of 34_fEZQkKCBw2DA46JQ9D8GG8D6.4GEDAFMP-EECN24C.GJ8@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=34_fEZQkKCBw2DA46JQ9D8GG8D6.4GEDAFMP-EECN24C.GJ8@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-dc6b5d1899eso1327579276.0 for ; Thu, 08 Feb 2024 07:48:52 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1707407331; x=1708012131; 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=GkurjLr2KJ06Z3QEBJTajcXp1Fe9o6FdUY3dEd+eNLc=; b=Bvya9TdZCxSC3rYQQS9KisnzGOuersLXOvcGVpGK5l/PwSDbNi5Je2YYp4xy/KTZen N/8BmqMJuyJPdC4kWFQo0y7Jj16MGJhzubAZKO0YM8EgdnBaBW7xuV6Rdva2RscqHZ+v t2fTLuMVz4TDrv+3rBDQyCxf8xDbtdPQvR8h/w6NNkUeZDROO9ZQYICxZQudsvsZv0W9 W0WOt7UJj+whrXe/5d/es/pitzTV/wwd/hffFcOb9JyAewjMebtNsnfUWqLSaD3+VnNq RQfDivffVGbKyR6Qc6wZ7aqWcUsAewXJDH3yFkDaYnHYXK9iGZniCDUXPWN/EdHXLWwy NbUQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1707407331; x=1708012131; 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=GkurjLr2KJ06Z3QEBJTajcXp1Fe9o6FdUY3dEd+eNLc=; b=Pt7E36152MUvPSHLLy80fl7ZylDh1ANwdgq8pjhqmWgIDQdKIpMWDNBV9QZlD/cJxQ Je8NAThcDNF/cl+EiUztuUp9hqiMzRe3tn+IhYdrFChqsfFY8LQupz+6h6WDMbX7DMhl TKuFk5UZE8dGoJ1810uHX9sebef5t1b6Q9SdcBd2CJ9LH9+DJuMcgE/sGigaL6tRJJZ9 8BLhXu8bQFUW9cIcyhXKTQurXqgkgchrnI29h32qasIl3qBScE+yIAEeuTCrKSME9kZ9 +HzW0OdoHv46EIyAzvZ+vc158DGYY/y1ekyD3vfwjf3GqUpu1kvEmWADxgl1v57LBHVo 6rFw== X-Forwarded-Encrypted: i=1; AJvYcCWWY2zohkls/k1qB0KaE8DBu9fl+p+YeTQP0nkoFCC+nvPJlMgwMWWIPR+8S2ELfMcXLLfr2G1frnXt5LiRVVDyAEg= X-Gm-Message-State: AOJu0YzYSHAp7Z2YOgEYpeqONKoVzN98DNwXlyC1RgItMsGEvH2CWs1z E6KUJxelRdIRjV7A02zr0byByUBfpdkyVnmDKBD+Xuz4vS4d52IPQQNogto3shfCXMPU92o/A9V y1TM9Re6zy2zLIQ== X-Google-Smtp-Source: AGHT+IHZ8Dbrlx4mYSSqSheMjR9uVubqsUmkFF4PLNwGiatZwaa03r5iM1Rw5TJUkiKh9weUpG7CJqzo/gNibUU= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:100b:b0:dc6:e884:2342 with SMTP id w11-20020a056902100b00b00dc6e8842342mr764942ybt.5.1707407331450; Thu, 08 Feb 2024 07:48:51 -0800 (PST) Date: Thu, 08 Feb 2024 15:47:54 +0000 In-Reply-To: <20240208-alice-mm-v2-0-d821250204a6@google.com> Mime-Version: 1.0 References: <20240208-alice-mm-v2-0-d821250204a6@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=12755; i=aliceryhl@google.com; h=from:subject:message-id; bh=5kbsE/b/eSnVbSFqPFnEYkacZIQs8b+yemi8lEykeZw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBlxPfU67tCAf96rUhr77wodzJbxjoBZvA+pKp54 TdgXCe6UwyJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZcT31AAKCRAEWL7uWMY5 RgZ3EACMa2s3PKNHIdyO26oX3t0dPYuDrEmv0G8WCEpnJsXaaYMUb7IEmcf8cM74d1xUs/tQWRI GDHB+GiwnDcEIkB+itkR2/WdykfPSUwtijCjJ7IVuaeYKTXe5y4S4bzUslEOUwxJGScFo+CpHBM XcLgq9ilImTzGR29npE+iqbTwErklrUA9JOn7yvI2l7Qq8zJ5wZ+8NGwHKYLfegy5lIvsajIqnL J1claGaD8NF+HlnSg+/Vw6rIndTyvNaOnI5eVGgPgOfpzi3tmer0/gopsjWSpLYksDsrwM5DgOd KZFb6ob+vBpSlbr0Wg5NEl9s+TLBj8mJlgAt5wFUg08GbKIy+oFsvAZwNGSuglAHu7FEN22u2uv ZWsSLCee6/Zvh8jHTh6KZHJLsCajnYSnc5BRW/iSkuH7dp5hF8ooBca9PoZVFW4Lnvy9DX++95h IH4z1nWm/dIqVGhZf3semETumlANLlHPnp/Eos2URF0jnhtI6ct4VH3kCZ82FeH9Ia320wfSKd5 kNxx0BMOURevsseZTCpziAeiiSYh19gQFlT/JvkDsVR/mTzIEegLfpMdYvfipw+DuCseg86j3bM cBhoKYkgeqatoOGFECGxHZcXOKZDrefX5jylDTCJd844FstI3U8aCbLGToKO03HpbkiuSCTMROc qU/XnZ0uYKaEJng== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240208-alice-mm-v2-4-d821250204a6@google.com> Subject: [PATCH v2 4/4] 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-Stat-Signature: 8n1zeeoymaengbs4ofc8udkjfhsqnjgg X-Rspamd-Server: rspam10 X-Rspamd-Queue-Id: 5C54E160006 X-Rspam-User: X-HE-Tag: 1707407332-789036 X-HE-Meta: U2FsdGVkX19rgk7+EAgEyf3zqT4xjz9maMAvjpNquIa2VsyZrf9nTulzh8mE6foDMoKPM/eA8WzQ+wzYxwUFLT8YOsx4PRAeCDClMCssGKgbkaK/ztrgdqkRfjTin2iCt3hqYLy+Ca3VSIgxLvwzeLWTwjJhXcCxxTmUUD31YrxnvHMhjUTLstshrCWI4TFbQS7ueQs8DXqf8SNZcX6sDXnW/npTGiVuG5Fm5bIcmn1KWqjPe5OsoBo/hGp+HLX7b08/E8J09HLtISwpVu3JFNwLhePsDcNufgeLkk8z29HOeV8nvv++H8trya6voc6WfqYSc0CqRWc8R0ooELBGUHgNKTTIAuNw5KBwmig1ykFVdoIdDQqNXNuxuqvc0uzQbEAlUspmgyJep2+yKP53nsosuBcjUZPgI8ol2lEPyTKvFqtxv71t8Ga53Q5MgOAyA1c/VvNMgXDRtkV4aR58+kUQigsrLLrhDW0lzXZ6i9njdFvMFujodvpo3ExVeMnYynphTvUnur1WdPpCpu5DOWHY6mzlwVxm9xEfTy2uY/wJrqI7CHse7bWe3reoGVpDsZLwKZV1xChfnhHV7kOsidtT97QrXeC/YLrm9c4OIggZt8PpJl00gt1O8fqjzkKG+ePjVcZRVHU9T/SQ2npEJEh3ejj+LVU9fM7FxhBSkO5mvuodr/SZ56A8Ot6Sx990MJvVKYHRobOorRQd34eytdKP5v1Uch9zjb45shXL5Esg/9Cpl0OOZKo42YqOgQGiug3LdagtAMzRT1GKwpQMuNyAdVlq5tstwFQqCr3fOGcwGgC/kc5R9PYabekFNHcWmIeIvKYXO7kN00IDqZD/G2P/U6HnrxqwCpua/zGaptg3xSG7ipbVXyegElaEVBdLLM9y/xNap63s0YXCgLMDpUpRYHTXS3/ChrzVEB4NKdeyoxoRAcDvkJV6jdYct6k+rumAlh9PNagghmVc5xq 7Kx5ERlz QWNNGd0XQX2RRUUy9bB2xadU2hM80bp4UFsgbkQdQOdcJi1OZMzk6CNCrRtvZ7zoN5/oqieQRTiO/VPwG5xdN5UplF9hrd+TXw7UTszLVqK0i7Qit8aG7aqgloYVmheFjgYmu+GzIqdFi8+dfe1XSYsxK0PKvNwdbx9wkvQ2BmOmfB/NHw3nRevbNsarWUNu872mqi0rZiihxv4OmD2/+GaUx3Z5+ScTIgfkUIcDIvJzHovWkbE/8xV/PPvQQ7j8EaOM8QjGyg/zFl463ghFqhBm9X4nM5lt22Z/l81+ma0S3D9Wh6a4NyyBT4/hbTnan2t9tPkQmC39tzO/h7nthC5uVURLBdtr5DIsML2Gye2CUT83ycMIIYXD1H78xh0x4sfhOVNsdiBxhszuRC7m79Rmn3Zt2N/sdpZZ4kMSvvr6b4H8czwAVhbnkKHDAnWEqFBZShu3+h80HpLxZcf9+fcocFfm9GcrCJ+5dx/ofGrBLccXRNzElhD/eMWCer0WqIy35Krp3VwiYzyOF6nnTwPmCdcZ836T6SaS/2m4ioc65B3B6Fd20dYq0hT0ImdBCT9rgffrmWLoIGUnOfNFkSEQj6UroR83s/0aHTQuq6stGREAgt6H0S77JiLu6LcdZXUdGoJRAG6zmplf2uCsbtvbz/VVa2u+th/JAbAn2PT8aNMZ72pxxJMKXsPcic5BAzlOA3MQ3f8as/3XxNlw5mP/4NUEYDwTOBpDJ 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 | 209 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 231 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 936651110c39..b5b7fa7bd456 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -22,3 +22,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 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 5a03aafcbb69..59ee6dd6f7c6 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -40,6 +40,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..ac253744f94b --- /dev/null +++ b/rust/kernel/page.rs @@ -0,0 +1,209 @@ +// 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 = 1 << PAGE_SHIFT; + +/// 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 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, + ) + }; + + 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(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(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`. + /// + /// # 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) }; + } +}