From nobody Fri Feb 13 15:42:20 2026 Received: from mail-lf1-f73.google.com (mail-lf1-f73.google.com [209.85.167.73]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 13AEA1E498 for ; Thu, 18 Apr 2024 08:59:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1713430777; cv=none; b=NeipFsYsNf9vQlTyEdj4rdfzlOUEMRAfNqKINM9zmkXiSqAxxDdxKkofCFggq+Fi96KUHRg+FkLJ7TnV/dspM50WIaGsOj3p5/J+/AKR3GDL+ktoNKMU9CcT1VtvMLI8fYjAKyJ22/Y+brQzA6/yDOTVeEd6ms6xZU1/oPx5MTg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1713430777; c=relaxed/simple; bh=2JondYFnHhIssn6wC/zGKzwrV5WsJAnpzq6WqSlXDWQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=h0JWdjrzOGHvSdXq2x76RE9vRISCNhZexgv5ab1Sw20go6sm8A57lF0T3rLfJCqYDDmfXuRRlnS/5Hk40d2qJNOALQt0FjTwdk6hu6hD5AAB9AzRjVzlLHNy4843UQcSUIdBotL6zu+wnigkixrqdFGnHvy3QMK48gWOvXNGMdo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=SSOhRRvD; arc=none smtp.client-ip=209.85.167.73 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="SSOhRRvD" Received: by mail-lf1-f73.google.com with SMTP id 2adb3069b0e04-516c97ddcd8so506062e87.2 for ; Thu, 18 Apr 2024 01:59:34 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713430773; x=1714035573; darn=vger.kernel.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=aOneHqkzjWbsXPBG08c1iIXkahak8VOduk+9lYv05Ps=; b=SSOhRRvD8yObD3Ypl3/sb1NLTZ3EtiKZHTuoXSw5inHV4LMoLR+k2rKOXr38H8wo7g AbbbJHuMQkWqIWtYwJS+bSAlSbdoYN/ThjSD4HjuNIugX+xrKzg0eLMKDwYvW2sbCge7 Z5JtDpPDUAKV/qPl+7Fdu6jdRuQIGq9bPk6b+prCQnCXTg4YZL7beVvWMpYxKgaeTjEy Z5xRvHTXeHnUSTWEWYPOTTdLPIGh4xnheJOgP5jVJeZ7trpOs/qd8dm1dYDp4DU2un4V KWNLXMPvoGDIjniAn17S2YunpgF8s7aiG1Vjyhu3GdjAUOm+iN4L/o8yxugZRjozQKFL JIbg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713430773; x=1714035573; 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=aOneHqkzjWbsXPBG08c1iIXkahak8VOduk+9lYv05Ps=; b=kW1o9QeKjLVHUaQ19TRtWXDav7Clz+JW0pRXx3d7CL03hv6uZqiNAda3fhf9sSZvwq noy5xEpTsOIbX7/KJuaFPFg14NmG/RccrXlvVs9HkJ06g/IIIdZA2kpFXZmrgyNzKMGj Zx2NjrkNimt97jcDXv9uOPHG3XYBxlJfyrIn0qSxSpG1exS8dBini4caZFjNzxn/y+sw 6ji5zjSmlSOv//p2Cme6KCcGlXhqj+u/blP+oHvxVBZgEdjP606oiAoqHpgqVnDrT0qg +2BP4WvnVD4pIgd0Y2Ol01940SLmwlaztHAUkYbrqwhvLqKnn4seqf6Kg+Siu8Z02DLk jPkA== X-Forwarded-Encrypted: i=1; AJvYcCUGZg0RSu8l+yqtb0TpAiiIdR9jYVbkgWNYwXD16EXZY66FGk3MzJkCZC2WOo8Vtxd2GAstzI42EdcPNRUavDvmXXWoIbZ4E9LHpMk2 X-Gm-Message-State: AOJu0YxAUbI9jqYrM/cKIDEHQ0DaDVwI3HEoJgjoRBxeBI02rONvSWFb gQMgnUEyVG3KM77yqOmraRjEPLubukZ9KlQMjOCWcmktRLOncyZZrDLXexSKOX2e0zqfgnWNOnL rFGHzvf48jQONqw== X-Google-Smtp-Source: AGHT+IHAzlRE+T5ZNzdf0n0yMnp0TRPLdqGfxRE+ai5i4Jw9MhTAF5YG02+gMQDX3d5VCntdRnGFyCJrt8qMyG4= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:ac2:5f63:0:b0:518:b58c:5232 with SMTP id c3-20020ac25f63000000b00518b58c5232mr1940lfc.10.1713430773184; Thu, 18 Apr 2024 01:59:33 -0700 (PDT) Date: Thu, 18 Apr 2024 08:59:17 +0000 In-Reply-To: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=15853; i=aliceryhl@google.com; h=from:subject:message-id; bh=dZfQOYQEGgz9vrwD+/QIrkBZiZV+Ak86iv4sMvdKcZY=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmIODtO+zgTchi2fWbmMoR8hezbeVKozC/rxnIH Fk8vU/95riJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZiDg7QAKCRAEWL7uWMY5 RvLND/42zY+nfrVdUZqjFKVr1NuzgOb6/IvXeHq8K+LMoavlpt6BGSIPiUfSuaEFgRDjkzDpnjt ucFzGZDWx6oCN/4lstzEucyIjWNxnR48QfRlZhM/OrvCiw2HR0yjRmKc83kWGacLIaNtQeePU+6 zwOH7xKJmrrUh/KA9KLZFOhgifzCeiRaCIqheoNh3M7q/KA8aRED9PBf6be+GRnfSlA/fdfrT9s 6UWvWZtr2ONv7R3Trh/klpANVtgEShr8lVmV5t0EQEmp+8Ni+DgpdhBn04FmrnBcSCKN1g7Dpo/ VlOlIKuleHV8Ja5xqk005npof0R1Xs9dT5lJREWO/ufD+UDt37h9CbQFbrmFG6PIC4/1vNvW5dm S6oepiulmGFRbMYLUCe3ujygDWhRct5X+VJow266U4Fvz+BbBL4YpfXpMDHCyJatO9c4+QqMv9c CjEcwZCayTr8lOF9RV10UhJ5dnJ49KLVrG8b8qCth/WADCcxVeSSKlHPWKBNgzTm75LMVpkJULF sKeTd64ya0OhpmgqM5S8jN0fmd9WrghxB12UAbY4sAYlkcvZbleRXowd9WuisyblzKNQCke5IBp YRtVnXcWpzYcAqRf7AeDVZXTxNJVCczFb7UH+M6PgYy1dktDn0ZT9mZBpjg2+LHk/eT2d/B7kRm pkb+sg3dqEm2CEg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240418-alice-mm-v6-1-cb8f3e5d688f@google.com> Subject: [PATCH v6 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=B8nnev=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 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable 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 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); =20 +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 9a943d99c71a..7ee807ae4680 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; =20 #[doc(hidden)] diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs new file mode 100644 index 000000000000..ee5623d7b98f --- /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 =3D usize; + +/// A pointer to an area in userspace memory, which can be either read-onl= y or read-write. +/// +/// All methods on this struct are safe: attempting to read or write on ba= d addresses (either out of +/// the bound of the slice or unmapped addresses) will return `EFAULT`. Co= ncurrent 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 f= iles 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 va= lue. +/// +/// These APIs are designed to make it difficult to accidentally write TOC= TOU (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 pr= event 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 locat= ion. +/// +/// If double-fetching a memory location is necessary for some reason, the= n that is done by creating +/// multiple readers to the same memory location, e.g. using [`clone_reade= r`]. +/// +/// # Examples +/// +/// Takes a region of userspace memory from the current process, and modif= y 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) =3D UserSlice::new(uptr, len).reader_writer(= ); +/// +/// let mut buf =3D Vec::new(); +/// read.read_all(&mut buf, GFP_KERNEL)?; +/// +/// for b in &mut buf { +/// *b =3D 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 =3D UserSlice::new(uptr, len).reader(); +/// +/// let mut buf =3D 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 =3D UserSlice::new(uptr, len).reader(); +/// +/// let mut buf =3D Vec::new(); +/// read.read_all(&mut buf, GFP_KERNEL)?; +/// +/// // THIS IS A BUG! The bytes could have changed since we checked th= em. +/// // +/// // 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 ad= dress and length, it can + /// safely be constructed inside a kernel thread with no current users= pace process. Reads and + /// writes wrap the kernel APIs `copy_from_user` and `copy_to_user`, w= hich check the memory map + /// of the current process and enforce that the address range is withi= n the user range (no + /// additional calls to `access_ok` are needed). Validity of the point= er 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 bl= ock 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 t= he 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 th= is operation. + self.length =3D self.length.checked_sub(num_skip).ok_or(EFAULT)?; + self.ptr =3D 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 des= cribed 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 =3D=3D 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 th= e 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 ini= tialized. + pub fn read_raw(&mut self, out: &mut [MaybeUninit]) -> Result { + let len =3D out.len(); + let out_ptr =3D out.as_mut_ptr().cast::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) =3D c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: `out_ptr` points into a mutable slice of length `len_ul= ong`, so we may write + // that many bytes to it. + let res =3D + unsafe { bindings::copy_from_user(out_ptr, self.ptr as *const = c_void, len_ulong) }; + if res !=3D 0 { + return Err(EFAULT); + } + self.ptr =3D self.ptr.wrapping_add(len); + self.length -=3D 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 th= e 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 u= ninitialized bytes to + // `out`. + let out =3D unsafe { &mut *(out as *mut [u8] as *mut [MaybeUninit<= u8>]) }; + self.read_raw(out) + } + + /// Reads the entirety of the user slice, appending it to the end of t= he 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 =3D self.length; + buf.reserve(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 nex= t `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 =3D=3D 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 t= he write goes out of bounds + /// of this [`UserSliceWriter`]. This call may modify the associated u= serspace slice even if it + /// returns an error. + pub fn write_slice(&mut self, data: &[u8]) -> Result { + let len =3D data.len(); + let data_ptr =3D data.as_ptr().cast::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) =3D c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: `data_ptr` points into an immutable slice of length `le= n_ulong`, so we may read + // that many bytes from it. + let res =3D unsafe { bindings::copy_to_user(self.ptr as *mut c_voi= d, data_ptr, len_ulong) }; + if res !=3D 0 { + return Err(EFAULT); + } + self.ptr =3D self.ptr.wrapping_add(len); + self.length -=3D len; + Ok(()) + } +} --=20 2.44.0.683.g7961c838ac-goog From nobody Fri Feb 13 15:42:20 2026 Received: from mail-yb1-f201.google.com (mail-yb1-f201.google.com [209.85.219.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3FE8A15ADBB for ; Thu, 18 Apr 2024 08:59:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1713430780; cv=none; b=p+I+FIBWf8d1G0gCTcqb5M355HN0RXfV8R9+pJbuvFE3eaNag6jsEVgKqp0se36+XDTlT48+0oREng/REV9pzFjHqrbh10PRUQjmXpCyAI/6+RGbhUOqYu1Qpm5J2Qd8zxojCk9irWkouzIOUtaUrPgqcbkbEBavauFQ9YMiqd8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1713430780; c=relaxed/simple; bh=MLZbMFrdM327Iliqelcm2H6dceUinbo2Qrr0nzN416M=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=ujL/Nz/8YeU6ruACUIEz+HUnuzRUvZVcAYmtJeaumGxF4hz73AroYW48jOtyoJvi1kTSj1C9CQ8eF1Hod7oYIz6cqBfCfZBjawwFwhOoOKEVFgf5bOFVCpdCljsnp9M1ionB5SG+/ecL8rHPKrQnE8Da9jxwXAj01sR6MP7naX0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=mbfVh5m7; arc=none smtp.client-ip=209.85.219.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="mbfVh5m7" Received: by mail-yb1-f201.google.com with SMTP id 3f1490d57ef6-dc6b26845cdso1207833276.3 for ; Thu, 18 Apr 2024 01:59:37 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713430776; x=1714035576; darn=vger.kernel.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=MXu0ivdSThjPNuQSvbrqR8EgqUkoc/lgNPsqzGk09fE=; b=mbfVh5m7hOGpfGhG1YlQAPS1XMw5wBZmexgAcT7GiZ5pu5EkUkEO2YNGBAvZ1uBvdN onVuHCo7bXVhC8t6HTC0uCzrTbP8zqHAO5WSMoY5845fTVpo+NDaYDATdLZx71QyCKcx lECyehnElthO6FS1N9M2Rymm9a6fc2Wh2L5QtVImI8Ri8qEDOIi3iiF6A3Vazn/5Ixy9 EVl68wv0NIghyCgTRbDp375FBFC5LtXxmSy9NiEWcLtDWPxJuh/MJGzSz6JAzz7KodJS FyEV2HsbyrOs+GgDky2zF9Lt3lAg6Osoe8LvUrj03745tICGAyRWWqdXhCsTNTG7kwhe UshA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713430776; x=1714035576; 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=MXu0ivdSThjPNuQSvbrqR8EgqUkoc/lgNPsqzGk09fE=; b=mIGiaTunwgQButO1gY3MISmSitkJcZg83URqDbdnMZjYZcdjJVJr7gJQnCrQcWDvxN kEiUNchFrTCewPQ0vKj6/S+JuiTsH4RVdDruHgthipa7x8DpXMZhF+7JqnIjXpYoSTMy fSBaKUDC8pq1/cZbuOA6kpAAuLZKv3RUfuax5TCvyhLGFM3uvaCcBzSjAPftOEHXn9zk Y3V3wnreZA44ntpp7vUjJCxOR3oy6yuYpwkpwCHtRwd+u3k6bnNkIibeof6yCX5a1UGA HpaS09h7gRrMzjnFlQ78COf9C7QnX6Z6MP5xVqLNzykXM87U7/7b4oADVQwzfbsC3BTm 9OWw== X-Forwarded-Encrypted: i=1; AJvYcCXkO/i0Kn2XwN11hc3p64CzMGF7mqKNIqwPH5VwYXyLqIEwpNN20k+sRtGbvh+VntsnuCeb6wglVIOAZb2+qsrTHFzkhmnpjluxq/3w X-Gm-Message-State: AOJu0YwQbwdcJbvo1+cGNpJZz9UZ8O0etup3ydaig+dWzXElXzrjjpcM YYZxWTdMdxHS6Wl1tIYalm1CMFOmNF7SoRIUZeidDYtrAB+UksG5/ZEtPy482yJl6GCceeWqRwN 4J8JPWdAuN5zJTw== X-Google-Smtp-Source: AGHT+IGse7NZQ2hEZ3xo8zQMgk9GxHVA8CNqzQiXXjRdYigAwKQOE+Tfaeop+mtM1YJnE9wBINVVlzrjz7ZKuzM= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:1141:b0:dc6:5396:c0d4 with SMTP id p1-20020a056902114100b00dc65396c0d4mr546819ybu.1.1713430776218; Thu, 18 Apr 2024 01:59:36 -0700 (PDT) Date: Thu, 18 Apr 2024 08:59:18 +0000 In-Reply-To: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5122; i=aliceryhl@google.com; h=from:subject:message-id; bh=x1NaT6C4DcUL7cPQ6UUi0mTx75zJnB9XyZJjsIRI3Ns=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmIODuRjVdfd6NY/1+Lcn75vkKinRf3CAdt5vul 8uvXQyrNxSJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZiDg7gAKCRAEWL7uWMY5 RsQMD/9U/ASnGmCDYMWUzDaCj6mk7qk2+xp5uBW1ucNBWrMyAEFMHPc5z03wfq4unBKyUtxuda3 cVebYAtbaZbp63wjQikTVnWr0A/vRMMbHK4rrmsUpppJWFebPLU5dwepofmDp1dUe4AsB7b4v44 Jn+7LT1sf4rD/QVa/iBoA1/HkJF3dbe5DL9LlCgW/jjTpTjCZF6vyyTPBonT3KKig+kGVf/mDXW SclM6B4dwaEHWE0iDwimbzGZ8olTZkYgOFHe27YIGru8D0vpepxeUE/iWloev4BSDHBgwwgmQKq LBBbgpJsR9jRU8oDstOfLK8AsYQxwhrvsJ0jeTIETH+3NwaB4KRpj1oMXBoKKLWZub9Kp9t+A5M X1bYRKt82+DXipxSeLK3h6XfUzxER09cfcT8U+Q2yixZ9gATa3U7PDUwp6JuKVlkr6Z1CMWH2Fv iy2Rj3azGJ9KQTkRTM2WpdQzShrIQPxjmkLdeub4Tr8oN+5W0UT/ywuAUF9UDsEn/+0N5N71PpP m+0Dpv35ERh8DmxzzX4Vsoh/qEjJlG2mAloMcUfjjyMt7ooKb3Id971TlasNffkGf6yIaIsBpXl 79SLRmMpdwi7FC/KENaINLCDuv9cayQySDvWxrjE1LMAvl61aKImCYsNgbngS3vnO/CiR+/W2Hv PVWyg3BJIZCYi/A== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240418-alice-mm-v6-2-cb8f3e5d688f@google.com> Subject: [PATCH v6 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=B8nnev=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 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable 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 --- 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 =20 @@ -138,13 +139,18 @@ __copy_to_user(void __user *to, const void *from, uns= igned long n) return raw_copy_to_user(to, from, n); } =20 -#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 =3D 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 =3D 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, un= signed 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 =20 -#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, unsi= gned long n) } return n; } -#else extern __must_check unsigned long _copy_to_user(void __user *, const void *, unsigned long); -#endif =20 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 =3D _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 } =20 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 =3D _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 } =20 #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 @@ =20 /* out-of-line parts */ =20 -#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 =3D 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 =3D 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 =20 -#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 lo= ng n) { - might_fault(); - if (should_fail_usercopy()) - return n; - if (likely(access_ok(to, n))) { - instrument_copy_to_user(to, from, n); - n =3D raw_copy_to_user(to, from, n); - } - return n; + return _inline_copy_to_user(to, from, n); } EXPORT_SYMBOL(_copy_to_user); #endif --=20 2.44.0.683.g7961c838ac-goog From nobody Fri Feb 13 15:42:21 2026 Received: from mail-lj1-f201.google.com (mail-lj1-f201.google.com [209.85.208.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E682515A4B8 for ; Thu, 18 Apr 2024 08:59:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.208.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1713430782; cv=none; b=H2nrmajA++TPzH+DncLVYtLIXKU2ZCRam9wyXaV03E6ZBAmWAS0K6AD5TyCQsOfiOw9h6nqnHDxmaJuOujyF7cOljmYOZXs5LKJreajnse41kf9TBUTs6MjFQdATvvx4NCOt3THGj0HwWjlbObXir6uAFFiCEz99QR/m/VNjZLs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1713430782; c=relaxed/simple; bh=nI8Gb6Ut6mQQFRyrF/IoMMXllmm0f2L2teM9nYy0pQk=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=YP16J5IRdS5bkmpjmbOwuOBzyK1QUzgI81m5DvuTn8g7IfvE+CnIY32NVyCPorQAGi/1efRbhgRA5iSfG4Js4XEtmOHtEW4SR8qaozqC1adJS6TneMKfbJYNoEhUs8HCw1KjoKtKVa0O2o+zjuyCeYskau5L9JZ7dAEC10ZomhY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=pKT1lB/h; arc=none smtp.client-ip=209.85.208.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="pKT1lB/h" Received: by mail-lj1-f201.google.com with SMTP id 38308e7fff4ca-2d8a7bb09afso5655421fa.0 for ; Thu, 18 Apr 2024 01:59:40 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713430779; x=1714035579; darn=vger.kernel.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=HgZdNi+a47HOfHsTxDpJlGILwCywia5g2y3UnrPe+eU=; b=pKT1lB/h1ceYRvXCxJ6fyVp+CUEA53mKc6suFUBMtQZ87Z01CxL4Zx+btMHFUSs+i2 sVLkrhk7L/KWGAMI1DGJ4hn2K6j4XenlMKNkld/7b4WF26uroAOlqAFFh1m6rErlhaeQ 9X0jEfy7LRbzhxku48OYmn5EVDwFU6Kj8dRCUmuTfH1bSKxfRi9Yxo+ciM6NE7t43tHN 4/t+RtVo13G62V/eaeNr8nFYeqDTqWMnjnGaJE3WBDng4CKQd3IgXyhELTKjD5JrsVLb CANpU1rHpqrERqi0Y3q2JDvfbbOl+nTrZyoL7sdcJ/5B0JOqn+94bxs9l2fn8Nbsq1Oq zHEg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713430779; x=1714035579; 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=HgZdNi+a47HOfHsTxDpJlGILwCywia5g2y3UnrPe+eU=; b=D2dJwq7z+Fg1OaQh5U5PL5WQXzYF6R40NqWPKFalA//qtQlGXs1qnXRFZLEbkA8auV IweK0rEz/IWl7Gr3Ml1Zf8YVrGSIbgip7aU+8FNdNw04qCt5m/OJcv+eN4jdFCn0TM5Q Rix4owXRBa7nCgYGznBdBOWf6AGkMOTDZ3kzFmBHhf9HfbNCvIiXcg8zERDDp6l7XOJ1 Y3cN+pTMFebTX6a5NsihIr8kYsFbwYO9dr2P6ecTPGn6qDtCp2gog+9K5poz7Lw67lT3 nGGKm3gFzN9qnKNnFFvZyPylabRtGGFYisqrTRUfEsTNRsF3Xm4abcwIfeLI0GBMqggl 4qVQ== X-Forwarded-Encrypted: i=1; AJvYcCWgJ5jVLEm1Wodw37rxZMipRTqkojKHbuCQRxNKg6eimM6UN/Sn8/5zd+GI6ywrZE2o91Aljr/byZqoa5zJ56eteB4SRjZBZnwU+C27 X-Gm-Message-State: AOJu0Yw0ZlOr3FP3eh3X8uGFb2sp5jwTzGP/r2p/CpfpRdXNX0l+tgPA 9NUMsoMh68JULAgS4DtM4zBfdekFHH2Js77ZeXPNpP6Qbh2sFP0lJqy2VONi6yNOQJOCwkoCvdl d7U0W/iuxb0Q6XQ== X-Google-Smtp-Source: AGHT+IH6ScDtDrgw+IgQwpvtBZKJlRmNiyvFjb4gONlBnfX6IBw590w36dZkN+MXAX42+StYgo9t80UV0fKV/JE= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:512:b0:518:bd37:87f2 with SMTP id o18-20020a056512051200b00518bd3787f2mr1938lfb.4.1713430779142; Thu, 18 Apr 2024 01:59:39 -0700 (PDT) Date: Thu, 18 Apr 2024 08:59:19 +0000 In-Reply-To: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8978; i=aliceryhl@google.com; h=from:subject:message-id; bh=nI8Gb6Ut6mQQFRyrF/IoMMXllmm0f2L2teM9nYy0pQk=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmIODvS6oNsms6X0YHcmuKs7EizEym1tAEymjog Q30/NA20CSJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZiDg7wAKCRAEWL7uWMY5 RncsEACrSjtg5WqYkwrxGPaVxe3pCJO44xelyaMAJzezxUveUUN5hRIaFILfZELJj21aJsGBbVu l5N9yhyek7O3RPzQFGOzyapoR0QkuNWswj8JdEFq34/xHTp02Dy0WRmgxYUeIyQo+CkH+epFXbA yLxSgdLPnaqwYLFkJL6W5fwIbas8WiKJyS7u/Udsd+14bj2lHYAYCKosI5sSyJbIaRX4ODOrp9F BNHlogeI0A9yixFtpGGvN8z+kLxbDNafpriT58EFMWb5WmrXUjW6w+nxdvj3byMBWWqo3FxHHmt O80OQrBHRpoM5az1Xz7ctWqayHAL1Q8VsbQCu87jrGxP8BFwhvnYpHS1G9LtlkuBXeKLEKmlx+U D+fcJj9z/3j1P8biVsbOFvv/64U8re5ZdjqRyOqBygddDFvMEVkY9jW7n7Z3NtPyMuw8vQn8Prz DEAp2pVwpkf7Luo7EZhM431ixMB1xM1F0M9590356xT26n8/qycKA8X6ApHtnC30MoQLF8PXEte 4eMs4UvJmDodAIddQUXiz+Kj0FhmLVKyq85a2LEXuJuocTEzIoW7G1ytgOSkfmWFxmzjfa241x8 MrruNrGto/mokKkTJkN9fr0Yr5NZeVs2OmcAPCWihtjiUChNskjqHNalBFknaZUrbLknfBkVYee XKo2SmbVJZgp8vg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240418-alice-mm-v6-3-cb8f3e5d688f@google.com> Subject: [PATCH v6 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=B8nnev=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 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable 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 Signed-off-by: Alice Ryhl Reviewed-by: Gary Guo --- 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 8fad61268465..9c57c6c75553 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 o= kay. +/// +/// It's okay for the type to have padding, as initializing those bytes ha= s 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 uninit= ialized. 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 add= resses are also considered +/// sensitive. However, leaking kernel pointers is not considered undefine= d 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 ee5623d7b98f..39481e374c40 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) =20 -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}; =20 /// The type used for userspace addresses. pub type UserPtr =3D usize; @@ -247,6 +253,41 @@ pub fn read_slice(&mut self, out: &mut [u8]) -> Result= { self.read_raw(out) } =20 + /// Reads a value of the specified type. + /// + /// Fails with `EFAULT` if the read happens on a bad address, or if th= e read goes out of bounds + /// of this [`UserSliceReader`]. + pub fn read(&mut self) -> Result { + let len =3D size_of::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) =3D c_ulong::try_from(len) else { + return Err(EFAULT); + }; + let mut out: MaybeUninit =3D 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 s= kips the check when the + // length is a compile-time constant. + let res =3D unsafe { + bindings::_copy_from_user( + out.as_mut_ptr().cast::(), + self.ptr as *const c_void, + len_ulong, + ) + }; + if res !=3D 0 { + return Err(EFAULT); + } + self.ptr =3D self.ptr.wrapping_add(len); + self.length -=3D 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 t= he 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 -=3D len; Ok(()) } + + /// Writes the provided Rust value to this userspace pointer. + /// + /// Fails with `EFAULT` if the write happens on a bad address, or if t= he write goes out of bounds + /// of this [`UserSliceWriter`]. This call may modify the associated u= serspace slice even if it + /// returns an error. + pub fn write(&mut self, value: &T) -> Result { + let len =3D size_of::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) =3D c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: The reference points to a value of type `T`, so it is v= alid for reading + // `size_of::()` bytes. + // + // By using the _copy_to_user variant, we skip the check_object_si= ze 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 =3D unsafe { + bindings::_copy_to_user( + self.ptr as *mut c_void, + (value as *const T).cast::(), + len_ulong, + ) + }; + if res !=3D 0 { + return Err(EFAULT); + } + self.ptr =3D self.ptr.wrapping_add(len); + self.length -=3D len; + Ok(()) + } } --=20 2.44.0.683.g7961c838ac-goog From nobody Fri Feb 13 15:42:21 2026 Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5604715CD5A for ; Thu, 18 Apr 2024 08:59:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1713430786; cv=none; b=npP59DWFBcv7SOiS4iAjOnipAoSwIkOLx4oho8v57DTCz1vKX8vX5cw4uZwfKny1uYmrjSSQE+8a8aqOM1hcwmFLXyPhipAq7ivcSw3uSuJW88ZqIEFyRMhhJrZVUGR9AXv9AAb2ozv4jKoYAw9KInNRaFSDIb2LMpa8nr5SvtI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1713430786; c=relaxed/simple; bh=af0xmkxz5WwJ2caWqC4SIR0mhucvRiEoxb05tr7yw14=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=nNE/w+l3ecxrIouwzWnkzYP0+xgLTTKDw3VLkdZNUZ6DppNZPYQqTdsojqUPE6cOy+JlygRTzqT7PHMCeM+zQspqsaxhzXiFK0qjz4mgLQLaCmNEAoIx/pbPgoyHSMacb5DIUa7irD5WA9bHfImzIrQoQsXqNef6fwspaYK83r8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=jT4ig7/S; arc=none smtp.client-ip=209.85.219.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="jT4ig7/S" Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-dc743cc50a6so939045276.2 for ; Thu, 18 Apr 2024 01:59:43 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713430782; x=1714035582; darn=vger.kernel.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=2i7cIGrycSQYWPlCCdINwh9/UQnjF+IIqZAJpSGmhgU=; b=jT4ig7/SBcQGwiG/AHNFpUNlEaYF5aOmPfi7nYObQfHk5EEs2t+jZ0r3DJLUY80cXr iUyTc0qF/JAy8VyrG1VOp19j7R3pZeIoRqMqfPofLEU4ELAd/+2ejUK4NSfrbLJIIsqL AxZRh6cZBOILitDvNcXsrOuoXknarXBYbyZuq0zEXTULLfptccGbkmWMPmSEgYLp9YXH BBBOr9neEwotYBRUdNnSP38sWT7cJomXGwC2ApqtvLyaFziwt+zc5EoRAezVTBcMRDBj AVvb2TnTmrOOREF6Uib3zdL6UI4d0XDrLMOnqWMjxIwjG0T2NFBx9Dt7Okeu86rXOhdf CEDw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713430782; x=1714035582; 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=2i7cIGrycSQYWPlCCdINwh9/UQnjF+IIqZAJpSGmhgU=; b=QF2NYWAyKykdBoKiT07B8gad1IbIHNdVkYEI5hMLKhuyl7HQQs1CsnOUfp6S4NyJJO RDFCuKzktBQwaPK2L9HXv6g8i1k1+RlJrmUorhKGlsK1vObd2jN3wyGti6Gay8JYlsMu RddejokY8uO4xma0XbRf1vQDR0umLatrIlmUoUJyc/hKFc5/1/ZA7deWQVMEGS+N8eQo kkWQ8hC3VXPMax2sa0FFaMcBTNcTvXkwx5IRfdEb2A3oleP5cXO30DuI9Qfw5bk1TxG1 QM8fdEPwG1BMXpZLtJceNfClqFb6lTEY3yNVzu8A3tf1hVEKMLFMt4luqziRDdYyfpBM J9IQ== X-Forwarded-Encrypted: i=1; AJvYcCWGbDbdcV0bn/UKa0fF7S09NIBMvqtnwy4jHcuF9QXnGizMeMSNXWC7+GfL9N1cSDk+m1Rm6KEbAhb2EVLVsbYA2qBwvwYrOJ5QapWA X-Gm-Message-State: AOJu0Yx8t9d9+WHzYx/M+y7gbKq+gx5ar2rUbV3tbIqs0X6k9lCWZb/S 1oJfHvLB3X7nDpg+BskEayXJvawif7nzPHUNoF33tajHVhRNtq4fCbh+NyzvaHi36Ylan/p6E88 rbaetK1klVMXjJA== X-Google-Smtp-Source: AGHT+IG+jY4+0ofbPAOxP4aGGV+IDNpzgvLMZWhsS1WIS60BQrHa6xxYtx5GVync8b3M5DHqH+EipzY/b+2qzBU= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:18cd:b0:de4:67d9:a2c6 with SMTP id ck13-20020a05690218cd00b00de467d9a2c6mr89467ybb.2.1713430782225; Thu, 18 Apr 2024 01:59:42 -0700 (PDT) Date: Thu, 18 Apr 2024 08:59:20 +0000 In-Reply-To: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=16029; i=aliceryhl@google.com; h=from:subject:message-id; bh=af0xmkxz5WwJ2caWqC4SIR0mhucvRiEoxb05tr7yw14=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmIODvBTN1EJk4q9WLN6UPNG6sSesov6EsZDtRE MaqZfGehSuJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZiDg7wAKCRAEWL7uWMY5 Rq/SD/9YqfoAjeuS9VklwHUSs1rn5vmzmFezb8JzHZ111jayAEZ1/AuITRgkAPPp+EY/GXWC9sR qSazhLjpMbJlQQVgAskubdzy63Ep6bsr/3Gwb9EnhVo+cZxg3JA7DP9y/dtrBBTcnwuSCxz9Q9N E4wScxVzeklnykkmwNHN4qiZ//mdG6b0FG3phZOIq+WAvWdhHxkQIxdODCWt6qPSvPntIj3+PPM 8fekPfWDKPdRmER+eWXAPQBfsKHdzBrRhj7frTBdaUELnd6evJrnduAtglFnqu2znIaRwomBHsW hMvEDO63+If+0T7pkWfEzrj0i4DPn7n4YaIMQwDYWdoxOWGiS/TUI3sRHFxGSL+7ooBt9SG7BRg j4oYk88EmNiiNR0Jad2E5UJj7lX2yiP/T+JWhFjBEKpN5FMs8Nrt7KfN4x0JWKvE5XpnaQoRYla rcqp0woeAlAzyGbo02t9PIb4TDQUwxTzsGgeMSxVq7izTevsrCCuj4LI6wbHCiSM2KIoSugK42l Pu1NpgPsiw9Ys2RWtLhiZ99b38voiTCrUVSfeKbfDKUdsLsZisaPcs8OTQFOq0FoyOULZCYKDqT I3b8KMNX9i0EfWQFLFCC7OpsoJBPfOH3RBtrOcEEcQ48hlvPvzHQyqAyLw6sm+nme1Ul+CPeo+T 7G1JpJbpOBZnLEw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240418-alice-mm-v6-4-cb8f3e5d688f@google.com> Subject: [PATCH v6 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=B8nnev=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 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable 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 Signed-off-by: Alice Ryhl Reviewed-by: Boqun Feng --- 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_helpe= r.h index ddb5644d4fd9..0862261cfbed 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -20,6 +20,7 @@ =20 /* `bindgen` gets confused at certain things. */ const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN =3D ARCH_SLAB_MINALIGN; +const size_t RUST_CONST_HELPER_PAGE_SIZE =3D PAGE_SIZE; const gfp_t RUST_CONST_HELPER_GFP_ATOMIC =3D GFP_ATOMIC; const gfp_t RUST_CONST_HELPER_GFP_KERNEL =3D GFP_KERNEL; const gfp_t RUST_CONST_HELPER_GFP_KERNEL_ACCOUNT =3D GFP_KERNEL_ACCOUNT; 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); =20 +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 f1c2c4aa22d2..7ab2b33f19d4 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -20,6 +20,13 @@ #[derive(Clone, Copy)] pub struct Flags(u32); =20 +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 =3D Self; fn bitor(self, rhs: Self) -> Self::Output { diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 7ee807ae4680..048e1662829a 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 =3D bindings::PAGE_SHIFT as usize; + +/// The number of bytes in a page. +pub const PAGE_SIZE: usize =3D bindings::PAGE_SIZE; + +/// A bitmask that gives the page containing a given address. +pub const PAGE_MASK: usize =3D !(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 thre= ad, so moving them across +// threads is safe. +unsafe impl Send for Page {} + +// SAFETY: Pages have no logic that relies on them not being accessed conc= urrently, 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 =3D 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 =3D 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 sl= eep. Other than that, it + // is always safe to call this method. + let page =3D unsafe { bindings::alloc_pages(flags.as_raw(), 0) }; + let page =3D NonNull::new(page).ok_or(AllocError)?; + // INVARIANT: We just successfully allocated a page, so we now hav= e ownership of the newly + // allocated page. We transfer that ownership to the new `Page` ob= ject. + 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 cal= led. The pointer might + /// only be mapped on the current thread, and when that is the case, d= ereferencing 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 =3D unsafe { bindings::kmap_local_page(self.as_ptr= ()) }; + + let res =3D 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 requi= red by `kunmap_local`. + // + // In other words, if this call to `kunmap_local` happens when a d= ifferent 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, w= ith bounds checking. + /// + /// If `f` is called, then it will be called with a pointer that point= s 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 t= his 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. T= he pointer might only be + /// mapped on the current thread, and when that is the case, dereferen= cing it on other threads + /// is UB. Other than that, the usual rules for dereferencing a raw po= inter 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 =3D off <=3D PAGE_SIZE && len <=3D PAGE_SIZE && (off= + len) <=3D PAGE_SIZE; + + if bounds_ok { + self.with_page_mapped(move |page_addr| { + // SAFETY: The `off` integer is at most `PAGE_SIZE`, so th= is pointer offset will + // result in a pointer that is in bounds or one off the en= d 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 `off= set .. 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 `off= set .. 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: usi= ze) -> 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` b= ytes. + // + // 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 `off= set .. 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 wr= ite to the same page that + /// overlaps with this write. + pub unsafe fn fill_zero_raw(&self, offset: usize, len: usize) -> Resul= t { + 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` b= ytes. + // + // 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 `off= set .. offset+len` goes + /// outside ot the page, then this call returns `EINVAL`. + /// + /// Like the other `UserSliceReader` methods, data races are allowed o= n 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 wr= ite 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` b= ytes. Furthermore, we have + // exclusive access to the slice since the caller guarantees t= hat there are no races. + reader.read_raw(unsafe { core::slice::from_raw_parts_mut(dst.c= ast(), len) }) + }) + } +} + +impl Drop for Page { + fn drop(&mut self) { + // SAFETY: By the type invariants, we have ownership of the page a= nd can free it. + unsafe { bindings::__free_pages(self.page.as_ptr(), 0) }; + } +} --=20 2.44.0.683.g7961c838ac-goog