1 use core::intrinsics::size_of;
2
3 use alloc::{
4 borrow::ToOwned,
5 collections::BTreeMap,
6 format,
7 string::String,
8 sync::{Arc, Weak},
9 vec::Vec,
10 };
11 use system_error::SystemError;
12
13 use crate::{
14 arch::mm::LockedFrameAllocator,
15 driver::base::device::device_number::DeviceNumber,
16 filesystem::vfs::{
17 core::{generate_inode_id, ROOT_INODE},
18 FileType,
19 },
20 kerror, kinfo,
21 libs::{
22 once::Once,
23 spinlock::{SpinLock, SpinLockGuard},
24 },
25 mm::allocator::page_frame::FrameAllocator,
26 process::{Pid, ProcessManager},
27 time::TimeSpec,
28 };
29
30 use super::vfs::{
31 file::{FileMode, FilePrivateData},
32 syscall::ModeType,
33 FileSystem, FsInfo, IndexNode, InodeId, Metadata,
34 };
35
36 pub mod kmsg;
37 pub mod log;
38 mod syscall;
39
40 /// @brief 进程文件类型
41 /// @usage 用于定义进程文件夹下的各类文件类型
42 #[derive(Debug)]
43 #[repr(u8)]
44 pub enum ProcFileType {
45 ///展示进程状态信息
46 ProcStatus = 0,
47 /// meminfo
48 ProcMeminfo = 1,
49 /// kmsg
50 ProcKmsg = 2,
51 //todo: 其他文件类型
52 ///默认文件类型
53 Default,
54 }
55
56 impl From<u8> for ProcFileType {
from(value: u8) -> Self57 fn from(value: u8) -> Self {
58 match value {
59 0 => ProcFileType::ProcStatus,
60 1 => ProcFileType::ProcMeminfo,
61 2 => ProcFileType::ProcKmsg,
62 _ => ProcFileType::Default,
63 }
64 }
65 }
66 /// @brief 节点私有信息结构体
67 /// @usage 用于传入各类文件所需的信息
68 #[derive(Debug)]
69 pub struct InodeInfo {
70 ///进程的pid
71 pid: Pid,
72 ///文件类型
73 ftype: ProcFileType,
74 //其他需要传入的信息在此定义
75 }
76
77 /// @brief procfs的inode名称的最大长度
78 const PROCFS_MAX_NAMELEN: usize = 64;
79
80 /// @brief procfs文件系统的Inode结构体
81 #[derive(Debug)]
82 pub struct LockedProcFSInode(SpinLock<ProcFSInode>);
83
84 /// @brief procfs文件系统结构体
85 #[derive(Debug)]
86 pub struct ProcFS {
87 /// procfs的root inode
88 root_inode: Arc<LockedProcFSInode>,
89 }
90
91 #[derive(Debug, Clone)]
92 pub struct ProcfsFilePrivateData {
93 data: Vec<u8>,
94 }
95
96 impl ProcfsFilePrivateData {
new() -> Self97 pub fn new() -> Self {
98 return ProcfsFilePrivateData { data: Vec::new() };
99 }
100 }
101
102 /// @brief procfs文件系统的Inode结构体(不包含锁)
103 #[derive(Debug)]
104 pub struct ProcFSInode {
105 /// 指向父Inode的弱引用
106 parent: Weak<LockedProcFSInode>,
107 /// 指向自身的弱引用
108 self_ref: Weak<LockedProcFSInode>,
109 /// 子Inode的B树
110 children: BTreeMap<String, Arc<LockedProcFSInode>>,
111 /// 当前inode的数据部分
112 data: Vec<u8>,
113 /// 当前inode的元数据
114 metadata: Metadata,
115 /// 指向inode所在的文件系统对象的指针
116 fs: Weak<ProcFS>,
117 /// 储存私有信息
118 fdata: InodeInfo,
119 }
120
121 /// 对ProcFSInode实现获取各类文件信息的函数
122 impl ProcFSInode {
123 /// @brief 去除Vec中所有的\0,并在结尾添加\0
124 #[inline]
trim_string(&self, data: &mut Vec<u8>)125 fn trim_string(&self, data: &mut Vec<u8>) {
126 data.retain(|x| *x != 0);
127
128 data.push(0);
129 }
130 // todo:其他数据获取函数实现
131
132 /// @brief 打开status文件
133 ///
open_status(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError>134 fn open_status(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError> {
135 // 获取该pid对应的pcb结构体
136 let pid = self.fdata.pid;
137 let pcb = ProcessManager::find(pid);
138 let pcb = if pcb.is_none() {
139 kerror!(
140 "ProcFS: Cannot find pcb for pid {:?} when opening its 'status' file.",
141 pid
142 );
143 return Err(SystemError::ESRCH);
144 } else {
145 pcb.unwrap()
146 };
147 // 传入数据
148 let pdata: &mut Vec<u8> = &mut pdata.data;
149
150 pdata.append(
151 &mut format!("Name:\t{}", pcb.basic().name())
152 .as_bytes()
153 .to_owned(),
154 );
155
156 let sched_info_guard = pcb.sched_info();
157 let state = sched_info_guard.inner_lock_read_irqsave().state();
158 let cpu_id = sched_info_guard
159 .on_cpu()
160 .map(|cpu| cpu.data() as i32)
161 .unwrap_or(-1);
162
163 let priority = sched_info_guard.priority();
164 let vrtime = sched_info_guard.virtual_runtime();
165
166 pdata.append(&mut format!("\nState:\t{:?}", state).as_bytes().to_owned());
167 pdata.append(
168 &mut format!("\nPid:\t{}", pcb.pid().into())
169 .as_bytes()
170 .to_owned(),
171 );
172 pdata.append(
173 &mut format!("\nPpid:\t{}", pcb.basic().ppid().into())
174 .as_bytes()
175 .to_owned(),
176 );
177 pdata.append(&mut format!("\ncpu_id:\t{}", cpu_id).as_bytes().to_owned());
178 pdata.append(
179 &mut format!("\npriority:\t{}", priority.data())
180 .as_bytes()
181 .to_owned(),
182 );
183 pdata.append(
184 &mut format!("\npreempt:\t{}", pcb.preempt_count())
185 .as_bytes()
186 .to_owned(),
187 );
188 pdata.append(&mut format!("\nvrtime:\t{}", vrtime).as_bytes().to_owned());
189
190 if let Some(user_vm) = pcb.basic().user_vm() {
191 let address_space_guard = user_vm.read();
192 // todo: 当前进程运行过程中占用内存的峰值
193 let hiwater_vm: u64 = 0;
194 // 进程代码段的大小
195 let text = (address_space_guard.end_code - address_space_guard.start_code) / 1024;
196 // 进程数据段的大小
197 let data = (address_space_guard.end_data - address_space_guard.start_data) / 1024;
198 drop(address_space_guard);
199 pdata.append(
200 &mut format!("\nVmPeak:\t{} kB", hiwater_vm)
201 .as_bytes()
202 .to_owned(),
203 );
204 pdata.append(&mut format!("\nVmData:\t{} kB", data).as_bytes().to_owned());
205 pdata.append(&mut format!("\nVmExe:\t{} kB", text).as_bytes().to_owned());
206 }
207
208 pdata.append(
209 &mut format!("\nflags: {:?}\n", pcb.flags().clone())
210 .as_bytes()
211 .to_owned(),
212 );
213
214 // 去除多余的\0
215 self.trim_string(pdata);
216
217 return Ok((pdata.len() * size_of::<u8>()) as i64);
218 }
219
220 /// 打开 meminfo 文件
open_meminfo(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError>221 fn open_meminfo(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError> {
222 // 获取内存信息
223 let usage = unsafe { LockedFrameAllocator.usage() };
224
225 // 传入数据
226 let data: &mut Vec<u8> = &mut pdata.data;
227
228 data.append(
229 &mut format!("MemTotal:\t{} kB\n", usage.total().bytes() >> 10)
230 .as_bytes()
231 .to_owned(),
232 );
233
234 data.append(
235 &mut format!("MemFree:\t{} kB\n", usage.free().bytes() >> 10)
236 .as_bytes()
237 .to_owned(),
238 );
239
240 // 去除多余的\0
241 self.trim_string(data);
242
243 return Ok((data.len() * size_of::<u8>()) as i64);
244 }
245
246 /// proc文件系统读取函数
proc_read( &self, offset: usize, len: usize, buf: &mut [u8], _pdata: &mut ProcfsFilePrivateData, ) -> Result<usize, SystemError>247 fn proc_read(
248 &self,
249 offset: usize,
250 len: usize,
251 buf: &mut [u8],
252 _pdata: &mut ProcfsFilePrivateData,
253 ) -> Result<usize, SystemError> {
254 let start = _pdata.data.len().min(offset);
255 let end = _pdata.data.len().min(offset + len);
256
257 // buffer空间不足
258 if buf.len() < (end - start) {
259 return Err(SystemError::ENOBUFS);
260 }
261
262 // 拷贝数据
263 let src = &_pdata.data[start..end];
264 buf[0..src.len()].copy_from_slice(src);
265 return Ok(src.len());
266 }
267 }
268
269 impl FileSystem for ProcFS {
root_inode(&self) -> Arc<dyn super::vfs::IndexNode>270 fn root_inode(&self) -> Arc<dyn super::vfs::IndexNode> {
271 return self.root_inode.clone();
272 }
273
info(&self) -> FsInfo274 fn info(&self) -> FsInfo {
275 return FsInfo {
276 blk_dev_id: 0,
277 max_name_len: PROCFS_MAX_NAMELEN,
278 };
279 }
280
as_any_ref(&self) -> &dyn core::any::Any281 fn as_any_ref(&self) -> &dyn core::any::Any {
282 self
283 }
284 }
285
286 impl ProcFS {
new() -> Arc<Self>287 pub fn new() -> Arc<Self> {
288 // 初始化root inode
289 let root: Arc<LockedProcFSInode> =
290 Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode {
291 parent: Weak::default(),
292 self_ref: Weak::default(),
293 children: BTreeMap::new(),
294 data: Vec::new(),
295 metadata: Metadata {
296 dev_id: 0,
297 inode_id: generate_inode_id(),
298 size: 0,
299 blk_size: 0,
300 blocks: 0,
301 atime: TimeSpec::default(),
302 mtime: TimeSpec::default(),
303 ctime: TimeSpec::default(),
304 file_type: FileType::Dir,
305 mode: ModeType::from_bits_truncate(0o555),
306 nlinks: 1,
307 uid: 0,
308 gid: 0,
309 raw_dev: DeviceNumber::default(),
310 },
311 fs: Weak::default(),
312 fdata: InodeInfo {
313 pid: Pid::new(0),
314 ftype: ProcFileType::Default,
315 },
316 })));
317
318 let result: Arc<ProcFS> = Arc::new(ProcFS { root_inode: root });
319
320 // 对root inode加锁,并继续完成初始化工作
321 let mut root_guard: SpinLockGuard<ProcFSInode> = result.root_inode.0.lock();
322 root_guard.parent = Arc::downgrade(&result.root_inode);
323 root_guard.self_ref = Arc::downgrade(&result.root_inode);
324 root_guard.fs = Arc::downgrade(&result);
325 // 释放锁
326 drop(root_guard);
327
328 // 创建meminfo文件
329 let inode = result.root_inode();
330 let binding = inode.create(
331 "meminfo",
332 FileType::File,
333 ModeType::from_bits_truncate(0o444),
334 );
335 if let Ok(meminfo) = binding {
336 let meminfo_file = meminfo
337 .as_any_ref()
338 .downcast_ref::<LockedProcFSInode>()
339 .unwrap();
340 meminfo_file.0.lock().fdata.pid = Pid::new(0);
341 meminfo_file.0.lock().fdata.ftype = ProcFileType::ProcMeminfo;
342 } else {
343 panic!("create meminfo error");
344 }
345
346 // 创建kmsg文件
347 let binding = inode.create("kmsg", FileType::File, ModeType::from_bits_truncate(0o444));
348 if let Ok(kmsg) = binding {
349 let kmsg_file = kmsg
350 .as_any_ref()
351 .downcast_ref::<LockedProcFSInode>()
352 .unwrap();
353 kmsg_file.0.lock().fdata.pid = Pid::new(1);
354 kmsg_file.0.lock().fdata.ftype = ProcFileType::ProcKmsg;
355 } else {
356 panic!("create ksmg error");
357 }
358
359 return result;
360 }
361
362 /// @brief 进程注册函数
363 /// @usage 在进程中调用并创建进程对应文件
register_pid(&self, pid: Pid) -> Result<(), SystemError>364 pub fn register_pid(&self, pid: Pid) -> Result<(), SystemError> {
365 // 获取当前inode
366 let inode: Arc<dyn IndexNode> = self.root_inode();
367 // 创建对应进程文件夹
368 let pid_dir: Arc<dyn IndexNode> = inode.create(
369 &pid.to_string(),
370 FileType::Dir,
371 ModeType::from_bits_truncate(0o555),
372 )?;
373 // 创建相关文件
374 // status文件
375 let binding: Arc<dyn IndexNode> = pid_dir.create(
376 "status",
377 FileType::File,
378 ModeType::from_bits_truncate(0o444),
379 )?;
380 let status_file: &LockedProcFSInode = binding
381 .as_any_ref()
382 .downcast_ref::<LockedProcFSInode>()
383 .unwrap();
384 status_file.0.lock().fdata.pid = pid;
385 status_file.0.lock().fdata.ftype = ProcFileType::ProcStatus;
386
387 //todo: 创建其他文件
388
389 return Ok(());
390 }
391
392 /// @brief 解除进程注册
393 ///
unregister_pid(&self, pid: Pid) -> Result<(), SystemError>394 pub fn unregister_pid(&self, pid: Pid) -> Result<(), SystemError> {
395 // 获取当前inode
396 let proc: Arc<dyn IndexNode> = self.root_inode();
397 // 获取进程文件夹
398 let pid_dir: Arc<dyn IndexNode> = proc.find(&pid.to_string())?;
399 // 删除进程文件夹下文件
400 pid_dir.unlink("status")?;
401
402 // 查看进程文件是否还存在
403 // let pf= pid_dir.find("status").expect("Cannot find status");
404
405 // 删除进程文件夹
406 proc.unlink(&pid.to_string())?;
407
408 return Ok(());
409 }
410 }
411
412 impl IndexNode for LockedProcFSInode {
open(&self, data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError>413 fn open(&self, data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError> {
414 // 加锁
415 let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock();
416
417 // 如果inode类型为文件夹,则直接返回成功
418 if let FileType::Dir = inode.metadata.file_type {
419 return Ok(());
420 }
421 let mut private_data = ProcfsFilePrivateData::new();
422 // 根据文件类型获取相应数据
423 let file_size = match inode.fdata.ftype {
424 ProcFileType::ProcStatus => inode.open_status(&mut private_data)?,
425 ProcFileType::ProcMeminfo => inode.open_meminfo(&mut private_data)?,
426 _ => {
427 todo!()
428 }
429 };
430 *data = FilePrivateData::Procfs(private_data);
431 // 更新metadata里面的文件大小数值
432 inode.metadata.size = file_size;
433
434 return Ok(());
435 }
436
close(&self, data: &mut FilePrivateData) -> Result<(), SystemError>437 fn close(&self, data: &mut FilePrivateData) -> Result<(), SystemError> {
438 let guard: SpinLockGuard<ProcFSInode> = self.0.lock();
439 // 如果inode类型为文件夹,则直接返回成功
440 if let FileType::Dir = guard.metadata.file_type {
441 return Ok(());
442 }
443 // 释放data
444 *data = FilePrivateData::Procfs(ProcfsFilePrivateData::new());
445
446 return Ok(());
447 }
448
read_at( &self, offset: usize, len: usize, buf: &mut [u8], data: &mut FilePrivateData, ) -> Result<usize, SystemError>449 fn read_at(
450 &self,
451 offset: usize,
452 len: usize,
453 buf: &mut [u8],
454 data: &mut FilePrivateData,
455 ) -> Result<usize, SystemError> {
456 if buf.len() < len {
457 return Err(SystemError::EINVAL);
458 }
459 // 加锁
460 let inode: SpinLockGuard<ProcFSInode> = self.0.lock();
461
462 // 检查当前inode是否为一个文件夹,如果是的话,就返回错误
463 if inode.metadata.file_type == FileType::Dir {
464 return Err(SystemError::EISDIR);
465 }
466
467 // 获取数据信息
468 let private_data = match data {
469 FilePrivateData::Procfs(p) => p,
470 _ => {
471 panic!("ProcFS: FilePrivateData mismatch!");
472 }
473 };
474
475 // 根据文件类型读取相应数据
476 match inode.fdata.ftype {
477 ProcFileType::ProcStatus => return inode.proc_read(offset, len, buf, private_data),
478 ProcFileType::ProcMeminfo => return inode.proc_read(offset, len, buf, private_data),
479 ProcFileType::ProcKmsg => (),
480 ProcFileType::Default => (),
481 };
482
483 // 默认读取
484 let start = inode.data.len().min(offset);
485 let end = inode.data.len().min(offset + len);
486
487 // buffer空间不足
488 if buf.len() < (end - start) {
489 return Err(SystemError::ENOBUFS);
490 }
491
492 // 拷贝数据
493 let src = &inode.data[start..end];
494 buf[0..src.len()].copy_from_slice(src);
495 return Ok(src.len());
496 }
497
write_at( &self, _offset: usize, _len: usize, _buf: &[u8], _data: &mut FilePrivateData, ) -> Result<usize, SystemError>498 fn write_at(
499 &self,
500 _offset: usize,
501 _len: usize,
502 _buf: &[u8],
503 _data: &mut FilePrivateData,
504 ) -> Result<usize, SystemError> {
505 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
506 }
507
fs(&self) -> Arc<dyn FileSystem>508 fn fs(&self) -> Arc<dyn FileSystem> {
509 return self.0.lock().fs.upgrade().unwrap();
510 }
511
as_any_ref(&self) -> &dyn core::any::Any512 fn as_any_ref(&self) -> &dyn core::any::Any {
513 self
514 }
515
metadata(&self) -> Result<Metadata, SystemError>516 fn metadata(&self) -> Result<Metadata, SystemError> {
517 let inode = self.0.lock();
518 let metadata = inode.metadata.clone();
519
520 return Ok(metadata);
521 }
522
set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError>523 fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> {
524 let mut inode = self.0.lock();
525 inode.metadata.atime = metadata.atime;
526 inode.metadata.mtime = metadata.mtime;
527 inode.metadata.ctime = metadata.ctime;
528 inode.metadata.mode = metadata.mode;
529 inode.metadata.uid = metadata.uid;
530 inode.metadata.gid = metadata.gid;
531
532 return Ok(());
533 }
534
resize(&self, len: usize) -> Result<(), SystemError>535 fn resize(&self, len: usize) -> Result<(), SystemError> {
536 let mut inode = self.0.lock();
537 if inode.metadata.file_type == FileType::File {
538 inode.data.resize(len, 0);
539 return Ok(());
540 } else {
541 return Err(SystemError::EINVAL);
542 }
543 }
544
create_with_data( &self, name: &str, file_type: FileType, mode: ModeType, data: usize, ) -> Result<Arc<dyn IndexNode>, SystemError>545 fn create_with_data(
546 &self,
547 name: &str,
548 file_type: FileType,
549 mode: ModeType,
550 data: usize,
551 ) -> Result<Arc<dyn IndexNode>, SystemError> {
552 // 获取当前inode
553 let mut inode = self.0.lock();
554 // 如果当前inode不是文件夹,则返回
555 if inode.metadata.file_type != FileType::Dir {
556 return Err(SystemError::ENOTDIR);
557 }
558 // 如果有重名的,则返回
559 if inode.children.contains_key(name) {
560 return Err(SystemError::EEXIST);
561 }
562
563 // 创建inode
564 let result: Arc<LockedProcFSInode> =
565 Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode {
566 parent: inode.self_ref.clone(),
567 self_ref: Weak::default(),
568 children: BTreeMap::new(),
569 data: Vec::new(),
570 metadata: Metadata {
571 dev_id: 0,
572 inode_id: generate_inode_id(),
573 size: 0,
574 blk_size: 0,
575 blocks: 0,
576 atime: TimeSpec::default(),
577 mtime: TimeSpec::default(),
578 ctime: TimeSpec::default(),
579 file_type: file_type,
580 mode: mode,
581 nlinks: 1,
582 uid: 0,
583 gid: 0,
584 raw_dev: DeviceNumber::from(data as u32),
585 },
586 fs: inode.fs.clone(),
587 fdata: InodeInfo {
588 pid: Pid::new(0),
589 ftype: ProcFileType::Default,
590 },
591 })));
592
593 // 初始化inode的自引用的weak指针
594 result.0.lock().self_ref = Arc::downgrade(&result);
595
596 // 将子inode插入父inode的B树中
597 inode.children.insert(String::from(name), result.clone());
598
599 return Ok(result);
600 }
601
link(&self, name: &str, other: &Arc<dyn IndexNode>) -> Result<(), SystemError>602 fn link(&self, name: &str, other: &Arc<dyn IndexNode>) -> Result<(), SystemError> {
603 let other: &LockedProcFSInode = other
604 .downcast_ref::<LockedProcFSInode>()
605 .ok_or(SystemError::EPERM)?;
606 let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock();
607 let mut other_locked: SpinLockGuard<ProcFSInode> = other.0.lock();
608
609 // 如果当前inode不是文件夹,那么报错
610 if inode.metadata.file_type != FileType::Dir {
611 return Err(SystemError::ENOTDIR);
612 }
613
614 // 如果另一个inode是文件夹,那么也报错
615 if other_locked.metadata.file_type == FileType::Dir {
616 return Err(SystemError::EISDIR);
617 }
618
619 // 如果当前文件夹下已经有同名文件,也报错。
620 if inode.children.contains_key(name) {
621 return Err(SystemError::EEXIST);
622 }
623
624 inode
625 .children
626 .insert(String::from(name), other_locked.self_ref.upgrade().unwrap());
627
628 // 增加硬链接计数
629 other_locked.metadata.nlinks += 1;
630 return Ok(());
631 }
632
unlink(&self, name: &str) -> Result<(), SystemError>633 fn unlink(&self, name: &str) -> Result<(), SystemError> {
634 let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock();
635 // 如果当前inode不是目录,那么也没有子目录/文件的概念了,因此要求当前inode的类型是目录
636 if inode.metadata.file_type != FileType::Dir {
637 return Err(SystemError::ENOTDIR);
638 }
639 // 不允许删除当前文件夹,也不允许删除上一个目录
640 if name == "." || name == ".." {
641 return Err(SystemError::ENOTEMPTY);
642 }
643
644 // 获得要删除的文件的inode
645 let to_delete = inode.children.get(name).ok_or(SystemError::ENOENT)?;
646 // 减少硬链接计数
647 to_delete.0.lock().metadata.nlinks -= 1;
648 // 在当前目录中删除这个子目录项
649 inode.children.remove(name);
650 return Ok(());
651 }
652
move_( &self, _old_name: &str, _target: &Arc<dyn IndexNode>, _new_name: &str, ) -> Result<(), SystemError>653 fn move_(
654 &self,
655 _old_name: &str,
656 _target: &Arc<dyn IndexNode>,
657 _new_name: &str,
658 ) -> Result<(), SystemError> {
659 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
660 }
661
find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError>662 fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
663 let inode = self.0.lock();
664
665 if inode.metadata.file_type != FileType::Dir {
666 return Err(SystemError::ENOTDIR);
667 }
668
669 match name {
670 "" | "." => {
671 return Ok(inode.self_ref.upgrade().ok_or(SystemError::ENOENT)?);
672 }
673
674 ".." => {
675 return Ok(inode.parent.upgrade().ok_or(SystemError::ENOENT)?);
676 }
677 name => {
678 // 在子目录项中查找
679 return Ok(inode.children.get(name).ok_or(SystemError::ENOENT)?.clone());
680 }
681 }
682 }
683
get_entry_name(&self, ino: InodeId) -> Result<String, SystemError>684 fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> {
685 let inode: SpinLockGuard<ProcFSInode> = self.0.lock();
686 if inode.metadata.file_type != FileType::Dir {
687 return Err(SystemError::ENOTDIR);
688 }
689
690 match ino.into() {
691 0 => {
692 return Ok(String::from("."));
693 }
694 1 => {
695 return Ok(String::from(".."));
696 }
697 ino => {
698 // 暴力遍历所有的children,判断inode id是否相同
699 // TODO: 优化这里,这个地方性能很差!
700 let mut key: Vec<String> = inode
701 .children
702 .keys()
703 .filter(|k| {
704 inode
705 .children
706 .get(*k)
707 .unwrap()
708 .0
709 .lock()
710 .metadata
711 .inode_id
712 .into()
713 == ino
714 })
715 .cloned()
716 .collect();
717
718 match key.len() {
719 0=>{return Err(SystemError::ENOENT);}
720 1=>{return Ok(key.remove(0));}
721 _ => panic!("Procfs get_entry_name: key.len()={key_len}>1, current inode_id={inode_id:?}, to find={to_find:?}", key_len=key.len(), inode_id = inode.metadata.inode_id, to_find=ino)
722 }
723 }
724 }
725 }
726
list(&self) -> Result<Vec<String>, SystemError>727 fn list(&self) -> Result<Vec<String>, SystemError> {
728 let info = self.metadata()?;
729 if info.file_type != FileType::Dir {
730 return Err(SystemError::ENOTDIR);
731 }
732
733 let mut keys: Vec<String> = Vec::new();
734 keys.push(String::from("."));
735 keys.push(String::from(".."));
736 keys.append(&mut self.0.lock().children.keys().cloned().collect());
737
738 return Ok(keys);
739 }
740 }
741
742 /// @brief 向procfs注册进程
procfs_register_pid(pid: Pid) -> Result<(), SystemError>743 pub fn procfs_register_pid(pid: Pid) -> Result<(), SystemError> {
744 let procfs_inode = ROOT_INODE().find("proc")?;
745
746 let procfs_inode = procfs_inode
747 .downcast_ref::<LockedProcFSInode>()
748 .expect("Failed to find procfs' root inode");
749 let fs = procfs_inode.fs();
750 let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap();
751
752 // 调用注册函数
753 procfs.register_pid(pid)?;
754
755 return Ok(());
756 }
757
758 /// @brief 在ProcFS中,解除进程的注册
procfs_unregister_pid(pid: Pid) -> Result<(), SystemError>759 pub fn procfs_unregister_pid(pid: Pid) -> Result<(), SystemError> {
760 // 获取procfs实例
761 let procfs_inode: Arc<dyn IndexNode> = ROOT_INODE().find("proc")?;
762
763 let procfs_inode: &LockedProcFSInode = procfs_inode
764 .downcast_ref::<LockedProcFSInode>()
765 .expect("Failed to find procfs' root inode");
766 let fs: Arc<dyn FileSystem> = procfs_inode.fs();
767 let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap();
768
769 // 调用解除注册函数
770 return procfs.unregister_pid(pid);
771 }
772
procfs_init() -> Result<(), SystemError>773 pub fn procfs_init() -> Result<(), SystemError> {
774 static INIT: Once = Once::new();
775 let mut result = None;
776 INIT.call_once(|| {
777 kinfo!("Initializing ProcFS...");
778 // 创建 procfs 实例
779 let procfs: Arc<ProcFS> = ProcFS::new();
780
781 // procfs 挂载
782 let _t = ROOT_INODE()
783 .find("proc")
784 .expect("Cannot find /proc")
785 .mount(procfs)
786 .expect("Failed to mount proc");
787 kinfo!("ProcFS mounted.");
788 result = Some(Ok(()));
789 });
790
791 return result.unwrap();
792 }
793