xref: /DragonOS/kernel/src/driver/net/sysfs.rs (revision fae6e9ade46a52976ad5d099643d51cc20876448)
1 use crate::{
2     driver::base::{
3         class::Class,
4         device::{device_manager, Device},
5         kobject::KObject,
6     },
7     filesystem::{
8         sysfs::{
9             file::sysfs_emit_str, Attribute, AttributeGroup, SysFSOpsSupport, SYSFS_ATTR_MODE_RO,
10             SYSFS_ATTR_MODE_RW,
11         },
12         vfs::syscall::ModeType,
13     },
14 };
15 use alloc::sync::Arc;
16 use intertrait::cast::CastArc;
17 use log::error;
18 use system_error::SystemError;
19 
20 use super::{class::sys_class_net_instance, NetDeivceState, NetDevice, Operstate};
21 
22 /// 将设备注册到`/sys/class/net`目录下
23 /// 参考:https://code.dragonos.org.cn/xref/linux-2.6.39/net/core/net-sysfs.c?fi=netdev_register_kobject#1311
24 pub fn netdev_register_kobject(dev: Arc<dyn NetDevice>) -> Result<(), SystemError> {
25     // 初始化设备
26     device_manager().device_default_initialize(&(dev.clone() as Arc<dyn Device>));
27 
28     // 设置dev的class为net
29     dev.set_class(Some(Arc::downgrade(
30         &(sys_class_net_instance().cloned().unwrap() as Arc<dyn Class>),
31     )));
32 
33     // 设置设备的kobject名
34     dev.set_name(dev.iface_name().clone());
35 
36     device_manager().add_device(dev.clone() as Arc<dyn Device>)?;
37 
38     return Ok(());
39 }
40 
41 // 参考:https://code.dragonos.org.cn/xref/linux-6.6.21/net/core/net-sysfs.c
42 #[derive(Debug)]
43 pub struct NetAttrGroup;
44 
45 impl AttributeGroup for NetAttrGroup {
46     fn name(&self) -> Option<&str> {
47         None
48     }
49 
50     fn attrs(&self) -> &[&'static dyn Attribute] {
51         &[
52             &AttrAddrAssignType,
53             &AttrAddrLen,
54             &AttrDevId,
55             &AttrIfalias,
56             &AttrIflink,
57             &AttrIfindex,
58             &AttrFeatrues,
59             &AttrType,
60             &AttrLinkMode,
61             &AttrAddress,
62             &AttrBroadcast,
63             &AttrCarrier,
64             &AttrSpeed,
65             &AttrDuplex,
66             &AttrDormant,
67             &AttrOperstate,
68             &AttrMtu,
69             &AttrFlags,
70             &AttrTxQueueLen,
71             &AttrNetdevGroup,
72         ]
73     }
74 
75     fn is_visible(
76         &self,
77         _kobj: Arc<dyn KObject>,
78         attr: &'static dyn Attribute,
79     ) -> Option<ModeType> {
80         return Some(attr.mode());
81     }
82 }
83 
84 /// # 表示网络接口的MAC地址是如何分配的
85 /// - 0(NET_ADDR_PERM): 永久的MAC地址(默认值)
86 /// - 1(NET_ADDR_RANDOM): 随机生成的MAC地址
87 /// - 2(NET_ADDR_STOLEN): 从其他设备中获取的MAC地址
88 /// - 3(NET_ADDR_SET): 由用户设置的MAC地址
89 #[derive(Debug)]
90 struct AttrAddrAssignType;
91 
92 impl Attribute for AttrAddrAssignType {
93     fn name(&self) -> &str {
94         "addr_assign_type"
95     }
96 
97     fn mode(&self) -> ModeType {
98         SYSFS_ATTR_MODE_RO
99     }
100 
101     fn support(&self) -> SysFSOpsSupport {
102         SysFSOpsSupport::ATTR_SHOW
103     }
104 
105     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
106         let net_device = kobj.cast::<dyn NetDevice>().map_err(|_| {
107             error!("AttrAddrAssignType::show() failed: kobj is not a NetDevice");
108             SystemError::EINVAL
109         })?;
110         let addr_assign_type = net_device.addr_assign_type();
111         sysfs_emit_str(buf, &format!("{}\n", addr_assign_type))
112     }
113 }
114 
115 /// # 表示网络接口的MAC地址的长度,以字节为单位
116 #[derive(Debug)]
117 struct AttrAddrLen;
118 
119 impl Attribute for AttrAddrLen {
120     fn name(&self) -> &str {
121         "addr_len"
122     }
123 
124     fn mode(&self) -> ModeType {
125         SYSFS_ATTR_MODE_RO
126     }
127 
128     fn support(&self) -> SysFSOpsSupport {
129         SysFSOpsSupport::ATTR_SHOW
130     }
131 
132     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
133         todo!("AttrAddrLen::show")
134     }
135 }
136 
137 /// # 表示网络接口的设备ID,是一个十六进制数
138 #[derive(Debug)]
139 struct AttrDevId;
140 
141 impl Attribute for AttrDevId {
142     fn name(&self) -> &str {
143         "dev_id"
144     }
145 
146     fn mode(&self) -> ModeType {
147         SYSFS_ATTR_MODE_RO
148     }
149 
150     fn support(&self) -> SysFSOpsSupport {
151         SysFSOpsSupport::ATTR_SHOW
152     }
153 
154     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
155         todo!("AttrDevId::show")
156     }
157 }
158 
159 /// # 表示网络接口的别名,可以设置
160 #[derive(Debug)]
161 struct AttrIfalias;
162 
163 impl Attribute for AttrIfalias {
164     fn name(&self) -> &str {
165         "ifalias"
166     }
167 
168     fn mode(&self) -> ModeType {
169         SYSFS_ATTR_MODE_RW
170     }
171 
172     fn support(&self) -> SysFSOpsSupport {
173         SysFSOpsSupport::ATTR_SHOW | SysFSOpsSupport::ATTR_STORE
174     }
175 
176     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
177         todo!("AttrIfalias::show")
178     }
179 
180     fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
181         todo!("AttrIfalias::store")
182     }
183 }
184 
185 /// # 表示网络接口的链路索引,用于表示网络接口在系统中的位置
186 #[derive(Debug)]
187 struct AttrIflink;
188 
189 impl Attribute for AttrIflink {
190     fn name(&self) -> &str {
191         "iflink"
192     }
193 
194     fn mode(&self) -> ModeType {
195         SYSFS_ATTR_MODE_RO
196     }
197 
198     fn support(&self) -> SysFSOpsSupport {
199         SysFSOpsSupport::ATTR_SHOW
200     }
201 
202     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
203         todo!("AttrIflink::show")
204     }
205 }
206 
207 /// # 标识网络接口的索引
208 #[derive(Debug)]
209 struct AttrIfindex;
210 
211 impl Attribute for AttrIfindex {
212     fn name(&self) -> &str {
213         "ifindex"
214     }
215 
216     fn mode(&self) -> ModeType {
217         SYSFS_ATTR_MODE_RO
218     }
219 
220     fn support(&self) -> SysFSOpsSupport {
221         SysFSOpsSupport::ATTR_SHOW
222     }
223 
224     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
225         todo!("AttrIfindex::show")
226     }
227 }
228 
229 /// # 用于显示网络接口支持的特性,这些特性通常由网络驱动程序和硬件能力决定
230 #[derive(Debug)]
231 struct AttrFeatrues;
232 
233 impl Attribute for AttrFeatrues {
234     fn name(&self) -> &str {
235         "features"
236     }
237 
238     fn mode(&self) -> ModeType {
239         SYSFS_ATTR_MODE_RO
240     }
241 
242     fn support(&self) -> SysFSOpsSupport {
243         SysFSOpsSupport::ATTR_SHOW
244     }
245 
246     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
247         todo!("AttrFeatrues::show")
248     }
249 }
250 
251 /// # 用于表示网络接口的类型
252 /// - 1:ARPHRD_ETHER 以太网接口
253 /// - 24:ARPHRD_LOOPBACK 回环接口
254 /// - 512:ARPHRD_IEEE80211_RADIOTAP IEEE 802.11 无线接口
255 /// - 768:ARPHRD_IEEE802154 IEEE 802.15.4 无线接口
256 /// - 769:ARPHRD_6LOWPAN 6LoWPAN接口
257 #[derive(Debug)]
258 struct AttrType;
259 
260 impl Attribute for AttrType {
261     fn name(&self) -> &str {
262         "type"
263     }
264 
265     fn mode(&self) -> ModeType {
266         SYSFS_ATTR_MODE_RO
267     }
268 
269     fn support(&self) -> SysFSOpsSupport {
270         SysFSOpsSupport::ATTR_SHOW
271     }
272 
273     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
274         let net_deive = kobj.cast::<dyn NetDevice>().map_err(|_| {
275             error!("AttrType::show() failed: kobj is not a NetDevice");
276             SystemError::EINVAL
277         })?;
278         let net_type = net_deive.net_device_type();
279         sysfs_emit_str(buf, &format!("{}\n", net_type))
280     }
281 }
282 
283 /// # 表示网络接口的链路模式,用于指示网络接口是否处于自动协商模式
284 /// - 0:表示网络接口处于自动协商模式
285 /// - 1:表示网络接口处于强制模式,即链路参数(如速度和双工模式)是手动配置的,而不是通过自动协商确定的
286 #[derive(Debug)]
287 struct AttrLinkMode;
288 
289 impl Attribute for AttrLinkMode {
290     fn name(&self) -> &str {
291         "link_mode"
292     }
293 
294     fn mode(&self) -> ModeType {
295         SYSFS_ATTR_MODE_RO
296     }
297 
298     fn support(&self) -> SysFSOpsSupport {
299         SysFSOpsSupport::ATTR_SHOW
300     }
301 
302     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
303         todo!("AttrLinkMode::show")
304     }
305 }
306 
307 /// # 表示网络接口的MAC地址
308 #[derive(Debug)]
309 struct AttrAddress;
310 
311 impl Attribute for AttrAddress {
312     fn name(&self) -> &str {
313         "address"
314     }
315 
316     fn mode(&self) -> ModeType {
317         SYSFS_ATTR_MODE_RO
318     }
319 
320     fn support(&self) -> SysFSOpsSupport {
321         SysFSOpsSupport::ATTR_SHOW
322     }
323 
324     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
325         let net_device = kobj.cast::<dyn NetDevice>().map_err(|_| {
326             error!("AttrAddress::show() failed: kobj is not a NetDevice");
327             SystemError::EINVAL
328         })?;
329         let mac_addr = net_device.mac();
330         sysfs_emit_str(buf, &format!("{}\n", mac_addr))
331     }
332 }
333 
334 /// # 表示网络接口的广播地址
335 #[derive(Debug)]
336 struct AttrBroadcast;
337 
338 impl Attribute for AttrBroadcast {
339     fn name(&self) -> &str {
340         "broadcast"
341     }
342 
343     fn mode(&self) -> ModeType {
344         SYSFS_ATTR_MODE_RO
345     }
346 
347     fn support(&self) -> SysFSOpsSupport {
348         SysFSOpsSupport::ATTR_SHOW
349     }
350 
351     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
352         todo!("AttrBroadcast::show")
353     }
354 }
355 
356 /// # 表示网络接口的物理链路状态
357 /// - 0:表示网络接口处于关闭状态
358 /// - 1:表示网络接口处于打开状态
359 #[derive(Debug)]
360 struct AttrCarrier;
361 
362 impl Attribute for AttrCarrier {
363     fn name(&self) -> &str {
364         "carrier"
365     }
366 
367     fn mode(&self) -> ModeType {
368         SYSFS_ATTR_MODE_RO
369     }
370 
371     fn support(&self) -> SysFSOpsSupport {
372         SysFSOpsSupport::ATTR_SHOW
373     }
374 
375     fn show(&self, kobj: Arc<dyn KObject>, buf: &mut [u8]) -> Result<usize, SystemError> {
376         let net_device = kobj.cast::<dyn NetDevice>().map_err(|_| {
377             error!("AttrCarrier::show() failed: kobj is not a NetDevice");
378             SystemError::EINVAL
379         })?;
380         if net_device
381             .net_state()
382             .contains(NetDeivceState::__LINK_STATE_START)
383             && !net_device
384                 .net_state()
385                 .contains(NetDeivceState::__LINK_STATE_NOCARRIER)
386         {
387             sysfs_emit_str(buf, "1\n")
388         } else {
389             sysfs_emit_str(buf, "0\n")
390         }
391     }
392 }
393 
394 /// # 表示网络接口的当前连接速度,单位为Mbps
395 /// - 特殊值:-1,表示无法确定,通常是因为接口不支持查询速度或接口未连接
396 #[derive(Debug)]
397 struct AttrSpeed;
398 
399 impl Attribute for AttrSpeed {
400     fn name(&self) -> &str {
401         "speed"
402     }
403 
404     fn mode(&self) -> ModeType {
405         SYSFS_ATTR_MODE_RO
406     }
407 
408     fn support(&self) -> SysFSOpsSupport {
409         SysFSOpsSupport::ATTR_SHOW
410     }
411 
412     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
413         todo!("AttrSpeed::show")
414     }
415 }
416 
417 /// # 表示网络接口的双工模式
418 /// - half:半双工,网络接口不能同时发送和接收数据
419 /// - full:全双工,网络接口可以同时发送和接收数据
420 /// - unknown:未知,通常表示接口未连接或无法确定双工模式
421 #[derive(Debug)]
422 struct AttrDuplex;
423 
424 impl Attribute for AttrDuplex {
425     fn name(&self) -> &str {
426         "duplex"
427     }
428 
429     fn mode(&self) -> ModeType {
430         SYSFS_ATTR_MODE_RO
431     }
432 
433     fn support(&self) -> SysFSOpsSupport {
434         SysFSOpsSupport::ATTR_SHOW
435     }
436 
437     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
438         todo!("AttrDuplex::show")
439     }
440 }
441 
442 /// 表示网络接口是否处于休眠状态
443 /// - 0:表示网络接口未处于休眠状态
444 /// - 1:表示网络接口处于休眠状态
445 #[derive(Debug)]
446 struct AttrDormant;
447 
448 impl Attribute for AttrDormant {
449     fn name(&self) -> &str {
450         "dormant"
451     }
452 
453     fn mode(&self) -> ModeType {
454         SYSFS_ATTR_MODE_RO
455     }
456 
457     fn support(&self) -> SysFSOpsSupport {
458         SysFSOpsSupport::ATTR_SHOW
459     }
460 
461     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
462         todo!("AttrDormant::show")
463     }
464 }
465 
466 /// # 表示网络接口的操作状态
467 /// - up:网络接口已启用并且正在运行
468 /// - down:网络接口已禁用或未连接
469 /// - dormant:网络接口处于休眠状态,等待某些条件满足后激活
470 /// - testing:网络接口正在测试中
471 /// - unknown:网络接口的状态未知
472 /// - notpresent:网络接口硬件不存在
473 /// - lowerlayerdown:网络接口的底层设备未启用
474 /// - inactive:网络接口未激活
475 #[derive(Debug)]
476 struct AttrOperstate;
477 
478 impl Attribute for AttrOperstate {
479     fn name(&self) -> &str {
480         "operstate"
481     }
482 
483     fn mode(&self) -> ModeType {
484         SYSFS_ATTR_MODE_RO
485     }
486 
487     fn support(&self) -> SysFSOpsSupport {
488         SysFSOpsSupport::ATTR_SHOW
489     }
490 
491     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
492         let net_device = _kobj.cast::<dyn NetDevice>().map_err(|_| {
493             error!("AttrOperstate::show() failed: kobj is not a NetDevice");
494             SystemError::EINVAL
495         })?;
496         if !net_device
497             .net_state()
498             .contains(NetDeivceState::__LINK_STATE_START)
499         {
500             net_device.set_operstate(Operstate::IF_OPER_DOWN);
501         }
502 
503         let operstate_str = match net_device.operstate() {
504             Operstate::IF_OPER_UP => "up",
505             Operstate::IF_OPER_DOWN => "down",
506             Operstate::IF_OPER_DORMANT => "dormant",
507             Operstate::IF_OPER_TESTING => "testing",
508             Operstate::IF_OPER_UNKNOWN => "unknown",
509             Operstate::IF_OPER_NOTPRESENT => "notpresent",
510             Operstate::IF_OPER_LOWERLAYERDOWN => "lowerlayerdown",
511         };
512 
513         sysfs_emit_str(_buf, &format!("{}\n", operstate_str))
514     }
515 }
516 
517 /// # 表示网络接口的最大传输单元
518 #[derive(Debug)]
519 struct AttrMtu;
520 
521 impl Attribute for AttrMtu {
522     fn name(&self) -> &str {
523         "mtu"
524     }
525 
526     fn mode(&self) -> ModeType {
527         SYSFS_ATTR_MODE_RO
528     }
529 
530     fn support(&self) -> SysFSOpsSupport {
531         SysFSOpsSupport::ATTR_SHOW
532     }
533 
534     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
535         todo!("AttrMtu::show")
536     }
537 
538     fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
539         todo!("AttrMtu::store")
540     }
541 }
542 
543 /// # 表示网络接口的标志,这些标志提供了关于网络接口状态和配置的详细信息
544 /// - IFF_UP(0x1):接口已启用
545 /// - IFF_BROADCAST(0x2):支持广播
546 /// - IFF_DEBUG(0x4):调试模式
547 /// - IFF_LOOPBACK(0x8):环回接口
548 /// - IFF_POINTOPOINT(0x10):点对点链路
549 /// - IFF_NOTRAILERS(0x20):禁用拖尾
550 /// - IFF_RUNNING(0x40):资源已分配
551 /// - IFF_NOARP(0x80):无ARP协议
552 /// - IFF_PROMISC(0x100):混杂模式
553 /// - IFF_ALLMULTI(0x200):接收所有多播放数据包
554 /// - IFF_ MASTER(0x400):主设备
555 /// - IFF_SLAVE(0x800):从设备
556 /// - IFF_MULTICAST(0x1000):支持多播
557 /// - IFF_PORTSEL(0x2000):可以选择媒体类型
558 /// - IFF_AUTOMEDIA(0x4000):自动选择媒体类型
559 /// - IFF_DYNAMIC(0x8000):动态接口
560 #[derive(Debug)]
561 struct AttrFlags;
562 
563 impl Attribute for AttrFlags {
564     fn name(&self) -> &str {
565         "flags"
566     }
567 
568     fn mode(&self) -> ModeType {
569         SYSFS_ATTR_MODE_RO
570     }
571 
572     fn support(&self) -> SysFSOpsSupport {
573         SysFSOpsSupport::ATTR_SHOW
574     }
575 
576     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
577         todo!("AttrFlags::show")
578     }
579 
580     fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
581         todo!("AttrFlags::store")
582     }
583 }
584 
585 /// # 表示网络接口的传输队列长度
586 #[derive(Debug)]
587 struct AttrTxQueueLen;
588 
589 impl Attribute for AttrTxQueueLen {
590     fn name(&self) -> &str {
591         "tx_queue_len"
592     }
593 
594     fn mode(&self) -> ModeType {
595         SYSFS_ATTR_MODE_RO
596     }
597 
598     fn support(&self) -> SysFSOpsSupport {
599         SysFSOpsSupport::ATTR_SHOW
600     }
601 
602     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
603         todo!("AttrTxQueueLen::show")
604     }
605 
606     fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
607         todo!("AttrTxQueueLen::store")
608     }
609 }
610 
611 /// # 表示网络设备所属的设备组
612 #[derive(Debug)]
613 struct AttrNetdevGroup;
614 
615 impl Attribute for AttrNetdevGroup {
616     fn name(&self) -> &str {
617         "netdev_group"
618     }
619 
620     fn mode(&self) -> ModeType {
621         SYSFS_ATTR_MODE_RO
622     }
623 
624     fn support(&self) -> SysFSOpsSupport {
625         SysFSOpsSupport::ATTR_SHOW
626     }
627 
628     fn show(&self, _kobj: Arc<dyn KObject>, _buf: &mut [u8]) -> Result<usize, SystemError> {
629         todo!("AttrNetdevGroup::show")
630     }
631 
632     fn store(&self, _kobj: Arc<dyn KObject>, _buf: &[u8]) -> Result<usize, SystemError> {
633         todo!("AttrNetdevGroup::store")
634     }
635 }
636