You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux内核空间中,如何通过struct net_device *获取关联PCI地址?

在Linux内核中从struct net_device*获取PCI地址

要从struct net_device *指针获取对应的PCI地址,核心是通过内核设备模型的关联关系,将网络设备转换为PCI设备结构体,再提取地址信息,具体实现如下:

核心逻辑

struct net_device 包含一个 struct device 类型的成员 dev,所有PCI设备的struct device实例都可以通过内核提供的宏转换为struct pci_dev,进而提取PCI总线、设备、功能号等地址信息。

实现步骤

  1. 校验设备类型:先用dev_is_pci()宏确认当前net_device对应的是PCI设备,避免后续操作出错。
  2. 转换为PCI设备结构体:通过to_pci_dev()宏将struct device转换为struct pci_dev。
  3. 提取PCI地址字段:从struct pci_dev中读取总线号、设备号、功能号,组合成标准PCI地址格式(如00:01.0)。

代码示例

#include <linux/netdevice.h>
#include <linux/pci.h>

void get_netdev_pci_addr(struct net_device *ndev)
{
    struct pci_dev *pdev;

    // 检查输入有效性及设备类型
    if (!ndev || !dev_is_pci(&ndev->dev)) {
        pr_err("Invalid net device or non-PCI device\n");
        return;
    }

    // 转换为PCI设备结构体
    pdev = to_pci_dev(&ndev->dev);

    // 打印标准格式的PCI地址
    pr_info("PCI Address: %02x:%02x.%x\n",
            pdev->bus->number,
            PCI_SLOT(pdev->devfn),
            PCI_FUNC(pdev->devfn));

    // 若需获取BAR地址,可访问pdev->resource数组
    // 示例:pr_info("BAR 0 base address: %pa\n", &pdev->resource[0].start);
}

注意事项

  • 内核需开启PCI支持(CONFIG_PCI=y),否则相关宏和结构体无法使用。
  • 必须保证struct net_device *指针有效,避免空指针或野指针访问。
  • to_pci_dev()仅对PCI设备有效,务必先通过dev_is_pci()校验,防止内核崩溃。

内容的提问来源于stack exchange,提问作者pa5h1nh0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 14:37:39