File: pci_path.cpp

package info (click to toggle)
intel-compute-runtime 25.44.36015.8-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 79,632 kB
  • sloc: cpp: 931,547; lisp: 2,074; sh: 719; makefile: 162; python: 21
file content (89 lines) | stat: -rw-r--r-- 2,271 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 * Copyright (C) 2021-2024 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 */

#include "shared/source/os_interface/linux/pci_path.h"

#include "shared/source/os_interface/linux/sys_calls.h"

#include <cstdint>
#include <string_view>
#include <unistd.h>

namespace NEO {
std::optional<std::string> getPciLinkPath(int deviceFd) {
    char path[256] = {0};
    size_t pathlen = 256;

    if (SysCalls::getDevicePath(deviceFd, path, pathlen)) {
        return std::nullopt;
    }

    if (SysCalls::access(path, F_OK)) {
        return std::nullopt;
    }

    int readLinkSize = 0;
    char devicePath[256] = {0};
    size_t devicePathLength = 256;
    readLinkSize = SysCalls::readlink(path, devicePath, devicePathLength);

    if (readLinkSize == -1) {
        return std::nullopt;
    }

    return std::string(devicePath, static_cast<size_t>(readLinkSize));
}

std::optional<std::string> getPciPath(int deviceFd) {

    auto deviceLinkPath = NEO::getPciLinkPath(deviceFd);

    if (deviceLinkPath == std::nullopt) {
        return std::nullopt;
    }

    auto pciPathPos = deviceLinkPath->find("/drm/render");

    if (pciPathPos == std::string::npos) {
        pciPathPos = deviceLinkPath->find("/drm/card");
    }

    if (pciPathPos == std::string::npos || pciPathPos < 12) {
        return std::nullopt;
    }

    return deviceLinkPath->substr(pciPathPos - 12u, 12u);
}

std::optional<std::string> getPciRootPath(int deviceFd) {

    auto pciLinkPath = NEO::getPciLinkPath(deviceFd);
    // pciLinkPath = "../../devices/pci0000:37/0000:37:01.0/0000:38:00.0/0000:39:01.0/0000:3a:00.0/drm/renderD128/",
    // Then root path = "/pci0000:37/0000:37:01.0/0000:38:00.0/"
    if (pciLinkPath == std::nullopt) {
        return std::nullopt;
    }

    auto startPos = pciLinkPath->find("/pci");
    if (startPos == std::string::npos) {
        return std::nullopt;
    }

    // Root PCI path is at 2 levels up from drm/renderD128
    uint32_t rootPciDepth = 4;
    auto endPos = std::string::npos;
    while (rootPciDepth--) {
        endPos = pciLinkPath->rfind('/', endPos - 1);
        if (endPos == std::string::npos) {
            return std::nullopt;
        }
    }

    return pciLinkPath->substr(startPos, endPos - startPos);
}

} // namespace NEO