feat: probe more device info
[lunaix-os.git] / lunaix-os / hal / ahci / ata.c
index ea2e5f34a4e98b95dec4af2fa46196323140edd8..486d69d7c76ac7a551c125f96c0da4e68b10b845 100644 (file)
@@ -2,6 +2,7 @@
 #include <hal/ahci/sata.h>
 
 #include <lunaix/mm/valloc.h>
+#include <lunaix/mm/vmm.h>
 #include <lunaix/spike.h>
 
 int
@@ -19,23 +20,18 @@ __sata_buffer_io(struct hba_port* port,
     int bitmask = 1 << slot;
 
     // 确保端口是空闲的
-    wait_until(!(port->regs[HBA_RPxTFD] & (HBA_PxTFD_BSY)));
+    wait_until(!(port->regs[HBA_RPxTFD] & (HBA_PxTFD_BSY | HBA_PxTFD_DRQ)));
 
     port->regs[HBA_RPxIS] = 0;
 
-    table->entries[0] =
-      (struct hba_prdte){ .byte_count = size - 1, .data_base = buffer };
+    table->entries[0] = (struct hba_prdte){ .byte_count = size - 1,
+                                            .data_base = vmm_v2p(buffer) };
     header->prdt_len = 1;
     header->options |= HBA_CMDH_WRITE * (write == 1);
 
-    uint16_t count = size / port->device->block_size;
-    if (count == 0 && size < port->device->block_size) {
-        // 一个special case: 当count=0的时候,表示的是65536个区块会被传输
-        // 如果这个0是因为不够除而导致的,那么说明size太小了
-        goto fail;
-    }
-
+    uint16_t count = ICEIL(size, port->device->block_size);
     struct sata_reg_fis* fis = table->command_fis;
+
     if ((port->device->flags & HBA_DEV_FEXTLBA)) {
         // 如果该设备支持48位LBA寻址
         sata_create_fis(
@@ -43,20 +39,34 @@ __sata_buffer_io(struct hba_port* port,
     } else {
         sata_create_fis(fis, write ? ATA_WRITE_DMA : ATA_READ_DMA, lba, count);
     }
-
-    port->regs[HBA_RPxCI] = bitmask;
-
-    wait_until(!(port->regs[HBA_RPxCI] & bitmask));
-
-    if ((port->regs[HBA_RPxTFD] & HBA_PxTFD_ERR)) {
-        // 有错误
-        sata_read_error(port);
-        goto fail;
+    /*
+          确保我们使用的是LBA寻址模式
+          注意:在ACS-3中(甚至在ACS-4),只有在(READ/WRITE)_DMA_EXT指令中明确注明了需要将这一位置位
+        而并没有在(READ/WRITE)_DMA注明。
+          但是这在ACS-2中是有的!于是这也就导致了先前的测试中,LBA=0根本无法访问,因为此时
+        的访问模式是在CHS下,也就是说LBA=0 => Sector=0,是非法的。
+          所以,我猜测,这要么是QEMU/VirtualBox根据ACS-2来编写的AHCI模拟,
+        要么是标准出错了(毕竟是working draft)
+    */
+    fis->dev = (1 << 6);
+
+    int retries = 0;
+
+    while (retries < MAX_RETRY) {
+        port->regs[HBA_RPxCI] = bitmask;
+
+        wait_until(!(port->regs[HBA_RPxCI] & bitmask));
+
+        if ((port->regs[HBA_RPxTFD] & HBA_PxTFD_ERR)) {
+            // 有错误
+            sata_read_error(port);
+            retries++;
+        } else {
+            vfree_dma(table);
+            return 1;
+        }
     }
 
-    vfree_dma(table);
-    return 1;
-
 fail:
     vfree_dma(table);
     return 0;