From nobody Sun Dec 14 06:15:48 2025 Received: from mail-pl1-f202.google.com (mail-pl1-f202.google.com [209.85.214.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1549F1F5433 for ; Mon, 5 May 2025 23:51:38 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746489101; cv=none; b=VZdasZdenl8N6Y0EFXXz2gfvQfJN0a3NnkFfA8yOqgtflW84zxPOnDh0fEyJ4ewY9GNmvjyd1PBiPNQvfX0YJ5mDTcyjeDtm3/5PoDbpqxm2LVUWRVK2UJq0TDC4vlLmQ6RXFr+ErI2HkCFvzq36039nkZfzChvwVqiyFeVL0sI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746489101; c=relaxed/simple; bh=Eb3lt2LvIAa6seENz5ciTjZBBIzUMwkJVD419FJR0/k=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=qfacrI3lzQbpiFlU12jm3oswguuNYVy/aaeGApADfgLcwgUvPNfCap4BKi2RFziAPv7lDhx/toVmsx5WhoKkFBVXWW9CBrhOKaiLg10zj6FgjkSCvSl3YnUWs7CJjGF1Yq65gTueVplQywNXCUUkirayOykFE2RuNv8yjB9Uves= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=ey2cf6KM; arc=none smtp.client-ip=209.85.214.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="ey2cf6KM" Received: by mail-pl1-f202.google.com with SMTP id d9443c01a7336-2254e0b4b85so46927355ad.0 for ; Mon, 05 May 2025 16:51:38 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746489098; x=1747093898; 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=6fPGr+WFW2LWEagGWid0GDx4A/neFED+/hSTuUt40rs=; b=ey2cf6KMYTU9m1TeTIa3la9+bAyXbyXM3l3dh0HPbXCRnfVXAsyRQxYpma1dnsohzB 2Li6XzrpOtFfv30kX0JGkFElEJhsif0UvtlKDhdpB3rRN2sCe31by2TD+5tV5I6zV/4n kYMizLpYf9CmzK8h0USPobkdmEWCSK/gEwsEUwGUKdbSPonJSTHVW2EMnAQaVwzIx6VM erIZyryrlvy8FD5vRh3tugzMFrUSjmw7z9//D1vhu3vqjFjC+PhXo8LFyqQbAfrror2R w2bOoQ9RP+HRGPWnrWq/OJgMHqWObM07ujkfICQ+oH8OgmaGst0cElvIL8PkLkVfdbwv 5RkQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746489098; x=1747093898; 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=6fPGr+WFW2LWEagGWid0GDx4A/neFED+/hSTuUt40rs=; b=oxT6KYvMAaU3iB/JtViHZ24N1EaMNBWkeLEBv6HtKF0k2qQKy4v5Q9n/2M97HWWRmM tqIaSS534lmvx8KBeBPUSzBuGu1DHfmoq2Ps42IMy36W356S5mA5q0HO5KtNgD9rB1PD N2nxOp8vR1CMLEbZv/QEimM/UxcCTVY+tW8uFUQpPF4RYopCY2oH4H+yocFk/elKrUCt WBRQYIxJXvOC3QOo+JBRWwonkbW2towY1HWtxX0gl4le64Ze2yqcbP89ffk4OvJFjec0 9885IKSaJ+O/jGRRIY4tzVaWcUlXcgoLnZVEVtjpy78zIP4z1t9h/Zlprty4RvLKHq1o YTlg== X-Gm-Message-State: AOJu0YzvRr4uhTYvCOswRAhxAruTxHK3ohXG09Hqy+oEV8E2pQKPVpuw EwZDpMjs6aI+2h69pAtgviNVUT7CTN2APKF9oX/hV1uqFWT2+YPBVK/jysnYhYdJvWKzGSPISFv /ktKgLg== X-Google-Smtp-Source: AGHT+IFigJKKKKjm1K5W2E01S3JsEY26jj1rJmi+XCK0W0m/bcH6kvD9XD1qlePnZV77bNRfaGKsLXGSuo3u X-Received: from pfhg23.prod.google.com ([2002:a62:e317:0:b0:73e:655:5bee]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a17:903:290:b0:220:ff82:1c60 with SMTP id d9443c01a7336-22e3280a6e2mr19726055ad.14.1746489098296; Mon, 05 May 2025 16:51:38 -0700 (PDT) Date: Mon, 05 May 2025 23:51:34 +0000 In-Reply-To: <20250505-debugfs-rust-v5-0-3e93ce7bb76e@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250505-debugfs-rust-v5-0-3e93ce7bb76e@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1746489094; l=6915; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=Eb3lt2LvIAa6seENz5ciTjZBBIzUMwkJVD419FJR0/k=; b=quWRvkW1Ex7bCk8S6MCaY7cWbf5BiM9t8ViG+nCebi7ZGPBsRB195nuaEt4me7CDFty8GvGgY Lnfid7D8CKzDF5KkF0gEokvDzlx0ABjyZaTkKEnfLiYPMAVph045FRk X-Mailer: b4 0.14.2 Message-ID: <20250505-debugfs-rust-v5-1-3e93ce7bb76e@google.com> Subject: [PATCH v5 1/4] rust: debugfs: Bind DebugFS directory creation From: Matthew Maurer To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Sami Tolvanen , Timur Tabi Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Matthew Maurer Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Support creating DebugFS directories and subdirectories. Similar to the original DebugFS API, errors are hidden. By default, when a root directory handle leaves scope, it will be cleaned up. Subdirectories will by default persist until their root directory is cleaned up, but can be converted into a root directory if a scoped lifecycle is desired. Signed-off-by: Matthew Maurer --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/kernel/debugfs.rs | 139 ++++++++++++++++++++++++++++++++++++= ++++ rust/kernel/lib.rs | 1 + 4 files changed, 142 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 906881b6c5cb6ff743e13b251873b89138c69a1c..a3b835e427b083a4ddd690d9e77= 39851f0af47ae 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7271,6 +7271,7 @@ F: include/linux/kobj* F: include/linux/property.h F: include/linux/sysfs.h F: lib/kobj* +F: rust/kernel/debugfs.rs F: rust/kernel/device.rs F: rust/kernel/device_id.rs F: rust/kernel/devres.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 8a2add69e5d66d1c2ebed9d2c950380e61c48842..787f928467faabd02a7f3cf0413= 78fac856c4f89 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/debugfs.rs b/rust/kernel/debugfs.rs new file mode 100644 index 0000000000000000000000000000000000000000..ed1aba6d700d064dbfd7e923dbc= bf80b9acf5361 --- /dev/null +++ b/rust/kernel/debugfs.rs @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: GPL-2.0 +// Copyright (C) 2025 Google LLC. + +//! DebugFS Abstraction +//! +//! C header: [`include/linux/debugfs.h`](srctree/include/linux/debugfs.h) + +use crate::str::CStr; +use core::marker::PhantomData; + +/// Owning handle to a DebugFS entry. +/// +/// # Invariants +/// +/// The wrapped pointer will always be `NULL`, an error, or an owned Debug= FS `dentry`. +#[repr(transparent)] +struct Entry<'a> { + #[cfg(CONFIG_DEBUG_FS)] + entry: *mut bindings::dentry, + // We need to be outlived by our parent, if they exist, but we don't a= ctually need to be able + // to access the data. + _phantom: PhantomData<&'a Entry<'a>>, +} + +// SAFETY: [`Entry`] is just a `dentry` under the hood, which the API prom= ises can be transferred +// between threads. +unsafe impl Send for Entry<'_> {} + +// SAFETY: All the native functions we re-export use interior locking, and= the contents of the +// struct are opaque to Rust. +unsafe impl Sync for Entry<'_> {} + +impl<'a> Entry<'a> { + /// Constructs a new DebugFS [`Entry`] from the underlying pointer. + /// + /// # Safety + /// + /// The pointer must either be an error code, `NULL`, or represent a t= ransfer of ownership of a + /// live DebugFS directory. If this is a child directory or file, `'a`= must be less than the + /// lifetime of the parent directory. + #[cfg(CONFIG_DEBUG_FS)] + unsafe fn from_ptr(entry: *mut bindings::dentry) -> Self { + Self { + entry, + _phantom: PhantomData, + } + } + + #[cfg(not(CONFIG_DEBUG_FS))] + fn new() -> Self { + Self { + _phantom: PhantomData, + } + } + + /// Returns the pointer representation of the DebugFS directory. + /// + /// # Guarantees + /// + /// Due to the type invariant, the value returned from this function w= ill always be an error + /// code, NUL, or a live DebugFS directory. + // If this function is ever needed with `not(CONFIG_DEBUG_FS)`, hardco= de it to return + // `ERR_PTR(ENODEV)`. + #[cfg(CONFIG_DEBUG_FS)] + fn as_ptr(&self) -> *mut bindings::dentry { + self.entry + } +} + +impl Drop for Entry<'_> { + fn drop(&mut self) { + // SAFETY: `debugfs_remove` can take `NULL`, error values, and leg= al DebugFS dentries. + // `as_ptr` guarantees that the pointer is of this form. + #[cfg(CONFIG_DEBUG_FS)] + unsafe { + bindings::debugfs_remove(self.as_ptr()) + } + } +} + +/// Owning handle to a DebugFS directory. +/// +/// This directory will be cleaned up when the handle leaves scope. +pub struct Dir<'a>(Entry<'a>); + +impl<'a> Dir<'a> { + /// Create a new directory in DebugFS. If `parent` is [`None`], it wil= l be created at the root. + #[cfg(CONFIG_DEBUG_FS)] + fn create<'b>(name: &CStr, parent: Option<&'a Dir<'b>>) -> Self { + let parent_ptr =3D match parent { + Some(parent) =3D> parent.0.as_ptr(), + None =3D> core::ptr::null_mut(), + }; + // SAFETY: + // * `name` argument points to a NUL-terminated string that lives = across the call, by + // invariants of `&CStr`. + // * If `parent` is `None`, `parent` accepts null pointers to mean= create at root. + // * If `parent` is `Some`, `parent` accepts live dentry debugfs p= ointers. + // so we can call `Self::from_ptr`. + let dir =3D unsafe { bindings::debugfs_create_dir(name.as_char_ptr= (), parent_ptr) }; + + // SAFETY: `debugfs_create_dir` either returns an error code or a = legal `dentry` pointer, + Self(unsafe { Entry::from_ptr(dir) }) + } + + #[cfg(not(CONFIG_DEBUG_FS))] + fn create<'b>(_name: &CStr, _parent: Option<&'a Dir<'b>>) -> Self { + Self(Entry::new()) + } + + /// Create a DebugFS subdirectory. + /// + /// Subdirectory handles cannot outlive the directory handle they were= created from. + /// + /// # Examples + /// + /// ``` + /// # use kernel::c_str; + /// # use kernel::debugfs::Dir; + /// let parent =3D Dir::new(c_str!("parent")); + /// let child =3D parent.subdir(c_str!("child")); + /// ``` + pub fn subdir<'b>(&'b self, name: &CStr) -> Dir<'b> { + Dir::create(name, Some(self)) + } + + /// Create a new directory in DebugFS at the root. + /// + /// # Examples + /// + /// ``` + /// # use kernel::c_str; + /// # use kernel::debugfs::Dir; + /// let debugfs =3D Dir::new(c_str!("parent")); + /// ``` + pub fn new(name: &CStr) -> Self { + Dir::create(name, None) + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index c3762e80b314316b4b0cee3bfd9442f8f0510b91..86f6055b828d5f711578293d891= 6a517f2436977 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -45,6 +45,7 @@ #[doc(hidden)] pub mod build_assert; pub mod cred; +pub mod debugfs; pub mod device; pub mod device_id; pub mod devres; --=20 2.49.0.967.g6a0df3ecc3-goog From nobody Sun Dec 14 06:15:48 2025 Received: from mail-pj1-f73.google.com (mail-pj1-f73.google.com [209.85.216.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 C618831280C for ; Mon, 5 May 2025 23:51:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746489102; cv=none; b=LX8jz5lVT5KPuC8FFe2X9KK+stzwyYkg609bSKYv95uiIlsWuvOxOokIVsj+omEdddHlDTPy7G25KiSWC66EIv5VA+9rgvln6lnhRYvBaF53fQSHwF1ABYlTsEOFa7W30Tca70Jx7whK/8r35FrsEHSqjNONJpVcaeFdnjEXnXo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746489102; c=relaxed/simple; bh=b3DJ+UN94pzhqaHjRVPoghHlS3Atsv9dVe93Z+66SE4=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=HYGXttqqSkGVcY1UByer22XFyRuy3wIVA+6gXeyFIUUKvC+pfew80xw5mGFdCxOuS3RCNG4n3FgG4vcTCZ/tIDqGllpbX0NnAKfqKXS7f3FwgKl0QarDMqCouNyMkk280suaIEpRYkUj48hY0FWLmQ3QdMdQ7EVlPd48BK93YYA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=UAlJc9IA; arc=none smtp.client-ip=209.85.216.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--mmaurer.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="UAlJc9IA" Received: by mail-pj1-f73.google.com with SMTP id 98e67ed59e1d1-30a3c3014fcso3562880a91.3 for ; Mon, 05 May 2025 16:51:40 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746489100; x=1747093900; 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=AlgqJD04Sxt1Yk0QMv5WSqDKEhc0Gfx3sxjzNK9A41Q=; b=UAlJc9IAKVeMkUhGGn6JnC4tRN/wY5ndC0gkp+5BljHcNcVyUa1yuRf3UjUE0C+5Cc r/Yk4P0ST1zjmujSimvZ4fz8brf9DySUzTOjTMq49SmyJGofYl3LMF0K0s64qJZQ+Kxn SCw/vimwbNydrTaqaVmriDGH1wgk1lwysjtOW0na62lmgeI02u44mQHfXVG0jPxF9bY3 nTCp+bPwbPXutc7QVSzdINs1F0JQ8EZEGllcD61qLasNSaLgAg0sA9mr8ONTs5Vs2EBt pZwvAq89EcaZkoZ2rNIonFmzjJEQdkdl0D5b6tPj78r4k8J022A763Ma8LnXuYQjGAp9 uOUA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746489100; x=1747093900; 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=AlgqJD04Sxt1Yk0QMv5WSqDKEhc0Gfx3sxjzNK9A41Q=; b=ulWrJvWAQsT8YtdHef4cCo59PUKFg4YT5GWWFbVBLojQbgEae0pL+p2g04RXnMbBGC jSxf6HCrLhi+YVIOr52I/o3L+nncycN8lf9qjkvj05LOXVAvsDcnmcHkIGaOi+DoPVdP evGkA7ZnvtDQbrjdqPJAK3D0JXc4fwbtaq6nHu2iW5xfOIyWDGm+HqyGvcFUhizNtCt5 fjmQ22dvF13sZzKnDvWaCBO02aJSDQrOLaRP7LjXCVBQbIhYLQkrkYcBjxzw6IUUrO92 IHWKLtbDOuxnlAvdCzEr6tnVkxiUTXZZWCy5cA9Xg37K2m7PEB6QiGTlVVbaukXaSQzx zKeA== X-Gm-Message-State: AOJu0Ywc3ONzi3q9CjR5GBpua+yiYbfc/zA1dl8hUDEhiGF136QsZXRx WcBb6q2nvVomsNrIQeh+VtZaSNy8BTFyVWAU5teI0qQNqd/VnQhlCPqKy8XMjJvvg7Etf8g3+uX ZBKPWzA== X-Google-Smtp-Source: AGHT+IFNZWb0O63dvnCCrz31HRZyMWLcWyX91j6SXGg7jk7gay8i0T8ORv64V7FMQ4A7/XzG2FlTbr1l8RpS X-Received: from pjbqo3.prod.google.com ([2002:a17:90b:3dc3:b0:2fe:800f:23a]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a17:90b:1f8d:b0:308:2b5b:d67f with SMTP id 98e67ed59e1d1-30a7c080700mr2109668a91.9.1746489100052; Mon, 05 May 2025 16:51:40 -0700 (PDT) Date: Mon, 05 May 2025 23:51:35 +0000 In-Reply-To: <20250505-debugfs-rust-v5-0-3e93ce7bb76e@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250505-debugfs-rust-v5-0-3e93ce7bb76e@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1746489094; l=6760; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=b3DJ+UN94pzhqaHjRVPoghHlS3Atsv9dVe93Z+66SE4=; b=73rsMIciHfAM9y1l3JvrXYr88Qe0xLWFfHhawlgR6VZREJwnB4IW2YQkbZDQfGPQSQpSZkbRE BWH1rPM3JzxAifs59J0L7rfeIOoI5MMkNJy4Ul/+eQdctvojq5FbuoG X-Mailer: b4 0.14.2 Message-ID: <20250505-debugfs-rust-v5-2-3e93ce7bb76e@google.com> Subject: [PATCH v5 2/4] rust: debugfs: Bind file creation for long-lived Display From: Matthew Maurer To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Sami Tolvanen , Timur Tabi Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Matthew Maurer Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Allows creation of files for references that live forever and lack metadata through the `Display` implementation. The reference must live forever because we do not have a maximum lifetime for the file we are creating. The `Display` implementation is used because `seq_printf` needs to route through `%pA`, which in turn routes through Arguments. A more generic API is provided later in the series, implemented in terms of this one. Signed-off-by: Matthew Maurer --- rust/kernel/debugfs.rs | 132 +++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 132 insertions(+) diff --git a/rust/kernel/debugfs.rs b/rust/kernel/debugfs.rs index ed1aba6d700d064dbfd7e923dbcbf80b9acf5361..4a138717bd0fdb320033d07446a= 192c9f520a17b 100644 --- a/rust/kernel/debugfs.rs +++ b/rust/kernel/debugfs.rs @@ -6,6 +6,7 @@ //! C header: [`include/linux/debugfs.h`](srctree/include/linux/debugfs.h) =20 use crate::str::CStr; +use core::fmt::Display; use core::marker::PhantomData; =20 /// Owning handle to a DebugFS entry. @@ -46,6 +47,19 @@ unsafe fn from_ptr(entry: *mut bindings::dentry) -> Self= { } } =20 + /// Constructs a new DebugFS [`Entry`] from the underlying pointer. + /// + /// # Safety + /// + /// The pointer must either be an error code, `NULL`, or represent a t= ransfer of ownership of a + /// live DebugFS directory. + #[cfg(not(CONFIG_DEBUG_FS))] + unsafe fn from_ptr(_entry: *mut bindings::dentry) -> Self { + Self { + _phantom: PhantomData, + } + } + #[cfg(not(CONFIG_DEBUG_FS))] fn new() -> Self { Self { @@ -124,6 +138,57 @@ pub fn subdir<'b>(&'b self, name: &CStr) -> Dir<'b> { Dir::create(name, Some(self)) } =20 + /// Create a file in a DebugFS directory with the provided name, and c= ontents from invoking + /// [`Display::fmt`] on the provided reference. + /// + /// # Examples + /// + /// ``` + /// # use kernel::c_str; + /// # use kernel::debugfs::Dir; + /// let dir =3D Dir::new(c_str!("my_debugfs_dir")); + /// dir.display_file(c_str!("foo"), &200); + /// // "my_debugfs_dir/foo" now contains the number 200. + /// ``` + pub fn display_file<'b, T: Display + Sized>( + &'b self, + name: &CStr, + data: &'static T, + ) -> File<'b> { + // SAFETY: + // * `name` is a NUL-terminated C string, living across the call, = by `CStr` invariant. + // * `parent` is a live `dentry` since we have a reference to it. + // * `vtable` is all stock `seq_file` implementations except for `= open`. + // `open`'s only requirement beyond what is provided to all open= functions is that the + // inode's data pointer must point to a `T` that will outlive it= , which we know because + // we have a static reference. + #[cfg(CONFIG_DEBUG_FS)] + let ptr =3D unsafe { + bindings::debugfs_create_file_full( + name.as_char_ptr(), + 0o444, + self.0.as_ptr(), + data as *const _ as *mut _, + core::ptr::null(), + &::VTABLE, + ) + }; + + #[cfg(not(CONFIG_DEBUG_FS))] + let ptr =3D { + // Mark parameters used + let (_, _) =3D (name, data); + crate::error::code::ENODEV.to_ptr() + }; + + // SAFETY: `debugfs_create_file_full` either returns an error code= or a legal + // dentry pointer, and without `CONFIG_DEBUGFS` we return an error= pointer, so + // `Entry::from_ptr` is safe to call here. + let entry =3D unsafe { Entry::from_ptr(ptr) }; + + File(entry) + } + /// Create a new directory in DebugFS at the root. /// /// # Examples @@ -137,3 +202,70 @@ pub fn new(name: &CStr) -> Self { Dir::create(name, None) } } +/// Handle to a DebugFS file. +#[repr(transparent)] +pub struct File<'a>(Entry<'a>); + +#[cfg(CONFIG_DEBUG_FS)] +mod helpers { + use crate::seq_file::SeqFile; + use crate::seq_print; + use core::fmt::Display; + + /// Implements `open` for `file_operations` via `single_open` to fill = out a `seq_file`. + /// + /// # Safety + /// + /// * `inode`'s private pointer must point to a value of type `T` whic= h will outlive the `inode` + /// and will not be mutated during this call. + /// * `file` must point to a live, not-yet-initialized file object. + pub(crate) unsafe extern "C" fn display_open( + inode: *mut bindings::inode, + file: *mut bindings::file, + ) -> i32 { + // SAFETY: + // * `file` is acceptable by caller precondition. + // * `print_act` will be called on a `seq_file` with private data = set to the third argument, + // so we meet its safety requirements. + // * The `data` pointer passed in the third argument is a valid `T= ` pointer that outlives + // this call by caller preconditions. + unsafe { bindings::single_open(file, Some(display_act::), (*ino= de).i_private) } + } + + /// Prints private data stashed in a seq_file to that seq file. + /// + /// # Safety + /// + /// `seq` must point to a live `seq_file` whose private data is a live= pointer to a `T` which is + /// not being mutated. + pub(crate) unsafe extern "C" fn display_act( + seq: *mut bindings::seq_file, + _: *mut core::ffi::c_void, + ) -> i32 { + // SAFETY: By caller precondition, this pointer is live, points to= a value of type `T`, and + // is not being mutated. + let data =3D unsafe { &*((*seq).private as *mut T) }; + // SAFETY: By caller precondition, `seq_file` points to a live `se= q_file`, so we can lift + // it. + let seq_file =3D unsafe { SeqFile::from_raw(seq) }; + seq_print!(seq_file, "{}", data); + 0 + } + + // Work around lack of generic const items. + pub(crate) trait DisplayFile: Display + Sized { + const VTABLE: bindings::file_operations =3D bindings::file_operati= ons { + read: Some(bindings::seq_read), + llseek: Some(bindings::seq_lseek), + release: Some(bindings::single_release), + open: Some(display_open:: as _), + // SAFETY: `file_operations` supports zeroes in all fields. + ..unsafe { core::mem::zeroed() } + }; + } + + impl DisplayFile for T {} +} + +#[cfg(CONFIG_DEBUG_FS)] +use helpers::*; --=20 2.49.0.967.g6a0df3ecc3-goog From nobody Sun Dec 14 06:15:48 2025 Received: from mail-pl1-f202.google.com (mail-pl1-f202.google.com [209.85.214.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6D571313048 for ; Mon, 5 May 2025 23:51:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.214.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746489104; cv=none; b=PgnfYNjE57bsMDKnqw8Gx1d6pdtPnpYAw3Qdkx5n6bydxTNHx9yQEOD+pt9hvgOdFyf/5RSylFYh0xq0f6IlzzxCGWy07J9QXNk8NAYN5WEcxfC54fIxgUEiwI8mHp+IUBSJCLBUvrg5B9knWgxs6t2EpLfpRhJ43yVoykjGUuo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746489104; c=relaxed/simple; bh=vA+3O1t3AGi/2mn5IPfBFihGnHyNUnS1wn1tz2cJ2+U=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=IzoPAgl/V81nioTa4oUf38Sh2nmzvlWjvW/OaWkrOTLlE5JsDiAi4VMDQ10vEMdlrn0OpwL4qM3lRDTZfznvWsJX9ctMJqQ6lU4XGz+8EYiQK8MPdBmZDxMfODq9W0Rv5ZqIwNC41FVjW2IR/6JbFu2DAvXDMTplH2wem9efUT4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=nWkjZ/S/; arc=none smtp.client-ip=209.85.214.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="nWkjZ/S/" Received: by mail-pl1-f202.google.com with SMTP id d9443c01a7336-2241e7e3addso45350375ad.1 for ; Mon, 05 May 2025 16:51:42 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746489102; x=1747093902; 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=jacHybD5l2r2uNkGTUFeSA2UwX+BWUuxXqoE7r0Z5kU=; b=nWkjZ/S/ovy7CNNOYIy8je/lm/5m02UD8NuxxNUYDuXQ+HhxAcU0V2unkQB0yOrBBb bSmLj9IVT104Hm59o/uW06j6w3QC4zgA29EqbysrigRHuO046/O5FXW8MXDpUVJGfqh/ bmKiNp8B/3PsHtp5UcXD6VkkzUb0v6xI44MN+62Efx1uS79eh2LUn9z99ogXozer32By acWBZmMRDEZNnDS9WNiLcG/3gwu3vhpxRfZdH3KBf63Z16ZYTSppEimAYS+cqUNOizz1 NcDkYF70dtYk4pZPqURnLwrXXaKf54DBtrn8h6DRuRM+wPtdNN+bvRCqXWn62GqIxHfA poiw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746489102; x=1747093902; 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=jacHybD5l2r2uNkGTUFeSA2UwX+BWUuxXqoE7r0Z5kU=; b=Lk/edUAC310XMoYrykb+8XwpWXEfdkXUCk5E2VCsEuzKxvmWA3aH0aD3/zkbvmBNGt jaM4ZNIfrVkpGS+SQx7arSP/5kZaibMyDi+oF3pvWS3nELOV29H+UhmufIjKxPDMwOOJ 7XzkHr+kg0YCZgBCgG2njEnFlPXa/uC6eMDdJn29tTuYx6KQxub5MhgCfdvldHnfnpoa uXHh0vmcNiloTmXKCj+dsIDeCGV+3FKLbYJ8lhESDjmVpTEZ5xc2DkNsiio05o9qP9x8 s1gM/6FB665TdPOrt4DdaDK4qI3urC8d9QSLxT4KmnFGZ5MOXiboSzNQ61sGdOU90Tk0 dUSg== X-Gm-Message-State: AOJu0YzwNM5wJEBvJWOHVFmj9ywGEjZq/boHdQ1VLrckRqeEl9Ekokj7 IqvnN/PYS1l/tSRGtRz8SN+xJdkBAG0t+M6o/50b+pnYYmR2CdRJRKlFqe51rhDmeo6mQpBLB8s 2fewvvA== X-Google-Smtp-Source: AGHT+IGlOzGin2PKFA5mkv3PM64Fa1xlk2aR4bHHjsQrq6I6muDss5yiDkB6A08sID82xIf/IFdy+5L3Pem4 X-Received: from plop13.prod.google.com ([2002:a17:902:8a8d:b0:22d:e49c:3cb]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a17:902:da8c:b0:223:2630:6b82 with SMTP id d9443c01a7336-22e102b8c91mr236889605ad.10.1746489101802; Mon, 05 May 2025 16:51:41 -0700 (PDT) Date: Mon, 05 May 2025 23:51:36 +0000 In-Reply-To: <20250505-debugfs-rust-v5-0-3e93ce7bb76e@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250505-debugfs-rust-v5-0-3e93ce7bb76e@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1746489094; l=6727; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=vA+3O1t3AGi/2mn5IPfBFihGnHyNUnS1wn1tz2cJ2+U=; b=tSSeDVBlQ7e9YMpXKBMRXFBdgOdeR5lLT0Oc9eMsrvbh/aDxJR6EmeGVRBQRPPoWXCd15gAL5 /vydOhPRrLKDRaqDpSE2y9wZ7/ub5ENCys4kDQlf+Ew82H9anaCun5O X-Mailer: b4 0.14.2 Message-ID: <20250505-debugfs-rust-v5-3-3e93ce7bb76e@google.com> Subject: [PATCH v5 3/4] rust: debugfs: Support format hooks From: Matthew Maurer To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Sami Tolvanen , Timur Tabi Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Matthew Maurer Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Rather than always using Display, allow hooking arbitrary functions to arbitrary files. Display technically has the expressiveness to do this, but requires a new type be declared for every different way to render things, which can be very clumsy. Signed-off-by: Matthew Maurer --- rust/kernel/debugfs.rs | 123 +++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 122 insertions(+), 1 deletion(-) diff --git a/rust/kernel/debugfs.rs b/rust/kernel/debugfs.rs index 4a138717bd0fdb320033d07446a192c9f520a17b..e2f5960bb87f24607780b3f4e67= 039e379f3bda6 100644 --- a/rust/kernel/debugfs.rs +++ b/rust/kernel/debugfs.rs @@ -6,6 +6,7 @@ //! C header: [`include/linux/debugfs.h`](srctree/include/linux/debugfs.h) =20 use crate::str::CStr; +use core::fmt; use core::fmt::Display; use core::marker::PhantomData; =20 @@ -154,6 +155,52 @@ pub fn display_file<'b, T: Display + Sized>( &'b self, name: &CStr, data: &'static T, + ) -> File<'b> { + // SAFETY: As `data` lives for the static lifetime, it outlives th= e file. + unsafe { self.display_file_raw(name, data) } + } + + /// Create a file in a DebugFS directory with the provided name, and c= ontents from invoking `f` + /// on the provided reference. + /// + /// `f` must be a function item or a non-capturing closure, or this wi= ll fail to compile. + /// + /// # Examples + /// + /// ``` + /// # use core::sync::atomic::{AtomicU32, Ordering}; + /// # use kernel::c_str; + /// # use kernel::debugfs::Dir; + /// let dir =3D Dir::new(c_str!("foo")); + /// static MY_ATOMIC: AtomicU32 =3D AtomicU32::new(3); + /// let file =3D dir.fmt_file(c_str!("bar"), &MY_ATOMIC, &|val, f| { + /// let out =3D val.load(Ordering::Relaxed); + /// writeln!(f, "{out:#010x}") + /// }); + /// MY_ATOMIC.store(10, Ordering::Relaxed); + /// ``` + pub fn fmt_file<'b, T, F: Fn(&T, &mut fmt::Formatter<'_>) -> fmt::Resu= lt>( + &'b self, + name: &CStr, + data: &'static T, + f: &'static F, + ) -> File<'b> { + // SAFETY: As `data` lives for the static lifetime, it outlives th= e file + unsafe { self.fmt_file_raw(name, data, f) } + } + + /// Creates a DebugFS file backed by the display implementation of the= provided pointer. + /// + /// # Safety + /// + /// The pointee of `data` must outlive the accessibility of the `Dir` = returned by this function. + /// This means that before `data` may become invalid, either: + /// * The refcount must go to zero. + /// * The file must be rendered inaccessible, e.g. via `debugfs_remove= `. + unsafe fn display_file_raw<'b, T: Display + Sized>( + &'b self, + name: &CStr, + data: *const T, ) -> File<'b> { // SAFETY: // * `name` is a NUL-terminated C string, living across the call, = by `CStr` invariant. @@ -189,6 +236,32 @@ pub fn display_file<'b, T: Display + Sized>( File(entry) } =20 + /// Create a file in a DebugFS directory with the provided name, and c= ontents from invoking the + /// fomatter on the attached data. + /// + /// The attached function must be a ZST, and will cause a compilation = error if it is not. + /// + /// # Safety + /// + /// `data` must outlive the resulting file's accessibility + unsafe fn fmt_file_raw<'b, T, F: Fn(&T, &mut fmt::Formatter<'_>) -> fm= t::Result>( + &'b self, + name: &CStr, + data: &T, + f: &'static F, + ) -> File<'b> { + #[cfg(CONFIG_DEBUG_FS)] + let data_adapted =3D FormatAdapter::new(data, f); + #[cfg(not(CONFIG_DEBUG_FS))] + let data_adapted =3D { + // Mark used + let (_, _) =3D (data, f); + &0 + }; + // SAFETY: data outlives the file's accessibility, so data_adapted= does too + unsafe { self.display_file_raw(name, data_adapted) } + } + /// Create a new directory in DebugFS at the root. /// /// # Examples @@ -202,6 +275,7 @@ pub fn new(name: &CStr) -> Self { Dir::create(name, None) } } + /// Handle to a DebugFS file. #[repr(transparent)] pub struct File<'a>(Entry<'a>); @@ -210,7 +284,9 @@ pub fn new(name: &CStr) -> Self { mod helpers { use crate::seq_file::SeqFile; use crate::seq_print; - use core::fmt::Display; + use core::fmt; + use core::fmt::{Display, Formatter}; + use core::marker::PhantomData; =20 /// Implements `open` for `file_operations` via `single_open` to fill = out a `seq_file`. /// @@ -265,6 +341,51 @@ pub(crate) trait DisplayFile: Display + Sized { } =20 impl DisplayFile for T {} + + /// Adapter to implement `Display` via a callback with the same repres= entation as `T`. + /// + /// # Invariants + /// + /// If an instance for `FormatAdapter<_, F>` is constructed, `F` is in= habited. + #[repr(transparent)] + pub(crate) struct FormatAdapter { + inner: T, + _formatter: PhantomData, + } + + impl FormatAdapter { + pub(crate) fn new<'a>(inner: &'a T, _f: &'static F) -> &'a Self { + // SAFETY: FormatAdapater is a repr(transparent) wrapper aroun= d T, so + // casting a reference is legal + // INVARIANT: We were passed a reference to F, so it is inhabi= ted. + unsafe { core::mem::transmute(inner) } + } + } + + impl Display for FormatAdapter + where + F: Fn(&T, &mut Formatter<'_>) -> fmt::Result + 'static, + { + fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { + // SAFETY: FormatAdapter<_, F> can only be constructed if F is= inhabited + let f: &F =3D unsafe { materialize_zst_fmt() }; + f(&self.inner, fmt) + } + } + + /// For types with a unique value, produce a static reference to it. + /// + /// # Safety + /// + /// The caller asserts that F is inhabited + unsafe fn materialize_zst_fmt() -> &'static F { + const { assert!(core::mem::size_of::() =3D=3D 0) }; + let zst_dangle: core::ptr::NonNull =3D core::ptr::NonNull::dang= ling(); + // SAFETY: While the pointer is dangling, it is a dangling pointer= to a ZST, based on the + // assertion above. The type is also inhabited, by the caller's as= sertion. This means + // we can materialize it. + unsafe { zst_dangle.as_ref() } + } } =20 #[cfg(CONFIG_DEBUG_FS)] --=20 2.49.0.967.g6a0df3ecc3-goog From nobody Sun Dec 14 06:15:48 2025 Received: from mail-pg1-f201.google.com (mail-pg1-f201.google.com [209.85.215.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 76B4F313041 for ; Mon, 5 May 2025 23:51:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.215.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746489107; cv=none; b=OoDQx3Ll0xc1rxtWzibVE35FEGa5s+YuzCMuxAE70qmUBQl6q0sC9/8HIA+0VEephi/y9Ux+NaNaKwfHDEm9xU3jopPx1YYQsV7Eg7vAlsVaT29kYtJQOHzO2S+kWeHcux7haARo+EzHTeRajvPCgZqe4pMZXshizp2NIFW8HQ4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746489107; c=relaxed/simple; bh=1Czlpu5Zw+onSfmWVzbc7ubzKt2PZFY4w+8ny+bUfx0=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=JKazhyScA8FNa+hY0JD9/pj2c0Ia7VCpluNeFo288iislzMyKZUem82NZA24QYW817q3agWzFXboi6jY5Q3cI6xML1Zqh5lvfl4xRi0T3Es1H3XtDa87KA/ayKFy97ZJXkZg2IdkWdbfCJTeZSUPXz1KK/CKdp8D0tLe+NAseac= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=VlWIUGxN; arc=none smtp.client-ip=209.85.215.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mmaurer.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="VlWIUGxN" Received: by mail-pg1-f201.google.com with SMTP id 41be03b00d2f7-b1f71ae2181so2632512a12.1 for ; Mon, 05 May 2025 16:51:44 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746489104; x=1747093904; 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=lVFcCuEJ5alfPtNg/Xq1mbavgiLO3WAXess9THLNyv0=; b=VlWIUGxNJn3tCOeuKj5hTbQ/wDNSomgHekXRUgLFRJnNiFAByZqBPkKhinYFdhH+q0 yjsWM0NheFRDECShWluFWi9mNkEd4IjIXupDWX23ErcEzdaw1YNJBtEQkBcA0bH1BFH4 7o3fN4b0UwYhOZr+EwD1liDOQD5YP+F9VmGxBALwcTVsRrfNX595vnGa4Lv+JIUzRY/K eekhPkVbQ4becN56TBaeJsIUe/QAd5stOv6kicU0ArvTJ+0duSotwH+uDRggYTn107In r5zx2fzqXuzpZG9SyZriVoU14IMETQEsdFwli7ZTiHK7RAbdPCRpxQJ+FOBe7+rAbxOh PasA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746489104; x=1747093904; 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=lVFcCuEJ5alfPtNg/Xq1mbavgiLO3WAXess9THLNyv0=; b=r5rHAbTd7hK9CP/keoDgYQYFxSEonFub01ezrFIaUS+IWzDQzKy16EOu1jXJ2xROcD glfHagWRw3szLKzGWRSqN2XR2/WHIELGANndJYtRZb+rYUCS6yxvteSXqEoP46k+CJSM KsVZBCXZzDIO0k9m/vCb3NHxPf4e3okRENqnUh/LmxZ27/eVAn/cYTGz7aHJ/FMQhM/z 3X4im8yTtGhpEFkCCq9xo8uNCDcAh976Wl7xGEcumdcJW5rJg2bQR387aeRjqMlMjNrW mntgoqtXqgN+0fGrEUgPw1p0M0Tdpyt7YqnjZf+oZ87/98uLCeq6SleHLnlQ0LD/LwFu n9/A== X-Gm-Message-State: AOJu0YxFaGqiVBJb/VjroRG2ApgGZV2Vq9R7L1ggX36NCIUGxIqc81/N XkpDS9XHopS6EjYbmIpKatUEXj+ygG5VIlGVggSFh4GM8mftuWtkoT4DSVKjsWjFXCEVDmbqWmk V00Npvg== X-Google-Smtp-Source: AGHT+IHhHeeJd9n5Zw7omC+WvKFKXAbgEziWfLrzNlmR3bEjX3KPOzvCbkNlX8p2OE6R7hdCj4z5Muub6Pbf X-Received: from plhz4.prod.google.com ([2002:a17:902:d9c4:b0:220:ecac:27e5]) (user=mmaurer job=prod-delivery.src-stubby-dispatcher) by 2002:a17:903:1b2f:b0:223:54aa:6d15 with SMTP id d9443c01a7336-22e1e8e5104mr161714215ad.12.1746489103754; Mon, 05 May 2025 16:51:43 -0700 (PDT) Date: Mon, 05 May 2025 23:51:37 +0000 In-Reply-To: <20250505-debugfs-rust-v5-0-3e93ce7bb76e@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250505-debugfs-rust-v5-0-3e93ce7bb76e@google.com> X-Developer-Key: i=mmaurer@google.com; a=ed25519; pk=2Ezhl7+fEjTOMVFpplDeak2AdQ8cjJieLRVJdNzrW+E= X-Developer-Signature: v=1; a=ed25519-sha256; t=1746489094; l=5037; i=mmaurer@google.com; s=20250429; h=from:subject:message-id; bh=1Czlpu5Zw+onSfmWVzbc7ubzKt2PZFY4w+8ny+bUfx0=; b=9DsYGfqkB44bJMw3Jc4sY+S7ingNR9ptF+1HkrZeHUix3jk0G2P5GA9QBUYyyyjDavOZBXfmR AGRN2rlofWOBQmJTKyGAx+GTLBwAfRLzS/3v59G0OMxBu29TqPDGFEn X-Mailer: b4 0.14.2 Message-ID: <20250505-debugfs-rust-v5-4-3e93ce7bb76e@google.com> Subject: [PATCH v5 4/4] rust: samples: Add debugfs sample From: Matthew Maurer To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Sami Tolvanen , Timur Tabi Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Matthew Maurer Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Provides an example of using the Rust DebugFS bindings. Signed-off-by: Matthew Maurer --- MAINTAINERS | 1 + samples/rust/Kconfig | 11 ++++++++ samples/rust/Makefile | 1 + samples/rust/rust_debugfs.rs | 60 ++++++++++++++++++++++++++++++++++++++++= ++++ 4 files changed, 73 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index a3b835e427b083a4ddd690d9e7739851f0af47ae..426bcdac025134e20911de8e2cf= 5c9efb0591814 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7278,6 +7278,7 @@ F: rust/kernel/devres.rs F: rust/kernel/driver.rs F: rust/kernel/faux.rs F: rust/kernel/platform.rs +F: samples/rust/rust_debugfs.rs F: samples/rust/rust_driver_platform.rs F: samples/rust/rust_driver_faux.rs =20 diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index 43cb72d72631bb2d6e06185e1d88778edff6ee13..6c42ed73f842cda26256039e691= 7bb443738d3f1 100644 --- a/samples/rust/Kconfig +++ b/samples/rust/Kconfig @@ -51,6 +51,17 @@ config SAMPLE_RUST_DMA =20 If unsure, say N. =20 +config SAMPLE_RUST_DEBUGFS + tristate "DebugFS Test Driver" + depends on DEBUG_FS + help + This option builds the Rust DebugFS Test driver sample. + + To compile this as a module, choose M here: + the module will be called rust_debugfs. + + If unsure, say N. + config SAMPLE_RUST_DRIVER_PCI tristate "PCI Driver" depends on PCI diff --git a/samples/rust/Makefile b/samples/rust/Makefile index 6a466afd2a21eba84a3b7b2be29f25dce44e9053..b1fc4677ed53fcf7d0f5a3dbf32= 2f65851bc1784 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -4,6 +4,7 @@ ccflags-y +=3D -I$(src) # needed for trace events obj-$(CONFIG_SAMPLE_RUST_MINIMAL) +=3D rust_minimal.o obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE) +=3D rust_misc_device.o obj-$(CONFIG_SAMPLE_RUST_PRINT) +=3D rust_print.o +obj-$(CONFIG_SAMPLE_RUST_DEBUGFS) +=3D rust_debugfs.o obj-$(CONFIG_SAMPLE_RUST_DMA) +=3D rust_dma.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) +=3D rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) +=3D rust_driver_platform.o diff --git a/samples/rust/rust_debugfs.rs b/samples/rust/rust_debugfs.rs new file mode 100644 index 0000000000000000000000000000000000000000..a4b17c8241330b2f6caf8f17a5b= 2366138de6ced --- /dev/null +++ b/samples/rust/rust_debugfs.rs @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2025 Google LLC. + +//! Sample DebugFS exporting module + +use core::mem::{forget, ManuallyDrop}; +use core::sync::atomic::{AtomicU32, Ordering}; +use kernel::c_str; +use kernel::debugfs::Dir; +use kernel::prelude::*; + +module! { + type: RustDebugFs, + name: "rust_debugfs", + authors: ["Matthew Maurer"], + description: "Rust DebugFS usage sample", + license: "GPL", +} + +struct RustDebugFs { + // As we only hold this for drop effect (to remove the directory) we h= ave a leading underscore + // to indicate to the compiler that we don't expect to use this field = directly. + _debugfs: Dir<'static>, +} + +static EXAMPLE: AtomicU32 =3D AtomicU32::new(8); + +impl kernel::Module for RustDebugFs { + fn init(_this: &'static ThisModule) -> Result { + // Create a debugfs directory in the root of the filesystem called= "sample_debugfs". + let debugfs =3D Dir::new(c_str!("sample_debugfs")); + + { + // Create a subdirectory, so "sample_debugfs/subdir" now exist= s. + // We wrap it in `ManuallyDrop` so that the subdirectory is no= t automatically discarded + // at the end of the scope - it will be cleaned up when `debug= fs` is. + let sub =3D ManuallyDrop::new(debugfs.subdir(c_str!("subdir"))= ); + + // Create a single file in the subdirectory called "example" t= hat will read from the + // `EXAMPLE` atomic variable. + // We `forget` the result to avoid deleting the file at the en= d of the scope. + forget(sub.fmt_file(c_str!("example"), &EXAMPLE, &|example, f|= { + writeln!(f, "Reading atomic: {}", example.load(Ordering::R= elaxed)) + })); + // Now, "sample_debugfs/subdir/example" will print "Reading at= omic: 8\n" when read. + } + + // Change the value in the variable displayed by the file. This is= intended to demonstrate + // that the module can continue to change the value used by the fi= le. + EXAMPLE.store(10, Ordering::Relaxed); + // Now, "sample_debugfs/subdir/example" will print "Reading atomic= : 10\n" when read. + + // Save the root debugfs directory we created to our module object= . It will be + // automatically cleaned up when our module is unloaded because dr= opping the module object + // will drop the `Dir` handle. The base directory, the subdirector= y, and the file will all + // continue to exist until the module is unloaded. + Ok(Self { _debugfs: debugfs }) + } +} --=20 2.49.0.967.g6a0df3ecc3-goog