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