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