Skip to content

Commit 6ca2cb4

Browse files
committed
Rust NetDevice and NetDeviceOperationsVtable struct
also adds drivers/net/dummy_rs.rs Signed-off-by: Finn Behrens <[email protected]>
1 parent fc2b177 commit 6ca2cb4

14 files changed

+2243
-3
lines changed

Diff for: drivers/net/Kconfig

+16
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,22 @@ config DUMMY
7272
To compile this driver as a module, choose M here: the module
7373
will be called dummy.
7474

75+
config DUMMY_RS
76+
tristate "Dummy net driver support"
77+
depends on HAS_RUST
78+
help
79+
This is essentially a bit-bucket device (i.e. traffic you send to
80+
this device is consigned into oblivion) with a configurable IP
81+
address. It is most commonly used in order to make your currently
82+
inactive SLIP address seem like a real address for local programs.
83+
If you use SLIP or PPP, you might want to say Y here. It won't
84+
enlarge your kernel. What a deal. Read about it in the Network
85+
Administrator's Guide, available from
86+
<http://www.tldp.org/docs.html#guide>.
87+
88+
To compile this driver as a module, choose M here: the module
89+
will be called dummy_rs.
90+
7591
config WIREGUARD
7692
tristate "WireGuard secure network tunnel"
7793
depends on NET && INET

Diff for: drivers/net/Makefile

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ obj-$(CONFIG_BONDING) += bonding/
1010
obj-$(CONFIG_IPVLAN) += ipvlan/
1111
obj-$(CONFIG_IPVTAP) += ipvlan/
1212
obj-$(CONFIG_DUMMY) += dummy.o
13+
obj-$(CONFIG_DUMMY_RS) += dummy_rs.o
1314
obj-$(CONFIG_WIREGUARD) += wireguard/
1415
obj-$(CONFIG_EQUALIZER) += eql.o
1516
obj-$(CONFIG_IFB) += ifb.o

Diff for: drivers/net/dummy_rs.rs

+240
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Rust dummy network driver
4+
//!
5+
//! This is a demonstration of what a small driver looks like in Rust, based on drivers/net/dummy.c.
6+
//! This code is provided as a demonstration only, not as a proposal to mass-rewrite existing drivers in Rust
7+
//!
8+
//! The purpose of this driver is to provide a device to point a
9+
//! route through, but not to actually transmit packets.
10+
//!
11+
//! Why? If you have a machine whose only connection is an occasional
12+
//! PPP/SLIP/PLIP link, you can only connect to your own hostname
13+
//! when the link is up. Otherwise you have to use localhost.
14+
//! This isn't very consistent.
15+
//!
16+
//! One solution is to set up a dummy link using PPP/SLIP/PLIP,
17+
//! but this seems (to me) too much overhead for too little gain.
18+
//! This driver provides a small alternative. Thus you can do
19+
//!
20+
//! [when not running slip]
21+
//! ifconfig dummy slip.addr.ess.here up
22+
//! [to go to slip]
23+
//! ifconfig dummy down
24+
//! dip whatever
25+
//!
26+
//! This was written by looking at the dummy network driver from Nick
27+
//! Holloway, which was written by looking at Donald Becker's skeleton driver
28+
//! and the loopback driver.
29+
//!
30+
//! Finn Behrens, 30th April 2021
31+
//!
32+
//! rust rewrite of the C version from Nick Holloway, 27th May 1994
33+
//! see [dummy.c](./dummy.c)
34+
35+
#![no_std]
36+
#![feature(allocator_api, global_asm)]
37+
38+
use core::ops::Deref;
39+
40+
use kernel::net::device;
41+
use kernel::net::prelude::*;
42+
use kernel::net::rtnl;
43+
use kernel::Error;
44+
use kernel::{
45+
net::netlink::{NlAttrVec, NlExtAck},
46+
prelude::*,
47+
};
48+
49+
module! {
50+
type: RustNetDummy,
51+
name: b"dummy_rs",
52+
author: b"Rust for Linux Contributors",
53+
description: b"Rust dummy network driver",
54+
license: b"GPL v2",
55+
alias_rtnl_link: b"dummy_rs",
56+
params: {
57+
numdummies: usize {
58+
default: 0,
59+
permissions: 0,
60+
description: b"Number of dummy_rs pseudo devices",
61+
},
62+
},
63+
}
64+
65+
fn setup(dev: &mut NetDevice<DummyRsDev>) {
66+
dev.ether_setup();
67+
68+
dev.set_ops();
69+
70+
// Fill in device structure with ethernet-generic values.
71+
dev.add_flag(device::Iff::NOARP);
72+
dev.remove_flag(device::Iff::MULTICAST);
73+
74+
dev.add_private_flag(device::IffPriv::LIVE_ADDR_CHANGE);
75+
dev.add_private_flag(device::IffPriv::NO_QUEUE);
76+
77+
let mut feature = device::feature::NetIF::new();
78+
79+
feature += device::feature::NETIF_F_SG;
80+
feature += device::feature::NETIF_F_FRAGLIST;
81+
feature += device::feature::NETIF_F_GSO_SOFTWARE;
82+
feature += device::feature::NETIF_F_HW_CSUM;
83+
feature += device::feature::NETIF_F_HIGHDMA;
84+
feature += device::feature::NETIF_F_LLTX;
85+
feature += device::feature::NETIF_F_GSO_ENCAP_ALL;
86+
87+
dev.set_features(feature);
88+
dev.set_hw_features(feature);
89+
dev.set_hw_enc_features(feature);
90+
91+
dev.hw_addr_random();
92+
dev.set_mtu(0, 0);
93+
}
94+
95+
fn validate(tb: &NlAttrVec, _data: &NlAttrVec, _ext_ack: &NlExtAck) -> Result {
96+
if let Some(addr) = tb.get(kernel::bindings::IFLA_ADDRESS) {
97+
if addr.nla_len() != kernel::net::netlink::ETH_ALEN {
98+
return Err(Error::EINVAL);
99+
}
100+
if !addr.is_valid_ether_addr() {
101+
return Err(Error::EADDRNOTAVAIL);
102+
}
103+
}
104+
Ok(())
105+
}
106+
107+
rtnl_link_ops! {
108+
kind: b"dummy_rs",
109+
type: DummyRsDev,
110+
setup: setup,
111+
validate: validate,
112+
}
113+
114+
struct RustNetDummy {
115+
//dev: NetDevice<DummyRsDev>,
116+
}
117+
118+
impl KernelModule for RustNetDummy {
119+
fn init() -> Result<Self> {
120+
let num = *numdummies.read();
121+
122+
unsafe { dummy_rs_link_ops.register() }?;
123+
124+
for _ in 0..(num) {
125+
let dev = NetDevice::new(
126+
DummyRsDev,
127+
kernel::cstr!("dummyrs%d"),
128+
kernel::net::device::NetNameAssingType::Enum,
129+
1,
130+
1,
131+
)?;
132+
dev.set_rtnl_ops(unsafe { &dummy_rs_link_ops });
133+
134+
if let Err(e) = dev.register() {
135+
pr_warn!("could not register: {}", e.to_kernel_errno());
136+
return Err(e);
137+
}
138+
}
139+
140+
Ok(RustNetDummy {
141+
//dev,
142+
})
143+
}
144+
}
145+
146+
impl Drop for RustNetDummy {
147+
fn drop(&mut self) {
148+
// TODO: remove unsafe somehow
149+
unsafe { dummy_rs_link_ops.unregister() };
150+
}
151+
}
152+
153+
struct DummyRsDev;
154+
155+
impl NetDeviceOps<Self> for DummyRsDev {
156+
kernel::declare_net_device_ops!(
157+
get_stats64,
158+
change_carrier,
159+
validate_addr,
160+
set_mac_addr,
161+
set_rx_mode
162+
);
163+
164+
fn init(dev: &mut NetDevice<Self>) -> Result {
165+
dev.set_new_pcpu_lstats()?;
166+
Ok(())
167+
}
168+
169+
fn uninit(dev: &mut NetDevice<Self>) {
170+
unsafe { dev.free_lstats() };
171+
}
172+
173+
fn start_xmit(skb: SkBuff, dev: &mut NetDevice<Self>) -> kernel::net::device::NetdevTX {
174+
let mut skb = skb;
175+
176+
dev.lstats_add(skb.len());
177+
178+
skb.tx_timestamp();
179+
drop(skb);
180+
181+
kernel::net::device::NetdevTX::TX_OK
182+
}
183+
184+
fn get_stats64(dev: &NetDevice<Self>, stats: &mut rtnl::RtnlLinkStats64) {
185+
stats.dev_read(dev);
186+
}
187+
188+
fn change_carrier(dev: &mut NetDevice<Self>, new_carrier: bool) -> Result {
189+
dev.carrier_set(new_carrier);
190+
191+
Ok(())
192+
}
193+
194+
fn validate_addr(dev: &NetDevice<Self>) -> Result {
195+
device::helpers::eth_validate_addr(dev)
196+
}
197+
198+
fn set_mac_addr(
199+
dev: &mut NetDevice<Self>,
200+
p: *mut kernel::c_types::c_void,
201+
) -> Result {
202+
device::helpers::eth_mac_addr(dev, p)
203+
}
204+
205+
// [Someting about faking multicast](https://elixir.bootlin.com/linux/v5.12-rc4/source/drivers/net/dummy.c#L48).
206+
fn set_rx_mode(_dev: &mut NetDevice<Self>) {}
207+
}
208+
209+
impl NetDeviceAdapter for DummyRsDev {
210+
type Inner = Self;
211+
212+
type Ops = Self;
213+
214+
type EthOps = Self;
215+
216+
fn setup(dev: &mut NetDevice<Self>) {
217+
setup(dev);
218+
}
219+
}
220+
221+
impl EthToolOps<Self> for DummyRsDev {
222+
kernel::declare_eth_tool_ops!(get_drvinfo, get_ts_info);
223+
224+
fn get_drvinfo(_dev: &NetDevice<Self>, info: &mut ethtool::EthtoolDrvinfo) {
225+
// TODO: how to do this more efficient without unsafe?
226+
// FIXME: !!
227+
let info: &kernel::bindings::ethtool_drvinfo = info.deref();
228+
unsafe {
229+
kernel::bindings::strlcpy(
230+
&(info.driver) as *const _ as *mut i8,
231+
b"dummy_rs\0" as *const _ as *mut i8,
232+
32,
233+
);
234+
}
235+
}
236+
237+
fn get_ts_info(dev: &NetDevice<Self>, info: &mut ethtool::EthToolTsInfo) -> Result {
238+
kernel::net::ethtool::helpers::ethtool_op_get_ts_info(dev, info)
239+
}
240+
}

Diff for: rust/helpers.c

+32-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
#include <linux/gfp.h>
88
#include <linux/highmem.h>
99
#include <linux/uio.h>
10+
#include <linux/netdevice.h>
11+
#include <linux/etherdevice.h>
12+
#include <linux/rtnetlink.h>
1013

1114
void rust_helper_BUG(void)
1215
{
@@ -105,8 +108,36 @@ size_t rust_helper_copy_to_iter(const void *addr, size_t bytes, struct iov_iter
105108
}
106109
EXPORT_SYMBOL_GPL(rust_helper_copy_to_iter);
107110

108-
#if !defined(CONFIG_ARM)
111+
void *rust_helper_netdev_priv(struct net_device *dev)
112+
{
113+
return netdev_priv(dev);
114+
}
115+
EXPORT_SYMBOL_GPL(rust_helper_netdev_priv);
116+
117+
void rust_helper_eth_hw_addr_random(struct net_device *dev)
118+
{
119+
eth_hw_addr_random(dev);
120+
}
121+
EXPORT_SYMBOL_GPL(rust_helper_eth_hw_addr_random);
122+
123+
int rust_helper_net_device_set_new_lstats(struct net_device *dev)
124+
{
125+
dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats);
126+
if (!dev->lstats)
127+
return -ENOMEM;
128+
129+
return 0;
130+
}
131+
EXPORT_SYMBOL_GPL(rust_helper_net_device_set_new_lstats);
132+
133+
void rust_helper_dev_lstats_add(struct net_device *dev, unsigned int len)
134+
{
135+
dev_lstats_add(dev, len);
136+
}
137+
EXPORT_SYMBOL_GPL(rust_helper_dev_lstats_add);
138+
109139
// See https://github.com/rust-lang/rust-bindgen/issues/1671
140+
#if !defined(CONFIG_ARM)
110141
static_assert(__builtin_types_compatible_p(size_t, uintptr_t),
111142
"size_t must match uintptr_t, what architecture is this??");
112143
#endif

Diff for: rust/kernel/bindings_helper.h

+8
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22

33
#include <linux/cdev.h>
44
#include <linux/fs.h>
5+
#include <linux/netdevice.h>
6+
#include <linux/ethtool.h>
7+
#include <linux/etherdevice.h>
8+
#include <linux/netdev_features.h>
9+
#include <linux/rtnetlink.h>
10+
#include <net/rtnetlink.h>
511
#include <linux/module.h>
612
#include <linux/random.h>
713
#include <linux/slab.h>
@@ -17,3 +23,5 @@
1723
// `bindgen` gets confused at certain things
1824
const gfp_t BINDINGS_GFP_KERNEL = GFP_KERNEL;
1925
const gfp_t BINDINGS___GFP_ZERO = __GFP_ZERO;
26+
27+
const int BINDINGS_NLA_HDRLEN = NLA_HDRLEN;

Diff for: rust/kernel/error.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
77
use crate::{bindings, c_types};
88
use alloc::{alloc::AllocError, collections::TryReserveError};
9-
use core::{num::TryFromIntError, str::Utf8Error};
9+
use core::{convert::TryFrom, num::TryFromIntError, str::Utf8Error};
1010

1111
/// Generic integer kernel error.
1212
///
@@ -48,6 +48,9 @@ impl Error {
4848
/// Interrupted system call.
4949
pub const EINTR: Self = Error(-(bindings::EINTR as i32));
5050

51+
/// Cannot assign requested address
52+
pub const EADDRNOTAVAIL: Self = Error(-(bindings::EADDRNOTAVAIL as i32));
53+
5154
/// Creates an [`Error`] from a kernel error code.
5255
pub fn from_kernel_errno(errno: c_types::c_int) -> Error {
5356
Error(errno)
@@ -104,3 +107,24 @@ impl From<AllocError> for Error {
104107
Error::ENOMEM
105108
}
106109
}
110+
111+
/// Used by the rtnl_link_ops macro to interface with C
112+
pub fn c_from_kernel_result<T>(r: Result<T>) -> T
113+
where
114+
T: TryFrom<c_types::c_int>,
115+
T::Error: core::fmt::Debug,
116+
{
117+
match r {
118+
Ok(v) => v,
119+
Err(e) => T::try_from(e.to_kernel_errno()).unwrap(),
120+
}
121+
}
122+
123+
#[macro_export]
124+
macro_rules! c_from_kernel_result {
125+
($($tt:tt)*) => {{
126+
$crate::c_from_kernel_result((|| {
127+
$($tt)*
128+
})())
129+
}};
130+
}

Diff for: rust/kernel/lib.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ mod error;
4343
pub mod file;
4444
pub mod file_operations;
4545
pub mod miscdev;
46+
pub mod net;
4647
pub mod pages;
4748

4849
pub mod linked_list;
@@ -65,7 +66,7 @@ pub mod iov_iter;
6566
mod types;
6667
pub mod user_ptr;
6768

68-
pub use crate::error::{Error, Result};
69+
pub use crate::error::{c_from_kernel_result, Error, Result};
6970
pub use crate::types::{CStr, Mode};
7071

7172
/// Page size defined in terms of the `PAGE_SHIFT` macro from C.

0 commit comments

Comments
 (0)