1 use crate::{ 2 filesystem::{sysfs::SysFSKernPrivateData, vfs::PollStatus}, 3 libs::spinlock::SpinLockGuard, 4 syscall::SystemError, 5 }; 6 use alloc::sync::Arc; 7 use core::fmt::Debug; 8 9 use super::KernFSInode; 10 11 /// KernFS文件的回调接口 12 /// 13 /// 当用户态程序打开、读取、写入、关闭文件时,kernfs会调用相应的回调函数。 14 pub trait KernFSCallback: Send + Sync + Debug { 15 fn open(&self, data: KernCallbackData) -> Result<(), SystemError>; 16 17 fn read( 18 &self, 19 data: KernCallbackData, 20 buf: &mut [u8], 21 offset: usize, 22 ) -> Result<usize, SystemError>; 23 24 fn write( 25 &self, 26 data: KernCallbackData, 27 buf: &[u8], 28 offset: usize, 29 ) -> Result<usize, SystemError>; 30 31 fn poll(&self, data: KernCallbackData) -> Result<PollStatus, SystemError>; 32 } 33 34 /// KernFS文件的回调数据 35 #[derive(Debug)] 36 pub struct KernCallbackData<'a> { 37 kern_inode: Arc<KernFSInode>, 38 private_data: SpinLockGuard<'a, Option<KernInodePrivateData>>, 39 } 40 41 #[allow(dead_code)] 42 impl<'a> KernCallbackData<'a> { 43 pub fn new( 44 kern_inode: Arc<KernFSInode>, 45 private_data: SpinLockGuard<'a, Option<KernInodePrivateData>>, 46 ) -> Self { 47 Self { 48 kern_inode, 49 private_data, 50 } 51 } 52 53 #[inline(always)] 54 pub fn kern_inode(&self) -> &Arc<KernFSInode> { 55 return &self.kern_inode; 56 } 57 58 #[inline(always)] 59 pub fn private_data(&self) -> &Option<KernInodePrivateData> { 60 return &self.private_data; 61 } 62 63 #[inline(always)] 64 pub fn private_data_mut(&mut self) -> &mut Option<KernInodePrivateData> { 65 return &mut self.private_data; 66 } 67 68 pub fn callback_read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SystemError> { 69 let private_data = self.private_data(); 70 if let Some(private_data) = private_data { 71 return private_data.callback_read(buf, offset); 72 } 73 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 74 } 75 76 pub fn callback_write(&self, buf: &[u8], offset: usize) -> Result<usize, SystemError> { 77 let private_data = self.private_data(); 78 if let Some(private_data) = private_data { 79 return private_data.callback_write(buf, offset); 80 } 81 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 82 } 83 } 84 85 #[allow(dead_code)] 86 #[derive(Debug)] 87 pub enum KernInodePrivateData { 88 SysFS(SysFSKernPrivateData), 89 } 90 91 impl KernInodePrivateData { 92 #[inline(always)] 93 pub fn callback_read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SystemError> { 94 match self { 95 KernInodePrivateData::SysFS(private_data) => { 96 return private_data.callback_read(buf, offset); 97 } 98 } 99 } 100 101 #[inline(always)] 102 pub fn callback_write(&self, buf: &[u8], offset: usize) -> Result<usize, SystemError> { 103 match self { 104 KernInodePrivateData::SysFS(private_data) => { 105 return private_data.callback_write(buf, offset); 106 } 107 } 108 } 109 } 110