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