1 /* 2 * Copyright 2019 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "pci.hpp" 18 19 extern "C" 20 { 21 #include <pciaccess.h> 22 } // extern "C" 23 24 #include <linux/pci_regs.h> 25 26 #include <cstring> 27 #include <optional> 28 #include <vector> 29 30 namespace host_tool 31 { 32 33 std::vector<PciDevice> 34 PciUtilImpl::getPciDevices(std::optional<PciFilter> filter) 35 { 36 struct pci_id_match match = {PCI_MATCH_ANY, PCI_MATCH_ANY, PCI_MATCH_ANY, 37 PCI_MATCH_ANY}; 38 std::vector<PciDevice> results; 39 40 if (filter.has_value()) 41 { 42 match.vendor_id = filter.value().vid; 43 match.device_id = filter.value().did; 44 } 45 46 auto it = pci_id_match_iterator_create(&match); 47 struct pci_device* dev; 48 49 while ((dev = pci_device_next(it))) 50 { 51 PciDevice item; 52 53 pci_device_probe(dev); 54 55 item.bus = dev->bus; 56 item.dev = dev->dev; 57 item.func = dev->func; 58 item.vid = dev->vendor_id; 59 item.did = dev->device_id; 60 61 for (int i = 0; i < PCI_STD_NUM_BARS; i++) 62 { 63 item.bars[i] = dev->regions[i].base_addr; 64 } 65 66 results.push_back(item); 67 } 68 69 pci_iterator_destroy(it); 70 return results; 71 } 72 73 } // namespace host_tool 74