linux字符設備驅動程序框架(老方法)

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/arch/regs-gpio.h>
#include <asm/hardware.h>
#include <linux/cdev.h>
#include <linux/types.h>

#define	xxx_DEVICE_COUNT	1	

/*自動創建設備節點類*/
static struct class *xxx_dev_class;
static struct class_device *xxx_dev_class_dev;

/*
	xxx設備相關的相關操作函數:open、read、write、close、ioctl等
*/
static int xxx_dev_open(struct inode *inode, struct file *filp)
{
	printk("Open xxx device OK.\n");
	return 0;
}

static int xxx_dev_close(struct inode *inode, struct file *filp)
{
	printk("Close xxx device OK.\n");
	return 0;
}

static int xxx_dev_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
	printk("Write xxx device OK.\n");
	return 0;
}

static int xxx_dev_read(struct file *file, const char __user *buf, size_t count, loff_t ppos)
{
	printk("Read xxx device OK.\n");
	return 0;
}

static int xxx_dev_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg)
{
	printk("DRIVER : Get cmd %d.\n", cmd);
	return 0;
}

/*
	xxx設備操作函數結構體
*/
struct file_operations xxx_fops = {
	.owner = THIS_MODULE,
	.open = xxx_dev_open,
	.release = xxx_dev_close,
	.read = xxx_dev_read,
	.write = xxx_dev_write,
	.ioctl = xxx_dev_ioctl,
};

/*
	xxx設備驅動模塊的註冊和卸載
*/
int xxx_major = 0;
static int __init initialization_xxx_dev(void)
{
	/* 註冊設備號 */
	printk("Before register xxx Major = %d\n", xxx_major);
	if (xxx_major) {
		register_chrdev(xxx_major, "xxx", &xxx_fops);
	} else {
		xxx_major = register_chrdev(0, "xxx", &xxx_fops);
	}
	printk("After register xxx Major = %d\n", xxx_major);

	/* 自動生成設備節點 */
	xxx_dev_class = class_create(THIS_MODULE, "xxx_dev");
	xxx_dev_class_dev = class_device_create(xxx_dev_class, NULL, MKDEV(xxx_major, 0), NULL, "xxx");
	/* 模塊初始化成功必須返回0 */
	printk("Module register OK.\n");
	return 0;
}

static void __exit cleanup_xxx_dev(void)
{
	/* 刪除設備文件 */
	unregister_chrdev(xxx_major, "xxx");
	class_device_unregister(xxx_dev_class_dev);
	class_destroy(xxx_dev_class);

	printk("Module unregister OK.\n");
}

/*
	模塊註冊與卸載
*/
module_init(initialization_xxx_dev);
module_exit(cleanup_xxx_dev);

/*
	模塊傳參:insmod char_driver_frame_old.ko xxx_major=xxx
*/
module_param(xxx_major, int, S_IRUGO);

/*
	模塊的相關聲明
*/
MODULE_AUTHOR("lhbo");
MODULE_DESCRIPTION("GPIO Driver for xxx");
MODULE_LICENSE("GPL");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章