96d163b93585ed8a0f7a273e25506f07a4d2b631
[lunaix-os.git] / lunaix-os / hal / ahci / utils.c
1 #include <hal/ahci/ahci.h>
2 #include <hal/ahci/hba.h>
3 #include <hal/ahci/sata.h>
4 #include <hal/ahci/scsi.h>
5 #include <klibc/string.h>
6
7 #include <lunaix/spike.h>
8
9 #define IDDEV_OFFMAXLBA 60
10 #define IDDEV_OFFMAXLBA_EXT 230
11 #define IDDEV_OFFLSECSIZE 117
12 #define IDDEV_OFFWWN 108
13 #define IDDEV_OFFSERIALNUM 10
14 #define IDDEV_OFFMODELNUM 27
15 #define IDDEV_OFFADDSUPPORT 69
16 #define IDDEV_OFFALIGN 209
17 #define IDDEV_OFFLPP 106
18 #define IDDEV_OFFCAPABILITIES 49
19
20 static uint32_t cdb_size[] = { SCSI_CDB12, SCSI_CDB16, 0, 0 };
21
22 void
23 ahci_parse_dev_info(struct hba_device* dev_info, uint16_t* data)
24 {
25     dev_info->max_lba = *((uint32_t*)(data + IDDEV_OFFMAXLBA));
26     dev_info->block_size = *((uint32_t*)(data + IDDEV_OFFLSECSIZE));
27     dev_info->cbd_size = cdb_size[(*data & 0x3)];
28     dev_info->wwn = *(uint64_t*)(data + IDDEV_OFFWWN);
29     dev_info->block_per_sec = 1 << (*(data + IDDEV_OFFLPP) & 0xf);
30     dev_info->alignment_offset = *(data + IDDEV_OFFALIGN) & 0x3fff;
31     dev_info->capabilities = *((uint32_t*)(data + IDDEV_OFFCAPABILITIES));
32
33     if (!dev_info->block_size) {
34         dev_info->block_size = 512;
35     }
36
37     if ((*(data + IDDEV_OFFADDSUPPORT) & 0x8)) {
38         dev_info->max_lba = *((uint64_t*)(data + IDDEV_OFFMAXLBA_EXT));
39         dev_info->flags |= HBA_DEV_FEXTLBA;
40     }
41
42     ahci_parsestr(dev_info->serial_num, data + IDDEV_OFFSERIALNUM, 10);
43     ahci_parsestr(dev_info->model, data + IDDEV_OFFMODELNUM, 20);
44 }
45
46 void
47 ahci_parsestr(char* str, uint16_t* reg_start, int size_word)
48 {
49     int j = 0;
50     for (int i = 0; i < size_word; i++, j += 2) {
51         uint16_t reg = *(reg_start + i);
52         str[j] = (char)(reg >> 8);
53         str[j + 1] = (char)(reg & 0xff);
54     }
55     str[j - 1] = '\0';
56     strrtrim(str);
57 }
58
59 int
60 ahci_try_send(struct hba_port* port, int slot)
61 {
62     int retries = 0, bitmask = 1 << slot;
63
64     // 确保端口是空闲的
65     wait_until(!(port->regs[HBA_RPxTFD] & (HBA_PxTFD_BSY | HBA_PxTFD_DRQ)));
66
67     hba_clear_reg(port->regs[HBA_RPxIS]);
68
69     while (retries < MAX_RETRY) {
70         // PxCI寄存器置位,告诉HBA这儿有个数据需要发送到SATA端口
71         port->regs[HBA_RPxCI] = bitmask;
72
73         wait_until_expire(!(port->regs[HBA_RPxCI] & bitmask), 1000000);
74
75         port->regs[HBA_RPxCI] &= ~bitmask; // ensure CI bit is cleared
76         if ((port->regs[HBA_RPxTFD] & HBA_PxTFD_ERR)) {
77             // 有错误
78             sata_read_error(port);
79             retries++;
80         } else {
81             break;
82         }
83     }
84
85     hba_clear_reg(port->regs[HBA_RPxIS]);
86
87     return retries < MAX_RETRY;
88 }