From nobody Mon Feb 9 08:54:34 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id EDFA7323D; Fri, 31 Jan 2025 13:32:11 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738330332; cv=none; b=IP6qVWJPa9oezOjQJnyDrwnTGsbh51gMaHHFnpN+gGHo50XBYjGAN95SHYsPbGBZaDWrVtuUcHRkXLJwv5fpoAC21TIS3DOoAiricPDBugrIMFXxvWzqfrkZVRpg961jHxw61upU843ly0wtr+ph+FV6H34Z+mdnJV9CCc5FwqA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738330332; c=relaxed/simple; bh=05RiDeU4JoMDP04huK1ZEw1hzOOuf/PISxFtZNSCll0=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=HopVnA3Zc2Sme80uu4WqBWtKgfHU/Oc5p29Re2qVKGKl8+CKcAVh8ytImhkGls67dl/ZN9uNAJTJu/K0beKJ7fyWkALpPqgZ2KWSx7v9T3zvWNJT7nHovDHXqLq1nj6Rw+lVvUpKYNj7a6A+e3fyyYVJ1pd6T9jJjCxFwTIy8nM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=VRgwVNsV; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="VRgwVNsV" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 709FEC4CEE2; Fri, 31 Jan 2025 13:32:07 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1738330331; bh=05RiDeU4JoMDP04huK1ZEw1hzOOuf/PISxFtZNSCll0=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=VRgwVNsV8CTpok2e2pUNzl3ggtvoQ0pcM36GF0X7Vi5AauBuAmYwXAUpOYphyKuL/ 5QqkiaB4u9sfeFLjUTOaUE9cs2nAeeuQ9q8uriKorR/6PqDgg6OL0CrPQPQDYd2ToG 6dBzjIsskHRbsijaSG1hGosCnsSfxNKpNRRzwUf2mJms4Tq2GBVtbGT93feCKPPg9S 7rcqfA6Q5JCGhl3f2vvC+5L+5FmNQoPiuR3juQEpw0kJ+KfgjU2VUFPZvGB+u9ry2V qZUxq/EMmMvJa7wNLrcP1JVrGo9uPWJ5bBTO0EWuLer1qSnCQ9N8ONW62kY7ptI1NI Gjt5foATluGHA== From: Andreas Hindborg Date: Fri, 31 Jan 2025 14:30:08 +0100 Subject: [PATCH 1/4] rust: types: add `ForeignOwnable::PointedTo` Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250131-configfs-v1-1-87947611401c@kernel.org> References: <20250131-configfs-v1-0-87947611401c@kernel.org> In-Reply-To: <20250131-configfs-v1-0-87947611401c@kernel.org> To: Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Joel Becker , Christoph Hellwig Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg , Tamir Duberstein X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=15053; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=Kz3NBZWvsN1C0g/Tf6dy5jZOMimPLS7pGuT/q5cX0sE=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnnNCDQ3mwWab2keobq4zBuQGYjHuwalPBkWKBv OOHgi3xOoiJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ5zQgwAKCRDhuBo+eShj d85ED/925F/18yCu2AuXyR6LC0hHYENqaOu0NpPS8yfZwklBRhyjMvFAI/r9Q/9ompCJj2Cml4F PY91JpaBxeJ2Cu94+sa4FTZgQcPHOs1xEBOZ0JaM1nincXu1bzEJtKPPSgo4rW+GgVdny9szobf TxCoemCoKI1Y9kGULWLJDyDkHppXARziCZIe0YGHCV7aL4pKeNCbtOYvbsUMHDoQ89AC3k4Kn3b 4qWIRD25rh5xnEPy4JqsFWvURAla0BWw46qbQcQWeE5LVY/9gY1tZTINuPs+TlOcylqvnjM4zZ+ Ser0LpEhoPJAV1mAUu5PIOq3RNxTbtLrSlhyTFPhDx3o8FGKY2zuTOoiEPaegH7vZOkbU+xkIcK tQp6f3Hzq+P0TsjDlAZH7O99YkqaejxxXa//xRFSs20nitRk4I4FxllJn8I0Qs7zxa29NU4iByx aZ457j7GZYFT5N1fKUx9nf6O2YejDTRCSYk6CQHYvQpRKHOVzVtz8eagcIFAiPeUwyjFuKSCdWA 8pYCK1d3YylDVamFNyrH6hAuC/83s0Xstr9x4m5ctQlz4eRdX6E9eEnsVwKo2CS8tTIt2ZBy12b gT95yBOr8yZ9XpNsMZiPa662KTC2gATX7mXv6l3SgvXjEithFwMR64+WoVbeesYnu6IriCWjbxu 2+4kjBGQ2KuZDbQ== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 From: Tamir Duberstein Allow implementors to specify the foreign pointer type; this exposes information about the pointed-to type such as its alignment. This requires the trait to be `unsafe` since it is now possible for implementors to break soundness by returning a misaligned pointer. Encoding the pointer type in the trait (and avoiding pointer casts) allows the compiler to check that implementors return the correct pointer type. This is preferable to directly encoding the alignment in the trait using a constant as the compiler would be unable to check it. Reviewed-by: Andreas Hindborg Signed-off-by: Tamir Duberstein Signed-off-by: Andreas Hindborg Reviewed-by: Alice Ryhl Reviewed-by: Fiona Behrens --- This is a resend of the patch at the link below, adapted to apply on top of `rust-6.14`. Link: https://lore.kernel.org/r/20241217-rust-xarray-bindings-v14-1-9fef3ce= fcb41@gmail.com --- rust/kernel/alloc/kbox.rs | 38 ++++++++++++++++++++------------------ rust/kernel/miscdevice.rs | 8 ++++---- rust/kernel/sync/arc.rs | 21 ++++++++++++--------- rust/kernel/types.rs | 46 +++++++++++++++++++++++++++++++------------= --- 4 files changed, 67 insertions(+), 46 deletions(-) diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs index cb4ebea3b07422ca0f402512b7c66d66fd212042..55529832db54adc4715c1a067f1= eb5ff3087c869 100644 --- a/rust/kernel/alloc/kbox.rs +++ b/rust/kernel/alloc/kbox.rs @@ -349,68 +349,70 @@ fn try_init(init: impl Init, flags: Flags) -= > Result } } =20 -impl ForeignOwnable for Box +// SAFETY: The `into_foreign` function returns a pointer that is well-alig= ned. +unsafe impl ForeignOwnable for Box where A: Allocator, { + type PointedTo =3D T; type Borrowed<'a> =3D &'a T; type BorrowedMut<'a> =3D &'a mut T; =20 - fn into_foreign(self) -> *mut crate::ffi::c_void { - Box::into_raw(self).cast() + fn into_foreign(self) -> *mut Self::PointedTo { + Box::into_raw(self) } =20 - unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self { + unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self { // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous // call to `Self::into_foreign`. - unsafe { Box::from_raw(ptr.cast()) } + unsafe { Box::from_raw(ptr) } } =20 - unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> &'a T { + unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> &'a T { // SAFETY: The safety requirements of this method ensure that the = object remains alive and // immutable for the duration of 'a. - unsafe { &*ptr.cast() } + unsafe { &*ptr } } =20 - unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> &'a mut T { - let ptr =3D ptr.cast(); + unsafe fn borrow_mut<'a>(ptr: *mut Self::PointedTo) -> &'a mut T { // SAFETY: The safety requirements of this method ensure that the = pointer is valid and that // nothing else will access the value for the duration of 'a. unsafe { &mut *ptr } } } =20 -impl ForeignOwnable for Pin> +// SAFETY: The `into_foreign` function returns a pointer that is well-alig= ned. +unsafe impl ForeignOwnable for Pin> where A: Allocator, { + type PointedTo =3D T; type Borrowed<'a> =3D Pin<&'a T>; type BorrowedMut<'a> =3D Pin<&'a mut T>; =20 - fn into_foreign(self) -> *mut crate::ffi::c_void { + fn into_foreign(self) -> *mut Self::PointedTo { // SAFETY: We are still treating the box as pinned. - Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }).cast() + Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) } =20 - unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self { + unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self { // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous // call to `Self::into_foreign`. - unsafe { Pin::new_unchecked(Box::from_raw(ptr.cast())) } + unsafe { Pin::new_unchecked(Box::from_raw(ptr)) } } =20 - unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> Pin<&'a T> { + unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> Pin<&'a T> { // SAFETY: The safety requirements for this function ensure that t= he object is still alive, // so it is safe to dereference the raw pointer. // The safety requirements of `from_foreign` also ensure that the = object remains alive for // the lifetime of the returned value. - let r =3D unsafe { &*ptr.cast() }; + let r =3D unsafe { &*ptr }; =20 // SAFETY: This pointer originates from a `Pin>`. unsafe { Pin::new_unchecked(r) } } =20 - unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> Pin<&'a mut = T> { - let ptr =3D ptr.cast(); + unsafe fn borrow_mut<'a>(ptr: *mut Self::PointedTo) -> Pin<&'a mut T> { // SAFETY: The safety requirements for this function ensure that t= he object is still alive, // so it is safe to dereference the raw pointer. // The safety requirements of `from_foreign` also ensure that the = object remains alive for diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index b3a6cc50b240e9373a7d4e9959fabb42235a794f..fe0c059fabac11c0f316128bf63= b5ff10ee3c3ca 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -189,7 +189,7 @@ impl VtableHelper { }; =20 // SAFETY: The open call of a file owns the private data. - unsafe { (*file).private_data =3D ptr.into_foreign() }; + unsafe { (*file).private_data =3D ptr.into_foreign().cast() }; =20 0 } @@ -205,7 +205,7 @@ impl VtableHelper { // SAFETY: The release call of a file owns the private data. let private =3D unsafe { (*file).private_data }; // SAFETY: The release call of a file owns the private data. - let ptr =3D unsafe { ::from_foreign(private)= }; + let ptr =3D unsafe { ::from_foreign(private.= cast()) }; =20 T::release(ptr); =20 @@ -223,7 +223,7 @@ impl VtableHelper { // SAFETY: The ioctl call of a file can access the private data. let private =3D unsafe { (*file).private_data }; // SAFETY: Ioctl calls can borrow the private data of the file. - let device =3D unsafe { ::borrow(private) }; + let device =3D unsafe { ::borrow(private.cas= t()) }; =20 match T::ioctl(device, cmd, arg) { Ok(ret) =3D> ret as c_long, @@ -243,7 +243,7 @@ impl VtableHelper { // SAFETY: The compat ioctl call of a file can access the private data. let private =3D unsafe { (*file).private_data }; // SAFETY: Ioctl calls can borrow the private data of the file. - let device =3D unsafe { ::borrow(private) }; + let device =3D unsafe { ::borrow(private.cas= t()) }; =20 match T::compat_ioctl(device, cmd, arg) { Ok(ret) =3D> ret as c_long, diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 3cefda7a43725581dc0eaa8441e2528c161162e1..dfe4abf82c25cf18398628d9cd5= 345a292419351 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -140,9 +140,10 @@ pub struct Arc { _p: PhantomData>, } =20 +#[doc(hidden)] #[pin_data] #[repr(C)] -struct ArcInner { +pub struct ArcInner { refcount: Opaque, data: T, } @@ -342,18 +343,20 @@ pub fn into_unique_or_drop(self) -> Option>> { } } =20 -impl ForeignOwnable for Arc { +// SAFETY: The `into_foreign` function returns a pointer that is well-alig= ned. +unsafe impl ForeignOwnable for Arc { + type PointedTo =3D ArcInner; type Borrowed<'a> =3D ArcBorrow<'a, T>; type BorrowedMut<'a> =3D Self::Borrowed<'a>; =20 - fn into_foreign(self) -> *mut crate::ffi::c_void { - ManuallyDrop::new(self).ptr.as_ptr().cast() + fn into_foreign(self) -> *mut Self::PointedTo { + ManuallyDrop::new(self).ptr.as_ptr() } =20 - unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self { + unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self { // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous // call to `Self::into_foreign`. - let inner =3D unsafe { NonNull::new_unchecked(ptr.cast::>()) }; + let inner =3D unsafe { NonNull::new_unchecked(ptr) }; =20 // SAFETY: By the safety requirement of this function, we know tha= t `ptr` came from // a previous call to `Arc::into_foreign`, which guarantees that `= ptr` is valid and @@ -361,17 +364,17 @@ unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) = -> Self { unsafe { Self::from_inner(inner) } } =20 - unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> ArcBorrow<'a, T>= { + unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> ArcBorrow<'a, T> { // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous // call to `Self::into_foreign`. - let inner =3D unsafe { NonNull::new_unchecked(ptr.cast::>()) }; + let inner =3D unsafe { NonNull::new_unchecked(ptr) }; =20 // SAFETY: The safety requirements of `from_foreign` ensure that t= he object remains alive // for the lifetime of the returned value. unsafe { ArcBorrow::new(inner) } } =20 - unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> ArcBorrow<'a= , T> { + unsafe fn borrow_mut<'a>(ptr: *mut Self::PointedTo) -> ArcBorrow<'a, T= > { // SAFETY: The safety requirements for `borrow_mut` are a superset= of the safety // requirements for `borrow`. unsafe { Self::borrow(ptr) } diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 0dfaf45a755c7ce702027918e5fd3e97c407fda4..0cf93c293b884004a6ed64c2c09= 723efa7986270 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -18,7 +18,19 @@ /// /// This trait is meant to be used in cases when Rust objects are stored i= n C objects and /// eventually "freed" back to Rust. -pub trait ForeignOwnable: Sized { +/// +/// # Safety +/// +/// Implementers must ensure that [`into_foreign`] returns a pointer which= meets the alignment +/// requirements of [`PointedTo`]. +/// +/// [`into_foreign`]: Self::into_foreign +/// [`PointedTo`]: Self::PointedTo +pub unsafe trait ForeignOwnable: Sized { + /// Type used when the value is foreign-owned. In practical terms only= defines the alignment of + /// the pointer. + type PointedTo; + /// Type used to immutably borrow a value that is currently foreign-ow= ned. type Borrowed<'a>; =20 @@ -27,16 +39,18 @@ pub trait ForeignOwnable: Sized { =20 /// Converts a Rust-owned object to a foreign-owned one. /// - /// The foreign representation is a pointer to void. There are no guar= antees for this pointer. - /// For example, it might be invalid, dangling or pointing to uninitia= lized memory. Using it in - /// any way except for [`from_foreign`], [`try_from_foreign`], [`borro= w`], or [`borrow_mut`] can - /// result in undefined behavior. + /// # Guarantees + /// + /// The return value is guaranteed to be well-aligned, but there are n= o other guarantees for + /// this pointer. For example, it might be null, dangling, or point to= uninitialized memory. + /// Using it in any way except for [`ForeignOwnable::from_foreign`], [= `ForeignOwnable::borrow`], + /// [`ForeignOwnable::try_from_foreign`] can result in undefined behav= ior. /// /// [`from_foreign`]: Self::from_foreign /// [`try_from_foreign`]: Self::try_from_foreign /// [`borrow`]: Self::borrow /// [`borrow_mut`]: Self::borrow_mut - fn into_foreign(self) -> *mut crate::ffi::c_void; + fn into_foreign(self) -> *mut Self::PointedTo; =20 /// Converts a foreign-owned object back to a Rust-owned one. /// @@ -46,7 +60,7 @@ pub trait ForeignOwnable: Sized { /// must not be passed to `from_foreign` more than once. /// /// [`into_foreign`]: Self::into_foreign - unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self; + unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self; =20 /// Tries to convert a foreign-owned object back to a Rust-owned one. /// @@ -58,7 +72,7 @@ pub trait ForeignOwnable: Sized { /// `ptr` must either be null or satisfy the safety requirements for [= `from_foreign`]. /// /// [`from_foreign`]: Self::from_foreign - unsafe fn try_from_foreign(ptr: *mut crate::ffi::c_void) -> Option { + unsafe fn try_from_foreign(ptr: *mut Self::PointedTo) -> Option { if ptr.is_null() { None } else { @@ -81,7 +95,7 @@ unsafe fn try_from_foreign(ptr: *mut crate::ffi::c_void) = -> Option { /// /// [`into_foreign`]: Self::into_foreign /// [`from_foreign`]: Self::from_foreign - unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> Self::Borrowed<'= a>; + unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> Self::Borrowed<'a>; =20 /// Borrows a foreign-owned object mutably. /// @@ -109,21 +123,23 @@ unsafe fn try_from_foreign(ptr: *mut crate::ffi::c_vo= id) -> Option { /// [`from_foreign`]: Self::from_foreign /// [`borrow`]: Self::borrow /// [`Arc`]: crate::sync::Arc - unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> Self::Borrow= edMut<'a>; + unsafe fn borrow_mut<'a>(ptr: *mut Self::PointedTo) -> Self::BorrowedM= ut<'a>; } =20 -impl ForeignOwnable for () { +// SAFETY: The `into_foreign` function returns a pointer that is dangling,= but well-aligned. +unsafe impl ForeignOwnable for () { + type PointedTo =3D (); type Borrowed<'a> =3D (); type BorrowedMut<'a> =3D (); =20 - fn into_foreign(self) -> *mut crate::ffi::c_void { + fn into_foreign(self) -> *mut Self::PointedTo { core::ptr::NonNull::dangling().as_ptr() } =20 - unsafe fn from_foreign(_: *mut crate::ffi::c_void) -> Self {} + unsafe fn from_foreign(_: *mut Self::PointedTo) -> Self {} =20 - unsafe fn borrow<'a>(_: *mut crate::ffi::c_void) -> Self::Borrowed<'a>= {} - unsafe fn borrow_mut<'a>(_: *mut crate::ffi::c_void) -> Self::Borrowed= Mut<'a> {} + unsafe fn borrow<'a>(_: *mut Self::PointedTo) -> Self::Borrowed<'a> {} + unsafe fn borrow_mut<'a>(_: *mut Self::PointedTo) -> Self::BorrowedMut= <'a> {} } =20 /// Runs a cleanup function/closure when dropped. --=20 2.47.0 From nobody Mon Feb 9 08:54:34 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E5B5C1C5F08; Fri, 31 Jan 2025 13:32:15 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738330337; cv=none; b=T5CO7eI0QD5vmxN5o2Bievl2Rqucqc54FMz5Ycpk9ybv1NIAISrzqG++6FkfUXbnmYqhwVyHJdZO4qFXsCgI/Tw10DED9Br+KdJ90ixQTeQMCR2QvHuFL9XcrTbzYdTJ5ZmEkQzfgbXDoac/Zmox2tJv/MOttkuVZFOsIaQQ4k4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738330337; c=relaxed/simple; bh=jHpF1BuZ7uj/LCUV3YDDlFLxUILPvoQ+0fRV9/HcuJk=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=LQ/11t1LIe+1eH021MxyZ8xuA9Z/fIBER8+l3XdSKEzv8taBMIoxMGbs6D9l3QVe/UPHp9v4UeteR8BkW0WyNMlt8t3vu4HNxEeB+Faud7k9YQ5ADlkfiQfwCjJYT7r6sJtJ1m273nmXzDkvKoPPw8H+x+enGs82YLQbNZTKmlo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=huBXUyEj; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="huBXUyEj" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 217B6C4CED1; Fri, 31 Jan 2025 13:32:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1738330335; bh=jHpF1BuZ7uj/LCUV3YDDlFLxUILPvoQ+0fRV9/HcuJk=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=huBXUyEjVVKAL+eSvihoFNaVsPzB1AlK0d/ITTrAu4XoY4ZzLjQRrEJsZPLswFbqm lLa2s0XQwUtLG7JBkhEbQFQCVxswLT/CsDlWRQDhOgQzrEtgjBZer1DAAs4RU2eZ4X HTZBkR8BZPETXyJz/Xp5AcVYbLjsUP/UAGClSsFca090VhRuAnFs0C+o/Hf+O+3MAu naB2+umJqVyHwpRTwrNDFM+fc7uR3bTpWoPaJ4pPei4lkVJ/WKcGAMsVF8yf2CIAxa ga/mk5lB14Oaa/drc2x7h7p/vugy0lamlH3E+okqTuB4BZdswUXtI4+zshif/gheO1 7wSU6hNORDlLg== From: Andreas Hindborg Date: Fri, 31 Jan 2025 14:30:09 +0100 Subject: [PATCH 2/4] rust: sync: change ` as ForeignOwnable>::PointedTo` to `T` Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250131-configfs-v1-2-87947611401c@kernel.org> References: <20250131-configfs-v1-0-87947611401c@kernel.org> In-Reply-To: <20250131-configfs-v1-0-87947611401c@kernel.org> To: Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Joel Becker , Christoph Hellwig Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=3523; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=jHpF1BuZ7uj/LCUV3YDDlFLxUILPvoQ+0fRV9/HcuJk=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnnNCE4hN1GKXpwFBcbE/AjFXNXsUDuZz20NKHt BxIPsSi32WJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ5zQhAAKCRDhuBo+eShj d7P+D/9GGJ/ooXfnANlP5KCxqWGPR3A/IgmrYAGCzMMrPDfHh5NSK05dFGgqRYiwNZDbkdUVIcv X49IbCeSJKn9m24StFnWyqsApxCR0qaeLTnLG+QeflgYcUHy5qY6LQuY1xe1eULCyREfxT0xp79 vqhkO6ZDPgvZJSkSW6bRvoS3xNVqbZttatfZEC6Xn8S3NyKWFzweBqPmuTOdUEk54qW7TWTEJQf 1pHZ5yOiYhxh9c2Pu4EBBQP4PdxjzHNTMYNCzwxI+TSE4wfntvd13GCi8iPBbtMNQCp/7a5UsCb PSAY99527e5G5Y5J0uLQAu2KNWshVAdefsIhCnSk9++MMXTR3ksFzhzsWsHXfLXwi7usCbTHIG/ Oi9E584bWzVf4Nyk/etTIyTp6Szyf7ZfINj/MIJLd9FsAV8fW5BvwD09y+cJToaX9WvtGGDCsmA X9hFRAM+eSLFKnHGg6/+XtBlj7LBv+L02ozgYEWgZUBmG8qUI0YCsWoISDLp/19Obtf9wiMi7g5 oRhC3MMMxqK2ATrzfJHOCLIkon+XKmrxaw3girv5/khVXnDYpMLfprSzE62vnCWoU1pNqrAhr/w kvyeZKH/Sbmz7h3dUb2/TLLbGirRhzTVTI5elAZl/vAsN6TrQHBEwkESuxnTOmM8ZTkWtiB3MQY AO5Y0jdlJxtm7eQ== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Using `ArcInner` as `PoinedTo` in the `ForeignOwnable` implementation for `Arc` is a bit unfortunate. Using `T` as `PointedTo` does not remove any functionality, but allows `ArcInner` to be private. Further, it allows downstream users to write code that is generic over `Box` and `Arc`, when downstream users need access to `T` after calling `into_foreign`. Signed-off-by: Andreas Hindborg Reviewed-by: Fiona Behrens --- This patch is a dependency for Rust `configfs` abstractions. It allows both `Box` and `Arc` to be used as pointer types in the `configfs` hierarchy. --- rust/kernel/sync/arc.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index dfe4abf82c25cf18398628d9cd5345a292419351..503e318b4c4effa2f1499b6fee0= 944079fde99aa 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -143,7 +143,7 @@ pub struct Arc { #[doc(hidden)] #[pin_data] #[repr(C)] -pub struct ArcInner { +struct ArcInner { refcount: Opaque, data: T, } @@ -345,18 +345,25 @@ pub fn into_unique_or_drop(self) -> Option>> { =20 // SAFETY: The `into_foreign` function returns a pointer that is well-alig= ned. unsafe impl ForeignOwnable for Arc { - type PointedTo =3D ArcInner; + type PointedTo =3D T; type Borrowed<'a> =3D ArcBorrow<'a, T>; type BorrowedMut<'a> =3D Self::Borrowed<'a>; =20 fn into_foreign(self) -> *mut Self::PointedTo { - ManuallyDrop::new(self).ptr.as_ptr() + let x =3D ManuallyDrop::new(self).ptr.as_ptr(); + // SAFETY: `x` is a valid pointer to `Self` so the projection belo= w is + // in bounds of the allocation. + unsafe { core::ptr::addr_of_mut!((*x).data) } } =20 unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self { + // SAFETY: We did the reverse offset calculation in `into_foreign`= , so + // the offset calculation below is in bounds of the allocation. + let inner_ptr =3D unsafe { kernel::container_of!(ptr, ArcInner,= data).cast_mut() }; + // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous // call to `Self::into_foreign`. - let inner =3D unsafe { NonNull::new_unchecked(ptr) }; + let inner =3D unsafe { NonNull::new_unchecked(inner_ptr) }; =20 // SAFETY: By the safety requirement of this function, we know tha= t `ptr` came from // a previous call to `Arc::into_foreign`, which guarantees that `= ptr` is valid and @@ -365,9 +372,13 @@ unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> S= elf { } =20 unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> ArcBorrow<'a, T> { + // SAFETY: We did the reverse offset calculation in `into_foreign`= , so + // the offset calculation below is in bounds of the allocation. + let inner_ptr =3D unsafe { kernel::container_of!(ptr, ArcInner,= data).cast_mut() }; + // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous // call to `Self::into_foreign`. - let inner =3D unsafe { NonNull::new_unchecked(ptr) }; + let inner =3D unsafe { NonNull::new_unchecked(inner_ptr) }; =20 // SAFETY: The safety requirements of `from_foreign` ensure that t= he object remains alive // for the lifetime of the returned value. --=20 2.47.0 From nobody Mon Feb 9 08:54:34 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9A4211C5F08; Fri, 31 Jan 2025 13:32:19 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738330340; cv=none; b=P9Xr+qyB2qyAyyEENlfyPzR1Mm+JsIv2vN5kjp36ss0iB9d9rRFl5EO4M3n9/JrVFijANelW0QR3cB78T6S2Iq8ahe3ySG+eR1pYhAUXXk+tEBxduQ7i5ULTys5Q/MCul7K4G4rGGVZyW/uPS0/68PRn3Qz75+vwWSooYy0kgOA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738330340; c=relaxed/simple; bh=5kUbYYl6O9tWK5RDQX4Cl2uMDL6vlLePNSLAY9RUwXY=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=c7ywX9721/zmhA0SXC2Lmvw/u5IckUHFw9Ll/AdeMOpIcpApO5njBhLcp5XEHu6K4jjebLLLS0IyY9odmIfKag0gkJoLrCgXu6aIOO+2vwDZIymRQFgOWadmBSyBfMVs1AnMkBPcnNlQyv8i+2oxkdmeHU/BHHdE0AxB5g+c1uA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=e9vg4NTX; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="e9vg4NTX" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 01DF3C4CEDF; Fri, 31 Jan 2025 13:32:15 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1738330339; bh=5kUbYYl6O9tWK5RDQX4Cl2uMDL6vlLePNSLAY9RUwXY=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=e9vg4NTXhi2tOtOrNqblIqDIw/64BQbCsdT5uzO/8vbacuaNebCp4uF7IM7eEhHLd FmnpCDq7J+TrtmG5+XJTXtAkwNfHjeTS/7J9pFgOiApKDqLytxBwJ3MSlztx/Edjfy 8lKG5fMxW0R0MU9KegjJsrEgUWb3nXDioHLW29+cnrv0L2lHU88mDthIDFa9FnEL53 fqonwto2Sh11Jz/LvTGkcGhJscArkYB8ZozPhj4UOHwCnTkFbjayjDUQCI0320G90p VYnhp5oM4CRIgFBek0dLF0jymSmrSlShrKCfFH4zuKsAOkYZOoplXYs2211/sudjeq f+L9dC9BEdwCQ== From: Andreas Hindborg Date: Fri, 31 Jan 2025 14:30:10 +0100 Subject: [PATCH 3/4] rust: configfs: introduce rust support for configfs Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250131-configfs-v1-3-87947611401c@kernel.org> References: <20250131-configfs-v1-0-87947611401c@kernel.org> In-Reply-To: <20250131-configfs-v1-0-87947611401c@kernel.org> To: Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Joel Becker , Christoph Hellwig Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=40827; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=5kUbYYl6O9tWK5RDQX4Cl2uMDL6vlLePNSLAY9RUwXY=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnnNCFVyIRYsi0WkvnCP4abr6uEy5FxwSKemn7c ouTjkk7eVOJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ5zQhQAKCRDhuBo+eShj d3U5EACsttUzgUB/sHQWHcslihgE6sFnpbEAkbq0Z/biKpSu4FmnJ/OPGU+eI7iNehJxq7rt8hD c/oJ+Z5Ry3Xh9qJI5XmLBVOuQD17E7Bh3QIjRpksTBTXFjE62A7aDt17/mjIkbAZICgPvq5C1l+ pibdqKbpo/sal77uxnvYegfpJfaO2W++ihxl1x0qmYToLEy6MOUi61ALV5FA+UuNeXILbREJHpf zSCpURF9w+3uz8MMB8fibIek1gst3sfsMApSXb6sZE//M4NGPdtMwiqC/p/ftAEXYljsFIPJM1M PIBXNx8tRBKEIh1cQZ0BG95A+k9jVP9qX73UEAJOo94S6/0kEGOm75TmSBw/jM9zKssApMeMez3 pQeE5iBEGRFt1FSKDE1Iqkb0/Wuzmv3SAWSGPPJo5xzWNgqQU8NGu4zMiGIZhwpD7vRGZ3uKf/B Z1hoRGj+rpvLO048IKt0i9eLb5smawBkAss1M2qrueVeo0x2AIKSBfnexlaty5M1nOjhpeLTf3d XkQUrbHE1ekXCdLYcWP7inm6ZTShz9K6EUM7Un0lTJQBK1JHfRziRYDEzMP9NsMe42VCb43x5q5 wArA0lqRypDJTPYafVMxFy9ljCylVTr4Og+UB9yLQi11cD2jnQjkERHT7GfzzPYhNIh/1PKUuw/ kaRRXWszJrlLfqw== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 This patch adds a rust API for configfs, thus allowing rust modules to use configfs for configuration. The implementation is a shim on top of the C configfs implementation allowing safe use of the C infrastructure from rust. The patch enables the `const_mut_refs` feature on compilers before rustc 1.83. The feature was stabilized in rustc 1.83 and is not required to be explicitly enabled on later versions. Signed-off-by: Andreas Hindborg --- This patch is a direct dependency for `rnull`, the rust null block driver. --- init/Kconfig | 3 + rust/bindings/bindings_helper.h | 1 + rust/kernel/configfs.rs | 811 ++++++++++++++++++++++++++++++++++++= ++++ rust/kernel/lib.rs | 3 + samples/rust/Kconfig | 11 + samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 ++++++++++ 7 files changed, 1022 insertions(+) diff --git a/init/Kconfig b/init/Kconfig index 868ffa922b2c2852bdff67a0a17cf49277d39d40..c54a413de532a7d8616e994b4f1= 911972acc5c79 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -132,6 +132,9 @@ config CC_HAS_COUNTED_BY config RUSTC_HAS_COERCE_POINTEE def_bool RUSTC_VERSION >=3D 108400 =20 +config RUSTC_HAS_CONST_MUT_REFS_MERGED + def_bool RUSTC_VERSION >=3D 108300 + config PAHOLE_VERSION int default $(shell,$(srctree)/scripts/pahole-version.sh $(PAHOLE)) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 5c4dfe22f41a5a106330e8c43ffbd342c69c4e0b..bb3bf08a1cd7f34ad517372b78a= fcb9a680689da 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/configfs.rs b/rust/kernel/configfs.rs new file mode 100644 index 0000000000000000000000000000000000000000..7680461870efab1ef5604577015= 8cf3fd4e45e14 --- /dev/null +++ b/rust/kernel/configfs.rs @@ -0,0 +1,811 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! `configfs` interface. +//! +//! `configfs` is an in-memory pseudo file system for configuration of ker= nel +//! modules. Please see the [C documentation] for details and intended use= of +//! `configfs`. +//! +//! This module does not support the following `configfs` features: +//! +//! - Items. All group children are groups. +//! - Symlink support. +//! - `disconnect_notify` hook. +//! - Item `release` hook +//! - Default groups. +//! +//! See the [rust_configfs.rs] sample for a full example use of this modul= e. +//! +//! C header: [`include/linux/configfs.h`](srctree/include/linux/configfs.= h) +//! +//! [C documentation]: srctree/Documentation/filesystems/configfs.rst +//! [rust_configfs.rs]: srctree/samples/rust/rust_configfs.rs + +use crate::container_of; +use crate::page::PAGE_SIZE; +use crate::types::ForeignOwnable; +use crate::{prelude::*, types::Opaque}; +use core::cell::UnsafeCell; +use core::marker::PhantomData; +use core::ptr::addr_of; +use core::ptr::addr_of_mut; +use kernel::alloc::flags; +use kernel::str::CString; + +/// A `configfs` subsystem. +/// +/// This is the top level entrypoint for a `configfs` hierarchy. Embed a f= ield +/// of this type into a struct and implement [`HasSubsystem`] for the stru= ct +/// with the [`kernel::impl_has_subsystem`] macro. Instantiate the subsyst= em with +/// [`Subsystem::register`]. +/// +/// A [`Subsystem`] is also a [`Group`], and implementing [`HasSubsystem`]= for a +/// type will automatically implement [`HasGroup`] for the type. +#[pin_data(PinnedDrop)] +pub struct Subsystem { + #[pin] + subsystem: Opaque, + #[pin] + data: DATA, +} + +// SAFETY: We do not provide any operations on `Subsystem`. +unsafe impl Sync for Subsystem {} + +// SAFETY: Ownership of `Subsystem` can safely be transferred to other thr= eads. +unsafe impl Send for Subsystem {} + +impl Subsystem { + /// Create an initializer for a [`Subsystem`]. + /// + /// The subsystem will appear in configfs as a directory name given by + /// `name`. The attributes available in directory are specified by + /// `item_type`. + pub fn new( + name: &'static CStr, + item_type: &'static ItemType, + data: impl PinInit, + ) -> impl PinInit { + try_pin_init!(Self { + subsystem <- kernel::init::zeroed().chain( + |place: &mut Opaque| { + // SAFETY: All of `place` is valid for write. + unsafe { + addr_of_mut!((*place.get()).su_group.cg_item.ci_na= me ) + .write(name.as_ptr().cast_mut().cast()) + }; + // SAFETY: All of `place` is valid for write. + unsafe { + addr_of_mut!((*place.get()).su_group.cg_item.ci_ty= pe) + .write(item_type.as_ptr()) + }; + // SAFETY: We initialized the required fields of `plac= e.group` above. + unsafe { bindings::config_group_init(&mut (*place.get(= )).su_group) }; + // SAFETY: `place.su_mutex` is valid for use as a mute= x. + unsafe { bindings::__mutex_init( + &mut (*place.get()).su_mutex, + kernel::optional_name!().as_char_ptr(), + kernel::static_lock_class!().as_ptr()) + } + Ok(()) + }), + data <- data, + }) + .pin_chain(|this| { + crate::error::to_result( + // SAFETY: We initialized `this.subsystem` according to C = API contract above. + unsafe { bindings::configfs_register_subsystem(this.subsys= tem.get()) }, + ) + }) + } +} + +#[pinned_drop] +impl PinnedDrop for Subsystem { + fn drop(self: Pin<&mut Self>) { + // SAFETY: We registered `self.subsystem` in the initializer retur= ned by `Self::new`. + unsafe { bindings::configfs_unregister_subsystem(self.subsystem.ge= t()) }; + } +} + +/// Trait that allows offset calculations for structs that embed a `bindin= gs::config_group`. +/// +/// # Safety +/// +/// - Implementers of this trait must embed a `bindings::config_group`. +/// - Methods must be implemented according to method documentation. +unsafe trait HasGroup { + /// Return the address of the `bindings::config_group` embedded in `Se= lf`. + /// + /// # Safety + /// + /// - `this` must be a valid allocation of at least the size of `Self`. + unsafe fn group(this: *const Self) -> *const bindings::config_group; + + /// Return the address of the `Self` that `group` is embedded in. + /// + /// # Safety + /// + /// - `group` must point to the `bindings::config_group` that is embed= ded in + /// `Self`. + unsafe fn container_of(group: *const bindings::config_group) -> *const= Self; +} + +// SAFETY: `Subsystem` embeds a field of type `bindings::config_grou= p` +// within the `subsystem` field. +unsafe impl HasGroup for Subsystem { + unsafe fn group(this: *const Self) -> *const bindings::config_group { + // SAFETY: By impl and function safety requirement this projection= is in bounds. + unsafe { addr_of!((*(*this).subsystem.get()).su_group) } + } + + unsafe fn container_of(group: *const bindings::config_group) -> *const= Self { + // SAFETY: By impl and function safety requirement this projection= is in bounds. + let c_subsys_ptr =3D unsafe { container_of!(group, bindings::confi= gfs_subsystem, su_group) }; + let opaque_ptr =3D c_subsys_ptr.cast::>(); + // SAFETY: By impl and function safety requirement, `opaque_ptr` a= nd the + // pointer it returns, are within the same allocation. + unsafe { container_of!(opaque_ptr, Subsystem, subsystem) } + } +} + +/// A `configfs` group. +/// +/// To add a subgroup to `configfs`, embed a field of this type into a str= uct +/// and use it for the `CHLD` generic of [`GroupOperations`]. +#[pin_data] +pub struct Group { + #[pin] + group: Opaque, + #[pin] + data: DATA, +} + +impl Group { + /// Create an initializer for a new group. + /// + /// When instantiated, the group will appear as a directory with the n= ame + /// given by `name` and it will contain attributes specified by `item_= type`. + pub fn new( + name: CString, + item_type: &'static ItemType, + data: impl PinInit, + ) -> impl PinInit { + try_pin_init!(Self { + group <- kernel::init::zeroed().chain(|v: &mut Opaque| { + let place =3D v.get(); + let name =3D name.as_bytes_with_nul().as_ptr(); + // SAFETY: It is safe to initialize a group once it has be= en zeroed. + unsafe { + bindings::config_group_init_type_name(place, name as _= , item_type.as_ptr()) + }; + Ok(()) + }), + data <- data, + }) + } +} + +// SAFETY: `Group` embeds a field of type `bindings::config_group` +// within the `group` field. +unsafe impl HasGroup for Group { + unsafe fn group(this: *const Self) -> *const bindings::config_group { + Opaque::raw_get( + // SAFETY: By impl and function safety requirements this field + // projection is within bounds of the allocation. + unsafe { addr_of!((*this).group) }, + ) + } + + unsafe fn container_of(group: *const bindings::config_group) -> *const= Self { + let opaque_ptr =3D group.cast::>(); + // SAFETY: By impl and function safety requirement, `opaque_ptr` a= nd + // pointer it returns will be in the same allocation. + unsafe { container_of!(opaque_ptr, Self, group) } + } +} + +struct GroupOperationsVTable(PhantomData<(PAR, CHL= D, CPTR, PCPTR)>) +where + PAR: GroupOperations, + CPTR: InPlaceInit, PinnedSelf =3D PCPTR>, + PCPTR: ForeignOwnable>; + +/// # Safety +/// +/// `this` must be a valid pointer. +/// +/// If `this` does not represent the root group of a `configfs` subsystem, +/// `this` must be a pointer to a `bindings::config_group` embedded in a +/// `Group`. +/// +/// Otherwise, `this` must be a pointer to a `bindings::config_group` that +/// is embedded in a `bindings::configfs_subsystem` that is embedded in a +/// `Subsystem`. +unsafe fn get_group_data<'a, PAR>(this: *mut bindings::config_group) -> &'= a PAR { + // SAFETY: `this` is a valid pointer. + let is_root =3D unsafe { (*this).cg_subsys.is_null() }; + + if !is_root { + // SAFETY: By C API contact, `this` is a pointer to a + // `bindings::config_group` that we passed as a return value in fr= om + // `make_group`. Such a pointer is embedded within a `Group`. + unsafe { &(*Group::::container_of(this)).data } + } else { + // SAFETY: By C API contract, `this` is a pointer to the + // `bindings::config_group` field within a `Subsystem`. + unsafe { &(*Subsystem::container_of(this)).data } + } +} + +impl GroupOperationsVTable +where + PAR: GroupOperations, + CPTR: InPlaceInit, PinnedSelf =3D PCPTR>, + PCPTR: ForeignOwnable>, +{ + /// # Safety + /// + /// `this` must be a valid pointer. + /// + /// If `this` does not represent the root group of a `configfs` subsys= tem, + /// `this` must be a pointer to a `bindings::config_group` embedded in= a + /// `Group`. + /// + /// Otherwise, `this` must be a pointer to a `bindings::config_group` = that + /// is embedded in a `bindings::configfs_subsystem` that is embedded i= n a + /// `Subsystem`. + /// + /// `name` must point to a null terminated string. + unsafe extern "C" fn make_group( + this: *mut bindings::config_group, + name: *const kernel::ffi::c_char, + ) -> *mut bindings::config_group { + // SAFETY: By function safety requirements of this function, this = call + // is safe. + let parent_data =3D unsafe { get_group_data(this) }; + + let group_init =3D match PAR::make_group( + parent_data, + // SAFETY: By function safety requirements, name points to a n= ull + // terminated string. + unsafe { CStr::from_char_ptr(name) }, + ) { + Ok(init) =3D> init, + Err(e) =3D> return e.to_ptr(), + }; + + let child_group =3D CPTR::try_pin_init(group_init, flags::GFP_KERN= EL); + + match child_group { + Ok(child_group) =3D> { + let child_group_ptr =3D child_group.into_foreign(); + // SAFETY: We allocated the pointee of `child_ptr` above a= s a + // `Group`. + unsafe { Group::::group(child_group_ptr) }.cast_mut() + } + Err(e) =3D> e.to_ptr(), + } + } + + /// # Safety + /// + /// If `this` does not represent the root group of a `configfs` subsys= tem, + /// `this` must be a pointer to a `bindings::config_group` embedded in= a + /// `Group`. + /// + /// Otherwise, `this` must be a pointer to a `bindings::config_group` = that + /// is embedded in a `bindings::configfs_subsystem` that is embedded i= n a + /// `Subsystem`. + /// + /// `item` must point to a `bindings::config_item` within a + /// `bindings::config_group` within a `Group`. + unsafe extern "C" fn drop_item( + this: *mut bindings::config_group, + item: *mut bindings::config_item, + ) { + // SAFETY: By function safety requirements of this function, this = call + // is safe. + let parent_data =3D unsafe { get_group_data(this) }; + + // SAFETY: By function safety requirements, `item` is embedded in a + // `config_group`. + let c_child_group_ptr =3D + unsafe { kernel::container_of!(item, bindings::config_group, c= g_item) }; + // SAFETY: By function safety requirements, `c_child_group_ptr` is + // embedded within a `Group`. + let r_child_group_ptr =3D unsafe { Group::::container_of(c_c= hild_group_ptr) }; + + if PAR::HAS_DROP_ITEM { + PAR::drop_item( + parent_data, + // SAFETY: We called `into_foreign` to produce `r_child_gr= oup_ptr` in + // `make_group`. There are not other borrows of this point= er in existence. + unsafe { PCPTR::borrow(r_child_group_ptr.cast_mut()) }, + ); + } + + // SAFETY: By C API contract, `configfs` is not going to touch `it= em` + // again. + unsafe { bindings::config_item_put(item) }; + + // SAFETY: We called `into_foreign` on `r_chilc_group_ptr` in + // `make_group`. + let pin_child: PCPTR =3D unsafe { PCPTR::from_foreign(r_child_grou= p_ptr.cast_mut()) }; + drop(pin_child); + } + + const VTABLE: bindings::configfs_group_operations =3D bindings::config= fs_group_operations { + make_item: None, + make_group: Some(Self::make_group), + disconnect_notify: None, + drop_item: Some(Self::drop_item), + is_visible: None, + is_bin_visible: None, + }; +} + +/// Operations implemented by `configfs` groups that can create subgroups. +/// +/// Implement this trait on structs that embed a [`Subsystem`] or a [`Grou= p`]. +#[vtable] +pub trait GroupOperations { + /// The parent data object type. + /// + /// The implementer of this trait is this kind of data object. Shold b= e set + /// to `Self`. + type Parent; + + /// The child data object type. + /// + /// This group will create subgroups (subdirectories) backed by this k= ind of + /// object. + type Child; + + /// The type of the pointer used to point to [`Self::Child`]. + /// + /// This pointer type should support pinned in-place initialization. + type ChildPointer: InPlaceInit, PinnedSelf =3D Self= ::PinChildPointer>; + + /// The pinned version of the child pointer. + /// + /// This type must be convertible to a raw pointer according to [`Fore= ignOwnable`]. + type PinChildPointer: ForeignOwnable>; + + /// The kernel will call this method in response to `mkdir(2)` in the + /// directory representing `this`. + /// + /// To accept the request to create a group, implementations should + /// instantiate a `CHLD` and return a `CPTR` to it. To prevent creatio= n, + /// return a suitable error. + fn make_group( + this: &Self::Parent, + name: &CStr, + ) -> Result, Error>>; + + /// The kernel will call this method before the directory representing + /// `_child` is removed from `configfs`. + /// + /// Implementations can use this method to do house keeping before + /// `configfs` drops its reference to `CHLD`. + fn drop_item( + _this: &Self::Parent, + _child: ::Borrowed<'_>, + ) { + kernel::build_error!(kernel::error::VTABLE_DEFAULT_ERROR) + } +} + +/// A `configfs` attribute. +/// +/// An attribute appear as a file in configfs, inside a folder that repres= ent +/// the group that the attribute belongs to. +#[repr(transparent)] +pub struct Attribute { + attribute: Opaque, + _p: PhantomData<(AO, DATA)>, +} + +// SAFETY: We do not provide any operations on `Attribute`. +unsafe impl Sync for Attribute {} + +// SAFETY: Ownership of `Attribute` can safely be transferred to other thr= eads. +unsafe impl Send for Attribute {} + +impl Attribute +where + AO: AttributeOperations, +{ + /// # Safety + /// + /// `item` must be embedded in a `bindings::config_group`. + /// + /// If `item` does not represent the root group of a `configfs` subsys= tem, + /// the group must be embedded in a `Group`. + /// + /// Otherwise, the group must be a embedded in a + /// `bindings::configfs_subsystem` that is embedded in a `Subsystem`. + /// + /// `page` must point to a writable buffer of size at least [`PAGE_SIZ= E`]. + unsafe extern "C" fn show( + item: *mut bindings::config_item, + page: *mut kernel::ffi::c_char, + ) -> isize { + let c_group: *mut bindings::config_group =3D + // SAFETY: By function safety requirements, `item` is embedded in a + // `config_group`. + unsafe { container_of!(item, bindings::config_group, cg_item) = }.cast_mut(); + + // SAFETY: The function safety requirements for this function sati= sfy + // the conditions for this call. + let data: &DATA =3D unsafe { get_group_data(c_group) }; + + // SAFETY: By function safety requirements, `page` is writable for= `PAGE_SIZE`. + let ret =3D AO::show(data, unsafe { &mut *(page as *mut [u8; PAGE_= SIZE]) }); + + match ret { + Ok(size) =3D> size as isize, + Err(err) =3D> err.to_errno() as isize, + } + } + + /// # Safety + /// + /// `item` must be embedded in a `bindings::config_group`. + /// + /// If `item` does not represent the root group of a `configfs` subsys= tem, + /// the group must be embedded in a `Group`. + /// + /// Otherwise, the group must be a embedded in a + /// `bindings::configfs_subsystem` that is embedded in a `Subsystem`. + /// + /// `page` must point to a readable buffer of size at least `size`. + unsafe extern "C" fn store( + item: *mut bindings::config_item, + page: *const kernel::ffi::c_char, + size: usize, + ) -> isize { + let c_group: *mut bindings::config_group =3D + // SAFETY: By function safety requirements, `item` is embedded in a + // `config_group`. + unsafe { container_of!(item, bindings::config_group, cg_item) = }.cast_mut(); + + // SAFETY: The function safety requirements for this function sati= sfy + // the conditions for this call. + let data: &DATA =3D unsafe { get_group_data(c_group) }; + + let ret =3D AO::store( + data, + // SAFETY: By function safety requirements, `page` is readable + // for at least `size`. + unsafe { core::slice::from_raw_parts(page.cast(), size) }, + ); + + match ret { + Ok(()) =3D> size as isize, + Err(err) =3D> err.to_errno() as isize, + } + } + + /// Create a new attribute. + /// + /// The attribute will appear as a file with name given by `name`. + pub const fn new(name: &'static CStr) -> Self { + Self { + attribute: Opaque::new(bindings::configfs_attribute { + ca_name: name as *const _ as _, + ca_owner: core::ptr::null_mut(), + ca_mode: 0o660, + show: Some(Self::show), + store: if AO::HAS_STORE { + Some(Self::store) + } else { + None + }, + }), + _p: PhantomData, + } + } +} + +/// Operations supported by an attribute. +/// +/// Implement this trait on type and pass that type as generic parameter w= hen +/// creating an [`Attribute`]. The type carrying the implementation serve = no +/// purpose other than specifying the attribute operations. +#[vtable] +pub trait AttributeOperations { + /// The type of the object that contains the field that is backing the + /// attribute for this operation. + type Data; + + /// This function is called by the kernel to read the value of an attr= ibute. + /// + /// Implementations should write the rendering of the attribute to `pa= ge` + /// and return the number of bytes written. + fn show(data: &Self::Data, page: &mut [u8; PAGE_SIZE]) -> Result; + + /// This function is called by the kernel to update the value of an at= tribute. + /// + /// Implementations should parse the value from `page` and update inte= rnal + /// state to reflect the parsed value. Partial writes are not supporte= d and + /// implementations should expect the full page to arrive in one write + /// operation. + fn store(_data: &Self::Data, _page: &[u8]) -> Result { + kernel::build_error!(kernel::error::VTABLE_DEFAULT_ERROR) + } +} + +/// A list of attributes. +/// +/// This type is used to construct a new [`ItemType`]. It represents a lis= t of +/// [`Attribute`] that will appear in the directory representing a [`Group= `]. +/// Users should not directly instantiate this type, rather they should us= e the +/// [`kernel::configfs_attrs`] macro to declare a static set of attributes= for a +/// group. +#[repr(transparent)] +pub struct AttributeList( + UnsafeCell<[*mut kernel::ffi::c_void; N]>, + PhantomData, +); + +// SAFETY: Ownership of `AttributeList` can safely be transferred to other= threads. +unsafe impl Send for AttributeList {} + +// SAFETY: We do not provide any operations on `AttributeList` that need s= ynchronization. +unsafe impl Sync for AttributeList {} + +impl AttributeList { + #[doc(hidden)] + /// # Safety + /// + /// This function can only be called by expanding the `configfs_attrs` + /// macro. + pub const unsafe fn new() -> Self { + Self(UnsafeCell::new([core::ptr::null_mut(); N]), PhantomData) + } + + #[doc(hidden)] + /// # Safety + /// + /// This function can only be called by expanding the `configfs_attrs` + /// macro. + pub const unsafe fn add< + const I: usize, + const ID: u64, + O: AttributeOperations, + >( + &'static self, + attribute: &'static Attribute, + ) { + if I >=3D N - 1 { + kernel::build_error!("Invalid attribute index"); + } + + // SAFETY: This function is only called through `configfs_attrs`. = This + // ensures that we are evaluating the function in const context wh= en + // initializing a static. As such, the reference created below wil= l be + // exclusive. + unsafe { + (&mut *self.0.get())[I] =3D (attribute as *const Attribute) + .cast_mut() + .cast() + }; + } +} + +/// A representation of the attributes that will appear in a [`Group`]. +/// +/// Users should not directly instantiate objects of this type. Rather, th= ey +/// should use the [`kernel::configfs_attrs`] macro to statically declare = the +/// shape of a [`Group`]. +#[pin_data] +pub struct ItemType { + #[pin] + item_type: Opaque, + _p: PhantomData, +} + +// SAFETY: We do not provide any operations on `ItemType` that need synchr= onization. +unsafe impl Sync for ItemType {} + +// SAFETY: Ownership of `ItemType` can safely be transferred to other thre= ads. +unsafe impl Send for ItemType {} + +impl ItemType { + #[doc(hidden)] + pub const fn new_with_child_ctor( + owner: &'static ThisModule, + attributes: &'static AttributeList, + ) -> Self + where + PAR: GroupOperations, + CPTR: InPlaceInit, PinnedSelf =3D PCPTR>, + PCPTR: ForeignOwnable>, + { + Self { + item_type: Opaque::new(bindings::config_item_type { + ct_owner: owner.as_ptr(), + ct_group_ops: (&GroupOperationsVTable::::VTABLE as *const _) + as *mut _, + ct_item_ops: core::ptr::null_mut(), + ct_attrs: attributes as *const _ as _, + ct_bin_attrs: core::ptr::null_mut(), + }), + _p: PhantomData, + } + } + + #[doc(hidden)] + pub const fn new( + owner: &'static ThisModule, + attributes: &'static AttributeList, + ) -> Self { + Self { + item_type: Opaque::new(bindings::config_item_type { + ct_owner: owner.as_ptr(), + ct_group_ops: core::ptr::null_mut(), + ct_item_ops: core::ptr::null_mut(), + ct_attrs: attributes as *const _ as _, + ct_bin_attrs: core::ptr::null_mut(), + }), + _p: PhantomData, + } + } +} + +impl ItemType { + fn as_ptr(&self) -> *const bindings::config_item_type { + self.item_type.get() + } +} + +/// Define a list of configfs attributes statically. +#[macro_export] +macro_rules! configfs_attrs { + ( + container: $container:ty, + attributes: [ + $($name:ident: $attr:literal,)* + ], + ) =3D> { + $crate::configfs_attrs!( + count: + @container($container), + @child(), + @no_child(x), + @attrs($($name $attr)*), + @eat($($name $attr,)*), + @assign(), + @cnt(0usize), + ) + }; + ( + container: $container:ty, + child: $child:ty, + pointer: $pointer:ty, + pinned: $pinned:ty, + attributes: [ + $($name:ident: $attr:literal,)* + ], + ) =3D> { + $crate::configfs_attrs!( + count: + @container($container), + @child($child, $pointer, $pinned), + @no_child(), + @attrs($($name $attr)*), + @eat($($name $attr,)*), + @assign(), + @cnt(0usize), + ) + }; + (count: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned:ty)?), + @no_child($($no_child:ident)?), + @attrs($($aname:ident $aattr:literal)*), + @eat($name:ident $attr:literal, $($rname:ident $rattr:literal,)*), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) =3D> { + $crate::configfs_attrs!( + count: + @container($container), + @child($($child, $pointer, $pinned)?), + @no_child($($no_child)?), + @attrs($($aname $aattr)*), + @eat($($rname $rattr,)*), + @assign($($assign)* { + const N: usize =3D $cnt; + // SAFETY: We are expanding `configfs_attrs`. + unsafe { + $crate::macros::paste!( [< $container:upper _ATTRS >]) + .add::( + & $crate::macros::paste!( [< $container:upper = _ $name:upper _ATTR >]) + ) + }; + }), + @cnt(1usize + $cnt), + ) + }; + (count: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned:ty)?), + @no_child($($no_child:ident)?), + @attrs($($aname:ident $aattr:literal)*), + @eat(), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) =3D> + { + $crate::configfs_attrs!(final: + @container($container), + @child($($child, $pointer, $pinned)?), + @no_child($($no_child)?), + @attrs($($aname $aattr)*), + @assign($($assign)*), + @cnt($cnt), + ) + }; + (final: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned:ty)?), + @no_child($($no_child:ident)?), + @attrs($($name:ident $attr:literal)*), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) =3D> + { + { + $( + $crate::macros::paste!{ + // SAFETY: We are expanding `configfs_attrs`. + static [< $container:upper _ $name:upper _ATTR >]: + $crate::configfs::Attribute<$attr, $container, $cont= ainer> =3D + unsafe { + $crate::configfs::Attribute::new(c_str!(::core= ::stringify!($name))) + }; + } + )* + + + const N: usize =3D $cnt + 1usize; + $crate::macros::paste!{ + // SAFETY: We are expanding `configfs_attrs`. + static [< $container:upper _ATTRS >]: + $crate::configfs::AttributeList =3D + unsafe { $crate::configfs::AttributeList::new() }; + } + + $($assign)* + + $( + $crate::macros::paste!{ + const [<$no_child:upper>]: bool =3D true; + }; + + $crate::macros::paste!{ + static [< $container:upper _TPE >] : $crate::configfs:= :ItemType<$container> =3D + $crate::configfs::ItemType::new::( + &THIS_MODULE, &[<$ container:upper _ATTRS >] + ); + } + )? + + $( + $crate::macros::paste!{ + static [< $container:upper _TPE >]: + $crate::configfs::ItemType<$container> =3D + $crate::configfs::ItemType::new_with_child_ctor:: + ( + &THIS_MODULE, &[<$ container:upper _ATTRS >] + ); + } + )? + + &$crate::macros::paste!( [< $container:upper _TPE >] ) + } + }; + +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 545d1170ee6358e185b48ce10493fc61c646155c..91f05cf54db0ea83f27837c4c3a= 80cf48c5158da 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -19,6 +19,7 @@ #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(unsize))] #![feature(inline_const)] #![feature(lint_reasons)] +#![cfg_attr(not(CONFIG_RUSTC_HAS_CONST_MUT_REFS_MERGED), feature(const_mut= _refs))] =20 // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling. @@ -35,6 +36,8 @@ pub mod block; #[doc(hidden)] pub mod build_assert; +#[cfg(CONFIG_CONFIGFS_FS)] +pub mod configfs; pub mod cred; pub mod device; pub mod error; diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index b0f74a81c8f9ad24c9dc1ca057f83531156084aa..ba540a167ebf49853f377f09374= bba0c6facee8c 100644 --- a/samples/rust/Kconfig +++ b/samples/rust/Kconfig @@ -30,6 +30,17 @@ config SAMPLE_RUST_PRINT =20 If unsure, say N. =20 +config SAMPLE_RUST_CONFIGFS + tristate "Configfs sample" + depends on CONFIGFS_FS + help + This option builds the Rust configfs sample. + + To compile this as a module, choose M here: + the module will be called rust_configfs. + + If unsure, say N. + config SAMPLE_RUST_HOSTPROGS bool "Host programs" help diff --git a/samples/rust/Makefile b/samples/rust/Makefile index c1a5c16553955b1cfc59d77e85e1d60b06242967..2b2621046f10609321b76cad3c7= f327bafc802c0 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -3,6 +3,7 @@ ccflags-y +=3D -I$(src) # needed for trace events =20 obj-$(CONFIG_SAMPLE_RUST_MINIMAL) +=3D rust_minimal.o obj-$(CONFIG_SAMPLE_RUST_PRINT) +=3D rust_print.o +obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) +=3D rust_configfs.o =20 rust_print-y :=3D rust_print_main.o rust_print_events.o =20 diff --git a/samples/rust/rust_configfs.rs b/samples/rust/rust_configfs.rs new file mode 100644 index 0000000000000000000000000000000000000000..a77fe292d1b6c775210abb31d70= 6519de2ab125a --- /dev/null +++ b/samples/rust/rust_configfs.rs @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust configfs sample. + +use kernel::alloc::flags; +use kernel::c_str; +use kernel::configfs; +use kernel::configfs_attrs; +use kernel::new_mutex; +use kernel::prelude::*; +use kernel::sync::Arc; +use kernel::sync::Mutex; + +module! { + type: RustConfigfs, + name: "rust_configfs", + author: "Rust for Linux Contributors", + description: "Rust configfs sample", + license: "GPL", +} + +#[pin_data] +struct RustConfigfs { + #[pin] + config: configfs::Subsystem, +} + +#[pin_data] +struct Configuration { + message: &'static CStr, + #[pin] + bar: Mutex<(KBox<[u8; 4096]>, usize)>, +} + +impl Configuration { + fn new() -> impl PinInit { + try_pin_init!(Self { + message: c_str!("Hello World\n"), + bar <- new_mutex!((KBox::new([0;4096], flags::GFP_KERNEL)?,0)), + }) + } +} + +impl kernel::InPlaceModule for RustConfigfs { + fn init(_module: &'static ThisModule) -> impl PinInit { + pr_info!("Rust configfs sample (init)\n"); + + let item_type =3D configfs_attrs! { + container: Configuration, + child: Child, + pointer: Arc>, + pinned: Arc>, + attributes: [ + message: 0, + bar: 1, + ], + }; + + try_pin_init!(Self { + config <- configfs::Subsystem::new( + kernel::c_str!("rust_configfs"), item_type, Configuration:= :new() + ), + }) + } +} + +#[vtable] +impl configfs::GroupOperations for Configuration { + type Parent =3D Self; + type Child =3D Child; + type ChildPointer =3D Arc>; + type PinChildPointer =3D Arc>; + + fn make_group( + _this: &Self, + name: &CStr, + ) -> Result, Error>> { + let tpe =3D configfs_attrs! { + container: Child, + child: GrandChild, + pointer: Arc>, + pinned: Arc>, + attributes: [ + baz: 0, + ], + }; + + Ok(configfs::Group::new(name.try_into()?, tpe, Child::new())) + } +} + +#[vtable] +impl configfs::AttributeOperations<0> for Configuration { + type Data =3D Configuration; + + fn show(container: &Configuration, page: &mut [u8; 4096]) -> Result { + pr_info!("Show message\n"); + let data =3D container.message; + page[0..data.len()].copy_from_slice(data); + Ok(data.len()) + } +} + +#[vtable] +impl configfs::AttributeOperations<1> for Configuration { + type Data =3D Configuration; + + fn show(container: &Configuration, page: &mut [u8; 4096]) -> Result { + pr_info!("Show bar\n"); + let guard =3D container.bar.lock(); + let data =3D guard.0.as_slice(); + let len =3D guard.1; + page[0..len].copy_from_slice(&data[0..len]); + Ok(len) + } + + fn store(container: &Configuration, page: &[u8]) -> Result { + pr_info!("Store bar\n"); + let mut guard =3D container.bar.lock(); + guard.0[0..page.len()].copy_from_slice(page); + guard.1 =3D page.len(); + Ok(()) + } +} + +#[pin_data] +struct Child {} + +impl Child { + fn new() -> impl PinInit { + try_pin_init!(Self {}) + } +} + +#[vtable] +impl configfs::GroupOperations for Child { + type Parent =3D Self; + type Child =3D GrandChild; + type ChildPointer =3D Arc>; + type PinChildPointer =3D Arc>; + + fn make_group( + _this: &Self, + name: &CStr, + ) -> Result, Error>> { + let tpe =3D configfs_attrs! { + container: GrandChild, + attributes: [ + gc: 0, + ], + }; + + Ok(configfs::Group::new( + name.try_into()?, + tpe, + GrandChild::new(), + )) + } +} + +#[vtable] +impl configfs::AttributeOperations<0> for Child { + type Data =3D Child; + + fn show(_container: &Child, page: &mut [u8; 4096]) -> Result { + pr_info!("Show baz\n"); + let data =3D c"Hello Baz\n".to_bytes(); + page[0..data.len()].copy_from_slice(data); + Ok(data.len()) + } +} + +#[pin_data] +struct GrandChild {} + +impl GrandChild { + fn new() -> impl PinInit { + try_pin_init!(Self {}) + } +} + +#[vtable] +impl configfs::AttributeOperations<0> for GrandChild { + type Data =3D GrandChild; + + fn show(_container: &GrandChild, page: &mut [u8; 4096]) -> Result { + pr_info!("Show baz\n"); + let data =3D c"Hello GC\n".to_bytes(); + page[0..data.len()].copy_from_slice(data); + Ok(data.len()) + } +} --=20 2.47.0 From nobody Mon Feb 9 08:54:34 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 507FE4A07; Fri, 31 Jan 2025 13:32:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738330327; cv=none; b=LK6oVEi+DzTvi6sWRPjgh1ys+7NV0Y113AdNoYjp6+n0Z27LtgQCwiiwzR1BRQHTsP6ts0KYTlVc4i8eXlhhzFC/CsMfDYPOq8HaMXR86f/+1JquJLrhxdhkWaX7C4aslqLLK0PkgxDm3DQPHjClJ5o/SjnmcR4idJb9nwWXcEQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1738330327; c=relaxed/simple; bh=jYdCxBRQsq28Ql1ctvq0LlUY6kmD+tpiLL9GHuxgW/o=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=A4qMkJYbT3yAeqM+XpxBoSX9+HgmrBW1mxooWuy4KVwprxaXnHfX65xjjnR+s/YZpKtxs0t/PPFh9c8da8mMccvpvmrtTdOBBFVb2/7891ROtFaqv+LdsTgaK89zt/nlURZDftasfeIT1KQ3KT/70e+rONWPllNtYac0R0NvCWc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=m6dGyb1s; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="m6dGyb1s" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9865AC4CED1; Fri, 31 Jan 2025 13:32:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1738330326; bh=jYdCxBRQsq28Ql1ctvq0LlUY6kmD+tpiLL9GHuxgW/o=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=m6dGyb1sZ7PV3ZhtIBX1syFOzkQ/L5tl0S5Bhrt3JRiMqGtbty8Rz5o79gPuMfkdJ ulHFMHVR5x5DN9pki9oB5ohklVooRvQXG2pWz/j9vN/8KohYDXF1paTZhbfE6MsdWe dM9qxoGyq4/sFfwhjDBug1HiWlvMFGhrmpqsyFRwexQQxz3dpXVsT3+MNkwDr4EMnV osUgVtPIVZsc+F1Lyj+K3YwDhO7zMAwAkiK4+Al/4moXGwRlAYMA+TJdlKZyK6wnu6 CfpLrDeJGCkhFfg7baSmEacO6Fw0HvPdOB/rOmrOedJpSZczRmcPo5pq5OC6bEq6I9 hdADI6KUBoYyw== From: Andreas Hindborg Date: Fri, 31 Jan 2025 14:30:11 +0100 Subject: [PATCH 4/4] MAINTAINERS: add entry for configfs Rust abstractions Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250131-configfs-v1-4-87947611401c@kernel.org> References: <20250131-configfs-v1-0-87947611401c@kernel.org> In-Reply-To: <20250131-configfs-v1-0-87947611401c@kernel.org> To: Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Joel Becker , Christoph Hellwig Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=761; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=jYdCxBRQsq28Ql1ctvq0LlUY6kmD+tpiLL9GHuxgW/o=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnnNCGpYHw+GfgBcO6nZ+V1Nufvqqqf6BLWBAia MXVfOM1nzOJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ5zQhgAKCRDhuBo+eShj d7mFD/0VGxUVtVOepbPCnRO8F9U2VR1DBipgbSYawB8Ul2UwQH5gKvp8l+LqOgzgC0xmkDXq7Y3 vJ0yqOV+q5rIvK0i+jSX+rgKA0R4JHKGX22X54VZNrjq3zswoD2e2uPdbwh7J4EMc+JqItMXuA5 oC6ZPouKhNVUoO8IUQs4KVcRDEtCgjdMMDXut2rI9cFNOrQX9K7Bk3eA5s8bwz5AisChW8qui29 iuh7sflloe1w+EYWTGBw59bBwV9p/F1QVIEMhR5cEhf1zRHNcKKSLLTQq077UcLhR3fv+CrpONo 5GmtOBsz6R3VlVak0f+FNPGbXN8uYtRoRaDVwJcEFVmXlmxwsjjpciIQxMwHKYXVBzLBHp9ZPUf N71P5joS2Degs5l/2g/0BimpChBf5XKGcqtmVK7jm8PGv526V+UCkiZ94FeuCmwWW1zvNIDoFka 1a2HeTZW4BDu5Hyb7+hcknu8nQ5SMRzoU5LNSVOEkFYTOGy/aUYcNIzE5LY6FDA4OeSgwnqXSM9 5rfDlsNWoiI4ejxqWinlRYTCl3mZzij3al/WBumUrAzd+t3VqMLX1ePF/FwRxaXihUREFpQnpGj EqHe5vZdxPIVb7Re9SQvPaKzy0DTO8H4/zYf1u4c5bFyA1fyyJWeSd4sMprEdrM2WXYKUvQOons dXvjHYVlcTXCyWw== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Update MAINTAINERS with entry for Rust configfs abstractions. Signed-off-by: Andreas Hindborg --- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index baf0eeb9a35548fd3a4c5a39096dbfe17b967cdb..7e3d238ef21cabb7608b004d0d8= 07c801446a18f 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5806,6 +5806,13 @@ F: fs/configfs/ F: include/linux/configfs.h F: samples/configfs/ =20 +CONFIGFS [RUST] +M: Andreas Hindborg +L: rust-for-linux@vger.kernel.org +S: Supported +F: rust/kernel/configfs.rs +F: samples/rust/rust_configfs.rs + CONGATEC BOARD CONTROLLER MFD DRIVER M: Thomas Richard S: Maintained --=20 2.47.0