Reputation: 41002
I have this in a kernel module:
/*global scope declared*/
static int array[10]={1,2,3,4,5,6,7,8,9,10};
and I have functions for open close read and write works perfectly, i want to share the array[8]
with the user space application in the bottom of this page.
in the kernel module:
static int *my_mmap (struct file *filep, struct vm_area_struct *vma ) {
if (remap_pfn_range(vma,
vma->vm_start,
virt_to_phys(array)>> PAGE_SHIFT,
10,
vma->vm_page_prot) < 0) {
printk("remap_pfn_range failed\n");
return -EIO;
}
return 0;
the application in user-space's source code:
#define LEN (64*1024)
/* prototype for thread routine */
#define FILE_PATH "/dev/my_module"
int main()
{
int i=0;
int fd = open(FILE_PATH,O_RDWR);
int* vadr = mmap(0, LEN, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
for (i=0;i<10;++i){
printf("%d",*(vadr+i));
}
return 0;
}
Upvotes: 1
Views: 6756
Reputation: 651
Refer to Implementing mmap for transferring data from user space to kernel space for a guide on how to share data between kernel and user space properly. I have it implemented in my custom driver and it works fine. If you don't need the speed though, using copy_to_user is safer and easier.
Upvotes: 0
Reputation: 15218
This is wrong on so many levels I don't know where to even start :-)
There are probably more problems, but this is what pops to mind.
The right thing to do is not share data between kernel and user space, but copy it over using copy_to_user and friends, unless you really know what you are doing and why.
If you really must share the memory, then allocate a free page, map it from kernel space (e.g. kmap) and from user space (like you did) and hope that your platform doesn't have a VIPT cache.
Upvotes: 1
Reputation: 71555
Your array is an array of char, but your userspace program is accessing it as an array of int.
Upvotes: 0
Reputation: 326
I'm a relative newcomer to kernel programming so I may be missing something but isn't it possible for you to use copy_to_user in this case?
unsigned long copy_to_user(void __user * to, const void * from, unsigned long n);
In brief
to = address in userspace (destination)
from = address in kernel (source)
n = number of bytes to copy
Upvotes: 0