2 #include <lunaix/mm/kalloc.h>
3 #include <lunaix/syslog.h>
7 static struct llist_header pci_devices;
10 pci_probe_msi_info(struct pci_device* device);
13 pci_probe_device(int bus, int dev, int funct)
15 uint32_t base = PCI_ADDRESS(bus, dev, funct);
16 pci_reg_t reg1 = pci_read_cspace(base, 0);
18 // Vendor=0xffff则表示设备不存在
19 if (PCI_DEV_VENDOR(reg1) == PCI_VENDOR_INVLD) {
23 pci_reg_t hdr_type = pci_read_cspace(base, 0xc);
24 hdr_type = (hdr_type >> 16) & 0xff;
26 if ((hdr_type & 0x80)) {
27 hdr_type = hdr_type & ~0x80;
28 // 探测多用途设备(multi-function device)
29 for (int i = 1; i < 7; i++) {
30 pci_probe_device(bus, dev, i);
35 // XXX: 目前忽略所有桥接设备,比如PCI-PCI桥接器,或者是CardBus桥接器
39 pci_reg_t intr = pci_read_cspace(base, 0x3c);
40 pci_reg_t class = pci_read_cspace(base, 0x8);
42 struct pci_device* device = lxmalloc(sizeof(struct pci_device));
43 *device = (struct pci_device){ .cspace_base = base,
48 pci_probe_msi_info(device);
50 llist_append(&pci_devices, &device->dev_chain);
57 // XXX: 尽管最多会有256条PCI总线,但就目前而言,只考虑bus #0就足够了
58 for (int bus = 0; bus < 1; bus++) {
59 for (int dev = 0; dev < 32; dev++) {
60 pci_probe_device(bus, dev, 0);
66 pci_probe_msi_info(struct pci_device* device)
69 pci_read_cspace(device->cspace_base, PCI_REG_STATUS_CMD) >> 16;
71 if (!(status & 0x10)) {
76 pci_reg_t cap_ptr = pci_read_cspace(device->cspace_base, 0x34) & 0xff;
80 cap_hdr = pci_read_cspace(device->cspace_base, cap_ptr);
81 if ((cap_hdr & 0xff) == 0x5) {
83 device->msi_loc = cap_ptr;
86 cap_ptr = (cap_hdr >> 8) & 0xff;
93 struct pci_device *pos, *n;
94 llist_for_each(pos, n, &pci_devices, dev_chain)
96 kprintf(KINFO "(B%xh:D%xh:F%xh) Dev %x:%x, Class 0x%x\n",
97 PCI_BUS_NUM(pos->cspace_base),
98 PCI_SLOT_NUM(pos->cspace_base),
99 PCI_FUNCT_NUM(pos->cspace_base),
100 PCI_DEV_VENDOR(pos->device_info),
101 PCI_DEV_DEVID(pos->device_info),
102 PCI_DEV_CLASS(pos->class_info));
104 kprintf(KINFO "\t IRQ: %d, INT#x: %d\n",
105 PCI_INTR_IRQ(pos->intr_info),
106 PCI_INTR_PIN(pos->intr_info));
109 kprintf(KINFO "\t MSI supported (@%xh)\n", pos->msi_loc);
115 pci_get_device_by_id(uint16_t vendorId, uint16_t deviceId)
117 uint32_t dev_info = vendorId | (deviceId << 16);
118 struct pci_device *pos, *n;
119 llist_for_each(pos, n, &pci_devices, dev_chain)
121 if (pos->device_info == dev_info) {
130 pci_get_device_by_class(uint32_t class)
132 struct pci_device *pos, *n;
133 llist_for_each(pos, n, &pci_devices, dev_chain)
135 if (PCI_DEV_CLASS(pos->class_info) == class) {
146 llist_init_head(&pci_devices);