From 9d527c7e7b9c539b29e7a2d3728ac739e790dd81 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Tue, 10 May 2022 17:41:19 +0200 Subject: [PATCH 01/25] rust: device: fix commit reference style Signed-off-by: Miguel Ojeda --- rust/kernel/device.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs index 51974b80ba587b..c37f555c534d0b 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -31,8 +31,9 @@ use crate::c_str; /// related to `self`, that is, actions on it will affect `self`. For example, if one calls /// `get_device`, then the refcount on the device represented by `self` will be incremented. /// -/// Additionally, implementers must ensure that the device is never renamed. Commit a5462516aa994 -/// has details on why `device_rename` should not be used. +/// Additionally, implementers must ensure that the device is never renamed. Commit a5462516aa99 +/// ("driver-core: document restrictions on device_rename()") has details on why `device_rename` +/// should not be used. pub unsafe trait RawDevice { /// Returns the raw `struct device` related to `self`. fn raw_device(&self) -> *mut bindings::device; From 919ce3f185c866f475d589432c1bdfd9af320797 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Fri, 22 Jul 2022 23:18:42 +0200 Subject: [PATCH 02/25] rust: kernel: sort `feature`s Signed-off-by: Miguel Ojeda --- rust/kernel/lib.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index e0aa70f1364354..c5f62f9d6fc56e 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -14,20 +14,20 @@ #![no_std] #![feature(allocator_api)] #![feature(associated_type_defaults)] +#![feature(coerce_unsized)] #![feature(const_mut_refs)] #![feature(const_ptr_offset_from)] #![feature(const_refs_to_cell)] #![feature(const_trait_impl)] #![feature(core_ffi_c)] #![feature(c_size_t)] +#![feature(dispatch_from_dyn)] #![feature(doc_cfg)] +#![feature(duration_constants)] #![feature(generic_associated_types)] #![feature(ptr_metadata)] #![feature(receiver_trait)] -#![feature(coerce_unsized)] -#![feature(dispatch_from_dyn)] #![feature(unsize)] -#![feature(duration_constants)] // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling. From 2119a6e023e60b61fa5772050b069cdb1fa2f85d Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Fri, 22 Jul 2022 23:24:16 +0200 Subject: [PATCH 03/25] rust: kernel: use `# Examples` consistently In other words, the plural form, even if there is a single example. Signed-off-by: Miguel Ojeda --- rust/kernel/lib.rs | 4 ++-- rust/kernel/module_param.rs | 2 +- rust/kernel/sync.rs | 2 +- rust/kernel/sync/locked_by.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index c5f62f9d6fc56e..306d54ac4243ff 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -194,7 +194,7 @@ impl<'a> Drop for KParamGuard<'a> { /// Calculates the offset of a field from the beginning of the struct it belongs to. /// -/// # Example +/// # Examples /// /// ``` /// # use kernel::prelude::*; @@ -232,7 +232,7 @@ macro_rules! offset_of { /// as opposed to a pointer to another object of the same type. If this condition is not met, /// any dereference of the resulting pointer is UB. /// -/// # Example +/// # Examples /// /// ``` /// # use kernel::container_of; diff --git a/rust/kernel/module_param.rs b/rust/kernel/module_param.rs index 5c99fb8e63fda7..bf8f74bdd3a628 100644 --- a/rust/kernel/module_param.rs +++ b/rust/kernel/module_param.rs @@ -210,7 +210,7 @@ macro_rules! impl_module_param { #[macro_export] /// Generate a static [`kernel_param_ops`](../../../include/linux/moduleparam.h) struct. /// -/// # Example +/// # Examples /// ```ignore /// make_param_ops!( /// /// Documentation for new param ops. diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index da96e9d712197a..255a4928a47ae9 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -5,7 +5,7 @@ //! This module contains the kernel APIs related to synchronisation that have been ported or //! wrapped for usage by Rust code in the kernel and is shared by all of them. //! -//! # Example +//! # Examples //! //! ``` //! # use kernel::mutex_init; diff --git a/rust/kernel/sync/locked_by.rs b/rust/kernel/sync/locked_by.rs index 334935fb1e37c7..2dc6e3a77420b5 100644 --- a/rust/kernel/sync/locked_by.rs +++ b/rust/kernel/sync/locked_by.rs @@ -15,7 +15,7 @@ use core::{cell::UnsafeCell, ops::Deref, ptr}; /// [`LockedBy`] wraps the data in lieu of another locking primitive, and only allows access to it /// when the caller shows evidence that 'external' lock is locked. /// -/// # Example +/// # Examples /// /// The following is an example for illustrative purposes: `InnerDirectory::bytes_used` is an /// aggregate of all `InnerFile::bytes_used` and must be kept consistent; so we wrap `InnerFile` in From a283c6a4e080a10fc4bb9bbf2baca9d8f0fa7caa Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Fri, 22 Jul 2022 23:29:09 +0200 Subject: [PATCH 04/25] rust: kernel: fix non-empty lines after section headers Signed-off-by: Miguel Ojeda --- rust/kernel/build_assert.rs | 1 + rust/kernel/fs/param.rs | 1 + rust/kernel/module_param.rs | 1 + 3 files changed, 3 insertions(+) diff --git a/rust/kernel/build_assert.rs b/rust/kernel/build_assert.rs index 18cffec7d03723..72c533d8058d8a 100644 --- a/rust/kernel/build_assert.rs +++ b/rust/kernel/build_assert.rs @@ -9,6 +9,7 @@ /// be called, a build error will be triggered. /// /// # Examples +/// /// ``` /// # use kernel::build_error; /// #[inline] diff --git a/rust/kernel/fs/param.rs b/rust/kernel/fs/param.rs index 9e64ea9db64877..434e99a2996340 100644 --- a/rust/kernel/fs/param.rs +++ b/rust/kernel/fs/param.rs @@ -434,6 +434,7 @@ macro_rules! count_brace_items { /// Defines the file system parameters of a given file system context. /// /// # Examples +/// /// ``` /// # use kernel::prelude::*; /// # use kernel::{c_str, fs, str::CString}; diff --git a/rust/kernel/module_param.rs b/rust/kernel/module_param.rs index bf8f74bdd3a628..6df38c78c65c0b 100644 --- a/rust/kernel/module_param.rs +++ b/rust/kernel/module_param.rs @@ -211,6 +211,7 @@ macro_rules! impl_module_param { /// Generate a static [`kernel_param_ops`](../../../include/linux/moduleparam.h) struct. /// /// # Examples +/// /// ```ignore /// make_param_ops!( /// /// Documentation for new param ops. From 166e870463ce51d9ae849ce8719e88ba5f96da20 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 23 Jul 2022 17:36:12 +0200 Subject: [PATCH 05/25] rust: macros: fix commit reference style Signed-off-by: Miguel Ojeda --- rust/macros/module.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/macros/module.rs b/rust/macros/module.rs index 75b9cbca2e86dc..edf37c38a08e86 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -431,7 +431,7 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { // Note: the C macro that generates the static structs for the `__param` section // asks for them to be `aligned(sizeof(void *))`. However, that was put in place - // in 2003 in commit 38d5b085d2 (\"[PATCH] Fix over-alignment problem on x86-64\") + // in 2003 in commit 38d5b085d2a0 (\"[PATCH] Fix over-alignment problem on x86-64\") // to undo GCC over-alignment of static structs of >32 bytes. It seems that is // not the case anymore, so we simplify to a transparent representation here // in the expectation that it is not needed anymore. From 748dfa5f65f2aed7a4dc481d16b659c0b1bc9318 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 23 Jul 2022 17:37:40 +0200 Subject: [PATCH 06/25] rust: kernel: use Markdown in comment Signed-off-by: Miguel Ojeda --- rust/kernel/delay.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/delay.rs b/rust/kernel/delay.rs index d28d45ec2e57f0..150287b4ffa112 100644 --- a/rust/kernel/delay.rs +++ b/rust/kernel/delay.rs @@ -52,7 +52,7 @@ fn coarse_sleep_conversion(duration: Duration) -> core::ffi::c_uint { /// coarse_sleep(Duration::new(1, 2)); // Equivalent to `msleep(1001)`. /// ``` pub fn coarse_sleep(duration: Duration) { - // SAFETY: msleep is safe for all values of an `unsigned int`. + // SAFETY: `msleep` is safe for all values of an `unsigned int`. unsafe { bindings::msleep(coarse_sleep_conversion(duration)) } } From c082e831682b1790ff409181efb29b0cc3c963ed Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 23 Jul 2022 17:38:20 +0200 Subject: [PATCH 07/25] rust: kernel: simplify comment to avoid mentioning the type Signed-off-by: Miguel Ojeda --- rust/kernel/delay.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/delay.rs b/rust/kernel/delay.rs index 150287b4ffa112..1e987fa659419b 100644 --- a/rust/kernel/delay.rs +++ b/rust/kernel/delay.rs @@ -52,7 +52,7 @@ fn coarse_sleep_conversion(duration: Duration) -> core::ffi::c_uint { /// coarse_sleep(Duration::new(1, 2)); // Equivalent to `msleep(1001)`. /// ``` pub fn coarse_sleep(duration: Duration) { - // SAFETY: `msleep` is safe for all values of an `unsigned int`. + // SAFETY: `msleep` is safe for all values of its argument. unsafe { bindings::msleep(coarse_sleep_conversion(duration)) } } From e800a0fca49a55bc0aa637b3c292f9b1be0b0aa2 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Tue, 26 Jul 2022 15:06:56 +0200 Subject: [PATCH 08/25] rust: fix English typos found by `checkpatch.pl` Signed-off-by: Miguel Ojeda --- rust/kernel/workqueue.rs | 4 ++-- rust/macros/lib.rs | 2 +- rust/macros/vtable.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 78554aee53f036..68faa8e5f58b56 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -129,7 +129,7 @@ macro_rules! init_work_item_adapter { /// ``` /// /// The following example is used to create a work item and enqueue it several times. We note that -/// enqueing while the work item is already queued is a no-op, so we enqueue it when it is not +/// enqueuing while the work item is already queued is a no-op, so we enqueue it when it is not /// enqueued yet. /// /// ``` @@ -420,7 +420,7 @@ impl BoxedQueue { /// /// # Safety /// - /// `ptr` must be non-null and valid. Additionaly, ownership must be handed over to new + /// `ptr` must be non-null and valid. Additionally, ownership must be handed over to new /// instance of [`BoxedQueue`]. unsafe fn new(ptr: *mut bindings::workqueue_struct) -> Self { Self { diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 4f1b44b23e7593..cf02b441619c61 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -106,7 +106,7 @@ pub fn module(ts: TokenStream) -> TokenStream { /// This attribute is intended to close the gap. Traits can be declared and /// implemented with the `#[vtable]` attribute, and a `HAS_*` associated constant /// will be generated for each method in the trait, indicating if the implementor -/// has overriden a method. +/// has overridden a method. /// /// This attribute is not needed if all methods are required. /// diff --git a/rust/macros/vtable.rs b/rust/macros/vtable.rs index 1ab64bade873e3..98340ea0af5fef 100644 --- a/rust/macros/vtable.rs +++ b/rust/macros/vtable.rs @@ -66,7 +66,7 @@ pub(crate) fn vtable(_attr: TokenStream, ts: TokenStream) -> TokenStream { // so we have to generate a const for all methods. write!( const_items, - "/// Indicates if the `{f}` method is overriden by the implementor. + "/// Indicates if the `{f}` method is overridden by the implementor. const {gen_const_name}: bool = false;", ) .unwrap(); From 0f01f0d508c6932efd760e46886f3ce9400106f1 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Tue, 26 Jul 2022 15:18:00 +0200 Subject: [PATCH 09/25] rust: helpers: sort `#include`s Signed-off-by: Miguel Ojeda --- rust/helpers.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/helpers.c b/rust/helpers.c index b5c4133d91eb71..bf790f46c76317 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -38,7 +39,6 @@ #include #include #include -#include __noreturn void rust_helper_BUG(void) { From 72b2a9cb8865918385f91cd35d032d7fd8b3f6be Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Tue, 26 Jul 2022 15:21:45 +0200 Subject: [PATCH 10/25] rust: bindings: sort `#include`s Signed-off-by: Miguel Ojeda --- rust/bindings/bindings_helper.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 214cff169137c0..284793085d5530 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -36,7 +37,6 @@ #include #include #include -#include /* `bindgen` gets confused at certain things. */ const gfp_t BINDINGS_GFP_KERNEL = GFP_KERNEL; From 3dd99ebee84cf2f6f42c735f9d9a94592f18c7df Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Tue, 26 Jul 2022 15:27:48 +0200 Subject: [PATCH 11/25] rust: exports: remove trailing semicolon in macro This deals with the `checkpatch.pl` warning: ```txt WARNING: macros should not use a trailing semicolon +#define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym); ``` Signed-off-by: Miguel Ojeda --- rust/exports.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/exports.c b/rust/exports.c index 43c6ee7d98e5fa..bb7cc64cecd0dd 100644 --- a/rust/exports.c +++ b/rust/exports.c @@ -13,7 +13,7 @@ #include -#define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym); +#define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym) #include "exports_core_generated.h" #include "exports_alloc_generated.h" From c5ce2c4d8794db3e1ddede5a3c45d21762c2092d Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Thu, 28 Jul 2022 13:38:23 +0200 Subject: [PATCH 12/25] locking/spinlock: add tabs to reduce patch size This also makes it more consistent to the other patch we are sending. Signed-off-by: Miguel Ojeda --- include/linux/spinlock.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/include/linux/spinlock.h b/include/linux/spinlock.h index cdcbf9d9c70c70..27df5380c1e42d 100644 --- a/include/linux/spinlock.h +++ b/include/linux/spinlock.h @@ -338,11 +338,11 @@ static inline void __spin_lock_init(spinlock_t *lock, const char *name, __raw_spin_lock_init(spinlock_check(lock), name, key, LD_WAIT_CONFIG); } -# define spin_lock_init(lock) \ -do { \ - static struct lock_class_key __key; \ - \ - __spin_lock_init(lock, #lock, &__key); \ +# define spin_lock_init(lock) \ +do { \ + static struct lock_class_key __key; \ + \ + __spin_lock_init(lock, #lock, &__key); \ } while (0) #else From 94c0961329a52b297a8314e6d085ea8cb0024882 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Wed, 27 Jul 2022 13:30:53 +0200 Subject: [PATCH 13/25] compiler_types: add comment on `__BINDGEN__` Signed-off-by: Miguel Ojeda --- include/linux/compiler_types.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/include/linux/compiler_types.h b/include/linux/compiler_types.h index e466718fbb87d9..50b3f6b9502e5f 100644 --- a/include/linux/compiler_types.h +++ b/include/linux/compiler_types.h @@ -4,6 +4,10 @@ #ifndef __ASSEMBLY__ +/* + * Skipped when running bindgen due to a libclang issue; + * see https://github.com/rust-lang/rust-bindgen/issues/2244. + */ #if defined(CONFIG_DEBUG_INFO_BTF) && defined(CONFIG_PAHOLE_HAS_BTF_TAG) && \ __has_attribute(btf_type_tag) && !defined(__BINDGEN__) # define BTF_TYPE_TAG(value) __attribute__((btf_type_tag(#value))) From d249f1509dac90d1ef408664a92be362b9c9bf35 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Fri, 29 Jul 2022 15:16:01 +0200 Subject: [PATCH 14/25] rust: kernel: `rustfmt` documentation examples cleanups Signed-off-by: Miguel Ojeda --- rust/kernel/amba.rs | 6 +++--- rust/kernel/driver.rs | 12 ++++++------ rust/kernel/fs/param.rs | 14 +++++++------- rust/kernel/gpio.rs | 5 ++++- rust/kernel/io_mem.rs | 1 - rust/kernel/irq.rs | 11 ++++++----- rust/kernel/kasync/executor/workqueue.rs | 2 +- rust/kernel/sync/nowait.rs | 4 ++-- rust/kernel/sync/seqlock.rs | 2 +- rust/kernel/sync/smutex.rs | 4 ++-- rust/kernel/task.rs | 8 ++++---- rust/kernel/workqueue.rs | 4 ++-- 12 files changed, 38 insertions(+), 35 deletions(-) diff --git a/rust/kernel/amba.rs b/rust/kernel/amba.rs index 604e5d802e7277..d8f06abd660860 100644 --- a/rust/kernel/amba.rs +++ b/rust/kernel/amba.rs @@ -243,9 +243,9 @@ macro_rules! module_amba_driver { /// # fn probe(_dev: &mut amba::Device, _id: Option<&Self::IdInfo>) -> Result { /// # Ok(()) /// # } -/// define_amba_id_table! {(), [ -/// ({ id: 0x00041061, mask: 0x000fffff }, None), -/// ]} +/// define_amba_id_table! {(), [ +/// ({ id: 0x00041061, mask: 0x000fffff }, None), +/// ]} /// # } /// ``` #[macro_export] diff --git a/rust/kernel/driver.rs b/rust/kernel/driver.rs index 0ae9f4d3dbc53d..82b39231e3117a 100644 --- a/rust/kernel/driver.rs +++ b/rust/kernel/driver.rs @@ -280,16 +280,16 @@ macro_rules! first_item { /// assert_eq!([] as [u32; 0], second_item!()); /// assert_eq!([10u32], second_item!((X, 10u32))); /// assert_eq!([10u32], second_item!((X, 10u32),)); -/// assert_eq!([10u32], second_item!(({X}, 10u32))); -/// assert_eq!([10u32], second_item!(({X}, 10u32),)); +/// assert_eq!([10u32], second_item!(({ X }, 10u32))); +/// assert_eq!([10u32], second_item!(({ X }, 10u32),)); /// assert_eq!([10u32, 20], second_item!((X, 10u32), (X, 20))); /// assert_eq!([10u32, 20], second_item!((X, 10u32), (X, 20),)); -/// assert_eq!([10u32, 20], second_item!(({X}, 10u32), ({X}, 20))); -/// assert_eq!([10u32, 20], second_item!(({X}, 10u32), ({X}, 20),)); +/// assert_eq!([10u32, 20], second_item!(({ X }, 10u32), ({ X }, 20))); +/// assert_eq!([10u32, 20], second_item!(({ X }, 10u32), ({ X }, 20),)); /// assert_eq!([10u32, 20, 30], second_item!((X, 10u32), (X, 20), (X, 30))); /// assert_eq!([10u32, 20, 30], second_item!((X, 10u32), (X, 20), (X, 30),)); -/// assert_eq!([10u32, 20, 30], second_item!(({X}, 10u32), ({X}, 20), ({X}, 30))); -/// assert_eq!([10u32, 20, 30], second_item!(({X}, 10u32), ({X}, 20), ({X}, 30),)); +/// assert_eq!([10u32, 20, 30], second_item!(({ X }, 10u32), ({ X }, 20), ({ X }, 30))); +/// assert_eq!([10u32, 20, 30], second_item!(({ X }, 10u32), ({ X }, 20), ({ X }, 30),)); /// ``` #[macro_export] macro_rules! second_item { diff --git a/rust/kernel/fs/param.rs b/rust/kernel/fs/param.rs index 434e99a2996340..445cea404bcdd9 100644 --- a/rust/kernel/fs/param.rs +++ b/rust/kernel/fs/param.rs @@ -417,12 +417,12 @@ impl Re /// # use kernel::count_brace_items; /// /// assert_eq!(0, count_brace_items!()); -/// assert_eq!(1, count_brace_items!({A})); -/// assert_eq!(1, count_brace_items!({A},)); -/// assert_eq!(2, count_brace_items!({A}, {B})); -/// assert_eq!(2, count_brace_items!({A}, {B},)); -/// assert_eq!(3, count_brace_items!({A}, {B}, {C})); -/// assert_eq!(3, count_brace_items!({A}, {B}, {C},)); +/// assert_eq!(1, count_brace_items!({ A })); +/// assert_eq!(1, count_brace_items!({ A },)); +/// assert_eq!(2, count_brace_items!({ A }, { B })); +/// assert_eq!(2, count_brace_items!({ A }, { B },)); +/// assert_eq!(3, count_brace_items!({ A }, { B }, { C })); +/// assert_eq!(3, count_brace_items!({ A }, { B }, { C },)); /// ``` #[macro_export] macro_rules! count_brace_items { @@ -462,7 +462,7 @@ macro_rules! count_brace_items { /// impl fs::Context for Example { /// type Data = Box; /// -/// kernel::define_fs_params!{Box, +/// kernel::define_fs_params! {Box, /// {flag, "flag", |s, v| { s.flag = Some(v); Ok(()) } }, /// {flag_no, "flagno", |s, v| { s.flag_no = Some(v); Ok(()) } }, /// {bool, "bool", |s, v| { s.bool_value = Some(v); Ok(()) } }, diff --git a/rust/kernel/gpio.rs b/rust/kernel/gpio.rs index fcd10e07265937..53c7b398d10b0f 100644 --- a/rust/kernel/gpio.rs +++ b/rust/kernel/gpio.rs @@ -79,7 +79,10 @@ pub trait Chip { /// /// ``` /// # use kernel::prelude::*; -/// use kernel::{device::RawDevice, gpio::{self, Registration}}; +/// use kernel::{ +/// device::RawDevice, +/// gpio::{self, Registration}, +/// }; /// /// struct MyGpioChip; /// #[vtable] diff --git a/rust/kernel/io_mem.rs b/rust/kernel/io_mem.rs index 3b289a9461a6e3..ff6886a9e3b76f 100644 --- a/rust/kernel/io_mem.rs +++ b/rust/kernel/io_mem.rs @@ -56,7 +56,6 @@ impl Resource { /// /// Ok(()) /// } -/// /// ``` pub struct IoMem { ptr: usize, diff --git a/rust/kernel/irq.rs b/rust/kernel/irq.rs index 52706f78105876..941c2eafb8f2c4 100644 --- a/rust/kernel/irq.rs +++ b/rust/kernel/irq.rs @@ -395,8 +395,7 @@ pub trait Handler { /// } /// /// fn request_irq(irq: u32, data: Box) -> Result> { -/// irq::Registration::try_new( -/// irq, data, irq::flags::SHARED, fmt!("example_{irq}")) +/// irq::Registration::try_new(irq, data, irq::flags::SHARED, fmt!("example_{irq}")) /// } /// ``` pub struct Registration(InternalRegistration); @@ -450,7 +449,10 @@ pub trait ThreadedHandler { /// /// ``` /// # use kernel::prelude::*; -/// use kernel::{irq, sync::{Ref, RefBorrow}}; +/// use kernel::{ +/// irq, +/// sync::{Ref, RefBorrow}, +/// }; /// /// struct Example; /// @@ -463,8 +465,7 @@ pub trait ThreadedHandler { /// } /// /// fn request_irq(irq: u32, data: Ref) -> Result> { -/// irq::ThreadedRegistration::try_new( -/// irq, data, irq::flags::SHARED, fmt!("example_{irq}")) +/// irq::ThreadedRegistration::try_new(irq, data, irq::flags::SHARED, fmt!("example_{irq}")) /// } /// ``` pub struct ThreadedRegistration(InternalRegistration); diff --git a/rust/kernel/kasync/executor/workqueue.rs b/rust/kernel/kasync/executor/workqueue.rs index f9aa7fafadccf4..81cd16880600d2 100644 --- a/rust/kernel/kasync/executor/workqueue.rs +++ b/rust/kernel/kasync/executor/workqueue.rs @@ -174,8 +174,8 @@ struct ExecutorInner { /// ``` /// # use kernel::prelude::*; /// use kernel::kasync::executor::workqueue::Executor; -/// use kernel::workqueue; /// use kernel::spawn_task; +/// use kernel::workqueue; /// /// fn example_shared_workqueue() -> Result { /// let mut handle = Executor::try_new(workqueue::system())?; diff --git a/rust/kernel/sync/nowait.rs b/rust/kernel/sync/nowait.rs index c9ee2f9a360743..09852d71aeb25b 100644 --- a/rust/kernel/sync/nowait.rs +++ b/rust/kernel/sync/nowait.rs @@ -30,7 +30,7 @@ const CONTENDED: u8 = 2; /// b: u32, /// } /// -/// let x = NoWaitLock::new(Example{ a: 10, b: 20 }); +/// let x = NoWaitLock::new(Example { a: 10, b: 20 }); /// /// // Modifying the protected value. /// { @@ -72,7 +72,7 @@ const CONTENDED: u8 = 2; /// b: u32, /// } /// -/// let x = NoWaitLock::new(Example{ a: 10, b: 20 }); +/// let x = NoWaitLock::new(Example { a: 10, b: 20 }); /// /// // No contention when lock is released. /// let guard = x.try_lock().unwrap(); diff --git a/rust/kernel/sync/seqlock.rs b/rust/kernel/sync/seqlock.rs index 1f5e7e996cb873..276d5b86893012 100644 --- a/rust/kernel/sync/seqlock.rs +++ b/rust/kernel/sync/seqlock.rs @@ -18,8 +18,8 @@ use core::{cell::UnsafeCell, marker::PhantomPinned, ops::Deref, pin::Pin}; /// # Examples /// ///``` -/// use kernel::sync::{SeqLock, SpinLock}; /// use core::sync::atomic::{AtomicU32, Ordering}; +/// use kernel::sync::{SeqLock, SpinLock}; /// /// struct Example { /// a: AtomicU32, diff --git a/rust/kernel/sync/smutex.rs b/rust/kernel/sync/smutex.rs index 80ac292e4df60d..e19dd966640a1a 100644 --- a/rust/kernel/sync/smutex.rs +++ b/rust/kernel/sync/smutex.rs @@ -71,7 +71,7 @@ const LOCKED: usize = 1; /// b: u32, /// } /// -/// static EXAMPLE: Mutex = Mutex::new(Example{ a: 10, b: 20 }); +/// static EXAMPLE: Mutex = Mutex::new(Example { a: 10, b: 20 }); /// /// fn inc_a(example: &Mutex) { /// let mut guard = example.lock(); @@ -84,7 +84,7 @@ const LOCKED: usize = 1; /// } /// /// fn try_new(a: u32, b: u32) -> Result>> { -/// Ref::try_new(Mutex::new(Example {a, b})) +/// Ref::try_new(Mutex::new(Example { a, b })) /// } /// /// assert_eq!(EXAMPLE.lock().a, 10); diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs index c8d11ca8f09681..67040b53281648 100644 --- a/rust/kernel/task.rs +++ b/rust/kernel/task.rs @@ -41,7 +41,7 @@ use core::{cell::UnsafeCell, fmt, marker::PhantomData, ops::Deref, ptr}; /// incremented when creating `State` and decremented when it is dropped: /// /// ``` -/// use kernel::{ARef, task::Task}; +/// use kernel::{task::Task, ARef}; /// /// struct State { /// creator: ARef, @@ -113,9 +113,9 @@ impl Task { /// Launches 10 threads and waits for them to complete. /// /// ``` - /// use kernel::task::Task; - /// use kernel::sync::{CondVar, Mutex}; /// use core::sync::atomic::{AtomicU32, Ordering}; + /// use kernel::sync::{CondVar, Mutex}; + /// use kernel::task::Task; /// /// kernel::init_static_sync! { /// static COUNT: Mutex = 0; @@ -133,7 +133,7 @@ impl Task { /// /// // Set count to 10 and spawn 10 threads. /// *COUNT.lock() = 10; - /// for i in 0..10 { + /// for i in 0..10 { /// Task::spawn(fmt!("test{i}"), threadfn).unwrap(); /// } /// diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 68faa8e5f58b56..c6b89f13746901 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -134,8 +134,8 @@ macro_rules! init_work_item_adapter { /// /// ``` /// # use kernel::workqueue::{self, Work}; -/// use kernel::sync::UniqueRef; /// use core::sync::atomic::{AtomicU32, Ordering}; +/// use kernel::sync::UniqueRef; /// /// struct Example { /// count: AtomicU32, @@ -174,8 +174,8 @@ macro_rules! init_work_item_adapter { /// /// ``` /// # use kernel::workqueue::{self, Work, WorkAdapter}; -/// use kernel::sync::{Ref, UniqueRef}; /// use core::sync::atomic::{AtomicU32, Ordering}; +/// use kernel::sync::{Ref, UniqueRef}; /// /// struct Example { /// work1: Work, From 833095d2fd180976c6ef07b1b9b69dede09be97f Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Fri, 29 Jul 2022 15:32:19 +0200 Subject: [PATCH 15/25] treewide: other `rustfmt`-inspired cleanups Signed-off-by: Miguel Ojeda --- drivers/android/transaction.rs | 8 ++++---- rust/kernel/hwrng.rs | 3 ++- rust/kernel/sync/seqlock.rs | 2 +- rust/kernel/unsafe_list.rs | 2 +- rust/macros/lib.rs | 7 ++++--- 5 files changed, 12 insertions(+), 10 deletions(-) diff --git a/drivers/android/transaction.rs b/drivers/android/transaction.rs index 3b2a5ea7379274..6d8510e3f889c4 100644 --- a/drivers/android/transaction.rs +++ b/drivers/android/transaction.rs @@ -196,10 +196,10 @@ impl Transaction { impl DeliverToRead for Transaction { fn do_work(self: Ref, thread: &Thread, writer: &mut UserSlicePtrWriter) -> Result { - /* TODO: Initialise the following fields from tr: - pub sender_pid: pid_t, - pub sender_euid: uid_t, - */ + // TODO: Initialise the following fields from `tr`: + // - `pub sender_pid: pid_t`. + // - `pub sender_euid: uid_t`. + let send_failed_reply = ScopeGuard::new(|| { if self.node_ref.is_some() && self.flags & TF_ONE_WAY == 0 { let reply = Either::Right(BR_FAILED_REPLY); diff --git a/rust/kernel/hwrng.rs b/rust/kernel/hwrng.rs index 3e9bd354ab6b56..5918f567c3327a 100644 --- a/rust/kernel/hwrng.rs +++ b/rust/kernel/hwrng.rs @@ -96,7 +96,8 @@ impl Registration { let name = CString::try_from_fmt(name)?; - // SAFETY: Registration is pinned and contains allocated and set to zero `bindings::hwrng` structure. + // SAFETY: Registration is pinned and contains allocated and set to zero + // `bindings::hwrng` structure. Self::init_hwrng( unsafe { &mut *this.hwrng.get() }, &name, diff --git a/rust/kernel/sync/seqlock.rs b/rust/kernel/sync/seqlock.rs index 276d5b86893012..5014e70621f695 100644 --- a/rust/kernel/sync/seqlock.rs +++ b/rust/kernel/sync/seqlock.rs @@ -17,7 +17,7 @@ use core::{cell::UnsafeCell, marker::PhantomPinned, ops::Deref, pin::Pin}; /// /// # Examples /// -///``` +/// ``` /// use core::sync::atomic::{AtomicU32, Ordering}; /// use kernel::sync::{SeqLock, SpinLock}; /// diff --git a/rust/kernel/unsafe_list.rs b/rust/kernel/unsafe_list.rs index f8c2c63b09087f..df496667c03389 100644 --- a/rust/kernel/unsafe_list.rs +++ b/rust/kernel/unsafe_list.rs @@ -4,7 +4,7 @@ //! //! We don't use the C version for two main reasons: //! - Next/prev pointers do not support `?Sized` types, so wouldn't be able to have a list of, for -//! example, dyn Trait. +//! example, `dyn Trait`. //! - It would require the list head to be pinned (in addition to the list entries). use core::{cell::UnsafeCell, iter, marker::PhantomPinned, mem::MaybeUninit, ptr::NonNull}; diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index cf02b441619c61..eb0187f85521eb 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -68,7 +68,8 @@ use proc_macro::TokenStream; /// - `description`: byte array of the description of the kernel module. /// - `license`: byte array of the license of the kernel module (required). /// - `alias`: byte array of alias name of the kernel module. -/// - `alias_rtnl_link`: byte array of the `rtnl_link_alias` of the kernel module (mutually exclusive with `alias`). +/// - `alias_rtnl_link`: byte array of the `rtnl_link_alias` of the kernel module +/// (mutually exclusive with `alias`). /// - `params`: parameters for the kernel module, as described below. /// /// # Supported parameter types @@ -85,8 +86,8 @@ use proc_macro::TokenStream; /// - `isize`: No equivalent C param type. /// - `usize`: No equivalent C param type. /// - `str`: Corresponds to C `charp` param type. Reading returns a byte slice. -/// - `ArrayParam`: Corresponds to C parameters created using `module_param_array`. An array -/// of `T`'s of length at **most** `N`. +/// - `ArrayParam`: Corresponds to C parameters created using `module_param_array`. +/// An array of `T`'s of length at **most** `N`. /// /// `invbool` is unsupported: it was only ever used in a few modules. /// Consider using a `bool` and inverting the logic instead. From 767e953a730ac3991ebf865acac0db8e628f8160 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sun, 31 Jul 2022 17:35:06 +0200 Subject: [PATCH 16/25] rust: macros: use `//` comment style in Rust Signed-off-by: Miguel Ojeda --- rust/macros/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index eb0187f85521eb..dfb9b3c6f0dc73 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -135,7 +135,7 @@ pub fn module(ts: TokenStream) -> TokenStream { /// impl Operations for Foo { /// fn foo(&self) -> Result<()> { /// # Err(EINVAL) -/// /* ... */ +/// // ... /// } /// } /// From f87f7e0cd4653be56c0155481cc744caae96022e Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sun, 31 Jul 2022 17:54:16 +0200 Subject: [PATCH 17/25] treewide: finish Rust comments in period Signed-off-by: Miguel Ojeda --- rust/kernel/file.rs | 2 +- rust/kernel/pages.rs | 2 +- rust/kernel/str.rs | 4 ++-- rust/macros/vtable.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/rust/kernel/file.rs b/rust/kernel/file.rs index 32fa52d184cfe9..0f1f841aff9cb9 100644 --- a/rust/kernel/file.rs +++ b/rust/kernel/file.rs @@ -47,7 +47,7 @@ pub mod flags { /// Ensure that this file is created with the `open(2)` call. pub const O_EXCL: u32 = bindings::O_EXCL; - /// Large file size enabled (`off64_t` over `off_t`) + /// Large file size enabled (`off64_t` over `off_t`). pub const O_LARGEFILE: u32 = bindings::O_LARGEFILE; /// Do not update the file last access time. diff --git a/rust/kernel/pages.rs b/rust/kernel/pages.rs index 8bf2ea88f689c5..f2bb26810cd74a 100644 --- a/rust/kernel/pages.rs +++ b/rust/kernel/pages.rs @@ -36,7 +36,7 @@ impl Pages { if pages.is_null() { return Err(ENOMEM); } - // INVARIANTS: We checked that the allocation above succeeded> + // INVARIANTS: We checked that the allocation above succeeded. Ok(Self { pages }) } diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index f4bfd7087f7184..874003e39cba60 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -228,7 +228,7 @@ impl fmt::Display for CStr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for &c in self.as_bytes() { if (0x20..0x7f).contains(&c) { - // Printable character + // Printable character. f.write_char(c as char)?; } else { write!(f, "\\x{:02x}", c)?; @@ -258,7 +258,7 @@ impl fmt::Debug for CStr { f.write_str("\"")?; for &c in self.as_bytes() { match c { - // Printable characters + // Printable characters. b'\"' => f.write_str("\\\"")?, 0x20..=0x7e => f.write_char(c as char)?, _ => write!(f, "\\x{:02x}", c)?, diff --git a/rust/macros/vtable.rs b/rust/macros/vtable.rs index 98340ea0af5fef..a64d60cc855c99 100644 --- a/rust/macros/vtable.rs +++ b/rust/macros/vtable.rs @@ -7,7 +7,7 @@ use std::fmt::Write; pub(crate) fn vtable(_attr: TokenStream, ts: TokenStream) -> TokenStream { let mut tokens: Vec<_> = ts.into_iter().collect(); - // Scan for the `trait` or `impl` keyword + // Scan for the `trait` or `impl` keyword. let is_trait = tokens .iter() .find_map(|token| match token { From d95515727b7ad3388a7418a6e58c0bf351463119 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sun, 31 Jul 2022 18:34:30 +0200 Subject: [PATCH 18/25] treewide: fix too-long-lines `checkpatch.pl` warnings Signed-off-by: Miguel Ojeda --- rust/kernel/file.rs | 6 ++- rust/macros/module.rs | 79 ++++++++++++++++++++++++------------ rust/macros/vtable.rs | 8 +++- scripts/rust-is-available.sh | 3 +- 4 files changed, 64 insertions(+), 32 deletions(-) diff --git a/rust/kernel/file.rs b/rust/kernel/file.rs index 0f1f841aff9cb9..78628f367efffc 100644 --- a/rust/kernel/file.rs +++ b/rust/kernel/file.rs @@ -326,7 +326,8 @@ impl, T: Operations> OperationsVtable { offset: *mut bindings::loff_t, ) -> core::ffi::c_ssize_t { from_kernel_result! { - let mut data = unsafe { UserSlicePtr::new(buf as *mut core::ffi::c_void, len).writer() }; + let mut data = + unsafe { UserSlicePtr::new(buf as *mut core::ffi::c_void, len).writer() }; // SAFETY: `private_data` was initialised by `open_callback` with a value returned by // `T::Data::into_pointer`. `T::Data::from_pointer` is only called by the // `release` callback, which the C API guarantees that will be called only when all @@ -374,7 +375,8 @@ impl, T: Operations> OperationsVtable { offset: *mut bindings::loff_t, ) -> core::ffi::c_ssize_t { from_kernel_result! { - let mut data = unsafe { UserSlicePtr::new(buf as *mut core::ffi::c_void, len).reader() }; + let mut data = + unsafe { UserSlicePtr::new(buf as *mut core::ffi::c_void, len).reader() }; // SAFETY: `private_data` was initialised by `open_callback` with a value returned by // `T::Data::into_pointer`. `T::Data::from_pointer` is only called by the // `release` callback, which the C API guarantees that will be called only when all diff --git a/rust/macros/module.rs b/rust/macros/module.rs index edf37c38a08e86..4e68cf63a2cc8a 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -388,9 +388,15 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { let read_func = if permissions_are_readonly(¶m_permissions) { format!( " - fn read(&self) -> &<{param_type_internal} as kernel::module_param::ModuleParam>::Value {{ - // SAFETY: Parameters do not need to be locked because they are read only or sysfs is not enabled. - unsafe {{ <{param_type_internal} as kernel::module_param::ModuleParam>::value(&__{name}_{param_name}_value) }} + fn read(&self) + -> &<{param_type_internal} as kernel::module_param::ModuleParam>::Value {{ + // SAFETY: Parameters do not need to be locked because they are + // read only or sysfs is not enabled. + unsafe {{ + <{param_type_internal} as kernel::module_param::ModuleParam>::value( + &__{name}_{param_name}_value + ) + }} }} ", name = info.name, @@ -400,9 +406,14 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { } else { format!( " - fn read<'lck>(&self, lock: &'lck kernel::KParamGuard) -> &'lck <{param_type_internal} as kernel::module_param::ModuleParam>::Value {{ + fn read<'lck>(&self, lock: &'lck kernel::KParamGuard) + -> &'lck <{param_type_internal} as kernel::module_param::ModuleParam>::Value {{ // SAFETY: Parameters are locked by `KParamGuard`. - unsafe {{ <{param_type_internal} as kernel::module_param::ModuleParam>::value(&__{name}_{param_name}_value) }} + unsafe {{ + <{param_type_internal} as kernel::module_param::ModuleParam>::value( + &__{name}_{param_name}_value + ) + }} }} ", name = info.name, @@ -413,13 +424,15 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { let kparam = format!( " kernel::bindings::kernel_param__bindgen_ty_1 {{ - arg: unsafe {{ &__{name}_{param_name}_value }} as *const _ as *mut core::ffi::c_void, + arg: unsafe {{ &__{name}_{param_name}_value }} + as *const _ as *mut core::ffi::c_void, }}, ", name = info.name, param_name = param_name, ); - write!(modinfo.buffer, + write!( + modinfo.buffer, " static mut __{name}_{param_name}_value: {param_type_internal} = {param_default}; @@ -443,26 +456,30 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { }} #[cfg(not(MODULE))] - const __{name}_{param_name}_name: *const core::ffi::c_char = b\"{name}.{param_name}\\0\" as *const _ as *const core::ffi::c_char; + const __{name}_{param_name}_name: *const core::ffi::c_char = + b\"{name}.{param_name}\\0\" as *const _ as *const core::ffi::c_char; #[cfg(MODULE)] - const __{name}_{param_name}_name: *const core::ffi::c_char = b\"{param_name}\\0\" as *const _ as *const core::ffi::c_char; + const __{name}_{param_name}_name: *const core::ffi::c_char = + b\"{param_name}\\0\" as *const _ as *const core::ffi::c_char; #[link_section = \"__param\"] #[used] - static __{name}_{param_name}_struct: __{name}_{param_name}_RacyKernelParam = __{name}_{param_name}_RacyKernelParam(kernel::bindings::kernel_param {{ - name: __{name}_{param_name}_name, - // SAFETY: `__this_module` is constructed by the kernel at load time and will not be freed until the module is unloaded. - #[cfg(MODULE)] - mod_: unsafe {{ &kernel::bindings::__this_module as *const _ as *mut _ }}, - #[cfg(not(MODULE))] - mod_: core::ptr::null_mut(), - ops: unsafe {{ &{ops} }} as *const kernel::bindings::kernel_param_ops, - perm: {permissions}, - level: -1, - flags: 0, - __bindgen_anon_1: {kparam} - }}); + static __{name}_{param_name}_struct: __{name}_{param_name}_RacyKernelParam = + __{name}_{param_name}_RacyKernelParam(kernel::bindings::kernel_param {{ + name: __{name}_{param_name}_name, + // SAFETY: `__this_module` is constructed by the kernel at load time + // and will not be freed until the module is unloaded. + #[cfg(MODULE)] + mod_: unsafe {{ &kernel::bindings::__this_module as *const _ as *mut _ }}, + #[cfg(not(MODULE))] + mod_: core::ptr::null_mut(), + ops: unsafe {{ &{ops} }} as *const kernel::bindings::kernel_param_ops, + perm: {permissions}, + level: -1, + flags: 0, + __bindgen_anon_1: {kparam} + }}); ", name = info.name, param_type_internal = param_type_internal, @@ -472,7 +489,8 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { ops = ops, permissions = param_permissions, kparam = kparam, - ).unwrap(); + ) + .unwrap(); } } @@ -513,11 +531,16 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { static mut __MOD: Option<{type_}> = None; - // SAFETY: `__this_module` is constructed by the kernel at load time and will not be freed until the module is unloaded. + // SAFETY: `__this_module` is constructed by the kernel at load time and will not be + // freed until the module is unloaded. #[cfg(MODULE)] - static THIS_MODULE: kernel::ThisModule = unsafe {{ kernel::ThisModule::from_ptr(&kernel::bindings::__this_module as *const _ as *mut _) }}; + static THIS_MODULE: kernel::ThisModule = unsafe {{ + kernel::ThisModule::from_ptr(&kernel::bindings::__this_module as *const _ as *mut _) + }}; #[cfg(not(MODULE))] - static THIS_MODULE: kernel::ThisModule = unsafe {{ kernel::ThisModule::from_ptr(core::ptr::null_mut()) }}; + static THIS_MODULE: kernel::ThisModule = unsafe {{ + kernel::ThisModule::from_ptr(core::ptr::null_mut()) + }}; // Loadable modules need to export the `{{init,cleanup}}_module` identifiers. #[cfg(MODULE)] @@ -597,7 +620,9 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream { modinfo = modinfo.buffer, generated_array_types = generated_array_types, initcall_section = ".initcall6.init" - ).parse().expect("Error parsing formatted string into token stream.") + ) + .parse() + .expect("Error parsing formatted string into token stream.") } #[cfg(test)] diff --git a/rust/macros/vtable.rs b/rust/macros/vtable.rs index a64d60cc855c99..34d5e7fb5768a2 100644 --- a/rust/macros/vtable.rs +++ b/rust/macros/vtable.rs @@ -53,8 +53,12 @@ pub(crate) fn vtable(_attr: TokenStream, ts: TokenStream) -> TokenStream { let mut const_items; if is_trait { - const_items = "/// A marker to prevent implementors from forgetting to use [`#[vtable]`](vtable) attribute when implementing this trait. - const USE_VTABLE_ATTR: ();".to_owned(); + const_items = " + /// A marker to prevent implementors from forgetting to use [`#[vtable]`](vtable) + /// attribute when implementing this trait. + const USE_VTABLE_ATTR: (); + " + .to_owned(); for f in functions { let gen_const_name = format!("HAS_{}", f.to_uppercase()); diff --git a/scripts/rust-is-available.sh b/scripts/rust-is-available.sh index bdab1c5908457c..0ddad3fcd32c37 100755 --- a/scripts/rust-is-available.sh +++ b/scripts/rust-is-available.sh @@ -134,7 +134,8 @@ if [ "$1" = -v ]; then ) if [ "$clang_version" != "$bindgen_libclang_version" ]; then echo >&2 "***" - echo >&2 "*** libclang (used by the Rust bindings generator '$BINDGEN') version does not match Clang's. This may be a problem." + echo >&2 "*** libclang (used by the Rust bindings generator '$BINDGEN')" + echo >&2 "*** version does not match Clang's. This may be a problem." echo >&2 "*** libclang version: $bindgen_libclang_version" echo >&2 "*** Clang version: $clang_version" echo >&2 "***" From 77a1a8c952e10dafcc91047b5025b18e0408def5 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sun, 31 Jul 2022 18:58:27 +0200 Subject: [PATCH 19/25] rust: kernel: apply `rustfmt` to `from_kernel_result!` blocks Signed-off-by: Miguel Ojeda --- rust/kernel/amba.rs | 6 +++++- rust/kernel/file.rs | 18 +++++++++++++----- rust/kernel/fs.rs | 10 +++++++--- rust/kernel/irq.rs | 6 +++++- 4 files changed, 30 insertions(+), 10 deletions(-) diff --git a/rust/kernel/amba.rs b/rust/kernel/amba.rs index d8f06abd660860..ec8808124a2943 100644 --- a/rust/kernel/amba.rs +++ b/rust/kernel/amba.rs @@ -120,7 +120,11 @@ unsafe extern "C" fn probe_callback( } else { // SAFETY: The offset comes from a previous call to `offset_from` in `IdArray::new`, // which guarantees that the resulting pointer is within the table. - let ptr = unsafe { aid.cast::().offset(offset as _).cast::>() }; + let ptr = unsafe { + aid.cast::() + .offset(offset as _) + .cast::>() + }; // SAFETY: The id table has a static lifetime, so `ptr` is guaranteed to be valid for // read. unsafe { (&*ptr).as_ref() } diff --git a/rust/kernel/file.rs b/rust/kernel/file.rs index 78628f367efffc..f77cf0ba911904 100644 --- a/rust/kernel/file.rs +++ b/rust/kernel/file.rs @@ -361,8 +361,12 @@ impl, T: Operations> OperationsVtable { // references to `file` have been released, so we know it can't be called while this // function is running. let f = unsafe { T::Data::borrow((*file).private_data) }; - let read = - T::read(f, unsafe { File::from_ptr(file) }, &mut iter, offset.try_into()?)?; + let read = T::read( + f, + unsafe { File::from_ptr(file) }, + &mut iter, + offset.try_into()?, + )?; unsafe { (*iocb).ki_pos += bindings::loff_t::try_from(read).unwrap() }; Ok(read as _) } @@ -389,7 +393,7 @@ impl, T: Operations> OperationsVtable { f, unsafe { File::from_ptr(file) }, &mut data, - unsafe { *offset }.try_into()? + unsafe { *offset }.try_into()?, )?; unsafe { (*offset) += bindings::loff_t::try_from(written).unwrap() }; Ok(written as _) @@ -410,8 +414,12 @@ impl, T: Operations> OperationsVtable { // references to `file` have been released, so we know it can't be called while this // function is running. let f = unsafe { T::Data::borrow((*file).private_data) }; - let written = - T::write(f, unsafe { File::from_ptr(file) }, &mut iter, offset.try_into()?)?; + let written = T::write( + f, + unsafe { File::from_ptr(file) }, + &mut iter, + offset.try_into()?, + )?; unsafe { (*iocb).ki_pos += bindings::loff_t::try_from(written).unwrap() }; Ok(written as _) } diff --git a/rust/kernel/fs.rs b/rust/kernel/fs.rs index 49c293fd6bc393..46dc38aad2bc47 100644 --- a/rust/kernel/fs.rs +++ b/rust/kernel/fs.rs @@ -166,7 +166,10 @@ impl Tables { // SAFETY: The callback contract guarantees the parameter key to be valid and last at // least the duration of the callback. T::Context::parse_unknown_param( - &mut data, unsafe { CStr::from_char_ptr(param.key) }, val)?; + &mut data, + unsafe { CStr::from_char_ptr(param.key) }, + val, + )?; Ok(0) } } @@ -291,8 +294,9 @@ impl Tables { // SAFETY: Both `fc` and `buf` are guaranteed to be valid; the former because the // callback is still ongoing and the latter because its lifefime is tied to that of // `page`, which is also valid for the duration of the callback. - to_result( - unsafe { bindings::generic_parse_monolithic(fc, buf.as_mut_ptr().cast()) })?; + to_result(unsafe { + bindings::generic_parse_monolithic(fc, buf.as_mut_ptr().cast()) + })?; } Ok(0) } diff --git a/rust/kernel/irq.rs b/rust/kernel/irq.rs index 941c2eafb8f2c4..f2fa270dd7288c 100644 --- a/rust/kernel/irq.rs +++ b/rust/kernel/irq.rs @@ -213,7 +213,11 @@ unsafe extern "C" fn irq_set_type_callback( // SAFETY: The value returned by `IrqData` is only valid until the end of this function, and // `irq_data` is guaranteed to be valid until then (by the contract with C code). - let ret = T::set_type(data, &mut LockedIrqData(unsafe { IrqData::from_ptr(irq_data) }), flow_type)?; + let ret = T::set_type( + data, + &mut LockedIrqData(unsafe { IrqData::from_ptr(irq_data) }), + flow_type, + )?; Ok(ret as _) } } From 552295801f2acd838bfced9de9bfb715a3c3c751 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Mon, 1 Aug 2022 12:06:14 +0200 Subject: [PATCH 20/25] rust: use `<>` link style in comments too This is intended to follow our "use Markdown for comments too" / "comments and docs should be easily interchangeable" guideline. Signed-off-by: Miguel Ojeda --- rust/bindings/lib.rs | 2 +- rust/kernel/file.rs | 4 ++-- rust/kernel/kasync/net.rs | 2 +- rust/kernel/lib.rs | 3 +-- rust/kernel/sync/guard.rs | 2 +- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/rust/bindings/lib.rs b/rust/bindings/lib.rs index e5df198512a26b..7fdd74e68b60c3 100644 --- a/rust/bindings/lib.rs +++ b/rust/bindings/lib.rs @@ -10,7 +10,7 @@ #![no_std] #![feature(core_ffi_c)] -// See https://github.com/rust-lang/rust-bindgen/issues/1651. +// See . #![cfg_attr(test, allow(deref_nullptr))] #![cfg_attr(test, allow(unaligned_references))] #![cfg_attr(test, allow(unsafe_op_in_unsafe_fn))] diff --git a/rust/kernel/file.rs b/rust/kernel/file.rs index f77cf0ba911904..62538e6b3eea6c 100644 --- a/rust/kernel/file.rs +++ b/rust/kernel/file.rs @@ -335,7 +335,7 @@ impl, T: Operations> OperationsVtable { // function is running. let f = unsafe { T::Data::borrow((*file).private_data) }; // No `FMODE_UNSIGNED_OFFSET` support, so `offset` must be in [0, 2^63). - // See discussion in https://github.com/fishinabarrel/linux-kernel-module-rust/pull/113 + // See . let read = T::read( f, unsafe { File::from_ptr(file) }, @@ -388,7 +388,7 @@ impl, T: Operations> OperationsVtable { // function is running. let f = unsafe { T::Data::borrow((*file).private_data) }; // No `FMODE_UNSIGNED_OFFSET` support, so `offset` must be in [0, 2^63). - // See discussion in https://github.com/fishinabarrel/linux-kernel-module-rust/pull/113 + // See . let written = T::write( f, unsafe { File::from_ptr(file) }, diff --git a/rust/kernel/kasync/net.rs b/rust/kernel/kasync/net.rs index c692c2f48d478f..b4bbeffad94a1b 100644 --- a/rust/kernel/kasync/net.rs +++ b/rust/kernel/kasync/net.rs @@ -199,7 +199,7 @@ impl<'a, Out, F: FnMut() -> Result + Send + 'a> SocketFuture<'a, Out, F> { // There is a potential soundness issue here because we're generating a shared reference to // `Self` while `Self::poll` has a mutable (unique) reference. However, for `!Unpin` types // (like `Self`), `&mut T` is treated as `*mut T` per - // https://github.com/rust-lang/rust/issues/63818 -- so we avoid the unsoundness. Once a + // -- so we avoid the unsoundness. Once a // more definitive solution is available, we can change this to use it. let s = unsafe { &*crate::container_of!(wq_entry, Self, wq_entry) }; if mask & s.mask == 0 { diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 306d54ac4243ff..b55fe00761c2bb 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -262,7 +262,6 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! { // SAFETY: FFI call. unsafe { bindings::BUG() }; // Bindgen currently does not recognize `__noreturn` so `BUG` returns `()` - // instead of `!`. - // https://github.com/rust-lang/rust-bindgen/issues/2094 + // instead of `!`. See . loop {} } diff --git a/rust/kernel/sync/guard.rs b/rust/kernel/sync/guard.rs index 85c7d6a0addd09..757d85eac7afe5 100644 --- a/rust/kernel/sync/guard.rs +++ b/rust/kernel/sync/guard.rs @@ -21,7 +21,7 @@ pub struct Guard<'a, L: Lock + ?Sized, I: LockInfo = WriteLock> { // SAFETY: `Guard` is sync when the data protected by the lock is also sync. This is more // conservative than the default compiler implementation; more details can be found on -// https://github.com/rust-lang/rust/issues/41622 -- it refers to `MutexGuard` from the standard +// -- it refers to `MutexGuard` from the standard // library. unsafe impl Sync for Guard<'_, L, I> where From 10664d3fb12962f5992b749173f55d0f828aa235 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Mon, 1 Aug 2022 12:35:36 +0200 Subject: [PATCH 21/25] rust: alloc: use `<>` links in `README.md` Signed-off-by: Miguel Ojeda --- rust/alloc/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust/alloc/README.md b/rust/alloc/README.md index 9cf0d074c82a6a..c89c753720b509 100644 --- a/rust/alloc/README.md +++ b/rust/alloc/README.md @@ -1,9 +1,9 @@ # `alloc` These source files come from the Rust standard library, hosted in -the https://github.com/rust-lang/rust repository, licensed under +the repository, licensed under "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details, -see https://github.com/rust-lang/rust/blob/master/COPYRIGHT. +see . Please note that these files should be kept as close as possible to upstream. In general, only additions should be performed (e.g. new From 0473a8d0683715e8c6e4fbb8da8e68ef72b7c98c Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Mon, 1 Aug 2022 12:20:15 +0200 Subject: [PATCH 22/25] rust: alloc: add missing `SPDX-License-Identifier`s These should have been there in the last `alloc` version upgrade. Signed-off-by: Miguel Ojeda --- rust/alloc/boxed/thin.rs | 2 ++ rust/alloc/ffi/c_str.rs | 2 ++ rust/alloc/ffi/mod.rs | 2 ++ 3 files changed, 6 insertions(+) diff --git a/rust/alloc/boxed/thin.rs b/rust/alloc/boxed/thin.rs index db7a3e91aa8001..9135203114fcc9 100644 --- a/rust/alloc/boxed/thin.rs +++ b/rust/alloc/boxed/thin.rs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + // Based on // https://github.com/matthieu-m/rfc2580/blob/b58d1d3cba0d4b5e859d3617ea2d0943aaa31329/examples/thin.rs // by matthieu-m diff --git a/rust/alloc/ffi/c_str.rs b/rust/alloc/ffi/c_str.rs index 172a008e89a064..5e2f4073771a32 100644 --- a/rust/alloc/ffi/c_str.rs +++ b/rust/alloc/ffi/c_str.rs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + #[cfg(test)] mod tests; diff --git a/rust/alloc/ffi/mod.rs b/rust/alloc/ffi/mod.rs index eed2851c1539b1..56d429785339de 100644 --- a/rust/alloc/ffi/mod.rs +++ b/rust/alloc/ffi/mod.rs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + //! Utilities related to FFI bindings. //! //! This module provides utilities to handle data across non-Rust From 2dd5cafdb6972efdcd89424eeabe2c26804b540f Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Mon, 1 Aug 2022 12:41:02 +0200 Subject: [PATCH 23/25] rust: kernel: std_vendor: clarify licensing even further Given Linus' comments on the `alloc` patch on v6, I thought it would be a good idea to make this paragraph even more clear (i.e. that the original code was actually under "Apache-2.0 OR MIT" -- the SPDX identifier alone could be understood as "we decided to license this ourselves under Apache/MIT, but it may not be the original license"). This also makes the wording more consistent with what we have for `rust/alloc/README.md` -- they are now almost identical. Signed-off-by: Miguel Ojeda --- rust/kernel/std_vendor.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/rust/kernel/std_vendor.rs b/rust/kernel/std_vendor.rs index d64f30ce78dc3b..ffbaca0c4cb75f 100644 --- a/rust/kernel/std_vendor.rs +++ b/rust/kernel/std_vendor.rs @@ -1,8 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT -//! The contents of this file come from the Rust standard library, hosted in the -//! repository. For copyright details, see -//! . +//! The contents of this file come from the Rust standard library, hosted in +//! the repository, licensed under +//! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details, +//! see . /// [`std::dbg`], but using [`pr_info`] instead of [`eprintln`]. /// From 13947745f6ecb676f6bf439939a01d270bc91938 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Mon, 1 Aug 2022 16:27:24 +0200 Subject: [PATCH 24/25] scripts: is_rust_module: add comment and link about `.comment` Signed-off-by: Miguel Ojeda --- scripts/is_rust_module.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/is_rust_module.sh b/scripts/is_rust_module.sh index 277a64d07f22c1..28b3831a7593f4 100755 --- a/scripts/is_rust_module.sh +++ b/scripts/is_rust_module.sh @@ -10,4 +10,7 @@ set -e # Using the `16_` prefix ensures other symbols with the same substring # are not picked up (even if it would be unlikely). The last part is # used just in case LLVM decides to use the `.` suffix. +# +# In the future, checking for the `.comment` section may be another +# option, see https://github.com/rust-lang/rust/pull/97550. ${NM} "$*" | grep -qE '^[0-9a-fA-F]+ r _R[^[:space:]]+16___IS_RUST_MODULE[^[:space:]]*$' From ecd8e1f97d09f83a2dae02b04079e6b7d5d3bf79 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Mon, 1 Aug 2022 16:45:37 +0200 Subject: [PATCH 25/25] Makefile: clarify that `.rsi` files may not be compilable Signed-off-by: Miguel Ojeda --- Makefile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 35eb70c7ae3fe8..cd1d545f316bc6 100644 --- a/Makefile +++ b/Makefile @@ -1716,8 +1716,9 @@ help: @echo ' rust-analyzer - Generate rust-project.json rust-analyzer support file' @echo ' (requires kernel .config)' @echo ' dir/file.[os] - Build specified target only' - @echo ' dir/file.rsi - Build macro expanded source, similar to C preprocessing' - @echo ' (run with RUSTFMT=n to skip reformatting if needed)' + @echo ' dir/file.rsi - Build macro expanded source, similar to C preprocessing.' + @echo ' Run with RUSTFMT=n to skip reformatting if needed.' + @echo ' The output is not intended to be compilable.' @echo ' dir/file.ll - Build the LLVM assembly file' @echo '' @$(if $(dtstree), \