0
votes

Considering the Linux case, where we have a kernel stack for each user stack, from what I know, whenever a context switch happens, we switch to kernel mode of the current process.

Here we save the current status, registers, program data etc. of the current process and then the scheduler (not sure if it runs in this kernel) saves the PCB and loads the PCB of the next process to be scheduled.

Now the first question is if the explanation above seems to make sense for you, considering a context switch where each process has also a "dedicated" kernel stack.

And the other part of my question is, how would a context switch happen if we had a single kernel stack for all the processes?

1

1 Answers

0
votes

Each process has its own kernel stack.

I will use the latest kernel as an example.

In include/linux/sched.h, there is a union named thread_union and its definition is as follows:

union thread_union {
#ifndef CONFIG_THREAD_INFO_IN_TASK
    struct thread_info thread_info;
#endif
    unsigned long stack[THREAD_SIZE/sizeof(long)];
};

When a new process is created, the kernel will allocate a thread_union to it and each process will have its "dedicated" thread_union.

  1. The first member thread_info is a struct which contains a pointer to the task_struct of this process.
  2. The second member stack is the kernel stack of this process.
  3. This is a union, so the two members use the same memory space. thread_info is not very big, so there is enough space for kernel stack.

When a process invokes a system call, it will use its own kernel stack and save the %ESP which points to user stack in the kernel stack.

Each process has its own thread_union, so they have their own "dedicated" kernel stack.