1.设备驱动模块加载函数:module_init()
static int Module_init(void) { int result; /*将主设备号和次设备号转换成dev_t类型*/ dev_t devno = MKDEV(major, 0); /* 申请设备号*/ if (major) { /*静态*/ result = register_chrdev_region(devno, 2, "devname"); } else {/*动态*/ result = alloc_chrdev_region(&devno, 0, 2, "devname"); usercdev_major = MAJOR(devno); } if (result < 0) { return result; } /*初始化cdev结构*/ cdev_init(&cdev, &file_fops); cdev.owner = THIS_MODULE; cdev.ops = &file_fops; /* 注册字符设备 */ cdev_add(&cdev, MKDEV(major, 0), DEVNR); /* 为设备描述结构分配内存*/ pDevDescst = kmalloc(USERCDEV_NR_DEVS * sizeof(struct usercdev_dev), GFP_KERNEL); if (!pDevDescst) /*申请失败*/ { result = - ENOMEM; unregister_chrdev_region(devno, 1); /*申请失败处理*/ return result; } else { memset(pDevDescst, 0, sizeof(struct DevDescs)); /*为设备分配内存*/ for (i=0; i < DEVS_NR; i++) { pDevDescst[i].size = DEV_SIZE; pDevDescst[i].data = kmalloc(DEV_SIZE, GFP_KERNEL); memset(pDevDescst[i].data, 0,DEV_SIZE); } } }
2.模块卸载函数 Module_exit()
static void Module_exit(void) { /*注销设备*/ cdev_del(&cdev); /*释放设备结构体内存*/ kfree(pDevDescst); /*释放设备号*/ unregister_chrdev_region(MKDEV(major, 0), 2); }