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