1 // SPDX-License-Identifier: GPL-2.0
2
3 //! Rust printing macros sample.
4
5 use kernel::pr_cont;
6 use kernel::prelude::*;
7
8 module! {
9 type: RustPrint,
10 name: "rust_print",
11 author: "Rust for Linux Contributors",
12 description: "Rust printing macros sample",
13 license: "GPL",
14 }
15
16 struct RustPrint;
17
18 #[expect(clippy::disallowed_macros)]
arc_print() -> Result19 fn arc_print() -> Result {
20 use kernel::sync::*;
21
22 let a = Arc::new(1, GFP_KERNEL)?;
23 let b = UniqueArc::new("hello, world", GFP_KERNEL)?;
24
25 // Prints the value of data in `a`.
26 pr_info!("{}", a);
27
28 // Uses ":?" to print debug fmt of `b`.
29 pr_info!("{:?}", b);
30
31 let a: Arc<&str> = b.into();
32 let c = a.clone();
33
34 // Uses `dbg` to print, will move `c` (for temporary debugging purposes).
35 dbg!(c);
36
37 // Pretty-prints the debug formatting with lower-case hexadecimal integers.
38 pr_info!("{:#x?}", a);
39
40 Ok(())
41 }
42
43 impl kernel::Module for RustPrint {
init(_module: &'static ThisModule) -> Result<Self>44 fn init(_module: &'static ThisModule) -> Result<Self> {
45 pr_info!("Rust printing macros sample (init)\n");
46
47 pr_emerg!("Emergency message (level 0) without args\n");
48 pr_alert!("Alert message (level 1) without args\n");
49 pr_crit!("Critical message (level 2) without args\n");
50 pr_err!("Error message (level 3) without args\n");
51 pr_warn!("Warning message (level 4) without args\n");
52 pr_notice!("Notice message (level 5) without args\n");
53 pr_info!("Info message (level 6) without args\n");
54
55 pr_info!("A line that");
56 pr_cont!(" is continued");
57 pr_cont!(" without args\n");
58
59 pr_emerg!("{} message (level {}) with args\n", "Emergency", 0);
60 pr_alert!("{} message (level {}) with args\n", "Alert", 1);
61 pr_crit!("{} message (level {}) with args\n", "Critical", 2);
62 pr_err!("{} message (level {}) with args\n", "Error", 3);
63 pr_warn!("{} message (level {}) with args\n", "Warning", 4);
64 pr_notice!("{} message (level {}) with args\n", "Notice", 5);
65 pr_info!("{} message (level {}) with args\n", "Info", 6);
66
67 pr_info!("A {} that", "line");
68 pr_cont!(" is {}", "continued");
69 pr_cont!(" with {}\n", "args");
70
71 arc_print()?;
72
73 trace::trace_rust_sample_loaded(42);
74
75 Ok(RustPrint)
76 }
77 }
78
79 impl Drop for RustPrint {
drop(&mut self)80 fn drop(&mut self) {
81 pr_info!("Rust printing macros sample (exit)\n");
82 }
83 }
84
85 mod trace {
86 use core::ffi::c_int;
87
88 kernel::declare_trace! {
89 /// # Safety
90 ///
91 /// Always safe to call.
92 unsafe fn rust_sample_loaded(magic: c_int);
93 }
94
trace_rust_sample_loaded(magic: i32)95 pub(crate) fn trace_rust_sample_loaded(magic: i32) {
96 // SAFETY: Always safe to call.
97 unsafe { rust_sample_loaded(magic as c_int) }
98 }
99 }
100