1. 程式人生 > >字元裝置驅動程式的編寫

字元裝置驅動程式的編寫

字元裝置是3類裝置(字元裝置、塊裝置、網路裝置)中的一類,其驅動程式的完成的主要工作是初始化、新增和刪除cdev結構體,申請和釋放裝置號。以及填充file_operations結構體中的操作函式,實現file_operations結構體中的read()、write和ioctl()等函式是驅動程式設計的主體工作。(參考宋寶華老師的書籍)

cdev結構體
   struct cdev{
           struct kobject kobj;                //內嵌的kobject物件
           struct module *owner;          //所屬模組
           struct file_operation *ops;    //檔案操作結構體
           struct list_head list;              
           dev_t dev;                             //裝置號
           unsigned int count;
};

     1.dev_t dev 定義了裝置號,位32位,12位主裝置號,20位次裝置    號
      獲取裝置號:
         MAJOR(dev_t dev);  //主裝置號
         MINOR(dev_t dev);  //此裝置號
    生成dev:
        MKDEV(int major, int minor);
    分配和釋放裝置號
       //已知主裝置
       int register_chrdev_region(dev_t from, unsigned count, const char *name);
       //避免裝置號衝突
       int alloc_chrdev_region(dev_t *dev, unsigned baseminor,unsigned count, const char *name);

  2.操作cdev結構體的函式如下:
      void cdev_init(struct cdev * , struct file_operations *);
      struct cdev *cdev_alloc(void);
      void cdev_put(struct cdev *p);
      int cdev_add(struct cdev*, dev_t, unsigned);
      void cdev_del(struct cdev*);
     實現細節如下:
    void cdev_init(struct cdev *cdev,struct file_operations *fops)
    {
      memset(cdev, 0 ,sizeof(*cdev));
      INIT_LIST_HEAD(&cdev->list);
      kobject_init(&cdev->kobj, &ktype_cdev_default);
      cdev->ops = fops;//將傳入的檔案操作結構體指標賦值給cdev的ops
   }      
 //動態申請一個cdev記憶體
  struct cdev *cdev_alloc()
{
       struct cdev *p = kzalloc(sizeof(struct cdev), GFP_KERNEL);  
      if(p){
            INIT_LIST_HEAD(&p->list);
            kobject_init(&p->kobj, &ktype_cdev_dynamic);          
      }
    return p;     

}

cdev_add()和cdev_del()分別向系統新增和刪除一個cdev

file_operations結構體:
   裡面的函式比較多,主要是read()、write()、ioctl();