我正在尝试创建一个测试模块 - 一个响应来自用户的调用的字符设备。 到目前为止,该模块运行良好 - 响应读,写和ioctls。
总的想法是:在模块中创建一个变量,并能够读/写(通过mmap)到这个变量。
这是内核代码(缩小范围):
static char *hwevents;
static struct file_operations testmod_fops = {
.write = t_write,
.open = t_open,
.unlocked_ioctl = t_ioctl,
.read = t_read,
.mmap = t_mmap,
.owner = THIS_MODULE
};
static int t_mmap(struct file *filp, struct vm_area_struct *vma)
{
unsigned long phys = virt_to_phys(hwevents) << PAGE_SHIFT;
printk("test!\n");
pr_err("started mmap func\n");
if (remap_pfn_range(vma, vma->vm_start, phys, (vma->vm_end - vma->vm_start), vma->vm_page_prot))
return -2;
pr_err("finished mmap func\n");
vma->vm_ops = &simple_remap_vm_ops;
simple_vma_open(vma);
return 0;
}
static int __init testmod_init(void)
{
int i;
printk("I am here\n");
misc_register(&testmod_miscdev);
hwevents = (char *)get_zeroed_page(GFP_KERNEL);
if (hwevents == NULL) {
pr_err("hwevents allocating failed\n");
return -1;
}
return 0;
};
这是用户空间代码:
int memory_map_hub()
{
int fd;
void *mp = NULL;
if(fd = open("/dev/testmod", O_RDWR) == -1){
printf("error opening file\n");
return -1;
}
mp = mmap(NULL, 8, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_SHARED, fd, 0);
if (mp == (void *)-1) {
printf("failed\n");
return -1;
}
printf("the address returned is %p\n", mp);
munmap(mp, 8);
close(fd);
return 0;
}
2件不起作用的东西:
首先 - mmap()函数总是返回(-1)。 second - 内核空间中mmap函数内的printk()/ pr_err()不起作用。
似乎内核空间中的mmap函数甚至没有启动并自动返回-1。
感谢
编辑:这是答案 - ENODEV error in MMAP