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