Copy_to_user () and copy_from_user () for the underlying data type

I am writing a Linux kernel driver and for each function that sends data to user space or reads data from user space, I use copy_to_user () and copy_from_user (). My question is: do I need to use these calls if I just copy a basic data type like u32 or int?

+6
source share
2 answers

If the function receives a pointer to user space data, you should use copy_from_user() to copy the pointed data from user space to kernel space (and vice versa).

Note that the pointer value is passed by value (like all C parameters), so you do not need to do copy_from_user() to get the pointer value before you can copy_from_user() to point to the data it points to.

Numeric arguments work just like pointer arguments; in terms of C, they are both scalars. You do not need to use copy_from_user() to copy the parameter value; which is already copied. You only need to use it to copy the data that the passed pointer points to.

So, if you have an int parameter, you can use it directly. If your parameter points to int , then the int object will be in user space, and you need to use copy_to_user to copy the value of this object to kernel space.

+7
source

When a user transfers data to kernel space, this data can be divided into several pages, and these pages can even be in changed memory. In these cases, you have to wait until the kernel changes on the page and gets access to the page on which the data is located. In the case of elementary data types (for example, int or pointers) it is also true that some architectures (especially x86 intel) do not force the user to align the data, so even an integer can be divided on the page border. You may have access to the first part of your integer, but wait until the second is replaced by the memory manager before everything is available.

You can save some callbacks by placing all user data in a structure whose pointer is passed to the kernel. You can copy_from_user this as a block and retain access (and be at risk of blocking several times)

So, and as a conclusion, use functions even for basic types , since there are a lot of them. Do not assume anything about where user data may be when working in kernel mode. You have access to it, but the virtual addresses of the kernel of user data have nothing to do with the virtual addresses visible in user mode.

+2
source

Source: https://habr.com/ru/post/984576/


All Articles