0

我有一个 gpio 设备。我有一些内核模块可以使用这个设备。

//headers
#include <linux/module.h>
#include <linux/init.h>
...

//declarations 
static si_t *gpio_sih;
static int gpio_major;
static struct class *gpiodev_class = NULL;

//some functions for open, read, write, etc
...

static struct file_operations gpio_fops = {...} // <- look up 

static int __init
gpio_init(void)
{
    if (!(gpio_sih = si_kattach(SI_OSH)))
        return -ENODEV;
    if ((gpio_major = register_chrdev(0, "gpio", &gpio_fops)) < 0)
        return gpio_major;
    gpiodev_class = class_create(THIS_MODULE, "gpio");
    if (IS_ERR(gpiodev_class)) {
        printk("Error creating gpio class\n");
        return -1;
    }
    class_device_create(gpiodev_class, NULL, MKDEV(gpio_major, 0), NULL, "gpio");
    return 0;
}

static void __exit
gpio_exit(void)
{
    if (gpiodev_class != NULL) {
        class_device_destroy(gpiodev_class, MKDEV(gpio_major, 0));
        class_destroy(gpiodev_class);
    }
    gpiodev_class = NULL;
    if (gpio_major >= 0)
        unregister_chrdev(gpio_major, "gpio");
    si_detach(gpio_sih);
}

module_init(gpio_init);
module_exit(gpio_exit);

另外,我需要另一个内核模块来处理这个物理设备,但它必须是系统中的另一个字符设备,具有另一个文件操作。我应该怎么办?类比写一个模块?

//headers
#include <linux/module.h>
#include <linux/init.h>
...

//declarations 
static si_t *another_gpio_sih;
static int another_gpio_major;
static struct class *another_gpiodev_class = NULL;

//some functions for another_open, another_read, another_write, another_etc
...

static struct file_operations another_gpio_fops = {...} // <- look up 

static int __init
another_gpio_init(void)
{
    if (!(another_gpio_sih = si_kattach(SI_OSH)))
        return -ENODEV;
    if ((another_gpio_major = register_chrdev(0, "another_gpio", &another_gpio_fops)) < 0)
        return gpio_major;
    another_gpiodev_class = class_create(THIS_MODULE, "another_gpio");
    if (IS_ERR(another_gpiodev_class)) {
        printk("Error creating gpio class\n");
        return -1;
    }
    class_device_create(another_gpiodev_class, NULL, MKDEV(another_gpio_major, 0), NULL, "another_gpio");
    return 0;
}

static void __exit
another_gpio_exit(void)
{
    if (another_gpiodev_class != NULL) {
        class_device_destroy(another_gpiodev_class, MKDEV(another_gpio_major, 0));
        class_destroy(another_gpiodev_class);
    }
    another_gpiodev_class = NULL;
    if (another_gpio_major >= 0)
        unregister_chrdev(another_gpio_major, "another_gpio");
    si_detach(another_gpio_sih);
}

module_init(another_gpio_init);
module_exit(another_gpio_exit);

还是使用导出全局变量?

EXPORT_SYMBOL(gpio_sih);
EXPORT_SYMBOL(gpiodev_class);

extern static si_t *another_gpio_sih;
extern static struct class *another_gpiodev_class;

谢谢。

4

1 回答 1

0

首先,为什么需要所有这些设备?为什么不使用标准内核接口:/sys/class/gpio?

它允许从用户空间读取、写入和等待 gpio 的更改。

第二。如果您有两个具有几乎相同功能的字符设备,为什么不在一个驱动程序中处理它们,设置它们一个主要编号和两个不同的次要编号,正确实现从 file_operation 中打开模拟,一切都会好起来的。

于 2013-07-06T00:00:55.220 回答