Search code examples
operating-systemschedulingkernel-mode

Does CPU always execute instructions in kernel mode?


This is perhaps a very silly question, but it's been bugging me for a while. My doubt is that since the only threads that are scheduled onto the CPU are kernel threads(typically) and since every user thread is mapped to a kernel thread, does that mean that all applications essentially run in kernel mode?


Solution

  • There's multiple scenarios where some are less common. One possible example (of a less common scenario) is having a single kernel stack per CPU, with "save user-space thread state" as part of privilege level change from user-space to kernel and "load possibly different user-space thread's state" as part of privilege level change from kernel back to user-space (where it's hard to say if kernel's code use 1 thread/task per CPU or if kernel's code doesn't use the concept of threads/tasks at all and only exists between the 2 halves of a potential user-space thread switch).

    For the common scenario, every thread/task has a kernel part (and its own kernel stack, etc) and a user-space part (and its own user-space stack, etc). In this case it can be described as task switches only ever occuring when the thread is using its kernel part; but after the task switch the task's kernel part can switch to the same task's user-space part and back again whenever it wants (e.g. for kernel system calls and IRQs).

    Note that this isn't the only way to describe the common scenario; but it is my preferred way (because it avoids "beginner pitfalls" - specifically, the false assumption that IRQs are a necessary part of task switching).

    I suspect that this way of describing the common scenario (i.e. that task switches only happen between tasks running kernel code) has caused your doubts.