如果 Linux 内核模块不使用任何物理硬件,它可以使用 UIO 吗?

标签 c linux linux-kernel kernel linux-device-driver

我正计划构建一个需要与用户空间设备驱动程序交互的 Linux 内核模块,并且我需要将数据导出到用户空间。阅读之后,我认为 UIO 接口(interface)可能正是我所需要的。

我看了一些例子,它们都是基于这样的假设,即内核模块本身将直接与硬件交互,并引用设备结构、中断等内容。

是否可以编写纯软件内核模块并仍然使用 UIO 库?或者直接使用 sysfs 会是更好的方法吗?

编辑:我附上了一些我正在处理的测试代码。目标是尝试通过 UIO 接口(interface)从用户空间读取字符串,但我认为这不会起作用,因为我看不到如何正确启动我认为需要的 struct device对于 uio_register_device

#include <linux/module.h>  // Needed by all modules
#include <linux/kernel.h>  // Needed for KERN_ALERT

#include <linux/uio_driver.h>
#include <linux/slab.h>    // GFP_ defs
#include <linux/device.h>

char test_data[] = "This is some test data to read in user-space via UIO\n";

int init_module(void)
{
  struct uio_info *info;
  struct device *dev;
  info = kzalloc(sizeof(struct uio_info), GFP_KERNEL);
  if (!info)
    return -ENOMEM;

  // need to use struct device for uio_register_device
  dev = kzalloc(sizeof(struct device), GFP_KERNEL);
  dev->parent = 0;
  dev->init_name = "UIO test driver";

  info->name = "uio_test";
  info->version = "0.0.1";

  info->mem[0].size = sizeof(test_data);
  info->mem[0].memtype = UIO_MEM_LOGICAL;
  info->mem[0].addr = (phys_addr_t) kmalloc(sizeof(test_data), GFP_KERNEL);
  snprintf((char *) info->mem[0].addr, sizeof(test_data), "%s", test_data);

  info->irq = UIO_IRQ_NONE;

  // now we need to register the device for it to create /dev/uioN and sysfs files
  if (uio_register_device(dev, info)) {
    printk(KERN_ALERT "uio_test: couldn't register UIO device\n");
    kfree(dev);
    kfree((char *) info->mem[0].addr);
    kfree(info);
    return -ENODEV;
  }

  printk(KERN_ALERT "uio_test: init complete\n");

  return 0;
}


void cleanup_module(void)
{
  printk(KERN_ALERT "uio_test: exit\n");
}  

MODULE_LICENSE("GPL");

最佳答案

内核驱动背后的全部意义在于与硬件对话。如果您没有任何硬件,那么您可能根本不需要内核驱动程序。

如果内核模块不与硬件对话,它在做什么?从哪里获取数据?要回答您的问题,完全可以编写一个实际上不与硬件对话但仍与 UIO 对话的内核驱动程序,但我不确定它实际上会说什么。

关于如果 Linux 内核模块不使用任何物理硬件,它可以使用 UIO 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37617763/

相关文章:

objective-c - 在 MacOS 10.10 上监视文件系统事件

c - 如何获取 <linux/bootmem.h> 文件并修复错误 "fatal error: linux/bootmem.h: No such file or directory #include <linux/bootmem.h>"?

c++ - typedef void FOO 与 #define FOO void 在函数签名中的含义

python - 如何在 Django 的一个 HTML 页面中打开两个日志文件?

Linux bash if - elif 没有按预期工作

linux - tshark 2.2.6 在某些计算机上不显示 data.text 字段

linux - 一个线程获取信号量而另一个线程释放信号量的有效用例是什么?

linux - 执行 `ls *.c` 时内部会发生什么?

c - 为什么函数调用不是左值

c - 生成连通图并检查它是否有欧拉循环