1 #include <hal/ahci/hba.h>
2 #include <hal/ahci/sata.h>
3 #include <hal/ahci/scsi.h>
4 #include <hal/ahci/utils.h>
6 #include <klibc/string.h>
7 #include <lunaix/mm/valloc.h>
8 #include <lunaix/mm/vmm.h>
9 #include <lunaix/spike.h>
10 #include <lunaix/syslog.h>
13 scsi_create_packet12(struct scsi_cdb12* cdb,
18 memset(cdb, 0, sizeof(*cdb));
20 cdb->lba_be = SCSI_FLIP(lba);
21 cdb->length = SCSI_FLIP(alloc_size);
25 scsi_create_packet16(struct scsi_cdb16* cdb,
30 memset(cdb, 0, sizeof(*cdb));
32 cdb->lba_be_hi = SCSI_FLIP((uint32_t)(lba >> 32));
33 cdb->lba_be_lo = SCSI_FLIP((uint32_t)lba);
34 cdb->length = SCSI_FLIP(alloc_size);
38 scsi_parse_capacity(struct hba_device* device, uint32_t* parameter)
40 if (device->cbd_size == SCSI_CDB16) {
42 SCSI_FLIP(*(parameter + 1)) | (SCSI_FLIP(*parameter) << 32);
43 device->block_size = SCSI_FLIP(*(parameter + 2));
45 // for READ_CAPACITY(10)
46 device->max_lba = SCSI_FLIP(*(parameter));
47 device->block_size = SCSI_FLIP(*(parameter + 1));
52 __scsi_buffer_io(struct hba_device* dev,
58 assert_msg(((uintptr_t)buffer & 0x3) == 0, "HBA: Bad buffer alignment");
60 struct hba_port* port = dev->port;
61 struct hba_cmdh* header;
62 struct hba_cmdt* table;
63 int slot = hba_prepare_cmd(port, &table, &header, buffer, size);
64 int bitmask = 1 << slot;
67 wait_until(!(port->regs[HBA_RPxTFD] & (HBA_PxTFD_BSY | HBA_PxTFD_DRQ)));
69 port->regs[HBA_RPxIS] = 0;
71 header->options |= (HBA_CMDH_WRITE * (write == 1)) | HBA_CMDH_ATAPI;
73 uint32_t count = ICEIL(size, port->device->block_size);
75 struct sata_reg_fis* fis = (struct sata_reg_fis*)table->command_fis;
76 void* cdb = table->atapi_cmd;
77 sata_create_fis(fis, ATA_PACKET, (size << 8), 0);
78 fis->feature = 1 | ((!write) << 2);
80 if (port->device->cbd_size == 16) {
81 scsi_create_packet16((struct scsi_cdb16*)cdb,
82 write ? SCSI_WRITE_BLOCKS_16 : SCSI_READ_BLOCKS_16,
86 scsi_create_packet12((struct scsi_cdb12*)cdb,
87 write ? SCSI_WRITE_BLOCKS_12 : SCSI_READ_BLOCKS_12,
93 *((uint8_t*)cdb + 1) = 3 << 5; // RPROTECT=011b 禁用保护检查
97 while (retries < MAX_RETRY) {
98 port->regs[HBA_RPxCI] = bitmask;
100 wait_until_expire(!(port->regs[HBA_RPxCI] & bitmask), 1000000);
102 if ((port->regs[HBA_RPxTFD] & HBA_PxTFD_ERR)) {
104 sata_read_error(port);
118 scsi_read_buffer(struct hba_device* dev,
123 return __scsi_buffer_io(dev, lba, buffer, size, 0);
127 scsi_write_buffer(struct hba_device* dev,
132 return __scsi_buffer_io(dev, lba, buffer, size, 1);