Question

As I know linux kernel threads do not have their own address space as compare to user space threads/process. Kernel threads do not context switch into user space but kernel threads are schedulable and preemptable. So my question is that if the kernel thread do not have the address space then how the switching/preemption of kernel thread works?

Was it helpful?

Solution

Kernel threads basically executes a function. They are created using the kernel_thread() function which receives the address of the function to execute, the arguments to that function and some clone flags as arguments.

This function essentially invokes a common do_fork() passing it the address of the Kernel Mode stack where copy_thread() will find the initial values of the CPU registers for the kernel thread.

Basically kernel_thread() builds the stack in a way that:

  • ebx and edx register will be set by copy_thread() to the values fn and arg
  • eip will be set to a small routine that will load the arguments and call fn

This way the new kernel thread starts executing fn(arg).

As you can see, a kernel thread knows about what code to execute by the address of fn. This function normally is already defined somewhere inside the kernel, by setting eip to point there, this way the kernel thread knows the instructions to execute. No need for text segment because there's no need to map an executable file to a memory region.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top