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