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