I have initially written a virtual device driver, and after the driver is successfully loaded, an error will be reported when opening it, fd = open(filename, O_RDWR); fd = -1. Could you please tell me what is wrong with my driver code?
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#define HELLO_MAJOR 504 /* 主设备号,若为0,则会自动分配*/
#define HELLO_NAME "hello_2" /* 设备名 */
static char readbuf[100]; //读缓存区
static char writebuf[100]; //写缓存区
static char kerneldata[] = {"kernel data!"}; //
static int hello_drv_open(struct inode *inode, struct file *filp)
{
// printk("%s:%s line %d\n", __FILE__, __FUNCTION__, __LINE__);//打印调试信息
return 0;
}
static ssize_t hello_drv_read(struct file *filp, char __user *buf, size_t cnt, loff_t *offt)
{
int retvalue = 0;
// printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);//打印调试信息
memcpy(readbuf, kerneldata, sizeof(kerneldata));
retvalue = copy_to_user(buf, readbuf, cnt);
if(retvalue ==0 ){
printk("kernel senddata is ok!\r\n");
} else{
printk("kernel senddata failed! \r\n");
}
return 0;
}
static ssize_t hello_drv_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
int retvalue = 0;
// printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);//打印调试信息
/* 接收用户空间传递给内核的数据b并且打印出来 */
retvalue = copy_from_user(writebuf, buf, cnt);
if(retvalue ==0 ){
printk("kernel recvdata is %s!\r\n",writebuf);
} else{
printk("kernel recvdata failed! \r\n");
}
return 0;
}
static int hello_drv_release(struct inode *inode, struct file *filp)
{
return 0;
}
//设备操作函数结构体
static struct file_operations hello_drv_fops=
{
.owner = THIS_MODULE,
.open = hello_drv_open, //对于函数来说,函数名和&函数名都标识函数地址
.read = hello_drv_read,
.write = hello_drv_write,
.release = hello_drv_release,
};
static int __init hello_drv_init(void)
{
int retvalue, err;
retvalue = register_chrdev(HELLO_MAJOR, HELLO_NAME, &hello_drv_fops);
if(retvalue < 0){
printk("hello driver register failed\r\n");
}
printk("hello_drv_init()\r\n");
return 0;
}
static void __exit hello_drv_exit(void)
{
unregister_chrdev(HELLO_MAJOR, HELLO_NAME);
printk("hello_drv_exit()\r\n");
}
//将上述2个函数z指定为驱动的入口和出口函数
module_init(hello_drv_init);
module_exit(hello_drv_exit);
//LICENSE和作者信息
MODULE_LICENSE("GPL");
MODULE_AUTHOR("WXY");
MODULE_INFO(intree,"Y");