From nobody Fri Dec 19 21:12:40 2025 Received: from mail-lf1-f74.google.com (mail-lf1-f74.google.com [209.85.167.74]) (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 A301A16FF5F for ; Tue, 28 May 2024 14:58:18 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716908300; cv=none; b=Q8B6B1oQEfGh+Mn8LDoFfNu9yuEF29naC+o8BHtVENo/zf9Fmm9+1HV5qubp5sk/NqpoSoFOT+4lmCktJVtc5Z2F3YZd7RYI3OOxmboLdAobBdJmaHmzqVGqAMotdObuty5PCDjNn9t6LJKX+NPyxI3mJvOhhrj/RVx+BMPI/2w= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716908300; c=relaxed/simple; bh=bAnCEa/erhDmZsiB7H9fwSPtBIVcIRW/I8ZTIy0mAKU=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=IOKpf1rNVjyyGQY6t6FvGD73CQb/9B9Lk7isoWKKhg4PFmC4OGUrSnH+EyeJ1OfynN1n2AOSVr8dUK/XBFxTfpmooy0YDEUv3Ge+M6n1fNGgA30rRgeQzj/1cPnecmSAy+yRB2Iqs6MfF4A3jTS8tc+qotxVV6UsC5c7fya34LE= 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=OH6vs6Db; arc=none smtp.client-ip=209.85.167.74 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="OH6vs6Db" Received: by mail-lf1-f74.google.com with SMTP id 2adb3069b0e04-5296043d77bso809042e87.3 for ; Tue, 28 May 2024 07:58:18 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1716908297; x=1717513097; darn=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=MbNhTCNPPg7usQjQRVAmhprE0uGhsuRXbAWwmmZLIiQ=; b=OH6vs6DbiQ+GOT/0A4xJJwWnwe8l1Sr24r7l9VfqCxEo+ks8a1+a/tuFiaXW11+o5S OoNCi0SQp8DkzG6Eyw1vbSQV7w46gkw9XLZh+iUtGdE2WyukimxZSKyG08wYkXV1Zb+8 JQiItXCFoQK+F19zb3PtbAe4TYmB6RWkhFC2Rg0vVI3t/bk9jHqesfgymzQjANgkJik4 vHzRDwJB7ZddPI9qgvIhRnmYp5N3VFDEWzU1EMMv1N3nNwJhpI6zaSVrqZJwNgwTnhOf sN/MPFetEgflwRennRELSoTfMG68TiffYGXC8JrejIxu5Kf0yWBu5JV2Sc2auFg9KCK/ dyqg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1716908297; x=1717513097; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=MbNhTCNPPg7usQjQRVAmhprE0uGhsuRXbAWwmmZLIiQ=; b=AZzfvhn8zhN8ZpuAO2fDIlnRu8wYo6UoyAwuCcgjIUowMhyDx8NVa7DIHcMfZY8Rpn mn3savc8gvk6B9LNF4OZITyBzMvSBfKhNB9T7DMCydACS6y8S8uACV9V45wxVMJWJwQn fhrnI3GPujYwkzi/wKwOSQxeV41Tyymcp4WPFXJ6su8CDNYJbv9MQVrLy1F9IoST3AiQ ghDV1srnbyj8TFmwjTpUGYde6DkCDzZ/B+L1KCV4v44KZKzteDRtqlhPzDoXLSsvhQX8 euh70JhWOY50sQtPVjn9FTe904cKgVR2Lsr8BieRhq7SkI42t2J2oyh3z3lD+FMx3eW2 d1Jg== X-Forwarded-Encrypted: i=1; AJvYcCWfgmXsjL3sVrcHv8qmDH5J7zhQC7XgoME9IdNjoy4zy2S46J9mxNpCHoRu4yNxP9nDLFu0t0Y7FpKUdMlHsppmbSkuO0PdTbd9G8SG X-Gm-Message-State: AOJu0YyBxlRncLGJWyUxk8oIMDZPc80AKKIvEHfaREAHsw0H0PicLbOr 9RffC/MypvwyHspnHTyuCTfs6wv2FtE0ry/y3HFpz9qQNLsoctuQwjQWW+sJtS7XTjB9x6TF58F S1mPDXlPQIDz/hg== X-Google-Smtp-Source: AGHT+IGKTzvYBVxuxp0VYfqRsp+nXS80+pOFrmh9vT+H19zk2AtK9i56hrMm1YftZM2YjXGr+riL5kwpUaFyUE8= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:4402:b0:529:ab01:8069 with SMTP id 2adb3069b0e04-529ab0182dbmr5757e87.13.1716908296723; Tue, 28 May 2024 07:58:16 -0700 (PDT) Date: Tue, 28 May 2024 14:58:02 +0000 In-Reply-To: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=15868; i=aliceryhl@google.com; h=from:subject:message-id; bh=xSbvVhrtFodD9MRESuXkcvT+XV4rvLfOM/6wExJZQsQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmVfEARqNIHiaKy6z316zm3PP79ctgWVQBabdCc l/fttkHreWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZlXxAAAKCRAEWL7uWMY5 RkTNEACIqh4LUos+sWpcJRx24EvZkwksLjc1ka4p+vlWBcvxp7SVkMsWwF2VtnKK8/bBDVOpbZV 2dsWXyio/j2tYPt6eDdqhMzhQnFfN3IKv+2r3OF1pbAWrgT80prHGMvDFpi+w4sNK6rHutxBKMq LM3W3yRYjI+4d7BkrgzmLszN3V44jFI9xj6VCviXzVHYoU/aO7tZGMqBizL+YiOetPxok1tKpGs 6JYq1WesiFFSJFNFNoEupEolZBNDNSYJVnEZ06uL8uyonk6yMU1NGmK4pI5mLO0mXk4kGIpwumr ZY7TPrbJM62OPgOHU0d5iTBCXG9M999lWdE5nreINZERUZv2FyQJo/zVnGkEe7nxmcf8WA7HzSW zMnyDACW1QooRkj3ZYxqloCMRiSMPWJsIrKFtFRxNP7kOUHj2DAU7wNCzsQiPBgUJBBhDB71Mbf k+YA+tiZwxLxamSC5UDoHhrIiobMqran1KtIKfihbIvfd7TlUFDn1Q/RC1Y4f5Mzkf7qMQRSWLj JXkb5/xtjvtzTeeSMP33sjCziO+zKGmnuBXvheSBs4OIzL+JqexdWTTIiAFJ+FVLr2Fvc8wpJJT DGfmORaBLX4NReBCJ/Ox9J/uR9/SV0Fu0DBVMWso2YJejWLADed2IEHxpx1uQtNn6EofSOLuYIB CrkyYbre7wKtgmg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240528-alice-mm-v7-1-78222c31b8f4@google.com> Subject: [PATCH v7 1/4] rust: uaccess: add userspace pointers From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=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 2c37a0f5d7a8..d6abe4bd45d9 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -39,6 +39,20 @@ __noreturn void rust_helper_BUG(void) } EXPORT_SYMBOL_GPL(rust_helper_BUG); =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 fbd91a48ff8b..767026db068e 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -45,6 +45,7 @@ pub mod task; pub mod time; pub mod types; +pub mod uaccess; pub mod workqueue; =20 #[doc(hidden)] diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs new file mode 100644 index 000000000000..77957d7ec011 --- /dev/null +++ b/rust/kernel/uaccess.rs @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Slices to user space memory regions. +//! +//! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) + +use crate::{alloc::Flags, bindings, error::Result, prelude::*}; +use alloc::vec::Vec; +use core::ffi::{c_ulong, c_void}; +use core::mem::MaybeUninit; + +/// The type used for userspace addresses. +pub type UserPtr =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; + VecExt::::reserve(buf, len, flags)?; + + // The call to `try_reserve` was successful, so the spare capacity= is at least `len` bytes + // long. + self.read_raw(&mut buf.spare_capacity_mut()[..len])?; + + // SAFETY: Since the call to `read_raw` was successful, so the 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.45.1.288.g0e0cd299f1-goog From nobody Fri Dec 19 21:12:40 2025 Received: from mail-lf1-f74.google.com (mail-lf1-f74.google.com [209.85.167.74]) (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 4F08F17084E for ; Tue, 28 May 2024 14:58:21 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716908303; cv=none; b=fVNglqBhf1ZJ6q8XuYNrGK9Q9YfAqDgQJ6Mom3SVzK96ZIPiOIFWJzG+qCJy6e/WI+q38pu1yPLfTMQ8QNZh/YsYH8BiuAlfEV2ptkKcD5EehDmVQ68cx+fugJrRAXdtq+nquwLK5WdPEAU47tAQ3ZGmaZKQWFAEOzc5ejSxXGA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716908303; c=relaxed/simple; bh=o0vfP46JuhVT9I8s8c1aGsT1nEiHVNuFmZxbFB7IUxY=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=aRmAooLJuYPA2kxZireV5OoK2PVx38g3IsMdfK8PPNHmAcGAdWOXWkMxIZx4eBy3RXqbnRun1z3wXozsbE9WnPHhadet5KReSr32kp9/v3p8pyuFpR/nbBJgUlsq+5nu55YN2mHTMgFQ3hxUHyMEpV70FrpbY3+iiteo1mEeth4= 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=Ea0IfQej; arc=none smtp.client-ip=209.85.167.74 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="Ea0IfQej" Received: by mail-lf1-f74.google.com with SMTP id 2adb3069b0e04-52707aca5caso429185e87.1 for ; Tue, 28 May 2024 07:58:21 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1716908299; x=1717513099; 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=TDs1IJHnbNwo/zETkdmKSImuTQj5Z+oesXCPuXUO86Y=; b=Ea0IfQejoKzuWZmF2hpVVurSvkmJrBYExpVpSWyOK2n1nIFRSJybv9KLBhDXNIKV/F zCEdYC0D8441Lmo2KdSdi3nmvYRrBSQw2jYq3mXFph13JgPLySkjxKYeT4r72emQVuui 8c7KepdI3ngUXJbvTmoWeSEksLrfUJwhbXJYv9Hv9eOagKrKtf+qemyPt2fE0gZE6Nht tm5ZaUsCPX3l1QD+9d1X/gTO0Mkx85fqiuP7GSk6KAqYQCWTOB46dRWuFLcQtx5x/HSF i2Ed2hMe1vY6nJbF0OdehUTsN/BmRLKBfot/zFFWX2I5S0+2bdgCwEo21FvUNKMaZg0E TKrg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1716908299; x=1717513099; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=TDs1IJHnbNwo/zETkdmKSImuTQj5Z+oesXCPuXUO86Y=; b=UIrZFP0JF6P5g2citevN2y5M2ALpwFlm1KadUFZDowMtZ75Jo05USZQSmQBoXIOsuc KJRaMleilm78HW7dEpx1IQnABrWmTc0/AJue1XkombL3qsdW2INHrIDvNbHIOJHcElA9 xLIqq5NelB4xuy1MjILAEpWRZPNUXqFo6K5CxeosVJ93CvdvGyNN/ImAyR1sY3vmHAnk 9Ui0hAsZp1hR/XWOWMh9/F/L79SdqHeqQcQFi6ajkyibT9IAU73D7vga+fPh7nSkG0co RoyeN051bSwrMutLkdConurf7tprjv0B8wmdnwymDJMkmljryuDw47wkUha/a19c3RWW ceyQ== X-Forwarded-Encrypted: i=1; AJvYcCV/KrBLBHM3HZU32p2kyJmrFbU27k1lbzqlWp3h2hAD3rQKp/AHXs1ATmDCxfcZcKG1gCB4cqqTpmsFNpI7aDgE+BOBUKPIkfkUfNkO X-Gm-Message-State: AOJu0Yy1af630InGC4LdqNuQzeMAcHQS2RbEGtwti48g+V+BkRw0IBT2 jKfi+MH6NYnwmQFSMAGdIUgIkVyKzPRK/226HxJPnG1LIwNazWA4vF1x7hQkyMtv8e9e8Zo7k+U Ei+hCb1FsT3yxTw== X-Google-Smtp-Source: AGHT+IE0/smWA0nv7DnIzJunDnNDJqSN2EHjtIqsT2/sKJP0Nv5knZ9MVxp5tyeosgZSBFdOKEeD2mUHzkRd5q0= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:4508:b0:527:4ba:5c90 with SMTP id 2adb3069b0e04-527f16c29eemr16354e87.4.1716908299488; Tue, 28 May 2024 07:58:19 -0700 (PDT) Date: Tue, 28 May 2024 14:58:03 +0000 In-Reply-To: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5419; i=aliceryhl@google.com; h=from:subject:message-id; bh=yETbsBE1UqQkTUzr6kFMmtAy1ZCV9RovzSXiqjWQMC0=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmVfEBZqo9IvVPwPO5CrRJ9S+efkmY181jkflVc +WDKDaJ64KJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZlXxAQAKCRAEWL7uWMY5 RueSD/4wGfhLRtZZBSvagz2Tr+7o+akzMLKWhMQWrJ8eKjNds02I9WbzFLZQUGXQ+4RqiLvddU4 n8fLx3irk1ez8T2CEBs2O9zrruwTzwEi76SM9MbP9366gM1BH3RZV/48csVSYgCW6qUBSdVqE3r S4Yk9ttNOYeJxILvebO8goJJgqQIcmyI7J8JG7HlmLdq33wrdNfNwCvH1bkxj27/BzRUqOAnRdG 4emSEQudPjgRcQAUqYek+ZPl1t70K18AjpySXsRtbvdPk84CpoCMCUBmx0q9XIbEs96+qBvCjmU saj6XzYGCChZpUMn4ERwoPTvmnIrKCcc4PDYxImnLEi7TsXDbrEMBpP3bRIVjupFwEpskKqI6Oe 7fZ1KycxvBFAq+/Cp/wiYClD0TxxK41XS9oK/qRukR9BlMHf0zadfQlwnx4dbMLyxGk7Fl2hlwH G0Sc3XFE0Mkud0WOFEKQ+0l85lZq/vTdHxYqzjUCmhlg8nkMrF4IfRAdk9R7EZvdWy1ioq7PUMD xEsXLgsyhIdd3nDBtRIFjIXNkeXeMrgy/tnBwk/hCIIM+bFJcx3e/6JvMdWJVhIBI1SEYxLjzyB zxqRBpw1O+VulD9zCEJFIthq2o0jSikBBtciQBV+VZFr/debLYs26gcJTVHfDPh/jOhqRPdf/sO swwxMcc0sTnOzbg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240528-alice-mm-v7-2-78222c31b8f4@google.com> Subject: [PATCH v7 2/4] uaccess: always export _copy_[from|to]_user with CONFIG_RUST From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=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 Acked-by: Andrew Morton --- include/linux/uaccess.h | 46 ++++++++++++++++++++++++++++++++-------------- lib/usercopy.c | 30 ++++-------------------------- 2 files changed, 36 insertions(+), 40 deletions(-) diff --git a/include/linux/uaccess.h b/include/linux/uaccess.h index 3064314f4832..d8e4105a2f21 100644 --- a/include/linux/uaccess.h +++ b/include/linux/uaccess.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #include =20 @@ -138,13 +139,26 @@ __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 +/* + * Architectures that #define INLINE_COPY_TO_USER use this function + * directly in the normal copy_to/from_user(), the other ones go + * through an extern _copy_to/from_user(), which expands the same code + * here. + * + * Rust code always uses the extern definition. + */ static inline __must_check unsigned long -_copy_from_user(void *to, const void __user *from, unsigned long n) +_inline_copy_from_user(void *to, const void __user *from, unsigned long n) { unsigned long res =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 +167,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 +182,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 499a7a7d54db..7b17b83c8042 100644 --- a/lib/usercopy.c +++ b/lib/usercopy.c @@ -12,40 +12,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.45.1.288.g0e0cd299f1-goog From nobody Fri Dec 19 21:12:40 2025 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.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 2E52217108A for ; Tue, 28 May 2024 14:58:24 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.208.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716908307; cv=none; b=ZPMpAwlYWRm1knq+o4eLm6RMSaeh+f9lcbf6CVUgRmkkxyTqjvKuEED/9x1nvow/V87CapcQ4xTQbUju5oJ1Wy9zjgi+vIdvV91vgRe9nCMoDrhAHwJWw5G4rk+dnZDf1BkPvVuPLWlyyuVzEvQnu9diPCGWk9JUScq2Gmp253M= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716908307; c=relaxed/simple; bh=yYu+EAbmrLlEDaJXxUlWd5cGuX40snAODQjVSX7+z6k=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=pnanSwZK9isp+mjfDFbDk/JF7bmb41l1/HPso6h1SjSHml87I0R6jo3EoamEnQ1TQRi2XKn22F5hSSQnzqbiSlPTAi9Fv9uGU9siPJrDtMO1efpGciHeNyVX5aRS6kSiJUMogHF2988t2eFi6gr7u+FaLaPHf07eZ2h9OTCUo3I= 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=ZZyN2iFJ; arc=none smtp.client-ip=209.85.208.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="ZZyN2iFJ" Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2e95877b88fso7468421fa.2 for ; Tue, 28 May 2024 07:58:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1716908302; x=1717513102; darn=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=b9/4bIUoqG75SiXX4ggGIII0PXg7f1u44UaqTYS94zc=; b=ZZyN2iFJmXdUAUyRYkPfvGWewQPCfO/ZtSTs8gT5NkP3S4rLcPcFb9yYdnJFemG6jb fNxRpXPg0vMPA0k7dYmE8DXWzN73xu/ZN/1zbojL54cVs/u53RlKrp3yczClBH/wB1ic Vg71TrW4Jv4+qAvAo+I+0s5tsQPkDQE7YS8LnhzAoxkcqX25bvErBjeTHOm6/C7pSIR5 li4g2PqVWkAyPGjGEUv5mih6N5Y4erboQgckIgQyJwYhKPKbRRqJcDN/M3sx4X9bZkt9 WGJztpEjtHXwCEn/QH4pkELvZEKm5VSCRWI7VOIFV7KZxKRZy53K3+01DJh+UYkLwnQT bAZA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1716908302; x=1717513102; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=b9/4bIUoqG75SiXX4ggGIII0PXg7f1u44UaqTYS94zc=; b=DPii6r9pbE/VIedvlTvSDs0EfqrE0zarBv/wN/GhMdokV3CjM1apa9RPG++AS+SSmT M2eROOdu6jb+06Yc4apot/0ix5Dde5VtPM7CqIjt7qOq5QwG0L744Ej6EfuPWgKjI4WY xNpxot4NiCbGJ/dUyjncwLPhJZWBoiRdBJnUjBN9BQMP1SUvojpQnoMLGv17txzT5nY0 +Ef4rXi3Gx7rD4XFRLlVLLCuEQcnwRUsIi68muSuuCT5NiDh2qTl8IO0rsm4HhDaCSgu j4YIGOaaVvAsuDXUDTQq5O8Pe6vgRNVOrs4zHnGAi4IL5MqUtm7J8b+z1Ji57lRwCqIS 6ljQ== X-Forwarded-Encrypted: i=1; AJvYcCXJHYC60zuvo767VF8HvOphac9mKnEHJeUR5c0pMp5nlwEnG0KJry5/ES8I4dOY4cswK3KUeTHTq6lWyBgp9bWMOlktmwJUKVpdTEHk X-Gm-Message-State: AOJu0YwI5U6Yd80CRAUI6D73LTdoVHvAoVBvdV/scWP/bcoGvNHLiVyb Bi7AEezW0UirtFYONXJqVOntZ99+gHVTPrxGPGEf7SQqVuCCpQwjidNaKPP131+tjgunEs+UuoP iYq1wj1duPCcggA== X-Google-Smtp-Source: AGHT+IGI0oSXsScGynqqZZ2qwR5qKbUrUE71Co+pWa+5ECFU6Ac40a2IMZtYKbVJYyka3eZNWCz/z+D1TV0BmGo= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a2e:360a:0:b0:2e0:d8c9:990b with SMTP id 38308e7fff4ca-2e95b27444fmr106591fa.6.1716908302093; Tue, 28 May 2024 07:58:22 -0700 (PDT) Date: Tue, 28 May 2024 14:58:04 +0000 In-Reply-To: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=9020; i=aliceryhl@google.com; h=from:subject:message-id; bh=yYu+EAbmrLlEDaJXxUlWd5cGuX40snAODQjVSX7+z6k=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmVfEB6oia3O2ePKqSvHFP2bMtfCznNnjJ6XHWK p+dntQJgACJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZlXxAQAKCRAEWL7uWMY5 RuYID/0Zn/Ekx3yhhKl8ze+ZbQzTKxxhXSitWFq4evNnN7TxwgP5on/9bu3I4gtYDFe787qYSj9 BOCif2gFbd/W7XnW2o0c4X44ErtiRtxHIxRN9v+BKfZCw5QQARt8Ajgsui4ZfRYwEWk44TPZI1Y ZQTmnG9HQ1sfgWJZDxSWzWPnFQ/y3r7fHtuFkKQ0eT5vm738ccBDWCX4XX19tH9Mr7CgaOoMQnu OquFHYfIDW84czELfZA/wxol/7ce8K8ryQibE6naSMDfDSInpHzGfx8/ip8PtM9Mi/jDby2llEO nT0Zl8jquE9Pe7raOb3reL8EWbRnIQpOF4/IIYqakQtDvI5fM4Z+TgS2S6kD1o83Hpg3ku22YvS syoIxmuGiZ8E4R1mMfy9mU/qoQGf6OTWSfNu+EycjF7B2+bWIRSXAiu8zEyfuXbJktrruMZFHWV fsvstUp7l71TeB77N1rF2vyk7xgkxGRylsQPfG/ED3UuJEO8Xx7FdHMuAtBIzqJX64qyC/lh+Mq 1W7nAeH1p02ib0EQGuTuP20f5kPoK8dQqaILUGYUKSoVf8OJlZIcoZobaU+TMGjtE9ZFjaTEZHZ Kmcyjbt85Yq0OSAPNijN/SRH7zbXdnauNWXi3h+wi7DmKTGme5m2Rc26ifu9o9W9e8qOef1bzSQ q8YkdHOAa9SgfJA== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240528-alice-mm-v7-3-78222c31b8f4@google.com> Subject: [PATCH v7 3/4] rust: uaccess: add typed accessors for userspace pointers From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=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 Reviewed-by: Gary Guo Signed-off-by: Alice Ryhl --- rust/kernel/types.rs | 64 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/uaccess.rs | 79 ++++++++++++++++++++++++++++++++++++++++++++++= ++-- 2 files changed, 141 insertions(+), 2 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 2e7c9008621f..bd189d646adb 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -409,3 +409,67 @@ pub enum Either { /// Constructs an instance of [`Either`] containing a value of type `R= `. Right(R), } + +/// Types for which any bit pattern is valid. +/// +/// Not all types are valid for all values. For example, a `bool` must be = either zero or one, so +/// reading arbitrary bytes into something that contains a `bool` is not 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 77957d7ec011..80f7e7ca2f5e 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -4,10 +4,16 @@ //! //! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) =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.45.1.288.g0e0cd299f1-goog From nobody Fri Dec 19 21:12:40 2025 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.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 25C30171662 for ; Tue, 28 May 2024 14:58:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.208.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716908309; cv=none; b=CL1LHQIW3olEtIVwfILTUBrldGNGyyKckSQcc2I50v9eFR8dkc+DERG1PXKAk4JUoNiMJqcIa39J5Mb1JACZmDKXjc8pYZ0jrwMOKEn3Fq/Oz8hshZzBL3bzjR2Y4+A/T1bYgoXOp/3K6QzvxDQQEqoT8/VYoi6WlL92jA/bXr8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1716908309; c=relaxed/simple; bh=/HE8lkngIqgSFXOtkqfoTmQKkoPIxutv/DByz3hii1k=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=c1pgyUFxBDop2RzhV13hiOwHKMtYmJN2FQtg7CRSDhgPCzGlu9y4f6ENyO/Q4pGjA0Pii/v9fmMPLJ4JabDLKlEJAqe7ga0sb6kIpXM46olL+SLV0UY5stwdZTv/ATI6Q9Rm/GECb/j0M67dAZFp2wlE/fE1TsGuA0gvqw1UPNE= 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=Qgc3zJ3G; arc=none smtp.client-ip=209.85.208.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="Qgc3zJ3G" Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2e95ad43e9fso6392861fa.2 for ; Tue, 28 May 2024 07:58:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1716908305; x=1717513105; darn=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=eO05l42JzpfeTNPK2MRvp86M9FhFhNRtSy4S1tjVhus=; b=Qgc3zJ3GYsnur+WEgkbHZGn8z61m9aXvhvxXSRQKEtKmbf1eod9PQpwYSX7CcMuXzK Vik7nn7qNvJ7REJbs4vb/iAW/fQFRkZWccyLfdVd4cywGZgXD27ZEVEZDCyCJPvbWGRj H6VRYmJpYgfO3go/xsAufLiWyGyLKkZ+wzf6/uKsbL9azbbLwED74spI3aXqb7SL5pa2 fO0kPB4PojyJ6dS4/VYQaryCfB6bjrpWTAbSULkDCAnDJhM2aPp7IELfYCT1djtRjX1Q WG/qcCW6/kXRFGrqCmrVGdEZqedjvTtS2jLUhB8V+B+7+NP1PaMe/4TbhXNI31l3xN6t H7Ew== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1716908305; x=1717513105; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=eO05l42JzpfeTNPK2MRvp86M9FhFhNRtSy4S1tjVhus=; b=X5cb5k2J2lGVufqFwlbTJcQj7nLzP0dvO7M8pc+0eWKZFZiEl4c0+sQ064lUHlKMaK JY6+8v58QjkRIAnYY1s+gQsf02fwKf5zmR9CHNpQSwLB59AYcnOF5REGhF61GkdAgD9R 0Tc8ngONsziBMKSLrNEbkM8bK2Oi0waSVX+IydujZ0+JU+4+nrVjT7o6dr7VVwT5o2Pb NpHP5skTLNNPHpbpswh0qIQ98hv5x3JCaWDSxKwWGs/9SkPbdG3FUN8BYjLYRZ/LVmvi 7RynBHiShZKTmgg1r5Kirgxg8XxUoxGO513XsgT4dpL1a6R4sefTnB37tXhScL8z5t1J xMoQ== X-Forwarded-Encrypted: i=1; AJvYcCU+nqu3w5npKN9ZbeiS8UGc6EkKRuY9TpfZ46zlyzHyRx8YEynFA2nRAE3egGLmXztr2rGqBazWf/Fw74qisT9q0vyiaPZAK1/zUjwC X-Gm-Message-State: AOJu0YxITF8uKiAOWLygRtExl+bs8bbyhDeQebgDsU2sXAQ407N3hItB TKqg2HVVcm04bn6+szQGJW3Z207zNyxMQd7sfTGBBHDFe1CG5vvWB6d03v40O1qgigEZreptoTn YAl7fGwRH0cBepg== X-Google-Smtp-Source: AGHT+IEOF4n7i+XUKYEBH94ipp8W/G8bUc6RNmidal0r91mtpuFIe9xOXChYEoPu4AGoMAK43jNu8IHHgNDq/Yo= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:32d3:b0:51d:5f9c:50ad with SMTP id 2adb3069b0e04-529666c4680mr10952e87.12.1716908305169; Tue, 28 May 2024 07:58:25 -0700 (PDT) Date: Tue, 28 May 2024 14:58:05 +0000 In-Reply-To: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=16077; i=aliceryhl@google.com; h=from:subject:message-id; bh=/HE8lkngIqgSFXOtkqfoTmQKkoPIxutv/DByz3hii1k=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmVfECAVuTTj15038Ew2DTzS3KESwLDvumYApMa eZb1p+NiP+JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZlXxAgAKCRAEWL7uWMY5 Rs9lD/wLFlIa+NMQSL+XMbCYpTDJQVbp+7DZpIvygiwW1JH34lbNywTpBNp3IjSEx7IgKIZUwoF kMBSbh+5TLnO+MIt7RBsY7Yn6V3Lvkhchd8wVGOtzIvmj1kpcvvqVCqvttpFMSR1QAeDnLfZjX/ uo07YYKK7D+J6grc/ZIv12/HP4CtFBTE0dPyW2h0FgbrVItek7+rZ8f7bB8HpKaF6+NEM+QP9JM qZjIl6j0deYWCQWDWo/wFsab9voyLxhzZ/E9YdE1tKjzw0/GSoaU/PmJ5a/eI8I1eCMmUMMCPFO CBTheF4vo8iwkb5e1YeCot0wTD+nGkmNaGx69RensXoGwEjKsfHa1lt3717UMZ44CWyeAWO5y52 8BWzcbqDjf93IDGHHUUVYNVzge4NJ1X2nPjtNwNniUow8yX6DmL3ZS9m46Pv+GWM9gzbZySJ82n umQAWuDZnhs0gmNxNfjb3v5Hu7KdbtbhBfBMFmMPtFnfhMLCcDptTiwbOLCWQ4E4km7PfVvvcB9 VDq5ao+YdwiAcPS0LZe7Pw56pHdFynJWMwXQ4/6xfy2JwbbKY38O21FOAQh52cVxRfgRd1woFBT pYGjdKWyrYxNnCZe1Gec4b2THgA6zK3Qd7kfvLGNaxMQxusI2VYvkn9dSmKF1Oa+fw+FAZ7mzJ0 Wqjz3DW/CXKlOJw== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240528-alice-mm-v7-4-78222c31b8f4@google.com> Subject: [PATCH v7 4/4] rust: add abstraction for `struct page` From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=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 Reviewed-by: Boqun Feng Signed-off-by: Alice Ryhl --- rust/bindings/bindings_helper.h | 1 + rust/helpers.c | 20 ++++ rust/kernel/alloc.rs | 7 ++ rust/kernel/lib.rs | 1 + rust/kernel/page.rs | 250 ++++++++++++++++++++++++++++++++++++= ++++ 5 files changed, 279 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_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 d6abe4bd45d9..305f0577fae9 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include #include @@ -94,6 +96,24 @@ int rust_helper_signal_pending(struct task_struct *t) } EXPORT_SYMBOL_GPL(rust_helper_signal_pending); =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 531b5e471cb1..72f475e44144 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 767026db068e..5d310e79485f 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -35,6 +35,7 @@ pub mod kunit; #[cfg(CONFIG_NET)] pub mod net; +pub mod page; pub mod prelude; pub mod print; mod static_assert; diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs new file mode 100644 index 000000000000..121d20066645 --- /dev/null +++ b/rust/kernel/page.rs @@ -0,0 +1,250 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Kernel page allocation and management. + +use crate::{ + alloc::{AllocError, Flags}, + bindings, + error::code::*, + error::Result, + uaccess::UserSliceReader, +}; +use core::ptr::{self, NonNull}; + +/// A bitwise shift for the page size. +pub const PAGE_SHIFT: usize =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.45.1.288.g0e0cd299f1-goog