xref: /DragonOS/kernel/src/driver/disk/ahci/mod.rs (revision f79998f626801329580c782fd05e36cb2027f474)
1 // 导出 ahci 相关的 module
2 pub mod ahci_inode;
3 pub mod ahcidisk;
4 pub mod hba;
5 
6 use crate::driver::base::block::disk_info::BLK_GF_AHCI;
7 use crate::driver::block::cache::cached_block_device::BlockCache;
8 // 依赖的rust工具包
9 use crate::driver::pci::pci::{
10     get_pci_device_structure_mut, PciDeviceStructure, PCI_DEVICE_LINKEDLIST,
11 };
12 use crate::filesystem::devfs::devfs_register;
13 
14 use crate::driver::disk::ahci::{
15     ahcidisk::LockedAhciDisk,
16     hba::HbaMem,
17     hba::{HbaPort, HbaPortType},
18 };
19 use crate::libs::rwlock::RwLockWriteGuard;
20 use crate::libs::spinlock::{SpinLock, SpinLockGuard};
21 use crate::mm::virt_2_phys;
22 use ahci_inode::LockedAhciInode;
23 use alloc::{boxed::Box, collections::LinkedList, format, string::String, sync::Arc, vec::Vec};
24 use core::sync::atomic::compiler_fence;
25 use log::{debug, error};
26 use system_error::SystemError;
27 
28 // 仅module内可见 全局数据区  hbr_port, disks
29 static LOCKED_HBA_MEM_LIST: SpinLock<Vec<&mut HbaMem>> = SpinLock::new(Vec::new());
30 static LOCKED_DISKS_LIST: SpinLock<Vec<Arc<LockedAhciDisk>>> = SpinLock::new(Vec::new());
31 
32 const AHCI_CLASS: u8 = 0x1;
33 const AHCI_SUBCLASS: u8 = 0x6;
34 
35 /* TFES - Task File Error Status */
36 #[allow(non_upper_case_globals)]
37 pub const HBA_PxIS_TFES: u32 = 1 << 30;
38 
39 /// @brief 寻找所有的ahci设备
40 /// @param list 链表的写锁
41 /// @return Result<Vec<&'a mut Box<dyn PciDeviceStructure>>, SystemError>   成功则返回包含所有ahci设备结构体的可变引用的链表,失败则返回err
42 fn ahci_device_search<'a>(
43     list: &'a mut RwLockWriteGuard<'_, LinkedList<Box<dyn PciDeviceStructure>>>,
44 ) -> Result<Vec<&'a mut Box<dyn PciDeviceStructure>>, SystemError> {
45     let result = get_pci_device_structure_mut(list, AHCI_CLASS, AHCI_SUBCLASS);
46 
47     if result.is_empty() {
48         return Err(SystemError::ENODEV);
49     }
50 
51     return Ok(result);
52 }
53 
54 /// @brief: 初始化 ahci
55 pub fn ahci_init() -> Result<(), SystemError> {
56     let mut list = PCI_DEVICE_LINKEDLIST.write();
57     let ahci_device = ahci_device_search(&mut list)?;
58     // 全局数据 - 列表
59     let mut disks_list = LOCKED_DISKS_LIST.lock();
60 
61     for device in ahci_device {
62         let standard_device = device.as_standard_device_mut().unwrap();
63         standard_device.bar_ioremap();
64         // 对于每一个ahci控制器分配一块空间
65         let ahci_port_base_vaddr =
66             Box::leak(Box::new([0u8; (1 << 20) as usize])) as *mut u8 as usize;
67         let virtaddr = standard_device
68             .bar()
69             .ok_or(SystemError::EACCES)?
70             .get_bar(5)
71             .or(Err(SystemError::EACCES))?
72             .virtual_address()
73             .unwrap();
74         // 最后把这个引用列表放入到全局列表
75         let mut hba_mem_list = LOCKED_HBA_MEM_LIST.lock();
76         //这里两次unsafe转引用规避rust只能有一个可变引用的检查,提高运行速度
77         let hba_mem = unsafe { (virtaddr.data() as *mut HbaMem).as_mut().unwrap() };
78         hba_mem_list.push(unsafe { (virtaddr.data() as *mut HbaMem).as_mut().unwrap() });
79         let pi = volatile_read!(hba_mem.pi);
80         let hba_mem_index = hba_mem_list.len() - 1;
81         drop(hba_mem_list);
82         // 初始化所有的port
83         let mut id = 0;
84         for j in 0..32 {
85             if (pi >> j) & 1 > 0 {
86                 let hba_mem_list = LOCKED_HBA_MEM_LIST.lock();
87                 let hba_mem_port = &mut hba_mem.ports[j];
88                 let tp = hba_mem_port.check_type();
89                 match tp {
90                     HbaPortType::None => {
91                         debug!("<ahci_rust_init> Find a None type Disk.");
92                     }
93                     HbaPortType::Unknown(err) => {
94                         debug!("<ahci_rust_init> Find a Unknown({:?}) type Disk.", err);
95                     }
96                     _ => {
97                         debug!("<ahci_rust_init> Find a {:?} type Disk.", tp);
98 
99                         // 计算地址
100                         let fb = virt_2_phys(ahci_port_base_vaddr + (32 << 10) + (j << 8));
101                         let clb = virt_2_phys(ahci_port_base_vaddr + (j << 10));
102                         let ctbas = (0..32)
103                             .map(|x| {
104                                 virt_2_phys(
105                                     ahci_port_base_vaddr + (40 << 10) + (j << 13) + (x << 8),
106                                 ) as u64
107                             })
108                             .collect::<Vec<_>>();
109 
110                         // 初始化 port
111                         hba_mem_port.init(clb as u64, fb as u64, &ctbas);
112                         drop(hba_mem_list);
113                         compiler_fence(core::sync::atomic::Ordering::SeqCst);
114                         // 创建 disk
115                         disks_list.push(LockedAhciDisk::new(
116                             format!("ahci_disk_{}", id),
117                             BLK_GF_AHCI,
118                             hba_mem_index as u8,
119                             j as u8,
120                         )?);
121                         id += 1; // ID 从0开始
122 
123                         debug!("start register ahci device");
124 
125                         // 挂载到devfs上面去
126                         let ret = devfs_register(
127                             format!("ahci_{}", id).as_str(),
128                             LockedAhciInode::new(disks_list.last().unwrap().clone()),
129                         );
130                         if let Err(err) = ret {
131                             error!(
132                                 "Ahci_{} ctrl = {}, port = {} failed to register, error code = {:?}",
133                                 id,
134                                 hba_mem_index as u8,
135                                 j,
136                                 err
137                             );
138                         }
139                     }
140                 }
141             }
142         }
143         BlockCache::init();
144     }
145 
146     compiler_fence(core::sync::atomic::Ordering::SeqCst);
147     return Ok(());
148 }
149 
150 /// @brief: 获取所有的 disk
151 #[allow(dead_code)]
152 pub fn disks() -> Vec<Arc<LockedAhciDisk>> {
153     let disks_list = LOCKED_DISKS_LIST.lock();
154     return disks_list.clone();
155 }
156 
157 /// @brief: 通过 name 获取 disk
158 pub fn get_disks_by_name(name: String) -> Result<Arc<LockedAhciDisk>, SystemError> {
159     let disks_list: SpinLockGuard<Vec<Arc<LockedAhciDisk>>> = LOCKED_DISKS_LIST.lock();
160     let result = disks_list
161         .iter()
162         .find(|x| x.0.lock().name == name)
163         .ok_or(SystemError::ENXIO)?
164         .clone();
165     return Ok(result);
166 }
167 
168 /// @brief: 通过 ctrl_num 和 port_num 获取 port
169 fn _port(ctrl_num: u8, port_num: u8) -> &'static mut HbaPort {
170     let list: SpinLockGuard<Vec<&mut HbaMem>> = LOCKED_HBA_MEM_LIST.lock();
171     let port: &HbaPort = &list[ctrl_num as usize].ports[port_num as usize];
172 
173     return unsafe { (port as *const HbaPort as *mut HbaPort).as_mut().unwrap() };
174 }
175