blob: 7fa4d59354c0e2d7f91f3138aaf05881fa9451a7 [file] [log] [blame]
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -07001/*
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
Patrick Venture9b37b092020-05-28 20:58:57 -070019extern "C"
20{
Benjamin Fairc04c2c52020-06-05 09:14:44 -070021#include <pciaccess.h>
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070022} // extern "C"
23
Benjamin Fairc04c2c52020-06-05 09:14:44 -070024#include <linux/pci_regs.h>
25
Patrick Venture24141612019-05-03 17:59:18 -070026#include <cstring>
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070027#include <optional>
28#include <vector>
29
30namespace host_tool
31{
32
33std::vector<PciDevice>
34 PciUtilImpl::getPciDevices(std::optional<PciFilter> filter)
35{
Benjamin Fairc04c2c52020-06-05 09:14:44 -070036 struct pci_id_match match = {PCI_MATCH_ANY, PCI_MATCH_ANY, PCI_MATCH_ANY,
37 PCI_MATCH_ANY};
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070038 std::vector<PciDevice> results;
39
40 if (filter.has_value())
41 {
Benjamin Fairc04c2c52020-06-05 09:14:44 -070042 match.vendor_id = filter.value().vid;
43 match.device_id = filter.value().did;
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070044 }
45
Benjamin Fairc04c2c52020-06-05 09:14:44 -070046 auto it = pci_id_match_iterator_create(&match);
47 struct pci_device* dev;
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070048
Benjamin Fairc04c2c52020-06-05 09:14:44 -070049 while ((dev = pci_device_next(it)))
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070050 {
51 PciDevice item;
52
Benjamin Fairc04c2c52020-06-05 09:14:44 -070053 pci_device_probe(dev);
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070054
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;
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070060
Benjamin Fairc04c2c52020-06-05 09:14:44 -070061 for (int i = 0; i < PCI_STD_NUM_BARS; i++)
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070062 {
Benjamin Fairc04c2c52020-06-05 09:14:44 -070063 item.bars[i] = dev->regions[i].base_addr;
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070064 }
Benjamin Fairc04c2c52020-06-05 09:14:44 -070065
66 results.push_back(item);
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070067 }
68
Benjamin Fairc04c2c52020-06-05 09:14:44 -070069 pci_iterator_destroy(it);
Patrick Ventureb5bf0fc2019-05-03 14:33:49 -070070 return results;
71}
72
73} // namespace host_tool