《linux設備驅動開發詳解》筆記——6字符設備驅動

 

 

6.1 字符設備驅動結構

先看看字符設備驅動的架構:node

6.1.1 cdev

  cdev結構體是字符設備的核心數據結構,用於描述一個字符設備,cdev定義以下:linux

  

#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 *);                     //  從系統中刪除cdevshell

6.1.2 設備號

註冊設備號和釋放設備號,設備號也是系統資源,須要注意在註銷函數時釋放:ubuntu

#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);  // 動態分配,並註冊設備號api

/**
* 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目錄下自動生成設備文件,可以使用以下函數實現app

#include <linux/device.h>

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

  /**
  * 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.一套驅動對應多個設備的方法

相關文章
相關標籤/搜索