How to access user space memory from the Linux kernel?

linux-kernel, memory-management

Solution

You may find this useful.

Let us repeat that the buff argument to the read and write methods is a user-space pointer. Therefore, it cannot be directly dereferenced by kernel code. There are a few reasons for this restriction:

Depending on which architecture your driver is running on, and how the kernel was configured, the user-space pointer may not be valid while running in kernel mode at all. There may be no mapping for that address, or it could point to some other, random data.

Even if the pointer does mean the same thing in kernel space, user-space memory is paged, and the memory in question might not be resident in RAM when the system call is made. Attempting to reference the user-space memory directly could generate a page fault, which is something that kernel code is not allowed to do. The result would be an "oops," which would result in the death of the process that made the system call.

The pointer in question has been supplied by a user program, which could be buggy or malicious. If your driver ever blindly dereferences a user-supplied pointer, it provides an open doorway allowing a user-space program to access or overwrite memory anywhere in the system. If you do not wish to be responsible for compromising the security of your users' systems, you cannot ever dereference a user-space pointer directly.

Source: http://www.makelinux.net/ldd3/chp-3-sect-7

That said, I am myself curious to know what happens if the user-space address is indeed valid, and none of the above conditions apply...

Problem

I know that `copy_to_user`/`copy_from_user`, `get_user`/`put_user` functions are for this purpose. My question is that, given a user space address/pointer, how can I access the data pointed to by the address from the kernel in general? I can imagine that first I have to make sure the containing page should be in physical memory (instead of in disk). What is the next step? Can I use `*p`, where `p` is the pointer pointing to some user space data, directly to refer to the data? Or do I have to first invoke `kmap` to map the containing physical page frame to the kernel virtual address space? Why?

Original source