# Kernel Mode ###### tags: `IT鐵人` ## kernel mode & user mode 為了安全的管理不同的user process,保護他們之間不會互相干擾,我們需要不同的模式來管理,就像是上下層一樣,分為系統的kernel mode以及使用者的user mode。 簡單來說kernel mode負責分配誰能使用哪些資源,現在輪到誰來執行,以及一些重要或是可能危害系統的指令都會交給kernel mode處理。  |mode|差別| |-|-| |kernel mode|又叫System/Privileged/Supervisor mode,代表kernel取得對系統的控制權。(即kernel取得CPU在執行一些system process)在此mode下,可以執行特權指令(Privileged Instruction)。 |user mode|代表user process取得CPU在執行之mode,在此mode下,不允許執行特權指令。| 此外,Dual mode之實現需要硬體額外支援。例如提供一個mode bit決定現在是哪一種mode。 ## Privileged Instruction 任何可能造成系統重大危害的指令都可以稱為Privileged Instruction。只能在kernel mode下執行,不允許在user mode下執行。 一般而言,下列這些指令是Privileged Instruction: * I/O instruction(I/O protection) * Base/limit register值修改(Memory protection) * Time值修改(CPU protection) * Turn off interrupt * Switch mode to kernel mode * Clear Memory 如果沒有區分Privileged Instruction的話,User process可能可以隨意修改Memory的值,造成程式危害;讓自己可以永遠占用CPU;隨意寫入檔案;不接受任何原先預計要對該process產生影響的interrupt。  ## Protection 以下會介紹前面提到的各種protection,並敘述該protection的過程: ### I/O Protection 為了防止user process執行I/O指令操控I/O Devices,降低出錯機率及使用複雜度。 將I/O設為Privileged Instruction。 |步驟|內容| |-|-| |1|User process發出system call通知需要執行I/O Instruction。 |2|OS trap進入kernel mode。 |3|I/O subsystem執行I/O指令。 |4|I/O結果回傳給I/O subsystem。 |5|I/O subsystem回傳給user process並切換回user mode。 ### Memory Protection 為了防止user process任意存取其他process及kernel所在的記憶體區域。 假設Memory管理採用Contiguous Allocation的方法,則利用Base register及Limit register管理process能使用的記憶體區間。 |步驟|內容| |-|-| |1|存取Memory時,將位址傳給OS trap進入的kernel mode。 |2|計算位址是否大於等於Base且小於Base+Limit。 |3|如果結果為true則回傳legal同意存取;反之則回傳illegal不同意存取。 ### CPU Protection 為了防止user process長期/無限期占用CPU而不釋放。 利用Timer,OS會規定一個process使用CPU之MAX-Time-Quantum,當process取得CPU後,Time值則設為Max-Time-Quantum,隨著process使用CPU的時間增加,Timer值會逐步遞減,當Time值=0時,Timer會發出"Time-Out" Interrupt通知OS,OS會強迫此process放掉CPU。 | 上一篇 | 下一篇 | |-|-| |[I/O運作](https://hackmd.io/@dZfCcN4hT8aUuDPv3B8CWQ/SyexQvsWt)|[System Call & OS架構](https://hackmd.io/@dZfCcN4hT8aUuDPv3B8CWQ/Hk99oy0-F) 
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.