From patchwork Tue May 28 14:58:02 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13676937 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 3984AC25B7C for ; Tue, 28 May 2024 14:58:22 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B46E66B009D; Tue, 28 May 2024 10:58:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id B216F6B009E; Tue, 28 May 2024 10:58:21 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9E7986B009F; Tue, 28 May 2024 10:58:21 -0400 (EDT) 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 7A13A6B009D for ; Tue, 28 May 2024 10:58:21 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id A115DC05CB for ; Tue, 28 May 2024 14:58:20 +0000 (UTC) X-FDA: 82168110360.08.9A20F5F Received: from mail-lf1-f74.google.com (mail-lf1-f74.google.com [209.85.167.74]) by imf28.hostedemail.com (Postfix) with ESMTP id 732EFC000D for ; Tue, 28 May 2024 14:58:18 +0000 (UTC) Authentication-Results: imf28.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=IJw2jlEX; spf=pass (imf28.hostedemail.com: domain of 3CPFVZgkKCHsZkhbdqxgkfnnfkd.bnlkhmtw-lljuZbj.nqf@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=3CPFVZgkKCHsZkhbdqxgkfnnfkd.bnlkhmtw-lljuZbj.nqf@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=1716908298; 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=MbNhTCNPPg7usQjQRVAmhprE0uGhsuRXbAWwmmZLIiQ=; b=URx7g9Hd+dXOjyAzOt/Xz2qHaenLcmnmRYE6YKwk592QiHBbqO4lQg5Vs5rrpoqcC/IgEH iIVj+nwN98uJViWd1gpnIMULb56o70Fk76MhWwoTQrjZ5aTgACKgdt4rwmnB+HbEt0PfoN FXB4dvqMdMOvU7gC5JfB2q50odmOY9Y= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1716908298; a=rsa-sha256; cv=none; b=nmXf4pL68WQLBeNyPj+OEu9TybRJkinuX2gg4V9TJHBtG9neOKdlRzYCvxxpglqUswkQSj S73nr+J3n1XT0VVauk9XySDkomhlg2JZC6rOxMYmpka49KivJivW5Jw3bc8MtOCwHjENB4 OoSB7DZv0X49ZdHV06Nn8qkCzpn15bA= ARC-Authentication-Results: i=1; imf28.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=IJw2jlEX; spf=pass (imf28.hostedemail.com: domain of 3CPFVZgkKCHsZkhbdqxgkfnnfkd.bnlkhmtw-lljuZbj.nqf@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=3CPFVZgkKCHsZkhbdqxgkfnnfkd.bnlkhmtw-lljuZbj.nqf@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com Received: by mail-lf1-f74.google.com with SMTP id 2adb3069b0e04-523936877dbso934197e87.2 for ; Tue, 28 May 2024 07:58:18 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1716908297; x=1717513097; 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=MbNhTCNPPg7usQjQRVAmhprE0uGhsuRXbAWwmmZLIiQ=; b=IJw2jlEX8OMRix6iSKqbnORFJsTq3wmRsr5cIk2jjlj1cenJiH+JhmZgrRIED4TApC ld/6DoKPp6UK2TSaZH+j172eQh/PtGGbA76UlJOIOs04auHVeRVDX590FX5u3R0q9iKS cMiGKEtSwHirAk9cX7Qg2tG/Bb8uXhBC4A81RwYAcN8iHgH3UOrdD3PRkYsuBQreg1AL 5XqPYBvFh6ZOdpTXS6Gou7tOkVLqdjT4CuYSQ+IYXYsjUTK2GBfqqfWePc6wMf3vwanX NgZ2YXxCt0ujkQSGrHfZHqZEhFrh27+i4esPQSUS0L/3mlnOF5mJsywXLsF28mYqkHZn euLw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1716908297; x=1717513097; 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=MbNhTCNPPg7usQjQRVAmhprE0uGhsuRXbAWwmmZLIiQ=; b=J2jgC0okuxvJY0GaSYNfVn+lSbI44v8iaHGBAmUxqZ3WYkDrarx18X/PQ2KMuL5leu rHgM5fFGdoLxF5rzWbDZhdCgUAPMEdlvL/dhsgE0NJtdRV1i0uOqRx/PqRLf9wLH/Czc 3x5QvuScRQSza0awcayw8hdmI9bIO1WCPevMKTOYkU+0QOfrOz2y/R0mH2FUQCNG2Srs jPQBZOYRyWiLRiceCkPRtqJk4IWt1oq1BIvBAW5S8RCJmaggQdecwOnEuK0AvPwCauPp Y7FOtPYJualN8nvVM4HOico0WFlHfNpMzC41oYskeAgM+oaM8V50Hs61P4oLFFo4fsgM tZWA== X-Forwarded-Encrypted: i=1; AJvYcCUKEP5qW1tWwNxPcEpyPdvP61GpyAHutjZUMFbdvBw84xne+K89k9vABH8/DBoIwcWeweGN/xfxrlicGTWKKNLLDV8= X-Gm-Message-State: AOJu0Yz8ObA+Ti8qssOTCxt+9pc0Ai0In/dp9Rx6txv+X7ncyZQnOa7Q 1WVMbVBrxzqvwMJiOfP277ulHYeoDdDLjAE+YssHLjaL7Mc9rQDpcDi+58sRpUPtnrG+YP9VyhE FdRUJ/+PJYnCb1Q== X-Google-Smtp-Source: AGHT+IGKTzvYBVxuxp0VYfqRsp+nXS80+pOFrmh9vT+H19zk2AtK9i56hrMm1YftZM2YjXGr+riL5kwpUaFyUE8= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:4402:b0:529:ab01:8069 with SMTP id 2adb3069b0e04-529ab0182dbmr5757e87.13.1716908296723; Tue, 28 May 2024 07:58:16 -0700 (PDT) Date: Tue, 28 May 2024 14:58:02 +0000 In-Reply-To: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> Mime-Version: 1.0 References: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=15868; i=aliceryhl@google.com; h=from:subject:message-id; bh=xSbvVhrtFodD9MRESuXkcvT+XV4rvLfOM/6wExJZQsQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmVfEARqNIHiaKy6z316zm3PP79ctgWVQBabdCc l/fttkHreWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZlXxAAAKCRAEWL7uWMY5 RkTNEACIqh4LUos+sWpcJRx24EvZkwksLjc1ka4p+vlWBcvxp7SVkMsWwF2VtnKK8/bBDVOpbZV 2dsWXyio/j2tYPt6eDdqhMzhQnFfN3IKv+2r3OF1pbAWrgT80prHGMvDFpi+w4sNK6rHutxBKMq LM3W3yRYjI+4d7BkrgzmLszN3V44jFI9xj6VCviXzVHYoU/aO7tZGMqBizL+YiOetPxok1tKpGs 6JYq1WesiFFSJFNFNoEupEolZBNDNSYJVnEZ06uL8uyonk6yMU1NGmK4pI5mLO0mXk4kGIpwumr ZY7TPrbJM62OPgOHU0d5iTBCXG9M999lWdE5nreINZERUZv2FyQJo/zVnGkEe7nxmcf8WA7HzSW zMnyDACW1QooRkj3ZYxqloCMRiSMPWJsIrKFtFRxNP7kOUHj2DAU7wNCzsQiPBgUJBBhDB71Mbf k+YA+tiZwxLxamSC5UDoHhrIiobMqran1KtIKfihbIvfd7TlUFDn1Q/RC1Y4f5Mzkf7qMQRSWLj JXkb5/xtjvtzTeeSMP33sjCziO+zKGmnuBXvheSBs4OIzL+JqexdWTTIiAFJ+FVLr2Fvc8wpJJT DGfmORaBLX4NReBCJ/Ox9J/uR9/SV0Fu0DBVMWso2YJejWLADed2IEHxpx1uQtNn6EofSOLuYIB CrkyYbre7wKtgmg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240528-alice-mm-v7-1-78222c31b8f4@google.com> Subject: [PATCH v7 1/4] rust: uaccess: add userspace pointers From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj=C3=B8?= =?utf-8?q?nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , Trevor Gross , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspam-User: X-Stat-Signature: nks7m1aztkcqibt46w1ennafn13gxjyw X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 732EFC000D X-HE-Tag: 1716908298-504245 X-HE-Meta: U2FsdGVkX1/WqFwa/xXp6hu3Kkw22Hc7XqLXvbK+EzBZ9rAQrbGz0ECHby+ddWujQjvF5bVROeAom3DKMWprhdtqoDMyZJ7hOstnI0YtoLFOoAnwwQ0naLfOkbRr9tsJrjm56Cok1sagPT6b0oKq+SvpS7YzrfAvhM76nsiMF+/Ub0A3saDbCmdZ93zvQo55EjqseecvnTj4zpS0UEyGhQx6C4WSegucsLIrCS6bPcbio5gOJoi3xe4apcOkmqCWw3nwjKAiyJRoUmj+TIuuLpu2fzjEvysEs/e72AwUdnj8q3/dE/JNQA5yWtgLTYW34plAYtf39d/DKlR3l1qY5QndVOTjFnnUBm1HCjNDrpZPH5Ri3ZYU4cW2kuzhro1qRhZa9AFriwDosehvcmIagPr6dUa3lnkrVPgvSFFkLQp8d41W88vmWxhR2N0e6Gwdw51aHQpjvyjD9lD4oBusDhmxj0hFjOz/CoHr+FJrxXEX+pslFgrquzPY4M7rx1x9nT/bmTxI/faUlFD3jFG1qW73AupT7eF+Ceseyx0IoTQFuWQUYMGbxGw2wd3HWBvrVzbyWdqYj9dbVJcfBEVW92kj58L+l00OuVMZhIiTZpmwk8Json5+EcqUy6Y7gPSjIJuQcWZJlIYZgbiRLdMRe7jfPuNc2omWwTbnL7dHQm9xEoH7IsLs7DRfzknO1q2edNOlA0fIS1HikXKrAJnbAVhEe0/YHDMcHiM2BQ4iqA+1zApqowhWtHecPNd8G06cuDqtd08lJTTfGLc5wiaro53vc7kSmwlG+x2ciHOL8eCNOT5znvM14GstFLUpmK4Ga3Gt7SlkVP5cDND9l7uRtowxIUQ+SAFdvGuv4H3pGpAH6P4OQLdlRa4SdRg8dz2xfwy6/Qrq4nk0Im8ZVneXJLx5//GCpl7jdsdJmOTHGs9wEo0tEVVN8fyN0GgliLk0+GB2AYZDt088070nE3/ o79sHnJP eZo/eVFwCLeNmXcy1vG7QsQGVglMrVvd0WptG2MRVk9vw4X6hV5k9msBbNRp7RfewrBqghBRQpTKEs96D6667jgR/zEuRrnr8KxDaUiCipF1uI5BLSWzIdnPz2PI11oBBtUI2UH7cwILMw4QqFu3M7edwHawgrjC0WumSmQlE90+I5QbT6sI3clKyDVI02EyzDoSj4sukzD5QmiltPIF4TBMe5Pm8rtqCMg/GPPUdHCIXx/imzcBw94dkSM82sHSNfSm9MNKfKq+BeorkUq15HHJP9y/ulRxQu2JvgdUaLzz1ffI7RQp43nyowpnGgIyCSvs8UyNE+t34t2VTjQu+vekyci9YHe4SEoRYWNrirMM++WPrIi5V1b9f09c2J4g/VOuzh5cZWqZgXcuBoCRGbAMrg9Dy5GULrwAbyMhvf9f1Ea1Wah90hezxWM1g17Mok2XPRscbwk+8dSayCYj1VHXoyfjVv60IsiyalpVMe6dvd0LJy9GusaKdC7gsT7dQiKj6XbCGQF2Twiu/3U5Is99EdHTwloB2fM694NVA5VQS6ZVNWhIZfZp+3fUcuq+QE7+pKGl2qgmDuAgS8566LZAAHPEUmShc8FrIpJFTq60OyruEMYhGmIwv5LJz0gzQ+vURS/19rgTzl3Nfa5FFDhDZnS0ijkVGfwXzwYdQUdTbWpH2M3aGav1U9crg91CO4+/Xp2xwEctZPxWyNZpAaBzhVSNaGYH/OY5eX1Qpisu0Veq+mjs34PbopL5vvs8/3VapJYbJnbGQt9PEbaw0p2z5xD0v2SW2esbb 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: attempting to read or write on bad addresses (either out of the bound of the slice or unmapped addresses) 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 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 `UserSlice`, 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 `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). 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, and various other changes. Signed-off-by: Wedson Almeida Filho Co-developed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Trevor Gross Reviewed-by: Boqun Feng Signed-off-by: Alice Ryhl --- rust/helpers.c | 14 +++ rust/kernel/lib.rs | 1 + rust/kernel/uaccess.rs | 313 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 328 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 2c37a0f5d7a8..d6abe4bd45d9 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -39,6 +39,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 fbd91a48ff8b..767026db068e 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -45,6 +45,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..77957d7ec011 --- /dev/null +++ b/rust/kernel/uaccess.rs @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Slices to user space memory regions. +//! +//! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) + +use crate::{alloc::Flags, bindings, error::Result, prelude::*}; +use alloc::vec::Vec; +use core::ffi::{c_ulong, c_void}; +use core::mem::MaybeUninit; + +/// The type used for userspace addresses. +pub type UserPtr = 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: attempting to read or write on bad addresses (either out of +/// the bound of the slice or unmapped addresses) 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::{UserPtr, UserSlice}; +/// +/// fn bytes_add_one(uptr: UserPtr, len: usize) -> Result<()> { +/// let (read, mut write) = UserSlice::new(uptr, len).reader_writer(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf, GFP_KERNEL)?; +/// +/// 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::{UserPtr, UserSlice}; +/// +/// /// Returns whether the data in this region is valid. +/// fn is_valid(uptr: UserPtr, len: usize) -> Result { +/// let read = UserSlice::new(uptr, len).reader(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf, GFP_KERNEL)?; +/// +/// todo!() +/// } +/// +/// /// Returns the bytes behind this user pointer if they are valid. +/// fn get_bytes_if_valid(uptr: UserPtr, 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, GFP_KERNEL)?; +/// +/// // 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: UserPtr, + 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). Validity of the pointer is checked when you + /// attempt to read or write, not in the call to `UserSlice::new`. + /// + /// 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: UserPtr, 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 happens on a bad address. + pub fn read_all(self, buf: &mut Vec, flags: Flags) -> Result { + self.reader().read_all(buf, flags) + } + + /// 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: UserPtr, + 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_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 kernel buffer. + /// + /// For a version that uses `&mut [u8]`, please see [`UserSliceReader::read_slice`]. + /// + /// Fails with `EFAULT` if the read happens on a bad address, or if the read goes out of bounds + /// of this [`UserSliceReader`]. This call may modify `out` even if it returns an error. + /// + /// # Guarantees + /// + /// After a successful call to this method, all bytes in `out` are initialized. + pub fn read_raw(&mut self, out: &mut [MaybeUninit]) -> Result { + let len = out.len(); + let out_ptr = out.as_mut_ptr().cast::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: `out_ptr` points into a mutable slice of length `len_ulong`, so we may write + // that many bytes to it. + let res = + unsafe { bindings::copy_from_user(out_ptr, self.ptr as *const c_void, len_ulong) }; + if res != 0 { + return Err(EFAULT); + } + self.ptr = self.ptr.wrapping_add(len); + self.length -= len; + Ok(()) + } + + /// Reads raw data from the user slice into a kernel buffer. + /// + /// Fails with `EFAULT` if the read happens on a bad address, or if the read goes out of bounds + /// of this [`UserSliceReader`]. This call may modify `out` even if it returns an error. + pub fn read_slice(&mut self, out: &mut [u8]) -> Result { + // SAFETY: The types are compatible and `read_raw` doesn't write uninitialized bytes to + // `out`. + let out = unsafe { &mut *(out as *mut [u8] as *mut [MaybeUninit]) }; + self.read_raw(out) + } + + /// Reads the entirety of the user slice, appending it to the end of the provided buffer. + /// + /// Fails with `EFAULT` if the read happens on a bad address. + pub fn read_all(mut self, buf: &mut Vec, flags: Flags) -> Result { + let len = self.length; + VecExt::::reserve(buf, len, flags)?; + + // The call to `try_reserve` was successful, so the spare capacity is at least `len` bytes + // long. + self.read_raw(&mut buf.spare_capacity_mut()[..len])?; + + // 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() + len) }; + Ok(()) + } +} + +/// A writer for [`UserSlice`]. +/// +/// Used to incrementally write into the user slice. +pub struct UserSliceWriter { + ptr: UserPtr, + 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 kernel buffer. + /// + /// Fails with `EFAULT` if the write happens on a bad address, or if the write goes out of bounds + /// of this [`UserSliceWriter`]. This call may modify the associated userspace slice even if it + /// returns an error. + pub fn write_slice(&mut self, data: &[u8]) -> Result { + let len = data.len(); + let data_ptr = data.as_ptr().cast::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: `data_ptr` points into an immutable slice of length `len_ulong`, so we may read + // that many bytes from it. + let res = unsafe { bindings::copy_to_user(self.ptr as *mut c_void, data_ptr, len_ulong) }; + if res != 0 { + return Err(EFAULT); + } + self.ptr = self.ptr.wrapping_add(len); + self.length -= len; + Ok(()) + } +} From patchwork Tue May 28 14:58:03 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13676938 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 58302C27C43 for ; Tue, 28 May 2024 14:58:25 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id C337D6B009E; Tue, 28 May 2024 10:58:24 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id BE5D56B009F; Tue, 28 May 2024 10:58:24 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9E73F6B00A0; Tue, 28 May 2024 10:58:24 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 777926B009E for ; Tue, 28 May 2024 10:58:24 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 21A6E141316 for ; Tue, 28 May 2024 14:58:24 +0000 (UTC) X-FDA: 82168110528.12.C8C09B5 Received: from mail-lf1-f73.google.com (mail-lf1-f73.google.com [209.85.167.73]) by imf03.hostedemail.com (Postfix) with ESMTP id 2333A20002 for ; Tue, 28 May 2024 14:58:20 +0000 (UTC) Authentication-Results: imf03.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=OzXiguX5; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf03.hostedemail.com: domain of 3C_FVZgkKCH4cnkegt0jniqqing.eqonkpwz-oomxcem.qti@flex--aliceryhl.bounces.google.com designates 209.85.167.73 as permitted sender) smtp.mailfrom=3C_FVZgkKCH4cnkegt0jniqqing.eqonkpwz-oomxcem.qti@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1716908301; 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=TDs1IJHnbNwo/zETkdmKSImuTQj5Z+oesXCPuXUO86Y=; b=GpB47NHGCM2mxWftalYQdTCS5XUUFg8yyUrpeFgLx2ixihf1SRH7MdHOKhxKCOIsnJ2U1E 3U91HczYO7/uPz2vcMwsbkvqW9xRHflDUVpy3HnCpzxu51UUS6+d/GdwortJ6n/5HEslXe h10kKJqqxMm+JvBm99hzFDEk2dKYG70= ARC-Authentication-Results: i=1; imf03.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=OzXiguX5; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf03.hostedemail.com: domain of 3C_FVZgkKCH4cnkegt0jniqqing.eqonkpwz-oomxcem.qti@flex--aliceryhl.bounces.google.com designates 209.85.167.73 as permitted sender) smtp.mailfrom=3C_FVZgkKCH4cnkegt0jniqqing.eqonkpwz-oomxcem.qti@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1716908301; a=rsa-sha256; cv=none; b=jGC5XRfNU9a4+R6vSBl3H+erJm1VtrdYHjxQt+BLjIelJhbgyZnwtBcMIcpRUO8+XHEFNS KRYo+gxyqYKVv9czDwFN+7VWtJgReLmZtYUbH7YMyN5VR4/PAgLJIB4qlm8PwRPb0hQa7w Gi55PodP5P+LZFBSe+O2A2EtdTI3CIQ= Received: by mail-lf1-f73.google.com with SMTP id 2adb3069b0e04-529a5b739cbso461243e87.0 for ; Tue, 28 May 2024 07:58:20 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1716908299; x=1717513099; 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=TDs1IJHnbNwo/zETkdmKSImuTQj5Z+oesXCPuXUO86Y=; b=OzXiguX5W0tC901seBbtqH4NNpFJPW8ZPFsYUp0QtA/BNNylZbGf+UaAy3RHSCn7ZV r2EssO2tBp4bE7u6vvX1UrJxlW+ccaznYfjgLJ/ukFdkd9J5gypvxLQZcOShdhoDn55V Hr8VUTpbVlClhzd8PxyaaYbymtI2oo25S+an0Mloe6QSlzuJV9y3xjEoWVJUupvD6zJO gf3879hx7ZsOrgSJcU8haEA1bHDaVlPS6qPDy2sYeK++NsL+JYRBdmg7PL3IKCpH56iC hJs1gVJn+6CGN3ZQdPG5+921OVN01OMtsH9z9tpLyL8jd+tHNg0/s7BRQ9gvmB9RUL7d Acnw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1716908299; x=1717513099; 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=TDs1IJHnbNwo/zETkdmKSImuTQj5Z+oesXCPuXUO86Y=; b=fUCYkZRXNcKS33GqzB4T0I14/gkChJlcqD8v5muLUnv9/92IPnqs2VPItD2U04QsvA oVVggyGuHtPHaACNY2x8Y8lVoF6fnqiDrz31wXC0KT0ol5xyTq0RyqRfpXtBI6hA1gEj WIAQZKcip7So0vh54NgtEBpSgSHlkpeLK0jTVI+cvdoYHKUrhyfXKMOF6yNwLZ8VcBo4 CNnijCQSNDz2I6j2vaJDI2CbN0tU0lBSqqgfSB4Vv2rc+6YrNsqV/30ZC7skBfbxSeaG kih9wgMJGta7z1Vg2yqIX6inI638S1Sb5x56an+CBbfKbMrX82ioABUUuExMkdFkFtHh Dehg== X-Forwarded-Encrypted: i=1; AJvYcCUoqA8YWcPGr70G1ttVU1Ytm1gjiXtMiYwJflKOQZVfjxDJdhk5I+ETq7ZTq8iodYVsPTYOj/t2EHIP13ns2FJ7Vlc= X-Gm-Message-State: AOJu0YyDVSnyJf6Et2frDgEzpqptgUM1kNhZvj64+vbEgbrDUUgZYi6F nw+hjB5WCJeZu0tF+83fUIG41nu1U0hvVc3InU/OyFlNXPlTwOcmxK75KtJGQnY80bx1U0J9gFW K9p5EoQLMRJtFmg== X-Google-Smtp-Source: AGHT+IE0/smWA0nv7DnIzJunDnNDJqSN2EHjtIqsT2/sKJP0Nv5knZ9MVxp5tyeosgZSBFdOKEeD2mUHzkRd5q0= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:4508:b0:527:4ba:5c90 with SMTP id 2adb3069b0e04-527f16c29eemr16354e87.4.1716908299488; Tue, 28 May 2024 07:58:19 -0700 (PDT) Date: Tue, 28 May 2024 14:58:03 +0000 In-Reply-To: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> Mime-Version: 1.0 References: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5419; i=aliceryhl@google.com; h=from:subject:message-id; bh=yETbsBE1UqQkTUzr6kFMmtAy1ZCV9RovzSXiqjWQMC0=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmVfEBZqo9IvVPwPO5CrRJ9S+efkmY181jkflVc +WDKDaJ64KJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZlXxAQAKCRAEWL7uWMY5 RueSD/4wGfhLRtZZBSvagz2Tr+7o+akzMLKWhMQWrJ8eKjNds02I9WbzFLZQUGXQ+4RqiLvddU4 n8fLx3irk1ez8T2CEBs2O9zrruwTzwEi76SM9MbP9366gM1BH3RZV/48csVSYgCW6qUBSdVqE3r S4Yk9ttNOYeJxILvebO8goJJgqQIcmyI7J8JG7HlmLdq33wrdNfNwCvH1bkxj27/BzRUqOAnRdG 4emSEQudPjgRcQAUqYek+ZPl1t70K18AjpySXsRtbvdPk84CpoCMCUBmx0q9XIbEs96+qBvCjmU saj6XzYGCChZpUMn4ERwoPTvmnIrKCcc4PDYxImnLEi7TsXDbrEMBpP3bRIVjupFwEpskKqI6Oe 7fZ1KycxvBFAq+/Cp/wiYClD0TxxK41XS9oK/qRukR9BlMHf0zadfQlwnx4dbMLyxGk7Fl2hlwH G0Sc3XFE0Mkud0WOFEKQ+0l85lZq/vTdHxYqzjUCmhlg8nkMrF4IfRAdk9R7EZvdWy1ioq7PUMD xEsXLgsyhIdd3nDBtRIFjIXNkeXeMrgy/tnBwk/hCIIM+bFJcx3e/6JvMdWJVhIBI1SEYxLjzyB zxqRBpw1O+VulD9zCEJFIthq2o0jSikBBtciQBV+VZFr/debLYs26gcJTVHfDPh/jOhqRPdf/sO swwxMcc0sTnOzbg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240528-alice-mm-v7-2-78222c31b8f4@google.com> Subject: [PATCH v7 2/4] uaccess: always export _copy_[from|to]_user with CONFIG_RUST From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj=C3=B8?= =?utf-8?q?nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , Trevor Gross , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspamd-Queue-Id: 2333A20002 X-Stat-Signature: q9dtwwgwmamzrecetdm8xaa9noom8qs7 X-Rspam-User: X-Rspamd-Server: rspam04 X-HE-Tag: 1716908300-198066 X-HE-Meta: U2FsdGVkX18gnLuS+09ZcVIDmsJQ8NB7LbkNqqUZl3j5m1Z1/mkgHkFw1ByoRhGIcOmY8HKpyD534KseHVOEs4gBXynvsv/7WNOjOlc7ehGh7aIwBwud/Dw+OQRvI4d4k29lOoSuQGH/H77XNEqCQ2zmGLEGR+0j95i4NsCC8HxjAA4EPHUUFKqMFQEOykD9xa//OMSPx3GY4u+sJPfgJ6s3fSj13UnygF+BHvqRlf9gRyQVg/zlqWzRF8N/ZyzYwJaRI5PzUxrjZxrxSuWFbZU6Hezbc0s1C6J/+uD4/Dg84xEv0gF9pzP1MaMNcjWFGJ1lSbWYiQeoLPGMfZkWrpdd0C396AJKhk4m9hxqKmiIZL0cTa0ozVI+icx+ktUg7My437aLwCT7qQSmnPfXMvCSqs5UQ53BLKOzZ5o7ulPw5bJnbtD1fVFWb/32In4EMibcz9GrK9cq0cCdXkV8ZkB9Kd2LeTSJYoT6gyrByTTgZ1ifEPB+cNiCymNfcVmHzSvu4asFJkt4EdHE8/2tICK8VZKWC36HREPpkDQym54fLHx3QG8w6Sxno+sWUjdDPnfiDXKWBlTU1Gb9JuExrL0tU0n3+EQmVDRJYSDlH3YXPq74Sr2oun45Dn00dJAFW7Eh7ekngzkZrnD3vUeE33cOZKTJnueJz0fmtOJ/t4kR5zK25Cw6v4LRknK8JvUbBNkEw20PIkr1dAKQ6gSw3zMk+1Ng3mkHcYgcYvqbdOd8l4iO1DLzoABQik2r7blYh6FiL/2yw3NSGrSjcWV+w5l2hyEvG46xjuxZtbbUJok2o9eU1QUNfk4JU5H1615ir5o6A8Rom6MAbcCDxdjz4uYkPkQyaXx2ZkZp0An9PS3ECJHrs1YXcWnv1GCdD/TzR+RalfIy72LbQwSLXNSWybu9BlAIAqy6RJCkYbwDuVB6chr98b39JcYT7/yUgGXpPQqjH0PIHaId8oRMjQd q/E+Y7kl BVNdgdjn3Cf69SZZcNUCytWdK5jNrd51dm15Qwpk8E7/MMmyRVVmtef149GnhPDWN1GFjhWggRuaWw56Zx/eYW857BMfhVIQXtFE53Ev+qcMAFkde13ZoZOj39VOy6sLNsnJmnacuHg21G/5ySBu6JATB2SuzskyCjBb7RdiREzZpBszAhTJVCF/G6Eo0lNSk/V1nWA6D8jwjATsJHc+wluXAGMHwtnSJ+5jJjzW0Q9jIAQV+5PlygdOZ6tT6FxBEn07U+GhbYbzvKtcdVMiFdWfBcyoYto3bdCL332yGuP6tTuAe77ay+jlNjaqn3apmA9RVZlrjyVxao84E1t4CvyNFy872A0wTQ69Fub1llGUhY2On+AMWiH1F1deBipnjfw77SDXd/0wp+Ke+HBwqCyZzW0ji5knlsHPehgQbVbkKQ6SueBspEswejPyOu+f2lMUCiBSkz/heUCh7kpMPwHTyGgbRB2zcYYP/o+T+aREEqWevJilZ9P58tRDE3JPEYSiDfXT2v0QUuPUdbFyaXYHtnu6WuQzCg0xCcoP6eeFU7WLLn5j37LYQ49PGKaAHaciy9A1zvuFVaKe56auXVj32cdkbu24a2gIQjWcHJseykLr06bAByxWXPfJ/Oh/Z7JjphjZSthxCcMVCMGE0Wk0i2rw6KG9EN1f8fbEKANcWQkZ/Pfdu+G+kOCZFRGlhcN5Wgz99qzQOEXXj00hyTN3GYbpRc7PDYqMj6D42wxVqyixj6QIngVNc+cFzQ31AceDM+A4TptAdOfnN3yubOjuEKJOpWMteT3e40VJuRi8FQr8bxmo4pY+7UokrZLrpZgkUbO3Y+WcAp9A= 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. Alice has verified that this patch passes the CONFIG_TEST_USER_COPY test on x86 using the Android cuttlefish emulator. Signed-off-by: Arnd Bergmann Tested-by: Alice Ryhl Reviewed-by: Boqun Feng Reviewed-by: Kees Cook Signed-off-by: Alice Ryhl Acked-by: Andrew Morton --- include/linux/uaccess.h | 46 ++++++++++++++++++++++++++++++++-------------- lib/usercopy.c | 30 ++++-------------------------- 2 files changed, 36 insertions(+), 40 deletions(-) diff --git a/include/linux/uaccess.h b/include/linux/uaccess.h index 3064314f4832..d8e4105a2f21 100644 --- a/include/linux/uaccess.h +++ b/include/linux/uaccess.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -138,13 +139,26 @@ __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 +/* + * Architectures that #define INLINE_COPY_TO_USER use this function + * directly in the normal copy_to/from_user(), the other ones go + * through an extern _copy_to/from_user(), which expands the same code + * here. + * + * Rust code always uses the extern definition. + */ 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 +167,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 +182,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 499a7a7d54db..7b17b83c8042 100644 --- a/lib/usercopy.c +++ b/lib/usercopy.c @@ -12,40 +12,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 Tue May 28 14:58:04 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13676939 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 E2F80C25B78 for ; Tue, 28 May 2024 14:58:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 10EE76B00A0; Tue, 28 May 2024 10:58:27 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 0BE696B00A1; Tue, 28 May 2024 10:58:27 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E79D26B00A2; Tue, 28 May 2024 10:58:26 -0400 (EDT) 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 C50F66B00A0 for ; Tue, 28 May 2024 10:58:26 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 6E6C7A17F8 for ; Tue, 28 May 2024 14:58:26 +0000 (UTC) X-FDA: 82168110612.12.663FB19 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.202]) by imf10.hostedemail.com (Postfix) with ESMTP id 54B8AC0020 for ; Tue, 28 May 2024 14:58:24 +0000 (UTC) Authentication-Results: imf10.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=aW8R2TCr; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf10.hostedemail.com: domain of 3DvFVZgkKCIEfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=3DvFVZgkKCIEfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1716908304; 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=b9/4bIUoqG75SiXX4ggGIII0PXg7f1u44UaqTYS94zc=; b=jlcbXvBmlH6TG9NxT+bZRgBtmQ3afdLptAGA4Jnz3XOgmGuUMyw3Fs2m3Ed5WUel07Qe7x P9OP2ur05VcROPt7ztr9vqnbYqBzphTD19+IUOkvPEEuY36bBin8QEOccMuM5ES0HAhKQZ /9z9RyMV7029rS1+VN0pMB2GiJmYW+E= ARC-Authentication-Results: i=1; imf10.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=aW8R2TCr; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf10.hostedemail.com: domain of 3DvFVZgkKCIEfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=3DvFVZgkKCIEfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1716908304; a=rsa-sha256; cv=none; b=nO3s7sP5073kcQHqWZAnib4czeHKRFXOxl08AnWQVFGx7ypL93d0iLZrWLBi9Z3N+y3p++ rzN/2DyDAA5oLEQnBxhkRD5dn7uY8tSE2a81uZ89fA8cv0nCxe/1o/TLrcUNDCk2K6b7om ED4eqFzgqj2ltS1Rj5YtM/+0c00zL/0= Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2e95a1eba87so7032931fa.0 for ; Tue, 28 May 2024 07:58:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1716908302; x=1717513102; 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=b9/4bIUoqG75SiXX4ggGIII0PXg7f1u44UaqTYS94zc=; b=aW8R2TCryXNRZLmpe8GRH2CpWl345WSNC+xWlOBy6rneJQlWKS15ALzdo67vqrgay5 5HNdHIeLAYAy6inSyPBt7ZhVUH8QP3sN0jkqrpv7pY4QrVtAjBrOz2MTZNFAn0G1eiAz rwNzpLMDIcXdWSKj0BBX+VUU7Qsd3WUT+l76z6KwUTEj7UzHc1Q3aoPhxY8scaWGsPRt DNNDYhdAjizrAxFcj8Q9W2JnGA3ieFvWg473GyceKUfKONJO6Gi6RNSCtio1CGXIh4Dj /HY4nQOMD+bnRwXtmuXNgkjBth6p7oKpeJjnvcaU/nrdiGtgT1d64jUzBcnkgDRqb+28 o2cg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1716908302; x=1717513102; 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=b9/4bIUoqG75SiXX4ggGIII0PXg7f1u44UaqTYS94zc=; b=bWf4vybEkRUzFVvSaweb6vAej4QpPZ6K+CXRvjBHSDYr5PWxS+BjNODnph0tX/u30Z /C5RtHb8U5dy1LEjB2lO0ifrfWOKjQ4rgCoW4cWBlw3ZZxA0DKgF/isIlY0OPcsyQ++8 X74QgK0UqUJD3k5fOQjce/pzrF5nxwvXA7cvYnBhTWvWE3f2FYnGI55KWM69vI/jy8eG A0byn829V+z8zY9GIjN9lAwTQfm3T37gj5ALcUhKTXn7+dZb7nTt+ZaFWogt6t8CWvcr 0LaOOBKfeUXPdtzlTG3nbainxRK+ZTRMSm6BOKtWwYqiESUOHXomoifFPG37K7ZMRjuV cJkA== X-Forwarded-Encrypted: i=1; AJvYcCXFt89r3L0K/fN5RsjNCPSitF2GikwJdloMpK+mRpprHCFiKKIRDCz0ng9OHAK1BnzNv2k3lXN2ZVn4eP86/rJ8sBk= X-Gm-Message-State: AOJu0YzlY/RF24WA8eousFMwLctvP8rvGZbMqc8IqA3xlXxSvTV7gE+g YR7/kguIOE3U2WWM42PliML7cUrlAjtFELBTJBnNhseujnabRNJwdQdyzkARh5yLIvHUxFdybAG ZULUw8o6qpLs39Q== X-Google-Smtp-Source: AGHT+IGI0oSXsScGynqqZZ2qwR5qKbUrUE71Co+pWa+5ECFU6Ac40a2IMZtYKbVJYyka3eZNWCz/z+D1TV0BmGo= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a2e:360a:0:b0:2e0:d8c9:990b with SMTP id 38308e7fff4ca-2e95b27444fmr106591fa.6.1716908302093; Tue, 28 May 2024 07:58:22 -0700 (PDT) Date: Tue, 28 May 2024 14:58:04 +0000 In-Reply-To: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> Mime-Version: 1.0 References: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=9020; i=aliceryhl@google.com; h=from:subject:message-id; bh=yYu+EAbmrLlEDaJXxUlWd5cGuX40snAODQjVSX7+z6k=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmVfEB6oia3O2ePKqSvHFP2bMtfCznNnjJ6XHWK p+dntQJgACJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZlXxAQAKCRAEWL7uWMY5 RuYID/0Zn/Ekx3yhhKl8ze+ZbQzTKxxhXSitWFq4evNnN7TxwgP5on/9bu3I4gtYDFe787qYSj9 BOCif2gFbd/W7XnW2o0c4X44ErtiRtxHIxRN9v+BKfZCw5QQARt8Ajgsui4ZfRYwEWk44TPZI1Y ZQTmnG9HQ1sfgWJZDxSWzWPnFQ/y3r7fHtuFkKQ0eT5vm738ccBDWCX4XX19tH9Mr7CgaOoMQnu OquFHYfIDW84czELfZA/wxol/7ce8K8ryQibE6naSMDfDSInpHzGfx8/ip8PtM9Mi/jDby2llEO nT0Zl8jquE9Pe7raOb3reL8EWbRnIQpOF4/IIYqakQtDvI5fM4Z+TgS2S6kD1o83Hpg3ku22YvS syoIxmuGiZ8E4R1mMfy9mU/qoQGf6OTWSfNu+EycjF7B2+bWIRSXAiu8zEyfuXbJktrruMZFHWV fsvstUp7l71TeB77N1rF2vyk7xgkxGRylsQPfG/ED3UuJEO8Xx7FdHMuAtBIzqJX64qyC/lh+Mq 1W7nAeH1p02ib0EQGuTuP20f5kPoK8dQqaILUGYUKSoVf8OJlZIcoZobaU+TMGjtE9ZFjaTEZHZ Kmcyjbt85Yq0OSAPNijN/SRH7zbXdnauNWXi3h+wi7DmKTGme5m2Rc26ifu9o9W9e8qOef1bzSQ q8YkdHOAa9SgfJA== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240528-alice-mm-v7-3-78222c31b8f4@google.com> Subject: [PATCH v7 3/4] rust: uaccess: add typed accessors for userspace pointers From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj=C3=B8?= =?utf-8?q?nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , Trevor Gross , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspamd-Queue-Id: 54B8AC0020 X-Stat-Signature: caxexob7mipzntcpx48erg1qdtxsc8r7 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1716908304-215083 X-HE-Meta: U2FsdGVkX1+0B9lqtMK7yjRTvc3U69Xp0skpDb2mPs6EExXJ12H4lqhibFD2Gazjpvey1Bw7ZxOL0NiUIlTIaHZxCzVZZ41EVhFMqJQSgoZ45fq9o53KmKw8Q+vqGQFaSizdaXXhERQ9ZApJ/c9O0jC9jEdr1RNbfhvUqoLaG04AusjP61b+rXUFLDuOHu/3ZyegDspkwqvExCzLNrylGEk3sFFEDqXAmphD2E+FY0SHdzHJj185uccSrqIpC9Q7RBFybY4QSc3+cUD7qrJjW28t5H8ftwZewKKopXd9hLRVIK8/319dcNyTV4EzDWFsCU1wc58Yx0+pm4DvNQbGfIxq2xt/7NgZxUZ3zTIv5tExkMYoLb92Y34iVqBczjxz/J9BrzL8xJKwcJ4aI3tx1NWLCM7R7q85lE/UUriFlWkZjX1vHtnp7YtioguFGXaB9FVkgVGlZjmOA0UDc2iGvAH82/sBihBGzsXw6vS7MA99NwAPfYd2W3IZbkBBYvEBfr+4DY6xA4EFr8vwuAmFRAwKTqzYbditvFxfs9TdCZAWL8QtGKLQPuJczjT3l5RxOM6HPXkfdH15mJzSx2UXsoI8vIJprkubtbH8nB+hXHx7Cvvmq7zisn3LQQC+ntYc5oVGF1M8FP5IjCN2y5j20vmOpmqoWLKZ4YE22XdBdn5j/1Kxpvs/uGlcs28adml3kUQeDKDMSC6WVYtjUROG1yKxoSSVd5+WwuPWm09b/9NRpKf6TZPWZXhhyeAxwilnW730px0t9IkWcIpuVsqwwIeZJv4E9v1cjseLTEXuokW/1yL7SQhb+5mDUqidPQiF5YLxGiHTwPVMC7YDClGRDAi/f5ilemt5N9WcMabeHENfrBwkwkV6lubJmMluisvFGO8bl9TdLUpBzZvDNB3v3OSJKNofGQ3kRdmgG2CkncKx256Cd0/rugvWtpei9bt5YUx15fwCwrVX5ufLXRW G/pjKM69 sG/1C8Lth2xlbLwOf/MHS10FsFUwKnuRW2xmV6n7Pa2BPI6CTXtoAvq1g26mGzFRqdsNXb2S3q/vkPU/5KUzzghSLp5Ee5aZZ2+t9TEhN9vdZRIYuZBrYyS1fJg9F9kZiEW2rTBfkddMBT2YJKU8TW1MbaQlLVu2+dZX4CYNYAiJhoXwGFTO5BIYgQOmFrw4BSGIT2PJg14TbLt7AwkZ4I1RZJirDO0JWkfRwzJST0zEbfeuzujEf4BOJtcEAvDSV4130JIOO2oby6Il2IB8fgH0iXz+50KzTWZepQVQoGutZJBdZuFn0LGHsXQyYZGQsvURW2i0HMj8mx5ezwKXMvEA/1JxMNyYGfbZuF9APPTapteaKeqiX6kH3hq6RGvPpbYOXhIQB2IAw9qJObPzS+pmd0EIFlKSph7WV1QKZoyE/H3QoUk0PFPAndqjMlRSZlOpjrUc3lTXMG3HvG12G3LOq7MIdJVev0g9WD43lwjJ5h8txug2aaeGqg+tmSPDnoT7HQyiIewAIZzM1d4r6Wq9TBV76Fi6n0iu4k/DLAr94GttTpfBxqQFRDL6WGjk4fVaVTCDgwTCemp8zsHHVqgj50UnF/09+5q/MyMotdcFSwVQ5WyyB6XVRSWnbsruGIzU5tlxSnXWjqFUpsxUhhRiipZiu9q/LJntnSspkxrroFgW94Tp+/nPqJA== 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 Reviewed-by: Benno Lossin Reviewed-by: Boqun Feng Reviewed-by: Trevor Gross Reviewed-by: Gary Guo Signed-off-by: Alice Ryhl --- rust/kernel/types.rs | 64 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/uaccess.rs | 79 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 141 insertions(+), 2 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 2e7c9008621f..bd189d646adb 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -409,3 +409,67 @@ 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. This type must not have interior mutability. +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. This type must not have interior +/// mutability. +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 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 77957d7ec011..80f7e7ca2f5e 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -4,10 +4,16 @@ //! //! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) -use crate::{alloc::Flags, bindings, error::Result, prelude::*}; +use crate::{ + alloc::Flags, + bindings, + error::Result, + prelude::*, + types::{AsBytes, FromBytes}, +}; use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; -use core::mem::MaybeUninit; +use core::mem::{size_of, MaybeUninit}; /// The type used for userspace addresses. pub type UserPtr = usize; @@ -247,6 +253,41 @@ pub fn read_slice(&mut self, out: &mut [u8]) -> Result { self.read_raw(out) } + /// Reads a value of the specified type. + /// + /// Fails with `EFAULT` if the read happens on a bad address, or if the read goes out of bounds + /// of this [`UserSliceReader`]. + 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 as *const c_void, + len_ulong, + ) + }; + if res != 0 { + return Err(EFAULT); + } + self.ptr = self.ptr.wrapping_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. /// /// Fails with `EFAULT` if the read happens on a bad address. @@ -310,4 +351,38 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result { self.length -= len; Ok(()) } + + /// Writes the provided Rust value to this userspace pointer. + /// + /// Fails with `EFAULT` if the write happens on a bad address, or if the write goes out of bounds + /// of this [`UserSliceWriter`]. This call may modify the associated userspace slice even if it + /// returns an error. + 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 as *mut c_void, + (value as *const T).cast::(), + len_ulong, + ) + }; + if res != 0 { + return Err(EFAULT); + } + self.ptr = self.ptr.wrapping_add(len); + self.length -= len; + Ok(()) + } } From patchwork Tue May 28 14:58:05 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13676940 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 A42DDC25B78 for ; Tue, 28 May 2024 14:58:31 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id DB86E6B00A2; Tue, 28 May 2024 10:58:29 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D6A696B00A3; Tue, 28 May 2024 10:58:29 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id B94E56B00A4; Tue, 28 May 2024 10:58:29 -0400 (EDT) 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 98D526B00A2 for ; Tue, 28 May 2024 10:58:29 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 1E1E840601 for ; Tue, 28 May 2024 14:58:29 +0000 (UTC) X-FDA: 82168110738.16.E95E770 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.202]) by imf12.hostedemail.com (Postfix) with ESMTP id E46BB40023 for ; Tue, 28 May 2024 14:58:26 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=uCjBrdVO; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf12.hostedemail.com: domain of 3EfFVZgkKCIQitqkmz6ptowwotm.kwutqv25-uus3iks.wzo@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=3EfFVZgkKCIQitqkmz6ptowwotm.kwutqv25-uus3iks.wzo@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1716908307; 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=eO05l42JzpfeTNPK2MRvp86M9FhFhNRtSy4S1tjVhus=; b=qhVsdEZA8e0IApbMKzBiY8W6ch3XNOghRtSNJAjXAFNr4ICx9HADkyWDL1MFCrZAeeem5E K6x8KSaxkU4AmZpAItulsgHcIDy9T44mie9kD2pbuRsQ1GjS4JDTj6psCwEQknIfUVHFnI aao9lDbNSYgWxAq0i2W5RUsdCy+wyys= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=uCjBrdVO; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf12.hostedemail.com: domain of 3EfFVZgkKCIQitqkmz6ptowwotm.kwutqv25-uus3iks.wzo@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=3EfFVZgkKCIQitqkmz6ptowwotm.kwutqv25-uus3iks.wzo@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1716908307; a=rsa-sha256; cv=none; b=qj4Bdiz0MCc4wzof7/5lplhqWz2Tk214jeS35NWPNX7dBix/l07717tUJI/XrjEPMaUOSJ HnAmq9W26xCeL6zG9O8FQyiFQ3ta5SD4rbA/liVs5lz38yrpRxOZJZ5upWvXiF0EvGHpEs oGBTr4arDmtk4pZnwBZ0DkLW+CJXstU= Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2e95a1e65c2so8975281fa.0 for ; Tue, 28 May 2024 07:58:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1716908305; x=1717513105; 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=eO05l42JzpfeTNPK2MRvp86M9FhFhNRtSy4S1tjVhus=; b=uCjBrdVO6HsQUsH5JMqUya3oWUIaP32ltr2sMX3Pwas7wKzcKt1fpXqPScpdBSleOy p7AnWe5CSYeW9BlYbewHwBOt18ANdN7/1NZ0HyZgtr6xd+jjuiRF7MYbivQ6c5DtljId RjpRB6PXq8rdAz5qiu864RjCHyLfhqdqAM9oIgJd605V8/R5uZ6yvlC3DFDWMC+weFge RJ6ph4xkcekHL2Ub/mRLOHAVm+xd2GhugRKH7x13suIbDWKfkH7eGImOMTOLM1q6XWdP /hTpp/GTPjJMfgleJYaILf8atYpWF1GP3MFdpk7R6v32UTyvOUehGstF5EtjXzxTpAlc WMLQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1716908305; x=1717513105; 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=eO05l42JzpfeTNPK2MRvp86M9FhFhNRtSy4S1tjVhus=; b=QP4P3N6nXI6sjwWm/SY/SaPV/OpLqxuWVzWlrJ+gtw4EhlTEN7Ymre47JLvEQh65nP eawNF8yXRgnLFjtP11AdU04dkILha+PHfeB3GObeiqm9zzhFTgEUpCIakAPtc1oGBflt bwBwmS2BE+UaP/SOD/LQPEiECmmHf6BWnpOhihNe4QsafR1DLv+v/1oGqCnEr5rpXW5h AcyXrHK77s0MjtKAZkwmZ4oPasWgByiquPvt9RjjO9NJITSmHdm5Q5sE4oihQgPSdQnU s9YjtNZl98hx/G2gqPSxxEJONXEJl2HXDQ5VSNpAzEkpdcdECE6968w90tA3/i9FedZg JUKg== X-Forwarded-Encrypted: i=1; AJvYcCW/HsecrevH+kGJGtRznPM6BhHAWxHX4Eugphzpb34ZcIaeyYoH6X6IFt5nL98pzCIfwSrd6+hjCvMscInLkK82qO0= X-Gm-Message-State: AOJu0YzO205NgSpiF8ucShB6jubuHlAYnXNJ/XyHkMCrvbJWSyzZxVs3 DrArr5sdFINl+J87hwheWyrEbGa2pXSFyOyZTxECe/k4QxMlgUfbp7exBws4FoUorrTFHktZR1K egYUnePmn3lxaSA== X-Google-Smtp-Source: AGHT+IEOF4n7i+XUKYEBH94ipp8W/G8bUc6RNmidal0r91mtpuFIe9xOXChYEoPu4AGoMAK43jNu8IHHgNDq/Yo= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:32d3:b0:51d:5f9c:50ad with SMTP id 2adb3069b0e04-529666c4680mr10952e87.12.1716908305169; Tue, 28 May 2024 07:58:25 -0700 (PDT) Date: Tue, 28 May 2024 14:58:05 +0000 In-Reply-To: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> Mime-Version: 1.0 References: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=16077; i=aliceryhl@google.com; h=from:subject:message-id; bh=/HE8lkngIqgSFXOtkqfoTmQKkoPIxutv/DByz3hii1k=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmVfECAVuTTj15038Ew2DTzS3KESwLDvumYApMa eZb1p+NiP+JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZlXxAgAKCRAEWL7uWMY5 Rs9lD/wLFlIa+NMQSL+XMbCYpTDJQVbp+7DZpIvygiwW1JH34lbNywTpBNp3IjSEx7IgKIZUwoF kMBSbh+5TLnO+MIt7RBsY7Yn6V3Lvkhchd8wVGOtzIvmj1kpcvvqVCqvttpFMSR1QAeDnLfZjX/ uo07YYKK7D+J6grc/ZIv12/HP4CtFBTE0dPyW2h0FgbrVItek7+rZ8f7bB8HpKaF6+NEM+QP9JM qZjIl6j0deYWCQWDWo/wFsab9voyLxhzZ/E9YdE1tKjzw0/GSoaU/PmJ5a/eI8I1eCMmUMMCPFO CBTheF4vo8iwkb5e1YeCot0wTD+nGkmNaGx69RensXoGwEjKsfHa1lt3717UMZ44CWyeAWO5y52 8BWzcbqDjf93IDGHHUUVYNVzge4NJ1X2nPjtNwNniUow8yX6DmL3ZS9m46Pv+GWM9gzbZySJ82n umQAWuDZnhs0gmNxNfjb3v5Hu7KdbtbhBfBMFmMPtFnfhMLCcDptTiwbOLCWQ4E4km7PfVvvcB9 VDq5ao+YdwiAcPS0LZe7Pw56pHdFynJWMwXQ4/6xfy2JwbbKY38O21FOAQh52cVxRfgRd1woFBT pYGjdKWyrYxNnCZe1Gec4b2THgA6zK3Qd7kfvLGNaxMQxusI2VYvkn9dSmKF1Oa+fw+FAZ7mzJ0 Wqjz3DW/CXKlOJw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240528-alice-mm-v7-4-78222c31b8f4@google.com> Subject: [PATCH v7 4/4] rust: add abstraction for `struct page` From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj=C3=B8?= =?utf-8?q?nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , Trevor Gross , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspamd-Queue-Id: E46BB40023 X-Stat-Signature: w5bw7sn43hc59n514hj661yqhm45pt84 X-Rspam-User: X-Rspamd-Server: rspam11 X-HE-Tag: 1716908306-317734 X-HE-Meta: U2FsdGVkX1+fQXxWfa+5fTrmeb/dXpSEDruoYSpu0QjsvkS1a1w/RwBUILG/CkRRNFZEE5nAUYE2v/tGwsdYfscwqIz+5tu/WS69JGinMyBtlSqu1kvLGg+K1jMn/mFqcep4xMqqH0uW5YwgW6CCc6KbQtxJbGM3oIUPskgXMrf0I62ouwrgKyfhZSCgOQnfO0PBn+9gtHL3TEOT1c4iE84ORyz1YwCOM9IsoLSj4QGIb2PATXYVo58e/74Ifv5HNF7pRRTOR9+LnIRh76G+SOdqhJQN7Lo0w9JlAXxpzALj6EgmRUNq/FeCOQblus4b0wAu6iFlrwwZt6xgwIlMsIzwBaYHfGlvXqe5I5L6l9IWkJ8j/g+b5MK1D/QqdBbV5Zm4Of3KOJGyiBgCCvZIiklUm+756jGTCn3TCmEFv9k+kiOLtKMz9h8y00waNXaYloO9rgOzAUZ9PIC0gkhKFP8A0eTVGDosRqw/btPaz2SD2G7yW4Hibc7jyVNxAXHnan2rCDDMLuOb0HxETndvQk0v8Vyo6vmWZhvJLiTFToFXB4GMR3hNm63f2MUFCRipIAyQiVheNDSDTBLLRXMswBpQGDWARSklP8UUQKXMCmgyLv1kEe25wFSx2W/QqlWGlUSY4efCz0a7NoIDdYWTERBtgoJyZXpYLES6N58aUS+aiQUagyuPz2Kv+nwaEZszGpVQ9js7rI33Rodg5hQY0hUipLAqZubtkBSjqRjNPSXdDpSPXCTeKVcNKQdFFeKtc2cxEh1h8Vga2Lxx0Q1t4/jiKTGJwNbdc8V4O0myAv+7m0y6bweFmbicXYUbCrpfJRXOqJOuOlJ14Iw12/009MkPBZJMoDqvnSoG2Ti4dkl3wvaYyt7Knc83BCr6G2zmaULFF2vBkZcQ5ERW45wmPcsC56CRrc7bI6LgfLXP3aAOXxLA8R3wU2471cadqDkxdpWh7lYthuliUVIsDEH X2wkfEnA f9jKUhLu739+Orh/J0FFoihvYi3ZG9C6HzsSAEKS9OUHTC6gCpWSuuv+BY/yiQO9hvMPcocAPX6iqjS5PW3zQJaMhr9QpB0xOwePRHm2+maFsVFp+LIS/BAN+tcFtea66U/SqcK1ieDQBaSWGG3I316VhklSnX7t510Tyz1X7x34XWNsqYiohVKp+WFGSEVasvm+k+LhJj6j3NYM26hC1uyu81rsus0MgyEFzg02uoMlfLlK6OVHKpRJf1bqPH53VNy7dVJc8Ly4+235E/OfM8LERX+u9vTr0Eza8gVeZgOMW3cTZyIihni+8cBrseeWvnCum/FeJvhoQdYp/yuuatgxJ8RW5/RIUtSfjHPsMZP6QZmEHqHVeeBrOgjuD3pYBLiOCciM23I9Yu1oNVIB/96nxlPBUCZAcSBBKqvL+ip/G7rfLg1g0QK0AFqVuvsulL2ciEpQmkXmfQfT9ys7TQPywv9YSDGc8qGz2E1XwWJkb3QcPTAMjq3eZY8vOjuO73pJKENkbcVdzdXusRav2369OhkGkdXFhlMarq3DsOab5/igntble96dC6/8T8K9HQ8gGV0Ot5oU4unwI8y1rKpaRCQothh3tJfXweUmUgdYLajA8vWiqYCt9IDBR1YaSrAzyubwOJEMoX44b4zYvj5ULoq4iYK0UHsMW 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. Rust Binder needs to manage pages directly as that is how transactions are delivered: Each process has an mmap'd region for incoming transactions. When an incoming transaction arrives, the Binder driver will choose a region in the mmap, allocate and map the relevant pages manually, and copy the incoming transaction directly into the page. This architecture allows the driver to copy transactions directly from the address space of one process to another, without an intermediate copy to a kernel buffer. This code is based on Wedson's page abstractions from the old rust branch, but it has been modified by Alice by removing the incomplete support for higher-order pages, by introducing the `with_*` helpers to consolidate the bounds checking logic into a single place, and various other changes. Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Reviewed-by: Andreas Hindborg Reviewed-by: Trevor Gross Reviewed-by: Benno Lossin Reviewed-by: Boqun Feng Signed-off-by: Alice Ryhl --- rust/bindings/bindings_helper.h | 1 + rust/helpers.c | 20 ++++ rust/kernel/alloc.rs | 7 ++ rust/kernel/lib.rs | 1 + rust/kernel/page.rs | 250 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 279 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index ddb5644d4fd9..0862261cfbed 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -20,6 +20,7 @@ /* `bindgen` gets confused at certain things. */ const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN = ARCH_SLAB_MINALIGN; +const size_t RUST_CONST_HELPER_PAGE_SIZE = PAGE_SIZE; const gfp_t RUST_CONST_HELPER_GFP_ATOMIC = GFP_ATOMIC; const gfp_t RUST_CONST_HELPER_GFP_KERNEL = GFP_KERNEL; const gfp_t RUST_CONST_HELPER_GFP_KERNEL_ACCOUNT = GFP_KERNEL_ACCOUNT; diff --git a/rust/helpers.c b/rust/helpers.c index d6abe4bd45d9..305f0577fae9 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include #include @@ -94,6 +96,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/alloc.rs b/rust/kernel/alloc.rs index 531b5e471cb1..72f475e44144 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -20,6 +20,13 @@ #[derive(Clone, Copy)] pub struct Flags(u32); +impl Flags { + /// Get the raw representation of this flag. + pub(crate) fn as_raw(self) -> u32 { + self.0 + } +} + impl core::ops::BitOr for Flags { type Output = Self; fn bitor(self, rhs: Self) -> Self::Output { diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 767026db068e..5d310e79485f 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -35,6 +35,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..121d20066645 --- /dev/null +++ b/rust/kernel/page.rs @@ -0,0 +1,250 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Kernel page allocation and management. + +use crate::{ + alloc::{AllocError, Flags}, + bindings, + error::code::*, + error::Result, + uaccess::UserSliceReader, +}; +use core::ptr::{self, NonNull}; + +/// A bitwise shift for the page size. +pub const PAGE_SHIFT: usize = bindings::PAGE_SHIFT as usize; + +/// The number of bytes in a page. +pub const PAGE_SIZE: usize = bindings::PAGE_SIZE; + +/// A bitmask that gives the page containing a given address. +pub const PAGE_MASK: usize = !(PAGE_SIZE - 1); + +/// A pointer to a page that owns the page allocation. +/// +/// # Invariants +/// +/// The pointer is valid, and has ownership over the page. +pub struct Page { + page: NonNull, +} + +// SAFETY: Pages have no logic that relies on them staying on a given thread, so moving them across +// threads is safe. +unsafe impl Send for Page {} + +// SAFETY: Pages have no logic that relies on them not being accessed concurrently, so accessing +// them concurrently is safe. +unsafe impl Sync for Page {} + +impl Page { + /// Allocates a new page. + /// + /// # Examples + /// + /// Allocate memory for a page. + /// + /// ``` + /// use kernel::page::Page; + /// + /// # fn dox() -> Result<(), kernel::alloc::AllocError> { + /// let page = Page::alloc_page(GFP_KERNEL)?; + /// # Ok(()) } + /// ``` + /// + /// Allocate memory for a page and zero its contents. + /// + /// ``` + /// use kernel::page::Page; + /// + /// # fn dox() -> Result<(), kernel::alloc::AllocError> { + /// let page = Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?; + /// # Ok(()) } + /// ``` + pub fn alloc_page(flags: Flags) -> Result { + // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it + // is always safe to call this method. + let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) }; + let page = NonNull::new(page).ok_or(AllocError)?; + // INVARIANT: We just successfully allocated a page, so we now have ownership of the newly + // allocated page. We transfer that ownership to the new `Page` object. + 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. + /// + /// # Using the raw pointer + /// + /// It is up to the caller to use the provided raw pointer correctly. The pointer is valid for + /// `PAGE_SIZE` bytes and for the duration in which the closure is called. The pointer might + /// only be mapped on the current thread, and when that is the case, dereferencing it on other + /// threads is UB. Other than that, the usual rules for dereferencing a raw pointer apply: don't + /// cause data races, the memory may be uninitialized, and so on. + /// + /// If multiple threads map the same page at the same time, then they may reference with + /// different addresses. However, even if the addresses are different, the underlying memory is + /// still the same for these purposes (e.g., it's still a data race if they both write to the + /// same underlying byte at the same time). + 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()); + + // This unmaps the page mapped above. + // + // SAFETY: 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`. + /// + /// # Using the raw pointer + /// + /// It is up to the caller to use the provided raw pointer correctly. The pointer is valid for + /// `len` bytes and for the duration in which the closure is called. The pointer might only be + /// mapped on the current thread, and when that is the case, dereferencing it on other threads + /// is UB. Other than that, the usual rules for dereferencing a raw pointer apply: don't cause + /// data races, the memory may be uninitialized, and so on. + /// + /// If multiple threads map the same page at the same time, then they may reference with + /// different addresses. However, even if the addresses are different, the underlying memory is + /// still the same for these purposes (e.g., it's still a data race if they both write to the + /// same underlying byte at the same time). + fn with_pointer_into_page( + &self, + off: usize, + len: usize, + f: impl FnOnce(*mut u8) -> Result, + ) -> Result { + let bounds_ok = off <= PAGE_SIZE && len <= PAGE_SIZE && (off + len) <= PAGE_SIZE; + + if bounds_ok { + self.with_page_mapped(move |page_addr| { + // SAFETY: The `off` integer is at most `PAGE_SIZE`, so this pointer offset will + // result in a pointer that is in bounds or one off the end of the page. + f(unsafe { page_addr.add(off) }) + }) + } else { + Err(EINVAL) + } + } + + /// Maps the page and reads from it into the given buffer. + /// + /// This method will perform bounds checks on the page offset. If `offset .. offset+len` goes + /// outside ot the page, then this call returns `EINVAL`. + /// + /// # Safety + /// + /// * Callers must ensure that `dst` is valid for writing `len` bytes. + /// * Callers must ensure that this call does not race with a write to the same page that + /// overlaps with this read. + pub unsafe fn read_raw(&self, dst: *mut u8, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |src| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then + // it has performed a bounds check and guarantees that `src` is + // valid for `len` bytes. + // + // There caller guarantees that there is no data race. + unsafe { ptr::copy_nonoverlapping(src, dst, len) }; + Ok(()) + }) + } + + /// Maps the page and writes into it from the given buffer. + /// + /// This method will perform bounds checks on the page offset. If `offset .. offset+len` goes + /// outside ot the page, then this call returns `EINVAL`. + /// + /// # Safety + /// + /// * Callers must ensure that `src` is valid for reading `len` bytes. + /// * Callers must ensure that this call does not race with a read or write to the same page + /// that overlaps with this write. + pub unsafe fn write_raw(&self, src: *const u8, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |dst| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then it has performed a + // bounds check and guarantees that `dst` is valid for `len` bytes. + // + // There caller guarantees that there is no data race. + unsafe { ptr::copy_nonoverlapping(src, dst, len) }; + Ok(()) + }) + } + + /// Maps the page and zeroes the given slice. + /// + /// This method will perform bounds checks on the page offset. If `offset .. offset+len` goes + /// outside ot the page, then this call returns `EINVAL`. + /// + /// # Safety + /// + /// Callers must ensure that this call does not race with a read or write to the same page that + /// overlaps with this write. + pub unsafe fn fill_zero_raw(&self, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |dst| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then it has performed a + // bounds check and guarantees that `dst` is valid for `len` bytes. + // + // There caller guarantees that there is no data race. + unsafe { ptr::write_bytes(dst, 0u8, len) }; + Ok(()) + }) + } + + /// Copies data from userspace into this page. + /// + /// This method will perform bounds checks on the page offset. If `offset .. offset+len` goes + /// outside ot the page, then this call returns `EINVAL`. + /// + /// Like the other `UserSliceReader` methods, data races are allowed on the userspace address. + /// However, they are not allowed on the page you are copying into. + /// + /// # Safety + /// + /// Callers must ensure that this call does not race with a read or write to the same page that + /// overlaps with this write. + pub unsafe fn copy_from_user_slice_raw( + &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. Furthermore, we have + // exclusive access to the slice since the caller guarantees that there are no races. + reader.read_raw(unsafe { core::slice::from_raw_parts_mut(dst.cast(), 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) }; + } +}