Chinaunix首页 | 论坛 | 博客
  • 博客访问: 390657
  • 博文数量: 380
  • 博客积分: 75
  • 博客等级: 民兵
  • 技术积分: 1925
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-05 15:35
文章分类

全部博文(380)

文章存档

2014年(1)

2013年(2)

2012年(19)

2011年(358)

我的朋友

分类:

2012-05-28 22:09:22

原文地址:scull分析 作者:amwha

   看了一周多的LDD3了,第一个比较完整的字符驱动scull现在加几行注释在里面,呵呵!
请路过的高手指导一下,里面的问题,主要是:
struct scull_dev *scull_devices;这里定义的是指针,在使用的时候为什么可以用数组,文中有几处是这样的情况,都不太理解。
 
以下是本地头文件:
 

/*
 * scull.h -- definitions for the char module
 *
 * Copyright (C) 2001 Alessandro Rubini and Jonathan Corbet
 * Copyright (C) 2001 O'Reilly & Associates
 *
 * The source code in this file can be freely used, adapted,
 * and redistributed in source or binary form, so long as an
 * acknowledgment appears in derived source files. The citation
 * should list that the code comes from the book "Linux Device
 * Drivers" by Alessandro Rubini and Jonathan Corbet, published
 * by O'Reilly & Associates. No warranty is attached;
 * we cannot take responsibility for errors or fitness for use.
 *
 * $Id: scull.h,v 1.15 2004/11/04 17:51:18 rubini Exp $
 */


#ifndef _SCULL_H_
#define _SCULL_H_

#include <linux/ioctl.h> /* needed for the _IOW etc stuff used later */

/*
 * Macros to help debugging
 */


#undef PDEBUG /* undef it, just in case */  //这里是关于打印的信息的开或关。
#ifdef SCULL_DEBUG
# ifdef __KERNEL__
     /* This one if debugging is on, and kernel space */
# define PDEBUG(fmt, args...) printk( KERN_DEBUG "scull: " fmt, ## args)
# else
     /* This one for user space */
# define PDEBUG(fmt, args...) fprintf(stderr, fmt, ## args)
# endif
#else
# define PDEBUG(fmt, args...) /* not debugging: nothing */
#endif

#undef PDEBUGG
#define PDEBUGG(fmt, args...) /* nothing: it's a placeholder */

#ifndef SCULL_MAJOR
#define SCULL_MAJOR 0 /* dynamic major by default */
#endif

#ifndef SCULL_NR_DEVS
#define SCULL_NR_DEVS 4 /* scull0 through scull3 */ 一共有四个设备
#endif

#ifndef SCULL_P_NR_DEVS
#define SCULL_P_NR_DEVS 4 /* scullpipe0 through scullpipe3 */
#endif

/*
 * The bare device is a variable-length region of memory.
 * Use a linked list of indirect blocks.
 *
 * "scull_dev->data" points to an array of pointers, each
 * pointer refers to a memory area of SCULL_QUANTUM bytes.
 *
 * The array (quantum-set) is SCULL_QSET long.
 */

#ifndef SCULL_QUANTUM
#define SCULL_QUANTUM 4000
#endif

#ifndef SCULL_QSET
#define SCULL_QSET 1000
#endif

/*
 * The pipe device is a simple circular buffer. Here its default size
 */

#ifndef SCULL_P_BUFFER
#define SCULL_P_BUFFER 4000
#endif

/*
 * Representation of scull quantum sets.
 */

struct scull_qset {
    void **data;
    struct scull_qset *next;
};

struct scull_dev {              //设备结构体
    struct scull_qset *data; /* Pointer to first quantum set */
    int quantum; /* the current quantum size */
    int qset; /* the current array size */
    unsigned long size; /* amount of data stored here */
    unsigned int access_key; /* used by sculluid and scullpriv */
    struct semaphore sem; /* mutual exclusion semaphore */
    struct cdev cdev;     /* Char device structure        */
};

/*
 * Split minors in two parts
 */

#define TYPE(minor)    (((minor) >> 4) & 0xf)    /* high nibble */
#define NUM(minor)    ((minor) & 0xf)        /* low nibble */


/*
 * The different configurable parameters
 */

extern int scull_major; /* main.c */   //模块参数,
extern int scull_nr_devs;
extern int scull_quantum;
extern int scull_qset;

/*
 * Prototypes for shared functions
 */


//函数原型
int scull_trim(struct scull_dev *dev);

ssize_t scull_read(struct file *filp, char __user *buf, size_t count,
                   loff_t *f_pos);
ssize_t scull_write(struct file *filp, const char __user *buf, size_t count,
                    loff_t *f_pos);


/*
 * Ioctl definitions
 */


/* Use 'k' as magic number */   //幻数,这里定的是K,因为一个字符型变量是8位的,正好幻数也是要8位,但是不要和已经使用的冲突,不然没有办法使用。不知道用那一个,
#define SCULL_IOC_MAGIC 'k'
/* Please use a different 8-bit number in your code */
//以下是ioctl的命令了
#define SCULL_IOCRESET  _IO(SCULL_IOC_MAGIC, 0)  

/*
 * S means "Set" through a ptr,
 * T means "Tell" directly with the argument value
 * G means "Get": reply by setting through a pointer
 * Q means "Query": response is on the return value
 * X means "eXchange": switch G and S atomically
 * H means "sHift": switch T and Q atomically
 */

#define SCULL_IOCSQUANTUM _IOW(SCULL_IOC_MAGIC, 1, int)
#define SCULL_IOCSQSET _IOW(SCULL_IOC_MAGIC, 2, int)
#define SCULL_IOCTQUANTUM _IO(SCULL_IOC_MAGIC, 3)
#define SCULL_IOCTQSET _IO(SCULL_IOC_MAGIC, 4)
#define SCULL_IOCGQUANTUM _IOR(SCULL_IOC_MAGIC, 5, int)
#define SCULL_IOCGQSET _IOR(SCULL_IOC_MAGIC, 6, int)
#define SCULL_IOCQQUANTUM _IO(SCULL_IOC_MAGIC, 7)
#define SCULL_IOCQQSET _IO(SCULL_IOC_MAGIC, 8)
#define SCULL_IOCXQUANTUM _IOWR(SCULL_IOC_MAGIC, 9, int)
#define SCULL_IOCXQSET _IOWR(SCULL_IOC_MAGIC,10, int)
#define SCULL_IOCHQUANTUM _IO(SCULL_IOC_MAGIC, 11)
#define SCULL_IOCHQSET _IO(SCULL_IOC_MAGIC, 12)

/*
 * The other entities only have "Tell" and "Query", because they're
 * not printed in the book, and there's no need to have all six.
 * (The previous stuff was only there to show different ways to do it.
 */

#define SCULL_P_IOCTSIZE _IO(SCULL_IOC_MAGIC, 13)
#define SCULL_P_IOCQSIZE _IO(SCULL_IOC_MAGIC, 14)
/* ... more to come */

#define SCULL_IOC_MAXNR 14

#endif /* _SCULL_H_ */


以下是scull.c了

一般的驱动程序都是从尾部阅读开始的。而且最好是用source Insight建一个project,然后就可以到处jump to definition了,爽,哈哈!

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

#include <linux/kernel.h>    /* printk() */
#include <linux/slab.h>        /* kmalloc() */
#include <linux/fs.h>        /* everything... */
#include <linux/errno.h>    /* error codes */
#include <linux/types.h>    /* size_t */
#include <linux/fcntl.h>    /* O_ACCMODE */
#include <linux/cdev.h>
#include <asm/system.h>        /* cli(), *_flags */
#include <asm/uaccess.h>    /* copy_*_user */
#include "scull.h"        /* local definitions */

/*
 * Our parameters which can be set at load time.
 */

int scull_major = SCULL_MAJOR;   //传入模块的参数,感觉搞得很复杂
int scull_minor = 0;
int scull_nr_devs = SCULL_NR_DEVS;    /* number of bare scull devices */
int scull_quantum = SCULL_QUANTUM;
int scull_qset = SCULL_QSET;

module_param(scull_major, int, S_IRUGO);
module_param(scull_minor, int, S_IRUGO);
module_param(scull_nr_devs, int, S_IRUGO);
module_param(scull_quantum, int, S_IRUGO);
module_param(scull_qset, int, S_IRUGO);
//?????????????????????????????????????定义了一个设备对像指针(为什么下面用数组,搞不清白)
struct scull_dev *scull_devices;    /* allocated in scull_init_module */

/*
 * Empty out the scull device; must be called with the device
 * semaphore held.初始化设备里面定义 的一些空间
 */



int scull_trim(struct scull_dev *dev)
{
    struct scull_qset *next, *dptr;  //定义了两个结构指针,采用的是链表,本人数据结构学得不好,现在噩梦开始了
    int qset = dev->qset; /* "dev" is not-null *///当前的数组大小
    int i;

    for (dptr = dev->data; dptr; dptr = next) { /* all the list items *///这一个data应该是scull_qset对像
        if (dptr->data) { //这个data应该是scull_qset成员变量
            for (i = 0; i < qset; i++)
                kfree(dptr->data[i]);  //释放内存,这里又来了一个数组,我的理解是:死皮赖脸要这么多的空间
            kfree(dptr->data); //估计是里面以前有东西,现在斗一斗,让出来,给我用
            dptr->data = NULL;  //初始化为空
        }
        next = dptr->next;  //指针后移
        kfree(dptr);   //释放这个指针,不知道理解得对不对了,呵呵
    }

//两次for循环后,这些空间都初始化好了!
    dev->size = 0;
    dev->quantum = scull_quantum;
    dev->qset = scull_qset;
    dev->data = NULL;
    return 0;
}



/*
 * Open and close
 */


int scull_open(struct inode *inode, struct file *filp)
{
    struct scull_dev *dev; /* device information */
//这个函数的作用是通过一个结构的成员的指针,找到整个结构的指针,不是很明白用法
    dev = container_of(inode->i_cdev, struct scull_dev, cdev);
    filp->private_data = dev; /* for other methods *///设备一般是要先打再能进行读啊写啊还有其它操作,那么在第一步打开的时候,要把设备与设备操作结构给关联起来,open传入的第二个参数,文件指针,在文件这个结构体里有一个private_data数据成员,通过上一步的赋值操作,把设备和设备文件结构给关联起来了,这样在以后的read,write。。。中只要把这个private_data赋值给定义的设备结构dev,那么read,write方法操作的就是open的这个设备了,而不是其它的设备。

    /* now trim to 0 the length of the device if open was write-only *///只读打开
    if ( (filp->f_flags & O_ACCMODE) == O_WRONLY) {
        if (down_interruptible(&dev->sem))  //一般都要判断一下,P操作,这是一种可休眠可中断方式的休眠,在没有获得信号量的时候,这个进程将进入到可中断的休眠状态,还有种锁的机制是,自旋锁,其实,信号的底层实现上,还是自旋锁,看下信号量的结构体定义:

struct semaphore {
 spinlock_t  lock;
 unsigned int  count;
 struct list_head wait_list;
};
自旋锁是一种忙等的状态的锁,没有获得锁的话,就要一直围着这个锁打转,这就是铊的字面意思了。
在内核中避免并发和竞态的的方法有很多,有信号量和自旋锁的变种,如原子操作,位操作。当要保护的临界代码很短小的时候,如:p++这样的操作,使用一个信号量或是一个自旋锁,有点浪费了,用原子操作,atomic_t p。什么是原子操作呢?就是不可打断的。p++在c语言里是可以被打断的,因为在汇编里,他会汇编成三条汇编语言。那么这三条都可能会被 打断 的。加上原子操作后,呵呵,打断不了。
            return -ERESTARTSYS;
        scull_trim(dev); /* ignore errors */ //这个操作是临界代码了
        up(&dev->sem);  //v操作,释放信号量
    }
    return 0; /* success */
}
//那么什么时候用自旋锁,什么时候用信号量呢,一般在要进行大量的数据操作的时候,一般用信号量,耗用的时间相对来着要长一些,而一般的操作,用spinlock就可以了。



int scull_release(struct inode *inode, struct file *filp)
{
    return 0;
}//这家伙很懒,什么也没有干



/*
 * Follow the list
 */

//又开始了噩梦了,这是通过这个链表,找到具体的位置 (指针函数,返回一个指针)
struct scull_qset *scull_follow(struct scull_dev *dev, int n)
{
    struct scull_qset *qs = dev->data;

        /* Allocate first qset explicitly if need be */
    if (! qs) {
        qs = dev->data = kmalloc(sizeof(struct scull_qset), GFP_KERNEL);
        if (qs == NULL)
            return NULL; /* Never mind */
        memset(qs, 0, sizeof(struct scull_qset));
    }

    /* Then follow the list */

//应该是单链表,错误理解一定要指出啊,谢谢!
    while (n--) {
        if (!qs->next) {
            qs->next = kmalloc(sizeof(struct scull_qset), GFP_KERNEL);
            if (qs->next == NULL)
                return NULL; /* Never mind */
            memset(qs->next, 0, sizeof(struct scull_qset));
        }
        qs = qs->next;
        continue;
    }
    return qs;
}



/*
 * Data management: read and write
 */


ssize_t scull_read(struct file *filp, char __user *buf, size_t count,
                loff_t *f_pos)
{

//read函数能通过private_data来访问设备结构体,具体怎么实现的呢?因为在打开的时候,open方法的时候,会把设备结构体的信息赋值给struct file的private_data这个数据成员变量,在这里,回写一下,就可以知道read方法所要操作对像了。

    struct scull_dev *dev = filp->private_data;
    struct scull_qset *dptr;    /* the first listitem */
    int quantum = dev->quantum, qset = dev->qset;
    int itemsize = quantum * qset; /* how many bytes in the listitem */
    int item, s_pos, q_pos, rest;
    ssize_t retval = 0;

    if (down_interruptible(&dev->sem)) //取得信号量,p操作
        return -ERESTARTSYS;
    if (*f_pos >= dev->size) //越界了,滚出去!!呵呵f_pos是读取的位置
        goto out;
    if (*f_pos + count > dev->size) //没有越界,但是要读的数超过了本来的大小,那就把剩下的读走吧
        count = dev->size - *f_pos;

    /* find listitem, qset index, and offset in the quantum */
    item = (long)*f_pos / itemsize;
    rest = (long)*f_pos % itemsize;
    s_pos = rest / quantum; q_pos = rest % quantum;

    /* follow the list up to the right position (defined elsewhere) */
    dptr = scull_follow(dev, item);   //找到位置

    if (dptr == NULL || !dptr->data || ! dptr->data[s_pos])
        goto out; /* don't fill holes */

    /* read only up to the end of this quantum */
    if (count > quantum - q_pos)
        count = quantum - q_pos;

    if (copy_to_user(buf, dptr->data[s_pos] + q_pos, count)) {
        retval = -EFAULT;
        goto out;
    }
    *f_pos += count;  //读完后的数据新位置
    retval = count;  //返回读取的数据量

  out:
    up(&dev->sem);     //释放信号量,一般大量的数据拷贝,都要用到信号量机制来防止并发和竞态
    return retval;
}

ssize_t scull_write(struct file *filp, const char __user *buf, size_t count,
                loff_t *f_pos)
{
    struct scull_dev *dev = filp->private_data;
    struct scull_qset *dptr;
    int quantum = dev->quantum, qset = dev->qset;
    int itemsize = quantum * qset;
    int item, s_pos, q_pos, rest;
    ssize_t retval = -ENOMEM; /* value used in "goto out" statements */

    if (down_interruptible(&dev->sem))
        return -ERESTARTSYS;

    /* find listitem, qset index and offset in the quantum */
    item = (long)*f_pos / itemsize;
    rest = (long)*f_pos % itemsize;
    s_pos = rest / quantum; q_pos = rest % quantum;

    /* follow the list up to the right position */
    dptr = scull_follow(dev, item);
    if (dptr == NULL)
        goto out;
    if (!dptr->data) {
        dptr->data = kmalloc(qset * sizeof(char *), GFP_KERNEL);
        if (!dptr->data)
            goto out;
        memset(dptr->data, 0, qset * sizeof(char *));
    }
    if (!dptr->data[s_pos]) {
        dptr->data[s_pos] = kmalloc(quantum, GFP_KERNEL);
        if (!dptr->data[s_pos])
            goto out;
    }
    /* write only up to the end of this quantum */
    if (count > quantum - q_pos)
        count = quantum - q_pos;

    if (copy_from_user(dptr->data[s_pos]+q_pos, buf, count)) {
        retval = -EFAULT;
        goto out;
    }
    *f_pos += count;
    retval = count;

        /* update the size */
    if (dev->size < *f_pos)
        dev->size = *f_pos;

  out:
    up(&dev->sem);
    return retval;
}

//下面就是文件操作了
struct file_operations scull_fops = {
    .owner = THIS_MODULE,  //必须,
    .read = scull_read,   //在头文件里申明的的三个函数
    .write = scull_write,
    .open = scull_open,
    .release = scull_release,
};

/*
 * Finally, the module stuff
 */

/*
 * The cleanup function is used to handle initialization failures as well.
 * Thefore, it must be careful to work correctly even if some of the items
 * have not been initialized
 */

//下面就是卸载模块的啦
void scull_cleanup_module(void)
{
    int i;
    dev_t devno = MKDEV(scull_major, scull_minor);

    /* Get rid of our char dev entries */

   //??????????????????????????这条件判断是做什么用的???分配的内存大小??搞不太清
    if (scull_devices) {
        for (i = 0; i < scull_nr_devs; i++) {
            scull_trim(scull_devices + i);  //清下0
            cdev_del(&scull_devices[i].cdev);  //取消关联
        }
        kfree(scull_devices); //释放内存空间
    }

    /* cleanup_module is never called if registering failed */
    unregister_chrdev_region(devno, scull_nr_devs);//把设备注销了
}
/*
 * Set up the char_dev structure for this device.
 *///以下几行代码完成的是字符设备的注册工作。什么init啊,add啊,等早期也有字符设备注册的函数,int register_chrdev(),int unregister_chrdev()这是在2.4的内核中的老办法,2.6的内核中仍然保留。不过不建议使用。

static void scull_setup_cdev(struct scull_dev *dev, int index)

//传入的参数有设备结构体和次设备号
{
    int err, devno = MKDEV(scull_major, scull_minor + index);
    //合并一下,主设备号12位次设备号20位,这个宏就是一个移位操作
    cdev_init(&dev->cdev, &scull_fops);//初始化设备,把文件操作和设备关联起来。
    dev->cdev.owner = THIS_MODULE; //一定要,但都是一样的,呵呵
//    dev->cdev.ops = &scull_fops;  //其实cdev_init里最后要的一句就是这一句了,呵呵,
//cdev.h
    err = cdev_add (&dev->cdev, devno, 1);
    /* Fail gracefully if need be */
    if (err)
        printk(KERN_NOTICE "Error %d adding scull%d", err, index);
}


int scull_init_module(void)
{
    int result, i;
    dev_t dev = 0;

/*
 * Get a range of minor numbers to work with, asking for a dynamic
 * major unless directed otherwise at load time.
 *///以下是完成主设备号的分配(头文件里定义scull_major=0,条件不成立)

    if (scull_major) {      
        dev = MKDEV(scull_major, scull_minor);
        result = register_chrdev_region(dev, scull_nr_devs, "scull");//静态注册
    } else {
        result = alloc_chrdev_region(&dev, scull_minor, scull_nr_devs,
                "scull");//动态分配LDD3推荐使用的方法,不过很多的驱动程序都会按照上面的格式开写,
        scull_major = MAJOR(dev); //分配到的主设备号,回写一下
    }
    if (result < 0) {
        printk(KERN_WARNING "scull: can't get major %d\n", scull_major);
        return result;
    }

        /*
     * allocate the devices -- we can't have them static, as the number
     * can be specified at load time
     */

    scull_devices = kmalloc(scull_nr_devs * sizeof(struct scull_dev), GFP_KERNEL);  //内核空间里内存的分配函数get_free_page
    if (!scull_devices) {  //分配不成功
        result = -ENOMEM;
        goto fail; /* Make this more graceful *///退出了驱动里面goto用得好像是不少
    }
    memset(scull_devices, 0, scull_nr_devs * sizeof(struct scull_dev));//初始化为0,国嵌里说,为设备描述结构分配内存,而分配的时候 scull_nr_devs决定了它可以使用数组。

        /* Initialize each device. *///四个

//?????????????????????????????????????这里有一个疑问,就是初始化对像的时候用的是指针,这里怎么用了数组,请牛人指导一下//
    for (i = 0; i < scull_nr_devs; i++) {
        scull_devices[i].quantum = scull_quantum; //4000
        scull_devices[i].qset = scull_qset;   //1000
        init_MUTEX(&scull_devices[i].sem);   //初始化信号量
        scull_setup_cdev(&scull_devices[i], i);
    }

    return 0; /* succeed */

  fail:
    scull_cleanup_module();
    return result;
}

module_init(scull_init_module);//初始化
module_exit(scull_cleanup_module);//卸载

MODULE_AUTHOR("amwha");  //作者
MODULE_LICENSE("Dual BSD/GPL");//licence

 

下面是测试程序了,这个就不说了。都看得懂!

#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main()
{
    char buffer1[20]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
    char buffer2[20]={0};
    int sculltest;
    int code,i;
    
    sculltest = open("/dev/scull0",O_WRONLY );

    for ( i=20 ; i>0 ; i-=code)        {
        if ((code=write(sculltest , &buffer1[20-i] , i)) != i) printf("write error! code=%d \n",code);
        else printf("write ok! code=%d \n",code);
    }

    close(sculltest);


    sculltest = open("/dev/scull0",O_RDONLY );

    for ( i=20 ; i>0 ; i-=code)        {
        if ((code=read(sculltest , &buffer2[20-i] , i)) != i) printf("read error! code=%d \n",code);
        else printf("read ok! code=%d \n",code);
    }
    
    for(i=0;i<20;i+=5)
        printf("[%d]=%d [%d]=%d [%d]=%d [%d]=%d [%d]=%d\n",i,buffer2[i],i+1,buffer2[i+1],i+2,buffer2[i+2],i+3,buffer2[i+3],i+4,buffer2[i+4]);

    printf("\n");

    close(sculltest);
  exit(0);
}

 

以上是我对LDD3中scull的分析了,一定会有很多理解上的错误,请路过的高手指正。

struct semaphore {
    spinlock_t        lock;
    unsigned int        count;
    struct list_head    wait_list;
};


阅读(693) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~