From patchwork Wed Jan 24 11:20:21 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13528936 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 0C309C47DDF for ; Wed, 24 Jan 2024 11:20:52 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7D7A76B007E; Wed, 24 Jan 2024 06:20:52 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 75E906B0080; Wed, 24 Jan 2024 06:20:52 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5D9266B0082; Wed, 24 Jan 2024 06:20:52 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id 45D316B007E for ; Wed, 24 Jan 2024 06:20:52 -0500 (EST) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 045FFA2014 for ; Wed, 24 Jan 2024 11:20:51 +0000 (UTC) X-FDA: 81713962344.16.6AE7399 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.202]) by imf28.hostedemail.com (Postfix) with ESMTP id 12C4FC0003 for ; Wed, 24 Jan 2024 11:20:49 +0000 (UTC) Authentication-Results: imf28.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=RxdJxtbf; spf=pass (imf28.hostedemail.com: domain of 3kPKwZQkKCG0LWTNPcjSWRZZRWP.NZXWTYfi-XXVgLNV.ZcR@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=3kPKwZQkKCG0LWTNPcjSWRZZRWP.NZXWTYfi-XXVgLNV.ZcR@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=1706095250; 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=sOlUnGTFxhN3Wh+HyLrepLimkn/9swyxf47U8+mQUyU=; b=w/T6X8h7tMG+PwORS7DYSnBp9x2QPdsO6NAsv8Z0IKAjtK/ZM2BIwMq0I2IaRpaRkdvPYh E7jQcPNFyzOyirWXRjAiWBbGSO2OoHPrXuwCK+hjwdRApt423lTyb8801pp6Z2ocB2ZyKO tQ6rVxcQEjl+dSENy4XUWnYZ1yMG5Ag= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1706095250; a=rsa-sha256; cv=none; b=08Wz138BNyxWLr5pzidcjLW73wi7jn5peWA+ruhTRQIqjzl/YH7Lq6iKdBV1tV3T17sb5Q KINv4i05VVujrRrxHjwShiw7zRNtq7MuoV55+u50iL5u3awnKTGvSL3kj2KGkI/tL3xgXj bX9umq3L3bfY5Up9feWAFz5kltlph44= ARC-Authentication-Results: i=1; imf28.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=RxdJxtbf; spf=pass (imf28.hostedemail.com: domain of 3kPKwZQkKCG0LWTNPcjSWRZZRWP.NZXWTYfi-XXVgLNV.ZcR@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=3kPKwZQkKCG0LWTNPcjSWRZZRWP.NZXWTYfi-XXVgLNV.ZcR@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2cf119d6c7aso9857301fa.1 for ; Wed, 24 Jan 2024 03:20:49 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1706095248; x=1706700048; 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=sOlUnGTFxhN3Wh+HyLrepLimkn/9swyxf47U8+mQUyU=; b=RxdJxtbfWIkZp/0bUCkGhlnYK4yDpX4P2saVxsjHgXv7Bl6nK7xQIQIEuKUuocwuKA VMP1QeBmmPygY1hL+ue8RbV3Yv8hBNU+eWQPCP4NECEpVtHdwvoJsIgY/Y7JLSowvXxK hdvAQmK5a5qZvASJV8mNOPqsokjOQafS+oVmaO/M0xukvqQIK7DrZfIImc6k8Ld8HxU8 LRpWQ+FrbdYtIaYrA0ynZGVwdCbv7qz/DUZ0tIFGk0cS4xxEkPeeYSCrzqEQlDGDqzJ0 8sDEhJ0gj7NM9U6u9yJXCH0IpmamgKrZmeoCi+WEJtWS6R4+wD1xTmRR1WPAN5qUfiHr iu0Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1706095248; x=1706700048; 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=sOlUnGTFxhN3Wh+HyLrepLimkn/9swyxf47U8+mQUyU=; b=k00GJmletVz6S2s+5NDyGxMYoO40dadUzHGNWORuJ/cv74C7OjEFDUpBmFqPKbhA2L TUqJPEcM8/MN3iMYedxSJlBKgHIwNJapIVVBAZAO81AHFI4jwdJlRyej6Setg8lw4Nni LKEnsB/37YdsBGBtksyFKP2nyJZxj0tQ2SWBDGUAlKk6pLn9PDY+q/vDbq2d5jYO9vEi vZ9rvwi66pPgELNHzWOc6582vJhpATV1Kmios7vvo0UrC8nLzqxHLCBoXrO8X2YPjHvc sKskejioZUXhp4SETBKJ5MOVGzRy99/imV1g1XIGTKgmor3/LzAl0YJWf7BCR2JkY8Z7 spbA== X-Gm-Message-State: AOJu0YwjfQN9/6SlBu7G+w4Jh69IqvZSrRtCjtzfeKa7gk+i33vh9Uqf QSIsOC6eKqyhmXx8w1cThW0bdhMW2ljC+I5YYPzIHu4lcQoFP2lPeuVxx2PTuklQ3IesO7GTPKi UdR+dN3D5KPC0yQ== X-Google-Smtp-Source: AGHT+IFUYMF+5aVolcJmSgvYFnzvo3J5rdE3577wOO1E14UnlXcw+yKrbQDZV1pCgDhSzd5JSUABWHV4PUCu0xY= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:651c:b10:b0:2cd:eb48:b13a with SMTP id b16-20020a05651c0b1000b002cdeb48b13amr2362ljr.0.1706095248056; Wed, 24 Jan 2024 03:20:48 -0800 (PST) Date: Wed, 24 Jan 2024 11:20:21 +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=12466; i=aliceryhl@google.com; h=from:subject:message-id; bh=bddQOIHpQkNTHq5sjTLF1voN+vRIKosROer1IBiKH5A=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBlsPKIRQHGdOXUpFINztbIBSV3FRotWlg2iJOOs JAtY6uLI4CJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZbDyiAAKCRAEWL7uWMY5 RoEfD/91wS6JPiDUWmveLCNNVfA6anIc+FlQsNYh5zlWLLaxe+paLhsR0TrGWOogLdJ0IEH0jMU IJsgpxyuIHJ2gU5Wv5XJ/6T652mp+neY7FLhbDy1AwyaDjOtyZe9YG+lleVY+cCb6JfpCjaxQ4P OAVNBrtDzv/q7RDe3hJBJmc/qi1UJW7CaM0N7AkAHqVopOdi0JV3NUvYYJhsPtOSaWVNdHjw3Rc /xkUIhvoMY7HUz4660SIcOVUBgPQ+N4jwsZlX04QD+FjKi0ZPRchMCJOf622yKI8c41wmdO3df1 JnbwGrCqZ+0OJkDowIjxUddGR/jm98odkcYtso9gCXCuW36zQv/E9Aqlbi0qg0G1oM1msuV2B7C JZPkTcmL26OQXZe4H3N1wZblu6NK8NJmtZz+3uBhALhRAKwr2lzNLRdmlfKwUU0uqIpFREk6hLZ jNQOzCCe1nDDxMaexOZbX8TNzih7O6/k928AQFtMyzzAZDPlUysnD+MosOPxFxdV5HM0lfpL/9W nz2hVF8znvzWDXkB9Rt2J2uVFdJLkH6FKbXEPXkM/aeRQQVE3QMZmVDvuNj6b1RliB551Mm/ljQ LHlblg1e2PzRKPE09USqjXaol+QbwGQO4Of/MO8jkDxLXA/xE0vBkCLIk0zXRcK6rzE3V6CKHR6 FOwnyPzNQkC5n6g== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240124-alice-mm-v1-1-d1abcec83c44@google.com> Subject: [PATCH 1/3] rust: 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: 12C4FC0003 X-Rspam-User: X-Rspamd-Server: rspam11 X-Stat-Signature: fud9idtqx5eto93r9x1mcq5pjna8ngi1 X-HE-Tag: 1706095249-738281 X-HE-Meta: U2FsdGVkX19zeVOrNkWSK7uwXcNodxU8iWyUYoUhi82vzTjuGC7CruBJCdzVjPwHz00jvvJsB1YOSj/q6o4xiENtykRW5aOLDbhUGWdcMwfboaldlM5q45F+fOkOvbyOnhDrjNFKhUk4/2FLqkwYnQ5Was/3cN7BZe+4VSViOdfoynyYa9CDBmT6o+mAIjzSNARKYWRHzQ4ktfXVjxoaz3m5UZwhgmPwF0wZdUgK9XKDQ9qCuFDe+yDsRdk8QedAVG81bJdJNNfmtYp68gAqV7u2bVMLzQatCYs4jt9MzKOhOqwLAKrsba58swNi2y/AJuU/0df5TrzPT5EnNDBc1f//9So+A6t/GOtQuXCgemt3tNuAGXCfFdAGlXTvj54Ypy2gLvCaVIQtwiGraEMHauxSuIsEdmpZi5uLvwClSNhycvvpbQ60TOAHfBKUuF3pNE5+7yKpRG/W/9a3WqNsRIvI1Y9dO6IhgwEsBPRDO73r22Ssp9GT0LuS5gexwtQvnIseu9BpMr0nIrFRVyAPuncPGZW0188bEMsT6MTR2m+NfTFUwJvaYNqoH4YXea/4CSooQmS4LbYoVG31SoX21MWYuML+JlvWwrj5x6MOrd4C3xBPrRep0c3v/DuDbGQukfXu59xEQVVMfvE2gbVTz/e0Z3HRZMp3NKi6v954vHRD++5uyCdG2+VRLh6qvlaHfkra7bKUSndinLENZGo6Ph1E02Wz3ZIsy0GbQmsulw+a4PYuOxlbRmnsdRmralbwqplHkFOBlEkBqSGgDmhtwKlpl3biTyV+6d6b/pkiYyRthHBJvZhM9ytBysNDhg+xocO3x8xybAo6h/wdN3c5dQeCMrs+GTTK+a+roDE3tTz45zfgQfrB5Lo4dAVclNs/OlUJj5Cz0/nHQvvl+JxPgiMcnWgtRpwUGEor5zSjKGZXTvRLPjVZIP/QEeYxrFkO74z4QJY2nRuVmvirNly MRYVIfWe h9kvawcfsVBpgUacdBNX6f+vmo7zwmyTol68Krws89wQsE6orbX6pp8ZLPIg2fmrpHrDEkwDpE3O09vV8tsjeMrW3U80m97HNgMswnsb6LGUFAHqztwdDA7V2npHKclsXYeH4haXjjNB+YlSoCvpaATWIpjZEcIHMfdZVVblUu37VId1RYxZ0tomWEMuHJllcsPcZxVc8WCSBwudoeT4usY+TvTlLIZ/CGQnZpdX0o8az/cYih2a0mq+WMKL3czN9q8tvJtCkB3RQ61lv07qoZ6Mva32mZWooaRly3ARxVRVRiRwiYHr7O0oFq1HSzHR+6NDaJng2hYt3kiNdf33IQmypZnpsiH0S7WNLsAqhw8SzcV6jl/ot+xQ5dhtJcpnafHes/2GhNuEQWzdDmy6nL2ii/wDwAagWN6qK+9BcR7mAGiG/xPjLQan2CZuGWaMsaZdJavBClAOttvcKIJRj3AFoDNJ57Sn7c43pFpWzJtHPnrazuL9PmJxYxuhh/ouGHG9N6RXUmEe8FGbokrlYeikjCQAVW9sfbB0GieHsxG4uB35SlH7AczhwBud2TLT1QerL4zmEee/kbP5NkafnonhPabSdVCyfxhB1O9F+JRv1o+OMd/G4VprqMCTpb6Losx8mr6UiG3nTDYBtZI4yjYIJ9C5B0UgINFo5hYgvnKKHJEnXR3EA0rQYG8c9UK5fbddI 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/user_ptr.rs | 222 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 237 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 7ac39874aeac..041233305fda 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -50,6 +50,7 @@ pub mod sync; pub mod task; pub mod types; +pub mod user_ptr; pub mod workqueue; #[doc(hidden)] diff --git a/rust/kernel/user_ptr.rs b/rust/kernel/user_ptr.rs new file mode 100644 index 000000000000..00aa26aa6a83 --- /dev/null +++ b/rust/kernel/user_ptr.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! User pointers. +//! +//! C header: [`include/linux/uaccess.h`](../../../../include/linux/uaccess.h) + +// Comparison with MAX_USER_OP_LEN triggers this lint on platforms +// where `c_ulong == usize`. +#![allow(clippy::absurd_extreme_comparisons)] + +use crate::{bindings, error::code::*, error::Result}; +use alloc::vec::Vec; +use core::ffi::{c_ulong, c_void}; + +/// The maximum length of a operation using `copy_[from|to]_user`. +/// +/// If a usize is not greater than this constant, then casting it to `c_ulong` +/// is guaranteed to be lossless. +const MAX_USER_OP_LEN: usize = c_ulong::MAX as usize; + +/// 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, e.g. using +/// [`clone_reader`]. +/// +/// 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). +/// +/// [`std::io`]: https://doc.rust-lang.org/std/io/index.html +/// [`clone_reader`]: UserSlicePtrReader::clone_reader +pub struct UserSlicePtr(*mut c_void, usize); + +impl UserSlicePtr { + /// Constructs a user slice from a raw pointer and a length in bytes. + /// + /// Callers must be careful to avoid time-of-check-time-of-use + /// (TOCTOU) issues. The simplest way is to create a single instance of + /// [`UserSlicePtr`] per user memory block as it reads each byte at + /// most once. + pub fn new(ptr: *mut c_void, length: usize) -> Self { + UserSlicePtr(ptr, length) + } + + /// Reads the entirety of the user slice. + /// + /// Returns `EFAULT` if the address does not currently point to + /// mapped, readable memory. + pub fn read_all(self) -> Result> { + self.reader().read_all() + } + + /// Constructs a [`UserSlicePtrReader`]. + pub fn reader(self) -> UserSlicePtrReader { + UserSlicePtrReader(self.0, self.1) + } + + /// Constructs a [`UserSlicePtrWriter`]. + pub fn writer(self) -> UserSlicePtrWriter { + UserSlicePtrWriter(self.0, self.1) + } + + /// Constructs both a [`UserSlicePtrReader`] and a [`UserSlicePtrWriter`]. + pub fn reader_writer(self) -> (UserSlicePtrReader, UserSlicePtrWriter) { + ( + UserSlicePtrReader(self.0, self.1), + UserSlicePtrWriter(self.0, self.1), + ) + } +} + +/// A reader for [`UserSlicePtr`]. +/// +/// Used to incrementally read from the user slice. +pub struct UserSlicePtrReader(*mut c_void, usize); + +impl UserSlicePtrReader { + /// 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.1` first since that's the fallible one. + self.1 = self.1.checked_sub(num_skip).ok_or(EFAULT)?; + self.0 = self.0.wrapping_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. + pub fn clone_reader(&self) -> UserSlicePtrReader { + UserSlicePtrReader(self.0, self.1) + } + + /// Returns the number of bytes left to be read from this. + /// + /// Note that even reading less than this number of bytes may fail. + pub fn len(&self) -> usize { + self.1 + } + + /// Returns `true` if no data is available in the io buffer. + pub fn is_empty(&self) -> bool { + self.1 == 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.1 || len > MAX_USER_OP_LEN { + 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.0, len as c_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.0 = self.0.wrapping_add(len); + self.1 -= len; + Ok(()) + } + + /// Reads all remaining data in the buffer into a vector. + /// + /// Fails with `EFAULT` if the read encounters a page fault. + pub fn read_all(&mut self) -> Result> { + let len = self.len(); + let mut data = Vec::::try_with_capacity(len)?; + + // SAFETY: The output buffer is valid for `len` bytes as we just allocated that much space. + unsafe { self.read_raw(data.as_mut_ptr(), len)? }; + + // SAFETY: Since the call to `read_raw` was successful, the first `len` bytes of the vector + // have been initialized. + unsafe { data.set_len(len) }; + Ok(data) + } +} + +/// A writer for [`UserSlicePtr`]. +/// +/// Used to incrementally write into the user slice. +pub struct UserSlicePtrWriter(*mut c_void, usize); + +impl UserSlicePtrWriter { + /// 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.1 + } + + /// Returns `true` if no more data can be written to this buffer. + pub fn is_empty(&self) -> bool { + self.1 == 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.1 || len > MAX_USER_OP_LEN { + return Err(EFAULT); + } + let res = unsafe { bindings::copy_to_user(self.0, data.cast::(), len as c_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.0 = self.0.wrapping_add(len); + self.1 -= 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 Wed Jan 24 11:20:22 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13528937 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 427B4C46CD2 for ; Wed, 24 Jan 2024 11:20:55 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id BF54D6B0080; Wed, 24 Jan 2024 06:20:54 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id B7F386B0082; Wed, 24 Jan 2024 06:20:54 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 933AE6B0083; Wed, 24 Jan 2024 06:20:54 -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 7CB4C6B0080 for ; Wed, 24 Jan 2024 06:20:54 -0500 (EST) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 5F6F816064B for ; Wed, 24 Jan 2024 11:20:54 +0000 (UTC) X-FDA: 81713962428.28.A764AEA Received: from mail-yw1-f201.google.com (mail-yw1-f201.google.com [209.85.128.201]) by imf07.hostedemail.com (Postfix) with ESMTP id 8570040011 for ; Wed, 24 Jan 2024 11:20:52 +0000 (UTC) Authentication-Results: imf07.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=ao3ZXVNv; spf=pass (imf07.hostedemail.com: domain of 3k_KwZQkKCHAOZWQSfmVZUccUZS.QcaZWbil-aaYjOQY.cfU@flex--aliceryhl.bounces.google.com designates 209.85.128.201 as permitted sender) smtp.mailfrom=3k_KwZQkKCHAOZWQSfmVZUccUZS.QcaZWbil-aaYjOQY.cfU@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=1706095252; 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=yeYmyXZKazzZuN2hgbJgkgGVYq/XVAwngt0nzNHk5M8=; b=0X3gRLAZk6n9RKY3mwJ+DXx2O6yoFicFRwa2rYdVkwlRz+a4lFQsS2VEkcoKAHXkematMB 9rKsWsPuMJziwEqoneiRsj5c+tp2pohOjqO1f+XNhqNd8EWuZIzkDmFRbVUzt/8v+7aUNc 51KuNrP6BbmF6O5h5OjHZ2ZYMujHuug= ARC-Authentication-Results: i=1; imf07.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=ao3ZXVNv; spf=pass (imf07.hostedemail.com: domain of 3k_KwZQkKCHAOZWQSfmVZUccUZS.QcaZWbil-aaYjOQY.cfU@flex--aliceryhl.bounces.google.com designates 209.85.128.201 as permitted sender) smtp.mailfrom=3k_KwZQkKCHAOZWQSfmVZUccUZS.QcaZWbil-aaYjOQY.cfU@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1706095252; a=rsa-sha256; cv=none; b=z3rKyYpucxLX+ewscfOTqEGGDFZfy6i4TUSSQnQTodp53xuYzz+CJjyQPGNteUMuFd7IAP MSl/Cr8PO5wx6/H4xSzbFJFyIsokOGjsajrledYCkX/1ptMwTBMtgtZBxZYOHVJ2f5eLD3 1QYO7x1Za1pkTtXgH+THiHKhROLw7lM= Received: by mail-yw1-f201.google.com with SMTP id 00721157ae682-5f53b4554b6so79549047b3.3 for ; Wed, 24 Jan 2024 03:20:52 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1706095251; x=1706700051; 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=yeYmyXZKazzZuN2hgbJgkgGVYq/XVAwngt0nzNHk5M8=; b=ao3ZXVNvJ+B3h7ZvZHzM5XfWIcEJEQlpvJ9VWCK6PRLcsyGshJQp7qRGcE6zPI7PV6 yBrEIXbol3cu2pH2o4norbtwn5vVhyVkGefgh/WlUcyqGXIXlSs1cvOadBLJTBH6rwDU QSSIciI5ORb7n21nz8vMBTosSjc21LTL4jW5U3WQPTvOw0EwnRsPQxT/bfxsNEltObix 0/AnjiIVJiBQWBrRs0Kl0POtsZmkkNEUkU3NluGHcROKCSVVoy5yHXnRh/V99xHEGlCt fNn9rQhRQ60/PdWOBMc52yjrrvwpQLXQ6THxNgA/GC/9iibSANkK7hwa6mSRIw+NeVTE B6QQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1706095251; x=1706700051; 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=yeYmyXZKazzZuN2hgbJgkgGVYq/XVAwngt0nzNHk5M8=; b=mUssTk3ixpo3BzXNPi+0hRI4qFTXfNhP11851hv6YTrq6dhTEw88wvbCvWKsVf6Imz +P8e/GHwUdE9/hgswSb0blDNJcoTvEMX6R8HPqGH/LimIE9bmAVjtr8JphEIy56yC9gq eeR9Wn18TYKUy7gYRN/VLG30VU/4Sr1xxz3B7o+LdNJuDrg1TpnKCBGotyjy/H/tmMWj +BeNoyJka71/K/VNTkuTC2rUUUBmLvjKx/E86Ooif8xU9oNRSMbDY7j8d0VCT4RlwCi9 CB5EQ3SpIfmOqGVDmqGAJVmaCcxq0o3mTT3VwjjWxvQQkvsZ+9Fov52PR9LbyzmXGJ1d Z6xw== X-Gm-Message-State: AOJu0YxLCkTQV9NifwLaV+IO/eybAViexT9FnOciMe4ca+LT7TyQMTIh TXI5iR3RhY0KdhyGQwgDZP5MEokFAHmahQ+nYqPrxoNDrEDu3eHc/dbcoH0ubS49e/lnePU9tHV KJ4TzIxEwcMOk8w== X-Google-Smtp-Source: AGHT+IGjH/Ff2xSwSbT5vioutXPHVy7bJJQ3zau2ipxnPdyw1mlt022gceufBKa+5P6ckJhvnWfDj7xA0hX24cM= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a81:4ec3:0:b0:5ff:5135:ffcf with SMTP id c186-20020a814ec3000000b005ff5135ffcfmr211243ywb.4.1706095251533; Wed, 24 Jan 2024 03:20:51 -0800 (PST) Date: Wed, 24 Jan 2024 11:20:22 +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=9645; i=aliceryhl@google.com; h=from:subject:message-id; bh=vymGv46wM2XordLIDJAiR3VCTZsi5VESqwv8kajL3uk=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBlsPKJ3p0VhgMk8AKpCRyFubtzOao8ccYGTzkG+ +NZ+y3/eiCJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZbDyiQAKCRAEWL7uWMY5 RokAD/0TXFTgaEHIwdd+VZdCdJ3hpjT/gV/L0H4iqM+pzhwCg2FAbC2zAQUnoY5eSMPfazzRrkR b7I/ZDPT0xZAd2e+TLeiKEJSenYcP0bpVFnQjP1H8QJV1Y53i7lXVV/q8dpAXQ6fbbZvB98Pv06 Bky6MCWbbb8kgmCH14Jv5Vgxa3P83UrVdNlNE7XQu6dgORciRLcuuLi819gqMmRrVAUs1WMceGx t38dHV0F9KRYj2YIEebTN8BNvR+fxrT7RNu3SC6TAjA2p+V0TT4fl7thO2VlttP+UStglznTOL+ jkjEwOGg3VN9XVEPGbnODkUE6L+Pzhgb469AoYErW9epYGP6Com15uAiEsOA9IUmx82YYAopg8N jbVf/P67GLvzss8LprRUNrVQy4veFRwaZhoxrpJ3q7c2QIuDOfVgIXd59tJ+0+pV2KOIyL8F1Is MYjacF8CeI1cKXEUEx0SigY3tSQogrXTPRTb0XFs0yiviDd/mFnWSxCgzobtlYKJNTTcO50saJp 0uWo2Ni9PiyzXnZacb/bkx/GS1bE1V44v3tTlxbDTa2Djy2Cz6/TUEm2ntReBxDgepV4K/XgJnq 2yu18Jm11EpkRMTkio2ISHW42srkLhYsD9yZRMARFPWHqrjuZVamQIWBYq/rhZDz0wL8t5qOVb9 hSf4DHbGeXA8Tfw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240124-alice-mm-v1-2-d1abcec83c44@google.com> Subject: [PATCH 2/3] rust: 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-Rspamd-Queue-Id: 8570040011 X-Rspam-User: X-Stat-Signature: thh6ox7g15osw8g15wadqb6oqsmt471q X-Rspamd-Server: rspam01 X-HE-Tag: 1706095252-724394 X-HE-Meta: U2FsdGVkX19Vnmn5p9j0ROEhfALNB8i8dWw6GJA6+YhB/ONKHkKoqVLFnVm/Abk20B5Nwx/6XZhSBI2NsTuyng+XnSxxKDa44WTdkFH0Ucyj5AzTvCc8bOgqRZ8gEmUmw5NqTweMkT9jwB+j+pe2ncAC5tSvAELQgnfeU7Yl29MfrDaD7E7niIRxtVooBQFB1pbE0j/Cx4V7X3gztn2PtnVyM9kX1V+gS5hs0irdX/tXafLtNMEJYaQK7b3p2QdIPMGvjvVK76iUJ1Oy2irXA5E9/CHvbb6HlKOnYA81DE383L4A7cXliQMpr4KzTrfQMINSY2qKgC1nw3vqFS04RZpOBlk2IcasmAt4E8p4Qhv8rbYu8wcaD7F1RjKgwmvMi/OTK81NU7EAn8hs9JhBhVe/TB+vJpLGVVzxCwhgjXbJhq176Q7+6WTYaP8XrNcO2Sgfe9HkGqUKliA2iktbkpNFDFxTzmKK8Ik1OqwHLUS12ZfZ9e524kRIndbY1XEqQX9D64l+xlLoFGHBuHtflSgO3DNZwXM5O4TSbUSgANah9So0Q4Xr0pVOE2AHZKqxS+SRXvLMwxIoZzOh3Ly+LLRgSyfGr0luB2H8ngRbDX0JuR/EueGRR10ktD4OtVsE+kCIM5/abcjfXfAyCU79IirNTD12xa4KZHa+Us2RE9Z3o82MzZUJ5aqY0xPM0bm2K6uyxlvJ+XMlrudaAJAiy5T3oZYzJ5Xkg3+KH1ysYHqtmKkrfM7uZ1mTmnBpsMLLcB6pZakne3l9zc9QlyYDjADCDhnOKzzuRXf2AjBgOjsowj4g6OAfMIjNs9+Oa1yHRwETfETOz/yn4v5WKNc+3k4elJeff53nUIZ8W+ZxczQGAmi2ho0SM1VA+SJRql0d1UNf4QicOATss4aqrvwJgazrxUVStNKm+zWK2M7gkLwFRllLC6mFRdh7ERz6bEQdYItzN/A7nvLsKaSCX/0 7SjnnJqt ryTzkQ+Jk/2LoARPhO+npKdB+CpILP9q0Hn5mUYcJq3HzoCXne1cqzDnf5mafRqHDL/WO3QAyYu/V/Qf8g2OY11gZoozZRHFtnjuzIY3tPekyIFJbc4vnq5P9EYFxmv23KWH+sm61Uf5VuL0fPl/G2CddmHfIs9yJ1FBvIYxsy5g+hhujKgDfASwXajtPGguWhbIjol47VCz6XsYJcgEgUJOx1BIOH6pDUV2X52dH0uFldRVwuWEeL9B4GIKaYKAgTSBPxgOwBu7zs/rm7VbE41cOE6HUWeBe6Rzz64vHr5T8ShoNU0J8ZOj2fleUEO/NpzKAuuoaAd6ofDBKIjYe2NyuB0vtKI5HY7yD6x2g5JgJJiw38gvo69tADS5ComlM4YJgk2vChXsa2mfJRHosrgtdwBYohhxyEyzPcI1hqVUGArXoK8jaxXToQISmAF5yNwLGD5II1LMH37YmhNT1PQD68QH6HB9Ql6Yqfrlv6u4dy/k11ZeQNDFiskYFddf3wSx32kVEQGDvRIv/A62lIuZe9n45FlxOULMb0tcymL0BOQcruQPqvHU3qE0Q6ORN6GPj0wg4HwDk6sdIjicpMiKYIKzzuCTetFcV4TOYuahAbUCXw240j2aWrSF+cxbAhgDMyJLbIHRltjhP3Ux6XCTIi03yuEI0gfmIi1owRP7VJm14XHNRvkj8gCyOxKlN45zkIzdsfug129DbcPaPQZadpdPbdoGuBYVWKWEMuonWZRk= 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 Signed-off-by: Arnd Bergmann --- rust/helpers.c | 34 +++++++++++++ rust/kernel/user_ptr.rs | 125 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 312b6fcb49d5..187f445fbf19 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -52,6 +52,40 @@ unsigned long rust_helper_copy_to_user(void __user *to, const void *from, } EXPORT_SYMBOL_GPL(rust_helper_copy_to_user); +/* + * These methods skip the `check_object_size` check that `copy_[to|from]_user` + * normally performs. In C, these checks are skipped whenever the length is a + * compile-time constant, since when that is the case, the kernel pointer + * usually points at a local variable that is being initialized and the kernel + * pointer is trivially non-dangling. + * + * These helpers serve the same purpose in Rust. Whenever the length is known at + * compile-time, we call this helper to skip the check. + */ +unsigned long rust_helper_copy_from_user_unsafe_skip_check_object_size(void *to, const void __user *from, unsigned long n) +{ + unsigned long res; + + might_fault(); + instrument_copy_from_user_before(to, from, n); + if (should_fail_usercopy()) + return n; + res = raw_copy_from_user(to, from, n); + instrument_copy_from_user_after(to, from, n, res); + return res; +} +EXPORT_SYMBOL_GPL(rust_helper_copy_from_user_unsafe_skip_check_object_size); + +unsigned long rust_helper_copy_to_user_unsafe_skip_check_object_size(void __user *to, const void *from, unsigned long n) +{ + might_fault(); + if (should_fail_usercopy()) + return n; + instrument_copy_to_user(to, from, n); + return raw_copy_to_user(to, from, n); +} +EXPORT_SYMBOL_GPL(rust_helper_copy_to_user_unsafe_skip_check_object_size); + void rust_helper_mutex_lock(struct mutex *lock) { mutex_lock(lock); diff --git a/rust/kernel/user_ptr.rs b/rust/kernel/user_ptr.rs index 00aa26aa6a83..daa46abe5525 100644 --- a/rust/kernel/user_ptr.rs +++ b/rust/kernel/user_ptr.rs @@ -11,6 +11,7 @@ use crate::{bindings, error::code::*, error::Result}; use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; +use core::mem::{size_of, MaybeUninit}; /// The maximum length of a operation using `copy_[from|to]_user`. /// @@ -151,6 +152,36 @@ 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 { + if size_of::() > self.1 || size_of::() > MAX_USER_OP_LEN { + return Err(EFAULT); + } + let mut out: MaybeUninit = MaybeUninit::uninit(); + // SAFETY: The local variable `out` is valid for writing `size_of::()` bytes. + let res = unsafe { + bindings::copy_from_user_unsafe_skip_check_object_size( + out.as_mut_ptr().cast::(), + self.0, + size_of::() as c_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.0 = self.0.wrapping_add(size_of::()); + self.1 -= size_of::(); + // SAFETY: The read above has initialized all bytes in `out`, and since + // `T` implements `ReadableFromBytes`, any bit-pattern is a valid value + // for this type. + Ok(unsafe { out.assume_init() }) + } + /// Reads all remaining data in the buffer into a vector. /// /// Fails with `EFAULT` if the read encounters a page fault. @@ -219,4 +250,98 @@ 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 { + if size_of::() > self.1 || size_of::() > MAX_USER_OP_LEN { + return Err(EFAULT); + } + // SAFETY: The reference points to a value of type `T`, so it is valid + // for reading `size_of::()` bytes. + let res = unsafe { + bindings::copy_to_user_unsafe_skip_check_object_size( + self.0, + (value as *const T).cast::(), + size_of::() as c_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.0 = self.0.wrapping_add(size_of::()); + self.1 -= size_of::(); + Ok(()) + } } + +/// Specifies that a type is safely readable from bytes. +/// +/// 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 ReadableFromBytes {} + +// SAFETY: All bit patterns are acceptable values of the types below. +unsafe impl ReadableFromBytes for u8 {} +unsafe impl ReadableFromBytes for u16 {} +unsafe impl ReadableFromBytes for u32 {} +unsafe impl ReadableFromBytes for u64 {} +unsafe impl ReadableFromBytes for usize {} +unsafe impl ReadableFromBytes for i8 {} +unsafe impl ReadableFromBytes for i16 {} +unsafe impl ReadableFromBytes for i32 {} +unsafe impl ReadableFromBytes for i64 {} +unsafe impl ReadableFromBytes 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 ReadableFromBytes for [T] {} +unsafe impl ReadableFromBytes for [T; N] {} + +/// Specifies that a type is safely writable to 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 WritableToBytes {} + +// SAFETY: Instances of the following types have no uninitialized portions. +unsafe impl WritableToBytes for u8 {} +unsafe impl WritableToBytes for u16 {} +unsafe impl WritableToBytes for u32 {} +unsafe impl WritableToBytes for u64 {} +unsafe impl WritableToBytes for usize {} +unsafe impl WritableToBytes for i8 {} +unsafe impl WritableToBytes for i16 {} +unsafe impl WritableToBytes for i32 {} +unsafe impl WritableToBytes for i64 {} +unsafe impl WritableToBytes for isize {} +unsafe impl WritableToBytes for bool {} +unsafe impl WritableToBytes for char {} +unsafe impl WritableToBytes 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 WritableToBytes for [T] {} +unsafe impl WritableToBytes for [T; N] {} 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) }; + } +}