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