现在的位置: 首页 > 综合 > 正文

Linux驱动开发–Linux字符设备驱动模板

2018年03月16日 ⁄ 综合 ⁄ 共 2093字 ⁄ 字号 评论关闭
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/fs.h>/*包含struct file_operations,MAJOR等*/
#include <linux/slab.h>/*kmalloc*/
#include <asm/io.h>/*ioread8...*/
#include <mach/map.h>
#include <mach/regs-gpio.h>
#include <mach/gpio-bank-l.h>/*端口操作用到的三个头文件*/


#define XXX_MAJOR 125
#define DEVICE_NAME "xxx_dev"
#define CMD_1 0;
#define CMD_2 1;

int xxx_major=XXX_MAJOR;
struct XXX_DEV{
	struct cdev cdev;
	int value;	
};

struct XXX_DEV *xxx_dev;

int  xxx_open(struct inode* inode,struct file* filp)
{
	struct XXX_DEV* dev;
	dev=container_of(inode->i_cdev,struct XXX_DEV,cdev);
	filp->private_data=dev;
	return 0;
}

int  xxx_release(struct inode* inode,struct file* filp)
{
	return 0;
}

ssize_t xxx_read(struct file* filp,char __user *buf,size_t count,loff_t *f_pos)
{
	return 0;
}

ssize_t xxx_write(struct file *filp,const char __user *buf,size_t count,loff_t *f_pos)
{
	return 0;
}

long xxx_ioctl(struct file *filp,unsigned int cmd,unsigned long arg)
{
	struct XXX_DEV *xxx_dev=filp->private_data;
	switch(cmd){
	case LED_0:{
		break;
	}
	case LED_1:{
		break;	
	}
	default:
		return -ENOTTY;
	}
	return 0;
}

struct file_operations xxx_fops={
	.owner=THIS_MODULE,
	.open=xxx_open,
	.read=xxx_read,
	.write=xxx_write,
	.unlocked_ioctl=xxx_ioctl,
	.release=xxx_release,
};

static int __init xxx_init(void)
{
	int result;
	dev_t devno;
	if(XXX_MAJOR){
		devno=MKDEV(XXX_MAJOR,0);
		result=register_chrdev_region(devno,1,DEVICE_NAME);
	}else{
		result=alloc_chrdev_region(&devno,0,1,DEVICE_NAME);
		xxx_major=MAJOR(devno);
	}
	if(result<0){
		printk(KERN_WARNING "ERROR: can not register\n");
		return result;
	}
	
	xxx_dev=kmalloc(sizeof(struct XXX_DEV),GFP_KERNEL);
	if(!xxx_dev){
		result=-ENOMEM;
		goto fail;
	}
	memset(xxx_dev,0,sizeof(struct XXX_DEV));
	cdev_init(&xxx_dev->cdev,&xxx_fops);
	xxx_dev->cdev.owner=THIS_MODULE;
	result=cdev_add(&xxx_dev->cdev,devno,1);
	if(result){
		printk(KERN_WARNING "ERROR: can not add cdev\n");
		goto fail;
	}
	return 0;
fail:
	unregister_chrdev_region(devno,1);
	return result;
}

static void __exit xxx_exit(void)
{
	dev_t devno=MKDEV(xxx_major,0);
	if(xxx_dev){
		cdev_del(&xxx_dev->cdev);
		kfree(xxx_dev);
	}
	unregister_chrdev_region(devno,1);
}

MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("yixuaning <yixuaning@sina.com>");
module_init(xxx_init);
module_exit(xxx_exit);

 

抱歉!评论已关闭.