From patchwork Mon Apr 15 07:13:53 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13629527 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 C28EBC00A94 for ; Mon, 15 Apr 2024 07:14:21 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 583D36B008C; Mon, 15 Apr 2024 03:14:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 50B5A6B0092; Mon, 15 Apr 2024 03:14:21 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3ACA46B0093; Mon, 15 Apr 2024 03:14:21 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 16E6F6B008C for ; Mon, 15 Apr 2024 03:14:21 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id C6C3C140498 for ; Mon, 15 Apr 2024 07:14:20 +0000 (UTC) X-FDA: 82010902680.16.F4A52E0 Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) by imf21.hostedemail.com (Postfix) with ESMTP id 16FAC1C000C for ; Mon, 15 Apr 2024 07:14:18 +0000 (UTC) Authentication-Results: imf21.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=mDZ+B8Wr; spf=pass (imf21.hostedemail.com: domain of 3ytMcZgkKCB03EB57KRAE9HH9E7.5HFEBGNQ-FFDO35D.HK9@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=3ytMcZgkKCB03EB57KRAE9HH9E7.5HFEBGNQ-FFDO35D.HK9@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=1713165259; 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=gPsi/82HDlElzGLDbKl3QsVxsZX8wiW1/rZTZrUN8mw=; b=Qymfh+Kn+m4Sd4JM3aCP1XHmOelTzfXtim3AGauFtejXSJjBn36BT3Yy+nlN9N+4BOQybl tShlObz6k9p8UuIfgMYKYLZ6oAFOLwN6wYJ1TYWgW4/GMsctZ+m0jrzMIZS4t5nQotCzq9 O3MqJca81WTXawuRfNpiJL2cbTNMCTM= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1713165259; a=rsa-sha256; cv=none; b=dqpWiypRrYgSjJ6naqdtb0dC165S7XAWzHcN6tCDt8rmzluCUZxdfDuetpI6mhc9ub7L2F TkpWZbaRbCVG+t4CSjZgc3miqbFEPDEDfUo0VVhz0x1i2fBa2lSHGBB948mMyBmsiE/MNd Ghgo3b66XvSNbxOkyKxWZwiWDeZ1nHE= ARC-Authentication-Results: i=1; imf21.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=mDZ+B8Wr; spf=pass (imf21.hostedemail.com: domain of 3ytMcZgkKCB03EB57KRAE9HH9E7.5HFEBGNQ-FFDO35D.HK9@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=3ytMcZgkKCB03EB57KRAE9HH9E7.5HFEBGNQ-FFDO35D.HK9@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-dcbee93a3e1so4685658276.3 for ; Mon, 15 Apr 2024 00:14:18 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713165258; x=1713770058; 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=gPsi/82HDlElzGLDbKl3QsVxsZX8wiW1/rZTZrUN8mw=; b=mDZ+B8Wr2OgNstHX9Wtl0PbuFgaYKM+40Fw+Ip0QlJi8hSnSPsMkt9pc+ZtUQ6ibsz JsKmoBl4OAiRrQzB9F2tDnDvzF7DJQJeA8u7/3kO7QZp22d0zsc7ikZVCudgPZtQ1ed3 lh94IJZ/jdZ/xUg7H/8A9j69lJB92IwUWyKX+/yZrsuagxq8NMs+kqmY9oHgr+lSN0Et oEIM5cIzBThptaQXov0w8VE7brzBQ6ENmz9d2vIq2UUWQjQ4Ap12pbw9mQofXIsB2LEX DLCR0lTnpdA019QVWwM6o18yGAtiOrA/ALv8JurUm23jp2v85o6Bp1+r2CMLLWmJvvYz pHQQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713165258; x=1713770058; 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=gPsi/82HDlElzGLDbKl3QsVxsZX8wiW1/rZTZrUN8mw=; b=YYJTUsdYgnR/ba1PPJKjPnxP1DhXLPxpP59AvHVao0E0E/0wxRsBzXNlzE73KggyMR JUMo+3sx0Lgvlhhpr5walbDDX7BbPzLgdvD1ybRdwY9kXEbEcRZVgIP2xo795dLx3bQp mAuwQgMgaYHx//o87SYBTcwCrgqRiLuRPpiiyCEgoBX3b7tovw5Jon/casWLz/CXjHg9 Oi7wEPr1rygZJYehGpMYMYzuox2vbcQjDEiwXH1WP6WoHX6TGcYroI9cqO73okxZBgKG DTfvGrYt80J+PqHlLdi6oVEVukEnjSPsPcclQWjtEe06bW/ooagM729vb7M1N2xguEC6 qbVg== X-Forwarded-Encrypted: i=1; AJvYcCWFsHuEMY+j+/7sBbuvXDKRGqL/h2gjYupyb+4nUpHlZKlrHa6ja1EkBXQxg24qFYRvJCP7baSezSmiLHR9Cd9wIBs= X-Gm-Message-State: AOJu0Ywbkjw76cDse2I8C5dAhS4iRHoOLQXwm9W+XL/mz+3yx+fu4GFO fSpylcxp5ijkScVR3AQjzkE1T+0dPm0vtB0NWW4nfbZvsw3FVpaR3f6BBS3jP5eOBmkSVjdguYo Vt9Zlvw+/kAkhWQ== X-Google-Smtp-Source: AGHT+IHO1a/TIo+ODNueO5S/jTlindE5np/HbvfupAbQcKpEJq3V8CqBFgvXPRG//Zj7Vd3zjtFH6qla2qW3cT0= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:10c2:b0:dbd:73bd:e55a with SMTP id w2-20020a05690210c200b00dbd73bde55amr1133317ybu.4.1713165258199; Mon, 15 Apr 2024 00:14:18 -0700 (PDT) Date: Mon, 15 Apr 2024 07:13:53 +0000 In-Reply-To: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> Mime-Version: 1.0 References: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=15177; i=aliceryhl@google.com; h=from:subject:message-id; bh=SoqPn2LPVb+BTP38IpB0LoymmpwLHXDbLBIRx2qwK8A=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmHNPBHO7WqwzbeKC9Qz1KbtF1FhT8jL8Hmg2gQ n91Fr4IeoOJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZhzTwQAKCRAEWL7uWMY5 RjWsEAC1nW29kfPewx8tCwQiy7+HkXLiviVtLhUxxUNufpUittkrOOP65Fra1jtpRO+yslVhCuk j7CsRdUQjzmLVscuHrIZybxw/MtKAKW5mTtE+olQID2W78hFeus0NNtAWvTszYMxX2rsCUY/EGH JcXLdfyxQYYPdqxpA9wbooEKhhwvD+THmC3otpEfAp8eWGmpXOVFh2C0HQnoBUQnCXW/K7J6G6K yTrEnoiJhsJsEEC7eB6W8+dSS7NldSM7z+AnY/TLie3FMxtTDhiAhMmjVRtu06kLzEugm2U3U0j UQ/HHYGrv/16pb9FZPgt/OwWSYXr3T3gR9bYBoR7pfpTk2bOYEotJeF1PrppuKpCZBAcYFkDrkW Nfnd8TUXgIt6SPq7PqGjVbKJ1Bd+Lg31/xp47ZcXDOl/VfUTdv/B0tt654Isn3NOIkjPrhFQEVX Ke47rtST9Hf7zpePx2p57C2IykFNfSllyjtGPA3cRDLH504dMI8rdioLue09U2mUdm0/kno87ss bJQv4218KT4oVFhxDvka6O+ItO1CzDtbgYVqKmijvH9AdVvHBJJQULal7rlA69iG/LGEuA5in/D QzZMxUgLiUJnHMNo9RJibboJ9siWBvzOKfzybv3VJ1YuQE0wVChFUQA1bycUfkSlmFfQMDoiJFA eWhuU2AKk4teOyw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240415-alice-mm-v5-1-6f55e4d8ef51@google.com> Subject: [PATCH v5 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 , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspamd-Queue-Id: 16FAC1C000C X-Rspam-User: X-Rspamd-Server: rspam11 X-Stat-Signature: pgqdz7nk954t3auidmgc1rkosoi5m76o X-HE-Tag: 1713165258-680976 X-HE-Meta: U2FsdGVkX1/Q+K6l1fEY5Awa9QIQjA5Ly4FjFUrjgQPsOlP9K1ULjIyaQ0Y9ELMuxpmNQTUaiTse9VQww31egH+NW2CzWbMcirY2Yex6Tf69mA+a0xe/EIqgcRc2/EuzdzzBG8zZgUxLijuyFCAn0VU54ZCgFaHlsN6Mk0bn0k7uCqq6Aiw5o2S8/9e7SeeCx39PCFGI3EphJ4FHIUBQd7HJU5OSFFFGPwCOHf0VJN9rUECi6sYPmGiQjhcFyoYpeZ7STK2HCOBYOcBuC1okS3hCsFZU8O5MVAyg+c5sKMVbnmXbZKqTB6aXbjXHymLO6+X6emVZjH2e1ysfk0esllNQqzQRDtR3p2PV/Fw4udftsd1ZXij/hNtwiwOg94DIfVEfvZyLYaq4Mp0KAnVm9by+rXEgSeClN1peqcsEipGpIuxud38nMlj+nnsItmTYAiUNnnf/ioN4Bn7oIu1IVAOAlk9DBZaTwqTNOQsynMNJq1TZrYmO3Bir92RM3ogIJ3WzW+f6irHpnOUwMxW33UKJCOU+4flsVw/3r4W9utJSAr/jUzm2SKklZbeczb1hX4ELY5cmbgqxFeC5FhCUpqQB9/ajV0qNN7urKOLagc2SEZXsE74cqaZNkujBqUwl7miuzq1pR8gsHCpo5c7Fli/4NCXTQg4NUWsIWGVuPEcA6262jemBlIJbRL1CCPnGBsQavY6TpKqZkBkyTFeR3eUlyxf2SXwDau9z1Zi6bWpXJfs2cRXgY6CyvAsdKbK6i55q/BJVpaLlR9Yf1I/rg+/qNQQb8RNHwZH3rpUaxUFL0f7kHKsvt9ynwwFA7FffJos9rcPcMKgldA85ZUFwwHU8CqPBEVxQF05lPk6VBaEietdhS9dhAuydRysLocEscNTX2z2iSZi1EUbBe7tekAWA1xfaqSmNK1EoZfc9Ch/zM8TgzRFCYbf81cWZtw3PTUoVljTBos2MrpI4iZ8 XSd/Aibu MpIdy8Pa2zTFri3QSgcJtz4cOUJxJYljyJe/KcOBuu6WUZKV+CCW/0gomuvSYdTm9KwT6H7Ps3KiZbZzNiJox+IpITHBR3JJBAQSTQJB9z7D39BbHCsrsHDCoV6Jjl0mA0eDTRZUdeWHbKKLOphgIiA/h8zB/2Yi2dwtJZ3LtFt7bGtQqQIHXeN0s3lJO24WU4wSMpkuS6b+Q/3ILwNilnmykk68Nn6aWNSGtxKc4KBNvLwe/yKx5z4pb8WUuzg4vtReWDwcGFn9Sbg63CYawJVREWQrXZ/nxecjWs8ScpNFmiHAZ1CAvaYjesi7FOb3Hb704A9uQr13jk9T2muEGZsCvn2rSYPYvJEhGmtM7EsiZF+bp/WxifRxeRFtbNJs/+j9Zalm3pRa17e80AmWuVTbyMPTlVhDmtB6G5H23wk06SlXtlHYH/3W1SGiOVQWKtiZm 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 `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, and various other changes. Signed-off-by: Wedson Almeida Filho Co-developed-by: Alice Ryhl Signed-off-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Boqun Feng Reviewed-by: Trevor Gross --- rust/helpers.c | 14 +++ rust/kernel/lib.rs | 1 + rust/kernel/uaccess.rs | 304 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 319 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 be68d5e567b1..37f84223b83f 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -49,6 +49,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..c97029cdeba1 --- /dev/null +++ b/rust/kernel/uaccess.rs @@ -0,0 +1,304 @@ +// 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::{bindings, error::code::*, error::Result}; +use alloc::vec::Vec; +use core::ffi::{c_ulong, c_void}; +use core::mem::MaybeUninit; + +/// 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::UserSlice; +/// +/// fn bytes_add_one(uptr: *mut c_void, len: usize) -> Result<()> { +/// let (read, mut write) = UserSlice::new(uptr, len).reader_writer(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf)?; +/// +/// for b in &mut buf { +/// *b = b.wrapping_add(1); +/// } +/// +/// write.write_slice(&buf)?; +/// Ok(()) +/// } +/// ``` +/// +/// Example illustrating a TOCTOU (time-of-check to time-of-use) bug. +/// +/// ```no_run +/// use alloc::vec::Vec; +/// use core::ffi::c_void; +/// use kernel::error::{code::EINVAL, Result}; +/// use kernel::uaccess::UserSlice; +/// +/// /// Returns whether the data in this region is valid. +/// fn is_valid(uptr: *mut c_void, len: usize) -> Result { +/// let read = UserSlice::new(uptr, len).reader(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf)?; +/// +/// todo!() +/// } +/// +/// /// Returns the bytes behind this user pointer if they are valid. +/// fn get_bytes_if_valid(uptr: *mut c_void, len: usize) -> Result> { +/// if !is_valid(uptr, len)? { +/// return Err(EINVAL); +/// } +/// +/// let read = UserSlice::new(uptr, len).reader(); +/// +/// let mut buf = Vec::new(); +/// read.read_all(&mut buf)?; +/// +/// // THIS IS A BUG! The bytes could have changed since we checked them. +/// // +/// // To avoid this kind of bug, don't call `UserSlice::new` multiple +/// // times with the same address. +/// Ok(buf) +/// } +/// ``` +/// +/// [`std::io`]: https://doc.rust-lang.org/std/io/index.html +/// [`clone_reader`]: UserSliceReader::clone_reader +pub struct UserSlice { + ptr: *mut c_void, + length: usize, +} + +impl UserSlice { + /// Constructs a user slice from a raw pointer and a length in bytes. + /// + /// Constructing a [`UserSlice`] performs no checks on the provided address and length, it can + /// safely be constructed inside a kernel thread with no current userspace process. Reads and + /// writes wrap the kernel APIs `copy_from_user` and `copy_to_user`, which check the memory map + /// of the current process and enforce that the address range is within the user range (no + /// additional calls to `access_ok` are needed). + /// + /// Callers must be careful to avoid time-of-check-time-of-use (TOCTOU) issues. The simplest way + /// is to create a single instance of [`UserSlice`] per user memory block as it reads each byte + /// at most once. + pub fn new(ptr: *mut c_void, length: usize) -> Self { + UserSlice { ptr, length } + } + + /// Reads the entirety of the user slice, appending it to the end of the provided buffer. + /// + /// Fails with `EFAULT` if the read happens on a bad address. + pub fn read_all(self, buf: &mut Vec) -> Result { + self.reader().read_all(buf) + } + + /// Constructs a [`UserSliceReader`]. + pub fn reader(self) -> UserSliceReader { + UserSliceReader { + ptr: self.ptr, + length: self.length, + } + } + + /// Constructs a [`UserSliceWriter`]. + pub fn writer(self) -> UserSliceWriter { + UserSliceWriter { + ptr: self.ptr, + length: self.length, + } + } + + /// Constructs both a [`UserSliceReader`] and a [`UserSliceWriter`]. + /// + /// Usually when this is used, you will first read the data, and then overwrite it afterwards. + pub fn reader_writer(self) -> (UserSliceReader, UserSliceWriter) { + ( + UserSliceReader { + ptr: self.ptr, + length: self.length, + }, + UserSliceWriter { + ptr: self.ptr, + length: self.length, + }, + ) + } +} + +/// A reader for [`UserSlice`]. +/// +/// Used to incrementally read from the user slice. +pub struct UserSliceReader { + ptr: *mut c_void, + length: usize, +} + +impl UserSliceReader { + /// Skip the provided number of bytes. + /// + /// Returns an error if skipping more than the length of the buffer. + pub fn skip(&mut self, num_skip: usize) -> Result { + // Update `self.length` first since that's the fallible part of this operation. + self.length = self.length.checked_sub(num_skip).ok_or(EFAULT)?; + self.ptr = self.ptr.wrapping_byte_add(num_skip); + Ok(()) + } + + /// Create a reader that can access the same range of data. + /// + /// Reading from the clone does not advance the current reader. + /// + /// The caller should take care to not introduce TOCTOU issues, as described in the + /// documentation for [`UserSlice`]. + pub fn clone_reader(&self) -> UserSliceReader { + UserSliceReader { + ptr: self.ptr, + length: self.length, + } + } + + /// Returns the number of bytes left to be read from this reader. + /// + /// Note that even reading less than this number of bytes may fail. + pub fn len(&self) -> usize { + self.length + } + + /// Returns `true` if no data is available in the io buffer. + pub fn is_empty(&self) -> bool { + self.length == 0 + } + + /// Reads raw data from the user slice into a kernel buffer. + /// + /// After a successful call to this method, all bytes in `out` are initialized. + /// + /// Fails with `EFAULT` if the read happens on a bad address. + 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, len_ulong) }; + if res != 0 { + return Err(EFAULT); + } + // Userspace pointers are not directly dereferencable by the kernel, so we cannot use `add`, + // which has C-style rules for defined behavior. + self.ptr = self.ptr.wrapping_byte_add(len); + self.length -= len; + Ok(()) + } + + /// Reads raw data from the user slice into a kernel buffer. + /// + /// Fails with `EFAULT` if the read happens on a bad address. + 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) -> Result { + let len = self.length; + buf.try_reserve(len)?; + + // 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: *mut c_void, + length: usize, +} + +impl UserSliceWriter { + /// Returns the amount of space remaining in this buffer. + /// + /// Note that even writing less than this number of bytes may fail. + pub fn len(&self) -> usize { + self.length + } + + /// Returns `true` if no more data can be written to this buffer. + pub fn is_empty(&self) -> bool { + self.length == 0 + } + + /// Writes raw data to this user pointer from a kernel buffer. + /// + /// Fails with `EFAULT` if the write happens on a bad address. + 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, data_ptr, len_ulong) }; + if res != 0 { + return Err(EFAULT); + } + // Userspace pointers are not directly dereferencable by the kernel, so + // we cannot use `add`, which has C-style rules for defined behavior. + self.ptr = self.ptr.wrapping_byte_add(len); + self.length -= len; + Ok(()) + } +} From patchwork Mon Apr 15 07:13:54 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13629528 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 EA84AC4345F for ; Mon, 15 Apr 2024 07:14:24 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7A5AB6B0093; Mon, 15 Apr 2024 03:14:24 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 77CB36B0095; Mon, 15 Apr 2024 03:14:24 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5CF776B0096; Mon, 15 Apr 2024 03:14: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 3F9F76B0093 for ; Mon, 15 Apr 2024 03:14:24 -0400 (EDT) Received: from smtpin18.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id F136FA14E2 for ; Mon, 15 Apr 2024 07:14:23 +0000 (UTC) X-FDA: 82010902806.18.00E99BA Received: from mail-yw1-f202.google.com (mail-yw1-f202.google.com [209.85.128.202]) by imf24.hostedemail.com (Postfix) with ESMTP id 23639180015 for ; Mon, 15 Apr 2024 07:14:21 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=RtPxz53i; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf24.hostedemail.com: domain of 3zdMcZgkKCCA6HE8ANUDHCKKCHA.8KIHEJQT-IIGR68G.KNC@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3zdMcZgkKCCA6HE8ANUDHCKKCHA.8KIHEJQT-IIGR68G.KNC@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1713165262; 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=622yrrnqj1BqCsmBBgHjaeo0syiJ1Yu6xB3lMWoaVgY=; b=ze+T3A4IOK54gN1fipRT3HrGpQL0WJ1KVRDiVQGJG2GvKnxgbAGRphjVN4O20zW/308KEa spS3davkMVaEEPQj+fiMGCQvt68rQzgc85uIb7ksDCZ8UnkFmG7U5syfJBc+08/IRObXkJ ewiyGwXIrdHBZ36UBT3sOpZlKNuoziI= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=RtPxz53i; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf24.hostedemail.com: domain of 3zdMcZgkKCCA6HE8ANUDHCKKCHA.8KIHEJQT-IIGR68G.KNC@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3zdMcZgkKCCA6HE8ANUDHCKKCHA.8KIHEJQT-IIGR68G.KNC@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1713165262; a=rsa-sha256; cv=none; b=Xney3EVhbdYGRoTJuYzRBQcghgEoJq2L2LTWzXojk3ZFWdhzvXNMxQst7J1gX/kWMLpAUD SWjudqTFmGRAGXrE8zTAxvVErf/i+9np7Mnw0m/26jTDiEPriWkL22vPjjsU0MfcjahG9w 5qwMLYQUGvs4llDsDsgtnUrpGgCCcz0= Received: by mail-yw1-f202.google.com with SMTP id 00721157ae682-615138794f5so49928317b3.2 for ; Mon, 15 Apr 2024 00:14:21 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713165261; x=1713770061; 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=622yrrnqj1BqCsmBBgHjaeo0syiJ1Yu6xB3lMWoaVgY=; b=RtPxz53iCAE2o9PiDTx7g1DdLlJ5xbYs7wmYZDzQ3XOKzcREG2zz6cjUOsa2m9pQM0 hR6CeVwDviA9YDdclV9vBuW84hT11j6K5j4zSRaNQjCY3eYz52FYRdevyYTEhOiHWPC4 wj3ADhDcg0oQq3NyHA+0ucW1Eiz2Qxi/wF006ltWU3Vd8PUorqUVQ8Xv0h7ao78F8Ebx HPnxkNxZoQIvkREfisDqxRlCigl85HOD07XeAv2SqGI8cqbdO8tYcfqDyi/VKrMXNwbv hdIeAs/basqaZWgs9TqKjuMfuZiol1k37/4mXYLAFLmHFl68POQyFoElRf9KLED2PZ6A 0HkQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713165261; x=1713770061; 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=622yrrnqj1BqCsmBBgHjaeo0syiJ1Yu6xB3lMWoaVgY=; b=fWywmObZtj4DGLJIPsh5s7AvsoH31a16jY6/JtTaukwmcvfleA6zsVZxGrja2Fu5Qs UiyVgRmKA7R9BXrpdXv8hSKDpT2SfvvLv4WhiPWx6TAfZh874p05DZ+7HclF9vTu1kA0 ORcd1T0vnFf9NxEBYdN4Sdlg6FsCHJQicC1fPt/gO2bG8vCfSb//IUajMZom2onq1Mun G4+RlymPnfgrgTT97mw+Gplmz/FpzhYgT/t3ImwY11hGwi+u5+WCmRaNK0JQ7JyunLDz Bdz/6PdDFXM1Fjk+ZBOhuFBrWw1TSnV+jTBlextdDZFX8xlY9ZV4SCsVk3zvedbh4xyN KAOA== X-Forwarded-Encrypted: i=1; AJvYcCXAHVk88KxsE9TELAo5l4C/r+VMJM9yX1966xIB2qRv8UXUwjxpy3oNEZ5KtioUscBaXBj9P8fpckixjR/1nt3faJU= X-Gm-Message-State: AOJu0YzVaMua1rSHy409BI8OLTprXhsufnoEepcOp4RJLklktVqZCLij ntYGZ81oVELCuvZDXica3j+xX/uaRX9TfNYlTzqZBujZbmqRCtLpML+PxcSR+1/ClPoCi6yGQwB 9FtkKBVOrqktHDQ== X-Google-Smtp-Source: AGHT+IEDy2cmxpL9gABLPqVzqQohAjhb5CWGb1j6O1qtcixaXYYFz1PV+vHzyNZSAuog3D6lnXz1u9jyr1ONoMc= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:690c:380e:b0:61a:bdb1:896e with SMTP id jx14-20020a05690c380e00b0061abdb1896emr905088ywb.5.1713165261254; Mon, 15 Apr 2024 00:14:21 -0700 (PDT) Date: Mon, 15 Apr 2024 07:13:54 +0000 In-Reply-To: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> Mime-Version: 1.0 References: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5074; i=aliceryhl@google.com; h=from:subject:message-id; bh=AYyTAq6TYaErSLcGReltlD/lrWoe0YO/q7GJueIPc/E=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmHNPCMZ5vFU68UUZuEzeqiEIJzbZO38/o+JL+b QhoXSkxAV+JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZhzTwgAKCRAEWL7uWMY5 RgEND/44B8JnNUin8lR9qqAELaIcTM4HHQAqgjQcaq5vFiabeNWQXj3yhNBDx3J6cwMFPgUmzsW F0ScjCrdPGfcNsrfowQWRKjm+fd4/OFEPByQecQrQ5MycDypNU3HBGA5lzfFMXIe7TErrFcRTNO +IkzkcixhueU/LQRUXNOZ/sHvLEmrnRqDFo5VrJ4fK+ksJ0PrC4xaP3KP/Yogc8Q6XYcDW8RYAG UyMLchf7IioeYhbNjPx0wiQRLhmAYaRoXRAjOLHABj0iPL3DKwTZyAmqxf7oWPFBX9BDtBfzZMA BfmaVVex3kI1vFaEzf6Xk77iSatVYVGBKegP8YvulcitWEMufwN/GQtNj0Ju4KBZqwNWIbz2gEj ukZ2coclsr6Ri+4Uqi1LJGwc5T9c+iLDcX8oyFLm8fyk74r+831KbSMSbiyczG/OvEyhG9DvgkH aNaQJHbYzDbT0dUcBKStl/Tx6FwnQoOmoXdFk2zEW1b1CKVbpRvNnJAQonqojW6N+ztBawG2N4R zu57ZDq9xIxB+dOXYzak1KI4q+Ijk9rgfji34kQR49kdRzXfadYHU51Z74+tvdaLaaTtb27p/mk 8E9/wQjavMJvqcABCML87U94lfB9agMkUrrLIF0pCulOMbJZEC4zHUHtRArxAdAQUeONiFwELOb sM3yhdquYvASE7w== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240415-alice-mm-v5-2-6f55e4d8ef51@google.com> Subject: [PATCH v5 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 , 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: ptdd1ja81ymn7ppdw1tb5jdyi9mh1m3a X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 23639180015 X-HE-Tag: 1713165261-608695 X-HE-Meta: U2FsdGVkX1/ChgH1eztD/dxmquNcEEUumuPGvLf60TtsR7rrbxKrWRazbOZrz/GGLLPsH6cPp9swDAt8xaanBOn048hLcEu/qJU6Gx1U9ndNhJnpHchulND1MtubgadkoMMO6xaCtc+KeW043z0J5CJL0g4pxaXM4YuttBnPHn+NlcR52/z/4q68dSXfK1ec6PQPwsXZe+hU4xhye6JDSsxe67sJ8InJZdc9F5XId1PGFmFvGUp64oyYD2j+CvJwv1EITZHIVwthzvJUdR0ZiTa2Zj+QmXcr7s6j/ze3N67QAK7O7ziJ2iFF00jcfVKbTgrXOrgeXZnpSRIZ/9iMMHYDdMOFXfHKwZwbUJ/YuCRQDyuIqEu4IrVLH3/ltscHB0PXVpOuWLIlkwTaiast55Odp5lSjMsHAZoQ9SSlYCL9g5CrOnPGMkBeDDWp47c+/GW+3NktwnM4d8afkra7eCpzkFyRQyJFyrO3AjYVqYfG8a2e+fQXm2ooQcbAYg+clu1lWx9rbHyulKQ5YSQun9bZeOcp58wt+CeJSzY4G9vrlQGgsD/p3gxu2locedYsAEFVZtZTAX2EssENuOE8VJ0FOfoxhGtslhd+Fe8R/K9wwsPEOHnQ4y/V3fGnvam/OISN6hiUBwHZluho+4K54xseiDJ8C1MJwO4STUoFHOggIVtm+JdCegLYpDAlPm5y4X9EyUzH6Y+U6q3Cwqps6u4DRq1pi2KWsaf/C3iWBwmhQIvL0Glih12Xkit8IvtTk1W19iSrsxMlJIZjy0l7ZlVa22eAdFO8mXERwKE1o4klAItjB0uLbuSqNOvCm+J/RrJoo2PbSkEBadlFaxyUI2lqsT+wLNzPuPnHYz8h9CafIQiO37dap/1rGC/nLerDep51bqgz8N8v+34Rbam/XgoijAz0t2JA8Iq/3IPfbtMFw/ByRCHFp8gMxPMQuyKHCRvn/63UgfG9RxGFk5K VRXt8hny 52aO+1SW7dC6hQUEL2r2gNphX8UPNV4fcRyCeKvWSKOL9fn86/u2YvgbQzOcSamHZnld6f/KMImzz82nn1XTmEOMjXtr4FUTcr/qJ1CTz3ClVeviNjJDPIyfV8iVhEjJxx9kqOOaMe3Ku3sWObzNmcRNlGb0FYgbUK4Z9FXVXg2C58f8kNQd3JafilymPrGje46BgVUK2RKZmxPwEY9y6GdguENygVeOgvTCIGuWhuSw1vVuKlSOCXdGwwRJ1aHJE7FTsIjdBpX7V4zbxjFbiKowV6+1/IOx+T2TWaQXKhfP7lWmPRCGgHsnZTDucbQr9EAm9gH7tl2y61ND9sAu1sFgkLk7SSzLgzaLsV3KtwAF54iRscxcyQLg9eqmnLqWo4dXxTt+g/v85whEmsaj4QJmdGxLnhgdqJWu5XVn3YEhzpA7B6sJadyBfWjYjhfubKqlbrOhKPL0Z2/rBiiC0JDGF5K+i/8zX43fHzbCBYvooc6YA/NrLycgy1oSKMo2W3wiVdiI/BjyVeZ8yMgajOU2bhWhqFF6u91PdREv9Y231jnSMObx8s6LpaDV386PucZxUEqqNhfQOdn7mp0KP0doYNcESsG8TiSbrubPERXbbqv8Tlqxb+N4/VvBcVAiamwopH4aEwfc3vJjiESN0mU9dUfO0aj6RVdOq+qorlTX/1y1Rw7eiLbsiAl3PMLXwolJUxv7tlGEmcM7VAFn4HhD/obo/Zq+8Udn5e5dJf7dtW1yOinhknackrJT7CfLUlGPKb1Our1RD9MKV2U8j5UNfiw== 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 Signed-off-by: Alice Ryhl Reviewed-by: Kees Cook --- include/linux/uaccess.h | 38 ++++++++++++++++++++++++-------------- lib/usercopy.c | 30 ++++-------------------------- 2 files changed, 28 insertions(+), 40 deletions(-) diff --git a/include/linux/uaccess.h b/include/linux/uaccess.h index 3064314f4832..2ebfce98b5cc 100644 --- a/include/linux/uaccess.h +++ b/include/linux/uaccess.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -138,13 +139,18 @@ __copy_to_user(void __user *to, const void *from, unsigned long n) return raw_copy_to_user(to, from, n); } -#ifdef INLINE_COPY_FROM_USER static inline __must_check unsigned long -_copy_from_user(void *to, const void __user *from, unsigned long n) +_inline_copy_from_user(void *to, const void __user *from, unsigned long n) { unsigned long res = n; might_fault(); if (!should_fail_usercopy() && likely(access_ok(from, n))) { + /* + * Ensure that bad access_ok() speculation will not + * lead to nasty side effects *after* the copy is + * finished: + */ + barrier_nospec(); instrument_copy_from_user_before(to, from, n); res = raw_copy_from_user(to, from, n); instrument_copy_from_user_after(to, from, n, res); @@ -153,14 +159,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 +174,32 @@ _copy_to_user(void __user *to, const void *from, unsigned long n) } return n; } -#else extern __must_check unsigned long _copy_to_user(void __user *, const void *, unsigned long); -#endif static __always_inline unsigned long __must_check copy_from_user(void *to, const void __user *from, unsigned long n) { - if (check_copy_size(to, n, false)) - n = _copy_from_user(to, from, n); - return n; + if (!check_copy_size(to, n, false)) + return n; +#ifdef INLINE_COPY_FROM_USER + return _inline_copy_from_user(to, from, n); +#else + return _copy_from_user(to, from, n); +#endif } static __always_inline unsigned long __must_check copy_to_user(void __user *to, const void *from, unsigned long n) { - if (check_copy_size(from, n, true)) - n = _copy_to_user(to, from, n); - return n; + if (!check_copy_size(from, n, true)) + return n; + +#ifdef INLINE_COPY_TO_USER + return _inline_copy_to_user(to, from, n); +#else + return _copy_to_user(to, from, n); +#endif } #ifndef copy_mc_to_kernel diff --git a/lib/usercopy.c b/lib/usercopy.c index d29fe29c6849..de7f30618293 100644 --- a/lib/usercopy.c +++ b/lib/usercopy.c @@ -7,40 +7,18 @@ /* out-of-line parts */ -#ifndef INLINE_COPY_FROM_USER +#if !defined(INLINE_COPY_FROM_USER) || defined(CONFIG_RUST) unsigned long _copy_from_user(void *to, const void __user *from, unsigned long n) { - unsigned long res = n; - might_fault(); - if (!should_fail_usercopy() && likely(access_ok(from, n))) { - /* - * Ensure that bad access_ok() speculation will not - * lead to nasty side effects *after* the copy is - * finished: - */ - barrier_nospec(); - instrument_copy_from_user_before(to, from, n); - res = raw_copy_from_user(to, from, n); - instrument_copy_from_user_after(to, from, n, res); - } - if (unlikely(res)) - memset(to + (n - res), 0, res); - return res; + return _inline_copy_from_user(to, from, n); } EXPORT_SYMBOL(_copy_from_user); #endif -#ifndef INLINE_COPY_TO_USER +#if !defined(INLINE_COPY_TO_USER) || defined(CONFIG_RUST) unsigned long _copy_to_user(void __user *to, const void *from, unsigned long n) { - might_fault(); - if (should_fail_usercopy()) - return n; - if (likely(access_ok(to, n))) { - instrument_copy_to_user(to, from, n); - n = raw_copy_to_user(to, from, n); - } - return n; + return _inline_copy_to_user(to, from, n); } EXPORT_SYMBOL(_copy_to_user); #endif From patchwork Mon Apr 15 07:13:55 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13629529 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 E0006C4345F for ; Mon, 15 Apr 2024 07:14:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7094E6B0096; Mon, 15 Apr 2024 03:14:27 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6BA716B0098; Mon, 15 Apr 2024 03:14:27 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 534DD6B0099; Mon, 15 Apr 2024 03:14:27 -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 2CD8B6B0096 for ; Mon, 15 Apr 2024 03:14:27 -0400 (EDT) Received: from smtpin20.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id F2404A04B9 for ; Mon, 15 Apr 2024 07:14:26 +0000 (UTC) X-FDA: 82010902932.20.AF3C810 Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) by imf17.hostedemail.com (Postfix) with ESMTP id 0E5BC4000C for ; Mon, 15 Apr 2024 07:14:24 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=mcKcP5Fn; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf17.hostedemail.com: domain of 30NMcZgkKCCM9KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=30NMcZgkKCCM9KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1713165265; 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=MhdlP5JlKNtstcGdifj2bRw8BnPpw/8WvVvi1+ODuPA=; b=3pWmZfMdYEjiOXlVFnxEbRrabRoOAWUs52O1/C0Sb8/ZC0rh6rJZ413S2WfbTFiLmJYTrn BfcOaOjXG/hIzDT91AkT83OPyvZuynBN3hd/Y0hDHyfUWZFSEIRMxNPFqJ+lzTs3tzrwZi +5iphbpqDSPaK6FUiReYg1Zo8pUp2eA= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=mcKcP5Fn; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf17.hostedemail.com: domain of 30NMcZgkKCCM9KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=30NMcZgkKCCM9KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1713165265; a=rsa-sha256; cv=none; b=Lj/LzFR4x9HOPW+sZmvKlff7zfucsXdNyNFIX2UBNBGrTAgitc2AmElZt+H8+kIiHsW11k 3lqNaO0EkSQ6yAkuwdt3gRPQ048Tc4j8tsjV2+p5NOOCmHQVJmcBjxPp0x+FMuMUHvodJD xohIJlcjzVOTPJNnBhPtGEzFElKJ248= Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-dd1395fd1bfso5156932276.0 for ; Mon, 15 Apr 2024 00:14:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713165264; x=1713770064; 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=MhdlP5JlKNtstcGdifj2bRw8BnPpw/8WvVvi1+ODuPA=; b=mcKcP5FneBixtdJVY7GpCXNPK9ajWrk9YxvVHzUAKpLQCi+rKU5q5NKvn9XhMrrbCZ KR/eQg3jaU6DRNQWxiB7zJesI8c3ypko5aHJAK2eYVatX2JB3tScdAaUY1ofE6O47HIC nJjP9/HhJQmudbV34KlQkbH5ydjwASXc9PN7YhNXIrp74V0SZo8tG2H7V7cgBsY2RT0b onkORk13aDoEPnatU+1gBYxI0/fpBcjZ+nsLr6dEZZEPGoGhCwpS1wrwR1SOik1tC6qD UfyAJDvdlTxZqZuSDgsEsttah6nlwi2Qa6OoLPpKhL/farpVu37D+7BkFzeX4t6E2NcA J0sA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713165264; x=1713770064; 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=MhdlP5JlKNtstcGdifj2bRw8BnPpw/8WvVvi1+ODuPA=; b=e9QqOYr7XCb0ubB5fzwvAejMRgqCoQZjCqCdUnCcOyDNJH49vceohR8N7Qq7aV0jkm Zp4ZCvBcf6ey4rdOVfOeBqu4YBqEGq4/RolWE2wMGcMn0uLgkisdZMuTk1QDbVp5Y1OD 66bdnZnLqEcaRECVPSpS/4x+iJkfsqgYbfq302jXthHCmhwa+mi4lMrriicNDpF+DtHJ ncH1LoMxkdEDi1hkpvtBALcm4qZzb63vdtmbhtfKiKQLN65SBrbl9dEw1LHXje/7wCEr GOlqo5dc8UEfXJUA2Y2bVfDRz9EbZcNJlFpglcjpo5xd95nFzyl+jNPl4Ej3uWHxpy6R BLUg== X-Forwarded-Encrypted: i=1; AJvYcCUYLBpJ6h9qp7hbowgYU9gBl/r21HYv680ElCgoMGOEcoD6uTs58kQlAXyKq71T+keskX6JabPXt8Gne8Uv4OIp3QI= X-Gm-Message-State: AOJu0YyOtXPxa7S/pXYGWViCTF2VM/jRMapn7MI15xzxqfZYbAalwIa1 jqXQTXUzEYOwGmAnoyYfv/sUQ41al8QeRkjHM4PMt9BPwCq8Av4dH51qvSHyMPfEwC4DRv766XR gf8syKjCOcmLbEQ== X-Google-Smtp-Source: AGHT+IHwi6w0lDXo5tZreR0tVkBy1RTj7mLjFE+yjLToXnPFfw726W8T3Ei3bLcl/Sjj7d4uVRnPuHJYNVD4lW0= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:1502:b0:dc7:49a9:6666 with SMTP id q2-20020a056902150200b00dc749a96666mr3155257ybu.3.1713165264142; Mon, 15 Apr 2024 00:14:24 -0700 (PDT) Date: Mon, 15 Apr 2024 07:13:55 +0000 In-Reply-To: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> Mime-Version: 1.0 References: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8745; i=aliceryhl@google.com; h=from:subject:message-id; bh=BPvxCnQU8QVu2tTG/MzhVBESR9s1ykEepxIFWcgj764=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmHNPCpIenedGq5y7NqOIo3z3RQyWrBzGEt1gNy 6aXpXjCwQWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZhzTwgAKCRAEWL7uWMY5 Rk10D/9rglwh8dFgKcRzxbw+8GX1BZNX08YZpvZd/17rL32smdZiZTKPJd75K2m/Uw2pN+V6Zmd UvNUMMkIUcPwF8PpoPJcm0hhQQ2sj1A2yS6Kcr2CXrGkj9E4xdH3I+2hY+6UQqiKXYHS13XwenS rSQ5sgsLOkGh3CgtKyd+52Dptr5ZdGAjugEmG5uP/m2ZwBX+JecqZcTCROMyO/mgZvD0EoMoy29 wLiOeA1yWDMq0+Tnm0xmUIgX3wmgm7kHxa0rnK1CMapZ7o/fwXC7BsDTiQTOlR9jgei0FBGeMVo wUbt7E9pHZMGIY3y8lIUxcrsu8fOvAr3FVAGazwWYIUCp5dB1JMZFQd3FWdMSFA+Ivbz//PS/XG sI/GrjEhtjJKAnmaoV5KlkXr0EvIZFEdFp+LU3T35weYFXrkaVM2Wz/HuTKoW6e+R7m2EZyRsks LF1s5nNZMpli7Aae4sXdVvkRrHtJP9adKd8cr7v9WtK7+VLE/K8uqbu264A/KUskT9wkFduxdbO 3SV3bWG6uARUGmgJLvJYoaCuQl3wS36vsQVeBlV/EJiYZvo7bm7I20ejyJuXFjH8cpNw6lrBL68 +JDQthtx6tOI8tOa2+Q6fZgRVERlT8kyZ5cYmtwEyTPq+Bvi2odqaqrtdV4Wn6ikMAcXyTI9RyK oSV1ESaJlxi79Jg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240415-alice-mm-v5-3-6f55e4d8ef51@google.com> Subject: [PATCH v5 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 , 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: 0E5BC4000C X-Stat-Signature: j5f91ohc6ebiq3hbqxusd9rkxdzzn8es X-Rspam-User: X-HE-Tag: 1713165264-248656 X-HE-Meta: U2FsdGVkX1/p7L9NNxRFtauyi7wmB4CsVJ1Tl+dThbmOBBLkUAfn2K1CdpMxBadjpw7kWfkBgv5VqGpOgjrsURc1axsuNseadjt5+Khfpb9svz0mb+e4iY7lO7n4htXcjIEpfwC0AW1cPnShdIQdkApvuH7Lz2Iu6YvBJLB+/66CJYHQSjoSsu+rAhuzqSPreDEizUOQq1sisgi2iK5pxkU1QIBFalTjLpOmNn2A3Lgv/xzl+kr9bnkLbi6/8yyWyWwcc06xYMTX+/r/4xjt88ZBOI44OpxdV1vGozueSd8cK2RIo96I00unsBN0YfzHS2whZk4O8Y0Fo/BPlKBW8JLIBxaTS4f4FVgJxjTRE7FRTlreXoHYbF5i+6S1rBPFdKZzJMarmFfN6efkuI6kmJygMGCkL4AFjwOV4EF+QhmJ4QlYTdsGuwuAaVVHtqyskRTfuYzonK5nuTmSCtgiva/NDSJg27e7Y6mqlDLbf1+7UwH/oHDXGxzy6WBTtXSv5Yr+xuWdkRgekaEDj3zS2ga4KwyqNRGgJqC6bhKvl0spyvAy/KpZUw1RSZzC7xpV4ww/Oq7mas2eSWEUQvJyUSnxFou08eJvXAfX0q4b2MeMEsCVtaPDvGoKyjAaRkanVZbZGj028WSHmfGcUGJYn9dPJcEu1I5ZOdK1oDRGSklzfJimIcbd43cQvdZ0QnB5QZheD8qdD9nDlA4BB5qNphdFDNYQkMLeB+PEGL+IEKglDyVZKzPTR3GuNRYKeFbePOpNSoWXDa6fBakcLa9qmbwHlKF4tKQRaaMtaJX6fMvrG/HnWjZ99DrfiTGKQ0f5XJGY5N5ExoHmO1e3qvVB9gLDcVrPfgjpFCijFXCGmxmU51TyD5x2hr/NFytLgy7KER0s6+u4LMQyOJg+VJ4RrbtYSjenu4mLUh29zTnvu0FNvtI+mURBeeZdRdrZIQnNlLdgBhzZU80XzoRzvQp P2/MlzW4 ik3uXdHT6raW6GTPSEqQ+e5RdMRBAybMOaeFqPEK/OedpI/AUlwqUnysoPry7ejFGDgYA/29g05aCCJYL6FwEwvHL0TM6W87VGMzi4cm8wGN+nP3Fg6+16K8h2AYso0Vqnl2BkiPdMfRFSIUNXLDRFOyWGhxDfDtheTvZ4tG2J45pO8F/BQTCmvj12kYuWyF0LfNDytWy7CFJIkrPLupQ8MEuSpMVulcsdo7v0P6bT9vTsOOuCAVvg1r1MiM3t9xz+jJNg7UiChnj3dwA4651b0MatP4zfQNYvSLc7C6vHmT9lgJWoTt2MRCYzzA99Ssuc0SG82PnZqxq//FO8RwAT/JC6DMfsdlYyYYmeQGdZ3ifAS37Ow/SbGYI8epWIqDUq40gVvsnlHpFzI0mDLHbt8KSEIVCKJGQH5vf8Nr+OKNzBfmAhdrwK4AE6YilH2QQny3P0B4EFI0bV+sxJztCB9edOZsQZuaQqC+fRqXSvMRoXJrHzcS1oyTFNJii713X0ds0FtEqMXvkSJj/JHMhLSXie4Xo1HxH2ekt48FkEys7oB29fr8JRkVei8QtX+xa39g3p1LLuTZndosNjpK6n6ulKZbnX+nnusscH9tp9yQCv1vCtf4yGWS+HQJBcVmbRd8s6hIGBNS/jPAb4acaVH6JZN9cN3Fq8iy4VmleUc/vSqh5YUtAL4vtvtCoFXjLCcuKk6BvOjXRf14em/c/j81MxFjOeLU5yaJe 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 Signed-off-by: Alice Ryhl Reviewed-by: Trevor Gross --- rust/kernel/types.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/uaccess.rs | 71 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 132 insertions(+), 2 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index aa77bad9bce4..414ba602fc5b 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -409,3 +409,66 @@ pub enum Either { /// Constructs an instance of [`Either`] containing a value of type `R`. Right(R), } + +/// Types for which any bit pattern is valid. +/// +/// Not all types are valid for all values. For example, a `bool` must be either zero or one, so +/// reading arbitrary bytes into something that contains a `bool` is not okay. +/// +/// It's okay for the type to have padding, as initializing those bytes has no effect. +/// +/// # Safety +/// +/// All bit-patterns must be valid for this type. +pub unsafe trait FromBytes {} + +// SAFETY: All bit patterns are acceptable values of the types below. +unsafe impl FromBytes for u8 {} +unsafe impl FromBytes for u16 {} +unsafe impl FromBytes for u32 {} +unsafe impl FromBytes for u64 {} +unsafe impl FromBytes for usize {} +unsafe impl FromBytes for i8 {} +unsafe impl FromBytes for i16 {} +unsafe impl FromBytes for i32 {} +unsafe impl FromBytes for i64 {} +unsafe impl FromBytes for isize {} +// SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit +// patterns are also acceptable for arrays of that type. +unsafe impl FromBytes for [T] {} +unsafe impl FromBytes for [T; N] {} + +/// Types that can be viewed as an immutable slice of initialized bytes. +/// +/// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This +/// means that it should not have any padding, as padding bytes are uninitialized. Reading +/// uninitialized memory is not just undefined behavior, it may even lead to leaking sensitive +/// information on the stack to userspace. +/// +/// The struct should also not hold kernel pointers, as kernel pointer addresses are also considered +/// sensitive. However, leaking kernel pointers is not considered undefined behavior by Rust, so +/// this is a correctness requirement, but not a safety requirement. +/// +/// # Safety +/// +/// Values of this type may not contain any uninitialized bytes. +pub unsafe trait AsBytes {} + +// SAFETY: Instances of the following types have no uninitialized portions. +unsafe impl AsBytes for u8 {} +unsafe impl AsBytes for u16 {} +unsafe impl AsBytes for u32 {} +unsafe impl AsBytes for u64 {} +unsafe impl AsBytes for usize {} +unsafe impl AsBytes for i8 {} +unsafe impl AsBytes for i16 {} +unsafe impl AsBytes for i32 {} +unsafe impl AsBytes for i64 {} +unsafe impl AsBytes for isize {} +unsafe impl AsBytes for bool {} +unsafe impl AsBytes for char {} +unsafe impl AsBytes for str {} +// SAFETY: If individual values in an array have no uninitialized portions, then the 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 c97029cdeba1..e3953eec61a3 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -4,10 +4,15 @@ //! //! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) -use crate::{bindings, error::code::*, error::Result}; +use crate::{ + bindings, + error::code::*, + error::Result, + types::{AsBytes, FromBytes}, +}; use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; -use core::mem::MaybeUninit; +use core::mem::{size_of, MaybeUninit}; /// A pointer to an area in userspace memory, which can be either read-only or read-write. /// @@ -238,6 +243,38 @@ 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 encounters a page fault. + pub fn read(&mut self) -> Result { + let len = size_of::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + let mut out: MaybeUninit = MaybeUninit::uninit(); + // SAFETY: The local variable `out` is valid for writing `size_of::()` bytes. + // + // By using the _copy_from_user variant, we skip the check_object_size check that verifies + // the kernel pointer. This mirrors the logic on the C side that skips the check when the + // length is a compile-time constant. + let res = unsafe { + bindings::_copy_from_user(out.as_mut_ptr().cast::(), self.ptr, len_ulong) + }; + if res != 0 { + return Err(EFAULT); + } + // Since this is not a pointer to a valid object in our program, we cannot use `add`, which + // has C-style rules for defined behavior. + self.ptr = self.ptr.wrapping_byte_add(len); + self.length -= len; + // SAFETY: The read above has initialized all bytes in `out`, and since `T` implements + // `FromBytes`, any bit-pattern is a valid value for this type. + Ok(unsafe { out.assume_init() }) + } + /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with `EFAULT` if the read happens on a bad address. @@ -301,4 +338,34 @@ 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 encounters a page fault. + pub fn write(&mut self, value: &T) -> Result { + let len = size_of::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: The reference points to a value of type `T`, so it is valid for reading + // `size_of::()` bytes. + // + // By using the _copy_to_user variant, we skip the check_object_size check that verifies the + // kernel pointer. This mirrors the logic on the C side that skips the check when the length + // is a compile-time constant. + let res = unsafe { + bindings::_copy_to_user(self.ptr, (value as *const T).cast::(), len_ulong) + }; + if res != 0 { + return Err(EFAULT); + } + // Since this is not a pointer to a valid object in our program, we cannot use `add`, which + // has C-style rules for defined behavior. + self.ptr = self.ptr.wrapping_byte_add(len); + self.length -= len; + Ok(()) + } } From patchwork Mon Apr 15 07:13:56 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13629530 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 4B517C4345F for ; Mon, 15 Apr 2024 07:14:31 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D28FB6B0099; Mon, 15 Apr 2024 03:14:30 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id CD47D6B009A; Mon, 15 Apr 2024 03:14:30 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id B28B66B009B; Mon, 15 Apr 2024 03:14:30 -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 892856B0099 for ; Mon, 15 Apr 2024 03:14:30 -0400 (EDT) Received: from smtpin21.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 5B648120478 for ; Mon, 15 Apr 2024 07:14:30 +0000 (UTC) X-FDA: 82010903100.21.4B1DE22 Received: from mail-lf1-f74.google.com (mail-lf1-f74.google.com [209.85.167.74]) by imf30.hostedemail.com (Postfix) with ESMTP id 5850D80011 for ; Mon, 15 Apr 2024 07:14:28 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=3PwfzN6j; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf30.hostedemail.com: domain of 30tMcZgkKCCUBMJDFSZIMHPPHMF.DPNMJOVY-NNLWBDL.PSH@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=30tMcZgkKCCUBMJDFSZIMHPPHMF.DPNMJOVY-NNLWBDL.PSH@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1713165268; 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=dQnBVtrhJpUgOHcm+nS3apY4eRmi29T+h46zYZ5XaoI=; b=78VEa3qNLxTj4ubRUuUw7rM08BqQs35OlB7/5CfHt+/n+xfnJa8ot5pEKoaZnFFw+D09V0 xZt4w5mtHreKCbgJwMH9PRQ0K2vald9z+PapQWtqHzFAu466jyJZsyX9/eST9TImSNM4dC 0uTuJC53C3LC5/u7m4eEbDjTFAmEI1c= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=3PwfzN6j; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf30.hostedemail.com: domain of 30tMcZgkKCCUBMJDFSZIMHPPHMF.DPNMJOVY-NNLWBDL.PSH@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=30tMcZgkKCCUBMJDFSZIMHPPHMF.DPNMJOVY-NNLWBDL.PSH@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1713165268; a=rsa-sha256; cv=none; b=WgT7ZB+z4/xZo5BUiuk9X1aZ4kgWrIWzgM8nyaxFla4tZ1JKIyVm831gmPCxfQ/QJDt9c5 S6vnvZkD4lRH0Bir47KSb3aMkAe+UCRfneG76qhCVcUTjBWzIeqqpb9MkSNlIjSk0ofX6g xWxbiFdYA7xt9mvgMnAZRHMCmwKoqyw= Received: by mail-lf1-f74.google.com with SMTP id 2adb3069b0e04-516d46e1bafso1385321e87.2 for ; Mon, 15 Apr 2024 00:14:27 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713165266; x=1713770066; 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=dQnBVtrhJpUgOHcm+nS3apY4eRmi29T+h46zYZ5XaoI=; b=3PwfzN6jdPelYK0z3nM0Hpd8OD+qRUyZONDzqXdhwsAR+beKiAy3RY0YWNivAtKy8H W4vmOShbGZeyTb8viI1dfDJKqicjDMpS/13n1pMvJN+k3N0zuTFbO9CBa5L4ZKyLM0d/ 4JTx2yboQ+XrO313dWPde/MxgW5fmjGQ1ljoLQFMzoj1JYquIKPBnnK7DskEptoNzojH GnilU7ZgGVrSEaEb0tMckJX2c1Ym1c3iglzTtbMarru2BFBC9KRzqFPX4CmN1cDI4HjK pzAfiolaHKp78qLzCvbC8zTTV476SpiAJkfDh6uxOyM2pkm0QTx4lbj8nF3e2MCU4W2d gkTA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713165266; x=1713770066; 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=dQnBVtrhJpUgOHcm+nS3apY4eRmi29T+h46zYZ5XaoI=; b=mb7YGH5k04ZZRod7jMctOGEqqPB1S8P7xRaopaNrx3Uaf5nyUA0eXJUgIo9y/WAEGh zZ4e0b7MUyk73J9dTv+L+B28eoCWRROPJWEedR05qyo4950b7sIxzBErCFMhg1KbEjia jceUVESHRA/HHEgtpFS2SSMWJT3l46Sk8OeFemuK09VxfceNh1aQTaD1EzOHwRske1Ar P5GURGLUWQA5uOOJEHwGY7sdWajx/V+xTYDXOprv4FWabE892RovkoqLL/ag8vuh8sxO jWOFVBDLUBzuiiurTROjd9V1S1wPkWZReLWe6ZKCPe/YuRx5MWc0G38RxZ5gslffxKvy wDiw== X-Forwarded-Encrypted: i=1; AJvYcCU4VbvaizMOQw+oyU/6UyZrIz+LUWSZHw1ffE+hwuOrFs/qFeRFy9e1JF3q00C1SwUZhU1Oa50Qivi1HR7fUYaKmug= X-Gm-Message-State: AOJu0YzNF9I6z0Mbph2U7ndtoL0+SbZtP0KH3lRq7IKj960ANpvZhNWE S105xxrA60zeq3QdshwloYldJJB1KEG+O3yw6yWUkdr1C9Wq3gUs2FCqgA589gdvP3KySHomJqo 2o8Zs0nxpXtTNAg== X-Google-Smtp-Source: AGHT+IGj4s5XcuUlnHXAqbbbB0vr64kBb3ewtMkKntnALdO/9Wx+FqLH+bIRcaQ7/jFxocSOccqLI8Do0Wig5+w= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:2c8c:b0:518:c9cc:f169 with SMTP id dw12-20020a0565122c8c00b00518c9ccf169mr2703lfb.9.1713165266687; Mon, 15 Apr 2024 00:14:26 -0700 (PDT) Date: Mon, 15 Apr 2024 07:13:56 +0000 In-Reply-To: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> Mime-Version: 1.0 References: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=15423; i=aliceryhl@google.com; h=from:subject:message-id; bh=8G034x9QLKwhszhfSOV4sRo/vOkKD0+Y6xZHnepJVr8=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmHNPDsrivyGBAl1qNxYjiDLbuOvR9BBC9GJHRV SrTL5tsTTKJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZhzTwwAKCRAEWL7uWMY5 RgbyEAC8Hby5pqtDLGHCfFHFUfA2ZVFgjQRHb7wotVVMNsB+JBI+okpEmkq1hVQ9IKfIqJhp3M4 1x4USMZMPWhgRqW5axodDBKLmyTHx25xMXZzs30QZWBlAzdQoTDCd7/kg2ifWL65XKzq/zwCa23 URd08TKx9DxT4rrtzz351hEQiGHMqHAdv90PkVjpi2WciRbuJhezN1chFIQBfHaA3wjc9wOkCvP TnUiM0yfI8FtWa45XFjHzIFXfb8Ol+m+HlQaBRs5pLrnceju1Fx6gK3yTLZcEE4vYBDaN60EsZJ IgPy9KcygbA9eD+qC/62oP+6+fjRUcWsaJWbxXiW+4j143NnHBMVuABzAJjv2plFjG9cLXF9H+L 7o7TJv8jRtFy9pJ3PMDk1sIv8P5az9x1ZLvopcCb42By5FyIOTVONzU/lP+7VN/rNGaRRm3dyij 0p9KtomDU9I4AvMG+RVOKpcGCEr4vraHoXjKqvu+VMwIj8q9ZCkdP+2HHZOHKWBnoWeZYItXExR mk195VQK4ICe14p7mz9yVNkC6CJ9ddk0OU2HXugUrBS3Rvr9td5Vf+mtdRua8sptmOq4/nta/uC NyXMM2Kwvtz76AFraOwujbgfAsmlAYAcIVsoAYy9n5oI6mef2PQIQ15or4w89JHnLrBMygqRoCP nSz+HTDGgKd+Ndw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240415-alice-mm-v5-4-6f55e4d8ef51@google.com> Subject: [PATCH v5 4/4] rust: add abstraction for `struct page` From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj=C3=B8?= =?utf-8?q?nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspamd-Queue-Id: 5850D80011 X-Rspam-User: X-Rspamd-Server: rspam02 X-Stat-Signature: uz3y7kfjkw3iwwfj9naeto1uyeo98kms X-HE-Tag: 1713165268-342097 X-HE-Meta: U2FsdGVkX18WvUksNrgwi3FxsaFP2xFmvdxGVElL0lGCIiTuX+Kvd8t2wqR1hPGEeA0WQi/IPo+kbcSyrGFEVVADD67ZnxQo3zZxZXFd7aTufup/Kp8u895VWhh+SuZJJQKQTwSlxjRnHiREyoawPCzqowRFMPpXeuS9segmDHCUBS7lk0YsqjTWsLGxpX2r0LYDhtzceD2VXTm9Dm8cW9S753wu5hgWUOpo8dYBEwO+s7rxFhKX207BE+X//8fMXMniKFhxE1Qd9jtkxZ23XwYkJrv4yqfNvipL1gRwhZtpPn4c/VmptrKuQGZ9NWKVFIx+9+zqP/UFs1Kiy+B7+lmAsP55ID6gfc1XKLt9ycoNSNhFN6KuW6HYFEh5QTV4pCRi42/v4w+5c1juq1We+IAaBHRnMvGff+Cg4n6SpjD5swNqlxYVgko0xa6jcgFJWHJ/MirU2Vi/c2ZxjxwerW7gElKrdsaVS5D0jYnf2QamDM8jpXXOMG4BPWXquWp7uF5tfsS6v+FqlhuoATTpzIJInX7tyG1uB8rYjQqvuVwWSFXOOf9ctrueqlh1gimho6fupFrj4DOTzfIoeFABivestmahuk1dHE1C2SfVpYEnlDcblJhjNYIrh5Gv2Xg9nWXhsokoThxRgP4OE1uR7GLfns+k0y7r9h1yNFt3VsR3Bx2ZDs2UDUNIK+RAYaCpwtpKJVm7kMFSZHopX2dLiqzn6rEviJhoi/uzvkUK/fVKRbRfAPVlfh3ByYHnaHb8a3Ow5bloHudOxACu5NxrKkIxUGulAR1hok346rAHtkScotsaF6PpxkwQ7q2LfloG8mwAPbtXQaUigmgOrrM9zhcuO1Gh7MohM91ytgW02mt6ljOzCK1tVAocHhU/eFJb2lflCqVxc4r41C8dWK9iMQlCp+CEaO0eTxAU99Wx27U/f4WtQa4MMf5ZTxR52pvI+Dw8dyOIzFW7vCDsQQa +ua8vyYU eMkdGPnx7miaKVgJg5lXRgaogJ7VbrAc14ST9KESkk/LnFNSpw6lM/eDnP2kprC3s6LdiHj8nRr2/+bxO3J7g/9iFEybq4bx7C+sRV7VF7YExkpYi1mT/pgkSatc7n8y0mO/go78e5qRTnefqiCbcLJtzoz3KMwWXVlJdQ8KPa5ci9SzzEI0YSqbBN0CkHkG3ih1xW1ExJ6GdRZJzYsPEPfadMdyEa/fDt3R7kOZTwAjYvK8oOta1PNXLD8pNodlduO6jAf/ID9e+Nb3xwxwqNh3JByY0mo7F5wpQaVtIv/ljLo0Q993GTl8G0Q/2c1ixw9Wuvz2asKVexjwR5HeXNloro1KknvjvKj+T3i48OGwOAl/cKErlAPU41lUZVemR4BQT/na8oRsLAXIyh3Yo/8TNBSdZENhD372AOGD2vTwWENif/AAshAq3oSDkEObZwpczXUkE4VyaqWUemEXDRVMY0fVZEsd5jP4frMpW+G733WtMp6MDw+Z0elnIpu76IeU0CwDP7blTuCjq+o85tNQE6Auk2AiursnkaW3lbXHGcdDWYQdJH4+Ip3RDQwv2xKSPfc35cTE6JvdizVF5uMrZT8I0z2npZ8FaOEA7vBucT1xK2dsBOv8W/rDgulhqww/bY+iDx23Flwu2UCYxczM5p33Qf19ctu7LDMDOnylucvfEvMLgqvWcKPH/3v+dd5vp1KLKHdYeAGzdri9znJ3BEdi/rPYvwAlU 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 by introducing gfp flags. Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Signed-off-by: Alice Ryhl Reviewed-by: Andreas Hindborg Reviewed-by: Benno Lossin Reviewed-by: Trevor Gross --- rust/bindings/bindings_helper.h | 2 + rust/helpers.c | 20 ++++ rust/kernel/lib.rs | 1 + rust/kernel/page.rs | 240 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 263 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 65b98831b975..da1e97871419 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -20,5 +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_KERNEL = GFP_KERNEL; const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO; +const gfp_t RUST_CONST_HELPER___GFP_HIGHMEM = ___GFP_HIGHMEM; diff --git a/rust/helpers.c b/rust/helpers.c index 312b6fcb49d5..72361003ba91 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include #include @@ -93,6 +95,24 @@ int rust_helper_signal_pending(struct task_struct *t) } EXPORT_SYMBOL_GPL(rust_helper_signal_pending); +struct page *rust_helper_alloc_pages(gfp_t gfp_mask, unsigned int order) +{ + return alloc_pages(gfp_mask, order); +} +EXPORT_SYMBOL_GPL(rust_helper_alloc_pages); + +void *rust_helper_kmap_local_page(struct page *page) +{ + return kmap_local_page(page); +} +EXPORT_SYMBOL_GPL(rust_helper_kmap_local_page); + +void rust_helper_kunmap_local(const void *addr) +{ + kunmap_local(addr); +} +EXPORT_SYMBOL_GPL(rust_helper_kunmap_local); + refcount_t rust_helper_REFCOUNT_INIT(int n) { return (refcount_t)REFCOUNT_INIT(n); diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 37f84223b83f..667fc67fa24f 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -39,6 +39,7 @@ pub mod kunit; #[cfg(CONFIG_NET)] pub mod net; +pub mod page; pub mod prelude; pub mod print; mod static_assert; diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs new file mode 100644 index 000000000000..f7f8870ddb66 --- /dev/null +++ b/rust/kernel/page.rs @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Kernel page allocation and management. + +use crate::{bindings, error::code::*, error::Result, uaccess::UserSliceReader}; +use core::{ + alloc::AllocError, + ptr::{self, NonNull}, +}; + +/// A bitwise shift for the page size. +pub const PAGE_SHIFT: usize = bindings::PAGE_SHIFT as usize; + +/// The number of bytes in a page. +pub const PAGE_SIZE: usize = bindings::PAGE_SIZE; + +/// A bitmask that gives the page containing a given address. +pub const PAGE_MASK: usize = !(PAGE_SIZE - 1); + +/// Flags for the "get free page" function that underlies all memory allocations. +pub mod flags { + /// gfp flags. + #[allow(non_camel_case_types)] + pub type gfp_t = bindings::gfp_t; + + /// `GFP_KERNEL` is typical for kernel-internal allocations. The caller requires `ZONE_NORMAL` + /// or a lower zone for direct access but can direct reclaim. + pub const GFP_KERNEL: gfp_t = bindings::GFP_KERNEL; + /// `GFP_ZERO` returns a zeroed page on success. + pub const __GFP_ZERO: gfp_t = bindings::__GFP_ZERO; + /// `GFP_HIGHMEM` indicates that the allocated memory may be located in high memory. + pub const __GFP_HIGHMEM: gfp_t = bindings::__GFP_HIGHMEM; +} + +/// A pointer to a page that owns the page allocation. +/// +/// # Invariants +/// +/// The pointer 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. + pub fn alloc_page(gfp_flags: flags::gfp_t) -> 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(gfp_flags, 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(&self, offset: usize, len: usize) -> Result { + self.with_pointer_into_page(offset, len, move |dst| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then it has performed a + // bounds check and guarantees that `dst` is valid for `len` bytes. + // + // There caller guarantees that there is no data race. + unsafe { ptr::write_bytes(dst, 0u8, len) }; + Ok(()) + }) + } + + /// Copies data from userspace into this page. + /// + /// This method will perform bounds checks on the page offset. If `offset .. offset+len` goes + /// outside ot the page, then this call returns `EINVAL`. + /// + /// Like the other `UserSliceReader` methods, data races are allowed on the userspace address. + /// However, they are not allowed on the page you are copying into. + /// + /// # Safety + /// + /// Callers must ensure that this call does not race with a read or write to the same page that + /// overlaps with this write. + pub unsafe fn copy_from_user_slice( + &self, + reader: &mut UserSliceReader, + offset: usize, + len: usize, + ) -> Result { + self.with_pointer_into_page(offset, len, move |dst| { + // SAFETY: If `with_pointer_into_page` calls into this closure, then it has performed a + // bounds check and guarantees that `dst` is valid for `len` bytes. 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) }; + } +}