Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

從零寫一個簡單的字符設備驅動

理論部分可參考《Linux Device Driver》第三版。實作時這裡主動指定主設備號,雖然書中建議優先讓系統自動分配,但為了看清楚每一步在做什麼,先手動指定反而更好理解。

步驟一:建立設備節點

先用 cat /proc/devices 查看已占用的主設備號,這裡假設 50 號未被使用:

mknod /dev/mycdev c 50 0
chmod 777 /dev/mycdev

其中 mycdev 就是下一步要安裝的模組名。

步驟二:撰寫驅動

/* ===================================================================
 * Filename: mycdev.c
 * Description: 簡單的字符設備驅動
 * Compiler: gcc
 *================================================================== */

#include <linux/init.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/cdev.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>

MODULE_LICENSE("GPL");

#define MYCDEV_MAJOR (50)
#define MYCDEV_SIZE  0x1000

static dev_t mycdev_major = MYCDEV_MAJOR;

struct mycdev {
    struct cdev cdev;
    unsigned char mem[255];
};

struct mycdev *devp;

static int mycdev_open(struct inode *inode, struct file *fp)
{
    fp->private_data = devp;
    return 0;
}

static int mycdev_release(struct inode *inode, struct file *fp)
{
    return 0;
}

static ssize_t mycdev_read(struct file *fp, char __user *buf,
                           size_t size, loff_t *pos)
{
    unsigned long p = *pos;
    unsigned int count = size;
    struct mycdev *tmp_dev = fp->private_data;

    if (p >= MYCDEV_SIZE) {
        return -1;
    }
    if (count > MYCDEV_SIZE - p) {
        count = MYCDEV_SIZE - p;
    }
    if (copy_to_user(buf, (void *)(tmp_dev->mem + p), count) != 0) {
        printk("read error!\n");
        return -1;
    } else {
        *pos += count;
        printk(KERN_INFO "read %d bytes from %ld\n", count, p);
    }
    return count;
}

static ssize_t mycdev_write(struct file *fp, const char __user *buf,
                            size_t size, loff_t *pos)
{
    unsigned long p = *pos;
    unsigned int count = size;
    struct mycdev *tmp_dev = fp->private_data;

    if (p > MYCDEV_SIZE) {
        return -1;
    }
    if (p > MYCDEV_SIZE - count) {
        count = MYCDEV_SIZE - p;
    }
    if (copy_from_user((void *)(tmp_dev->mem + p), buf, count) != 0) {
        return -1;
    } else {
        *pos += count;
        printk(KERN_INFO "write %d bytes from %ld\n", count, p);
    }
    return count;
}

static loff_t mycdev_llseek(struct file *fp, loff_t off, int whence)
{
    loff_t new_pos = 0;

    switch (whence) {
    case SEEK_SET:
        new_pos = off;
        break;
    case SEEK_CUR:
        new_pos = fp->f_pos + off;
        break;
    case SEEK_END:
        new_pos = MYCDEV_SIZE + off;
    }

    if (new_pos < 0) {
        return -EINVAL;
    } else {
        fp->f_pos = new_pos;
        return new_pos;
    }
}

static const struct file_operations mycdev_fops = {
    .owner   = THIS_MODULE,
    .read    = mycdev_read,
    .write   = mycdev_write,
    .open    = mycdev_open,
    .release = mycdev_release,
    .llseek  = mycdev_llseek,
};

static void setup_mycdev(struct mycdev *dev, int index)
{
    int ret;
    int devno = MKDEV(mycdev_major, index);

    cdev_init(&dev->cdev, &mycdev_fops);
    dev->cdev.owner = THIS_MODULE;
    dev->cdev.ops   = &mycdev_fops;
    ret = cdev_add(&dev->cdev, devno, 1);
    if (ret) {
        printk("adding mycdev error!\n");
    }
}

static int __init mycdev_init(void)
{
    int ret;
    dev_t devno = 0;

    if (mycdev_major) {          /* 靜態分配 */
        devno = MKDEV(mycdev_major, 0);
        ret = register_chrdev_region(devno, 1, "mycdev");
    } else {                     /* 動態分配 */
        ret = alloc_chrdev_region(&devno, 0, 1, "mycdev");
        mycdev_major = MAJOR(devno);
    }

    devp = kmalloc(sizeof(struct mycdev), GFP_KERNEL);
    if (!devp) {
        ret = -ENOMEM;
        unregister_chrdev_region(devno, 1);
        return ret;
    }
    memset(devp, 0, sizeof(struct mycdev));

    setup_mycdev(devp, 0);
    return 0;
}

static void __exit mycdev_exit(void)
{
    printk("mycdev module is leaving...\n");
    cdev_del(&devp->cdev);
    kfree(devp);
    unregister_chrdev_region(MKDEV(mycdev_major, 0), 1);
}

module_init(mycdev_init);
module_exit(mycdev_exit);

幾個容易忽略的地方

fp->private_data = devp 這一行讓 read/write 能拿到設備自己的結構體,是 Linux 驅動傳遞私有資料的標準手法。

read 與 write 都必須做邊界檢查並透過 copy_to_user/copy_from_user 搬資料,不能直接用 memcpy,否則使用者空間的非法位址會把內核拖垮。

不記得設 .owner = THIS_MODULE 是新手常犯的錯,少了它,模組被卸除後若仍有 fd 開著就會引發崩潰。另外注意結構體裡的 mem 只有 255 位元組,而 MYCDEV_SIZE 定義為 0x1000,兩者不一致,實作時應統一,否則存在越界寫入的風險。

Copyright © Linux教程網 All Rights Reserved