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