starnix_core/task/
net.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::device::kobject::Device;
6use crate::task::Kernel;
7use crate::task::waiter::WaitQueue;
8use crate::vfs::{FsStr, FsString};
9use starnix_sync::Mutex;
10use std::collections::BTreeMap;
11use std::num::NonZeroU64;
12use std::sync::atomic::AtomicBool;
13
14#[derive(Clone, Debug)]
15pub struct NetstackDevice {
16    pub device: Device,
17    pub interface_id: NonZeroU64,
18}
19
20/// Keeps track of network devices and their [`Device`].
21#[derive(Default)]
22pub struct NetstackDevices {
23    /// The known netstack devices.
24    devices: Mutex<BTreeMap<FsString, NetstackDevice>>,
25    /// `NetstackDevices` listens for events from the netlink worker, which
26    /// is initialized lazily and asynchronously. This waits for at least
27    /// the `Idle` event is observed on the interface watcher.
28    pub initialized_and_wq: (AtomicBool, WaitQueue),
29}
30
31impl NetstackDevices {
32    pub fn add_device(&self, kernel: &Kernel, name: &FsStr, interface_id: NonZeroU64) {
33        let mut devices = self.devices.lock();
34        let device = kernel.device_registry.add_net_device(name);
35        devices.insert(name.into(), NetstackDevice { device, interface_id });
36    }
37
38    pub fn remove_device(&self, kernel: &Kernel, name: &FsStr) {
39        let mut devices = self.devices.lock();
40        if let Some(NetstackDevice { device, interface_id: _ }) = devices.remove(name) {
41            kernel.device_registry.remove_net_device(device);
42        }
43    }
44
45    pub fn get_device(&self, name: &FsStr) -> Option<NetstackDevice> {
46        let devices = self.devices.lock();
47        devices.get(name).cloned()
48    }
49
50    pub fn snapshot_devices(&self) -> Vec<(FsString, NetstackDevice)> {
51        let devices = self.devices.lock();
52        devices.iter().map(|(name, device)| (name.clone(), device.clone())).collect()
53    }
54}