Rust dynamic debug support for pr_debug! and dev_dbg!
Subsystems (11)
v3 cover Rust dynamic debug support for pr_debug! and dev_dbg!
Add runtime dynamic debug control to Rust pr_debug! and dev_dbg!, using the existing C control file, boot/module parameters, prefixes and jump labels. Callsite flags and static keys always start disabled. Users enable messages with dyndbg queries; Rust debug assertions do not affect whether a debug message is printed.
This continues Andrew Ballance's RFC v2:
https://lore.kernel.org/rust-for-linux/[email protected]/
This revision retains RFC v2's nested-field static-branch macros and static mut descriptors addressed through raw pointers.
Changes since RFC v2:
- Make debug logging independent of Rust's debug_assertions setting. Both pr_debug! and dev_dbg! start disabled and are enabled through dyndbg; without dynamic debug support, both remain disabled.
- Keep caller expressions outside unsafe blocks and avoid implicit Rust references when reading descriptor flags without jump labels.
- Correct big-endian bitfield layout and keep module descriptors writable with #[used(compiler)]. This fixes the kernel write fault when static_key_enable_cpuslocked() tries to write the static key.
- Use Kbuild module names and actual format strings for filtering, preserve the crate log prefix, and support +d stack output.
- Complete DYNAMIC_DEBUG_CORE-only support with per-crate opt-in.
- Port to driver-core-testing and preserve Nova's firmware validation when debug logging is disabled.
Limitations:
- Function metadata deliberately remains <unknown>;
Andrew Ballance (3):
rust: jump label: add support for nested arguments
rust: print: add dynamic debug support to pr_debug!
rust: device: add dynamic debug support to dev_dbg!
Zhi Wang (2):
gpu: nova-core: validate firmware versions before debug logging
dynamic_debug: expose printing declarations with the core enabled
.../admin-guide/dynamic-debug-howto.rst | 41 ++++ MAINTAINERS | 2 + drivers/gpu/nova-core/firmware/booter.rs | 8 +- drivers/gpu/nova-core/firmware/fsp.rs | 3 +- .../nova-core/firmware/fwsec/bootloader.rs | 7 +- drivers/gpu/nova-core/firmware/gsp.rs | 3 +- drivers/gpu/nova-core/firmware/riscv.rs | 7 +- include/linux/dynamic_debug.h | 16 +- rust/Makefile | 3 + rust/bindings/bindings_helper.h | 1 + rust/helpers/dynamic_debug.c | 33 +++ rust/helpers/helpers.c | 1 + rust/kernel/device.rs | 42 +++- rust/kernel/jump_label.rs | 17 +- rust/kernel/print.rs | 53 ++++- rust/kernel/print/dynamic_debug.rs | 192 ++++++++++++++++++ scripts/Makefile.build | 1 + scripts/generate_rust_analyzer.py | 1 + 18 files changed, 386 insertions(+), 45 deletions(-) create mode 100644 rust/helpers/dynamic_debug.c create mode 100644 rust/kernel/print/dynamic_debug.rs
base-commit: f1850e443b0e4f2429ddf42a8d5033ea54ae8a90
Signature · 1 line
2.53.0
PATCH v3 1/5 gpu: nova-core: validate firmware versions before debug logging
Firmware loaders currently use tlv.get_string(b"VERS")? inside dev_dbg! arguments. The string conversion rejects non-printable ASCII, and its error currently propagates even with debug assertions disabled.
Move those conversions before the logging calls so that making dev_dbg! arguments conditional does not change firmware validation. Keep the message text and the order of the remaining initialization unchanged.
--- drivers/gpu/nova-core/firmware/booter.rs | 8 ++------ drivers/gpu/nova-core/firmware/fsp.rs | 3 ++- drivers/gpu/nova-core/firmware/fwsec/bootloader.rs | 7 ++----- drivers/gpu/nova-core/firmware/gsp.rs | 3 ++- drivers/gpu/nova-core/firmware/riscv.rs | 7 ++----- 5 files changed, 10 insertions(+), 18 deletions(-)
drivers/gpu/nova-core/firmware/booter.rs +2 -6
@@ -93,12 +93,8 @@ pub(crate) fn new( };let fw =request_tlv (dev, chipset, fw_name)?;let tlv =Tlv ::new (fw.data ())?; -dev_dbg! ( - dev, -"loaded {} firmware v{}\n" , - fw_name, - tlv.get_string (b"VERS" )? - ); +let version = tlv.get_string (b"VERS" )?; +dev_dbg! (dev,"loaded {} firmware v{}\n" , fw_name, version);let os_data_offset = tlv.get_u32 (b"DAOF" )?;let os_data_size = tlv.get_u32 (b"DASZ" )?;
drivers/gpu/nova-core/firmware/fsp.rs +2 -1
@@ -50,7 +50,8 @@ impl<'a> FspFirmware<'a> {pub (crate )fn new (dev: &'a device::Device <device::Bound >, chipset:Chipset ) ->Result <Self > {let fw =request_tlv (dev, chipset,"fmc" )?;let tlv =Tlv ::new (fw.data ())?; -dev_dbg! (dev,"loaded fsp firmware v{}\n" , tlv.get_string (b"VERS" )?); +let version = tlv.get_string (b"VERS" )?; +dev_dbg! (dev,"loaded fsp firmware v{}\n" , version);let fmc_image_data = tlv.get_bytes (b"BLOB" )?;let fmc_image =Coherent ::from_slice (dev, fmc_image_data,GFP_KERNEL )?;
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +2 -5
@@ -125,11 +125,8 @@ pub(crate) fn new( ) -> Result<Self> {let fw =request_tlv (dev, chipset,"gen_bootloader" )?;let tlv =Tlv ::new (fw.data ())?; -dev_dbg! ( - dev, -"loaded generic bootloader firmware v{}\n" , - tlv.get_string (b"VERS" )? - ); +let version = tlv.get_string (b"VERS" )?; +dev_dbg! (dev,"loaded generic bootloader firmware v{}\n" , version);let ucode = {let blob = tlv.get_bytes (b"BLOB" )?;
drivers/gpu/nova-core/firmware/gsp.rs +2 -1
@@ -74,7 +74,8 @@ pub(crate) fn new( pin_init::pin_init_scope (move || {let firmware =request_tlv (dev, chipset,"gsp" )?;let tlv =Tlv ::new (firmware.data ())?; -dev_dbg! (dev,"loaded gsp firmware v{}\n" , tlv.get_string (b"VERS" )?); +let version = tlv.get_string (b"VERS" )?; +dev_dbg! (dev,"loaded gsp firmware v{}\n" , version);let size = usize::from_safe_cast (tlv.get_u32 (b"SIZE" )?);let mut fw_vvec =VVec ::zeroed (size,GFP_KERNEL ).map_err (|_|ENOMEM )?;
drivers/gpu/nova-core/firmware/riscv.rs +2 -5
@@ -30,11 +30,8 @@ impl<'a> RiscvFirmware<'a> {/// Parses the RISC-V firmware image contained in `fw`. pub (crate )fn new (dev: &'a device::Device <device::Bound >, fw: &Firmware ) ->Result <Self > {let tlv =Tlv ::new (fw.data ())?; -dev_dbg! ( - dev, -"loaded gsp bootloader firmware v{}\n" , - tlv.get_string (b"VERS" )? - ); +let version = tlv.get_string (b"VERS" )?; +dev_dbg! (dev,"loaded gsp bootloader firmware v{}\n" , version);let code_offset = tlv.get_u32 (b"CDOF" )?;let data_offset = tlv.get_u32 (b"DAOF" )?;
Signature · 1 line
2.53.0
PATCH v3 2/5 rust: jump label: add support for nested arguments
In reply to Zhi WangFrom: Andrew Ballance <[email protected]>
allows for nested arguments to be used with the static_branch macro. e.g. outer.inner.key can now be accessed by the macro
[Zhi: Rebase; extend the host-test stub in the same way and document
the initialized-key and storage requirements for Rust-defined callsites.]
--- rust/kernel/jump_label.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-)
rust/kernel/jump_label.rs +10 -7
@@ -16,12 +16,15 @@/// /// # Safety /// -/// The macro must be used with a real static key defined by C. +/// The static variable must contain an initialized `static_key_false` at the specified field. +/// Its storage must remain valid while the key is registered with the jump label code. Updates +/// to the key must use the C static-key APIs. #[macro_export] macro_rules! static_branch_unlikely { - ($key:path, $keytyp:ty, $field:ident) => {{ + ($key:path, $keytyp:ty, $($field:ident).+) => {{let _key: *const $keytyp = ::core::ptr::addr_of!($key); -let _key: *const $crate::bindings::static_key_false = ::core::ptr::addr_of!((*_key).$field); +let _key: *const $crate::bindings::static_key_false = + ::core::ptr::addr_of!((*_key)$(.$field)+);let _key: *const $crate::bindings::static_key = _key.cast ();#[cfg(not( CONFIG_JUMP_LABEL ))]
@@ -30,7 +33,7 @@ macro_rules! static_branch_unlikely { }#[cfg( CONFIG_JUMP_LABEL )] - $crate::jump_label::arch_static_branch! { $key, $keytyp, $field,false } + $crate::jump_label::arch_static_branch! { $key, $keytyp, $($field).+,false } }}; }pub use static_branch_unlikely;
@@ -47,14 +50,14 @@ macro_rules! static_branch_unlikely {#[cfg(not(testlib))] #[cfg( CONFIG_JUMP_LABEL )] macro_rules! arch_static_branch { - ($key:path, $keytyp:ty, $field:ident, $branch:expr) => {'my_label: { + ($key:path, $keytyp:ty, $($field:ident).+, $branch:expr) => {'my_label: { $crate::asm!(include! (concat! (env! ("OBJTREE" ),"/rust/kernel/generated_arch_static_branch_asm.rs" )); l_yes =label {break 'my_labeltrue ; }, symb = sym $key, - off =const ::core::mem::offset_of!($keytyp, $field), + off =const ::core::mem::offset_of!($keytyp, $($field).+), branch =const $crate ::jump_label::bool_to_int ($branch), );
@@ -67,7 +70,7 @@ macro_rules! arch_static_branch {#[cfg(testlib)] #[cfg( CONFIG_JUMP_LABEL )] macro_rules! arch_static_branch { - ($key:path, $keytyp:ty, $field:ident, $branch:expr) => { + ($key:path, $keytyp:ty, $($field:ident).+, $branch:expr) => {// The asm falls through until patched, which never happens on the host. false };
Signature · 1 line
2.53.0
PATCH v3 3/5 dynamic_debug: expose printing declarations with the core enabled
In reply to Zhi WangThe dynamic debug printing functions exist whenever DYNAMIC_DEBUG_CORE is enabled, even if the current translation unit has not opted in to debug callsites. Expose their declarations under that same condition.
Rust bindings and helpers are compiled independently of the driver crates that opt in with DYNAMIC_DEBUG_MODULE. They need the declarations in a CORE-only configuration without enabling callsites globally. Leave the existing conditions around the callsite macros unchanged.
--- include/linux/dynamic_debug.h | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-)
include/linux/dynamic_debug.h +10 -6
@@ -131,12 +131,7 @@ struct ddebug_class_param {const struct ddebug_class_map *map; }; -/* -* pr_debug() and friends are globally enabled or modules have selectively -* enabled them. -*/ -#if defined(CONFIG_DYNAMIC_DEBUG ) || \ - (defined(CONFIG_DYNAMIC_DEBUG_CORE ) && defined(DYNAMIC_DEBUG_MODULE )) +#ifdef CONFIG_DYNAMIC_DEBUG_CORE extern __printf(2, 3) void __dynamic_pr_debug(struct _ddebug *descriptor, const char *fmt, ...);
@@ -161,6 +156,15 @@ void __dynamic_ibdev_dbg(struct _ddebug *descriptor,const struct ib_device *ibdev, const char *fmt, ...); +#endif /* CONFIG_DYNAMIC_DEBUG_CORE */ + +/* +* pr_debug() and friends are globally enabled or modules have selectively +* enabled them. +*/ +#if defined(CONFIG_DYNAMIC_DEBUG ) || \ + (defined(CONFIG_DYNAMIC_DEBUG_CORE ) && defined(DYNAMIC_DEBUG_MODULE )) +#define __dynamic_dump_stack (desc) \ { \ if (desc.flags & _DPRINTK_FLAGS_INCL_STACK) \
Signature · 1 line
2.53.0
PATCH v3 4/5 rust: print: add dynamic debug support to pr_debug!
In reply to Zhi WangFrom: Andrew Ballance <[email protected]>
Register Rust callsites in __dyndbg and use the existing C dynamic debug core for selection, prefixes, stack output and module lifetime handling. Keep the original Rust format string in the catalogue and format actual arguments through %pA, preserving the module prefix.
Keep the descriptor in static mut storage and access it through raw pointers, following the RFC v2 design. Use the nested-field static branch when jump labels are enabled; otherwise read the print flag via a C helper. Initialize every callsite as disabled, independently of Rust debug assertions, and let dynamic debug control its print state. Without dynamic debug for the crate, keep messages disabled while type-checking their arguments. Evaluate arguments only when enabled, and keep user expressions outside the macro's unsafe block. Use match scrutinees to keep formatting temporaries alive through the synchronous printing call.
Use used(compiler) for the descriptor: the GNU retain flag emitted by plain used collides with the module loader's SHF_RO_AFTER_INIT flag. Provide a host-test stub matching the existing printing macros.
Pass Kbuild's normalized module name through RUST_MODNAME for callsite identity, independently of the existing module! log prefix. Keep metadata items in a separate scope so implicit argument captures cannot be shadowed by macro-internal names.
Function names are deliberately recorded as <unknown>; module, file, line and original-format selection remain available without inferred function names or compiler-specific name extraction.
[Zhi: Rebase onto driver-core-testing; retain raw-pointer descriptor access;
revise bitfield initialization, configuration gates, Kbuild module identity, macro hygiene and synchronous printing; retain <unknown> function metadata and add maintainer routing.]
--- MAINTAINERS | 2 + rust/Makefile | 3 + rust/bindings/bindings_helper.h | 1 + rust/helpers/dynamic_debug.c | 25 +++++ rust/helpers/helpers.c | 1 + rust/kernel/print.rs | 53 +++++++-- rust/kernel/print/dynamic_debug.rs | 165 +++++++++++++++++++++++++++++ scripts/Makefile.build | 1 + scripts/generate_rust_analyzer.py | 1 + 9 files changed, 246 insertions(+), 6 deletions(-) create mode 100644 rust/helpers/dynamic_debug.c create mode 100644 rust/kernel/print/dynamic_debug.rs
MAINTAINERS +2 -0
@@ -9262,6 +9262,8 @@ S: Maintained F: include/linux/dynamic_debug.h F: lib/dynamic_debug.c F: lib/test_dynamic_debug.c +F: rust/helpers/dynamic_debug.c +F: rust/kernel/print/dynamic_debug.rs DYNAMIC INTERRUPT MODERATION M: Tal Gilboa <[email protected]>
rust/Makefile +3 -0
@@ -173,6 +173,7 @@ quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $< cmd_rustdoc = \ $(rustc_target_envs) \ OBJTREE=$(abspath $(objtree)) \ + RUST_MODNAME=$(call name-fix-token,$(subst rustdoc-,,$@)) \ $(RUSTDOC) $(filter-out $(skip_flags) --remap-path-scope=%,$(if $(rustdoc_host),$(rust_common_flags),$(rust_flags))) \ $(rustc_target_flags) -L$(objtree)/$(obj)$(if $(rustdoc_host),/host) \ -Zunstable-options --generate-link-to-definition \
@@ -388,6 +389,7 @@ quiet_cmd_rustdoc_test_kernel = RUSTDOC TK $< mkdir -p $(objtree)/$(obj)/test/doctests/kernel; \ $(rustc_target_envs) \ OBJTREE=$(abspath $(objtree)) \ + RUST_MODNAME=kernel \ $(RUSTDOC) --test $(filter-out --remap-path-scope=%,$(rust_flags)) \ -L$(objtree)/$(obj) --extern ffi --extern pin_init \ --extern kernel --extern build_error --extern macros \
@@ -647,6 +649,7 @@ quiet_cmd_rustc_library = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) L cmd_rustc_library = \ $(rustc_target_envs) \ OBJTREE=$(abspath $(objtree)) \ + RUST_MODNAME=$(call name-fix-token,$(modname)) \ $(if $(skip_clippy),$(RUSTC),$(RUSTC_OR_CLIPPY)) \ $(filter-out $(skip_flags),$(rust_flags)) $(rustc_target_flags) \ --emit=dep-info=$(depfile) --emit=$(if $(link_helper),llvm-bc=$(patsubst %.o,%.bc,$@),obj=$@) \
rust/bindings/bindings_helper.h +1 -0
@@ -54,6 +54,7 @@#include <linux/device/faux.h> #include <linux/dma-direction.h> #include <linux/dma-mapping.h> +#include <linux/dynamic_debug.h> #include <linux/dma-resv.h> #include <linux/errname.h> #include <linux/ethtool.h>
rust/helpers/dynamic_debug.c new file +25 -0
@@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/dynamic_debug.h> +#include <linux/printk.h> + +#ifdef CONFIG_DYNAMIC_DEBUG_CORE +#ifndef CONFIG_JUMP_LABEL +__rust_helper bool rust_helper_ddebug_enabled(struct _ddebug *descriptor) +{ +/* Match the C dynamic debug branch without creating a Rust reference. */ +return descriptor->flags & _DPRINTK_FLAGS_PRINT; +} +#endif + +/* The printing helpers receive Rust fmt::Arguments for the %pA bridge. */ +__rust_helper void rust_helper_ddebug_print(struct _ddebug *descriptor, +const char *prefix, +const void *args) +{ +__dynamic_pr_debug (descriptor,"%s: %pA" , prefix, args); +if (descriptor->flags & _DPRINTK_FLAGS_INCL_STACK) +dump_stack (); +} + +#endif
rust/helpers/helpers.c +1 -0
@@ -62,6 +62,7 @@#endif #include "drm.c" #include "drm_gpuvm.c" +#include "dynamic_debug.c" #include "err.c" #include "fs.c" #include "fwctl.c"
rust/kernel/print.rs +47 -6
78 lines not on this page · raw message
rust/kernel/print/dynamic_debug.rs new file +165 -0
165 lines not on this page · raw message
scripts/Makefile.build +1 -0
@@ -325,6 +325,7 @@ rust_allowed_features := arbitrary_self_types,asm_goto,generic_arg_infer,used_wi # modules case. rust_common_cmd = \ OBJTREE=$(abspath $(objtree)) \ + RUST_MODNAME=$(call name-fix-token,$(modname)) \ RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \ -Zallow-features=$(rust_allowed_features) \ -Zcrate-attr=no_std \
scripts/generate_rust_analyzer.py +1 -0
@@ -104,6 +104,7 @@ def generate_crates( edition = edition if edition is not None else "2021" crate_env = { "RUST_MODFILE": "This is only for rust-analyzer", + "RUST_MODNAME": display_name.replace("-", "_"), **crates_envs.get(display_name, {}), } return {
Signature · 1 line
2.53.0
Alice Ryhl
maintainerRe: [PATCH v3 4/5] rust: print: add dynamic debug support to pr_debug!
rust/kernel/print/dynamic_debug.rs line 23
Quoted 8 lines · Zhi Wang
rust/kernel/print/dynamic_debug.rs new file +8
-0+/// A dynamic debug callsite descriptor. +/// +/// The [`crate::dynamic_debug!`] macro places descriptors at stable addresses in `__dyndbg`. +#[repr(transparent)] +pub struct Descriptor { +/// The C descriptor, exposed for static-branch field addressing. +pub inner: bindings::_ddebug , +}
Should this be #[repr(C, align(8))] to match how C adds __aligned(8) in DEFINE_DYNAMIC_DEBUG_METADATA_CLS?
Quoted 24 lines
rust/kernel/print/dynamic_debug.rs new file +24
-0+impl Descriptor { +/// Creates an initially disabled descriptor. +pub const fn new ( + module: &'staticCStr , + file: &'staticCStr , + format: &'staticCStr , + line:u32 , + ) ->Self { +// SAFETY: `_ddebug` contains raw pointers, integers and, with jump labels, a static key. +// All accept zero; the pointers and bitfields are filled in before publication. +let mut descriptor: bindings::_ddebug =unsafe { core::mem::zeroed () }; + descriptor.modname =as_char_ptr_in_const_context (module); + descriptor.function =as_char_ptr_in_const_context (c"<unknown>" ); + descriptor.filename =as_char_ptr_in_const_context (file); + descriptor.format =as_char_ptr_in_const_context (format); + +// C packs `lineno:18`, `class_id:6` and `flags:8` into an unsigned int. Bindgen's setters +// are not const, so encode the target's bitfield ordering explicitly. Truncate line numbers +// as the C bitfield assignment does. +let line = line & ((1 <<18 ) -1 ); +let class = bindings::_DPRINTK_CLASS_DFLT; +let flags = bindings::_DPRINTK_FLAGS_NONE; +#[cfg(target_endian = "little" )] +let bits = (line | (class <<18 ) | (flags <<24 )).to_le_bytes ();
rust/kernel/print/dynamic_debug.rs line 58
Quoted 10 lines
rust/kernel/print/dynamic_debug.rs new file +10
-0+#[cfg(target_endian = "big" )] +let bits = ((line <<14 ) | (class <<8 ) | flags).to_be_bytes (); + descriptor._bitfield_1 = bindings::__BindgenBitfieldUnit::new (bits); + +#[cfg( CONFIG_JUMP_LABEL )] +// An all-zero key is `STATIC_KEY_INIT_FALSE`. +static_assert! (bindings::JUMP_TYPE_FALSE ==0 ); + +Self { inner: descriptor } + }
Two comments here:
1. Instead of hardcoding c"<unknown>" for descriptor.function, how about passing $crate::c_str!(module_path!()) from dynamic_debug! (an idea from Thomas Weißschuh's RFC series [1])? Even though Rust doesn't have a function_name!() macro, recording module_path!() makes the +f prefix flag useful and allows func queries in /proc/dynamic_debug/control to filter by Rust module path within a multi-file crate.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
2. The inline bitfield manipulation and unsafe { core::mem::zeroed() } is pretty ugly. Please use the same strategy as FamilyFlags in rust/kernel/net/netlink.rs to handle bitfields in const context:
- Move the bitfield construction into a dedicated helper struct with a
`const fn into_bitfield(self) -> bindings::__BindgenBitfieldUnit<[u8; 4]>`
method. - Construct bindings::_ddebug directly using struct literal syntax with ..pin_init::zeroed(), avoiding unsafe { core::mem::zeroed() } and field-by-field mutation.
- Add a kunit test (like test_family_flags_bitfield) that verifies into_bitfield() against bindgen's generated set_lineno, set_class_id, and set_flags (or bindings::_ddebug::new_bitfield_1).
Quoted 8 lines
rust/kernel/print/dynamic_debug.rs new file +8
-0+/// Prints arguments with the crate's log prefix and the dynamic debug prefixes. +/// +/// # Safety +/// +/// `descriptor` must point to an initialized descriptor valid for this call, whose string +/// pointers refer to valid NUL-terminated C strings. Concurrent access must follow the C +/// dynamic debug and jump label synchronization rules, without conflicting Rust accesses. +pub unsafe fn mut Self , prefix: &CStr , args: fmt::Arguments <'_>) {
rust/kernel/print/dynamic_debug.rs line 92
Quoted 10 lines
rust/kernel/print/dynamic_debug.rs new file +10
-0+// SAFETY: The descriptor is valid by the caller's guarantee. The helper uses the C string +// `prefix` and consumes `args` through `%pA` synchronously, so their borrows remain valid. +unsafe { + bindings::ddebug_print ( + &raw mut (*descriptor).inner, + prefix.as_char_ptr (), + core::ptr::from_ref (&args).cast (), + ) + }; + }
Descriptor::print (and Descriptor::dev_print in patch 5/5) should be marked #[inline], just like Descriptor::enabled.
Quoted 5 lines
rust/kernel/print/dynamic_debug.rs new file +5
-0+macro_rules! dynamic_debug { + ($descriptor:ident, ($($arg:tt)*), $body:block) => {{ +// Keep item names out of the user's scope, including implicit format captures. +let (descriptor, enabled) = { +// `used(compiler)` avoids `SHF_GNU_RETAIN`, which the module loader interprets as
rust/kernel/print/dynamic_debug.rs line 128
Quoted 10 lines
rust/kernel/print/dynamic_debug.rs new file +10
-0+// `SHF_RO_AFTER_INIT`. +#[used(compiler)] +#[unsafe(link_section = "__dyndbg" )] +static mut DESCRIPTOR : $crate::print::dynamic_debug::Descriptor = + $crate::print::dynamic_debug::Descriptor ::new ( + $crate::c_str!(env! ("RUST_MODNAME" )), + $crate::c_str!(file! ()), + $crate::dynamic_debug_format!($($arg)*), +line! (), + );
Is #[used(compiler)] needed here at all?
When the pr_debug! / dev_dbg! statement is reachable, DESCRIPTOR is already referenced by static_branch_unlikely!(DESCRIPTOR, ...) and by &raw mut DESCRIPTOR passed to Descriptor::print. And if the callsite is optimized out (for example, inside an unused function or dead branch), we *want* the static DESCRIPTOR to be deleted as well rather than leaving an orphan entry in __dyndbg. This would match C's DEFINE_DYNAMIC_DEBUG_METADATA_CLS, which does not use __used.
For instance, with #[used(compiler)] present, the uncalled fn example in the dev_dbg! doctest still emits a dead DESCRIPTOR into vmlinux's __dyndbg section.
rust/kernel/print/dynamic_debug.rs line 165
Quoted 8 lines
rust/kernel/print/dynamic_debug.rs new file +8
-0+/// Stub for host doctests, matching [`crate::print_macro!`]. +#[cfg(testlib)] +#[macro_export] +macro_rules! dynamic_debug { + ($descriptor:ident, ($($arg:tt)*), $body:block) => { + () + }; +}
If dynamic_debug! drops $body under #[cfg(testlib)], any variables used only inside pr_debug! or dev_dbg! will trigger unused_variables warnings under testlib, and $body won't be type-checked. How about:
if false {
let $descriptor: *mut $crate::print::dynamic_debug::Descriptor =
::core::ptr::null_mut();
$body
}Alice
Re: [PATCH v3 4/5] rust: print: add dynamic debug support to pr_debug!
On Fri, 16 Oct 2026 08:50:44 +0000
Alice Ryhl <[email protected]> wrote:
Hey Alice,
Thanks for the detailed review. My comments are below.
Quoted 5 lines · Zhi Wang
Quoted 4 lines
rust/kernel/print/dynamic_debug.rs new file +3
-0+/// A dynamic debug callsite descriptor. +/// +/// The [`crate::dynamic_debug!`] macro places descriptors at stable addresses in
__dyndbg. +#[repr(transparent)]
Quoted 9 lines
Review
Quoted 5 lines
(quoted diff) +2
-0+pub struct Descriptor { + /// The C descriptor, exposed for static-branch fieldaddressing.
(quoted diff) +2
-0+ pub inner: bindings::_ddebug, +}Should this be #[repr(C, align(8))] to match how C adds
__aligned(8)inDEFINE_DYNAMIC_DEBUG_METADATA_CLS?
IMHO, I guess this should be already aligned(8), looks like the repr(transparent) also inherit the alignment from the bindings? [1] I agree making it explicit looking better for readability.
[1]
https://doc.rust-lang.org/reference/type-layout.html#r-layout.repr.transparent.layout-abi
Quoted 8 lines
Quoted 8 lines
rust/kernel/print/dynamic_debug.rs new file +8
-0+impl Descriptor { +/// Creates an initially disabled descriptor. +pub const fn new ( + module: &'staticCStr , + file: &'staticCStr , + format: &'staticCStr , + line:u32 , + ) ->Self {
...snip...
Quoted 29 lines
Review
Quoted 2 lines
(quoted diff) +2
-0+ Self { inner: descriptor } + }Two comments here:
1. Instead of hardcoding
c"<unknown>"fordescriptor.function, how about passing$crate::c_str!(module_path!())fromdynamic_debug!(an idea from Thomas Weißschuh's RFC series [1])? Even though Rust doesn't have afunction_name!()macro, recordingmodule_path!()makes the+fprefix flag useful and allowsfuncqueries in/proc/dynamic_debug/controlto filter by Rust module path within a multi-file crate.[1]https://lore.kernel.org/rust-for-linux/[email protected]/
2. The inline bitfield manipulation and
unsafe { core::mem::zeroed() }is pretty ugly. Please use the same strategy asFamilyFlagsinrust/kernel/net/netlink.rsto handle bitfields inconst
context:- Move the bitfield construction into a dedicated helper struct
with aconst fn into_bitfield(self) -> bindings::__BindgenBitfieldUnit<[u8; 4]>method.
- Constructbindings::_ddebugdirectly using struct literal
syntax with..pin_init::zeroed(), avoidingunsafe { core::mem::zeroed() }and field-by-field mutation.
- Add a kunit test (liketest_family_flags_bitfield) that
verifiesinto_bitfield()against bindgen's generatedset_lineno,
Quoted 3 lines
`set_class_id`, and `set_flags` (or
bindings::_ddebug::new_bitfield_1).
Thanks so much for the detailed suggestions! I will try to see how to cope these with the combined patches with Thomas.
Quoted 2 lines
Quoted 2 lines
+ /// Prints arguments with the crate's log prefix and the
dynamic debug prefixes.
...snip...
Quoted 29 lines
Quoted 12 lines
rust/kernel/print/dynamic_debug.rs new file +3
-0+macro_rules! dynamic_debug { + ($descriptor:ident, ($($arg:tt)*), $body:block) => {{ +// Keep item names out of the user's scope, including implicit format captures.
(quoted diff) +2
-0+ let (descriptor, enabled) = { + // `used(compiler)` avoids `SHF_GNU_RETAIN`, which themodule loader interprets as
rust/kernel/print/dynamic_debug.rs new file +4
-0+// `SHF_RO_AFTER_INIT`. +#[used(compiler)] +#[unsafe(link_section = "__dyndbg" )] + static mut DESCRIPTOR:$crate::print::dynamic_debug::Descriptor =
rust/kernel/print/dynamic_debug.rs line 128
Quoted 6 lines
rust/kernel/print/dynamic_debug.rs new file +6
-0+ $crate::print::dynamic_debug::Descriptor ::new ( + $crate::c_str!(env! ("RUST_MODNAME" )), + $crate::c_str!(file! ()), + $crate::dynamic_debug_format!($($arg)*), +line! (), + );Is
#[used(compiler)]needed here at all?When the
pr_debug!/dev_dbg!statement is reachable,DESCRIPTORis already referenced bystatic_branch_unlikely!(DESCRIPTOR, ...)and by&raw mut DESCRIPTORpassed toDescriptor::print. And if the callsite is optimized out (for example, inside an unused function or dead branch), we *want* the staticDESCRIPTORto be deleted as well rather than leaving an orphan entry in__dyndbg. This would match C'sDEFINE_DYNAMIC_DEBUG_METADATA_CLS, which does not use__used.
Quoted 4 lines
For instance, with
#[used(compiler)]present, the uncalledfn examplein thedev_dbg!doctest still emits a deadDESCRIPTORintovmlinux's__dyndbgsection.
I see. Thanks for the detailed explanation. I am thinking if we can remove #[used] here? This is originally from Andrew's patch and causes kernel write fault when I try to enable the dynamic debug prints. I also see Thomas' patch is using used(compiler) [2], guess he might encounter the same problem.
My problem is my rustc/LLVM (rustc 1.94.0/LLVM 21.1.8) generates this symbol as SHF_GNU_RETAIN in the .ko when with #[used] and Linux kernel module loader explains this to SHF_RO_AFTER_INIT, then write fault is triggered when enabling the print...
[2]
https://lore.kernel.org/rust-for-linux/[email protected]/
Quoted 21 lines
rust/kernel/print/dynamic_debug.rs line 165
Quoted 8 lines
rust/kernel/print/dynamic_debug.rs new file +8
-0+/// Stub for host doctests, matching [`crate::print_macro!`]. +#[cfg(testlib)] +#[macro_export] +macro_rules! dynamic_debug { + ($descriptor:ident, ($($arg:tt)*), $body:block) => { + () + }; +}If
dynamic_debug!drops$bodyunder#[cfg(testlib)], any variables used only insidepr_debug!ordev_dbg!will triggerunused_variableswarnings undertestlib, and$bodywon't be type-checked. How about:if false {
let $descriptor: *mut$crate::print::dynamic_debug::Descriptor = ::core::ptr::null_mut(); $body }Alice
PATCH v3 5/5 rust: device: add dynamic debug support to dev_dbg!
In reply to Zhi WangFrom: Andrew Ballance <[email protected]>
Use Rust dynamic debug descriptors for dev_dbg! under DYNAMIC_DEBUG, or DYNAMIC_DEBUG_CORE with a per-crate DYNAMIC_DEBUG_MODULE opt-in. Route output through __dynamic_dev_dbg to retain device information and the standard dynamic debug prefix controls.
Evaluate both the device expression and formatting arguments only when the callsite is enabled. Calls start disabled and are controlled only by dynamic debug. Without dynamic debug for the crate, type-check the arguments without evaluating or printing them. Debug assertions no longer control either path.
Make direct Device::pr_dbg() calls unconditional, like the other level methods; callers needing callsite control and lazy evaluation use dev_dbg!. No in-tree direct callers need conversion.
Document configuration, module selection and the explicit function-name and embedded-NUL limitations.
[Zhi: Rebase onto driver-core-testing; use the revised descriptor and
printing bridge; keep device and argument evaluation conditional in both dynamic and fallback paths; keep caller expressions outside unsafe blocks while retaining their temporaries through each printing call.]
--- .../admin-guide/dynamic-debug-howto.rst | 41 ++++++++++++++++++ rust/helpers/dynamic_debug.c | 8 ++++ rust/kernel/device.rs | 42 +++++++++++++++---- rust/kernel/print/dynamic_debug.rs | 27 ++++++++++++ 4 files changed, 110 insertions(+), 8 deletions(-)
Documentation/admin-guide/dynamic-debug-howto.rst +41 -0
@@ -390,3 +390,44 @@ just a shortcut for ``print_hex_dump(KERN_DEBUG)``. For ``print_hex_dump_debug()``/``print_hex_dump_bytes()``, format string is its ``prefix_str`` argument, if it is constant string; or ``hexdump`` in case ``prefix_str`` is built dynamically. + +Rust printing macros +==================== + +Rust ``pr_debug!`` and ``dev_dbg!`` use the same control file and boot or +module parameters as their C counterparts. With ``CONFIG_DYNAMIC_DEBUG=y``, +their callsites are initially disabled and can be enabled at runtime or +through boot and module parameters. Rust's ``debug_assertions`` setting +does not affect debug logging. + +With only ``CONFIG_DYNAMIC_DEBUG_CORE=y``, select the Rust crates to include +in the catalogue using their Kbuild Rust flags, for example:: + + RUSTFLAGS_my_driver.o += --cfg DYNAMIC_DEBUG_MODULE + +Without dynamic debug for a crate, its ``pr_debug!`` and ``dev_dbg!`` calls +stay disabled. Disabled calls do not evaluate their formatting arguments +or device expressions, but their arguments are still checked at compile +time. Keep required work and error handling outside those expressions. + +Rust callsites support the ``module``, ``file``, ``line`` and ``format`` +selectors. The module is the name supplied by Kbuild, including for callsites +in nested Rust modules. Hyphens in this name become underscores, just as for C +callsites. This name is independent of the prefix printed by ``pr_debug!``, +which continues to use the name declared in ``module!``. The format is the +original Rust format string, with ``{}`` placeholders, rather than the C +``%pA`` formatting bridge. +An embedded NUL ends the catalogue's copy of the format string; Rust +formatting still uses the full string. + +Automatic Rust function names are not provided. The function field contains +``<unknown>``, which is also what the ``f`` prefix flag displays. Use the +other selectors to select Rust callsites; ``func`` cannot distinguish Rust +functions. Rust callsites use the default, unclassified debug class. + +For example, to control a module named ``my_driver`` at load time or while +it is running:: + + modprobe my_driver dyndbg=+p + echo 'module my_driver -p' > /proc/dynamic_debug/control + echo 'module my_driver +p' > /proc/dynamic_debug/control
rust/helpers/dynamic_debug.c +8 -0
@@ -22,4 +22,12 @@ __rust_helper void rust_helper_ddebug_print(struct _ddebug *descriptor,dump_stack (); } +__rust_helper void rust_helper_ddebug_dev_print(struct _ddebug *descriptor, +const struct device *dev, +const void *args) +{ +__dynamic_dev_dbg (descriptor, dev,"%pA" , args); +if (descriptor->flags & _DPRINTK_FLAGS_INCL_STACK) +dump_stack (); +}#endif
rust/kernel/device.rs +34 -8
66 lines not on this page · raw message
rust/kernel/print/dynamic_debug.rs +27 -0
@@ -8,6 +8,10 @@//! discovers them at boot or module load and removes them before the module is freed. use crate ::{ + device::{ +Device , +DeviceContext ,// + }, fmt, prelude::*, str::as_char_ptr_in_const_context,//
@@ -90,6 +94,29 @@ pub unsafe fn print(descriptor: *mut Self, prefix: &CStr, args: fmt::Arguments<' ) }; } + +/// Prints arguments with device information and the dynamic debug prefixes. +/// +/// # Safety +/// +/// `descriptor` must point to an initialized descriptor valid for this call, whose string +/// pointers refer to valid NUL-terminated C strings. Concurrent access must follow the C +/// dynamic debug and jump label synchronization rules, without conflicting Rust accesses. +pub unsafe fn dev_print <Ctx :DeviceContext >( + descriptor: *mut Self , + dev: &Device <Ctx >, + args: fmt::Arguments <'_>, + ) { +// SAFETY: The descriptor is valid by the caller's guarantee and `dev` is alive for this +// call. The helper consumes the `%pA` arguments synchronously without retaining them. +unsafe { + bindings::ddebug_dev_print ( + &raw mut (*descriptor).inner, + dev.as_raw (), + core::ptr::from_ref (&args).cast (), + ) + }; + } }/// Extracts only the format string for the callsite catalogue.
Signature · 1 line
2.53.0
Alice Ryhl
maintainerRe: [PATCH v3 5/5] rust: device: add dynamic debug support to dev_dbg!
rust/helpers/dynamic_debug.c __rust_helper void rust_helper_ddebug_print(struct _ddebug *descriptor, · line 32
Quoted 8 lines · Zhi Wang
rust/helpers/dynamic_debug.c +8
-0+__rust_helper void rust_helper_ddebug_dev_print(struct _ddebug *descriptor, +const struct device *dev, +const void *args) +{ +__dynamic_dev_dbg (descriptor, dev,"%pA" , args); +if (descriptor->flags & _DPRINTK_FLAGS_INCL_STACK) +dump_stack (); +}
Nit (also applies to rust_helper_ddebug_print in patch 4/5): if patch 3/5 also exposes __dynamic_dump_stack under #ifdef CONFIG_DYNAMIC_DEBUG_CORE, both helpers can use __dynamic_dump_stack((*descriptor)) instead of open-coding the _DPRINTK_FLAGS_INCL_STACK check.
rust/kernel/print/dynamic_debug.rs pub unsafe fn print(descriptor: *mut Self, prefix: &CStr, args: fmt::Arguments<' · line 109
Quoted 5 lines
rust/kernel/print/dynamic_debug.rs +5
-0+pub unsafe fn dev_print <Ctx :DeviceContext >( + descriptor: *mut Self , + dev: &Device <Ctx >, + args: fmt::Arguments <'_>, + ) {
Please add #[inline] here too.
Alice
On Thu, 1 Oct 2026 17:59:35 +0300
Zhi Wang <[email protected]> wrote:
Gentle Ping. :)
Quoted 65 lines
Add runtime dynamic debug control to Rust
pr_debug! anddev_dbg!, using the existing C control file, boot/module parameters, prefixes and jump labels. Callsite flags and static keys always start disabled. Users enable messages with dyndbg queries; Rust debug assertions do not affect whether a debug message is printed.This continues Andrew Ballance's RFC v2:
https://lore.kernel.org/rust-for-linux/[email protected]/This revision retains RFC v2's nested-field static-branch macros and static mut descriptors addressed through raw pointers.
Changes since RFC v2:
- Make debug logging independent of Rust's
debug_assertionssetting. Bothpr_debug! anddev_dbg! start disabled and are enabled through dyndbg; without dynamic debug support, both remain disabled.
- Keep caller expressions outside unsafe blocks and avoid implicit Rust references when reading descriptor flags without jump labels.
- Correct big-endian bitfield layout and keep module descriptors writable with #[used(compiler)]. This fixes the kernel write fault whenstatic_key_enable_cpuslocked()tries to write the static key.
- UseKbuildmodule names and actual format strings for filtering, preserve the crate log prefix, and support +d stack output.
- Complete DYNAMIC_DEBUG_CORE-only support with per-crate opt-in.
- Port to driver-core-testing and preserve Nova's firmware validation when debug logging is disabled.Limitations:
- Function metadata deliberately remains <unknown>;
Andrew Ballance (3):
rust: jump label: add support for nested arguments
rust: print: add dynamic debug support topr_debug!
rust: device: add dynamic debug support todev_dbg!Zhi Wang (2):
gpu: nova-core: validate firmware versions before debug logging
dynamic_debug: expose printing declarations with the core enabled.../admin-guide/dynamic-debug-howto.rst | 41 ++++ MAINTAINERS | 2 + drivers/gpu/nova-core/firmware/booter.rs | 8 +- drivers/gpu/nova-core/firmware/fsp.rs | 3 +- .../nova-core/firmware/fwsec/bootloader.rs | 7 +- drivers/gpu/nova-core/firmware/gsp.rs | 3 +- drivers/gpu/nova-core/firmware/riscv.rs | 7 +- include/linux/dynamic_debug.h | 16 +- rust/Makefile | 3 + rust/bindings/bindings_helper.h | 1 + rust/helpers/dynamic_debug.c | 33 +++ rust/helpers/helpers.c | 1 + rust/kernel/device.rs | 42 +++- rust/kernel/jump_label.rs | 17 +- rust/kernel/print.rs | 53 ++++- rust/kernel/print/dynamic_debug.rs | 192 ++++++++++++++++++ scripts/Makefile.build | 1 + scripts/generate_rust_analyzer.py | 1 + 18 files changed, 386 insertions(+), 45 deletions(-) create mode 100644 rust/helpers/dynamic_debug.c create mode 100644 rust/kernel/print/dynamic_debug.rsbase-commit:
f1850e443b0e4f2429ddf42a8d5033ea54ae8a90