What is the difference between kernel stack and user stack?

前端 未结 7 508
忘了有多久
忘了有多久 2021-01-31 06:25

What is the need of using two different stacks in same program? How does trap change the current stack of program from user stack to kernel stack? How does it come back to user

7条回答
  •  执笔经年
    2021-01-31 07:01

    I am learning OS in university, and our project is based on OS/161 built by Harvard. So my answer is all based on this OS.

    In OS/161, every thread has 2 stacks - one for user/application program, one for kernel program.

    1. What is the need of using two different stacks in same program?

    Say we only use stack in application mode. Since the memory space is shared by multiple threads, if some other thread accidently overwrite the address used by kernel, then kernel might be crashed, which leads to a very vulnerable OS.

    2. How does trap change the current stack of program from user stack to kernel stack?

    in OS/161, trap is used to transfer from an application program to kernel.There are three mechanisms that could invoke trap: System calls, Exceptions, and Interrupts. The trap frame in kernel stack is used to save current thread context.

    Following is the detailed process(from lecture note of UWaterloo CS350):

    • When one of above mechanism occurs, the hardware switches the CPU into privileged mode and transfers control to a predefined location, at which a kernel handler should be located.

    • The kernel handler creates a trap frame and uses it to saves the application thread context so that the handler code can be executed on the CPU.

    • Just before the kernel handler finishes executing, it restores the application thread context from the trap frame, before returning control to the application.

    3. How does it come back to user stack after completing system call?

    The process above explains clearly on this question as well.

提交回复
热议问题