1

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?

Ritesh
  • 91
  • 2
  • 10
  • What makes you think that it requires a user land address space to make a process/thread preemptable? – JustSid Jan 29 '14 at 17:33
  • I am not saying that it requires user address space, my doubt is that if kernel thread does not have address space then how will it access the kernel code/instructions? – Ritesh Jan 29 '14 at 17:35
  • A kernel thread, runs in the kernel context & address space! Kernel threads may be preemptable (CONFIG option) in which case interrupts, can cause the scheduler to reevaluate and switch to another thread. If the kernel is not a preempt one, then the thread runs until it is done, cooperative multi-tasking; which works in kernel as kernel code is `trusted` – Rob11311 May 26 '14 at 23:19

1 Answers1

1

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.

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
  • If kernel thread is executing the function (of which address was passed to kernel thread) and before the completion of function the kernel thread gets preempted, then how will it re-schedule again? – Ritesh Jan 29 '14 at 18:04
  • When it is preemted, `eip` (among every other registers) are stored either in Kernel Mode stack or `current.thread strcut`. Once resumed, all these registers are set back, so next instruction will be `eip`. Do I explain myself? – Paulo Bu Jan 29 '14 at 18:06
  • Looks like you have cleared my doubt. Thanks Paulo Bu. – Ritesh Jan 29 '14 at 18:11