《linux设备驱动开发详解》笔记——6字符设备驱动

 

 

6.1 字符设备驱动结构

先看看字符设备驱动的架构:

6.1.1 cdev

  cdev结构体是字符设备的核心数据结构,用于描述一个字符设备,cdev定义如下:

  

#include <linux/cdev.h>

struct cdev {
    struct kobject kobj;
    struct module *owner;
    const struct file_operations *ops;  // 文件操作结构体
    struct list_head list;
    dev_t dev;                // 设备号,12bit主设备号+20bit次设备号
    unsigned int count;           // 设备个数
};

设备号相关宏定义:
MAJOR(dev);      // 获取主设备号
MINOR(dev);      // 获取从设备号
MKDEV(major,minor); // 生产设备号 

cdev相关函数接口:

void cdev_init(struct cdev *, const struct file_operations *);  // 将cdev与file_operations挂钩
struct cdev *cdev_alloc(void);
void cdev_put(struct cdev *p);
int cdev_add(struct cdev *, dev_t, unsigned);            // 向系统中添加cdev,同时将cdev与设备号挂钩(设备号和设备名称是文件系统的组成部分,与用户交互的桥梁)
                                                                 // 注意判断返回值, A negative error code is returned on failure.返回1个负数
void cdev_del(struct cdev *);                     //  从系统中删除cdev

6.1.2 设备号

注册设备号和释放设备号,设备号也是系统资源,需要注意在注销函数时释放:

#include <linux/fs.h>

/**
* alloc_chrdev_region() - register a range of char device numbers
* @dev: output parameter for first assigned number
* @baseminor: first of the requested range of minor numbers
* @count: the number of minor numbers required
* @name: the name of the associated device or driver
*
* Allocates a range of char device numbers. The major number will be
* chosen dynamically, and returned (along with the first minor number)
* in @dev. Returns zero or a negative error code.
*/
int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,const char *name);  // 动态分配,并注册设备号

/**
* register_chrdev_region() - register a range of device numbers
* @from: the first in the desired range of device numbers; must include the major number.
* @count: the number of consecutive device numbers required
* @name: the name of the device or driver.
*
* Return value is zero on success, a negative error code on failure.
*/
int register_chrdev_region(dev_t from, unsigned count, const char *name);    // 将已知的设备号注册到系统中

/**
* unregister_chrdev_region() - return a range of device numbers
* @from: the first in the range of numbers to unregister
* @count: the number of device numbers to unregister
*
* This function will unregister a range of @count device numbers,
* starting with @from. The caller should normally be the one who
* allocated those numbers in the first place...
*/
void unregister_chrdev_region(dev_t from, unsigned count);  // 注销设备号

6.1.3 file_operations

   file_operations是字符设备驱动设计的主要内容, 应用程序进行open、close、write、read等操作时,通过文件系统简介调用file_operations里驱动实现的函数接口。

 

#include <linux/fs.h>

struct file_operations {
    struct module *owner;  // module是内核表示模块的单元,THIS_MODULE表示当前模块,insmod时内核创建一个module结构体
    loff_t (*llseek) (struct file *, loff_t, int);  // 修改文件当前读写位置,返回新位置,出错时返回-1
    ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);  // 读数据,与应用程序的read和fread对应
    ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);  // 写数据,与应用程序的write和fwrite对应;若未实现,应用调用时返回-EINVAL
    ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
    ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
    int (*iterate) (struct file *, struct dir_context *);
    unsigned int (*poll) (struct file *, struct poll_table_struct *);  // 多路复用
    long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); // 对应应用程序的ioctl
    long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
    int (*mmap) (struct file *, struct vm_area_struct *);  // 帧缓存是有用,应用映射后可直接访问内存空间,与应用程序的mmap对应。若驱动未实现时如果应用调用,返回-ENODEV
    int (*open) (struct inode *, struct file *);    // 若未定义,应用调用时返回成功
    int (*flush) (struct file *, fl_owner_t id);
    int (*release) (struct inode *, struct file *);
    int (*fsync) (struct file *, loff_t, loff_t, int datasync);
    int (*aio_fsync) (struct kiocb *, int datasync);
    int (*fasync) (int, struct file *, int);
    int (*lock) (struct file *, int, struct file_lock *);
    ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
    unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
    int (*check_flags)(int);
    int (*flock) (struct file *, int, struct file_lock *);
    ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
    ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
    int (*setlease)(struct file *, long, struct file_lock **);
    long (*fallocate)(struct file *file, int mode, loff_t offset,
              loff_t len);
    int (*show_fdinfo)(struct seq_file *m, struct file *f);
};

【注意】
各结构体成员的参数是struct file和struct inode,而不是应用程序里的文件描述符fd;

 

6.1.4 生成设备文件

  原书中没有介绍如何在/dev目录下自动生成设备文件,可使用如下函数实现

#include <linux/device.h>

  #define class_create(owner, name)
  ({ \
    static struct lock_class_key __key; \
    __class_create(owner, name, &__key); \
  })

  /**
  * class_create - create a struct class structure
  * @owner: pointer to the module that is to "own" this struct class
  * @name: pointer to a string for the name of this class.
  * @key: the lock_class_key for this class; used by mutex lock debugging
  *
  * This is used to create a struct class pointer that can then be used
  * in calls to device_create().  
  *
  * Returns &struct class pointer on success, or ERR_PTR() on error.
  *
  * Note, the pointer created here is to be destroyed when finished by
  * making a call to class_destroy().
  */
  struct class *__class_create(struct module *owner, const char *name,struct lock_class_key *key)

/**
 * device_create - creates a device and registers it with sysfs
 * @class: pointer to the struct class that this device should be registered to
 * @parent: pointer to the parent struct device of this new device, if any
 * @devt: the dev_t for the char device to be added
 * @drvdata: the data to be added to the device for callbacks
 * @fmt: string for the device's name
 *
 * This function can be used by char device classes.  A struct device
 * will be created in sysfs, registered to the specified class.
 *
 * A "dev" file will be created, showing the dev_t for the device, if
 * the dev_t is not 0,0.
 * If a pointer to a parent struct device is passed in, the newly created
 * struct device will be a child of that device in sysfs.
 * The pointer to the struct device will be returned from the call.
 * Any further sysfs files that might be required can be created using this
 * pointer.
 *
 * Returns &struct device pointer on success, or ERR_PTR() on error.
 *
 * Note: the struct class passed to this function must have previously
 * been created with a call to class_create().
 */
struct device *device_create(struct class *class, struct device *parent, dev_t devt, void *drvdata, const char *fmt, ...)

/**
* device_destroy - removes a device that was created with device_create()
* @class: pointer to the struct class that this device was registered with
* @devt: the dev_t of the device that was previously registered
*
* This call unregisters and cleans up a device that was created with a
* call to device_create().
*/
void device_destroy(struct class *class, dev_t devt);  

 

 

!!!6.1.5 字符设备驱动结构

6.1.4.1 模块加载和卸载

 

#include <linux/cdev.h>  // cdev
#include <linux/fs.h>   // file_operations
#include <linux/device.h> // class,device

/*
设备结构体 */ struct xxx_dev_t {
  struct cdev cdev;    // 一般cdev结构体不进行动态分配,直接定义在驱动程序里
  struct class class;   // 定义class,为了生成/dev/设备文件
  ....
}xxx_dev; /* 驱动模块加载函数 */ static int __init xxx_init( void )
{
  ...
  cdev_init( &xxx_dev.cdev, &xxx_fops );  // 建立cdev与file_operations的关联
  xxx_dev.cdev.owner = THIS_MODULE;

  /* 注册设备号 */
  if( xxx_major ){ 
    register_chrdev_region( xxx_dev_no, 1, DEV_NAME );
  }
  else{
    alloc_chrdev_region( &xxx_dev_no,0,1,DEV_NAME );
  }
   
  ret = cdev_add( &xxx_dev.cdev, xxx_dev_no,1 );   // 注册字符设备
  if(ret){
    // err proccess  
  }
 
  /* 设备文件相关 */
  xxx_dev.class = class_create( THIS_MODULE, DEV_NAME );        // 创建class
device_create( &xxx_dev.class, NULL, xxx_dev_no,NULL, DEV_NAME );  // 创建device,会在/dev目录下生成名字为DEV_NAME的设备文件
  ...
} /* 驱动模块卸载函数 */
static void __exit xxx_exit( void )
{
  unregister_chrdev_region( xxx_dev_no, 1); // 释放占用的设备号
  cdev_del( &xxx_dev.cdev );           // 注销字符设备
}

module_init(xxx_init);
module_eixt(xxx_exit);

 【注意】

  • init和exit函数的格式,static int __init xxx_init( void ),否则

6.1.4.2 file_operations成员函数

   大多数驱动都要实现read、write、ioctl等函数
  【注意】:

  1.参数中的*f_pos实际应该就是指向filp->f_pos的指针,由文件系统统一管理的偏移,驱动中read/write要直接使用这个偏移,并在完成操作后更新这个指针;

  2.llseek的参数中没有*f_pos,直接操作filp->f_pos即可。

struct file_operations xxx_fops = {
  .owner = THIS_MODULE,
  .read = xxx_read,
  .write = xxx_write,
  .unlocked_ioctl = xxx_ioctl,
  ...
}

ssize_t xxx_read( struct file * filp, char __user *buf, size_t count, loff_t * f_pos )
{
  ...
  copy_to_user( buf, ..., ...);
  ...
}
ssize_t xxx_write( struct file * filp, char __user *buf, size_t count, loff_t * f_pos )
{
  ...
  copy_from_user( buf, ..., ...);
  ...
}

long xxx_ioctrl( struct file * filp, unsigned int cmd, unsigned long arg )
{
  ...
  switch( cmd ){
  case XXX_CMD1:
    ...
    break;
  case XXX_CMD2:  
    ...
    break;
  default:
    // 不支持的命令
    return -ENOTTY;
  }
  
  return 0;
}

 

  【注意】:

  1.读写函数的参数中,buf是用户空间的,处于内核态的驱动不应该直接读写,应该调用特定接口,如下:

  2. 注意copy_to/from_user的参数位置,都是从第2个参数拷贝到第一个参数,有点类似memcpy,别搞反了!

  3. 注意检查copy函数的返回值,返回值n是剩余的字节数,正常时应该为0

#include <linux/uaccess.h>    // 内部包含 arch/arm/inculde/asm/uaccess.h,看来除了linux源码根目录的include目录,arch/arm/include也是驱动搜索的头文件目录

static
inline unsigned long __must_check copy_from_user(void *to, const void __user *from, unsigned long n) { if (access_ok(VERIFY_READ, from, n))    // 先检查是否传入的缓冲区是否属于用户空间 n = __copy_from_user(to, from, n); else /* security hole - plug it */ memset(to, 0, n); return n; } static inline unsigned long __must_check copy_to_user(void __user *to, const void *from, unsigned long n) { if (access_ok(VERIFY_WRITE, to, n)) n = __copy_to_user(to, from, n); return n; }

对于简单类型,如char,int,long可以使用简单的函数进行复制,如下:

  #define get_user(x,p) __get_user(x,p)    // x是变量,p是用户空间地址, x = *p
  #define put_user(x,p) __put_user(x,p)    // *p = x

  #define __get_user(x,ptr) \
  ({ \
    long __gu_err = 0; \
    __get_user_err((x),(ptr),__gu_err); \
    __gu_err; \
  })

  #define __put_user(x,ptr) \
  ({ \
    long __pu_err = 0; \
    __put_user_err((x),(ptr),__pu_err); \
    __pu_err; \
  })

 

 

6.1.4.3 ioctl()命令

  命令最好能区分不同设备,如果所有驱动都采用1,2,3这类命令,会造成命令码污染。linux有一套统一的ioctl命令生成的方式,最好使用该机制。  强制使用土鳖的1/2/3,没不会有啥大的问题。

设备类型type,是1个幻数,应参考内核中的ioctl-number.txt,不要与已使用的冲突;

序列号nr,8bit;

方向dir,_IOC_NONE( 无数据传输) 、_IOC_READ( 读) 、 _IOC_WRITE( 写) 和_IOC_READ|_IOC_WRITE( 双向) 。 数据传送的方向是从应用程序的角度来看的;

数据尺寸size,13~14bit;

用下述宏来生成命令:

#include <linux/ioctl.h>  // 实际是 include/uapi/linux/ioctl.h,看来uapi也是驱动搜索的目录之一

#define
_IO(type,nr) _IOC(_IOC_NONE,(type),(nr),0) #define _IOR(type,nr,size) _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size))) #define _IOW(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size))) #define _IOWR(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))

// 例如
#define GLOBALMEM_CMD_CLR  _IO('g',0)

 

6.2 globalmem设备驱动示例

   这本书使用globalmem模拟一种物理设备,所有的驱动都在这个设备上进行实例操作。

  【注意】

   1.模块编译的Makefile文件,首字母必须大写,否则make modules找不到Makefile文件,貌似是make modules时写死了,只认"Makefile"字样的文件;

6.2.1 单一设备

#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <asm/uaccess.h>


#define DEV_NAME    "globalmem"

#define GLOBALMEN_LEN    1024

struct globalmem_dev_t
{
    struct cdev cdev;
    struct class * class;
    dev_t  dev_no;

    char buf[GLOBALMEN_LEN];
}globalmem_dev;


int globalmem_open(struct inode * inode, struct file * filp)
{
    filp->private_data = &globalmem_dev;
    return 0;
}

ssize_t globalmem_read(struct file *filp, char __user * buf, size_t len, loff_t * pos)
{
    struct globalmem_dev_t * globalmem_devp;
    size_t len_rd;

    globalmem_devp = filp->private_data;
    if( (*pos)>GLOBALMEN_LEN )
        return 0;

    if( ( (*pos)+len) > GLOBALMEN_LEN  )
        len_rd = GLOBALMEN_LEN-(*pos);

    else
        len_rd = len;

    if( copy_to_user(buf,&globalmem_devp->buf[(*pos)],len_rd) )
        return -EFAULT;
    printk("read %d bytes from %d pos\r\n",(int)len_rd,(int)*pos);
    *pos += len_rd;
    return len_rd;
}


ssize_t globalmem_write (struct file *filp, const char __user *buf, size_t len, loff_t *pos)
{
    struct globalmem_dev_t * globalmem_devp;
    size_t len_wr;

    globalmem_devp = filp->private_data;
    if( (*pos)>GLOBALMEN_LEN )
        return 0;

    if( ((*pos)+len) > GLOBALMEN_LEN  )
        len_wr = GLOBALMEN_LEN-(*pos);

    else
        len_wr = len;
    if( copy_from_user(&globalmem_devp->buf[(*pos)],buf,len_wr) )
        return -EFAULT;
    printk("write %d bytes from %d pos\r\n",(int)len_wr,(int)*pos);
    *pos += len_wr;
    return len_wr;
}


loff_t globalmem_llseek(struct file *filp, loff_t offset, int whence )
{
    loff_t ret;    // 注意要有返回值

    switch(whence){
    case SEEK_SET:
        if( offset < 0 )
            return -EINVAL;
        if( offset > GLOBALMEN_LEN )
            return -EINVAL;
        filp->f_pos = offset;
        ret = filp->f_pos;    
        break;
    case SEEK_CUR:
        if((filp->f_pos+offset)< 0 )
            return -EINVAL;
        if((filp->f_pos+offset)> GLOBALMEN_LEN )
            return -EINVAL;
        filp->f_pos += offset;
        ret = filp->f_pos;
        break;
    case SEEK_END:
        if((filp->f_pos+offset)< 0 )
            return -EINVAL;
        if((filp->f_pos+offset) > GLOBALMEN_LEN )
            return -EINVAL;
        filp->f_pos += (offset+GLOBALMEN_LEN);
        ret = filp->f_pos;
        break;
    default:
        return -EINVAL;
        break;
    }
    
    return ret;
}


struct file_operations globalmem_fops = {
    .owner = THIS_MODULE,
    .open = globalmem_open,
    .read = globalmem_read,
    .write = globalmem_write,
    .llseek = globalmem_llseek,
};

static int __init globalmem_init( void )
{
    int ret;

    printk("enter globalmem_init()\r\n");
    
    cdev_init(&globalmem_dev.cdev,&globalmem_fops);
    globalmem_dev.cdev.owner=THIS_MODULE;

    if( (ret=alloc_chrdev_region(&globalmem_dev.dev_no,0,1,DEV_NAME))<0 )
    {
        printk("alloc_chrdev_region err.\r\n");    
        return ret;
    }
    ret = cdev_add(&globalmem_dev.cdev,globalmem_dev.dev_no,1);
    if( ret )
    {
        printk("cdev_add err.\r\n");    
        return ret;
    }

    /*
         * $ sudo insmod globalmem.ko    如果使用class_create,insmod时会报错,dmesg查看内核log信息发现找不到class相关函数
     *   insmod: ERROR: could not insert module globalmem.ko: Unknown symbol in module
     *   $ dmesg   
     *    [ 5495.606920] globalmem: Unknown symbol __class_create (err 0)
     *    [ 5495.606943] globalmem: Unknown symbol class_destroy (err 0)
     *    [ 5495.607027] globalmem: Unknown symbol device_create (err 0)
     */    

    globalmem_dev.class = class_create( THIS_MODULE, DEV_NAME );
    device_create(globalmem_dev.class,NULL,globalmem_dev.dev_no,NULL,DEV_NAME);

    /* init mem and pos */
    memset(globalmem_dev.buf,0,GLOBALMEN_LEN);
    return 0;
}


static void __exit globalmem_exit( void )
{
    unregister_chrdev_region(globalmem_dev.dev_no, 1);
    cdev_del(&globalmem_dev.cdev);
    class_destroy(globalmem_dev.class);
}


module_init(globalmem_init);
module_exit(globalmem_exit);

MODULE_LICENSE("GPL");    // 不加此声明,会报上述Unknown symbol问题


$ echo "hello world" > /dev/globalmem
$ cat /dev/globalmem
hello world

另一个终端监视printk的显示(用dmesg脚本)

[ 3158.660191] enter globalmem_init()
[ 3231.664661] open filp->private_data = 0xc0270480
[ 3231.664669] open filp->f_pos = 0
[ 3231.717074] write 4 bytes from 0 pos
[ 3598.704506] open filp->private_data = 0xc0270480
[ 3598.704519] open filp->f_pos = 0
[ 3598.704547] read 1024 bytes from 0 pos
[ 3598.707040] read 0 bytes from 1024 pos

 

6.2.2 支持N个设备

原则:cdev和file_operations本质上与驱动程序对应,理论上只需要1个就可以。同理,class定义设备的一种类型, 也不用定义多个。  具体设备(多个globalmem的buf)是多个,驱动程序要想办法把驱动文件file、inode与设备对应上就可以了。

上述原则与书中测试用例不太一致,书中定义了多个cdev。

同一套驱动需要支持多个同类设备,对上述驱动进行简单改造:

 【注意】exit时要把init时建立的文件都销毁,漏掉了很容易引发问题。一开始忘记了device_destroy,导致rmmod后再insmod出问题,因为没有卸干净,

/*
    一套驱动对应多个设备的方法,试着采用驱动和设备分离的思想
 */


#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <asm/uaccess.h>


#define DEV_NAME    "globalmem"
#define DEV_NUM        3
#define GLOBALMEN_LEN    1024

// 具体设备
struct globalmem_dev_t
{
    char buf[GLOBALMEN_LEN];
};

// 驱动
struct globalmem_driver_t
{
    struct cdev cdev;
    struct class * class;
};


struct globalmem_dev_t globalmem_dev[DEV_NUM];
struct globalmem_driver_t globalmem_driver;
dev_t  globalmem_devno;

int globalmem_open(struct inode * inode, struct file * filp)
{
    unsigned int minor = iminor(inode);  // 完成文件与设备的对应

    filp->private_data = &globalmem_dev[minor];
    return 0;
}

ssize_t globalmem_read(struct file *filp, char __user * buf, size_t len, loff_t * pos)
{
    struct globalmem_dev_t * globalmem_devp;
    size_t len_rd;

    globalmem_devp = filp->private_data;
    if( (*pos)>GLOBALMEN_LEN )
        return 0;

    if( ( (*pos)+len) > GLOBALMEN_LEN  )
        len_rd = GLOBALMEN_LEN-(*pos);

    else
        len_rd = len;

    if( copy_to_user(buf,&globalmem_devp->buf[(*pos)],len_rd) )
        return -EFAULT;
    printk("read %d bytes from %d pos\r\n",(int)len_rd,(int)*pos);
    *pos += len_rd;
    return len_rd;
}


ssize_t globalmem_write (struct file *filp, const char __user *buf, size_t len, loff_t *pos)
{
    struct globalmem_dev_t * globalmem_devp;
    size_t len_wr;

    globalmem_devp = filp->private_data;
    if( (*pos)>GLOBALMEN_LEN )
        return 0;

    if( ((*pos)+len) > GLOBALMEN_LEN  )
        len_wr = GLOBALMEN_LEN-(*pos);

    else
        len_wr = len;
    if( copy_from_user(&globalmem_devp->buf[(*pos)],buf,len_wr) )
        return -EFAULT;
    printk("write %d bytes from %d pos\r\n",(int)len_wr,(int)*pos);
    *pos += len_wr;
    return len_wr;
}


loff_t globalmem_llseek(struct file *filp, loff_t offset, int whence )
{
    loff_t ret;    // 注意要有返回值

    switch(whence){
    case SEEK_SET:
        if( offset < 0 )
            return -EINVAL;
        if( offset > GLOBALMEN_LEN )
            return -EINVAL;
        filp->f_pos = offset;
        ret = filp->f_pos;    
        break;
    case SEEK_CUR:
        if((filp->f_pos+offset)< 0 )
            return -EINVAL;
        if((filp->f_pos+offset)> GLOBALMEN_LEN )
            return -EINVAL;
        filp->f_pos += offset;
        ret = filp->f_pos;
        break;
    case SEEK_END:
        if((filp->f_pos+offset)< 0 )
            return -EINVAL;
        if((filp->f_pos+offset) > GLOBALMEN_LEN )
            return -EINVAL;
        filp->f_pos += (offset+GLOBALMEN_LEN);
        ret = filp->f_pos;
        break;
    default:
        return -EINVAL;
        break;
    }
    
    return ret;
}


struct file_operations globalmem_fops = {
    .owner = THIS_MODULE,
    .open = globalmem_open,
    .read = globalmem_read,
    .write = globalmem_write,
    .llseek = globalmem_llseek,
};

static int __init globalmem_init( void )
{
    int ret;
    int index;
    dev_t dev_no;
    int major;
    char name[16];
    

    printk("enter globalmem_init()\r\n");
    if( (ret=alloc_chrdev_region(&globalmem_devno,0,DEV_NUM,DEV_NAME))<0 )
    {
        printk("alloc_chrdev_region err.\r\n");    
        return ret;
    }
    else
        printk("alloc %d mem,first dev_no is %d.\r\n",DEV_NUM,(int)globalmem_devno);    
    major = MAJOR(globalmem_devno);
    
    cdev_init(&globalmem_driver.cdev,&globalmem_fops);
    globalmem_driver.cdev.owner=THIS_MODULE;

    
    ret = cdev_add(&globalmem_driver.cdev,globalmem_devno,DEV_NUM);
    if( ret )
    {
        printk("cdev_add err.\r\n");    
        return ret;
    }
    globalmem_driver.class = class_create( THIS_MODULE, DEV_NAME );


    for( index=0;index<DEV_NUM;index++ ){
        dev_no = MKDEV( major, index );
        snprintf(name,16,DEV_NAME"%d",index);
        printk("name:%s,dev_no %d.\r\n",name,dev_no);    
        device_create(globalmem_driver.class,NULL,dev_no,NULL,DEV_NAME"%d",index );
        /* init mem and pos */
        memset(globalmem_dev[index].buf,0,GLOBALMEN_LEN);
    }
    return 0;
}


static void __exit globalmem_exit( void )
{
    int index;
    dev_t dev_no;

    printk("enter globalmem_exit(),dev_no %d\r\n",globalmem_devno);
    unregister_chrdev_region(globalmem_devno, DEV_NUM);
    cdev_del(&globalmem_driver.cdev);
    for( index=0;index<DEV_NUM;index++){
        dev_no = MKDEV(MAJOR(globalmem_devno),index);
        device_destroy(globalmem_driver.class,dev_no);    // 注意注销时与init时建立的文件都要消除,否则会出问题
    }
    class_destroy(globalmem_driver.class);
    
}


module_init(globalmem_init);
module_exit(globalmem_exit);

MODULE_LICENSE("GPL");    

$ echo "mem0" > /dev/globalmem0
$ echo "mem1" > /dev/globalmem1
$ echo "mem2" > /dev/globalmem2
$ cat /dev/globalmem0
mem0
$ cat /dev/globalmem1
mem1
$ cat /dev/globalmem2
mem2

 

 

6.3 内核驱动的调试,printk

【问题1】 printk在ubuntu的shell终端里无法显示

  printk打印的是控制台,也就是/dev/console。而图形界面中的终端,其实是把stdin,stdout,stderr三个文件重定向了一下。所以printk是无法再图形界面中的终端中显示的,当然可以再/var/log/syslog或者用dmesg查看。

  在嵌入式设备中,其中初始化的时候把stdin,stdout,stderr均定向到了/dev/console中(main.c中的init_post函数里)。一般的情况下控制台就是串口。

【问题2】 ubuntu里怎么显示printk

  ubuntu这类的发行版linux,有专门的守护进程负责记录log信息,有些log信息里就保存着printk的打印信息(内核信息),可以用dmesg命令或者查看/proc/kmsg文件

  在一个单独的窗口里,可以输入如下命令,单独监测内核的日志文件,从而监控printk信息

// 方法1:
sudo cat /proc/kmsg    // 阻塞显示内核信息,只显示增量信息,感觉没有dmesg好用,会漏一些信息

// 方法2:可运行如下脚本,定期用dmesg查看内核信息
while true
do
  sudo dmesg -c  // dmesg不是增量显示,会打印所有的存量信息,所以用-c,显示后删除
  sleep 1      
done

 

6.4 错误类型说明

 驱动中注意使用这些标准的错误返回码

// base error
#define
EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Argument list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ #define ENOMEM 12 /* Out of memory */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define ENOTBLK 15 /* Block device required */ #define EBUSY 16 /* Device or resource busy */ #define EEXIST 17 /* File exists */ #define EXDEV 18 /* Cross-device link */ #define ENODEV 19 /* No such device */ #define ENOTDIR 20 /* Not a directory */ #define EISDIR 21 /* Is a directory */ #define EINVAL 22 /* Invalid argument */ #define ENFILE 23 /* File table overflow */ #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a typewriter */ #define ETXTBSY 26 /* Text file busy */ #define EFBIG 27 /* File too large */ #define ENOSPC 28 /* No space left on device */ #define ESPIPE 29 /* Illegal seek */ #define EROFS 30 /* Read-only file system */ #define EMLINK 31 /* Too many links */ #define EPIPE 32 /* Broken pipe */ #define EDOM 33 /* Math argument out of domain of func */ #define ERANGE 34 /* Math result not representable */
// not base error #define EDEADLK 35 /* Resource deadlock would occur */ #define ENAMETOOLONG 36 /* File name too long */ #define ENOLCK 37 /* No record locks available */ #define ENOSYS 38 /* Function not implemented */ #define ENOTEMPTY 39 /* Directory not empty */ #define ELOOP 40 /* Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /* Operation would block */ #define ENOMSG 42 /* No message of desired type */ #define EIDRM 43 /* Identifier removed */ #define ECHRNG 44 /* Channel number out of range */ #define EL2NSYNC 45 /* Level 2 not synchronized */ #define EL3HLT 46 /* Level 3 halted */ #define EL3RST 47 /* Level 3 reset */ #define ELNRNG 48 /* Link number out of range */ #define EUNATCH 49 /* Protocol driver not attached */ #define ENOCSI 50 /* No CSI structure available */ #define EL2HLT 51 /* Level 2 halted */ #define EBADE 52 /* Invalid exchange */ #define EBADR 53 /* Invalid request descriptor */ #define EXFULL 54 /* Exchange full */ #define ENOANO 55 /* No anode */ #define EBADRQC 56 /* Invalid request code */ #define EBADSLT 57 /* Invalid slot */ #define EDEADLOCK EDEADLK #define EBFONT 59 /* Bad font file format */ #define ENOSTR 60 /* Device not a stream */ #define ENODATA 61 /* No data available */ #define ETIME 62 /* Timer expired */ #define ENOSR 63 /* Out of streams resources */ #define ENONET 64 /* Machine is not on the network */ #define ENOPKG 65 /* Package not installed */ #define EREMOTE 66 /* Object is remote */ #define ENOLINK 67 /* Link has been severed */ #define EADV 68 /* Advertise error */ #define ESRMNT 69 /* Srmount error */ #define ECOMM 70 /* Communication error on send */ #define EPROTO 71 /* Protocol error */ #define EMULTIHOP 72 /* Multihop attempted */ #define EDOTDOT 73 /* RFS specific error */ #define EBADMSG 74 /* Not a data message */ #define EOVERFLOW 75 /* Value too large for defined data type */ #define ENOTUNIQ 76 /* Name not unique on network */ #define EBADFD 77 /* File descriptor in bad state */ #define EREMCHG 78 /* Remote address changed */ #define ELIBACC 79 /* Can not access a needed shared library */ #define ELIBBAD 80 /* Accessing a corrupted shared library */ #define ELIBSCN 81 /* .lib section in a.out corrupted */ #define ELIBMAX 82 /* Attempting to link in too many shared libraries */ #define ELIBEXEC 83 /* Cannot exec a shared library directly */ #define EILSEQ 84 /* Illegal byte sequence */ #define ERESTART 85 /* Interrupted system call should be restarted */ #define ESTRPIPE 86 /* Streams pipe error */ #define EUSERS 87 /* Too many users */ #define ENOTSOCK 88 /* Socket operation on non-socket */ #define EDESTADDRREQ 89 /* Destination address required */ #define EMSGSIZE 90 /* Message too long */ #define EPROTOTYPE 91 /* Protocol wrong type for socket */ #define ENOPROTOOPT 92 /* Protocol not available */ #define EPROTONOSUPPORT 93 /* Protocol not supported */ #define ESOCKTNOSUPPORT 94 /* Socket type not supported */ #define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ #define EPFNOSUPPORT 96 /* Protocol family not supported */ #define EAFNOSUPPORT 97 /* Address family not supported by protocol */ #define EADDRINUSE 98 /* Address already in use */ #define EADDRNOTAVAIL 99 /* Cannot assign requested address */ #define ENETDOWN 100 /* Network is down */ #define ENETUNREACH 101 /* Network is unreachable */ #define ENETRESET 102 /* Network dropped connection because of reset */ #define ECONNABORTED 103 /* Software caused connection abort */ #define ECONNRESET 104 /* Connection reset by peer */ #define ENOBUFS 105 /* No buffer space available */ #define EISCONN 106 /* Transport endpoint is already connected */ #define ENOTCONN 107 /* Transport endpoint is not connected */ #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ #define ETOOMANYREFS 109 /* Too many references: cannot splice */ #define ETIMEDOUT 110 /* Connection timed out */ #define ECONNREFUSED 111 /* Connection refused */ #define EHOSTDOWN 112 /* Host is down */ #define EHOSTUNREACH 113 /* No route to host */ #define EALREADY 114 /* Operation already in progress */ #define EINPROGRESS 115 /* Operation now in progress */ #define ESTALE 116 /* Stale file handle */ #define EUCLEAN 117 /* Structure needs cleaning */ #define ENOTNAM 118 /* Not a XENIX named type file */ #define ENAVAIL 119 /* No XENIX semaphores available */ #define EISNAM 120 /* Is a named type file */ #define EREMOTEIO 121 /* Remote I/O error */ #define EDQUOT 122 /* Quota exceeded */ #define ENOMEDIUM 123 /* No medium found */ #define EMEDIUMTYPE 124 /* Wrong medium type */ #define ECANCELED 125 /* Operation Canceled */ #define ENOKEY 126 /* Required key not available */ #define EKEYEXPIRED 127 /* Key has expired */ #define EKEYREVOKED 128 /* Key has been revoked */ #define EKEYREJECTED 129 /* Key was rejected by service */ /* for robust mutexes */ #define EOWNERDEAD 130 /* Owner died */ #define ENOTRECOVERABLE 131 /* State not recoverable */ #define ERFKILL 132 /* Operation not possible due to RF-kill */ #define EHWPOISON 133 /* Memory page has hardware error */

 

6.5 总结

总结一下应注意的事项:

1.write和read的pos指针的含义,llseek的f_pos的处理
2.copy_to/from_user的参数顺序
3.printk的查看方法
4.没有注册license引发的问题,MODULE_LICENSE("GPL")
5.错误类型及返回
6.使用私有数据的方法
7.一套驱动对应多个设备的方法

posted @ 2017-04-26 16:36  liuwanpeng  阅读(1306)  评论(0编辑  收藏  举报