天天看點

linux裝置驅動模闆

//linux 字元裝置驅動的組成模闆

struct xxx_dev_t{

struct cdev cdev;

};

/*裝置驅動子產品加載函數*/
static int __init xxx_init(void)
{
...
cdev_init(&xxx_dev.cdev, &xxx_fpos);    /*初始化cdev*/
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);  /*注冊裝置*/
...
}

 /*裝置驅動子產品解除安裝子產品*/
 static void __exit xxx_exit(void)
 {
 unregister_chrdev_region(xxx_dev_no, 1);   /*釋放占用的裝置号*/
 cdev_del(&xxx_dev.cdev);                   /*登出裝置*/
 ...
 }

  3. file_operations定義了字元裝置驅動提供給虛拟檔案系統的接口函數,常見的字元裝置驅動的這三個函數的形式如下:
  //讀裝置
  ssize_t xxx_read(struct file *filp ,char __ user *buf, size_t count, loff_t *f_ops)
  {
        ...
        copy_to_user(buf, ..., ...);
        ...
  }
           

//寫裝置

ssize_t xxx_write(struct file *filp , const char __user *buf , size_t count, loff_t *f_ops)

{

copy_from_user(…, buf, …);

}

//ioctl 函數

long xxx_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)

{

switch(cmd){

case xxx_CMD1:
     ...;
     break;
...
default ://不支援的指令
        return -ENOTTY;
}

return 0;
           

}

繼續閱讀