1 use alloc::vec::Vec;
2 use core::{intrinsics::size_of, ptr};
3 
4 use core::sync::atomic::compiler_fence;
5 
6 use crate::mm::phys_2_virt;
7 
8 /// 文件说明: 实现了 AHCI 中的控制器 HBA 的相关行为
9 
10 /// 根据 AHCI 写出 HBA 的 Command
11 pub const ATA_CMD_READ_DMA_EXT: u8 = 0x25; // 读操作,并且退出
12 pub const ATA_CMD_WRITE_DMA_EXT: u8 = 0x35; // 写操作,并且退出
13 #[allow(dead_code)]
14 pub const ATA_CMD_IDENTIFY: u8 = 0xEC;
15 #[allow(dead_code)]
16 pub const ATA_CMD_IDENTIFY_PACKET: u8 = 0xA1;
17 #[allow(dead_code)]
18 pub const ATA_CMD_PACKET: u8 = 0xA0;
19 pub const ATA_DEV_BUSY: u8 = 0x80;
20 pub const ATA_DEV_DRQ: u8 = 0x08;
21 
22 pub const HBA_PORT_CMD_CR: u32 = 1 << 15;
23 pub const HBA_PORT_CMD_FR: u32 = 1 << 14;
24 pub const HBA_PORT_CMD_FRE: u32 = 1 << 4;
25 pub const HBA_PORT_CMD_ST: u32 = 1;
26 #[allow(dead_code)]
27 pub const HBA_PORT_IS_ERR: u32 = 1 << 30 | 1 << 29 | 1 << 28 | 1 << 27;
28 pub const HBA_SSTS_PRESENT: u32 = 0x3;
29 pub const HBA_SIG_ATA: u32 = 0x00000101;
30 pub const HBA_SIG_ATAPI: u32 = 0xEB140101;
31 pub const HBA_SIG_PM: u32 = 0x96690101;
32 pub const HBA_SIG_SEMB: u32 = 0xC33C0101;
33 
34 /// 接入 Port 的 不同设备类型
35 #[derive(Debug)]
36 pub enum HbaPortType {
37     None,
38     Unknown(u32),
39     SATA,
40     SATAPI,
41     PM,
42     SEMB,
43 }
44 
45 /// 声明了 HBA 的所有属性
46 #[repr(packed)]
47 pub struct HbaPort {
48     pub clb: u64,         // 0x00, command list base address, 1K-byte aligned
49     pub fb: u64,          // 0x08, FIS base address, 256-byte aligned
50     pub is: u32,          // 0x10, interrupt status
51     pub ie: u32,          // 0x14, interrupt enable
52     pub cmd: u32,         // 0x18, command and status
53     pub _rsv0: u32,       // 0x1C, Reserved
54     pub tfd: u32,         // 0x20, task file data
55     pub sig: u32,         // 0x24, signature
56     pub ssts: u32,        // 0x28, SATA status (SCR0:SStatus)
57     pub sctl: u32,        // 0x2C, SATA control (SCR2:SControl)
58     pub serr: u32,        // 0x30, SATA error (SCR1:SError)
59     pub sact: u32,        // 0x34, SATA active (SCR3:SActive)
60     pub ci: u32,          // 0x38, command issue
61     pub sntf: u32,        // 0x3C, SATA notification (SCR4:SNotification)
62     pub fbs: u32,         // 0x40, FIS-based switch control
63     pub _rsv1: [u32; 11], // 0x44 ~ 0x6F, Reserved
64     pub vendor: [u32; 4], // 0x70 ~ 0x7F, vendor specific
65 }
66 
67 /// 全称 HBA Memory Register,是HBA的寄存器在内存中的映射
68 #[repr(packed)]
69 pub struct HbaMem {
70     pub cap: u32,             // 0x00, Host capability
71     pub ghc: u32,             // 0x04, Global host control
72     pub is: u32,              // 0x08, Interrupt status
73     pub pi: u32,              // 0x0C, Port implemented
74     pub vs: u32,              // 0x10, Version
75     pub ccc_ctl: u32,         // 0x14, Command completion coalescing control
76     pub ccc_pts: u32,         // 0x18, Command completion coalescing ports
77     pub em_loc: u32,          // 0x1C, Enclosure management location
78     pub em_ctl: u32,          // 0x20, Enclosure management control
79     pub cap2: u32,            // 0x24, Host capabilities extended
80     pub bohc: u32,            // 0x28, BIOS/OS handoff control and status
81     pub _rsv: [u8; 116],      // 0x2C - 0x9F, Reserved
82     pub vendor: [u8; 96],     // 0xA0 - 0xFF, Vendor specific registers
83     pub ports: [HbaPort; 32], // 0x100 - 0x10FF, Port control registers
84 }
85 
86 /// HBA Command Table 里面的 PRDT 项
87 /// 作用: 记录了内存中读/写数据的位置,以及长度。你可以把他类比成一个指针?
88 #[repr(packed)]
89 pub struct HbaPrdtEntry {
90     pub dba: u64, // Data base address
91     _rsv0: u32,   // Reserved
92     pub dbc: u32, // Byte count, 4M max, interrupt = 1
93 }
94 
95 /// HAB Command Table
96 /// 每个 Port 一个 Table,主机和设备的交互都靠这个数据结构
97 #[repr(packed)]
98 pub struct HbaCmdTable {
99     // 0x00
100     pub cfis: [u8; 64], // Command FIS
101     // 0x40
102     pub acmd: [u8; 16], // ATAPI command, 12 or 16 bytes
103     // 0x50
104     _rsv: [u8; 48], // Reserved
105     // 0x80
106     pub prdt_entry: [HbaPrdtEntry; 65535], // Physical region descriptor table entries, 0 ~ 65535, 需要注意不要越界
107 }
108 
109 /// HBA Command Header
110 /// 作用: 你可以把他类比成 Command Table 的指针。
111 /// 猜测: 这里多了一层 Header,而不是直接在 HbaMem 结构体指向 CmdTable,可能是为了兼容和可移植性?
112 #[repr(packed)]
113 pub struct HbaCmdHeader {
114     // DW0
115     pub cfl: u8,
116     // Command FIS length in DWORDS: 5(len in [2, 16]), atapi: 1, write - host to device: 1, prefetchable: 1
117     pub _pm: u8,    // Reset - 0x80, bist: 0x40, clear busy on ok: 0x20, port multiplier
118     pub prdtl: u16, // Physical region descriptor table length in entries
119     // DW1
120     pub _prdbc: u32, // Physical region descriptor byte count transferred
121     // DW2, 3
122     pub ctba: u64, // Command table descriptor base address
123     // DW4 - 7
124     pub _rsv1: [u32; 4], // Reserved
125 }
126 
127 /// Port 的函数实现
128 impl HbaPort {
129     /// 获取设备类型
check_type(&mut self) -> HbaPortType130     pub fn check_type(&mut self) -> HbaPortType {
131         if volatile_read!(self.ssts) & HBA_SSTS_PRESENT > 0 {
132             let sig = volatile_read!(self.sig);
133             match sig {
134                 HBA_SIG_ATA => HbaPortType::SATA,
135                 HBA_SIG_ATAPI => HbaPortType::SATAPI,
136                 HBA_SIG_PM => HbaPortType::PM,
137                 HBA_SIG_SEMB => HbaPortType::SEMB,
138                 _ => HbaPortType::Unknown(sig),
139             }
140         } else {
141             HbaPortType::None
142         }
143     }
144 
145     /// 启动该端口的命令引擎
start(&mut self)146     pub fn start(&mut self) {
147         while volatile_read!(self.cmd) & HBA_PORT_CMD_CR > 0 {
148             core::hint::spin_loop();
149         }
150         let val: u32 = volatile_read!(self.cmd) | HBA_PORT_CMD_FRE | HBA_PORT_CMD_ST;
151         volatile_write!(self.cmd, val);
152     }
153 
154     /// 关闭该端口的命令引擎
stop(&mut self)155     pub fn stop(&mut self) {
156         #[allow(unused_unsafe)]
157         {
158             volatile_write!(
159                 self.cmd,
160                 (u32::MAX ^ HBA_PORT_CMD_ST) & volatile_read!(self.cmd)
161             );
162         }
163 
164         while volatile_read!(self.cmd) & (HBA_PORT_CMD_FR | HBA_PORT_CMD_CR)
165             == (HBA_PORT_CMD_FR | HBA_PORT_CMD_CR)
166         {
167             core::hint::spin_loop();
168         }
169 
170         #[allow(unused_unsafe)]
171         {
172             volatile_write!(
173                 self.cmd,
174                 (u32::MAX ^ HBA_PORT_CMD_FRE) & volatile_read!(self.cmd)
175             );
176         }
177     }
178 
179     /// @return: 返回一个空闲 cmd table 的 id; 如果没有,则返回 Option::None
find_cmdslot(&self) -> Option<u32>180     pub fn find_cmdslot(&self) -> Option<u32> {
181         let slots = volatile_read!(self.sact) | volatile_read!(self.ci);
182         for i in 0..32 {
183             if slots & 1 << i == 0 {
184                 return Some(i);
185             }
186         }
187         return None;
188     }
189 
190     /// 初始化,  把 CmdList 等变量的地址赋值到 HbaPort 上 - 这些空间由操作系统分配且固定
191     /// 等价于原C版本的 port_rebase 函数
init(&mut self, clb: u64, fb: u64, ctbas: &Vec<u64>)192     pub fn init(&mut self, clb: u64, fb: u64, ctbas: &Vec<u64>) {
193         self.stop(); // 先暂停端口
194 
195         // 赋值 command list base address
196         // Command list offset: 1K*portno
197         // Command list entry size = 32
198         // Command list entry maxim count = 32
199         // Command list maxim size = 32*32 = 1K per port
200         volatile_write!(self.clb, clb);
201 
202         unsafe {
203             compiler_fence(core::sync::atomic::Ordering::SeqCst);
204             ptr::write_bytes(phys_2_virt(clb as usize) as *mut u64, 0, 1024);
205         }
206 
207         // 赋值 fis base address
208         // FIS offset: 32K+256*portno
209         // FIS entry size = 256 bytes per port
210         volatile_write!(self.fb, fb);
211         unsafe {
212             compiler_fence(core::sync::atomic::Ordering::SeqCst);
213             ptr::write_bytes(phys_2_virt(fb as usize) as *mut u64, 0, 256);
214         }
215 
216         // 赋值 command table base address
217         // Command table offset: 40K + 8K*portno
218         // Command table size = 256*32 = 8K per port
219         let mut cmdheaders = phys_2_virt(clb as usize) as *mut u64 as *mut HbaCmdHeader;
220         for i in 0..32 as usize {
221             volatile_write!((*cmdheaders).prdtl, 0); // 一开始没有询问,prdtl = 0
222             volatile_write!((*cmdheaders).ctba, ctbas[i]);
223             // 这里限制了 prdtl <= 8, 所以一共用了256bytes,如果需要修改,可以修改这里
224             compiler_fence(core::sync::atomic::Ordering::SeqCst);
225             unsafe {
226                 ptr::write_bytes(phys_2_virt(ctbas[i] as usize) as *mut u64, 0, 256);
227             }
228             cmdheaders = (cmdheaders as usize + size_of::<HbaCmdHeader>()) as *mut HbaCmdHeader;
229         }
230 
231         #[allow(unused_unsafe)]
232         {
233             // 启动中断
234             volatile_write!(self.ie, 0 /*TODO: Enable interrupts: 0b10111*/);
235 
236             // 错误码
237             volatile_write!(self.serr, volatile_read!(self.serr));
238 
239             // Disable power management
240             volatile_write!(self.sctl, volatile_read!(self.sctl) | 7 << 8);
241 
242             // Power on and spin up device
243             volatile_write!(self.cmd, volatile_read!(self.cmd) | 1 << 2 | 1 << 1);
244         }
245         self.start(); // 重新开启端口
246     }
247 }
248 
249 #[repr(u8)]
250 #[allow(dead_code)]
251 pub enum FisType {
252     /// Register FIS - host to device
253     RegH2D = 0x27,
254     /// Register FIS - device to host
255     RegD2H = 0x34,
256     /// DMA activate FIS - device to host
257     DmaAct = 0x39,
258     /// DMA setup FIS - bidirectional
259     DmaSetup = 0x41,
260     /// Data FIS - bidirectional
261     Data = 0x46,
262     /// BIST activate FIS - bidirectional
263     Bist = 0x58,
264     /// PIO setup FIS - device to host
265     PioSetup = 0x5F,
266     /// Set device bits FIS - device to host
267     DevBits = 0xA1,
268 }
269 
270 #[repr(packed)]
271 pub struct FisRegH2D {
272     // DWORD 0
273     pub fis_type: u8, // FIS_TYPE_REG_H2D
274 
275     pub pm: u8, // Port multiplier, 1: Command, 0: Control
276     // uint8_t pmport : 4; // Port multiplier  低4位
277     // uint8_t rsv0 : 3;   // Reserved
278     // uint8_t c : 1;      // 1: Command, 0: Control
279     pub command: u8,  // Command register
280     pub featurel: u8, // Feature register, 7:0
281 
282     // DWORD 1
283     pub lba0: u8,   // LBA low register, 7:0
284     pub lba1: u8,   // LBA mid register, 15:8
285     pub lba2: u8,   // LBA high register, 23:16
286     pub device: u8, // Device register
287 
288     // DWORD 2
289     pub lba3: u8,     // LBA register, 31:24
290     pub lba4: u8,     // LBA register, 39:32
291     pub lba5: u8,     // LBA register, 47:40
292     pub featureh: u8, // Feature register, 15:8
293 
294     // DWORD 3
295     pub countl: u8,  // Count register, 7:0
296     pub counth: u8,  // Count register, 15:8
297     pub icc: u8,     // Isochronous command completion
298     pub control: u8, // Control register
299 
300     // DWORD 4
301     pub rsv1: [u8; 4], // Reserved
302 }
303 
304 #[repr(packed)]
305 #[allow(dead_code)]
306 pub struct FisRegD2H {
307     // DWORD 0
308     pub fis_type: u8, // FIS_TYPE_REG_D2H
309 
310     pub pm: u8, // Port multiplier, Interrupt bit: 2
311 
312     pub status: u8, // Status register
313     pub error: u8,  // Error register
314 
315     // DWORD 1
316     pub lba0: u8,   // LBA low register, 7:0
317     pub lba1: u8,   // LBA mid register, 15:8
318     pub lba2: u8,   // LBA high register, 23:16
319     pub device: u8, // Device register
320 
321     // DWORD 2
322     pub lba3: u8, // LBA register, 31:24
323     pub lba4: u8, // LBA register, 39:32
324     pub lba5: u8, // LBA register, 47:40
325     pub rsv2: u8, // Reserved
326 
327     // DWORD 3
328     pub countl: u8,    // Count register, 7:0
329     pub counth: u8,    // Count register, 15:8
330     pub rsv3: [u8; 2], // Reserved
331 
332     // DWORD 4
333     pub rsv4: [u8; 4], // Reserved
334 }
335 
336 #[repr(packed)]
337 #[allow(dead_code)]
338 pub struct FisData {
339     // DWORD 0
340     pub fis_type: u8, // FIS_TYPE_DATA
341 
342     pub pm: u8, // Port multiplier
343 
344     pub rsv1: [u8; 2], // Reserved
345 
346     // DWORD 1 ~ N
347     pub data: [u8; 252], // Payload
348 }
349 
350 #[repr(packed)]
351 #[allow(dead_code)]
352 pub struct FisPioSetup {
353     // DWORD 0
354     pub fis_type: u8, // FIS_TYPE_PIO_SETUP
355 
356     pub pm: u8, // Port multiplier, direction: 4 - device to host, interrupt: 2
357 
358     pub status: u8, // Status register
359     pub error: u8,  // Error register
360 
361     // DWORD 1
362     pub lba0: u8,   // LBA low register, 7:0
363     pub lba1: u8,   // LBA mid register, 15:8
364     pub lba2: u8,   // LBA high register, 23:16
365     pub device: u8, // Device register
366 
367     // DWORD 2
368     pub lba3: u8, // LBA register, 31:24
369     pub lba4: u8, // LBA register, 39:32
370     pub lba5: u8, // LBA register, 47:40
371     pub rsv2: u8, // Reserved
372 
373     // DWORD 3
374     pub countl: u8,   // Count register, 7:0
375     pub counth: u8,   // Count register, 15:8
376     pub rsv3: u8,     // Reserved
377     pub e_status: u8, // New value of status register
378 
379     // DWORD 4
380     pub tc: u16,       // Transfer count
381     pub rsv4: [u8; 2], // Reserved
382 }
383 
384 #[repr(packed)]
385 #[allow(dead_code)]
386 pub struct FisDmaSetup {
387     // DWORD 0
388     pub fis_type: u8, // FIS_TYPE_DMA_SETUP
389 
390     pub pm: u8, // Port multiplier, direction: 4 - device to host, interrupt: 2, auto-activate: 1
391 
392     pub rsv1: [u8; 2], // Reserved
393 
394     // DWORD 1&2
395     pub dma_buffer_id: u64, /* DMA Buffer Identifier. Used to Identify DMA buffer in host memory. SATA Spec says host specific and not in Spec. Trying AHCI spec might work. */
396 
397     // DWORD 3
398     pub rsv3: u32, // More reserved
399 
400     // DWORD 4
401     pub dma_buffer_offset: u32, // Byte offset into buffer. First 2 bits must be 0
402 
403     // DWORD 5
404     pub transfer_count: u32, // Number of bytes to transfer. Bit 0 must be 0
405 
406     // DWORD 6
407     pub rsv6: u32, // Reserved
408 }
409