配置硬件资源

外设组件互连 (PCI) 设备将资源公开给系统 使用各种接口,包括中断、内存映射 I/O (MMIO) 寄存器和直接内存访问 (DMA) 缓冲区。Fuchsia 司机访问这些信息 通过父设备节点中的功能来配置资源。对于 PCI 设备: 父级提供 fuchsia.hardware.pci/Device FIDL 协议的实例 使驱动程序能够配置设备。

在本部分中,您将添加访问以下 MMIO 的功能 在 edu 设备上注册:

地址偏移 注册 读写 说明
0x00 身份识别 RO 主要 / 次要版本标识符
0x04 卡活跃性检查 RW 验证操作
0x08 阶乘计算 RW 计算存储值的阶乘
0x20 状态 RW 用于指示操作已完成的位字段

完成本部分后,项目应具有以下目录 结构:

//fuchsia-codelab/qemu_edu/drivers
                  |- BUILD.bazel
                  |- meta
                  |   |- qemu_edu.cml
                  |- edu_device.cc 
                  |- edu_device.h 
                  |- qemu_edu.bind
                  |- qemu_edu.cc
                  |- qemu_edu.h

连接到家长设备

从父设备访问 fuchsia.hardware.pci/Device 接口 节点,将 fuchsia.hardware.pci.Service 功能添加到驱动程序的 组件清单:

qemu_edu/drivers/meta/qemu_edu.cml

{
    include: [
        "syslog/client.shard.cml",
    ],
    program: {
        runner: 'driver',
        binary: 'driver/libqemu_edu.so',
        bind: 'meta/bind/qemu_edu.bindbc',
        // Identifies the device categories, for compatibility tests. This
        // example driver uses the 'misc' category; real drivers should
        // select a more specific category.
        device_categories: [
          { category: 'misc', subcategory: '' },
        ],
    },
    use: [
        { service: 'fuchsia.hardware.pci.Service' },
    ],
}

这样,驾驶员就可以打开与家长设备的连接,并访问 特定硬件的协议

更新驱动程序的 Start() 方法以访问 fuchsia.hardware.pci/Device 由父设备在驱动程序初始化期间提供:

qemu_edu/drivers/qemu_edu.cc

#include "qemu_edu.h"

#include <lib/driver/component/cpp/driver_export.h>

namespace qemu_edu {
// ...

// Initialize this driver instance
zx::result<> QemuEduDriver::Start() {

  // Connect to the parent device node.
  zx::result connect_result = incoming()->Connect<fuchsia_hardware_pci::Service::Device>("default");
  if (connect_result.is_error()) {
    FDF_SLOG(ERROR, "Failed to open pci service.", KV("status", connect_result.status_string()));
    return connect_result.take_error();
  }

  FDF_SLOG(INFO, "edu driver loaded successfully");

  return zx::ok();
}

}  // namespace qemu_edu

设置中断和 MMIO

连接到fuchsia.hardware.pci/Device后,您可以开始 将必要的设备资源映射到驱动程序中。

在项目中创建新的 qemu_edu/drivers/edu_device.h 文件 目录,其中包含以下内容:

qemu_edu/drivers/edu_device.h

#ifndef FUCHSIA_CODELAB_QEMU_EDU_DEVICE_H_
#define FUCHSIA_CODELAB_QEMU_EDU_DEVICE_H_

#include <fidl/fuchsia.hardware.pci/cpp/wire.h>
#include <lib/async/cpp/irq.h>
#include <lib/mmio/mmio.h>
#include <lib/zx/interrupt.h>

namespace edu_device {

// Interacts with the device hardware using a fuchsia.hardware.pci client.
class QemuEduDevice {
 public:
  explicit QemuEduDevice(async_dispatcher_t* dispatcher,
                         fidl::ClientEnd<fuchsia_hardware_pci::Device> pci)
      : dispatcher_(dispatcher), pci_(std::move(pci)) {}

  zx::result<> MapInterruptAndMmio();

 private:
  void HandleIrq(async_dispatcher_t* dispatcher, async::IrqBase* irq, zx_status_t status,
                 const zx_packet_interrupt_t* interrupt);

  async_dispatcher_t* const dispatcher_;

  fidl::WireSyncClient<fuchsia_hardware_pci::Device> pci_;
  std::optional<fdf::MmioBuffer> mmio_;
  zx::interrupt irq_;
  async::IrqMethod<QemuEduDevice, &QemuEduDevice::HandleIrq> irq_method_{this};
  std::optional<fit::callback<void(zx::result<uint32_t>)>> pending_callback_;
};

}  // namespace edu_device

#endif  // FUCHSIA_CODELAB_QEMU_EDU_DEVICE_H_

创建新的 qemu_edu/drivers/edu_device.cc 文件并添加以下代码 来实现 MapInterruptAndMmio() 方法。 此方法执行以下任务:

  1. 访问相应 PCI 区域的基地址寄存器 (BAR)。
  2. 提取 Fuchsia 的 VMO(虚拟内存对象) 区域。
  3. 在区域周围创建一个 MMIO 缓冲区以访问各个寄存器。
  4. 配置映射到设备中断的中断请求 (IRQ)。

qemu_edu/drivers/edu_device.cc

#include "edu_device.h"

#include <lib/driver/logging/cpp/structured_logger.h>

namespace edu_device {

// Initialize PCI device hardware resources
zx::result<> QemuEduDevice::MapInterruptAndMmio() {
  // Retrieve the Base Address Register (BAR) for PCI Region 0
  auto bar = pci_->GetBar(0);
  if (!bar.ok()) {
    FDF_SLOG(ERROR, "failed to get bar", KV("status", bar.status()));
    return zx::error(bar.status());
  }
  if (bar->is_error()) {
    FDF_SLOG(ERROR, "failed to get bar", KV("status", bar->error_value()));
    return zx::error(bar->error_value());
  }

  // Create a Memory-Mapped I/O (MMIO) region over BAR0
  {
    auto& bar_result = bar->value()->result;
    if (!bar_result.result.is_vmo()) {
      FDF_SLOG(ERROR, "unexpected bar type");
      return zx::error(ZX_ERR_NO_RESOURCES);
    }
    zx::result<fdf::MmioBuffer> mmio = fdf::MmioBuffer::Create(
        0, bar_result.size, std::move(bar_result.result.vmo()), ZX_CACHE_POLICY_UNCACHED_DEVICE);
    if (mmio.is_error()) {
      FDF_SLOG(ERROR, "failed to map mmio", KV("status", mmio.status_value()));
      return mmio.take_error();
    }
    mmio_ = *std::move(mmio);
  }

  // Configure interrupt handling for the device using INTx
  auto result = pci_->SetInterruptMode(fuchsia_hardware_pci::wire::InterruptMode::kLegacy, 1);
  if (!result.ok()) {
    FDF_SLOG(ERROR, "failed configure interrupt mode", KV("status", result.status()));
    return zx::error(result.status());
  }
  if (result->is_error()) {
    FDF_SLOG(ERROR, "failed configure interrupt mode", KV("status", result->error_value()));
    return zx::error(result->error_value());
  }

  // Map the device's interrupt to a system IRQ
  auto interrupt = pci_->MapInterrupt(0);
  if (!interrupt.ok()) {
    FDF_SLOG(ERROR, "failed to map interrupt", KV("status", interrupt.status()));
    return zx::error(interrupt.status());
  }
  if (interrupt->is_error()) {
    FDF_SLOG(ERROR, "failed to map interrupt", KV("status", interrupt->error_value()));
    return zx::error(interrupt->error_value());
  }
  irq_ = std::move(interrupt->value()->interrupt);
  // Start listening for interrupts.
  irq_method_.set_object(irq_.get());
  irq_method_.Begin(dispatcher_);

  return zx::ok();
}

}  // namespace edu_device

将新的设备资源添加到驱动程序类中:

qemu_edu/drivers/qemu_edu.h

#include <fidl/examples.qemuedu/cpp/wire.h>
#include <lib/driver/component/cpp/driver_base.h>
#include <lib/driver/devfs/cpp/connector.h>

#include "edu_device.h"

namespace qemu_edu {

class QemuEduDriver : public fdf::DriverBase {

 public:
  QemuEduDriver(fdf::DriverStartArgs start_args,
                fdf::UnownedSynchronizedDispatcher driver_dispatcher)
      : fdf::DriverBase("qemu-edu", std::move(start_args), std::move(driver_dispatcher)),
        devfs_connector_(fit::bind_member<&QemuEduDriver::Serve>(this)) {}

  virtual ~QemuEduDriver() = default;

  // Start hook called by the driver factory.
  zx::result<> Start() override;

 private:
  zx::result<> ExportToDevfs();
  void Serve(fidl::ServerEnd<examples_qemuedu::Device> request);

  fidl::WireSyncClient<fuchsia_driver_framework::Node> node_;
  fidl::WireSyncClient<fuchsia_driver_framework::NodeController> controller_;
  driver_devfs::Connector<examples_qemuedu::Device> devfs_connector_;
  std::shared_ptr<edu_device::QemuEduDevice> device_;
};

}  // namespace qemu_edu

更新驱动程序的 Run() 方法,以在驱动程序运行期间调用新方法 初始化:

qemu_edu/drivers/qemu_edu.cc

// Initialize this driver instance
zx::result<> QemuEduDriver::Start() {

  // Connect to the parent device node.
  zx::result connect_result = incoming()->Connect<fuchsia_hardware_pci::Service::Device>("default");
  if (connect_result.is_error()) {
    FDF_SLOG(ERROR, "Failed to open pci service.", KV("status", connect_result.status_string()));
    return connect_result.take_error();
  }

  // Map hardware resources from the PCI device
  device_ =
      std::make_shared<edu_device::QemuEduDevice>(dispatcher(), std::move(connect_result.value()));
  auto pci_status = device_->MapInterruptAndMmio();
  if (pci_status.is_error()) {
    return pci_status.take_error();
  }

  FDF_SLOG(INFO, "edu driver loaded successfully");

  return zx::ok();
}

更新驱动程序 build 配置,以包含新的源文件和依赖项 了解 fuchsia.hardware.pci 的 FIDL 绑定库:

qemu_edu/drivers/BUILD.bazel

fuchsia_cc_driver(
    name = "qemu_edu",
    srcs = [
        "edu_device.cc",
        "edu_device.h",
        "qemu_edu.cc",
        "qemu_edu.h",
    ],
    deps = [
        "@fuchsia_sdk//fidl/fuchsia.hardware.pci:fuchsia.hardware.pci_llcpp_cc",
        "@fuchsia_sdk//pkg/driver_component_cpp",
        "@fuchsia_sdk//pkg/driver_devfs_cpp",
        "@fuchsia_sdk//pkg/hwreg",
        "@fuchsia_sdk//pkg/mmio",
    ],
)

读取设备寄存器

将基本资源映射到驱动程序后,您可以访问个别 寄存器。将以下寄存器定义添加到 qemu_edu/drivers/edu_device.h 文件:

qemu_edu/drivers/edu_device.h

#include <hwreg/bitfields.h>

#include <fidl/fuchsia.hardware.pci/cpp/wire.h>
#include <lib/async/cpp/irq.h>
#include <lib/mmio/mmio.h>
#include <lib/zx/interrupt.h>

namespace edu_device {

// Register offset addresses for edu device MMIO area
constexpr uint32_t kIdentificationOffset = 0x00;
constexpr uint32_t kLivenessCheckOffset = 0x04;
constexpr uint32_t kFactorialComputationOffset = 0x08;
constexpr uint32_t kStatusRegisterOffset = 0x20;
constexpr uint32_t kInterruptStatusRegisterOffset = 0x24;
constexpr uint32_t kInterruptRaiseRegisterOffset = 0x60;
constexpr uint32_t kInterruptAcknowledgeRegisterOffset = 0x64;
constexpr uint32_t kDmaSourceAddressOffset = 0x80;
constexpr uint32_t kDmaDestinationAddressOffset = 0x80;
constexpr uint32_t kDmaTransferCountOffset = 0x90;
constexpr uint32_t kDmaCommandRegisterOffset = 0x98;

class Identification : public hwreg::RegisterBase<Identification, uint32_t> {
 public:
  DEF_FIELD(31, 24, major_version);
  DEF_FIELD(23, 16, minor_version);
  DEF_FIELD(15, 0, edu);

  static auto Get() { return hwreg::RegisterAddr<Identification>(kIdentificationOffset); }
};

class Status : public hwreg::RegisterBase<Status, uint32_t> {
 public:
  DEF_BIT(0, busy);
  DEF_BIT(7, irq_enable);

  static auto Get() { return hwreg::RegisterAddr<Status>(kStatusRegisterOffset); }
};

// Interacts with the device hardware using a fuchsia.hardware.pci client.
class QemuEduDevice {
 public:
  explicit QemuEduDevice(async_dispatcher_t* dispatcher,
                         fidl::ClientEnd<fuchsia_hardware_pci::Device> pci)
      : dispatcher_(dispatcher), pci_(std::move(pci)) {}

  zx::result<> MapInterruptAndMmio();

  void ComputeFactorial(uint32_t input, fit::callback<void(zx::result<uint32_t>)> callback);
  zx::result<uint32_t> LivenessCheck(uint32_t challenge);

  Identification IdentificationRegister() { return Identification::Get().ReadFrom(&*mmio_); }
  Status StatusRegister() { return Status::Get().ReadFrom(&*mmio_); }

 private:
  void HandleIrq(async_dispatcher_t* dispatcher, async::IrqBase* irq, zx_status_t status,
                 const zx_packet_interrupt_t* interrupt);

  async_dispatcher_t* const dispatcher_;

  fidl::WireSyncClient<fuchsia_hardware_pci::Device> pci_;
  std::optional<fdf::MmioBuffer> mmio_;
  zx::interrupt irq_;
  async::IrqMethod<QemuEduDevice, &QemuEduDevice::HandleIrq> irq_method_{this};
  std::optional<fit::callback<void(zx::result<uint32_t>)>> pending_callback_;
};

}  // namespace edu_device

此命令将设备规范中提供的寄存器偏移量声明为 常量。Fuchsia 的 hwreg 库封装了代表 位字段,使它们更易于访问,而无需执行单独的按位 操作。

qemu_edu/drivers/edu_device.cc 中实现以下额外方法 与 MMIO 区域交互,以便从 edu 设备注册:

  • ComputeFactorial():将输入值写入阶乘计算 注册并等待设备使用 中断。
  • HandleIrq():从阶乘寄存器中读取计算结果; 将其报告给待处理回调。
  • LivenessCheck():将质询值写入活跃性检查寄存器 并确认预期结果。

qemu_edu/drivers/edu_device.cc

#include "edu_device.h"

#include <lib/driver/logging/cpp/structured_logger.h>

namespace edu_device {
// ...

// Write data into the factorial register wait for an interrupt.
void QemuEduDevice::ComputeFactorial(uint32_t input,
                                     fit::callback<void(zx::result<uint32_t>)> callback) {
  if (pending_callback_.has_value()) {
    callback(zx::error(ZX_ERR_SHOULD_WAIT));
  }

  // Tell the device to raise an interrupt after computation.
  auto status = StatusRegister();
  status.set_irq_enable(true);
  status.WriteTo(&*mmio_);

  // Write the value into the factorial register to start computation.
  mmio_->Write32(input, kFactorialComputationOffset);

  // We will receive an interrupt when the computation completes.
  pending_callback_ = std::move(callback);
}

// Respond to INTx interrupts triggered by the device, and return the compute result.
void QemuEduDevice::HandleIrq(async_dispatcher_t* dispatcher, async::IrqBase* irq,
                              zx_status_t status, const zx_packet_interrupt_t* interrupt) {
  irq_.ack();
  if (!pending_callback_.has_value()) {
    FDF_LOG(ERROR, "Received unexpected interrupt!");
    return;
  }
  auto callback = std::move(*pending_callback_);
  pending_callback_ = std::nullopt;
  if (status != ZX_OK) {
    FDF_SLOG(ERROR, "Failed to wait for interrupt", KV("status", zx_status_get_string(status)));
    callback(zx::error(status));
    return;
  }

  // Acknowledge the interrupt with the edu device.
  auto int_status = mmio_->Read32(kInterruptStatusRegisterOffset);
  mmio_->Write32(int_status, kInterruptAcknowledgeRegisterOffset);

  // Deassert the legacy INTx interrupt on the PCI bus.
  auto irq_result = pci_->AckInterrupt();
  if (!irq_result.ok() || irq_result->is_error()) {
    FDF_SLOG(ERROR, "Failed to ack PCI interrupt",
             KV("status", irq_result.ok() ? irq_result->error_value() : irq_result.status()));
    callback(zx::error(ZX_ERR_IO));
    return;
  }

  // Reply with the result.
  uint32_t factorial = mmio_->Read32(kFactorialComputationOffset);
  FDF_SLOG(INFO, "Replying with", KV("factorial", factorial));
  callback(zx::ok(factorial));
}

// Write a challenge value to the liveness check register and return the result.
zx::result<uint32_t> QemuEduDevice::LivenessCheck(uint32_t challenge) {
  // Write the challenge value to the liveness check register.
  mmio_->Write32(challenge, kLivenessCheckOffset);

  // Return the result.
  auto value = mmio_->Read32(kLivenessCheckOffset);
  return zx::ok(value);
}

}  // namespace edu_device

将以下代码添加到驱动程序的 Start() 方法中,以读取主要版本和次要版本 并将其输出到 日志:

qemu_edu/drivers/qemu_edu.cc

// Initialize this driver instance
zx::result<> QemuEduDriver::Start() {
  // ...

  // Map hardware resources from the PCI device
  device_ =
      std::make_shared<edu_device::QemuEduDevice>(dispatcher(), std::move(connect_result.value()));
  auto pci_status = device_->MapInterruptAndMmio();
  if (pci_status.is_error()) {
    return pci_status.take_error();
  }

  // Report the version information from the edu device.
  auto version_reg = device_->IdentificationRegister();
  FDF_SLOG(INFO, "edu device version", KV("major", version_reg.major_version()),
           KV("minor", version_reg.minor_version()));

  return zx::ok();
}

重启模拟器

关停任何现有的模拟器实例:

ffx emu stop --all

启动一个新的 Fuchsia 模拟器实例,并启用驱动程序框架:

ffx emu start core.x64 --headless

重新加载驱动程序

使用 bazel run 命令构建并执行组件目标:

bazel run //fuchsia-codelab/qemu_edu/drivers:pkg.component

bazel run 命令会重新构建软件包并运行 ffx driver register,以 重新加载驱动程序组件。

检查系统日志,并验证您是否可以看到更新后的 FDF_SLOG() 消息,其中包含从标识注册读取的版本:

ffx log --filter qemu_edu
[driver_manager][driver_manager.cm][I]: [driver_runner.cc:959] Binding fuchsia-pkg://bazel.pkg.component/qemu_edu#meta/qemu_edu.cm to  00_06_0_
[full-drivers:root.sys.platform.pt.PCI0.bus.00_06_0_][qemu-edu,driver][I]: [fuchsia-codelab/qemu_edu/qemu_edu.cc:75] edu device version major=1 minor=0 

恭喜!您的驱动程序现在可以访问提供的 PCI 硬件资源 由绑定设备节点触发