0
votes

I am writing a kernel module in C. I need to declare a pointer to a character array in user space and fill it with data. I am declaring the pointer using char* __user, and filling it with the data calling copy_to_user function. Then I call copy_from_user function to check if the data is written correctly. Instead of reading the data I expect, I read only zeroes.

What am I missing? What is the correct way to write data in user space from kernel space?

Here is the code:

u16 address = 0xf0f0;
char __user *buf = address;
copy_to_user(buf, data_to_write, 20);

copy_from_user(data_to_read, buf, 20);
//printing data_to_read I read only zeroes.

Thank you!

1
Are you sure that the address 0xf0f0 is at all meaningful? Also, have you checked the return values? They'll tell you if the operation was successful from the functions' perspectives. - Thomas Jager
I checked the return values. The functions returned 20, so 20 are the number of bytes that could not be copied. So it is probable that the address is not meaningful. Thank you! - doramcquack
Why those magic numbers? - alx
@CacahueteFrito Are you talking about the 20s or the 0xf0f0? - Thomas Jager
@ThomasJager both - alx

1 Answers

0
votes

You can't just make up an (virtual) address and attempt to copy to it. You have to register it in the address space of the process. This is what the mmap() function does from user space. You need to perform an equivalent operation from within the kernel. Once you have created a writable, anonymous lump of memory, you should be free to copy into and out of it from the kernel.