samples: rust: add dummy network driver
Subsystems (3)
A message that is not in the archive (sent off-list or not yet received): [email protected]
PATCH v2 1/5 rust: core abstractions for network device drivers
From: FUJITA Tomonori <[email protected]>
This patch adds very basic abstractions to implement network device drivers, corresponds to the kernel's net_device and net_device_ops structs with support for register_netdev/unregister_netdev functions.
--- rust/bindings/bindings_helper.h | 2 + rust/helpers.c | 16 ++ rust/kernel/lib.rs | 3 + rust/kernel/net.rs | 5 + rust/kernel/net/dev.rs | 292 ++++++++++++++++++++++++++++++++ 5 files changed, 318 insertions(+) create mode 100644 rust/kernel/net.rs create mode 100644 rust/kernel/net/dev.rs
rust/bindings/bindings_helper.h +2 -0
@@ -6,6 +6,8 @@* Sorted alphabetically. */ +#include <linux/etherdevice.h> +#include <linux/netdevice.h> #include <linux/slab.h> #include <linux/refcount.h> #include <linux/wait.h>
rust/helpers.c +16 -0
@@ -23,10 +23,26 @@#include <linux/err.h> #include <linux/refcount.h> #include <linux/mutex.h> +#include <linux/netdevice.h> +#include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/sched/signal.h> #include <linux/wait.h> +#ifdef CONFIG_NET +void *rust_helper_netdev_priv (const struct net_device *dev) +{ +return netdev_priv (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_netdev_priv); + +void rust_helper_skb_tx_timestamp (struct sk_buff *skb) +{ +skb_tx_timestamp (skb); +} +EXPORT_SYMBOL_GPL (rust_helper_skb_tx_timestamp); +#endif +__noreturn void rust_helper_BUG (void ) {BUG ();
rust/kernel/lib.rs +3 -0
@@ -13,6 +13,7 @@#![no_std] #![feature(allocator_api)] +#![feature(const_maybe_uninit_zeroed)] #![feature(coerce_unsized)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)]
@@ -34,6 +35,8 @@pub mod error;pub mod init;pub mod ioctl; +#[cfg( CONFIG_NET )] +pub mod net;pub mod prelude;pub mod print;mod static_assert;
rust/kernel/net.rs new file +5 -0
@@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Networking core. + +pub mod dev;
rust/kernel/net/dev.rs new file +292 -0
292 lines not on this page · raw message
Signature · 1 line
2.34.1
Re: [PATCH v2 1/5] rust: core abstractions for network device drivers
Quoted 16 lines
rust/helpers.c +4
-0@@ -23,10 +23,26 @@#include <linux/err.h> #include <linux/refcount.h> #include <linux/mutex.h> +#include <linux/netdevice.h> +#include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/sched/signal.h> #include <linux/wait.h> +#ifdef CONFIG_NET +void *rust_helper_netdev_priv (const struct net_device *dev)
rust/helpers.c line 43
Quoted 10 lines
rust/helpers.c +10
-0+{ +return netdev_priv (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_netdev_priv); + +void rust_helper_skb_tx_timestamp (struct sk_buff *skb) +{ +skb_tx_timestamp (skb); +} +EXPORT_SYMBOL_GPL (rust_helper_skb_tx_timestamp);
This question is probably due to me not knowing about rust. Why have these helpers? They don't appear to don't do anything.
rust/helpers.c
Quoted 10 lines
rust/helpers.c +10
-0+impl<D: DriverData, T: DeviceOperations<D>> Registration<T, D> { +/// Creates new instance of registration. + pub fn try_new(tx_queue_size: u32, rx_queue_size: u32, data: D::Data) -> Result<Self> { +// SAFETY: FFI call. + let ptr = from_err_ptr(unsafe { + bindings::alloc_etherdev_mqs( + core::mem::size_of::<*const c_void>() as i32, + tx_queue_size, + rx_queue_size, + )
In the future, there might be some naming issues there. Not every network device in Linux is an Ethernet network device. Some network drivers will call alloc_netdev, or some other specialised allocator.
Andrew
Re: [PATCH v2 1/5] rust: core abstractions for network device drivers
Quoted 14 lines · Andrew Lunn
Quoted 14 lines
rust/helpers.c +2
-0@@ -23,10 +23,26 @@#include <linux/err.h> #include <linux/refcount.h> #include <linux/mutex.h> +#include <linux/netdevice.h> +#include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/sched/signal.h> #include <linux/wait.h>
Quoted 15 lines
rust/helpers.c line 43
Quoted 12 lines
rust/helpers.c +12
-0+#ifdef CONFIG_NET +void *rust_helper_netdev_priv (const struct net_device *dev) +{ +return netdev_priv (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_netdev_priv); + +void rust_helper_skb_tx_timestamp (struct sk_buff *skb) +{ +skb_tx_timestamp (skb); +} +EXPORT_SYMBOL_GPL (rust_helper_skb_tx_timestamp);This question is probably due to me not knowing about rust. Why have these helpers? They don't appear to don't do anything.
It's because we can't call inline C functions directly, so we need a non-inline version of it. (Similarly for #defines.)
Alice
Re: [PATCH v2 1/5] rust: core abstractions for network device drivers
Quoted 30 lines · Alice Ryhl
Quoted 20 lines · Andrew Lunn
Quoted 20 lines
rust/helpers.c +9
-0@@ -23,10 +23,26 @@#include <linux/err.h> #include <linux/refcount.h> #include <linux/mutex.h> +#include <linux/netdevice.h> +#include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/sched/signal.h> #include <linux/wait.h> +#ifdef CONFIG_NET +void *rust_helper_netdev_priv (const struct net_device *dev) +{ +return netdev_priv (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_netdev_priv); +Quoted 8 lines
rust/helpers.c line 43
Quoted 5 lines
rust/helpers.c +5
-0+void rust_helper_skb_tx_timestamp (struct sk_buff *skb) +{ +skb_tx_timestamp (skb); +} +EXPORT_SYMBOL_GPL (rust_helper_skb_tx_timestamp);This question is probably due to me not knowing about rust. Why have these helpers? They don't appear to don't do anything.
Quoted 2 lines
It's because we can't call inline C functions directly, so we need a non-inline version of it. (Similarly for #defines.)
Ah, thanks for the explanation.
This is going to be a problem for networking. The hot path has a lot of inline functions, because a function call is expensive. So there are going to be a lot of little wrappers like this. I don't want to encourage early optimisation without proper profiling, but at some point you might want to replace these wrappers with Rust, using whatever its equivalent of inline is.
Andrew
Re: [PATCH v2 1/5] rust: core abstractions for network device drivers
Quoted 9 lines · Andrew Lunn
Ah, thanks for the explanation.
This is going to be a problem for networking. The hot path has a lot of inline functions, because a function call is expensive. So there are going to be a lot of little wrappers like this. I don't want to encourage early optimisation without proper profiling, but at some point you might want to replace these wrappers with Rust, using whatever its equivalent of inline is.
Yeah, other use cases will also need that solved, e.g. Andreas for his NVMe work.
We discussed reimplementing performance-critical bits in Rust as you suggest, as well as cross-language LTO. We also talked about possible alternative approaches like "manual local LTO" for the helpers only via feeding their LLVM IR to rustc, which may recover most of the performance without having to go for full LTO and its associated kernel link times.
Cheers,
Miguel
Re: [PATCH v2 1/5] rust: core abstractions for network device drivers
In reply to Andrew LunnHi,
Quoted 11 lines · On Sat, 10 Jun 2023 16:11:41 +0200 Andrew Lunn <[email protected]> wrote:
rust/kernel/net/dev.rs line 92
Quoted 10 lines
rust/kernel/net/dev.rs new file +10
-0+impl<D: DriverData, T: DeviceOperations<D>> Registration<T, D> { + /// Creates new instance of registration. + pub fn try_new(tx_queue_size: u32, rx_queue_size: u32, data: D::Data) -> Result<Self> { + // SAFETY: FFI call. + let ptr = from_err_ptr(unsafe { + bindings::alloc_etherdev_mqs( + core::mem::size_of::<*const c_void>() as i32, + tx_queue_size, + rx_queue_size, + )
Quoted 4 lines
In the future, there might be some naming issues there. Not every network device in Linux is an Ethernet network device. Some network drivers will call
alloc_netdev, or some other specialised allocator.
Yeah, I thought about it. Actually dummy.c uses alloc_netdev (then calls ether_setup so does the same things that alloc_etherdev_mqs).
Wrapping alloc_etherdev_mqs is simpler because of a function pointer argument in alloc_netdev so I used alloc_etherdev_mqs.
Once someone takes up the issue, I guess that we could add new functions for other allocators.
thanks,
Re: [PATCH v2 1/5] rust: core abstractions for network device drivers
Quoted 2 lines
Once someone takes up the issue, I guess that we could add new functions for other allocators.
Then it would be good to name this function to make it clear it allocates and ethernet netdev, so leaving the namespace clean for other allocators.
Andrew
Re: [PATCH v2 1/5] rust: core abstractions for network device drivers
In reply to FUJITA Tomonorirust/kernel/net/dev.rs line 21
Quoted 9 lines · FUJITA Tomonori
rust/kernel/net/dev.rs new file +8
-0+/// Corresponds to the kernel's `struct net_device`. +/// +/// # Safety +/// +/// The kernel uses a `net_device` object with various functions like `struct net_device_ops`. +/// This object is passed to Rust callbacks while these functions are running. +/// The C API guarantees that `net_device` isn't released while this function is running. +pub struct Device (*mut bindings::net_device );
This is not a function :) So "while this function is running" does not make too much sense here.
Also, this is a struct, so we do not use # Safety sections. Instead, you may want to give this struct a # Invariants section, and explain what is guaranteed by this type.
Similarly for SkBuff below.
rust/kernel/net/dev.rs line 33
Quoted 4 lines
rust/kernel/net/dev.rs new file +4
-0+fn priv_data_ptr (netdev: *mut bindings::net_device ) -> *const c_void { +// SAFETY: The safety requirement ensures that the pointer is valid. +unsafe { core::ptr::read (bindings::netdev_priv (&mut *netdev)as *const *const c_void ) } + }
Like in the other patch, there is no safety requirement in this function, so you can't use that to justify it.
Even if this is a private function, it would be best if this is unsafe, then you can require callers to pass you a valid pointer -- you already have a SAFETY comment in the callers anyway, and those are the ones that can actually claim that the pointer is valid.
rust/kernel/net/dev.rs line 39
Quoted 4 lines
rust/kernel/net/dev.rs new file +4
-0+// SAFETY: `Device` exposes the state, `D::Data` object across threads +// but that type is required to be Send and Sync. +unsafe impl Send for Device {} +unsafe impl Sync for Device {}
Please provide a SAFETY comment for each. See e.g. the ones we have for ARef.
In addition, what is D::Data here? I guess you are referring to DriverData::Data somehow, but it is unclear what is D here.
Also, please use Markdown in comments, not just documentation, to be consistent, e.g.
... to be `Send` and `Sync`.
rust/kernel/net/dev.rs line 68
Quoted 9 lines
rust/kernel/net/dev.rs new file +9
-0+/// # Safety +/// +/// The pointer to the `net_device` object is guaranteed to be valid until +/// the registration object is dropped. +pub struct Registration <T :DeviceOperations <D >,D :DriverData > { + dev:Device , + is_registered:bool , + _p:PhantomData <(D ,T )>, +}
Ditto about this being a struct and # Safety.
Also, if it is valid until dropped, then it is "always" valid (as far as someone having such an object is concerned), so there is no need to say so.
rust/kernel/net/dev.rs line 72
Quoted 2 lines
rust/kernel/net/dev.rs new file +2
-0+fn drop (&mut self) { +// SAFETY: `dev` was allocated during initialization and guaranteed to be valid.
Do you mean dev.0?
Quoted 1 line
+ // SAFETY: the kernel allocated the space for a pointer.
Please capitalize to be consistent.
rust/kernel/net/dev.rs line 158
Quoted 6 lines
rust/kernel/net/dev.rs new file +5
-0+unsafe { +let priv_ptr = bindings::netdev_priv (ptr)as *mut *const c_void ; + core::ptr::write (priv_ptr, data.into_foreign ()); + } + ..unsafe { core::mem::MaybeUninit ::<bindings::net_device_ops >::zeroed ().assume_init () }
A comment on this would be nice. Also, missing SAFETY comment, even if it is a const.
Thanks!
Cheers,
Miguel
Re: [PATCH v2 1/5] rust: core abstractions for network device drivers
Hi,
Thanks a lot for reviewing!
Quoted 14 lines · On Sat, 10 Jun 2023 21:49:50 +0200 Miguel Ojeda…
Review
Quoted 9 lines · FUJITA Tomonori
(quoted diff) +8
-0+/// Corresponds to the kernel's `struct net_device`. +/// +/// # Safety +/// +/// The kernel uses a `net_device` object with various functions like `struct net_device_ops`. +/// This object is passed to Rust callbacks while these functions are running. +/// The C API guarantees that `net_device` isn't released while this function is running. +pub struct Device(*mut bindings::net_device);This is not a function :) So "while this function is running" does not make too much sense here.
Quoted 5 lines
Also, this is a
struct, so we do not use# Safetysections. Instead, you may want to give this struct a# Invariantssection, and explain what is guaranteed by this type.Similarly for
SkBuffbelow.
Sorry, obviously, I didn't understand comments about safety. Aded # Invariants section to both structures.
I've updated the comments and put the fixed version at the end. Can you check again? If it looks fine, I'll update the comments in the rest of patches.
Quoted 5 lines
Review
Quoted 4 lines
(quoted diff) +4
-0+ fn priv_data_ptr(netdev: *mut bindings::net_device) -> *const c_void { + // SAFETY: The safety requirement ensures that the pointer is valid. + unsafe { core::ptr::read(bindings::netdev_priv(&mut *netdev) as *const *const c_void) } + }
Quoted 7 lines
Like in the other patch, there is no safety requirement in this function, so you can't use that to justify it.
Even if this is a private function, it would be best if this is
unsafe, then you can require callers to pass you a valid pointer -- you already have aSAFETYcomment in the callers anyway, and those are the ones that can actually claim that the pointer is valid.
Fixed.
Quoted 8 lines
Review
Quoted 4 lines
(quoted diff) +4
-0+// SAFETY: `Device` exposes the state, `D::Data` object across threads +// but that type is required to be Send and Sync. +unsafe impl Send for Device {} +unsafe impl Sync for Device {}Please provide a
SAFETYcomment for each. See e.g. the ones we have forARef.
Quoted 7 lines
In addition, what is
D::Datahere? I guess you are referring toDriverData::Datasomehow, but it is unclear what isDhere.Also, please use Markdown in comments, not just documentation, to be consistent, e.g.
... to be `Send` and `Sync`.
Fixed both.
Quoted 12 lines
Review
Quoted 9 lines
(quoted diff) +9
-0+/// # Safety +/// +/// The pointer to the `net_device` object is guaranteed to be valid until +/// the registration object is dropped. +pub struct Registration<T: DeviceOperations<D>, D: DriverData> { + dev: Device, + is_registered: bool, + _p: PhantomData<(D, T)>, +}Ditto about this being a
structand# Safety.
Quoted 3 lines
Also, if it is valid until dropped, then it is "always" valid (as far as someone having such an object is concerned), so there is no need to say so.
Fixed.
Quoted 8 lines
Review
Quoted 2 lines
(quoted diff) +2
-0+ fn drop(&mut self) { + // SAFETY: `dev` was allocated during initialization and guaranteed to be valid.Do you mean
dev.0?Quoted 1 line
+ // SAFETY: the kernel allocated the space for a pointer.
Please capitalize to be consistent.
Fixed both.
Quoted 9 lines
Review
Quoted 6 lines
(quoted diff) +5
-0+ unsafe { + let priv_ptr = bindings::netdev_priv(ptr) as *mut *const c_void; + core::ptr::write(priv_ptr, data.into_foreign()); + } + ..unsafe { core::mem::MaybeUninit::<bindings::net_device_ops>::zeroed().assume_init() }A comment on this would be nice. Also, missing
SAFETYcomment, even if it is aconst.
Added.
Here's a fixed version.
rust: core abstractions for network device drivers
This patch adds very basic abstractions to implement network device drivers, corresponds to the kernel's net_device and net_device_ops structs with support for register_netdev/unregister_netdev functions.
allows the const_maybe_uninit_zeroed feature for core::mem::MaybeUinit::<T>::zeroed() in const function.
--- rust/bindings/bindings_helper.h | 2 + rust/helpers.c | 16 ++ rust/kernel/lib.rs | 3 + rust/kernel/net.rs | 5 + rust/kernel/net/dev.rs | 340 ++++++++++++++++++++++++++++++++ 5 files changed, 366 insertions(+) create mode 100644 rust/kernel/net.rs create mode 100644 rust/kernel/net/dev.rs
rust/bindings/bindings_helper.h +2 -0
@@ -6,6 +6,8 @@* Sorted alphabetically. */ +#include <linux/etherdevice.h> +#include <linux/netdevice.h> #include <linux/slab.h> #include <linux/refcount.h> #include <linux/wait.h>
rust/helpers.c +16 -0
@@ -23,10 +23,26 @@#include <linux/err.h> #include <linux/refcount.h> #include <linux/mutex.h> +#include <linux/netdevice.h> +#include <linux/skbuff.h> #include <linux/spinlock.h> #include <linux/sched/signal.h> #include <linux/wait.h> +#ifdef CONFIG_NET +void *rust_helper_netdev_priv (const struct net_device *dev) +{ +return netdev_priv (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_netdev_priv); + +void rust_helper_skb_tx_timestamp (struct sk_buff *skb) +{ +skb_tx_timestamp (skb); +} +EXPORT_SYMBOL_GPL (rust_helper_skb_tx_timestamp); +#endif +__noreturn void rust_helper_BUG (void ) {BUG ();
rust/kernel/lib.rs +3 -0
@@ -13,6 +13,7 @@#![no_std] #![feature(allocator_api)] +#![feature(const_maybe_uninit_zeroed)] #![feature(coerce_unsized)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)]
@@ -34,6 +35,8 @@pub mod error;pub mod init;pub mod ioctl; +#[cfg( CONFIG_NET )] +pub mod net;pub mod prelude;pub mod print;mod static_assert;
rust/kernel/net.rs new file +5 -0
@@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Networking core. + +pub mod dev;
rust/kernel/net/dev.rs new file +340 -0
340 lines not on this page · raw message
Signature · 1 line
2.34.1
Re: [PATCH v2 1/5] rust: core abstractions for network device drivers
Quoted 7 lines · FUJITA Tomonori
Sorry, obviously, I didn't understand comments about safety. Aded
# Invariantssection to both structures.I've updated the comments and put the fixed version at the end. Can you check again? If it looks fine, I'll update the comments in the rest of patches.
Looks better now (without having checked if they are correct w.r.t. what the C side guarantees) -- thanks! A couple comments below.
rust/kernel/net/dev.rs line 42
Quoted 11 lines
rust/kernel/net/dev.rs new file +11
-0+/// Gets a pointer to network device private data. +/// +/// A driver in C uses contiguous memory `struct net_device` and its private data. +/// A driver in Rust contiguous memory `struct net_device` and a pointer to its private data. +/// So a driver in Rust pays extra cost to access to its private data. +/// A device driver passes an properly initialized private data and the kernel saves +/// its pointer. +fn priv_data_ptr (&self) -> *const c_void { +// SAFETY: The type invariants guarantee that `self.0` is valid. +unsafe { core::ptr::read (bindings::netdev_priv (self.0 )as *const *const c_void ) } + }
Part of the docs of this function should probably be moved to the SAFETY comment, since it is needed to justify the ptr::read (and it is an implementation detail): self.0 is valid here, but we need to justify why reading from the returned pointer from netdev_priv is OK, and for that one needs to know the layout explained in the docs above.
Also, in general, please always aim to minimize what unsafe blocks cover. For instance, here there should be two blocks: one for the FFI call, and the other for the pointer read. Splitting such blocks makes it very clear that there are two different proofs needed here.
rust/kernel/net/dev.rs line 109
Quoted 7 lines
rust/kernel/net/dev.rs new file +7
-0+// SAFETY: `ptr` is valid and non-null since `alloc_etherdev_mqs()` +// returned a valid pointer which was null-checked. +let dev =unsafe { +let priv_ptr = bindings::netdev_priv (ptr)as *mut *const c_void ; + core::ptr::write (priv_ptr, data.into_foreign ()); +Device ::from_ptr (ptr) + };
Similarly here, i.e. the SAFETY comment does not mention why is priv_ptr valid for the ptr::write.
Cheers,
Miguel
PATCH v2 2/5 rust: add support for ethernet operations
In reply to a message not in the archiveFrom: FUJITA Tomonori <[email protected]>
This improves abstractions for network device drivers to implement struct ethtool_ops, the majority of ethernet device drivers need to do.
struct ethtool_ops also needs to access to device private data like struct net_devicve_ops.
Currently, only get_ts_info operation is supported. The following patch adds the Rust version of the dummy network driver thats uses the feature.
--- rust/bindings/bindings_helper.h | 1 + rust/kernel/net/dev.rs | 90 +++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+)
rust/bindings/bindings_helper.h +1 -0
@@ -7,6 +7,7 @@*/ #include <linux/etherdevice.h> +#include <linux/ethtool.h> #include <linux/netdevice.h> #include <linux/slab.h> #include <linux/refcount.h>
rust/kernel/net/dev.rs +90 -0
99 lines not on this page · raw message
Signature · 1 line
2.34.1
Re: [PATCH v2 2/5] rust: add support for ethernet operations
rust/kernel/net/dev.rs fn drop(&mut self) { · line 376
Quoted 7 lines
rust/kernel/net/dev.rs +7
-0+/// Corresponds to the kernel's `struct ethtool_ts_info`. +pub struct EthtoolTsInfo (*mut bindings::ethtool_ts_info ); + +/// Sets up the info for software timestamping. +/// +/// This can be [`Device`] method, but there are non ethernet devices. +pub fn ethtool_op_get_ts_info (dev: &mut Device , info: &mut EthtoolTsInfo ) ->Result {
Just an FYI: Despite it being called ethtool, it is not limited to ethernet devices. e.g. CAN devices make use of ethtool.
Andrew
Re: [PATCH v2 2/5] rust: add support for ethernet operations
Hi,
Quoted 10 lines · On Sat, 10 Jun 2023 18:48:00 +0200 Andrew Lunn <[email protected]> wrote:
rust/kernel/net/dev.rs fn drop(&mut self) { · line 376
Quoted 7 lines
rust/kernel/net/dev.rs +7
-0+/// Corresponds to the kernel's `struct ethtool_ts_info`. +pub struct EthtoolTsInfo (*mut bindings::ethtool_ts_info ); + +/// Sets up the info for software timestamping. +/// +/// This can be [`Device`] method, but there are non ethernet devices. +pub fn ethtool_op_get_ts_info (dev: &mut Device , info: &mut EthtoolTsInfo ) ->Result {Just an FYI: Despite it being called ethtool, it is not limited to ethernet devices. e.g. CAN devices make use of ethtool.
I see, I'll remove the comment in the next version.
thanks,
Re: [PATCH v2 2/5] rust: add support for ethernet operations
In reply to FUJITA Tomonorirust/kernel/net/dev.rs pub fn register(&mut self) -> Result { · line 142
Quoted 12 lines · FUJITA Tomonori
rust/kernel/net/dev.rs +11
-0+/// Sets `ethtool_ops` of `net_device`. +pub fn set_ether_operations <U >(&mut self) ->Result +where +U :EtherOperations <D >, + { +if self.is_registered { +Err (code::EINVAL ) + }else { +EtherOperationsAdapter ::<U ,D >::new ().set_ether_ops (&mut self.dev); +Ok (()) + }
You may want to use early return style, like in C, i.e. return Err(...);.
rust/kernel/net/dev.rs fn drop(&mut self) { · line 332
Quoted 2 lines
rust/kernel/net/dev.rs +2
-0+T ::get_ts_info (&mut dev, data, &mut info)?; +Ok (0 )
Can this be simplified to:
T::get_ts_info(&mut dev, data, &mut info)
?
rust/kernel/net/dev.rs fn drop(&mut self) { · line 354
Quoted 6 lines
rust/kernel/net/dev.rs +6
-0+fn set_ether_ops (&self, dev: &mut Device ) { +// SAFETY: The safety requirement ensures that the pointer is valid. +unsafe { + (*dev.0 ).ethtool_ops =Self ::build_ether_ops (); + } + }
Which safety requirement? Normally when we say "safety requirement", we are referring to the # Safety section on the current function (i.e. which would be unsafe). But this one is a safe function.
If you are referring to Device's, then that is a struct, so it would have invariants, not safety requirements (I will leave a quick note there too).
rust/kernel/net/dev.rs fn drop(&mut self) { · line 380
Quoted 8 lines
rust/kernel/net/dev.rs +8
-0+/// Sets up the info for software timestamping. +/// +/// This can be [`Device`] method, but there are non ethernet devices. +pub fn ethtool_op_get_ts_info (dev: &mut Device , info: &mut EthtoolTsInfo ) ->Result { +// SAFETY: The safety requirement ensures that the pointer is valid. +unsafe { + bindings::ethtool_op_get_ts_info (dev.0 , info.0 ); + }
Ditto here: there are no safety requirements in this function.
Cheers,
Miguel
Re: [PATCH v2 2/5] rust: add support for ethernet operations
Hi,
Quoted 14 lines · On Sat, 10 Jun 2023 21:14:37 +0200 Miguel Ojeda…
rust/kernel/net/dev.rs pub fn register(&mut self) -> Result { · line 142
Quoted 12 lines · FUJITA Tomonori
rust/kernel/net/dev.rs +11
-0+/// Sets `ethtool_ops` of `net_device`. +pub fn set_ether_operations <U >(&mut self) ->Result +where +U :EtherOperations <D >, + { +if self.is_registered { +Err (code::EINVAL ) + }else { +EtherOperationsAdapter ::<U ,D >::new ().set_ether_ops (&mut self.dev); +Ok (()) + }
Quoted 1 line
You may want to use early return style, like in C, i.e.
return Err(...);.
Sure, I'll update the code in that way.
Quoted 8 lines
rust/kernel/net/dev.rs fn drop(&mut self) { · line 332
Quoted 2 lines
rust/kernel/net/dev.rs +2
-0+T ::get_ts_info (&mut dev, data, &mut info)?; +Ok (0 )Can this be simplified to:
T::get_ts_info(&mut dev, data, &mut info)?
We could do:
T::get_ts_info(&mut dev, data, &mut info).map(|_| 0)
thanks,
Re: [PATCH v2 2/5] rust: add support for ethernet operations
Quoted 4 lines · FUJITA Tomonori
We could do:
T::get_ts_info(&mut dev, data, &mut info).map(|_| 0)
Ah, yeah, then the one you had originally is probably better.
Cheers,
Miguel
PATCH v2 3/5 rust: add support for get_stats64 in struct net_device_ops
In reply to a message not in the archiveFrom: FUJITA Tomonori <[email protected]>
get_stats64() is used to return the stats for user-space like the number of packets, which network device drivers are supposed to support.
--- rust/kernel/net/dev.rs | 58 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-)
rust/kernel/net/dev.rs +57 -1
@@ -8,7 +8,12 @@//! [`include/linux/skbuff.h`](../../../../include/linux/skbuff.h), //! [`include/uapi/linux/if_link.h`](../../../../include/uapi/linux/if_link.h). -use crate ::{bindings, error::*, prelude::vtable, types::ForeignOwnable }; +use crate ::{ + bindings, + error::*, + prelude::vtable, + types::{ForeignOwnable ,Opaque }, +};use {core::ffi::c_void, core::marker::PhantomData };/// Corresponds to the kernel's `struct net_device`.
@@ -168,6 +173,11 @@ pub fn set_ether_operations<U>(&mut self) -> Result }else {None }, + ndo_get_stats64: if <T>::HAS_GET_STATS64 { +Some (Self ::get_stats64_callback) + }else { +None + }, ..unsafe { core::mem::MaybeUninit ::<bindings::net_device_ops >::zeroed ().assume_init () } };
@@ -223,6 +233,18 @@ const fn build_device_ops() -> &'static bindings::net_device_ops {let skb =SkBuff (skb);T ::start_xmit (&mut dev, data, skb)as bindings::netdev_tx_t } + +unsafe extern "C" fn get_stats64_callback ( + netdev: *mut bindings::net_device , + stats: *mut bindings::rtnl_link_stats64 , + ) { +// SAFETY: The C API guarantees that `net_device` isn't released while this function is running. +let data =unsafe {D ::Data ::borrow (Device ::priv_data_ptr (netdev)) }; +let mut dev =Device (netdev); +// SAFETY: for writing and nobody else will read or write to it. +let stats =unsafe {RtnlLinkStats64 ::from_raw (stats) }; +T ::get_stats64 (&mut dev, data, stats); + } }// SAFETY: `Registration` exposes its state, `D::Data` object across threads
@@ -270,6 +292,14 @@ fn start_xmit( ) -> TxCode {TxCode ::Busy } + +/// Corresponds to `ndo_get_stats64` in `struct net_device_ops`. +fn get_stats64 ( + _dev: &mut Device , + _data: <D ::Data as ForeignOwnable >::Borrowed <'_>, + _stats: &mut RtnlLinkStats64 , + ) { + } }/// Corresponds to the kernel's `struct sk_buff`.
@@ -304,6 +334,32 @@ fn drop(&mut self) { } } +/// Corresponds to the kernel's `struct rtnl_link_stats64`. +#[repr(transparent)] +pub struct RtnlLinkStats64 (Opaque <bindings::rtnl_link_stats64 >); + +impl RtnlLinkStats64 { +/// # Safety +/// +/// For the duration of the lifetime 'a, the pointer must be valid for writing and nobody else +/// may read or write to the `rtnl_link_stats64` object. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::rtnl_link_stats64 ) -> &'amut Self { +unsafe { &mut *(ptras *mut Self ) } + } + +/// Updates TX stats. +pub fn set_tx_stats (&mut self, packets:u64 , bytes:u64 , errors:u64 , dropped:u64 ) { +// SAFETY: We have exclusive access to the `rtnl_link_stats64`, so writing to it is okay. +unsafe { +let inner =Opaque ::get (&self.0 ); + (*inner).tx_packets = packets; + (*inner).tx_bytes = bytes; + (*inner).tx_errors = errors; + (*inner).tx_dropped = dropped; + } + } +} +/// Builds the kernel's `struct ethtool_ops`. struct EtherOperationsAdapter <D ,T > { _p:PhantomData <(D ,T )>,
Signature · 1 line
2.34.1
PATCH v2 4/5 rust: add methods for configure net_device
In reply to a message not in the archiveFrom: FUJITA Tomonori <[email protected]>
adds methods to net::Device for the basic configurations of net_device.
--- rust/helpers.c | 7 ++++ rust/kernel/net/dev.rs | 76 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+)
rust/helpers.c +7 -0
@@ -21,6 +21,7 @@#include <linux/bug.h> #include <linux/build_bug.h> #include <linux/err.h> +#include <linux/etherdevice.h> #include <linux/refcount.h> #include <linux/mutex.h> #include <linux/netdevice.h>
@@ -30,6 +31,12 @@#include <linux/wait.h> #ifdef CONFIG_NET +void rust_helper_eth_hw_addr_random (struct net_device *dev) +{ +eth_hw_addr_random (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_eth_hw_addr_random); +void *rust_helper_netdev_priv (const struct net_device *dev) {return netdev_priv (dev);
rust/kernel/net/dev.rs +76 -0
88 lines not on this page · raw message
Signature · 1 line
2.34.1
PATCH v2 5/5 samples: rust: add dummy network driver
In reply to a message not in the archiveFrom: FUJITA Tomonori <[email protected]>
This is a simpler version of drivers/net/dummy.c.
This demonstrates the usage of abstractions for network device drivers.
--- samples/rust/Kconfig | 11 +++++ samples/rust/Makefile | 1 + samples/rust/rust_net_dummy.rs | 85 ++++++++++++++++++++++++++++++++++ scripts/Makefile.build | 2 +- 4 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 samples/rust/rust_net_dummy.rs
samples/rust/Kconfig +11 -0
@@ -30,6 +30,17 @@ config SAMPLE_RUST_PRINT If unsure, say N. +config SAMPLE_RUST_NET_DUMMY + tristate "Dummy network driver" + help + This is the simpler version of drivers/net/dummy.c. No intention to replace it. This provides educational information for Rust + abstractions for network drivers. + + To compile this as a module, choose M here: + the module will be called rust_minimal. + + If unsure, say N. + config SAMPLE_RUST_HOSTPROGS bool "Host programs" help
samples/rust/Makefile +1 -0
@@ -2,5 +2,6 @@ obj-$(CONFIG_SAMPLE_RUST_MINIMAL) += rust_minimal.o obj-$(CONFIG_SAMPLE_RUST_PRINT) += rust_print.o +obj-$(CONFIG_SAMPLE_RUST_NET_DUMMY) += rust_net_dummy.o subdir-$(CONFIG_SAMPLE_RUST_HOSTPROGS) += hostprogs
samples/rust/rust_net_dummy.rs new file +85 -0
85 lines not on this page · raw message
scripts/Makefile.build +1 -1
@@ -277,7 +277,7 @@ $(obj)/%.lst: $(src)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- -rust_allowed_features := new_uninit +rust_allowed_features := allocator_api,new_uninit rust_common_cmd = \ RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \
Signature · 1 line
2.34.1
Quoted 1 line
+ pr_info!("Hello Rust dummy netdev!");
In general, we discourage the use of pr_info(). netdev_info(ndev, ...) is what should be used, once the device is registered. The output then includes which device is says "hello world", which can be useful when you have more than one of them. netdev_info() can be called before the device is registered, but since the name is not fixed at that point, the output is a bit more ambiguous.
I would not say this is a blocked for this patchset, but i would add wrapping netdev_{dbg|warn|info|error}() high on your todo list, they are pretty fundamental to network drivers.
Andrew
Hi,
Quoted 9 lines · On Sat, 10 Jun 2023 18:59:52 +0200 Andrew Lunn <[email protected]> wrote:
Quoted 1 line
+ pr_info!("Hello Rust dummy netdev!");
In general, we discourage the use of
pr_info().netdev_info(ndev, ...)is what should be used, once the device is registered. The output then includes which device is says "hello world", which can be useful when you have more than one of them.netdev_info()can be called before the device is registered, but since the name is not fixed at that point, the output is a bit more ambiguous.
Quoted 3 lines
I would not say this is a blocked for this patchset, but i would add wrapping netdev_{dbg|warn|info|error}() high on your todo list, they are pretty fundamental to network drivers.
Sure, I'll add it to my after-initial-upstreaming TODO list with per_cpu stuff.
For now, I'll add 'TODO' comment in the next version.
thanks,
samples/rust/Kconfig config SAMPLE_RUST_PRINT · line 37
Quoted 6 lines · FUJITA Tomonori
samples/rust/Kconfig +5
-0+config SAMPLE_RUST_NET_DUMMY + tristate "Dummy network driver" + help + This is the simpler version of drivers/net/dummy.c. No intention to replace it. This provides educational information for Rust + abstractions for network drivers.
Long line.
Also, should this depend on NET?
samples/rust/rust_net_dummy.rs line 6
Quoted 2 lines
samples/rust/rust_net_dummy.rs new file +2
-0+use kernel::{ + bindings, c_str,
We should avoid using bindings outside the kernel crate (or, in the future, subsystem crates). Ideally this may be a hard error in the future (we have to see if we need flexibility in some places).
samples/rust/rust_net_dummy.rs line 31
Quoted 2 lines
samples/rust/rust_net_dummy.rs new file +2
-0+// device driver specific information +struct Stats {}
Please follow the documentation style used elsewhere.
samples/rust/rust_net_dummy.rs line 85
Quoted 7 lines
samples/rust/rust_net_dummy.rs new file +7
-0+module! { +type :DummyNetdev , + name:"rust_net_dummy" , + author:"Rust for Linux Contributors" , + description:"Rust dummy netdev" , + license:"GPL v2" , +}
Please move this to the top like in the other samples -- it is the convention we are following so far (even though it is different from the C side, and could change, but we should remain consistent).
scripts/Makefile.build $(obj)/%.lst: $(src)/%.c FORCE · line 280
Quoted 5 lines
# Compile Rust sources (.rs)
# ---------------------------------------------------------------------------scripts/Makefile.build +1
-1-rust_allowed_features := new_uninit +rust_allowed_features := allocator_api,new_uninit
Please add a note that you are adding this in the commit message, and which functionality we need from it.
Thanks!
Cheers,
Miguel