feat: readdir fix and demo
[lunaix-os.git] / lunaix-os / hal / ahci / ata.c
1 #include <hal/ahci/hba.h>
2 #include <hal/ahci/sata.h>
3
4 #include <lunaix/mm/valloc.h>
5 #include <lunaix/mm/vmm.h>
6 #include <lunaix/spike.h>
7
8 int
9 __sata_buffer_io(struct hba_device* dev,
10                  uint64_t lba,
11                  void* buffer,
12                  uint32_t size,
13                  int write)
14 {
15     assert_msg(((uintptr_t)buffer & 0x3) == 0, "HBA: Bad buffer alignment");
16
17     struct hba_port* port = dev->port;
18     struct hba_cmdh* header;
19     struct hba_cmdt* table;
20     int slot = hba_prepare_cmd(port, &table, &header, buffer, size);
21     int bitmask = 1 << slot;
22
23     // 确保端口是空闲的
24     wait_until(!(port->regs[HBA_RPxTFD] & (HBA_PxTFD_BSY | HBA_PxTFD_DRQ)));
25
26     port->regs[HBA_RPxIS] = 0;
27
28     header->options |= HBA_CMDH_WRITE * (write == 1);
29
30     uint16_t count = ICEIL(size, port->device->block_size);
31     struct sata_reg_fis* fis = table->command_fis;
32
33     if ((port->device->flags & HBA_DEV_FEXTLBA)) {
34         // 如果该设备支持48位LBA寻址
35         sata_create_fis(
36           fis, write ? ATA_WRITE_DMA_EXT : ATA_READ_DMA_EXT, lba, count);
37     } else {
38         sata_create_fis(fis, write ? ATA_WRITE_DMA : ATA_READ_DMA, lba, count);
39     }
40     /*
41           确保我们使用的是LBA寻址模式
42           注意:在ACS-3中(甚至在ACS-4),只有在(READ/WRITE)_DMA_EXT指令中明确注明了需要将这一位置位
43         而并没有在(READ/WRITE)_DMA注明。
44           但是这在ACS-2中是有的!于是这也就导致了先前的测试中,LBA=0根本无法访问,因为此时
45         的访问模式是在CHS下,也就是说LBA=0 => Sector=0,是非法的。
46           所以,我猜测,这要么是QEMU/VirtualBox根据ACS-2来编写的AHCI模拟,
47         要么是标准出错了(毕竟是working draft)
48     */
49     fis->dev = (1 << 6);
50
51     int retries = 0;
52
53     while (retries < MAX_RETRY) {
54         port->regs[HBA_RPxCI] = bitmask;
55
56         wait_until(!(port->regs[HBA_RPxCI] & bitmask));
57
58         if ((port->regs[HBA_RPxTFD] & HBA_PxTFD_ERR)) {
59             // 有错误
60             sata_read_error(port);
61             retries++;
62         } else {
63             vfree_dma(table);
64             return 1;
65         }
66     }
67
68 fail:
69     vfree_dma(table);
70     return 0;
71 }
72
73 int
74 sata_read_buffer(struct hba_device* dev,
75                  uint64_t lba,
76                  void* buffer,
77                  uint32_t size)
78 {
79     return __sata_buffer_io(dev, lba, buffer, size, 0);
80 }
81
82 int
83 sata_write_buffer(struct hba_device* dev,
84                   uint64_t lba,
85                   void* buffer,
86                   uint32_t size)
87 {
88     return __sata_buffer_io(dev, lba, buffer, size, 1);
89 }
90
91 void
92 sata_read_error(struct hba_port* port)
93 {
94     uint32_t tfd = port->regs[HBA_RPxTFD];
95     port->device->last_error = (tfd >> 8) & 0xff;
96     port->device->last_status = tfd & 0xff;
97 }