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

时间:2016-06-03 15:04:47

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

我打算构建一个需要与用户空间设备驱动程序接口的Linux内核模块,我需要将数据导出到用户空间。经过一些阅读后,我认为UIO接口可能就是我需要的。

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

是否可以编写仅限软件的内核模块并仍然使用UIO库?或者只是直接使用sysfs是一种更好的方法?

编辑:我正在附加一些我正在处理的测试代码。我的目标是尝试通过UIO界面从用户空间读取字符串,但我不认为这会起作用,因为我无法看到如何正确启动struct device我认为uio_register_device { {1}}。

#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");

1 个答案:

答案 0 :(得分:2)

内核驱动程序背后的重点是与硬件通信。如果您没有任何硬件,那么您可能根本不需要内核驱动程序。

内核模块在做什么,如果不与硬件通信?从哪里获取数据?要回答你的问题,完全有可能编写一个内核驱动程序,它实际上并没有与硬件通信,仍然与UIO交谈,但我不确定它实际上会说些什么。