feat: asynchronized SATA IO
[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/hba.h>
13 #include <hal/ahci/sata.h>
14 #include <hal/ahci/scsi.h>
15
16 #include <hal/pci.h>
17 #include <klibc/string.h>
18 #include <lunaix/block.h>
19 #include <lunaix/isrm.h>
20 #include <lunaix/mm/mmio.h>
21 #include <lunaix/mm/pmm.h>
22 #include <lunaix/mm/valloc.h>
23 #include <lunaix/mm/vmm.h>
24 #include <lunaix/spike.h>
25 #include <lunaix/syslog.h>
26
27 #define HBA_FIS_SIZE 256
28 #define HBA_CLB_SIZE 1024
29
30 // #define DO_HBA_FULL_RESET
31
32 LOG_MODULE("AHCI")
33
34 struct ahci_hba hba;
35
36 static char sata_ifs[][20] = { "Not detected",
37                                "SATA I (1.5Gbps)",
38                                "SATA II (3.0Gbps)",
39                                "SATA III (6.0Gbps)" };
40
41 extern void
42 ahci_fsexport(struct block_dev* bdev, void* fs_node);
43
44 extern void
45 __ahci_hba_isr(const isr_param* param);
46
47 extern void
48 __ahci_blkio_handler(struct blkio_req* req);
49
50 int
51 ahci_init_device(struct hba_port* port);
52
53 void
54 achi_register_ops(struct hba_port* port);
55
56 void
57 ahci_register_device(struct hba_device* hbadev);
58
59 unsigned int
60 ahci_get_port_usage()
61 {
62     return hba.ports_bmp;
63 }
64
65 struct hba_port*
66 ahci_get_port(unsigned int index)
67 {
68     if (index >= 32) {
69         return 0;
70     }
71     return hba.ports[index];
72 }
73
74 void
75 __hba_reset_port(hba_reg_t* port_reg)
76 {
77     // 根据:SATA-AHCI spec section 10.4.2 描述的端口重置流程
78     port_reg[HBA_RPxCMD] &= ~HBA_PxCMD_ST;
79     port_reg[HBA_RPxCMD] &= ~HBA_PxCMD_FRE;
80     int cnt = wait_until_expire(!(port_reg[HBA_RPxCMD] & HBA_PxCMD_CR), 500000);
81     if (cnt) {
82         return;
83     }
84     // 如果port未响应,则继续执行重置
85     port_reg[HBA_RPxSCTL] = (port_reg[HBA_RPxSCTL] & ~0xf) | 1;
86     io_delay(100000); //等待至少一毫秒,差不多就行了
87     port_reg[HBA_RPxSCTL] &= ~0xf;
88 }
89
90 void
91 ahci_init()
92 {
93     struct pci_device* ahci_dev = pci_get_device_by_class(AHCI_HBA_CLASS);
94     assert_msg(ahci_dev, "AHCI: Not found.");
95
96     struct pci_base_addr* bar6 = &ahci_dev->bar[5];
97     assert_msg(bar6->type & BAR_TYPE_MMIO, "AHCI: BAR#6 is not MMIO.");
98
99     pci_reg_t cmd = pci_read_cspace(ahci_dev->cspace_base, PCI_REG_STATUS_CMD);
100
101     // 禁用传统中断(因为我们使用MSI),启用MMIO访问,允许PCI设备间访问
102     cmd |= (PCI_RCMD_MM_ACCESS | PCI_RCMD_DISABLE_INTR | PCI_RCMD_BUS_MASTER);
103
104     pci_write_cspace(ahci_dev->cspace_base, PCI_REG_STATUS_CMD, cmd);
105
106     pci_setup_msi(ahci_dev, isrm_ivexalloc(__ahci_hba_isr));
107
108     memset(&hba, 0, sizeof(hba));
109
110     hba.base = (hba_reg_t*)ioremap(bar6->start, bar6->size);
111
112 #ifdef DO_HBA_FULL_RESET
113     // 重置HBA
114     hba.base[HBA_RGHC] |= HBA_RGHC_RESET;
115     wait_until(!(hba.base[HBA_RGHC] & HBA_RGHC_RESET));
116 #endif
117
118     // 启用AHCI工作模式,启用中断
119     hba.base[HBA_RGHC] |= HBA_RGHC_ACHI_ENABLE;
120     hba.base[HBA_RGHC] |= HBA_RGHC_INTR_ENABLE;
121
122     // As per section 3.1.1, this is 0 based value.
123     hba_reg_t cap = hba.base[HBA_RCAP];
124     hba_reg_t pmap = hba.base[HBA_RPI];
125
126     hba.ports_num = (cap & 0x1f) + 1;  // CAP.PI
127     hba.cmd_slots = (cap >> 8) & 0x1f; // CAP.NCS
128     hba.version = hba.base[HBA_RVER];
129     hba.ports_bmp = pmap;
130
131     /* ------ HBA端口配置 ------ */
132     uintptr_t clb_pg_addr, fis_pg_addr, clb_pa, fis_pa;
133     for (size_t i = 0, fisp = 0, clbp = 0; i < 32;
134          i++, pmap >>= 1, fisp = (fisp + 1) % 16, clbp = (clbp + 1) % 4) {
135         if (!(pmap & 0x1)) {
136             continue;
137         }
138
139         struct hba_port* port =
140           (struct hba_port*)valloc(sizeof(struct hba_port));
141         hba_reg_t* port_regs =
142           (hba_reg_t*)(&hba.base[HBA_RPBASE + i * HBA_RPSIZE]);
143
144 #ifndef DO_HBA_FULL_RESET
145         __hba_reset_port(port_regs);
146 #endif
147
148         if (!clbp) {
149             // 每页最多4个命令队列
150             clb_pa = pmm_alloc_page(KERNEL_PID, PP_FGLOCKED);
151             clb_pg_addr = ioremap(clb_pa, 0x1000);
152             memset(clb_pg_addr, 0, 0x1000);
153         }
154         if (!fisp) {
155             // 每页最多16个FIS
156             fis_pa = pmm_alloc_page(KERNEL_PID, PP_FGLOCKED);
157             fis_pg_addr = ioremap(fis_pa, 0x1000);
158             memset(fis_pg_addr, 0, 0x1000);
159         }
160
161         /* 重定向CLB与FIS */
162         port_regs[HBA_RPxCLB] = clb_pa + clbp * HBA_CLB_SIZE;
163         port_regs[HBA_RPxFB] = fis_pa + fisp * HBA_FIS_SIZE;
164
165         *port = (struct hba_port){ .regs = port_regs,
166                                    .ssts = port_regs[HBA_RPxSSTS],
167                                    .cmdlst = clb_pg_addr + clbp * HBA_CLB_SIZE,
168                                    .fis = fis_pg_addr + fisp * HBA_FIS_SIZE };
169
170         /* 初始化端口,并置于就绪状态 */
171         port_regs[HBA_RPxCI] = 0;
172
173         hba_clear_reg(port_regs[HBA_RPxSERR]);
174
175         hba.ports[i] = port;
176
177         if (!HBA_RPxSSTS_IF(port->ssts)) {
178             continue;
179         }
180
181         wait_until(!(port_regs[HBA_RPxCMD] & HBA_PxCMD_CR));
182         port_regs[HBA_RPxCMD] |= HBA_PxCMD_FRE;
183         port_regs[HBA_RPxCMD] |= HBA_PxCMD_ST;
184
185         if (!ahci_init_device(port)) {
186             kprintf(KERROR "init fail: 0x%x@p%d\n", port->regs[HBA_RPxSIG], i);
187             continue;
188         }
189
190         struct hba_device* hbadev = port->device;
191         kprintf(KINFO "sata%d: %s, sector_size=%dB, sector=%d\n",
192                 i,
193                 hbadev->model,
194                 hbadev->block_size,
195                 (uint32_t)hbadev->max_lba);
196
197         ahci_register_device(hbadev);
198     }
199 }
200
201 void
202 ahci_register_device(struct hba_device* hbadev)
203 {
204     struct block_dev* bdev =
205       block_alloc_dev(hbadev->model, hbadev, __ahci_blkio_handler);
206
207     bdev->end_lba = hbadev->max_lba;
208     bdev->blk_size = hbadev->block_size;
209
210     block_mount(bdev, ahci_fsexport);
211 }
212
213 void
214 ahci_list_device()
215 {
216     kprintf(KINFO "Version: %x; Ports: %d; Slot: %d\n",
217             hba.version,
218             hba.ports_num,
219             hba.cmd_slots);
220     struct hba_port* port;
221     for (size_t i = 0; i < 32; i++) {
222         port = hba.ports[i];
223
224         // 愚蠢的gcc似乎认为 struct hba_port* 不可能为空
225         //  所以将这个非常关键的if给优化掉了。
226         //  这里将指针强制转换为整数,欺骗gcc :)
227         if ((uintptr_t)port == 0) {
228             continue;
229         }
230
231         int device_state = HBA_RPxSSTS_IF(port->ssts);
232
233         kprintf("\t Port %d: %s (%x)\n",
234                 i,
235                 &sata_ifs[device_state],
236                 port->device->flags);
237
238         struct hba_device* dev_info = port->device;
239         if (!device_state || !dev_info) {
240             continue;
241         }
242         kprintf("\t\t capacity: %d KiB\n",
243                 (dev_info->max_lba * dev_info->block_size) >> 10);
244         kprintf("\t\t block size: %dB\n", dev_info->block_size);
245         kprintf("\t\t block/sector: %d\n", dev_info->block_per_sec);
246         kprintf("\t\t alignment: %dB\n", dev_info->alignment_offset);
247         kprintf("\t\t capabilities: %x\n", dev_info->capabilities);
248         kprintf("\t\t model: %s\n", &dev_info->model);
249         kprintf("\t\t serial: %s\n", &dev_info->serial_num);
250     }
251 }
252
253 int
254 __get_free_slot(struct hba_port* port)
255 {
256     hba_reg_t pxsact = port->regs[HBA_RPxSACT];
257     hba_reg_t pxci = port->regs[HBA_RPxCI];
258     hba_reg_t free_bmp = pxsact | pxci;
259     uint32_t i = 0;
260     for (; i <= hba.cmd_slots && (free_bmp & 0x1); i++, free_bmp >>= 1)
261         ;
262     return i | -(i > hba.cmd_slots);
263 }
264
265 void
266 sata_create_fis(struct sata_reg_fis* cmd_fis,
267                 uint8_t command,
268                 uint64_t lba,
269                 uint16_t sector_count)
270 {
271     cmd_fis->head.type = SATA_REG_FIS_H2D;
272     cmd_fis->head.options = SATA_REG_FIS_COMMAND;
273     cmd_fis->head.status_cmd = command;
274     cmd_fis->dev = 0;
275
276     cmd_fis->lba0 = SATA_LBA_COMPONENT(lba, 0);
277     cmd_fis->lba8 = SATA_LBA_COMPONENT(lba, 8);
278     cmd_fis->lba16 = SATA_LBA_COMPONENT(lba, 16);
279     cmd_fis->lba24 = SATA_LBA_COMPONENT(lba, 24);
280
281     cmd_fis->lba32 = SATA_LBA_COMPONENT(lba, 32);
282     cmd_fis->lba40 = SATA_LBA_COMPONENT(lba, 40);
283
284     cmd_fis->count = sector_count;
285 }
286
287 int
288 hba_bind_sbuf(struct hba_cmdh* cmdh, struct hba_cmdt* cmdt, struct membuf mbuf)
289 {
290     assert_msg(mbuf.buffer <= 0x400000, "HBA: Buffer too big");
291     cmdh->prdt_len = 1;
292     cmdt->entries[0] = (struct hba_prdte){ .data_base = vmm_v2p(mbuf.buffer),
293                                            .byte_count = mbuf.size - 1 };
294 }
295
296 int
297 hba_bind_vbuf(struct hba_cmdh* cmdh, struct hba_cmdt* cmdt, struct vecbuf* vbuf)
298 {
299     size_t i = 0;
300     struct vecbuf *pos, *n;
301
302     llist_for_each(pos, n, &vbuf->components, components)
303     {
304         assert_msg(i < HBA_MAX_PRDTE, "HBA: Too many PRDTEs");
305         assert_msg(pos->buf.buffer <= 0x400000, "HBA: Buffer too big");
306
307         cmdt->entries[i++] =
308           (struct hba_prdte){ .data_base = vmm_v2p(pos->buf.buffer),
309                               .byte_count = pos->buf.size - 1 };
310     }
311
312     cmdh->prdt_len = i + 1;
313 }
314
315 int
316 hba_prepare_cmd(struct hba_port* port,
317                 struct hba_cmdt** cmdt,
318                 struct hba_cmdh** cmdh)
319 {
320     int slot = __get_free_slot(port);
321     assert_msg(slot >= 0, "HBA: No free slot");
322
323     // 构建命令头(Command Header)和命令表(Command Table)
324     struct hba_cmdh* cmd_header = &port->cmdlst[slot];
325     struct hba_cmdt* cmd_table = vzalloc_dma(sizeof(struct hba_cmdt));
326
327     memset(cmd_header, 0, sizeof(*cmd_header));
328
329     // 将命令表挂到命令头上
330     cmd_header->cmd_table_base = vmm_v2p(cmd_table);
331     cmd_header->options =
332       HBA_CMDH_FIS_LEN(sizeof(struct sata_reg_fis)) | HBA_CMDH_CLR_BUSY;
333
334     *cmdh = cmd_header;
335     *cmdt = cmd_table;
336
337     return slot;
338 }
339
340 int
341 ahci_init_device(struct hba_port* port)
342 {
343     /* 发送ATA命令,参考:SATA AHCI Spec Rev.1.3.1, section 5.5 */
344     struct hba_cmdt* cmd_table;
345     struct hba_cmdh* cmd_header;
346
347     // mask DHR interrupt
348     port->regs[HBA_RPxIE] &= ~HBA_PxINTR_DHR;
349
350     // 预备DMA接收缓存,用于存放HBA传回的数据
351     uint16_t* data_in = (uint16_t*)valloc_dma(512);
352
353     int slot = hba_prepare_cmd(port, &cmd_table, &cmd_header);
354     hba_bind_sbuf(
355       cmd_header, cmd_table, (struct membuf){ .buffer = data_in, .size = 512 });
356
357     port->device = vzalloc(sizeof(struct hba_device));
358     port->device->port = port;
359
360     // 在命令表中构建命令FIS
361     struct sata_reg_fis* cmd_fis = (struct sata_reg_fis*)cmd_table->command_fis;
362
363     // 根据设备类型使用合适的命令
364     if (port->regs[HBA_RPxSIG] == HBA_DEV_SIG_ATA) {
365         // ATA 一般为硬盘
366         sata_create_fis(cmd_fis, ATA_IDENTIFY_DEVICE, 0, 0);
367     } else {
368         // ATAPI 一般为光驱,软驱,或者磁带机
369         port->device->flags |= HBA_DEV_FATAPI;
370         sata_create_fis(cmd_fis, ATA_IDENTIFY_PAKCET_DEVICE, 0, 0);
371     }
372
373     if (!ahci_try_send(port, slot)) {
374         goto fail;
375     }
376
377     /*
378         等待数据到达内存
379         解析IDENTIFY DEVICE传回来的数据。
380           参考:
381             * ATA/ATAPI Command Set - 3 (ACS-3), Section 7.12.7
382     */
383     ahci_parse_dev_info(port->device, data_in);
384
385     if (!(port->device->flags & HBA_DEV_FATAPI)) {
386         goto done;
387     }
388
389     /*
390         注意:ATAPI设备是无法通过IDENTIFY PACKET DEVICE 获取容量信息的。
391         我们需要使用SCSI命令的READ_CAPACITY(16)进行获取。
392         步骤如下:
393             1. 因为ATAPI走的是SCSI,而AHCI对此专门进行了SATA的封装,
394                也就是通过SATA的PACKET命令对SCSI命令进行封装。所以我们
395                首先需要构建一个PACKET命令的FIS
396             2. 接着,在ACMD中构建命令READ_CAPACITY的CDB - 一种SCSI命令的封装
397             3. 然后把cmd_header->options的A位置位,表示这是一个送往ATAPI的命令。
398                 一点细节:
399                     1. HBA往底层SATA控制器发送PACKET FIS
400                     2. SATA控制器回复PIO Setup FIS
401                     3. HBA读入ACMD中的CDB,打包成Data FIS进行答复
402                     4. SATA控制器解包,拿到CDB,通过SCSI协议转发往ATAPI设备。
403                     5. ATAPI设备回复Return Parameter,SATA通过DMA Setup FIS
404                        发起DMA请求,HBA介入,将Return Parameter写入我们在PRDT
405                        里设置的data_in位置。
406             4. 最后照常等待HBA把结果写入data_in,然后直接解析就好了。
407           参考:
408             * ATA/ATAPI Command Set - 3 (ACS-3), Section 7.18
409             * SATA AHCI HBA Spec, Section 5.3.7
410             * SCSI Command Reference Manual, Section 3.26
411     */
412
413     sata_create_fis(cmd_fis, ATA_PACKET, 512 << 8, 0);
414
415     // for dev use 12 bytes cdb, READ_CAPACITY must use the 10 bytes variation.
416     if (port->device->cbd_size == SCSI_CDB12) {
417         struct scsi_cdb12* cdb12 = (struct scsi_cdb12*)cmd_table->atapi_cmd;
418         // ugly tricks to construct 10 byte cdb from 12 byte cdb
419         scsi_create_packet12(cdb12, SCSI_READ_CAPACITY_10, 0, 512 << 8);
420     } else {
421         struct scsi_cdb16* cdb16 = (struct scsi_cdb16*)cmd_table->atapi_cmd;
422         scsi_create_packet16(cdb16, SCSI_READ_CAPACITY_16, 0, 512);
423         cdb16->misc1 = 0x10; // service action
424     }
425
426     cmd_header->transferred_size = 0;
427     cmd_header->options |= HBA_CMDH_ATAPI;
428
429     if (!ahci_try_send(port, slot)) {
430         goto fail;
431     }
432
433     scsi_parse_capacity(port->device, (uint32_t*)data_in);
434
435 done:
436     // reset interrupt status and unmask D2HR interrupt
437     port->regs[HBA_RPxIE] |= HBA_PxINTR_DHR;
438     achi_register_ops(port);
439
440     vfree_dma(data_in);
441     vfree_dma(cmd_table);
442
443     return 1;
444
445 fail:
446     port->regs[HBA_RPxIE] |= HBA_PxINTR_DHR;
447     vfree_dma(data_in);
448     vfree_dma(cmd_table);
449
450     return 0;
451 }
452
453 int
454 ahci_identify_device(struct hba_device* device)
455 {
456     // 用于重新识别设备(比如在热插拔的情况下)
457     vfree(device);
458     return ahci_init_device(device->port);
459 }
460
461 void
462 achi_register_ops(struct hba_port* port)
463 {
464     port->device->ops.identify = ahci_identify_device;
465     if (!(port->device->flags & HBA_DEV_FATAPI)) {
466         port->device->ops.submit = sata_submit;
467     } else {
468         port->device->ops.submit = scsi_submit;
469     }
470 }