如何使用ioctl()来操作我的内核模块?

hah*_*g65 14 linux kernel kernel-module linux-kernel gumstix

所以我正在尝试编写一个使用linux/timer.h文件的内核模块.我让它在模块内部工作,现在我试图让它从用户程序开始工作.

这是我的内核模块:

//Necessary Includes For Device Drivers.
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/proc_fs.h>
#include <asm/uaccess.h>
#include <linux/timer.h>
#include <linux/ioctl.h>

#define DEVICE_NAME "mytimer"
#define DEVICE_FILE_NAME "mytimer"
#define MAJOR_NUM 61
#define MINOR_NUM 0

MODULE_LICENSE("Dual BSD/GPL");

static struct timer_list my_timer;

struct file_operations FileOps = 
{
    //No File Operations for this timer.
};

//Function to perform when timer expires.
void TimerExpire(int data)
{
    printk("Timer Data: %d\n", data);
}

//Function to set up timers.
void TimerSetup(void)
{
    setup_timer(&my_timer, TimerExpire, 5678);
    mod_timer(&my_timer, jiffies + msecs_to_jiffies(5000));
}

//Module Init and Exit Functions.
int init_module(void)
{
    int initResult = register_chrdev(MAJOR_NUM, "mytimer", &FileOps);

    if (initResult < 0)
    {
        printk("Cannot obtain major number %d\n", MAJOR_NUM);

        return initResult;
    }

printk("Loading MyTimer Kernel Module...\n");


return 0;
}
void cleanup_module(void)
{
    unregister_chrdev(MAJOR_NUM, "mytimer");
    printk("Unloading MyTimer Kernel Module...\n");
}
Run Code Online (Sandbox Code Playgroud)

更具体地说,我希望我的用户程序调用TimerSetup()函数.我知道我需要使用ioctl(),但我不知道如何在我的MODULE FILE中指定TimerSetup()应该可以通过ioctl()调用.

另外,我的第二个问题:我能够修改我的模块,并使用正确的主编号mknod到/ dev/mytimer.但是当我尝试打开()它以便我可以从中获取文件描述符时,它会一直返回-1,我认为这是错误的.我确保权限很好(事实上,我只是为了确定它是777)...它仍然无效......有什么我缺少的吗?

以下是用户程序以防万一:

#include <stdio.h>

int main(int argc, char* argv[])
{
    int fd = open("/dev/mytimer", "r");
    printf("fd: %d\n", fd);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ost 20

您需要的示例代码可以在drivers/watchdog/softdog.c(在编写本文时从Linux 2.6.33开始)中找到,它说明了正确的文件操作以及如何允许userland用ioctl()填充结构.

对于需要编写琐碎的角色设备驱动程序的人来说,它实际上是一个很棒的工作教程.

回答我自己的问题时,我解剖了softdog的ioctl界面,这可能对你有所帮助.

这是它的要点(虽然远非详尽无遗)......

softdog_ioctl()您看到struct watchdog_info的简单初始化,它宣告功能,版本和设备信息:

    static const struct watchdog_info ident = {
            .options =              WDIOF_SETTIMEOUT |
                                    WDIOF_KEEPALIVEPING |
                                    WDIOF_MAGICCLOSE,
            .firmware_version =     0,
            .identity =             "Software Watchdog",
    };
Run Code Online (Sandbox Code Playgroud)

然后我们看一个用户只想获得这些功能的简单案例:

    switch (cmd) {
    case WDIOC_GETSUPPORT:
            return copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0;
Run Code Online (Sandbox Code Playgroud)

...当然,它将使用上面的初始化值填充相应的用户空间watchdog_info.如果copy_to_user()失败,则返回-EFAULT,这会导致相应的用户空间ioctl()调用返回-1,并且设置了有意义的错误.

注意,魔术请求实际上是在linux/watchdog.h中定义的,因此内核和用户空间共享它们:

#define WDIOC_GETSUPPORT        _IOR(WATCHDOG_IOCTL_BASE, 0, struct watchdog_info)
#define WDIOC_GETSTATUS         _IOR(WATCHDOG_IOCTL_BASE, 1, int)
#define WDIOC_GETBOOTSTATUS     _IOR(WATCHDOG_IOCTL_BASE, 2, int)
#define WDIOC_GETTEMP           _IOR(WATCHDOG_IOCTL_BASE, 3, int)
#define WDIOC_SETOPTIONS        _IOR(WATCHDOG_IOCTL_BASE, 4, int)
#define WDIOC_KEEPALIVE         _IOR(WATCHDOG_IOCTL_BASE, 5, int)
#define WDIOC_SETTIMEOUT        _IOWR(WATCHDOG_IOCTL_BASE, 6, int)
#define WDIOC_GETTIMEOUT        _IOR(WATCHDOG_IOCTL_BASE, 7, int)
#define WDIOC_SETPRETIMEOUT     _IOWR(WATCHDOG_IOCTL_BASE, 8, int)
#define WDIOC_GETPRETIMEOUT     _IOR(WATCHDOG_IOCTL_BASE, 9, int)
#define WDIOC_GETTIMELEFT       _IOR(WATCHDOG_IOCTL_BASE, 10, int)
Run Code Online (Sandbox Code Playgroud)

WDIOC显然标志着"Watchdog ioctl"

您可以轻松地更进一步,让您的驱动程序执行某些操作并将结果放在结构中并将其复制到用户空间.例如,如果struct watchdog_info也有成员__u32 result_code.注意,__u32只是内核的版本uint32_t.

使用ioctl(),用户传递一个对象的地址,无论是结构,整数,还是内核要求内核在相同的对象中写入其回复并将结果复制到提供的地址.

您需要做的第二件事是确保您的设备知道当有人打开,从中读取,写入或使用像ioctl()这样的钩子时要做什么,您可以通过研究软件狗轻松看到它.

有趣的是:

static const struct file_operations softdog_fops = {
        .owner          = THIS_MODULE,
        .llseek         = no_llseek,
        .write          = softdog_write,
        .unlocked_ioctl = softdog_ioctl,
        .open           = softdog_open,
        .release        = softdog_release,
};
Run Code Online (Sandbox Code Playgroud)

你在哪里看到unlocked_ioctl处理程序......你猜对了,softdog_ioctl().

我认为你可能会在处理ioctl()时并置一层真正不存在的复杂性,它真的很简单.出于同样的原因,大多数内核开发人员都不赞成添加新的ioctl接口,除非它们是绝对必要的.它很容易失去跟踪ioctl()将填充的类型与你用来做它的魔法,这是copy_to_user()失败的主要原因经常导致内核腐烂,大量的用户空间进程陷入困境磁盘睡眠.

对于计时器,我同意,ioctl()是通向理智的最短途径.


jsc*_*ier 8

您缺少结构中的.open函数指针,file_operations以指定进程尝试打开设备文件时要调用的函数.您还需要.ioctl为ioctl函数指定一个函数指针.

尝试阅读Linux内核模块编程指南,特别是第4章(字符设备文件)和第7章(与设备文件交谈).

第4章介绍了该file_operations结构,该结构保存了指向由模块/驱动程序定义的函数的指针,这些函数执行各种操作,如openioctl.

第7章提供了有关通过ioctls与模块/驱动器进行通信的信息.

Linux设备驱动程序,第三版是另一个很好的资源.


Cir*_*四事件 6

最小的可运行示例

在完全可重现的 QEMU + Buildroot 环境中进行测试,因此可能会帮助其他人开始ioctl工作。GitHub 上游: 内核模块| 共享标题| 用户空间

最烦人的部分是了解一些低 ID 被劫持:如果 cmd = 2则不会调用 ioctl,您必须使用_IOx宏。

内核模块:

#include <asm/uaccess.h> /* copy_from_user, copy_to_user */
#include <linux/debugfs.h>
#include <linux/module.h>
#include <linux/printk.h> /* printk */

#include "ioctl.h"

MODULE_LICENSE("GPL");

static struct dentry *dir;

static long unlocked_ioctl(struct file *filp, unsigned int cmd, unsigned long argp)
{
    void __user *arg_user;
    union {
        int i;
        lkmc_ioctl_struct s;
    } arg_kernel;

    arg_user = (void __user *)argp;
    pr_info("cmd = %x\n", cmd);
    switch (cmd) {
        case LKMC_IOCTL_INC:
            if (copy_from_user(&arg_kernel.i, arg_user, sizeof(arg_kernel.i))) {
                return -EFAULT;
            }
            pr_info("0 arg = %d\n", arg_kernel.i);
            arg_kernel.i += 1;
            if (copy_to_user(arg_user, &arg_kernel.i, sizeof(arg_kernel.i))) {
                return -EFAULT;
            }
        break;
        case LKMC_IOCTL_INC_DEC:
            if (copy_from_user(&arg_kernel.s, arg_user, sizeof(arg_kernel.s))) {
                return -EFAULT;
            }
            pr_info("1 arg = %d %d\n", arg_kernel.s.i, arg_kernel.s.j);
            arg_kernel.s.i += 1;
            arg_kernel.s.j -= 1;
            if (copy_to_user(arg_user, &arg_kernel.s, sizeof(arg_kernel.s))) {
                return -EFAULT;
            }
        break;
        default:
            return -EINVAL;
        break;
    }
    return 0;
}

static const struct file_operations fops = {
    .owner = THIS_MODULE,
    .unlocked_ioctl = unlocked_ioctl
};

static int myinit(void)
{
    dir = debugfs_create_dir("lkmc_ioctl", 0);
    /* ioctl permissions are not automatically restricted by rwx as for read / write,
     * but we could of course implement that ourselves:
     * /sf/ask/2092426241/ */
    debugfs_create_file("f", 0, dir, NULL, &fops);
    return 0;
}

static void myexit(void)
{
    debugfs_remove_recursive(dir);
}

module_init(myinit)
module_exit(myexit)
Run Code Online (Sandbox Code Playgroud)

内核模块和用户空间之间的共享头文件:

ioctl.h

#ifndef IOCTL_H
#define IOCTL_H

#include <linux/ioctl.h>

typedef struct {
    int i;
    int j;
} lkmc_ioctl_struct;
#define LKMC_IOCTL_MAGIC 0x33
#define LKMC_IOCTL_INC     _IOWR(LKMC_IOCTL_MAGIC, 0, int)
#define LKMC_IOCTL_INC_DEC _IOWR(LKMC_IOCTL_MAGIC, 1, lkmc_ioctl_struct)

#endif
Run Code Online (Sandbox Code Playgroud)

用户地:

#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "../ioctl.h"

int main(int argc, char **argv)
{
    int fd, arg_int, ret;
    lkmc_ioctl_struct arg_struct;

    if (argc < 2) {
        puts("Usage: ./prog <ioctl-file>");
        return EXIT_FAILURE;
    }
    fd = open(argv[1], O_RDONLY);
    if (fd == -1) {
        perror("open");
        return EXIT_FAILURE;
    }
    /* 0 */
    {
        arg_int = 1;
        ret = ioctl(fd, LKMC_IOCTL_INC, &arg_int);
        if (ret == -1) {
            perror("ioctl");
            return EXIT_FAILURE;
        }
        printf("arg = %d\n", arg_int);
        printf("ret = %d\n", ret);
        printf("errno = %d\n", errno);
    }
    puts("");
    /* 1 */
    {
        arg_struct.i = 1;
        arg_struct.j = 1;
        ret = ioctl(fd, LKMC_IOCTL_INC_DEC, &arg_struct);
        if (ret == -1) {
            perror("ioctl");
            return EXIT_FAILURE;
        }
        printf("arg = %d %d\n", arg_struct.i, arg_struct.j);
        printf("ret = %d\n", ret);
        printf("errno = %d\n", errno);
    }
    close(fd);
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)