From nobody Tue Oct 7 22:51:46 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.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 74A1C2D3EE3 for ; Fri, 4 Jul 2025 09:26:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751621184; cv=none; b=S0aYGa2FlAGlEkNzG0zmuC+O4Tipn+j2qUBn9T42ISF4jt+Q+EIZuvnGzqDwt4BIBDyqbIhIy1Hf0aI+E0I/1vI8GSE+knjUHCfa91sLQ3cjgrJaPlOkvQ7bkK5ME54GouPXgl0dmKRzeunQM19wrgFa0j9Vx0upODgX6gb+ytE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751621184; c=relaxed/simple; bh=GUVBYe3ElqgZ8myVjRq1MC1lE7GgjoXJmCVS8swISF0=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=sI0EuTyLPRsKRbQZWX9/LA8gQDaFXYzDtXcpd+f1JK9wrkzzCZ2rTOHli0gckSKH8mLnW2VvCsWuYBmRf5KfYE2Zq8+IJARYnPD6vGWnObghnuOHT1HxadfawKks9X83qATDJAbZkQR+y2RZln33mFbfH25GWy3dLSEM7LmGWQs= 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=F46mgFf0; arc=none smtp.client-ip=209.85.128.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="F46mgFf0" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-4535ee06160so6045165e9.3 for ; Fri, 04 Jul 2025 02:26:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1751621181; x=1752225981; 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=c32w900jPJ+cRo3HavDez6oS0pxYHFGoO7PGXsKOmnE=; b=F46mgFf0HjHT0hQtIUvoHBKd4Y3//9j+RGEyfx1Y6uc+aE0u/MHNR2k+xG/L5ynR4k E384q+WK4iUH4YmGayOO+c7Z8r0HSJuF8EWDs3bjgnkHtJGZ1IzJT2COjxXIkFn03hgR lNW2x95CBrce45/qAPE2KZoS+WXFuNCY6+/I2ykij6Gei5s+5gbbJLADPq89rcENPSlm w0iePzm3DTatcoG8AK1Naao/HI7ACcN+o1MeiV6ZMSrymSsCAk+rn/EoKcL4sQLRy96A 9104nhy0/2JIGYUPxn+tnb7OO+Z2mbMxbtmJ8KpIyYWF2vONw7FQTxVWYuhiRCY52J/u tkMQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1751621181; x=1752225981; 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=c32w900jPJ+cRo3HavDez6oS0pxYHFGoO7PGXsKOmnE=; b=poHQxcK19sXw9VwyITpvsWWd9UYjigeJuaxrV7roAuH2MeSdYmdRRqMxfoHR7UkapK ztd8txJuahpf+o6FYtZ/clIQc6u3F0i45gW4cunXb/Kr7c6RkQR4WZQj79gMNz5fh4bn NoL0HTAn8LhEWkjUzAkwTm6T3FJs8wP75iSnBbKsaygHMdf58ZPMIuYz10VzJIxRI0R0 TgvuCFlaUpEMfT7kQoOpfna/p0767z4miws8T4Qk4TuQUigJz7UePSlgRqgnhgONKxtO eTbMfxjp0AW445m0INIlzYvO2Jsij4t2GBQTEHAQl2xCnrbQoG3iWcHVNUwJTlWi/6QC R8Mg== X-Forwarded-Encrypted: i=1; AJvYcCVcvl3ez1l09gJWUdxh/O6x39QuKxenK/NIw/qttebgkxx8e0xtFZtZtGyfmR4v5kIuUtFpPze1vGyMAuU=@vger.kernel.org X-Gm-Message-State: AOJu0Yx2VFWNsgte0Jm0c0ZfNT7YrW5I1+rjUQGQqKhDQPQRJjnqLMve Qswolsyf47QV8di2RErcihvqPwu6IdVvn3QdXgsM0r1rmf5Y/Xr0vwqxnmBelHPDLSDpGJqTv1j 7PhX/qmJ2O4MOX7+9ww== X-Google-Smtp-Source: AGHT+IFJVeeE9iVd5s1Jk2vz/11bsqhZ1mGVQj4/jhzG4VqZ7medZF9PnozW8BWzsiISkuPr2gX4qlzv0WXMqW4= X-Received: from wmgg12.prod.google.com ([2002:a05:600d:c:b0:442:f45c:c10c]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3493:b0:442:cd03:3e2 with SMTP id 5b1f17b1804b1-454b306a122mr18684725e9.2.1751621180890; Fri, 04 Jul 2025 02:26:20 -0700 (PDT) Date: Fri, 04 Jul 2025 09:26:00 +0000 In-Reply-To: <20250704-iov-iter-v2-0-e69aa7c1f40e@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250704-iov-iter-v2-0-e69aa7c1f40e@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=7303; i=aliceryhl@google.com; h=from:subject:message-id; bh=GUVBYe3ElqgZ8myVjRq1MC1lE7GgjoXJmCVS8swISF0=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoZ545EoGErSoI63LAE38PekMbVIHg7PDc6pC4O qNnHAM+I9eJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaGeeOQAKCRAEWL7uWMY5 Rq7BD/47wCOhT3Qlevvp2V5GBBvM9BPm0DyYGM9/9tOunllOMEguVAeIzwraOKVBw0r5BvAPheB 7P1po0DKh+Ytjm/mcBphq+mL8HNOD0DylXGteBcB2ZnyDlGq2sxvLBXMuPVKgG11qJ+EZQkXMO+ t7cCkoM8VB2Y94rWRruwNfJoPuu/enaP6D5z77hllA5Lye187dVQPeqGTYS4Xh8p5RFRJqnn8XM lww83xRAcpYqPTIV7pzFKUwOJFG/319QJ/e9nuQspd2je2YavFVav9T/0F0PXI8F4rXb1hKtay1 xDF7+xmLkDhcMIb92sjCnCRNskv649o/rzM6X+bLGLQ4+kLvRJJS4ZJumj3mgS6QUil/rGmsPhT oPGMwYUdi3yC+32QQwH8eYXMY2LrP/E0oi/AZCUZwEwvuNlxtMUVl9rFscdEjo4WUeTS/lr7JKx hckinfj+e+oObnmfKEIni9PCKmc8/KitDW8vpRn+vcd8YjGzviIKLK9DTucsIAClM+5eEan8mqp i8yLEzaMgmm/Yng2PYYcOJcEyZvn3fNmVS2SjlVyAyHUrTRbtJUwf1OzGBzFZ+pFLJ7o0PgNZKv LxOm9bmovy2CATWI+IRjSGXWa+jrdx3KWo7XJRyWftXxmPS0tIG7UdWo7XgnvVUpdGGbE5wHDdB WEd65Yxbt50xB0g== X-Mailer: b4 0.14.2 Message-ID: <20250704-iov-iter-v2-1-e69aa7c1f40e@google.com> Subject: [PATCH v2 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE From: Alice Ryhl To: Greg Kroah-Hartman , Alexander Viro , Arnd Bergmann , Miguel Ojeda Cc: Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Andreas Hindborg , Trevor Gross , Danilo Krummrich , Matthew Maurer , Lee Jones , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Benno Lossin Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This adds abstractions for the iov_iter type in the case where data_source is ITER_SOURCE. This will make Rust implementations of fops->write_iter possible. This series only has support for using existing IO vectors created by C code. Additional abstractions will be needed to support the creation of IO vectors in Rust code. These abstractions make the assumption that `struct iov_iter` does not have internal self-references, which implies that it is valid to move it between different local variables. Signed-off-by: Alice Ryhl --- rust/kernel/iov.rs | 152 +++++++++++++++++++++++++++++++++++++++++++++++++= ++++ rust/kernel/lib.rs | 1 + 2 files changed, 153 insertions(+) diff --git a/rust/kernel/iov.rs b/rust/kernel/iov.rs new file mode 100644 index 0000000000000000000000000000000000000000..b4d7ec14c57a561a01cd65b6bdf= 0f94b1b373b84 --- /dev/null +++ b/rust/kernel/iov.rs @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2025 Google LLC. + +//! IO vectors. +//! +//! C headers: [`include/linux/iov_iter.h`](srctree/include/linux/iov_iter= .h), +//! [`include/linux/uio.h`](srctree/include/linux/uio.h) + +use crate::{ + alloc::{Allocator, Flags}, + bindings, + prelude::*, + types::Opaque, +}; +use core::{marker::PhantomData, mem::MaybeUninit, slice}; + +const ITER_SOURCE: bool =3D bindings::ITER_SOURCE !=3D 0; + +/// An IO vector that acts as a source of data. +/// +/// The data may come from many different sources. This includes both thin= gs in kernel-space and +/// reading from userspace. It's not necessarily the case that the data so= urce is immutable, so +/// rewinding the IO vector to read the same data twice is not guaranteed = to result in the same +/// bytes. It's also possible that the data source is mapped in a thread-l= ocal manner using e.g. +/// `kmap_local_page()`, so this type is not `Send` to ensure that the map= ping is read from the +/// right context in that scenario. +/// +/// # Invariants +/// +/// Must hold a valid `struct iov_iter` with `data_source` set to `ITER_SO= URCE`. For the duration +/// of `'data`, it must be safe to read the data in this IO vector. +#[repr(transparent)] +pub struct IovIterSource<'data> { + iov: Opaque, + /// Represent to the type system that this value contains a pointer to= readable data it does + /// not own. + _source: PhantomData<&'data [u8]>, +} + +impl<'data> IovIterSource<'data> { + /// Obtain an `IovIterSource` from a raw pointer. + /// + /// # Safety + /// + /// * For the duration of `'iov`, the `struct iov_iter` must remain va= lid and must not be + /// accessed except through the returned reference. + /// * For the duration of `'data`, the buffers backing this IO vector = must be valid for + /// reading. + #[track_caller] + #[inline] + pub unsafe fn from_raw<'iov>(ptr: *mut bindings::iov_iter) -> &'iov mu= t IovIterSource<'data> { + // SAFETY: The caller ensures that `ptr` is valid. + let data_source =3D unsafe { (*ptr).data_source }; + assert_eq!(data_source, ITER_SOURCE); + + // SAFETY: The caller ensures the struct invariants for the right = durations. + unsafe { &mut *ptr.cast::>() } + } + + /// Access this as a raw `struct iov_iter`. + #[inline] + pub fn as_raw(&mut self) -> *mut bindings::iov_iter { + self.iov.get() + } + + /// Returns the number of bytes available in this IO vector. + /// + /// Note that this may overestimate the number of bytes. For example, = reading from userspace + /// memory could fail with `EFAULT`, which will be treated as the end = of the IO vector. + #[inline] + pub fn len(&self) -> usize { + // SAFETY: It is safe to access the `count` field. + unsafe { + (*self.iov.get()) + .__bindgen_anon_1 + .__bindgen_anon_1 + .as_ref() + .count + } + } + + /// Returns whether there are any bytes left in this IO vector. + /// + /// This may return `true` even if there are no more bytes available. = For example, reading from + /// userspace memory could fail with `EFAULT`, which will be treated a= s the end of the IO vector. + #[inline] + pub fn is_empty(&self) -> bool { + self.len() =3D=3D 0 + } + + /// Advance this IO vector by `bytes` bytes. + /// + /// If `bytes` is larger than the size of this IO vector, it is advanc= ed to the end. + #[inline] + pub fn advance(&mut self, bytes: usize) { + // SAFETY: `self.iov` is a valid IO vector. + unsafe { bindings::iov_iter_advance(self.as_raw(), bytes) }; + } + + /// Advance this IO vector backwards by `bytes` bytes. + /// + /// # Safety + /// + /// The IO vector must not be reverted to before its beginning. + #[inline] + pub unsafe fn revert(&mut self, bytes: usize) { + // SAFETY: `self.iov` is a valid IO vector, and `bytes` is in boun= ds. + unsafe { bindings::iov_iter_revert(self.as_raw(), bytes) }; + } + + /// Read data from this IO vector. + /// + /// Returns the number of bytes that have been copied. + #[inline] + pub fn copy_from_iter(&mut self, out: &mut [u8]) -> usize { + // SAFETY: We will not write uninitialized bytes to `out`. + let out =3D unsafe { &mut *(out as *mut [u8] as *mut [MaybeUninit<= u8>]) }; + + self.copy_from_iter_raw(out).len() + } + + /// Read data from this IO vector and append it to a vector. + /// + /// Returns the number of bytes that have been copied. + #[inline] + pub fn copy_from_iter_vec( + &mut self, + out: &mut Vec, + flags: Flags, + ) -> Result { + out.reserve(self.len(), flags)?; + let len =3D self.copy_from_iter_raw(out.spare_capacity_mut()).len(= ); + // SAFETY: The next `len` bytes of the vector have been initialize= d. + unsafe { out.inc_len(len) }; + Ok(len) + } + + /// Read data from this IO vector into potentially uninitialized memor= y. + /// + /// Returns the sub-slice of the output that has been initialized. If = the returned slice is + /// shorter than the input buffer, then the entire IO vector has been = read. + #[inline] + pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit]) -> &= mut [u8] { + // SAFETY: `out` is valid for `out.len()` bytes. + let len =3D + unsafe { bindings::_copy_from_iter(out.as_mut_ptr().cast(), ou= t.len(), self.as_raw()) }; + + // SAFETY: We just initialized the first `len` bytes of `out`. + unsafe { slice::from_raw_parts_mut(out.as_mut_ptr().cast(), len) } + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 6b4774b2b1c37f4da1866e993be6230bc6715841..278b6fdee62156f4ed997c13fa1= 0bd2fb0fa3ad6 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -81,6 +81,7 @@ pub mod init; pub mod io; pub mod ioctl; +pub mod iov; pub mod jump_label; #[cfg(CONFIG_KUNIT)] pub mod kunit; --=20 2.50.0.727.gbf7dc18ff4-goog From nobody Tue Oct 7 22:51:46 2025 Received: from mail-wr1-f73.google.com (mail-wr1-f73.google.com [209.85.221.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 7A1BD289370 for ; Fri, 4 Jul 2025 09:26:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751621185; cv=none; b=NQNkqKKIXcK1BzcPe023dXWjmqaJS1mpUybnALHLZrmD3dBGLWf3DecASx8uFGaADDvntCnyBmLW9eIRoCvsYzkglCs8RYMkQMEx874ccE+CVY0wW8ja0tmr504cQQ6qMkHSKcTTiXJJy9AxRuXPBSgJrWdZ8sNWby/HgPJXZDo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751621185; c=relaxed/simple; bh=JZB7zO6gqQwgdwPk0qXB8K1QI4fPJKH7jlUq1EQPJjU=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=nZc6IUmF2ru+Bu7bf2LydpR1OyS7JYvhhkI6wfhRemaz5lG7h57SuSuU2e99tnkOkBA/8LE9LsRWga6KBScxMIDQA1WBKSZSmRndxycHzh5iRaBxZ9Cu/Srl8DtU97Gl82Gelht5yzYH48gyoHXq/BBP4O7YL3Y3/Y5ZshCxkOM= 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=ZO+SP0Dq; arc=none smtp.client-ip=209.85.221.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="ZO+SP0Dq" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-3a4eeed54c2so414094f8f.3 for ; Fri, 04 Jul 2025 02:26:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1751621182; x=1752225982; 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=+EGNm95/fFlMRBClRB3thVQC3r+aHPvX8cMZ8s8+maE=; b=ZO+SP0Dq+GoNYrEeZyGR2weFj8Owc7ZFcjDdqYPoeqYTXcPYloyrLsNtGVTTy752u7 sgWUpRRK4EiDeMWGAjJqaAag1yGRduLehE6OvPEp3K6gzjXZD3t8H9WF1/Z4Fo2fgeTf lsy9mjBGOz5t9HQrs3V6eY0g4gnCtY4JuX6IQ5KKvwJAiFSjaGSAy1L5FDdtPrlWA9Be IcDn5t5wrRQbVFyeksgCLPEYmjjPPynqp3XLBf0ZJRHQqSNT+16dUdrLgaYtglqRtXA+ 0+vwaC5KxWaV4IZLZMxNPagzZUmxuaHu23RvyyNJhGmS7VdMifrFFNYjCAQDVcQ5uW7i rOqg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1751621182; x=1752225982; 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=+EGNm95/fFlMRBClRB3thVQC3r+aHPvX8cMZ8s8+maE=; b=xI06qxPH08Bqn4y0ZrrEdIn/oyuoZFInrHYoR5Cb+cblldrH+XhF046/Dx/xFeF97M OFsy5DUkkpjpSDpjEa65QqmeFNApOyK/eDHAZHwVgsVjrIDDo/68tScNMZ5wvslVZngC oy7TgLrwK84ZqGNQ2AYN+RXtzrd9CqG/lqcUtBw3C2lwAW+Wtnia2MR6RQRm+TPpqAly AwZtlEZkFzGfSDph/QlkUxgIZOUx2qvjk2W1/AMsgO84VR5xCcyaiyge3+KvQkNMdf9i dKXm9Buju8BNt5QKYpt11AGSfKSw4O0fBvx3DFuQsdLCO0dWJbWT2hqD69UPntck37B/ lz0Q== X-Forwarded-Encrypted: i=1; AJvYcCXedSvS7PUAVKWoapdgrh4Mnc6l3DC2xutNf9VO3lrrfFJrOSPNX3gO8Ee+3ytlwo87MwVqVy7Rq6b/1vk=@vger.kernel.org X-Gm-Message-State: AOJu0YwTF5VomYp/1pV8+JOGeQejjOzgGsLj6DOYleBsJGpwhshVgeUR QMRe+B9BFCscQRvcoyXRoNIopqd9a3Cejv2P9lc6qhgruQhT9/MFarXo8XQKWdkBQW/YtV2WhFD OKDYNnuRUAM0+RGosmg== X-Google-Smtp-Source: AGHT+IHIM44HlZd8PDW2GOIjhtkmQHmHcNHFBYJ2nX7KOkSBkxrzLTkXgN3wEtT7InvpBRPg4JPHYIulJ8VfwjA= X-Received: from wrbce17.prod.google.com ([2002:a5d:5e11:0:b0:3a5:79a4:f479]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a5d:5f47:0:b0:3a4:fbaf:3f99 with SMTP id ffacd0b85a97d-3b4964f9d83mr1594055f8f.13.1751621181896; Fri, 04 Jul 2025 02:26:21 -0700 (PDT) Date: Fri, 04 Jul 2025 09:26:01 +0000 In-Reply-To: <20250704-iov-iter-v2-0-e69aa7c1f40e@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250704-iov-iter-v2-0-e69aa7c1f40e@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=6731; i=aliceryhl@google.com; h=from:subject:message-id; bh=JZB7zO6gqQwgdwPk0qXB8K1QI4fPJKH7jlUq1EQPJjU=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoZ545Eqk7L7oIUAZ0Q4uJFClYlg76z4GoKVod/ En/CeWvOqmJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaGeeOQAKCRAEWL7uWMY5 RqkLD/wO0YkFF4uRja0y8RMp77mYdzlpkRGJvZTpxtKBNxxhH4zCchA9MeC6EfThyI091bf6IY0 mSQFKPZ3RKhV75ZYmyqVEpiq5xlkZFhCQ5aco1wD5B6a5y1NNRbVAqINWQSJOe2ASspvHORyCvs zq98By88lFuhnGQEBw9rELy0UqQqmPSwZzwzvzLdf1Yyg5oG4n01ZZKJSDqXrplt5m4feSOfUyM jh3Q1NggZi5z4TwSdz40KMOqYD67jWrJiVQWJe8T9N255h2Fu+q06cVLP4ahVR2Q5ZeV97wDoaA LZU+aP0K9umS7d22SJe6DFrynioAi7xkQGVrDu2qDtdmW8x4t+6aeTBlFqKsTj+LExSlr9OqcrW +SZu8AgpMhjH6eiNS3geQNKFMp9m3tksFd4PPpSHOPH+FPVHObqUTJFSQseGE6cDjQqC9lD8Yr3 PhmK262k5vVz1/OEiWaVaJBK8Jw6axPRuZQrGt5ln/wOWdeUbENQqXqvm3QxQ7x49nwQOEqDb40 cmKMqxxZmIXzq9UhmfFWnoqLYdzit2e+bjGdHCbyypMnqubrR626hDqEds9Uyw8PUs3b4NmaSIN 9XZ+UicFCRlblM/oevmhspqJjENahg4vF/t1B3QYschAeipcOxD9FooY7/fuLArUwc1xEln6aC4 AGGPOxk9z1kNOqA== X-Mailer: b4 0.14.2 Message-ID: <20250704-iov-iter-v2-2-e69aa7c1f40e@google.com> Subject: [PATCH v2 2/4] rust: iov: add iov_iter abstractions for ITER_DEST From: Alice Ryhl To: Greg Kroah-Hartman , Alexander Viro , Arnd Bergmann , Miguel Ojeda Cc: Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Andreas Hindborg , Trevor Gross , Danilo Krummrich , Matthew Maurer , Lee Jones , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Benno Lossin Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This adds abstractions for the iov_iter type in the case where data_source is ITER_DEST. This will make Rust implementations of fops->read_iter possible. This series only has support for using existing IO vectors created by C code. Additional abstractions will be needed to support the creation of IO vectors in Rust code. These abstractions make the assumption that `struct iov_iter` does not have internal self-references, which implies that it is valid to move it between different local variables. Signed-off-by: Alice Ryhl --- rust/kernel/iov.rs | 137 +++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 137 insertions(+) diff --git a/rust/kernel/iov.rs b/rust/kernel/iov.rs index b4d7ec14c57a561a01cd65b6bdf0f94b1b373b84..917fc5242225aaef60e2170c806= 37a9161351f50 100644 --- a/rust/kernel/iov.rs +++ b/rust/kernel/iov.rs @@ -16,6 +16,15 @@ use core::{marker::PhantomData, mem::MaybeUninit, slice}; =20 const ITER_SOURCE: bool =3D bindings::ITER_SOURCE !=3D 0; +const ITER_DEST: bool =3D bindings::ITER_DEST !=3D 0; + +// Compile-time assertion for the above constants. +const _: () =3D { + build_assert!( + ITER_SOURCE !=3D ITER_DEST, + "ITER_DEST and ITER_SOURCE should be different." + ); +}; =20 /// An IO vector that acts as a source of data. /// @@ -150,3 +159,131 @@ pub fn copy_from_iter_raw(&mut self, out: &mut [Maybe= Uninit]) -> &mut [u8] { unsafe { slice::from_raw_parts_mut(out.as_mut_ptr().cast(), len) } } } + +/// An IO vector that acts as a destination for data. +/// +/// IO vectors support many different types of destinations. This includes= both buffers in +/// kernel-space and writing to userspace. It's possible that the destinat= ion buffer is mapped in a +/// thread-local manner using e.g. `kmap_local_page()`, so this type is no= t `Send` to ensure that +/// the mapping is written to the right context in that scenario. +/// +/// # Invariants +/// +/// Must hold a valid `struct iov_iter` with `data_source` set to `ITER_DE= ST`. For the duration +/// of `'data`, it must be safe to write data to this IO vector. +#[repr(transparent)] +pub struct IovIterDest<'data> { + iov: Opaque, + /// Represent to the type system that this value contains a pointer to= writable data it does + /// not own. + _source: PhantomData<&'data mut [u8]>, +} + +impl<'data> IovIterDest<'data> { + /// Obtain an `IovIterDest` from a raw pointer. + /// + /// # Safety + /// + /// * For the duration of `'iov`, the `struct iov_iter` must remain va= lid and must not be + /// accessed except through the returned reference. + /// * For the duration of `'data`, the buffers backing this IO vector = must be valid for + /// writing. + #[track_caller] + #[inline] + pub unsafe fn from_raw<'iov>(ptr: *mut bindings::iov_iter) -> &'iov mu= t IovIterDest<'data> { + // SAFETY: The caller ensures that `ptr` is valid. + let data_source =3D unsafe { (*ptr).data_source }; + assert_eq!(data_source, ITER_DEST); + + // SAFETY: The caller ensures the struct invariants for the right = durations. + unsafe { &mut *ptr.cast::>() } + } + + /// Access this as a raw `struct iov_iter`. + #[inline] + pub fn as_raw(&mut self) -> *mut bindings::iov_iter { + self.iov.get() + } + + /// Returns the number of bytes available in this IO vector. + /// + /// Note that this may overestimate the number of bytes. For example, = reading from userspace + /// memory could fail with EFAULT, which will be treated as the end of= the IO vector. + #[inline] + pub fn len(&self) -> usize { + // SAFETY: It is safe to access the `count` field. + unsafe { + (*self.iov.get()) + .__bindgen_anon_1 + .__bindgen_anon_1 + .as_ref() + .count + } + } + + /// Returns whether there are any bytes left in this IO vector. + /// + /// This may return `true` even if there are no more bytes available. = For example, reading from + /// userspace memory could fail with EFAULT, which will be treated as = the end of the IO vector. + #[inline] + pub fn is_empty(&self) -> bool { + self.len() =3D=3D 0 + } + + /// Advance this IO vector by `bytes` bytes. + /// + /// If `bytes` is larger than the size of this IO vector, it is advanc= ed to the end. + #[inline] + pub fn advance(&mut self, bytes: usize) { + // SAFETY: `self.iov` is a valid IO vector. + unsafe { bindings::iov_iter_advance(self.as_raw(), bytes) }; + } + + /// Advance this IO vector backwards by `bytes` bytes. + /// + /// # Safety + /// + /// The IO vector must not be reverted to before its beginning. + #[inline] + pub unsafe fn revert(&mut self, bytes: usize) { + // SAFETY: `self.iov` is a valid IO vector, and `bytes` is in boun= ds. + unsafe { bindings::iov_iter_revert(self.as_raw(), bytes) }; + } + + /// Write data to this IO vector. + /// + /// Returns the number of bytes that were written. If this is shorter = than the provided slice, + /// then no more bytes can be written. + #[inline] + pub fn copy_to_iter(&mut self, input: &[u8]) -> usize { + // SAFETY: `input` is valid for `input.len()` bytes. + unsafe { bindings::_copy_to_iter(input.as_ptr().cast(), input.len(= ), self.as_raw()) } + } + + /// Utility for implementing `read_iter` given the full contents of th= e file. + /// + /// The full contents of the file being read from is represented by `c= ontents`. This call will + /// write the appropriate sub-slice of `contents` and update the file = position in `ppos` so + /// that the file will appear to contain `contents` even if takes mult= iple reads to read the + /// entire file. + #[inline] + pub fn simple_read_from_buffer(&mut self, ppos: &mut i64, contents: &[= u8]) -> Result { + if *ppos < 0 { + return Err(EINVAL); + } + let Ok(pos) =3D usize::try_from(*ppos) else { + return Ok(0); + }; + if pos >=3D contents.len() { + return Ok(0); + } + + // BOUNDS: We just checked that `pos < contents.len()` above. + let num_written =3D self.copy_to_iter(&contents[pos..]); + + // OVERFLOW: pos+num_written <=3D contents.len() <=3D isize::MAX <= =3D i64::MAX + *ppos =3D (pos + num_written) as i64; + + Ok(num_written) + } +} --=20 2.50.0.727.gbf7dc18ff4-goog From nobody Tue Oct 7 22:51:46 2025 Received: from mail-wr1-f73.google.com (mail-wr1-f73.google.com [209.85.221.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 0EA262E9EC6 for ; Fri, 4 Jul 2025 09:26:24 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751621186; cv=none; b=i75ahLDsI/sBC8Iq5ULHsoP4c82YRX7Haflj5k2s2JNhc+EOnMLXs/VRnoiZRnbuJjMLjgbOlR5iYCRS0zJxfhtOi3oewpma2hKZPs2QwvApd7syLqOt2zIRtcEGJO4k8ZDKfEnveWCvDTZWOLG/0d9jHXza1b+a7K0es0NOk1g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751621186; c=relaxed/simple; bh=bRUtI9KpAhhm4yIAN+C8rrv5c2+QoPmfHSk9YxoCjuw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=kPiRLf5j8VRpvdS+uIAGvYyAe3U6D+flc/ORIj5248A5J6g1vdvgsURU9BfZL1bozEiR1oHdD4pRwdf4bVJpIK0cfshJkPf+fv1k6pG7wifxI5uBXLEEvItMT4OxyHCGxgFdW/Ep+GWa+JiLuNLXmhXplOUQUz6inejhDalGHaY= 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=lOWjDgtA; arc=none smtp.client-ip=209.85.221.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="lOWjDgtA" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-3a4f8fd1847so306113f8f.1 for ; Fri, 04 Jul 2025 02:26:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1751621183; x=1752225983; 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=zUd2sq4XBEjYfJBZbomCDBt/A4I34lE0cFv0SVFw/2I=; b=lOWjDgtAqKo6AaRSbm9xETI83ruGhsFW99hMOX4D0jbXewwdOkamajOgQavbhDm3Li Bzseop/lepHUoUcXr1jOnb08ZSlPwsBMbNZ7T/gwge3XPMeryGgsi+jJp9SBGUJFMuDa otkPCo0OvWamwcpshR98mmMQ8LNkTLVNc85i933OwxISvr5fAAnFQWwfJexpuQHRp4Vd gAOq6Ssk9/nFdkUcGrlzkPqbvHwYQAD/Dv59F03KkO6Wsg3vY+awTKCC8US79h/C+foR z+vfR+pTzJ0ktQjRXWEhUdcYWkj4lQRa4DkWAfkUyQky4fGuXuWY9J0//I39q/cMSP0D wVGA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1751621183; x=1752225983; 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=zUd2sq4XBEjYfJBZbomCDBt/A4I34lE0cFv0SVFw/2I=; b=ZtYmPpvud2hBJG2Jhd+W99Rw/FBt2U2ZRM6H7c6/xDxC2v0lm5o2jxeFyvoVOYEVaW eG2dfWQxQkaOSZQUHOpDsQteo/2yWHOvhJKXJ8Z+WRMQv4d3+dzN7FMRSY798iwuui94 hDJ7NzQHyYGOLIyvi9Rj+JN/eka8dvNb2Ti3E9iFJZdhmcXNzC1A0b5FkYQz4Rb6PdRh MKOHvPIvHsKnIumDPS/4zgcn+kORVXYuXhlpp/+wgVMXFYMqgMs0p6jIRa50Uc1sENSS Yh4AznYgo/FPlnZ1YepAWPLKz4ocEiSZlCxw9VlJbs6gbkstykURkkRy5KGJDQDzLAtr i6+w== X-Forwarded-Encrypted: i=1; AJvYcCW/ooB5aC0DcWO6i38b3bPe63q/rFNz4s+q7vBCc4vVPNEhiLKiEId/TS+2vsep7LTIKZLNgDOmXU/5qGc=@vger.kernel.org X-Gm-Message-State: AOJu0YxazeHil7yPjgDm4MIB5OzaCACOwCKokC8EDFupv7qQX0wEbqV2 9gls6THjzya6CaYE8MyiKDGkTHm/WxVE/xE2bHqAmoS1OdX4hns2gVoNG6QMRc8ooFIJiuzoqoo QnCftijMnJs7BsTeiZw== X-Google-Smtp-Source: AGHT+IFsAR7ak+uOFE2//Zn4PgR+QTZcpjZtO9D/5Piz3xZ6reTuB/G8jhnPA+dUhSNRqNVBuuFGL+Z6pShPp1k= X-Received: from wrbew11.prod.google.com ([2002:a05:6000:240b:b0:3a4:f038:be6b]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6000:2004:b0:3b3:9ca4:ac8e with SMTP id ffacd0b85a97d-3b4964f7b7emr1517776f8f.44.1751621183379; Fri, 04 Jul 2025 02:26:23 -0700 (PDT) Date: Fri, 04 Jul 2025 09:26:02 +0000 In-Reply-To: <20250704-iov-iter-v2-0-e69aa7c1f40e@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250704-iov-iter-v2-0-e69aa7c1f40e@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=5635; i=aliceryhl@google.com; h=from:subject:message-id; bh=bRUtI9KpAhhm4yIAN+C8rrv5c2+QoPmfHSk9YxoCjuw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoZ546DiATh9SRSszo5bqCJdgjEr67UShsCFwE+ lHjRArvg5WJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaGeeOgAKCRAEWL7uWMY5 RlqZD/wInSW2tpLzMczSL3xJmfBk81/dAlQcSKAP90dF9bAFfklJS2Ef5UQsCgghYigYFx4Cles HzNkNZmXEuzWbW68Gbas/HzMicHzEtDN/Vv5sLOwKPCvM+Kc70rXwkZdGM+k6NHET0Xfpxzt2sY uYWAauu6OD71rBL6m4m1S4Xs8Dn3s4xDVUq75BBgQk34rCywSlGbItwB6BCnC9HCnEb7w5soVBa trFWXr9JjHb36UJXC/+hb3WYajKdv8lskv91gHbSIHLjHuL/XM6VT0iV12N01emtXhM7j2X4075 0n22N0FL7zBy6WnIEXHNLXDv+ZelkWlV85Jiqo8mc62PZILCgoWxLKbkzl3lzh/0w9o/21LVo5Q xB6L4tt6hjZgwS38zlsFzbvKJgzPNs/Z0PlHfxUZtMFOenqUOkEpeffqZagZyWJoJL4deHxMS2j D+yMsuFo5arjbxWrFeS1d/kcXIRcuGEyASv3hKabzzii4mJHvlPzrLWMRKBwHwAPk4rmc0uERmR LbEnnuTGxJ1zBIDUG+aw6ZjvaA7e0R6OwEh4TQNjlIclSiPPNjA3qw/52n2dmdvYpCkNtqqoFFw K/oUxfOxVq3TJC1Oeaz6esqzaJ2iqVVeciK1Z2haaEBtS9e7lkWfzHXs4riRd3ba7eFKdcifEPv veMQzsFj1VuuPMg== X-Mailer: b4 0.14.2 Message-ID: <20250704-iov-iter-v2-3-e69aa7c1f40e@google.com> Subject: [PATCH v2 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures From: Alice Ryhl To: Greg Kroah-Hartman , Alexander Viro , Arnd Bergmann , Miguel Ojeda Cc: Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Andreas Hindborg , Trevor Gross , Danilo Krummrich , Matthew Maurer , Lee Jones , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Benno Lossin Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable These will be used for the read_iter() and write_iter() callbacks, which are now the preferred back-ends for when a user operates on a char device with read() and write() respectively. Co-developed-by: Lee Jones Signed-off-by: Lee Jones Signed-off-by: Alice Ryhl --- rust/kernel/miscdevice.rs | 97 +++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 96 insertions(+), 1 deletion(-) diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index 22f291211636f66efca6b33b675833236332719e..a49954c9b0d14117645be8139db= 792f1fd22589d 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -14,13 +14,14 @@ error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR}, ffi::{c_int, c_long, c_uint, c_ulong}, fs::File, + iov::{IovIterDest, IovIterSource}, mm::virt::VmaNew, prelude::*, seq_file::SeqFile, str::CStr, types::{ForeignOwnable, Opaque}, }; -use core::{marker::PhantomData, mem::MaybeUninit, pin::Pin}; +use core::{marker::PhantomData, mem::MaybeUninit, pin::Pin, ptr::NonNull}; =20 /// Options for creating a misc device. #[derive(Copy, Clone)] @@ -136,6 +137,16 @@ fn mmap( build_error!(VTABLE_DEFAULT_ERROR) } =20 + /// Read from this miscdevice. + fn read_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterDest<'_>)= -> Result { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Write to this miscdevice. + fn write_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterSource<'= _>) -> Result { + build_error!(VTABLE_DEFAULT_ERROR) + } + /// Handler for ioctls. /// /// The `cmd` argument is usually manipulated using the utilities in [= `kernel::ioctl`]. @@ -177,6 +188,36 @@ fn show_fdinfo( } } =20 +/// Wrapper for the kernel's `struct kiocb`. +/// +/// The type `T` represents the private data of the file. +pub struct Kiocb<'a, T> { + inner: NonNull, + _phantom: PhantomData<&'a T>, +} + +impl<'a, T: ForeignOwnable> Kiocb<'a, T> { + /// Get the Rust data that represents this misc device. + pub fn device(&self) -> ::Borrowed<'a> { + // SAFETY: The `kiocb` lets us access the private data. + let private =3D unsafe { (*(*self.inner.as_ptr()).ki_filp).private= _data }; + // SAFETY: The kiocb has shared access to the private data. + unsafe { ::borrow(private) } + } + + /// Gets the current value of `ki_pos`. + pub fn ki_pos(&self) -> i64 { + // SAFETY: The `kiocb` can access `ki_pos`. + unsafe { (*self.inner.as_ptr()).ki_pos } + } + + /// Gets a mutable reference to the `ki_pos` field. + pub fn ki_pos_mut(&mut self) -> &mut i64 { + // SAFETY: The `kiocb` can access `ki_pos`. + unsafe { &mut (*self.inner.as_ptr()).ki_pos } + } +} + /// A vtable for the file operations of a Rust miscdevice. struct MiscdeviceVTable(PhantomData); =20 @@ -240,6 +281,50 @@ impl MiscdeviceVTable { 0 } =20 + /// # Safety + /// + /// `kiocb` must be correspond to a valid file that is associated with= a + /// `MiscDeviceRegistration`. `iter` must be a valid `struct iov_it= er` for writing. + unsafe extern "C" fn read_iter( + kiocb: *mut bindings::kiocb, + iter: *mut bindings::iov_iter, + ) -> isize { + let kiocb =3D Kiocb { + // SAFETY: The read_iter call of a file is given a kiocb for t= hat file. + inner: unsafe { NonNull::new_unchecked(kiocb) }, + _phantom: PhantomData, + }; + // SAFETY: This is a valid `struct iov_iter` for writing. + let iov =3D unsafe { IovIterDest::from_raw(iter) }; + + match T::read_iter(kiocb, iov) { + Ok(res) =3D> res as isize, + Err(err) =3D> err.to_errno() as isize, + } + } + + /// # Safety + /// + /// `kiocb` must be correspond to a valid file that is associated with= a + /// `MiscDeviceRegistration`. `iter` must be a valid `struct iov_it= er` for writing. + unsafe extern "C" fn write_iter( + kiocb: *mut bindings::kiocb, + iter: *mut bindings::iov_iter, + ) -> isize { + let kiocb =3D Kiocb { + // SAFETY: The read_iter call of a file is given a kiocb for t= hat file. + inner: unsafe { NonNull::new_unchecked(kiocb) }, + _phantom: PhantomData, + }; + // SAFETY: This is a valid `struct iov_iter` for reading. + let iov =3D unsafe { IovIterSource::from_raw(iter) }; + + match T::write_iter(kiocb, iov) { + Ok(res) =3D> res as isize, + Err(err) =3D> err.to_errno() as isize, + } + } + /// # Safety /// /// `file` must be a valid file that is associated with a `MiscDeviceR= egistration`. @@ -336,6 +421,16 @@ impl MiscdeviceVTable { open: Some(Self::open), release: Some(Self::release), mmap: if T::HAS_MMAP { Some(Self::mmap) } else { None }, + read_iter: if T::HAS_READ_ITER { + Some(Self::read_iter) + } else { + None + }, + write_iter: if T::HAS_WRITE_ITER { + Some(Self::write_iter) + } else { + None + }, unlocked_ioctl: if T::HAS_IOCTL { Some(Self::ioctl) } else { --=20 2.50.0.727.gbf7dc18ff4-goog From nobody Tue Oct 7 22:51:46 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.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 4AD432DA769 for ; Fri, 4 Jul 2025 09:26:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751621188; cv=none; b=bSztBb+EUZCeDYB2H1fc3chscSHFocUSAdidkeTR0xmXTeE2nOeqHrqvOSWkXrkDljNqGdFeFewrezv+U89T8y6TvlKfd0wmOw6Gyb4Okj85K78gxGQwW3BYdhsAEnNDdGYEmOMZDs2UZB1Hc/GlEqowg78Xa+7wiiO2jkUmbpQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751621188; c=relaxed/simple; bh=B6C5WzpcTdAJyw37W4IFPFFrpl2YdAoUxTO/C6ZYP9Y=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=Ff26l1XcvcERrHGSQBTirAY4GZqUKFxJLalabb/F00NLX5zd5eV6lFJxlnMeP/OTV47dIQo547BPn9Lrjye3M6vBztpRcSU4cExRFXrj7yq78HqQaOA/cBagPXXF/bKTrQ7iwaCadIknetZKibiY6RapfJB6V+RG0/4cmEYBLPQ= 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=sx3nXLYo; arc=none smtp.client-ip=209.85.128.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="sx3nXLYo" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-4536962204aso2918355e9.3 for ; Fri, 04 Jul 2025 02:26:25 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1751621184; x=1752225984; 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=MR50fO5xmzFDTEg2wlFyTK3zQ7s7ufFg/ixzt4If/Do=; b=sx3nXLYoBZfNAEPCoYIDWq+n7l/RTVxcsDICg4dNEcgYaGXnrnMGrEyq6hKsqDQb4B 0+2PzqAR1rlDJeN90L5f8v3C/OH7gqnaEaz0HMapwUIy6brF1VjLCf0iw0I2Nwz2pkfm 3xIQVZPOek79rg9MorQ3bVNyDhuUxYIc7lJPMvON0wYIBx4rS8CB3DgHkYcxTchizDct yTgEjdK9Kf/aYWB9A90PLRrqljVxYI9dBRMLmaiG1tBTaX0zs3QRJ8AEWhDOLAPBBasa C3yQFqPy0u+Ow2O/YtVYJWHfijNb2RzuRk/176kPB0HWgKKunOSMImG2v6L0KPFcAPM4 MWZw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1751621184; x=1752225984; 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=MR50fO5xmzFDTEg2wlFyTK3zQ7s7ufFg/ixzt4If/Do=; b=UpBSzf9gbb8EAW0IL5YZ2YyZMP3aGSEmt0/gso2ZAJ/nLV4YavA75r9tU9kJwZD1Qa 7hynXZkefq2OMhdgah+APdG1rASg4j0WF1GAMQw+sqsJrenE40XdFniR9b7CIdsl547J vKvWS5dcmFof/myQCmsMt2PTagwBu4YBUoQmqmMI/qAapGnyg+Xj+TtLDuA/UY/KOR7s HZQ1UOlHcNL+Z85txNdHWyXfdh2lEbj0jTvTFlVSPUTioqlw9kvxH0OSMiNH9YvFgrOt +G3yNNrEtyO46KaKevxq0oTUm/NDAcYDvocXPQ654r+uYrPmCvSB4clSu11XyzKqzFyL kMeg== X-Forwarded-Encrypted: i=1; AJvYcCVv0wcrS1HsZvVQk8727BZJenmsLiuWgwZPYfJFiL6j96bGGnFmb/V5HiYOH/wG8Vt90MXjbDPDaYbewFw=@vger.kernel.org X-Gm-Message-State: AOJu0YyZwNS4QILm6DeM55qPJauEs2hF4++ErvKYtwkF+O5mHxEZ6Js2 DGFE3rm8Itjg6cgVlHRlK04lsyVze66PFzPK+E5ZftWRvrAiejHSljntBKdbe4z6YyVg7nNLlBj 9Q9PmOIcU0O5lSDh6/g== X-Google-Smtp-Source: AGHT+IHCtVdBGP9lMoZ4v6PFIcC0IVtWLebAFehqoiBmYdjoN/h3RTOF4SVckWEkPMd6hopVhYTdXVOoe3EVfQo= X-Received: from wmbjg20.prod.google.com ([2002:a05:600c:a014:b0:43c:ef7b:ffac]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a5d:5d0e:0:b0:3a4:f35b:d016 with SMTP id ffacd0b85a97d-3b497011a15mr1205095f8f.11.1751621184627; Fri, 04 Jul 2025 02:26:24 -0700 (PDT) Date: Fri, 04 Jul 2025 09:26:03 +0000 In-Reply-To: <20250704-iov-iter-v2-0-e69aa7c1f40e@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250704-iov-iter-v2-0-e69aa7c1f40e@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3201; i=aliceryhl@google.com; h=from:subject:message-id; bh=lnWi4k7yTJFShSQzujr6zKgF9AzbaeRzmZc5IbQPUys=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoZ546x2nNNNI31RVo/3/nAvI07XvY6uZrR0AxL VuwkRR6JduJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaGeeOgAKCRAEWL7uWMY5 RmmSD/oCj8we4NB4Br74fhQcwI6/Q7B6YSt9lyg7Bq8bUnb1yJc2DmgKoD2hxu0/rxd7qL9+3yp s7MCzn1J4gZx4QoJLByBslv9HgH6MoxvRQOL/piP2i6n/dXVht6CfM1nSdvIk4nJrKwMLVp4KCK 1cbXLgGH6k+TObbYDLkB8ljEZ303zhoz0u2yI8US0jmsz9yOWZPI8kOg/nZIyNa6CY05rfYjMLZ mqxdsGFpGr4nXTeiL+Ls2pXsBjzMsIIPGk7siuzjGaMnWqAq7JljVDzocwjS4VKrxVEk4zMf+A9 F6ao0AfGtT2m/w7ZP7+5E7PH5xiL8mA6EpGmzZ7HrAW9iljqfaNBomKn/ZQSyXJK24QVl04ffIj 3rR5OCQ2OgFNMT6IhNq2Fd/2jCtrdsZXOBpij+ZjwKu8MCPZQp5kFqQNPUi6rEaKYJt9PaYQ1WX vx0y8r9hXxZkURpjcG4mRtqGjux8/omosacaTSsLA7DEGgOTin/aAvfS7u8uskIEzsRzaE3RlVQ u4TvFUTxTA5TZfEc0zYAyvvG0HPs4I9s6pOdJKGbMUctRWsxTrbKszVypAfjtK+7+UuoNm51uok ACgZokoeMgjsh08LHiwwHQmFNaBmn1FxnbABmSiWxN5M3MqtJ7PaBtMZeEyibuIFETxIlII09ml Ste6eUfYmRBVM5w== X-Mailer: b4 0.14.2 Message-ID: <20250704-iov-iter-v2-4-e69aa7c1f40e@google.com> Subject: [PATCH v2 4/4] samples: rust_misc_device: Expand the sample to support read()ing from userspace From: Alice Ryhl To: Greg Kroah-Hartman , Alexander Viro , Arnd Bergmann , Miguel Ojeda Cc: Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Andreas Hindborg , Trevor Gross , Danilo Krummrich , Matthew Maurer , Lee Jones , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Benno Lossin Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable From: Lee Jones A userland application can now operate on the char device with read() in order to consume a locally held buffer. Memory for the buffer is to be provisioned and the buffer populated in its subsequently provided write() counterpart. Signed-off-by: Lee Jones Reviewed-by: Andreas Hindborg Co-developed-by: Alice Ryhl Signed-off-by: Alice Ryhl --- samples/rust/rust_misc_device.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/samples/rust/rust_misc_device.rs b/samples/rust/rust_misc_devi= ce.rs index c881fd6dbd08cf4308fe1bd37d11d28374c1f034..595411f92679b5a25bd81b032d6= 39d1332156a14 100644 --- a/samples/rust/rust_misc_device.rs +++ b/samples/rust/rust_misc_device.rs @@ -102,7 +102,8 @@ device::Device, fs::File, ioctl::{_IO, _IOC_SIZE, _IOR, _IOW}, - miscdevice::{MiscDevice, MiscDeviceOptions, MiscDeviceRegistration}, + iov::{IovIterDest, IovIterSource}, + miscdevice::{Kiocb, MiscDevice, MiscDeviceOptions, MiscDeviceRegistrat= ion}, new_mutex, prelude::*, sync::Mutex, @@ -144,6 +145,7 @@ fn init(_module: &'static ThisModule) -> impl PinInit { =20 struct Inner { value: i32, + buffer: KVVec, } =20 #[pin_data(PinnedDrop)] @@ -165,7 +167,10 @@ fn open(_file: &File, misc: &MiscDeviceRegistration) -> Result) -> Result, iov: &mut IovIterDest<'_= >) -> Result { + let me =3D kiocb.device(); + dev_info!(me.dev, "Reading from Rust Misc Device Sample\n"); + + let inner =3D me.inner.lock(); + // Read the buffer contents, taking the file position into account. + let read =3D iov.simple_read_from_buffer(kiocb.ki_pos_mut(), &inne= r.buffer)?; + + Ok(read) + } + + fn write_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterSource= <'_>) -> Result { + let me =3D kiocb.device(); + dev_info!(me.dev, "Writing to Rust Misc Device Sample\n"); + + let mut inner =3D me.inner.lock(); + + // Replace buffer contents. + inner.buffer.clear(); + let len =3D iov.copy_from_iter_vec(&mut inner.buffer, GFP_KERNEL)?; + + // Set position to zero so that future `read` calls will see the n= ew contents. + *kiocb.ki_pos_mut() =3D 0; + + Ok(len) + } + fn ioctl(me: Pin<&RustMiscDevice>, _file: &File, cmd: u32, arg: usize)= -> Result { dev_info!(me.dev, "IOCTLing Rust Misc Device Sample\n"); =20 --=20 2.50.0.727.gbf7dc18ff4-goog