驱动
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/io.h>
#include <linux/ioport.h>
#define DEMO_NAME "demo_char"
#define GPJ0_REGBASE 0xE0200240
typedef struct GPJ0REG
{
volatile unsigned int gpj0con ;
volatile unsigned int gpj0dat ;
}gpj0_reg_t;
static int my_major;
gpj0_reg_t *pGPJ0REG;
static int demo_chrdev_open(struct inode *inode, struct file *file)
{
pGPJ0REG->gpj0con &= 0xff000fff;
pGPJ0REG->gpj0con |= (1<<12)|(1<<16)|(1<<20);
pGPJ0REG->gpj0dat |= ((1<<3)|(1<<4)|(1<<5));
printk(KERN_INFO "demo_chrdev_open\n");
return 0;
}
static int demo_chrdev_release(struct inode *inode, struct file *file)
{
pGPJ0REG->gpj0dat |= ((1<<3)|(1<<4)|(1<<5));
printk(KERN_INFO "demo_chrdev_release\n");
return 0;
}
static ssize_t demo_chrdev_write(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos)
{
int ret = -1;
char kbuf[100] = {0};
ret = copy_from_user(kbuf,ubuf,count);
if(ret)
{
printk(KERN_ERR "copy_from_user fail\n");
return -EINVAL;
}
if(!strcmp(kbuf,"0"))
pGPJ0REG->gpj0dat &= ~((1<<3)|(1<<4)|(1<<5));
else if(!strcmp(kbuf,"1"))
pGPJ0REG->gpj0dat |= ((1<<3)|(1<<4)|(1<<5));
else
printk(KERN_INFO "input err\r\n");
printk(KERN_INFO "copy_from_user %s\r\n",kbuf);
return 0;
}
static const struct file_operations demo_fops = {
.owner = THIS_MODULE,
.open = demo_chrdev_open,
.release = demo_chrdev_release,
.write = demo_chrdev_write,
};
static int __init chrdev_init(void)
{
my_major = register_chrdev(0,DEMO_NAME,&demo_fops);
if(my_major<0){
printk(KERN_ERR "chrdev_init error.\n");
return -EINVAL;
}
printk(KERN_INFO "chrdev_init success.\n");
if(!request_mem_region(GPJ0_REGBASE,sizeof(gpj0_reg_t),"GPJ0REG"))
return -EINVAL;
pGPJ0REG = ioremap(GPJ0_REGBASE,sizeof(gpj0_reg_t));
return 0;
}
static void __exit chrdev_exit(void)
{
iounmap(pGPJ0REG);
release_mem_region(GPJ0_REGBASE,sizeof(gpj0_reg_t));
unregister_chrdev(my_major,DEMO_NAME);
printk(KERN_INFO "chrdev_exit\n");
}
module_init(chrdev_init);
module_exit(chrdev_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Xin-Ya Zhu<mhzhuxinya@outlook.com>");
MODULE_DESCRIPTION("demo test");
MODULE_ALIAS("alias xxx");
应用
int main(void)
{
int fd = -1;
char buf[100] = {0};
fd = open(FILE,O_RDWR);
if(fd<0)
{
printf("open error.\n");
return -1;
}
write(fd,LED_ON,strlen(LED_ON));
sleep(1);
write(fd,LED_OFF,strlen(LED_OFF));
sleep(1);
write(fd,LED_ON,strlen(LED_ON));
sleep(1);
write(fd,LED_OFF,strlen(LED_OFF));
sleep(1);
close(fd);
return 0;
}
/***************************
[root@zhuxinya text]
[15338.775103] chrdev_init success.
[root@zhuxinya text]
[root@zhuxinya text]
[15355.778153] demo_chrdev_open
[15355.779573] copy_from_user 0
[15356.782604] copy_from_user 1
[15357.784135] copy_from_user 0
[15358.785707] copy_from_user 1
[15359.787279] demo_chrdev_release
[root@zhuxinya text]
[root@zhuxinya text]
[15379.135901] chrdev_exit
*****************************/