4
votes

I have learned that every single process has its own area/block in the memory that consists of stack, heap, data and text (code) (see this).

Now I'm reading stuff about context switching. I read that during a context switch the CPU registers are pushed onto the stack and then the complete stack will be saved into the process control block. Is that basically how it works?

And why do I need to save the stack if every process has it's own stack?

2
Add the architecture. Is it x86?cadaniluk
Every CPL has its own stack. Read up about the TSS (Task State Segment).cadaniluk
Yes x86, single core. Maybe you can explain me context switching. The document I read clearly says: registers are pushed onto stack -> stack is saved in PCB. What did I miss?Richard
Could you link to the document to better explain it to you, please?cadaniluk
I'm sorry. I'm not allowed. It's property of the University im studing atRichard

2 Answers

3
votes

The complete stack is not saved in a context switch. A process context block only contains register values on every system I am aware of.

A stack is just a block of memory. There is nothing special about it. The only thing that makes it a stack is that the Stack Pointer register references it. A process can have multiple stacks. In fact they usually do. Processes usually have a stack for each processor mode. In multithreading, there is one stack for each thread.

1
votes

When a context switch occurs, the kernel brings in a new process and "kicks out" old the process. But when an old process gets its turn to occupy the CPU, its previous state (the state when it was "kicked out") must be restored to start execution from the point where it left off.
All architectures have a limited number of registers. The registers are also included in the state of a process to be stored for eviction. Saving registers on the stack is for efficiency's sake, so you just need to pop the values back in.
Furthermore, each process has its own Process Control Block (PCB) to store such values on a context switch so that the scheduling algorithm is not hindered and works on some simple process ID. When a process acquires the CPU, the PCB, attached with that ID, is restored.

Edit In my knowledge there is no CPU stack in x86. CPU has stack pointer to point to first element of the stack.