-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathif_net.rs
More file actions
729 lines (604 loc) · 22.6 KB
/
if_net.rs
File metadata and controls
729 lines (604 loc) · 22.6 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
//! # Network Interface Module
//!
//! This module provides the network interface module.
//!
//! `IfNet` is a structure that manages the network interface.
//! `NetDriver` is a structure that manages the network driver.
//!
//! These structures contain the following mutex-protected fields:
//!
//! 1. `NetDriver::rx_ringq`
//! 2. `IfNet::tx_ringq`
//! 3. `IfNet::inner`
//!
//! These mutexes must be locked in the order shown above.
use core::sync::atomic::{AtomicUsize, Ordering};
use alloc::{collections::BTreeMap, sync::Arc};
use awkernel_async_lib_verified::ringq::RingQ;
use smoltcp::{
iface::{Config, Interface, SocketSet},
phy::{self, Checksum, Device, DeviceCapabilities},
time::Instant,
wire::HardwareAddress,
};
use crate::sync::{mcs::MCSNode, mutex::Mutex, rwlock::RwLock};
use super::{
ether::{extract_headers, NetworkHdr, TransportHdr},
net_device::{EtherFrameBuf, EtherFrameRef, NetCapabilities, NetDevice, PacketHeaderFlags},
};
#[cfg(not(feature = "std"))]
use core::net::Ipv4Addr;
#[cfg(not(feature = "std"))]
use super::{ether::ETHER_ADDR_LEN, multicast::ipv4_addr_to_mac_addr, NetManagerError};
#[cfg(not(feature = "std"))]
use smoltcp::iface::MulticastError;
#[cfg(not(feature = "std"))]
use alloc::{
collections::{btree_map, BTreeSet},
vec,
vec::Vec,
};
struct NetDriver {
inner: Arc<dyn NetDevice + Sync + Send>,
rx_que_id: usize,
rx_ringq: Mutex<RingQ<EtherFrameBuf>>,
}
struct NetDriverRef<'a> {
inner: &'a Arc<dyn NetDevice + Sync + Send>,
rx_ringq: Option<&'a mut RingQ<EtherFrameBuf>>,
tx_ringq: &'a mut RingQ<Vec<u8>>,
}
impl NetDriverRef<'_> {
fn tx_packet_header_flags(&self, data: &[u8]) -> PacketHeaderFlags {
let mut flags = PacketHeaderFlags::empty();
let Ok(ext) = extract_headers(data) else {
return flags;
};
let capabilities = self.capabilities();
if matches!(ext.network, NetworkHdr::Ipv4(_)) && !capabilities.checksum.ipv4.tx() {
flags.insert(PacketHeaderFlags::IPV4_CSUM_OUT); // IPv4 checksum offload
}
match ext.transport {
TransportHdr::Tcp(_) => {
if !capabilities.checksum.tcp.tx() {
flags.insert(PacketHeaderFlags::TCP_CSUM_OUT); // TCP checksum offload
}
}
TransportHdr::Udp(_) => {
if !capabilities.checksum.udp.tx() {
flags.insert(PacketHeaderFlags::UDP_CSUM_OUT); // UDP checksum offload
}
}
_ => {}
}
flags
}
}
impl Device for NetDriverRef<'_> {
type RxToken<'b>
= NRxToken
where
Self: 'b;
type TxToken<'b>
= NTxToken<'b>
where
Self: 'b;
fn capabilities(&self) -> phy::DeviceCapabilities {
let mut cap = DeviceCapabilities::default();
cap.max_transmission_unit = 1500;
cap.max_burst_size = Some(64);
let capabilities = self.inner.capabilities();
if capabilities.contains(NetCapabilities::CSUM_IPv4) {
cap.checksum.ipv4 = Checksum::Rx;
}
// Note: Awkernel doen't yet support Ipv6.
// Additionally, tests for TCP functionality have not yet been conducted.
// Checksum offload currently only supports UDPv4.
// if capabilities.contains(NetCapabilities::CSUM_TCPv4 | NetCapabilities::CSUM_TCPv6) {
// cap.checksum.tcp = Checksum::Rx;
// }
// if capabilities.contains(NetCapabilities::CSUM_UDPv4 | NetCapabilities::CSUM_UDPv6) {
// cap.checksum.udp = Checksum::Rx;
// }
if capabilities.contains(NetCapabilities::CSUM_UDPv4) {
cap.checksum.udp = Checksum::Rx;
}
cap
}
/// The additional transmit token makes it possible to generate a reply packet
/// based on the contents of the received packet, without heap allocation.
fn receive(
&mut self,
_timestamp: smoltcp::time::Instant,
) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
if let Some(que) = self.rx_ringq.as_mut() {
if let Some(data) = que.pop() {
return Some((
NRxToken { data },
NTxToken {
tx_ring: self.tx_ringq,
},
));
}
}
None
}
/// The real packet transmission is performed when the token is consumed.
fn transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>> {
if !self.inner.can_send() {
return None;
}
if self.tx_ringq.is_full() {
return None;
}
Some(NTxToken {
tx_ring: self.tx_ringq,
})
}
}
pub(super) struct IfNet {
vlan: Option<u16>,
pub(super) inner: Mutex<IfNetInner>,
pub(super) socket_set: RwLock<SocketSet<'static>>,
rx_irq_to_driver: BTreeMap<u16, NetDriver>,
tx_only_ringq: Vec<Mutex<RingQ<Vec<u8>>>>,
pub(super) net_device: Arc<dyn NetDevice + Sync + Send>,
pub(super) is_poll_mode: bool,
poll_driver: Option<NetDriver>,
tick_driver: Option<NetDriver>,
time: crate::time::Time,
will_poll: AtomicUsize,
}
pub(super) struct IfNetInner {
pub(super) interface: Interface,
pub(super) default_gateway_ipv4: Option<smoltcp::wire::Ipv4Address>,
#[cfg(not(feature = "std"))]
multicast_addr_ipv4: BTreeSet<Ipv4Addr>,
#[cfg(not(feature = "std"))]
multicast_addr_mac: BTreeMap<[u8; ETHER_ADDR_LEN], u32>,
}
impl IfNetInner {
#[inline(always)]
pub fn get_interface(&mut self) -> &mut Interface {
&mut self.interface
}
#[inline(always)]
pub fn get_default_gateway_ipv4(&self) -> Option<smoltcp::wire::Ipv4Address> {
self.default_gateway_ipv4
}
#[inline(always)]
pub fn set_default_gateway_ipv4(&mut self, gateway: smoltcp::wire::Ipv4Address) {
if self.default_gateway_ipv4.is_some() {
self.interface.routes_mut().remove_default_ipv4_route();
}
self.interface
.routes_mut()
.add_default_ipv4_route(gateway)
.unwrap();
log::error!("adding {gateway:?} as a gateway");
self.default_gateway_ipv4 = Some(gateway);
}
}
impl IfNet {
pub fn new(net_device: Arc<dyn NetDevice + Sync + Send>, vlan: Option<u16>) -> Self {
let time = crate::time::Time::now();
let interface = {
let mut tx_ringq = RingQ::new(0);
let mut net_driver_ref = NetDriverRef {
inner: &net_device,
rx_ringq: None,
tx_ringq: &mut tx_ringq,
};
let instant = Instant::from_micros(time.uptime().as_micros() as i64);
let hardware_address =
HardwareAddress::Ethernet(smoltcp::wire::EthernetAddress(net_device.mac_address()));
let mut config = Config::new(hardware_address);
config.random_seed = time.uptime().as_nanos() as u64;
Interface::new(config, &mut net_driver_ref, instant)
};
// Create NetDrivers.
let mut rx_irq_to_driver = BTreeMap::new();
let mut tx_only_ringq = Vec::new();
for irq in net_device.irqs().into_iter() {
let rx_ringq = RingQ::new(512);
if let Some(que_id) = net_device.rx_irq_to_que_id(irq) {
rx_irq_to_driver.insert(
irq,
NetDriver {
inner: net_device.clone(),
rx_que_id: que_id,
rx_ringq: Mutex::new(rx_ringq),
},
);
}
let tx_ringq = Mutex::new(RingQ::new(512));
tx_only_ringq.push(tx_ringq);
}
let poll_driver = if net_device.poll_mode() {
let tx_ringq = Mutex::new(RingQ::new(512));
tx_only_ringq.push(tx_ringq);
Some(NetDriver {
inner: net_device.clone(),
rx_que_id: 0,
rx_ringq: Mutex::new(RingQ::new(512)),
})
} else {
None
};
let tick_driver = if net_device.tick_msec().is_some() {
let tx_ringq = Mutex::new(RingQ::new(512));
tx_only_ringq.push(tx_ringq);
Some(NetDriver {
inner: net_device.clone(),
rx_que_id: 0,
rx_ringq: Mutex::new(RingQ::new(512)),
})
} else {
None
};
// Create a SocketSet.
let socket_set = SocketSet::new(vec![]);
let is_poll_mode = net_device.poll_mode();
IfNet {
vlan,
inner: Mutex::new(IfNetInner {
interface,
default_gateway_ipv4: None,
#[cfg(not(feature = "std"))]
multicast_addr_ipv4: BTreeSet::new(),
#[cfg(not(feature = "std"))]
multicast_addr_mac: BTreeMap::new(),
}),
socket_set: RwLock::new(socket_set),
rx_irq_to_driver,
net_device,
tx_only_ringq,
is_poll_mode,
poll_driver,
tick_driver,
time,
will_poll: AtomicUsize::new(0),
}
}
/// Leave a multicast group.
/// This function calls `NetDevice::remove_multicast_addr` to remove a multicast address internally.
///
/// Returns `Ok(leave_sent)` if the address was removed successfully,
/// where `leave_sent` indicates whether an immediate leave packet has been sent.
#[cfg(not(feature = "std"))]
pub fn leave_multicast_v4(&self, addr: Ipv4Addr) -> Result<bool, NetManagerError> {
if !addr.is_multicast() {
return Err(NetManagerError::MulticastInvalidIpv4Address);
}
// Remove the multicast address from the list.
{
let mut node = MCSNode::new();
let inner = self.inner.lock(&mut node);
if !inner.multicast_addr_ipv4.contains(&addr) {
return Err(NetManagerError::MulticastNotJoined);
}
}
let mac_addr = ipv4_addr_to_mac_addr(addr);
// Leave the multicast group.
self.first_net_driver_ref(move |mut net_driver_ref| {
let timestamp = Instant::from_micros(self.time.elapsed().as_micros() as i64);
let smoltcp_addr = smoltcp::wire::Ipv4Address::from_bytes(&addr.octets());
let mut node = MCSNode::new();
let mut inner = self.inner.lock(&mut node);
match inner.interface.leave_multicast_group(
&mut net_driver_ref,
smoltcp_addr,
timestamp,
) {
Ok(result) => {
inner.multicast_addr_ipv4.remove(&addr);
// Disable the multicast address if it is not used.
match inner.multicast_addr_mac.entry(mac_addr) {
btree_map::Entry::Occupied(mut entry) => {
let count = entry.get_mut();
if *count == 1 {
entry.remove();
self.net_device
.remove_multicast_addr(&mac_addr)
.map_err(NetManagerError::DeviceError)?;
} else {
*count -= 1;
}
}
btree_map::Entry::Vacant(_) => {
return Err(NetManagerError::MulticastInvalidIpv4Address);
}
}
Ok(result)
}
Err(MulticastError::Exhausted) => Err(NetManagerError::SendError),
Err(_) => Err(NetManagerError::MulticastError),
}
})
}
#[cfg(not(feature = "std"))]
fn first_net_driver_ref<F, T>(&self, mut f: F) -> Result<T, NetManagerError>
where
F: FnMut(NetDriverRef) -> Result<T, NetManagerError>,
{
let first_driver = self.rx_irq_to_driver.first_key_value();
let ref_net_driver = first_driver
.as_ref()
.ok_or(NetManagerError::InvalidState)?
.1;
let tx_ringq = self
.tx_only_ringq
.get(ref_net_driver.rx_que_id)
.ok_or(NetManagerError::InvalidState)?;
let mut node = MCSNode::new();
let mut rx_ringq = ref_net_driver.rx_ringq.lock(&mut node);
let mut node = MCSNode::new();
let mut tx_ringq = tx_ringq.lock(&mut node);
let net_driver_ref = NetDriverRef {
inner: &ref_net_driver.inner,
rx_ringq: Some(&mut *rx_ringq),
tx_ringq: &mut tx_ringq,
};
f(net_driver_ref)
}
/// Join a multicast group.
/// This function calls `NetDevice::add_multicast_addr` and
/// `Interface::join_multicast_group` of `smoltcp` to add a multicast address internally.
///
/// Add an address to a list of subscribed multicast IP addresses.
/// Returns `Ok(announce_sent)`` if the address was added successfully,
/// where `announce_sent`` indicates whether an initial immediate announcement has been sent.
#[cfg(not(feature = "std"))]
pub fn join_multicast_v4(&self, addr: Ipv4Addr) -> Result<bool, NetManagerError> {
if !addr.is_multicast() {
return Err(NetManagerError::MulticastInvalidIpv4Address);
}
// Enable the multicast address if it is used.
let mac_addr = ipv4_addr_to_mac_addr(addr);
{
// Add the multicast address to the list.
let mut node = MCSNode::new();
let mut inner = self.inner.lock(&mut node);
if inner.multicast_addr_ipv4.contains(&addr) {
return Ok(false);
}
match inner.multicast_addr_mac.entry(mac_addr) {
btree_map::Entry::Occupied(mut entry) => {
*entry.get_mut() += 1;
}
btree_map::Entry::Vacant(entry) => {
entry.insert(1);
self.net_device
.add_multicast_addr(&mac_addr)
.map_err(NetManagerError::DeviceError)?;
}
}
}
// Join the multicast group.
let result = self.first_net_driver_ref(move |mut net_driver_ref| {
let timestamp = Instant::from_micros(self.time.elapsed().as_micros() as i64);
let smoltcp_addr = smoltcp::wire::Ipv4Address::from_bytes(&addr.octets());
let mut node = MCSNode::new();
let mut inner = self.inner.lock(&mut node);
match inner
.interface
.join_multicast_group(&mut net_driver_ref, smoltcp_addr, timestamp)
{
Ok(result) => {
inner.multicast_addr_ipv4.insert(addr);
Ok(result)
}
Err(MulticastError::Exhausted) => Err(NetManagerError::SendError),
Err(_) => Err(NetManagerError::MulticastError),
}
});
if result.is_ok() {
return result;
}
// Error handling.
// If an error occurs, the multicast address is removed from the list.
let mut node = MCSNode::new();
let mut inner = self.inner.lock(&mut node);
if let btree_map::Entry::Occupied(mut entry) = inner.multicast_addr_mac.entry(mac_addr) {
let num = entry.get_mut();
if *num == 1 {
entry.remove();
self.net_device
.remove_multicast_addr(&mac_addr)
.map_err(NetManagerError::DeviceError)?;
} else {
*num -= 1;
}
}
result
}
/// Poll the network interface.
/// This function will only send IP packets to transmit queues.
///
/// This function returns a boolean value indicating whether any packets were processed or emitted,
/// and thus, whether the readiness of any socket might have changed.
///
/// This algorithm is modeled and tested by spin.
/// See `awkernel/specification/awkernel_lib/src/net/if_net/README.md`.
#[cfg(not(feature = "std"))]
pub fn poll_tx_only(&self, que_id: usize) -> bool {
let Some(tx_ringq) = self.tx_only_ringq.get(que_id) else {
return false;
};
let mut result = false;
loop {
// If some task will poll, this task need not to poll.
if self
.will_poll
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| {
if n > 0 {
None
} else {
Some(n + 1)
}
})
.is_err()
{
return true;
}
let mut node = MCSNode::new();
let mut tx_ringq = tx_ringq.lock(&mut node);
let mut device_ref = NetDriverRef {
inner: &self.net_device,
rx_ringq: None,
tx_ringq: &mut tx_ringq,
};
let timestamp = Instant::from_micros(self.time.elapsed().as_micros() as i64);
result = result || {
let mut node = MCSNode::new();
let mut inner = self.inner.lock(&mut node);
let interface = inner.get_interface();
self.will_poll.fetch_sub(1, Ordering::Relaxed);
interface.poll(timestamp, &mut device_ref, &self.socket_set)
};
let is_full = device_ref.tx_ringq.is_full();
// send packets from the queue.
while !device_ref.tx_ringq.is_empty() {
if let Some(data) = device_ref.tx_ringq.pop() {
let tx_packet_header_flags = device_ref.tx_packet_header_flags(&data);
let data = EtherFrameRef {
data: &data,
vlan: self.vlan,
csum_flags: tx_packet_header_flags,
};
if self.net_device.send(data, que_id).is_err() {
log::error!("Failed to send a packet.");
}
} else {
break;
}
}
// If the queue is full, there should be packets to be processed,
// and thus the loop continues.
if !is_full {
break;
}
}
result
}
/// Poll the network interface.
/// This function receives and sends IP packets.
///
/// This function returns a boolean value indicating whether any packets were processed or emitted,
/// and thus, whether the readiness of any socket might have changed.
///
/// This algorithm is modeled and tested by spin.
/// See `awkernel/specification/awkernel_lib/src/net/if_net/README.md`.
fn poll_rx_tx(&self, ref_net_driver: &NetDriver) -> bool {
let que_id = ref_net_driver.rx_que_id;
let Some(tx_ringq) = self.tx_only_ringq.get(que_id) else {
return false;
};
self.will_poll.fetch_add(1, Ordering::Relaxed);
let mut node = MCSNode::new();
let mut rx_ringq = ref_net_driver.rx_ringq.lock(&mut node);
// receive packets from the RX queue.
while !rx_ringq.is_full() {
if let Ok(Some(data)) = ref_net_driver.inner.recv(ref_net_driver.rx_que_id) {
let _ = rx_ringq.push(data);
} else {
break;
}
}
let mut node = MCSNode::new();
let mut tx_ringq = tx_ringq.lock(&mut node);
let mut device_ref = NetDriverRef {
inner: &ref_net_driver.inner,
rx_ringq: Some(&mut rx_ringq),
tx_ringq: &mut tx_ringq,
};
let result = {
let timestamp = Instant::from_micros(self.time.elapsed().as_micros() as i64);
let mut node = MCSNode::new();
let mut inner = self.inner.lock(&mut node);
let interface = inner.get_interface();
self.will_poll.fetch_sub(1, Ordering::Relaxed);
interface.poll(timestamp, &mut device_ref, &self.socket_set)
};
// send packets from the queue.
while !device_ref.tx_ringq.is_empty() {
if let Some(data) = device_ref.tx_ringq.pop() {
let tx_packet_header_flags = device_ref.tx_packet_header_flags(&data);
let data = EtherFrameRef {
data: &data,
vlan: self.vlan,
csum_flags: tx_packet_header_flags,
};
let _ = self.net_device.send(data, ref_net_driver.rx_que_id);
} else {
break;
}
}
result
}
#[inline(always)]
pub fn poll_rx_poll_mode(&self) -> bool {
let Some(ref_net_driver) = self.poll_driver.as_ref() else {
return false;
};
if ref_net_driver.inner.can_send() {
self.poll_rx_tx(ref_net_driver)
} else {
false
}
}
#[inline(always)]
pub fn tick_rx_poll_mode(&self) {
let Some(ref_net_driver) = self.tick_driver.as_ref() else {
return;
};
if ref_net_driver.inner.can_send() {
self.poll_rx_tx(ref_net_driver);
}
}
/// If some packets are processed, return true.
/// If poll returns true, the caller should call poll again.
#[inline(always)]
pub fn poll_rx_irq(&self, irq: u16) -> bool {
let Some(ref_net_driver) = self.rx_irq_to_driver.get(&irq) else {
return false;
};
if ref_net_driver.inner.can_send() {
self.poll_rx_tx(ref_net_driver)
} else {
false
}
}
}
pub struct NRxToken {
data: EtherFrameBuf,
}
impl phy::RxToken for NRxToken {
/// Store packet data into the buffer.
/// Closure f will map the raw bytes to the form that
/// could be used in the higher layer of `smoltcp`.
fn consume<R, F>(mut self, f: F) -> R
where
F: FnOnce(&mut [u8]) -> R,
{
f(&mut self.data.data)
}
}
pub struct NTxToken<'a> {
tx_ring: &'a mut RingQ<Vec<u8>>,
}
impl phy::TxToken for NTxToken<'_> {
fn consume<R, F>(self, len: usize, f: F) -> R
where
F: FnOnce(&mut [u8]) -> R,
{
let mut buf = Vec::with_capacity(len);
#[allow(clippy::uninit_vec)]
unsafe {
buf.set_len(len);
};
let result = f(&mut buf[..len]);
let _ = self.tx_ring.push(buf);
result
}
}