Merge branch 'master' into sata-ahci-dev
[lunaix-os.git] / lunaix-os / hal / ahci / ahci.c
1 /**
2  * @file ahci.c
3  * @author Lunaixsky (zelong56@gmail.com)
4  * @brief A software implementation of Serial ATA AHCI 1.3.1 Specification
5  * @version 0.1
6  * @date 2022-06-28
7  *
8  * @copyright Copyright (c) 2022
9  *
10  */
11 #include <hal/ahci/ahci.h>
12 #include <hal/ahci/utils.h>
13 #include <hal/pci.h>
14 #include <klibc/string.h>
15 #include <lunaix/mm/mmio.h>
16 #include <lunaix/mm/pmm.h>
17 #include <lunaix/mm/valloc.h>
18 #include <lunaix/mm/vmm.h>
19 #include <lunaix/spike.h>
20 #include <lunaix/syslog.h>
21
22 #define HBA_FIS_SIZE 256
23 #define HBA_CLB_SIZE 1024
24
25 LOG_MODULE("AHCI")
26
27 static struct ahci_hba hba;
28
29 void
30 __ahci_hba_isr(isr_param param);
31
32 void
33 ahci_init()
34 {
35     struct pci_device* ahci_dev = pci_get_device_by_class(AHCI_HBA_CLASS);
36     assert_msg(ahci_dev, "AHCI: Not found.");
37
38     uintptr_t bar6, size;
39     size = pci_bar_sizing(ahci_dev, &bar6, 6);
40     assert_msg(bar6 && PCI_BAR_MMIO(bar6), "AHCI: BAR#6 is not MMIO.");
41
42     pci_reg_t cmd = pci_read_cspace(ahci_dev->cspace_base, PCI_REG_STATUS_CMD);
43
44     // 禁用传统中断(因为我们使用MSI),启用MMIO访问,允许PCI设备间访问
45     cmd |= (PCI_RCMD_MM_ACCESS | PCI_RCMD_DISABLE_INTR | PCI_RCMD_BUS_MASTER);
46
47     pci_write_cspace(ahci_dev->cspace_base, PCI_REG_STATUS_CMD, cmd);
48
49     pci_setup_msi(ahci_dev, AHCI_HBA_IV);
50     intr_subscribe(AHCI_HBA_IV, __ahci_hba_isr);
51
52     memset(&hba, 0, sizeof(hba));
53
54     hba.base = (hba_reg_t*)ioremap(PCI_BAR_ADDR_MM(bar6), size);
55
56     // 重置HBA
57     hba.base[HBA_RGHC] |= HBA_RGHC_RESET;
58     wait_until(!(hba.base[HBA_RGHC] & HBA_RGHC_RESET));
59
60     // 启用AHCI工作模式,启用中断
61     hba.base[HBA_RGHC] |= HBA_RGHC_ACHI_ENABLE;
62     hba.base[HBA_RGHC] |= HBA_RGHC_INTR_ENABLE;
63
64     // As per section 3.1.1, this is 0 based value.
65     hba_reg_t cap = hba.base[HBA_RCAP];
66     hba.ports_num = (cap & 0x1f) + 1;  // CAP.PI
67     hba.cmd_slots = (cap >> 8) & 0x1f; // CAP.NCS
68     hba.version = hba.base[HBA_RVER];
69
70     /* ------ HBA端口配置 ------ */
71     hba_reg_t pmap = hba.base[HBA_RPI];
72     uintptr_t clb_pg_addr, fis_pg_addr, clb_pa, fis_pa;
73     for (size_t i = 0, fisp = 0, clbp = 0; i < 32;
74          i++, pmap >>= 1, fisp = (fisp + 1) % 16, clbp = (clbp + 1) % 4) {
75         if (!(pmap & 0x1)) {
76             continue;
77         }
78
79         struct ahci_port* port =
80           (struct ahci_port*)valloc(sizeof(struct ahci_port));
81         hba_reg_t* port_regs =
82           (hba_reg_t*)(&hba.base[HBA_RPBASE + i * HBA_RPSIZE]);
83
84         if (!clbp) {
85             // 每页最多4个命令队列
86             clb_pa = pmm_alloc_page(KERNEL_PID, PP_FGLOCKED);
87             clb_pg_addr = ioremap(clb_pa, 0x1000);
88             memset(clb_pg_addr, 0, 0x1000);
89         }
90         if (!fisp) {
91             // 每页最多16个FIS
92             fis_pa = pmm_alloc_page(KERNEL_PID, PP_FGLOCKED);
93             fis_pg_addr = ioremap(fis_pa, 0x1000);
94             memset(fis_pg_addr, 0, 0x1000);
95         }
96
97         /* 重定向CLB与FIS */
98         port_regs[HBA_RPxCLB] = clb_pa + clbp * HBA_CLB_SIZE;
99         port_regs[HBA_RPxFB] = fis_pa + fisp * HBA_FIS_SIZE;
100
101         *port = (struct ahci_port){ .regs = port_regs,
102                                     .ssts = port_regs[HBA_RPxSSTS],
103                                     .cmdlst = clb_pg_addr + clbp * HBA_CLB_SIZE,
104                                     .fis = fis_pg_addr + fisp * HBA_FIS_SIZE };
105
106         /* 初始化端口,并置于就绪状态 */
107         port_regs[HBA_RPxCI] = 0;
108
109         // 需要通过全部置位去清空这些寄存器(相当的奇怪……)
110         port_regs[HBA_RPxSERR] = -1;
111
112         port_regs[HBA_RPxIE] |= (HBA_PxINTR_DMA);
113         port_regs[HBA_RPxIE] |= (HBA_PxINTR_D2HR);
114
115         hba.ports[i] = port;
116
117         if (HBA_RPxSSTS_IF(port->ssts)) {
118             wait_until(!(port_regs[HBA_RPxCMD] & HBA_PxCMD_CR));
119             port_regs[HBA_RPxCMD] |= HBA_PxCMD_FRE;
120             port_regs[HBA_RPxCMD] |= HBA_PxCMD_ST;
121             if (!ahci_identify_device(port)) {
122                 kprintf(KERROR "fail to probe device info");
123             }
124         }
125     }
126 }
127
128 char sata_ifs[][20] = { "Not detected",
129                         "SATA I (1.5Gbps)",
130                         "SATA II (3.0Gbps)",
131                         "SATA III (6.0Gbps)" };
132
133 void
134 __ahci_hba_isr(isr_param param)
135 {
136     // TODO: hba interrupt
137     kprintf(KDEBUG "HBA INTR\n");
138 }
139
140 void
141 ahci_list_device()
142 {
143     kprintf(KINFO "Version: %x; Ports: %d; Slot: %d\n",
144             hba.version,
145             hba.ports_num,
146             hba.cmd_slots);
147     struct ahci_port* port;
148     for (size_t i = 0; i < 32; i++) {
149         port = hba.ports[i];
150
151         // 愚蠢的gcc似乎认为 struct ahci_port* 不可能为空
152         //  所以将这个非常关键的if给优化掉了。
153         //  这里将指针强制转换为整数,欺骗gcc :)
154         if ((uintptr_t)port == 0) {
155             continue;
156         }
157
158         int device_state = HBA_RPxSSTS_IF(port->ssts);
159
160         kprintf("\t Port %d: %s (%x)\n",
161                 i,
162                 &sata_ifs[device_state],
163                 port->regs[HBA_RPxSIG]);
164
165         struct ahci_device_info* dev_info = port->device_info;
166         if (!device_state || !dev_info) {
167             continue;
168         }
169
170         kprintf("\t\t capacity: %d KiB\n",
171                 (dev_info->max_lba * dev_info->sector_size) >> 10);
172         kprintf("\t\t sector size: %dB\n", dev_info->sector_size);
173         kprintf("\t\t model: %s\n", &dev_info->model);
174         kprintf("\t\t serial: %s\n", &dev_info->serial_num);
175     }
176 }
177
178 int
179 achi_alloc_slot(struct ahci_port* port)
180 {
181     hba_reg_t pxsact = port->regs[HBA_RPxSACT];
182     hba_reg_t pxci = port->regs[HBA_RPxCI];
183     hba_reg_t free_bmp = pxsact | pxci;
184     uint32_t i = 0;
185     for (; i <= hba.cmd_slots && (free_bmp & 0x1); i++, free_bmp >>= 1)
186         ;
187     return i | -(i > hba.cmd_slots);
188 }
189
190 void
191 __ahci_create_fis(struct sata_reg_fis* cmd_fis,
192                   uint8_t command,
193                   uint32_t lba_lo,
194                   uint32_t lba_hi,
195                   uint16_t sector_count)
196 {
197     cmd_fis->head.type = SATA_REG_FIS_H2D;
198     cmd_fis->head.options = SATA_REG_FIS_COMMAND;
199     cmd_fis->head.status_cmd = command;
200     cmd_fis->dev = 0;
201
202     cmd_fis->lba0 = SATA_LBA_COMPONENT(lba_lo, 0);
203     cmd_fis->lba8 = SATA_LBA_COMPONENT(lba_lo, 8);
204     cmd_fis->lba16 = SATA_LBA_COMPONENT(lba_lo, 16);
205     cmd_fis->lba24 = SATA_LBA_COMPONENT(lba_lo, 24);
206
207     cmd_fis->lba32 = SATA_LBA_COMPONENT(lba_hi, 0);
208     cmd_fis->lba40 = SATA_LBA_COMPONENT(lba_hi, 8);
209
210     cmd_fis->count = sector_count;
211 }
212
213 int
214 ahci_identify_device(struct ahci_port* port)
215 {
216     int slot = achi_alloc_slot(port);
217     assert_msg(slot >= 0, "No free slot");
218
219     // 清空任何待响应的中断
220     port->regs[HBA_RPxIS] = 0;
221
222     /* 发送ATA命令,参考:SATA AHCI Spec Rev.1.3.1, section 5.5 */
223
224     // 构建命令头(Command Header)和命令表(Command Table)
225     struct ahci_hba_cmdh* cmd_header = &port->cmdlst[slot];
226     struct ahci_hba_cmdt* cmd_table = valloc_dma(sizeof(struct ahci_hba_cmdt));
227
228     memset(cmd_header, 0, sizeof(*cmd_header));
229     memset(cmd_table, 0, sizeof(*cmd_table));
230
231     // 预备DMA接收缓存,用于存放HBA传回的数据
232     uint16_t* data_in = (uint16_t*)valloc_dma(512);
233
234     cmd_table->entries[0] =
235       (struct ahci_hba_prdte){ .data_base = vmm_v2p(data_in),
236                                .byte_count = 511 }; // byte_count是从0开始算的
237
238     // 在命令表中构建命令FIS
239     struct sata_reg_fis* cmd_fis = (struct sata_reg_fis*)cmd_table->command_fis;
240
241     // 根据设备类型使用合适的命令
242     if (port->regs[HBA_RPxSIG] == HBA_DEV_SIG_ATA) {
243         // ATA 一般为硬盘
244         __ahci_create_fis(cmd_fis, ATA_IDENTIFY_DEVICE, 0, 0, 0);
245     } else {
246         // ATAPI 一般为光驱,软驱,或者磁带机
247         __ahci_create_fis(cmd_fis, ATA_IDENTIFY_PAKCET_DEVICE, 0, 0, 0);
248     }
249
250     // 将命令表挂到命令头上
251     cmd_header->cmd_table_base = vmm_v2p(cmd_table);
252     cmd_header->prdt_len = 1;
253     cmd_header->options |=
254       HBA_CMDH_FIS_LEN(sizeof(*cmd_fis)) | HBA_CMDH_CLR_BUSY;
255
256     // PxCI寄存器置位,告诉HBA这儿有个数据需要发送到SATA端口
257     port->regs[HBA_RPxCI] = (1 << slot);
258
259     wait_until(!(port->regs[HBA_RPxCI] & (1 << slot)));
260
261     /*
262         等待数据到达内存
263         解析IDENTIFY DEVICE传回来的数据。
264           参考:
265             * ATA/ATAPI Command Set - 3 (ACS-3), Section 7.12.7
266
267         注意:ATAPI无法通过IDENTIFY PACKET DEVICE 获取容量信息。
268         这需要另外使用特殊的SCSI命令中的READ CAPACITY(16)
269         来获取,这种命令需要使用ATA的PACKET命令发出。
270           参考:
271             * ATA/ATAPI Command Set - 3 (ACS-3), Section 7.18
272             * SATA AHCI HBA Spec, Section 5.3.7
273             * SCSI Command Reference Manual, Section 3.26
274     */
275     port->device_info = valloc(sizeof(struct ahci_device_info));
276     ahci_parse_dev_info(port->device_info, data_in);
277
278     vfree_dma(data_in);
279     vfree_dma(cmd_table);
280
281     return 1;
282 }
283
284 // TODO: Support ATAPI Device.