forked from datenlord/linux
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnet.rs
More file actions
1714 lines (1549 loc) · 58 KB
/
net.rs
File metadata and controls
1714 lines (1549 loc) · 58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-2.0
//! Networking core.
//!
//! C headers: [`include/net/net_namespace.h`](../../../../include/linux/net/net_namespace.h),
//! [`include/linux/netdevice.h`](../../../../include/linux/netdevice.h),
//! [`include/linux/skbuff.h`](../../../../include/linux/skbuff.h).
//! [`include/linux/ethtool.h`](../../../../include/linux/ethtool.h).
use crate::{
bindings,
error::{from_kernel_err_ptr, from_kernel_result},
prelude::*,
str::CStr,
to_result, ARef, AlwaysRefCounted, Error, PointerWrapper, Result,
};
use alloc::slice;
use core::{self, cell::UnsafeCell, ptr::NonNull};
#[cfg(CONFIG_NETFILTER)]
pub mod filter;
/// Wraps the kernel's `struct net_device`.
#[repr(transparent)]
pub struct Device(UnsafeCell<bindings::net_device>);
impl Device {
pub fn alloc_etherdev_mqs(sizeof: i32, count: u32) -> Result<ARef<Self>> {
// SAFETY: FFI call.
let res =
from_kernel_err_ptr(unsafe { bindings::alloc_etherdev_mqs(sizeof, count, count) })?;
// SAFETY: Since the `net_device` creation succeeded, the `res` must be valid.
let net: ARef<_> = unsafe { &*(res as *const Device) }.into();
Ok(net)
}
pub fn register_netdev(&mut self) -> Result<usize>{
unsafe{from_kernel_err_ptr(bindings::register_netdev(self.0 as *mut bindings::net_device))?}
}
pub fn netif_set_real_num_tx_queues(&mut self, txq: u32) {
unsafe{bindings::netif_set_real_num_tx_queues(self.0 as *mut bindings::net_device,
txq)}
}
pub fn netif_set_real_num_rx_queues(&mut self, rxq: u32) {
unsafe{bindings::netif_set_real_num_tx_queues(self.0 as *mut bindings::net_device,
rxq)}
}
pub fn priv_flags(&self) -> u32 {
unsafe { (*self.0).priv_flags as _ };
}
pub fn set_priv_flags(&mut self, flags: u32) {
unsafe { (*self.0).priv_flags = flags as _ };
}
pub fn set_ethtool_ops(&mut self, ops: &'static bindings::ethtool_ops) {
unsafe { (*self.0).ethtool_ops = ops};
}
pub fn set_netdev_ops(&mut self, ops: &'static bindings::net_device_ops) {
unsafe { (*self.0).netdev_ops = ops};
}
pub fn freatures(&mut self) -> u32 {
unsafe { (*self.0).features as _ };
}
pub fn set_freatures(&mut self, features: u32) {
unsafe { (*self.0).features = features};
}
pub fn set_vlan_features(&mut self, vlan_features: u32) {
unsafe { (*self.0).vlan_features = vlan_features};
}
pub fn set_min_mtu(&mut self, min_mtu: u32) {
unsafe { (*self.0).min_mtu = min_mtu};
}
pub fn set_max_mtu(&mut self, max_mtu: u32) {
unsafe { (*self.0).max_mtu = max_mtu};
}
}
// SAFETY: Instances of `Device` are created on the C side. They are always refcounted.
unsafe impl AlwaysRefCounted for Device {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
unsafe { bindings::dev_hold(self.0.get()) };
}
unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
// SAFETY: The safety requirements guarantee that the refcount is nonzero.
unsafe { bindings::dev_put(obj.cast().as_ptr()) };
}
}
/// Registration structure for a network device.
pub struct Registration<T: DeviceOperations> {
dev: *mut bindings::net_device,
registered: bool,
_p: PhantomData<T>,
}
impl<T: DeviceOperations> Registration<T> {
/// Creates new instance of registration.
pub fn try_new(parent: &dyn device::RawDevice) -> Result<Self> {
// SAFETY: FFI call.
let dev = unsafe { bindings::alloc_etherdev_mqs(size_of::<*mut u64>(), 1, 1) };
if dev.is_null() {
Err(ENOMEM)
} else {
// SAFETY: `dev` was allocated during initialization and is guaranteed to be valid.
unsafe { (*dev).dev.parent = parent.raw_device() }
Ok(Registration {
dev,
registered: false,
_p: PhantomData,
})
}
}
/// Returns a network device.
/// A driver might configure the device before registration.
pub fn dev_get(&self) -> ARef<Device> {
unsafe { &*(self.dev as *const Device) }.into()
}
/// Register a network device.
pub fn register(&mut self, data: T::Data) -> Result {
// SAFETY: `dev` was allocated during initialization and is guaranteed to be valid.
let ret = unsafe {
(*self.dev).netdev_ops = Self::build_device_ops();
bindings::register_netdev(self.dev)
};
if ret != 0 {
Err(Error::from_kernel_errno(ret))
} else {
self.registered = true;
unsafe {
// SAFETY: The C contract guarantees that `data` is available
// for implementers of the net_device operations (no other C code accesses
// it), so we know that there are no concurrent threads/CPUs accessing
// it (it's not visible to any other Rust code).
// bindings::dev_set_drvdata(&mut (*self.dev).dev, data.into_pointer() as _);
(*bindings::net_priv(self.dev))= T::Data::into_pointer(data) as _;
}
Ok(())
}
}
}
/// Wraps the kernel's `struct net`.
#[repr(transparent)]
pub struct Namespace(UnsafeCell<bindings::net>);
impl Namespace {
/// Finds a network device with the given name in the namespace.
pub fn dev_get_by_name(&self, name: &CStr) -> Option<ARef<Device>> {
// SAFETY: The existence of a shared reference guarantees the refcount is nonzero.
let ptr =
NonNull::new(unsafe { bindings::dev_get_by_name(self.0.get(), name.as_char_ptr()) })?;
Some(unsafe { ARef::from_raw(ptr.cast()) })
}
}
// SAFETY: Instances of `Namespace` are created on the C side. They are always refcounted.
unsafe impl AlwaysRefCounted for Namespace {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
unsafe { bindings::get_net(self.0.get()) };
}
unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
// SAFETY: The safety requirements guarantee that the refcount is nonzero.
unsafe { bindings::put_net(obj.cast().as_ptr()) };
}
}
/// Returns the network namespace for the `init` process.
pub fn init_ns() -> &'static Namespace {
unsafe { &*core::ptr::addr_of!(bindings::init_net).cast() }
}
/// Wraps the kernel's `struct sk_buff`.
#[repr(transparent)]
pub struct SkBuff(UnsafeCell<bindings::sk_buff>);
impl SkBuff {
/// Creates a reference to an [`SkBuff`] from a valid pointer.
///
/// # Safety
///
/// The caller must ensure that `ptr` is valid and remains valid for the lifetime of the
/// returned [`SkBuff`] instance.
pub unsafe fn from_ptr<'a>(ptr: *const bindings::sk_buff) -> &'a SkBuff {
// SAFETY: The safety requirements guarantee the validity of the dereference, while the
// `SkBuff` type being transparent makes the cast ok.
unsafe { &*ptr.cast() }
}
/// Returns the remaining data in the buffer's first segment.
pub fn head_data(&self) -> &[u8] {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
let headlen = unsafe { bindings::skb_headlen(self.0.get()) };
let len = headlen.try_into().unwrap_or(usize::MAX);
// SAFETY: The existence of a shared reference means `self.0` is valid.
let data = unsafe { core::ptr::addr_of!((*self.0.get()).data).read() };
// SAFETY: The `struct sk_buff` conventions guarantee that at least `skb_headlen(skb)` bytes
// are valid from `skb->data`.
unsafe { core::slice::from_raw_parts(data, len) }
}
/// Returns the total length of the data (in all segments) in the skb.
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> u32 {
// SAFETY: The existence of a shared reference means `self.0` is valid.
unsafe { core::ptr::addr_of!((*self.0.get()).len).read() }
}
}
// SAFETY: Instances of `SkBuff` are created on the C side. They are always refcounted.
unsafe impl AlwaysRefCounted for SkBuff {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference means that the refcount is nonzero.
unsafe { bindings::skb_get(self.0.get()) };
}
unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
// SAFETY: The safety requirements guarantee that the refcount is nonzero.
unsafe {
bindings::kfree_skb_reason(
obj.cast().as_ptr(),
bindings::skb_drop_reason_SKB_DROP_REASON_NOT_SPECIFIED,
)
};
}
}
/// An IPv4 address.
///
/// This is equivalent to C's `in_addr`.
#[repr(transparent)]
pub struct Ipv4Addr(bindings::in_addr);
impl Ipv4Addr {
/// A wildcard IPv4 address.
///
/// Binding to this address means binding to all IPv4 addresses.
pub const ANY: Self = Self::new(0, 0, 0, 0);
/// The IPv4 loopback address.
pub const LOOPBACK: Self = Self::new(127, 0, 0, 1);
/// The IPv4 broadcast address.
pub const BROADCAST: Self = Self::new(255, 255, 255, 255);
/// Creates a new IPv4 address with the given components.
pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Self {
Self(bindings::in_addr {
s_addr: u32::from_be_bytes([a, b, c, d]).to_be(),
})
}
}
/// An IPv6 address.
///
/// This is equivalent to C's `in6_addr`.
#[repr(transparent)]
pub struct Ipv6Addr(bindings::in6_addr);
impl Ipv6Addr {
/// A wildcard IPv6 address.
///
/// Binding to this address means binding to all IPv6 addresses.
pub const ANY: Self = Self::new(0, 0, 0, 0, 0, 0, 0, 0);
/// The IPv6 loopback address.
pub const LOOPBACK: Self = Self::new(0, 0, 0, 0, 0, 0, 0, 1);
/// Creates a new IPv6 address with the given components.
#[allow(clippy::too_many_arguments)]
pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Self {
Self(bindings::in6_addr {
in6_u: bindings::in6_addr__bindgen_ty_1 {
u6_addr16: [
a.to_be(),
b.to_be(),
c.to_be(),
d.to_be(),
e.to_be(),
f.to_be(),
g.to_be(),
h.to_be(),
],
},
})
}
}
/// A socket address.
///
/// It's an enum with either an IPv4 or IPv6 socket address.
pub enum SocketAddr {
/// An IPv4 socket address.
V4(SocketAddrV4),
/// An IPv6 socket address.
V6(SocketAddrV6),
}
/// An IPv4 socket address.
///
/// This is equivalent to C's `sockaddr_in`.
#[repr(transparent)]
pub struct SocketAddrV4(bindings::sockaddr_in);
impl SocketAddrV4 {
/// Creates a new IPv4 socket address.
pub const fn new(addr: Ipv4Addr, port: u16) -> Self {
Self(bindings::sockaddr_in {
sin_family: bindings::AF_INET as _,
sin_port: port.to_be(),
sin_addr: addr.0,
__pad: [0; 8],
})
}
/// Creates a new IPv4 socket address from C's `sockaddr_in` or `sockaddr` pointer.
///
/// # Safety
///
/// The caller must ensure that `ptr` points to C's `sockaddr_in` or `sockaddr`.
pub const unsafe fn from_ptr(ptr: *mut core::ffi::c_void) -> Self {
// Safety: The safety requirements guarantee the validity of the cast.
let ptr_n = ptr as *mut bindings::sockaddr_in;
// SAFETY: The above cast guarantees the validity of the dereference.
unsafe {
Self(bindings::sockaddr_in {
sin_family: (*ptr_n).sin_family,
sin_port: (*ptr_n).sin_port,
sin_addr: (*ptr_n).sin_addr,
__pad: (*ptr_n).__pad,
})
}
}
}
/// An IPv6 socket address.
///
/// This is equivalent to C's `sockaddr_in6`.
#[repr(transparent)]
pub struct SocketAddrV6(bindings::sockaddr_in6);
impl SocketAddrV6 {
/// Creates a new IPv6 socket address.
pub const fn new(addr: Ipv6Addr, port: u16, flowinfo: u32, scopeid: u32) -> Self {
Self(bindings::sockaddr_in6 {
sin6_family: bindings::AF_INET6 as _,
sin6_port: port.to_be(),
sin6_addr: addr.0,
sin6_flowinfo: flowinfo,
sin6_scope_id: scopeid,
})
}
}
/// A socket listening on a TCP port.
///
/// # Invariants
///
/// The socket pointer is always non-null and valid.
pub struct TcpListener {
pub(crate) sock: *mut bindings::socket,
}
// SAFETY: `TcpListener` is just a wrapper for a kernel socket, which can be used from any thread.
unsafe impl Send for TcpListener {}
// SAFETY: `TcpListener` is just a wrapper for a kernel socket, which can be used from any thread.
unsafe impl Sync for TcpListener {}
impl TcpListener {
/// Creates a new TCP listener.
///
/// It is configured to listen on the given socket address for the given namespace.
pub fn try_new(ns: &Namespace, addr: &SocketAddr) -> Result<Self> {
let mut socket = core::ptr::null_mut();
let (pf, addr, addrlen) = match addr {
SocketAddr::V4(addr) => (
bindings::PF_INET,
addr as *const _ as _,
core::mem::size_of::<bindings::sockaddr_in>(),
),
SocketAddr::V6(addr) => (
bindings::PF_INET6,
addr as *const _ as _,
core::mem::size_of::<bindings::sockaddr_in6>(),
),
};
// SAFETY: The namespace is valid and the output socket pointer is valid for write.
to_result(unsafe {
bindings::sock_create_kern(
ns.0.get(),
pf as _,
bindings::sock_type_SOCK_STREAM as _,
bindings::IPPROTO_TCP as _,
&mut socket,
)
})?;
// INVARIANT: The socket was just created, so it is valid.
let listener = Self { sock: socket };
// SAFETY: The type invariant guarantees that the socket is valid, and `addr` and `addrlen`
// were initialised based on valid values provided in the address enum.
to_result(unsafe { bindings::kernel_bind(socket, addr, addrlen as _) })?;
// SAFETY: The socket is valid per the type invariant.
to_result(unsafe { bindings::kernel_listen(socket, bindings::SOMAXCONN as _) })?;
Ok(listener)
}
/// Accepts a new connection.
///
/// On success, returns the newly-accepted socket stream.
///
/// If no connection is available to be accepted, one of two behaviours will occur:
/// - If `block` is `false`, returns [`crate::error::code::EAGAIN`];
/// - If `block` is `true`, blocks until an error occurs or some connection can be accepted.
pub fn accept(&self, block: bool) -> Result<TcpStream> {
let mut new = core::ptr::null_mut();
let flags = if block { 0 } else { bindings::O_NONBLOCK };
// SAFETY: The type invariant guarantees that the socket is valid, and the output argument
// is also valid for write.
to_result(unsafe { bindings::kernel_accept(self.sock, &mut new, flags as _) })?;
Ok(TcpStream { sock: new })
}
}
impl Drop for TcpListener {
fn drop(&mut self) {
// SAFETY: The type invariant guarantees that the socket is valid.
unsafe { bindings::sock_release(self.sock) };
}
}
/// A connected TCP socket.
///
/// # Invariants
///
/// The socket pointer is always non-null and valid.
pub struct TcpStream {
pub(crate) sock: *mut bindings::socket,
}
// SAFETY: `TcpStream` is just a wrapper for a kernel socket, which can be used from any thread.
unsafe impl Send for TcpStream {}
// SAFETY: `TcpStream` is just a wrapper for a kernel socket, which can be used from any thread.
unsafe impl Sync for TcpStream {}
impl TcpStream {
/// Reads data from a connected socket.
///
/// On success, returns the number of bytes read, which will be zero if the connection is
/// closed.
///
/// If no data is immediately available for reading, one of two behaviours will occur:
/// - If `block` is `false`, returns [`crate::error::code::EAGAIN`];
/// - If `block` is `true`, blocks until an error occurs, the connection is closed, or some
/// becomes readable.
pub fn read(&self, buf: &mut [u8], block: bool) -> Result<usize> {
let mut msg = bindings::msghdr::default();
let mut vec = bindings::kvec {
iov_base: buf.as_mut_ptr().cast(),
iov_len: buf.len(),
};
// SAFETY: The type invariant guarantees that the socket is valid, and `vec` was
// initialised with the output buffer.
let r = unsafe {
bindings::kernel_recvmsg(
self.sock,
&mut msg,
&mut vec,
1,
vec.iov_len,
if block { 0 } else { bindings::MSG_DONTWAIT } as _,
)
};
if r < 0 {
Err(Error::from_kernel_errno(r))
} else {
Ok(r as _)
}
}
/// Writes data to the connected socket.
///
/// On success, returns the number of bytes written.
///
/// If the send buffer of the socket is full, one of two behaviours will occur:
/// - If `block` is `false`, returns [`crate::error::code::EAGAIN`];
/// - If `block` is `true`, blocks until an error occurs or some data is written.
pub fn write(&self, buf: &[u8], block: bool) -> Result<usize> {
let mut msg = bindings::msghdr {
msg_flags: if block { 0 } else { bindings::MSG_DONTWAIT },
..bindings::msghdr::default()
};
let mut vec = bindings::kvec {
iov_base: buf.as_ptr() as *mut u8 as _,
iov_len: buf.len(),
};
// SAFETY: The type invariant guarantees that the socket is valid, and `vec` was
// initialised with the input buffer.
let r = unsafe { bindings::kernel_sendmsg(self.sock, &mut msg, &mut vec, 1, vec.iov_len) };
if r < 0 {
Err(Error::from_kernel_errno(r))
} else {
Ok(r as _)
}
}
}
impl Drop for TcpStream {
fn drop(&mut self) {
// SAFETY: The type invariant guarantees that the socket is valid.
unsafe { bindings::sock_release(self.sock) };
}
}
/// A structure for `NAPI` scheduling with weighting.
pub struct NapiStruct {
napi: bindings::napi_struct,
}
impl NapiStruct {
/// New an uninitialized `NapiStruct`.
///
/// # Safety
///
/// Callers must call [`NapiStruct::init`] before using the `NapiStruct` item.
unsafe fn new() -> Self {
Self {
napi: bindings::napi_struct::default(),
}
}
// Init the `NapiStruct` item.
fn init(
&mut self,
dev: &mut Device,
poll: Option<
unsafe extern "C" fn(
arg1: *mut bindings::napi_struct,
arg2: core::ffi::c_int,
) -> core::ffi::c_int,
>,
weight: i32,
) -> Result<usize> {
// SAFETY: The existence of the shared references mean `dev.0` and `self.0` are valid.
unsafe {
bindings::netif_napi_add_weight(
dev.0.get_mut() as _,
&mut self.napi as *mut bindings::napi_struct,
poll,
weight,
);
}
Ok(0)
}
}
/// The main device statistics structure.
///
/// # Invariants
///
/// `ptr` is always non-null and valid.
pub struct RtnlLinkStats64 {
ptr: *mut bindings::rtnl_link_stats64,
}
impl RtnlLinkStats64 {
/// Constructs a new `struct rtnl_link_stats64` wrapper.
///
/// # Safety
///
/// The pointer `ptr` must be non-null and valid for the lifetime of the returned object.
pub(crate) unsafe fn from_ptr(ptr: *mut bindings::rtnl_link_stats64) -> Self {
// INVARIANT: The safety requirements ensure the invariant.
Self { ptr }
}
}
/// RX/TX ring parameters.
///
/// # Invariants
///
/// `ptr` is always non-null and valid.
pub struct EthtoolRingparam {
ptr: *mut bindings::ethtool_ringparam,
}
impl EthtoolRingparam {
/// Constructs a new `struct ethtool_ringparam` wrapper.
///
/// # Safety
///
/// The pointer `ptr` must be non-null and valid for the lifetime of the returned object.
pub(crate) unsafe fn from_ptr(ptr: *mut bindings::ethtool_ringparam) -> Self {
// INVARIANT: The safety requirements ensure the invariant.
Self { ptr }
}
/// Sets the rx_max_pending associated with the ethtool ring param.
pub fn set_rx_max_pending(&mut self, rx_max_pending: u32) {
// SAFETY: `self.ptr` is valid by the type invariants.
unsafe { (*self.ptr).rx_max_pending = rx_max_pending as _ };
}
/// Sets the tx_max_pending associated with the ethtool ring param.
pub fn set_tx_max_pending(&mut self, tx_max_pending: u32) {
// SAFETY: `self.ptr` is valid by the type invariants.
unsafe { (*self.ptr).tx_max_pending = tx_max_pending as _ };
}
/// Sets the rx_pending associated with the ethtool ring param.
pub fn set_rx_pending(&mut self, rx_pending: u32) {
// SAFETY: `self.ptr` is valid by the type invariants.
unsafe { (*self.ptr).rx_pending = rx_pending as _ };
}
/// Sets the tx_pending associated with the ethtool ring param.
pub fn set_tx_pending(&mut self, tx_pending: u32) {
// SAFETY: `self.ptr` is valid by the type invariants.
unsafe { (*self.ptr).tx_pending = tx_pending as _ };
}
}
/// General driver and device information.
///
/// # Invariants
///
/// `ptr` is always non-null and valid.
pub struct EthtoolDrvinfo {
ptr: *mut bindings::ethtool_drvinfo,
}
impl EthtoolDrvinfo {
/// Constructs a new `struct irq_domain` wrapper.
///
/// # Safety
///
/// The pointer `ptr` must be non-null and valid for the lifetime of the returned object.
pub(crate) unsafe fn from_ptr(ptr: *mut bindings::ethtool_drvinfo) -> Self {
// INVARIANT: The safety requirements ensure the invariant.
Self { ptr }
}
}
/// Device-specific statistics.
///
/// # Invariants
///
/// `ptr` is always non-null and valid.
pub struct EthtoolStats {
ptr: *mut bindings::ethtool_stats,
}
impl EthtoolStats {
/// Constructs a new `struct ethtool_stats` wrapper.
///
/// # Safety
///
/// The pointer `ptr` must be non-null and valid for the lifetime of the returned object.
pub(crate) unsafe fn from_ptr(ptr: *mut bindings::ethtool_stats) -> Self {
// INVARIANT: The safety requirements ensure the invariant.
Self { ptr }
}
}
/// Configuring number of network channel.
///
/// # Invariants
///
/// `ptr` is always non-null and valid.
pub struct EthtoolChannels {
ptr: *mut bindings::ethtool_channels,
}
impl EthtoolChannels {
/// Constructs a new `struct ethtool_channels` wrapper.
///
/// # Safety
///
/// The pointer `ptr` must be non-null and valid for the lifetime of the returned object.
pub(crate) unsafe fn from_ptr(ptr: *mut bindings::ethtool_channels) -> Self {
// INVARIANT: The safety requirements ensure the invariant.
Self { ptr }
}
}
/// Link control and status.
///
/// # Invariants
///
/// `ptr` is always non-null and valid.
pub struct EthtoolLinkKsettings {
ptr: *const bindings::ethtool_link_ksettings,
}
impl EthtoolLinkKsettings {
/// Constructs a new `struct ethtool_link_ksettings` wrapper.
///
/// # Safety
///
/// The pointer `ptr` must be non-null and valid for the lifetime of the returned object.
pub(crate) unsafe fn from_ptr(ptr: *const bindings::ethtool_link_ksettings) -> Self {
// INVARIANT: The safety requirements ensure the invariant.
Self { ptr }
}
}
/// Command to get or set RX flow classification rules.
///
/// # Invariants
///
/// `ptr` is always non-null and valid.
pub struct EthtoolRxnfc {
ptr: *mut bindings::ethtool_rxnfc,
}
impl EthtoolRxnfc {
/// Constructs a new `struct ethtool_rxnfc` wrapper.
///
/// # Safety
///
/// The pointer `ptr` must be non-null and valid for the lifetime of the returned object.
pub(crate) unsafe fn from_ptr(ptr: *mut bindings::ethtool_rxnfc) -> Self {
// INVARIANT: The safety requirements ensure the invariant.
Self { ptr }
}
}
/// Coalescing parameters for IRQs and stats updates.
///
/// # Invariants
///
/// `ptr` is always non-null and valid.
pub struct EthtoolCoalesce {
ptr: *mut bindings::ethtool_coalesce,
}
impl EthtoolCoalesce {
/// Constructs a new `struct ethtool_coalesce` wrapper.
///
/// # Safety
///
/// The pointer `ptr` must be non-null and valid for the lifetime of the returned object.
pub(crate) unsafe fn from_ptr(ptr: *mut bindings::ethtool_coalesce) -> Self {
// INVARIANT: The safety requirements ensure the invariant.
Self { ptr }
}
}
/// Holds a device's timestamping and PHC association.
///
/// # Invariants
///
/// `ptr` is always non-null and valid.
pub struct EthtoolTsInfo {
ptr: *mut bindings::ethtool_ts_info,
}
impl EthtoolTsInfo {
/// Constructs a new `struct ethtool_ts_info` wrapper.
///
/// # Safety
///
/// The pointer `ptr` must be non-null and valid for the lifetime of the returned object.
pub(crate) unsafe fn from_ptr(ptr: *mut bindings::ethtool_ts_info) -> Self {
// INVARIANT: The safety requirements ensure the invariant.
Self { ptr }
}
}
#[vtable]
pub trait EthtoolOps {
/// The pointer type that will be used to hold user-defined data type.
type DataEthtoolOps: PointerWrapper + Send + Sync = ();
fn get_drvinfo(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
info: EthtoolDrvinfo,
);
fn get_link(data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>) -> u32;
fn get_ringparam(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
ring: EthtoolRingparam,
);
fn get_strings(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
stringset: u32,
ptr: *mut u8,
) -> Result<u32>;
fn get_sset_count(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
sset: i32,
) -> Result<i32>;
fn get_ethtool_stats(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
stats: EthtoolStats,
data: *mut u64,
);
fn set_channels(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
ethtool_channels: EthtoolChannels,
) -> Result<u32>;
fn get_channels(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
ethtool_channels: EthtoolChannels,
);
fn get_ts_info(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
info: EthtoolTsInfo,
) -> Result<u32>;
fn get_link_ksettings(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
ethtool_link_ksettings: EthtoolLinkKsettings,
) -> Result<u32>;
fn set_link_ksettings(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
ethtool_link_ksettings: EthtoolLinkKsettings,
) -> Result<u32>;
fn set_coalesce(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
ethtool_coalesce: EthtoolCoalesce,
) -> Result<i32>;
fn get_coalesce(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
ethtool_coalesce: EthtoolCoalesce,
) -> Result<i32>;
fn get_rxfh_key_size(data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>) -> u32;
fn get_rxfh_indir_size(data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>) -> u32;
fn get_rxfh(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
indir: *mut u32,
key: *mut u8,
hfunc: *mut u8,
) -> Result<i32>;
fn set_rxfh(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
indir: *const u32,
key: *const u8,
hfunc: u8,
) -> Result<i32>;
fn get_rxnfc(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
info: EthtoolRxnfc,
) -> Result<u32>;
fn set_rxnfc(
data: <Self::DataEthtoolOps as PointerWrapper>::Borrowed<'_>,
info: EthtoolRxnfc,
) -> Result<u32>;
}
#[vtable]
pub trait NetdevOps {
/// The pointer type that will be used to hold user-defined data type.
type DataNetdevOps: PointerWrapper + Send + Sync = ();
fn ndo_open(data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>) -> Result<i32>;
fn ndo_stop(data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>) -> Result<i32>;
fn ndo_start_xmit(
skb: &SkBuff,
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
) -> bindings::netdev_tx_t;
fn ndo_validate_addr(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
) -> Result<i32>;
fn ndo_set_mac_address(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
addr: SocketAddr,
) -> Result<i32>;
fn ndo_set_rx_mode(data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>);
fn ndo_get_stats64(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
storage: RtnlLinkStats64,
);
fn ndo_vlan_rx_add_vid(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
proto: u16,
vid: u16,
) -> Result<i32>;
fn ndo_vlan_rx_kill_vid(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
proto: u16,
vid: u16,
) -> Result<i32>;
fn ndo_bpf(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
buffer: &mut [u8],
) -> Result<u32>;
fn ndo_xdp_xmit(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
buffer: &mut [u8],
) -> Result<u32>;
fn ndo_features_check(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
skb: &SkBuff,
info: bindings::netdev_features_t,
) -> bindings::netdev_features_t;
fn ndo_get_phys_port_name(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
buffer: &mut [u8],
) -> Result<i32>;
fn ndo_set_features(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
features: bindings::netdev_features_t,
) -> Result<i32>;
fn ndo_tx_timeout(
data: <Self::DataNetdevOps as PointerWrapper>::Borrowed<'_>,
txqueue: core::ffi::c_uint,
);
}
struct NetDeviceTables<T: EthtoolOps + NetdevOps>(T);
impl<T: EthtoolOps + NetdevOps> NetDeviceTables<T> {
const ETHTOOL_OPS: bindings::ethtool_ops = bindings::ethtool_ops {
_bitfield_1: bindings::__BindgenBitfieldUnit::new([1; 1]),
supported_ring_params: 0,
supported_coalesce_params: 0,
get_drvinfo: if <T>::HAS_GET_DRVINFO {
Some(Self::get_drvinfo_callback)
} else {
None
},
get_link: if <T>::HAS_GET_LINK {
Some(Self::get_link_callback)
} else {
None
},
get_ringparam: if <T>::HAS_GET_RINGPARAM {
Some(Self::get_ringparam_callback)
} else {
None
},
get_strings: if <T>::HAS_GET_STRINGS {
Some(Self::get_strings_callback)
} else {
None
},
get_sset_count: if <T>::HAS_GET_SSET_COUNT {
Some(Self::get_sset_count_callback)
} else {
None
},
get_ethtool_stats: if <T>::HAS_GET_ETHTOOL_STATS {
Some(Self::get_ethtool_stats_callback)
} else {
None
},