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, , 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 ;
} 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 ; 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 ; 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 < )
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)< )
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)< )
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,,,DEV_NAME))< )
{
printk("alloc_chrdev_region err.\r\n");
return ret;
}
ret = cdev_add(&globalmem_dev.cdev,globalmem_dev.dev_no,);
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,,GLOBALMEN_LEN);
return ;
} static void __exit globalmem_exit( void )
{
unregister_chrdev_region(globalmem_dev.dev_no, );
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 ;
} 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 ; 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 ; 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 < )
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)< )
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)< )
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[]; printk("enter globalmem_init()\r\n");
if( (ret=alloc_chrdev_region(&globalmem_devno,,DEV_NUM,DEV_NAME))< )
{
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=;index<DEV_NUM;index++ ){
dev_no = MKDEV( major, index );
snprintf(name,,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,,GLOBALMEN_LEN);
}
return ;
} 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=;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.一套驱动对应多个设备的方法

《linux设备驱动开发详解》笔记——6字符设备驱动的更多相关文章

  1. linux设备驱动开发详解 笔记

      在目录的 Makefile 中关于 RTC_DRV_S3C 的编译脚本为: obj -$(CONFIG_RTC_DRV_S3C) += rtc-s3c.o 上述脚本意味着如果 RTC_DRV_S3 ...

  2. Linux设备驱动开发详解

    Linux设备驱动开发详解 http://download.csdn.net/detail/wuyouzi067/9581380

  3. 嵌入式Linux应用程序开发详解------(创建守护进程)

    嵌入式Linux应用程序开发详解 华清远见 本文只是阅读文摘. 创建一个守护进程的步骤: 1.创建一个子进程,然后退出父进程: 2.在子进程中使用创建新会话---setsid(): 3.改变当前工作目 ...

  4. 《linux设备驱动开发详解》笔记——15 linux i2c驱动

    结合实际代码和书中描述,可能跟书上有一定出入.本文后续芯片相关代码参考ZYNQ. 15.1 总体结构 如下图,i2c驱动分为如下几个重要模块 核心层core,完成i2c总线.设备.驱动模型,对用户提供 ...

  5. 《linux设备驱动开发详解》笔记——14 linux网络设备驱动

    14.1 网络设备驱动结构 网络协议接口层:硬件无关,标准收发函数dev_queue_xmit()和netif_rx();  注意,netif_rx是将接收到的数据给上层,有时也在驱动收到数据以后调用 ...

  6. 《linux设备驱动开发详解》笔记——12linux设备驱动的软件架构思想

    本章重点讲解思想.思想.思想. 12.1 linux驱动的软件架构 下述三种思想,在linux的spi.iic.usb等复杂驱动里广泛使用.后面几节分别对这些思想进行详细说明. 思想1:驱动与设备分离 ...

  7. 《linux设备驱动开发详解》笔记——10中断与时钟

    10.1 中断与定时器 中断一般有如下类型: 内部中断和外部中断:内部中断来自CPU,例如软件中断指令.溢出.除0错误等:外部中断有外部设备触发 可屏蔽中断和不可屏蔽中断 向量中断和非向量中断,ARM ...

  8. 《Linux设备驱动开发详解(第2版)》配套视频登录51cto教育频道

    http://edu.51cto.com/course/course_id-379-page-1.html http://edu.51cto.com/course/course_id-379-page ...

  9. Linux设备驱动开发详解-Note(11)--- Linux 文件系统与设备文件系统(3)

    Linux 文件系统与设备文件系统(3) 成于坚持,败于止步 sysfs 文件系统与 Linux 设备模型 1.sysfs 文件系统 Linux 2.6 内核引入了 sysfs 文件系统,sysfs ...

随机推荐

  1. iReport - 无法正常启动的解决方法

    问题与分析 最近需要用到iReport报表工具,但是在启动客户端时却发现只出现了启动界面,很快就界面消失没反应了.反复打开了好几次客户端,都无法正常打开.问了下同事,说是因为jdk升级的原因,以前项目 ...

  2. DRF教程5-API接口文档和接口测试

    配置 配置好,就可以访问web页面 pip install coreapi #安装依赖 from rest_framework.documentation import include_docs_ur ...

  3. centos 无界面 服务器 安装chrome部署chromedriver

    转:https://blog.csdn.net/u013849486/article/details/79466359 基本 做完了,要弄进docker里面去了的时候,才搜到 docker-chrom ...

  4. 基于华为云语音通知 VoiceCall 的应用上线记录并分享.NET CORE DEMO

    最近公司要上线语音通知功能,需求如下: 场景:发生报警时,自动通知到指定的手机号,同时,提供几个按键选项,例如,语音通知如下: “您好,XXX小区发生XXXX报警,按1确认报警,按2忽略报警,按3屏蔽 ...

  5. PHP中的文件操作

      文件系统的概述 任何类型的变量在运行的时候都是将其加载到内存里面.但是内存有一个特点:CPU读取内存的速度很快,但是一旦断电,内存里面的数据就会消失.如果要持久的保存数据,有两种方法:将数据存储到 ...

  6. spring boot使用AbstractXlsView导出excel

    一.maven依赖jar包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi ...

  7. I/O————数据流

    如何将一个long类型的数据写入文件中? 转字符串 → 通过 getbytes() 写进去,费劲,而且在此过程中 long 类型的数需要不断地转换. 现在,Java 中的数据流能够很好的解决这个问题( ...

  8. Android 麦克风录音带音量大小动态显示的圆形自定义View

    1.所谓无图无真相,先上效果图.我们要实现的就是中间那个录音的按钮,周边会显示一圈音量大小的波形 2.VolumCircleBar继承自View,我们进行了自定义,代码如下 package com.r ...

  9. IOSAutolayout

    21:55:33前言 1 MagicNumber -> autoresizingMask -> autolayout 以上是纯手写代码所经历的关于页面布局的三个时期 在iphone1-ip ...

  10. 【数据库-Azure SQL Database】如何创建事务复制将本地数据同步到 SQL Azure

    Azure SQL DB 可以被配置成为 SQL Server 事务复制的一个订阅者( subscriber ). 主要应用场景有两种: 将您的数据迁移到 Azure SQL DB, 并且没有宕机时间 ...