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/spike.h>
10 scsi_create_packet12(struct scsi_cdb12* cdb,
15 memset(cdb, 0, sizeof(*cdb));
17 cdb->lba_be = SCSI_FLIP(lba);
18 cdb->length = alloc_size;
22 scsi_create_packet16(struct scsi_cdb16* cdb,
27 memset(cdb, 0, sizeof(*cdb));
29 cdb->lba_be_hi = SCSI_FLIP(lba >> 32);
30 cdb->lba_be_lo = SCSI_FLIP((uint32_t)lba);
31 cdb->length = alloc_size;
35 scsi_parse_capacity(struct hba_device* device, uint32_t* parameter)
37 device->max_lba = SCSI_FLIP(*(parameter + 1));
38 device->block_size = SCSI_FLIP(*(parameter + 2));
42 __scsi_buffer_io(struct hba_port* port,
48 assert_msg(((uintptr_t)buffer & 0x3) == 0, "HBA: Bad buffer alignment");
50 struct hba_cmdh* header;
51 struct hba_cmdt* table;
52 int slot = hba_alloc_slot(port, &table, &header, 0);
53 int bitmask = 1 << slot;
56 wait_until(!(port->regs[HBA_RPxTFD] & (HBA_PxTFD_BSY)));
58 port->regs[HBA_RPxIS] = 0;
61 (struct hba_prdte){ .byte_count = size - 1, .data_base = buffer };
63 header->options |= (HBA_CMDH_WRITE * (write == 1)) | HBA_CMDH_ATAPI;
65 uint32_t count = size / port->device->block_size;
67 // 对ATAPI设备来说,READ/WRITE (16/12) 没有这个count=0的 special case
68 // 但是对于READ/WRITE (6),就存在这个special case
72 struct sata_reg_fis* fis = table->command_fis;
73 void* cdb = table->atapi_cmd;
74 sata_create_fis(fis, ATA_PACKET, (size << 8) & 0xffffff, 0);
76 if (port->device->cbd_size == 16) {
77 scsi_create_packet16((struct scsi_cdb16*)cdb,
78 write ? SCSI_WRITE_BLOCKS_16 : SCSI_READ_BLOCKS_16,
82 scsi_create_packet12((struct scsi_cdb12*)cdb,
83 write ? SCSI_WRITE_BLOCKS_12 : SCSI_READ_BLOCKS_12,
88 port->regs[HBA_RPxCI] = bitmask;
90 wait_until(!(port->regs[HBA_RPxCI] & bitmask));
92 if ((port->regs[HBA_RPxTFD] & HBA_PxTFD_ERR)) {
94 sata_read_error(port);
107 scsi_read_buffer(struct hba_port* port,
112 __scsi_buffer_io(port, lba, buffer, size, 0);
116 scsi_write_buffer(struct hba_port* port,
121 __scsi_buffer_io(port, lba, buffer, size, 1);