Linux Kernel Architecture

(Jacob Rumans) #1

Chapter 4: Virtual Process Memory


4.13 Copying Data between Kernel and


Userspace


The kernel often needs to copy data from userspace to kernel space; for example, when lengthy data
structures are passed indirectly in system calls by means of pointers. There is a similar need to write data
in the reverse direction from kernel space to userspace.

This cannot be done simply by passing and de-referencing pointers for two reasons. First, userspace
programs must not access kernel addresses; and second, there is no guarantee that a virtual page belong-
ing to a pointer from userspace is really associated with a physical page. The kernel therefore provides
several standard functions to cater for these special situations when data are exchanged between kernel
space and userspace. They are shown in summary form in Table 4-2.

Table 4-2: Standard Functions for Exchanging Data between Userspace and Kernel
Space

Function Meaning

copy_from_user(to, from, n)
__copy_from_user

Copies a string ofnbytes fromfrom(userspace) toto
(kernel space).

get_user(type *to, type* ptr) __get_user Reads a simple variable (char,long,...)fromptr
toto; depending on pointer type, the kernel decides
automatically to transfer 1, 2, 4, or 8 bytes.

strncopy_from_user(to, from, n)
__strncopy_from_user

Copies a null-terminated string with a maximum ofn
characters fromfrom(userspace) toto(kernel space).

put_user(type *from, type *to)
__put_user

Copies a simple value fromfrom(kernel space) toto
(userspace); the relevant value is determined automat-
ically from the pointer type passed.

copy_to_user(to, from, n)
__copy_to_user

Copiesnbytes fromfrom(kernel space) toto
(userspace).

Table 4-3 lists additional helper functions for working with strings from userspace. These functions are
subject to the same restrictions as the functions for copying data.

get_userandput_userfunction correctly only when applied to pointers to
‘‘simple‘‘ data types such aschar,int, and so on. They do not function with
compound data types or arrays because of the pointer arithmetic required (and
owing to the necessary implementation optimizations). Beforestructscanbe
exchanged between userspace and kernel space, it is necessary to copy the data and
then convert it to the correct type by means of typecasts.
Free download pdf