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