Shared memory between user space and kernel threads

I am developing a kernel application that includes kthreads. I create an array of structure and allocate memory using malloc in user space. Then I call the system call (which I implemented) and pass the address of the array to kernel space. In the system call handler, I create 2 kthreads that will control the array. kthread can change some value, and user-space threads can also change some values. The idea is to use an array as shared memory. But some, when I access memory in kernel space (using copy_from_user), the data is somehow changed. I can verify that the address is the same when it was assigned, and in the kernel. But when using copy_from_user, it provides various values, such as garbage values.

Also there is the following statement ok?

int kthread_run_function(void* data){ struct entry tmp; copy_from_user(&tmp, data, sizeof(struct entry)); } 
+4
source share
2 answers

This is not so, because copy_from_user() copies from the current user process (which should be obvious, since there is no way to tell which user process to copy from).

In syscall called by your user space process, this is normal because the current process is your user space process. However, in the kernel thread, the current process can be any other process in the system - therefore you copy random processes from the memory, therefore you get garbage.

If you want to exchange memory between the kernel and the process in user space, the correct way to do this is to allocate the kernel and then allow the user space process to map it to the address space using mmap() . Different pointers will be used in the kernel thread and user space process to refer to the memory area - the kernel thread will use the pointer to the memory allocated in the kernel address space, and the user space process will use the pointer to the memory area returned by mmap() .

+6
source

No, this is usually not normal, since data is the virtual address of the kernel, not the virtual address of the user.

However, IFF, you called kthread_create with the data argument equal to the __user pointer, this should be fine.

+1
source

All Articles