简体   繁体   中英

copy_from_user() runs in user space or kernel space?

copy_from_user() is used in kernel module. So my understanding is it runs in kernel space. however, I get confused after I read this "User context only. This function may sleep." Can anybody give me an explanation?

The phrase "user context" doesn't refer to user space execution. It refers to kernel code running in the context of a particular user process. There has to be a relevant user process for the from argument to be meaningful.

Quoting this web page (which I found with a quick Google search for "linux user context"):

There are two contexts (patterns of execution flow) in the Linux kernel: interrupt and user(space) contexts. User contexts are code which is entered from userspace: a system call. Unless the kernel code sleeps for some reason (explicitly allowing other code to run), no other user context will run on that CPU; this is the non-preemtive part. They are always associated with a particular process.

However, an interrupt can occur at any time, which halts the user context in its tracks and runs an interrupt context. This is not associated with any process; it is caused by a timer, an external hardware interrupt, or a bottom-half (bottom halves may be run off the timer or other interrupts, see below). When it is finished, the user context will resume.

(In comments, 0x90 suggests that this quote is misleading, which may well be correct.)

"User context" means here that when this function is called inside the kernel, the CPU must be in a state where it is configured to use a memory map associated with a user process. This map is specific to each process and basically has a range mapped to the kernel memory and a range mapped to the user process memory. This is why copy_from_user is able to copy bytes from the memory range of the process into a memory buffer in the kernel memory.

In some cases, for exemple when handling an interrupt, the CPU uses a different memory mapping in which there is no range for a user process, therefore copy_from_user doesn't make any sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM