Chinaunix首页 | 论坛 | 博客
  • 博客访问: 469136
  • 博文数量: 134
  • 博客积分: 3056
  • 博客等级: 中校
  • 技术积分: 1150
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-14 15:53
文章分类
文章存档

2013年(1)

2010年(133)

我的朋友

分类: LINUX

2010-08-03 01:43:06

1. 我的开发环境:
主机:ubuntu9.04+ARM交叉编译工具(arm-linux-gcc的版本是4.3.2)+IP地址为:192.168.1.222
目标板:mips开发板(系统是uclinux,内核linux-2.4.x)+uclinux安装了tftp命令+IP地址为:192.168.1.230

2. 提前说明:
Tekkaman NinjaLinux设备驱动程序学习(1)-字符设备驱动程序笔记已经非常详细了,基本上按照上面的走了一遍的。

3. scull.c源文件

#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/seq_file.h>
#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);

MODULE_AUTHOR("Michael Yao");
MODULE_LICENSE("Dual BSD/GPL");

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 */ /* scull_qset的个数 */
        if (dptr->data) {
            for (i = 0; i < qset; i++) /* 当前scull_qset(量子集)所含量子个数 */
                kfree(dptr->data[i]); /* 释放当前quantum(量子)的指向的空间 */
            kfree(dptr->data); /* 释放当前scull_qset的data指向的空间 */
            dptr->data = NULL; /* 杜绝野指针 */
        }
        next = dptr->next; /* 保存指向下一个scull_qset的指针,因为当前scull_qset会被释放掉,若不备份,就会对空指针进行引用 */
        kfree(dptr); /* 释放整个skull_qset */
    }
    dev->size = 0; /* 重新初始化,只有0个量子集: 存储的数据置零, 量子的大小, 量子集的个数,量子data域为空 */
    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 */

    /* scull_dev包含cdev结构,用定义在中的宏,我们通过它把stcull_dev结构中的cdev的字段提取出来,并用一个指针指向这个cdev字段 */
    dev = container_of(inode->i_cdev, struct scull_dev, cdev);
    filp->private_data = dev; /* for other methods */

    /* 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)) /* 用信号量进行并发控制 */
            return -ERESTARTSYS;
        scull_trim(dev); /* ignore errors */ /* 类似以只读方式打开文件,长度截断为零,scull_qset只有一个 */
        up(&dev->sem);
    }
    return 0; /* success */
}

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--) {    /* 如果所查找量子集大于当前量子集的数目,就分配(查找量子集-当前量子集)个scull_qset */
        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)
{
    struct scull_dev *dev = filp->private_data;    /* scull设备的指针被保存在file结构的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))
        return -ERESTARTSYS;
    if (*f_pos >= dev->size) /* 用户上次读写该文件的位置不超过dev->size, dev->size怎么算的? */
        goto out;
    if (*f_pos + count > dev->size)    /* 如果count大小不超过dev->size-*f_pos */
        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);
            cdev_del(&scull_devices[i].cdev);
        }
        kfree(scull_devices);
    }

    /* cleanup_module is never called if registering failed */
    unregister_chrdev_region(devno, scull_nr_devs);
    printk(KERN_NOTICE "unregister scull module!\n");

    /* and call the cleanup functions for friend devices */
    //scull_p_cleanup();

    //scull_access_cleanup();


}


/*
 * Set up the char_dev structure for this device.
 */

static void scull_setup_cdev(struct scull_dev *dev, int index)
{
    int err, devno = MKDEV(scull_major, scull_minor + index);
    
    cdev_init(&dev->cdev, &scull_fops);
    dev->cdev.owner = THIS_MODULE;
    dev->cdev.ops = &scull_fops;
    err = cdev_add (&dev->cdev, devno, 1);
    /* Fail gracefully if need be */
    if (err)
    {
        printk(KERN_NOTICE "Error %d adding scull%d", err, index);
    }
    else{
        printk(KERN_NOTICE "scull device setup success!\n");
    }
}


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.
 */

    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");
        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);
    if (!scull_devices) {
        result = -ENOMEM;
        goto fail; /* Make this more graceful */
    }
    memset(scull_devices, 0, scull_nr_devs * sizeof(struct scull_dev));

        /* Initialize each device. */
    for (i = 0; i < scull_nr_devs; i++) {
        scull_devices[i].quantum = scull_quantum;
        scull_devices[i].qset = scull_qset;
        init_MUTEX(&scull_devices[i].sem);
        scull_setup_cdev(&scull_devices[i], i);
    }

        /* At this point call the init function for any friend device */
    dev = MKDEV(scull_major, scull_minor + scull_nr_devs);
    //dev += scull_p_init(dev);

    //dev += scull_access_init(dev);


    printk(KERN_WARNING "scull module initialization success!\n");
    return 0; /* succeed */

  fail:
    scull_cleanup_module();
    return result;
}

module_init(scull_init_module);
module_exit(scull_cleanup_module);


需要注意的是 scull_major scull_minor scull_nr_devs scull_quantum scull_qset这五个变量为装载模块参数

与ldd3-samples/scull/main.c的差别请看
文件:scull.c.patch.tar.bz2
大小:5KB
下载:下载



4. scull.h源文件

/*
 * 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;



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 */
#define SCULL_IOC_MAGIC 'k'
/* Please use a different 8-bit number in your code */

#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_ */


与ldd3-samples/scull/scull.h的差别在于去掉scull_p_init(dev_t dev); scull_p_cleanup(void);
scull_access_init(dev_t dev); scull_access_cleanup(void); scull_llseek(struct file *filp, loff_t off, int whence); (struct inode *inode, struct file *filp,这几个函数的声明,同理scull.c中这几个函数的定义也得去了。

5. Makefile文件如下:

# Linux Device Driver Programming
# Michael Yao

# The path of kernel source code
KERNELDIR = /opt/friendly_ARM/mini2440/linux-2.6.29 #内核源码安装目录

#currnet path
PWD := $(shell pwd)

# Compiler
CROSS_COMPILE = /usr/local/arm/4.3.2/bin/arm-none-linux-gnueabi-
CC = $(CROSS_COMPILE)gcc
# Compilation Options
ifdef CONFIG_SMP
CFLAGS+=-D__SMP__ -DSMP
endif
CFLAGS +=

TARGET:=scull
obj-m := $(TARGET).o
#$(YOUR_TARGET)-objs := relied_source_file1.o relied_source_file2.o ... relied_source_fileN #N 是你的目标代码生成所依赖的源文件个数

all:
     $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
install:
     cp $(TARGET).ko /tftpboot        #已经安装并启动tftp服务
clean:
     rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions module*.* Module.*

.PHONY:all install clean



6. make 生成scull.ko文件

7. scull驱动程序的测试程序,scull_test.c文件如下:

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

int main()
{
    char write_buffer[20]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
    char read_buffer[20]={0};
    int sculltest;
    int read_or_write_success_nr,i;
    
    sculltest = open("/dev/scull0",O_WRONLY );
    if(sculltest == -1){
        printf("cannot open \"/dev/scull0\"!\n");
    }

    for ( i=20 ; i>0 ; i-=read_or_write_success_nr)        {
        if ((read_or_write_success_nr=write(sculltest , &write_buffer[20-i] , i)) != i) printf("write error! but the number of read success=%d \n",read_or_write_success_nr);
        else printf("write ok! the number of read success=%d \n",read_or_write_success_nr);
    }

    close(sculltest);


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

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

    printf("\n");

    close(sculltest);
  exit(0);
}


8. 交叉编译,生成scull_test文件

9. 在mini2440终端里用tftp传送6,8步生成的scull.ko和scull_test文件

10. 首先,按默认参数装载模块

[root@FriendlyARM 2.6.29.4-FriendlyARM]# insmod scull.ko
scull device setup
scull device setup
scull device setup
scull device setup
scull module initialization


,然后运行./scull_test

[root@FriendlyARM 2.6.29.4-FriendlyARM]# ./scull_test
write ok! write the number of read success=20
read
ok! the number of write success=20
[0]=0 [1]=1 [2]=2 [3]=3 [4]=4
[5]=5 [6]=6 [7]=7 [8]=8 [9]=9
[10]=10 [11]=11 [12]=12 [13]=13 [14]=14
[15]=15 [16]=16 [17]=17 [18]=18 [19]=19


11. 在指定量子大小为6,scull_quantum=6 数装载模块(在进行此次装载前得现卸载模块)

[root@FriendlyARM 2.6.29.4-FriendlyARM]# ./scull_test

write
error! but the number of read success=6
write
error! but the number of read success=6
write
error! but the number of read success=6
write ok! the number of read success=2
read
error! the number of write success=6
read
error! the number of write success=6
read
error! the number of write success=6
read ok! the number of write success=2
[0]=0 [1]=1 [2]=2 [3]=3 [4]=4
[5]=5 [6]=6 [7]=7 [8]=8 [9]=9
[10]=10 [11]=11 [12]=12 [13]=13 [14]=14
[15]=15 [16]=16 [17]=17 [18]=18 [19]=19


说明: 在scull_test读写驱动程序时,如果读写的最大个数超过限制,则按驱动程序默认的buffer的大小也就是quantum的大小进行读写,所以前三次读写会有错误,而最后一次读写的时候,循环变量i=2,小于6,所以读写正确。

12. 在指定量子大小为6,scull_quantum=6,量子集合的数目为1,scull_qset=1数装载模块(在进行此次装载前得现卸载模块),1*6<20,因为在scull.c中有这样的函数

scull_follow()


能够保证,即使定位的量子集“或”(也可以是“和”)量子不够即超出,但源码保证仍能正确使用。

[root@FriendlyARM 2.6.29.4-FriendlyARM]# ./scull_test

write but the number of read success=6
write but the number of read success=6
write but the number of read success=6
write the number of read success=2
read the number of write success=6
read the number of write success=6
read the number of write success=6
read the number of write success=2
[0]=0 [1]=1 [2]=2 [3]=3 [4]=4
[5]=5 [6]=6 [7]=7 [8]=8 [9]=9
[10]=10 [11]=11 [12]=12 [13]=13 [14]=14
[15]=15 [16]=16 [17]=17 [18]=18 [19]=19


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