ECS 150 The Kernel Abstraction
Prof. Joel Porquet-Lupine
UC Davis 2020/2021
Copyright 2017-2021 Joel Porquet-Lupine CC BY-NC-SA 4.0 International License /
1 / 26
Process abstraction
Process definition
A process is a program in execution
Disk Source
int x;
x = 42;
compile
Executable
.text .data 1011 0101
Processor
load+run
Memory
Stack
Heap Data
Instructions
Stack
Heap Data
Instructions
OS kernel
SP
PC
2 / 26
/
Process abstraction
Lack of protection
Multiple processes can be loaded in memory and run concurrently
Issues
Buggy process
Crash other processes Crash the OS
Hog all the resources
Malicious process
Solution
Redefine process abstraction Include notion of protection
Memory
Stack
Heap
Data
Instructions
Stack
Heap
Data
Instructions
Stack
Heap
Data
Instructions
3 / 26
/
Military defense Buggy C software program
OS kernel
Process abstraction
Process RE-definition
A process is a program in execution, running with limited rights
Protected execution
Memory segments process can access Other permissions process has
E.g., what files it can access
Based on process user ID, group ID
But efficient
Restricting rights must not hinder functionality
Efficient use of hardware
Communication with OS and between processes is safe
Process 1
Process 2
Process 3
PCB PCB PCB
User Kernel
PID=1
mem uid gid
PID=2
mem uid gid
PID=3
mem uid gid
4 / 26
/
Process abstraction
Limited privilege execution Interpreted execution
Basic model in interpreted languages
Javascript, Python, etc. Emulate each program instruction
If instruction is permitted, then perform it
Otherwise, stop process But execution quite slow
Native execution
Run unprivileged code directly on the CPU
Very fast execution
But safe execution needs specific hardware support
Application
Interpreter
Hardware
Application
Hardware
5 / 26
/
Dual-mode operation
Concept
Distinct execution modes supported directly in hardware
Indicated by a bit in processor status register (e.g., 0 or 1)
Can be more than one mode on some processor architectures
Kernel mode
Execution with full privileges on the hardware
Read/write to any memory location Access to any I/O device Read/write to any disk sector Send/receive any packet
Etc.
User mode
Limited privileges on the hardware
As granted by the operating system
User Mode
Kernel Mode
6 / 26
/
Dual-mode operation
Hardware support
Privileged instructions
Potentially unsafe instructions prohibited when in user mode Only available in kernel mode
Memory protection
Memory accesses outside of process memory limits prohibited Prevent process from overwriting kernels or other processes memory
Timer interrupts
Kernel periodically regains control on CPU Prevent running process from hogging hardware
Mode switch
Safe and efficient way to switch mode
From user mode to kernel mode, and vice-versa
7 / 26
/
Dual-mode operation
Typical 5-stage pipeline
Instruction Decode Register Fetch
Execute Address Calc.
Memory Access
Write Back
Instruction Fetch
IF ID EX MEM WB
Next PC
PC
IR
Next SEQ PC RS1
RS2
Next SEQ PC
Branch taken
Register File
Zero?
Memory
Imm Extend
Sign
ALU
Memory
WB Data
8 / 26
/
Adder
MUX
MUX MEM / WB
EX / MEM
ID / EX
IF / ID
MUX MUX
Dual-mode operation
Dual-mode 5-stage pipeline
Instruction Decode Register Fetch
Execute Address Calc.
Memory Access
Write Back
Instruction Fetch
IF ID EX MEM WB
Next PC
PC
IR
Next SEQ PC RS1
RS2
Next SEQ PC
Branch taken
Register File
Zero?
Memory
Imm Extend
Sign
ALU
Memory
Exception handler
WB Data
Status Register
Mode
9 / 26
/
Adder
MUX
MUX MEM / WB
EX / MEM
ID / EX
IF / ID
MUX MUX
ECS 150 The Kernel Abstraction
Prof. Joel Porquet-Lupine
UC Davis 2020/2021
Copyright 2017-2021 Joel Porquet-Lupine CC BY-NC-SA 4.0 International License /
10 / 26
Recap
Process abstraction, v2.0 Protected execution
Native execution
Application
Hardware
Process 1
Process 2
Process 3
PCB PCB PCB
User Kernel
PID=1 mem uid gid
Dual-mode operation User mode vs kernel mode
User Mode
Kernel Mode
Hardware support
Privileged instructions Memory protection Timer interrupts Mode switch
PID=2 mem uid gid
PID=3 mem uid gid
11 / 26
/
Privileged instructions
Definition
Instructions only available to code running in kernel mode
Processor exception if user code tries to execute privileged instruction
Example
And more
Toggle processor mode Modify memory protection Flush/invalidate caches/TLBs Halt or reset processor
Etc.
int main(void)
{
printf(Hello!
);
/* Try deactivating
* hardware interrupts */ asm (cli ::: memory);
while (1)
printf(I win?
);
return 0; }
x86_cli.c
$ ./x86_cli
Hello!
Segmentation fault (core dumped)
Illegal instructions are reported as segmentation faults on x86/Linux
12 / 26
/
Memory protection
Concept
Enforce memory boundaries to processes
Processor exception if code tries to access unauthorized memory
Virtual memory
Runtime translation between virtual and physical address spaces
Basic segmentation
Memory area defined by base and bound pair
Process
Memory
Base+ Bound
Base
Raise exception
>
CPU
Process
Memory
Physical address
Base
<Bound Translation Virtual addressPhysical address@virt @phys CPU Raise exception13 / 26/ Timer interruptsBoot sequenceUpon powering on the computerPrivilege mode set to kernel modePC set to address of boot code (e.g., BIOS) Boot code runsLoads kernel image into memory Jumps to kernel’s entry pointKernel code runsMachine setup (devices, virtual memory, interrupt vector table, etc.) Chooses the first user process to run, loads it, and jumps to itPrivilege bit set to user mode PC set to process’ entry pointFirst process runsNeed a way for kernel to re-take control… 14 / 26/ Timer interruptsHardware timerPeriodically interrupts the processorFrequency of interruption set by the kernelReturns control to the kernel exception handlerAlso used to maintain accurate and precise time of dayjiffy ticktickP1P1P2P3P215 / 26/ Mode switchingUser mode to kernel mode ExceptionsTriggered by program behavior Intentional or unintentional Synchronous eventsInterruptsTriggered by I/O devices (Better) alternative to polling Asynchronous eventsSystem callsRequest from process for kernel to perform operation on its behalfIntentional, synchronous eventsasm (“cli” ::: “memory”); int *a = NULL; *a = 42; User codeinstruction #ninstruction #n+1…Kernel code Interrupt …Interrupt before current instructionInterruptServiceRoutineread:movq $SYS_read, rax movq $fd, rdimovq $buf, rsi…syscall16 / 26/Return to instruction Mode switchingKernel mode to user mode Return from interrupt or system callResume suspended executionProcess context switchResume some other processNew process startJump to first instruction in programSignalAsynchronous notification If signal handler definedP1P1P1P2P2 P1P1(signal handler)P117 / 26/ ECS 150 – The Kernel AbstractionProf. Joel Porquet-LupineUC Davis – 2020/2021Copyright 2017-2021 Joel Porquet-Lupine – CC BY-NC-SA 4.0 International License /18 / 26RecapMode switchingUser to kernelExceptionsCaused by program behaviorSynchronous InterruptsTrigged by I/O devicesAsynchronous System callsService request to kernel SynchronousKernel to userReturn from interrupt or system callContext switch between processesNew process startSignal handlerP1P1 P1P2P2P1P1(signal handler)P119 / 26/ Mode switchingSafe and efficient switchingProtect from corrupting the kernelEntry door to the kernel for processes Reduce overhead of kernelMaximize CPU cycles for processesRequirements1. Atomic transfer of control2. Exception vector3. Transparent, restartable execution 20 / 26/ Mode switchingAtomic transfer of controlSafe transition between modes must be atomicI.e., in one unbreakable, logical stepCPU mode, PC, stack, memory protection, etc. changed at the same timeUser to kernel switchSave cause for jumpInterrupt, Exception, Syscall? Save current PCJump to kernel entry point(s) Switch from user to kernel mode Change memory protection Disable interruptsProcessKernelKernel to user switchJump to process (restore PC) Switch from kernel to user mode Change memory protection Restore interruptsProcessKernel21 / 26/ Mode switchingException vectorProvide limited number of entry points into the kernelTable set up by kernel: function pointers to exception handlersSoftware-managedSingle kernel entry point for CPUFixed or configurable addressSoftware dispatch based on exception causeExample MIPS processor/* Exception handler init */exception_handlers[0] = handle_int;exception_handlers[8] = handle_sys;exception_handlers[10] = handle_ri;…Hardware-managedCPU aware of vector Automatic hardware dispatchProcessor Memory Exception vector…handle_int() { …handle_sys() {} …}handle_ri() {} … exception_vector: # Kernel entry point # Retrieve cause from system register mfc0 k1, CP0_CAUSE# Extract exception codeandi k1, k1, 0x7c# Use code as index in arraylw k0, exception_handlers(k1) # Jump to proper handlerjr k0Example MIPS processorException vectorregister22 / 26/ Mode switchingTransparent, restartable executionProcesses should never know when they are interrupted Save/restore execution context (processor registers) Software-managedHardware-managedProcessor saves all the registers in a provided memory regionTask state segment (TSS) on x86 processorsRarely used in practiceE.g., not used by Linux or Windows handle_int:# Save all registerssw $1, 4(sp) sw $2, 8(sp) sw $3, 12(sp)……lw $3, 12(sp)lw $2, 8(sp) lw $1, 4(sp)# Jump back to processeret# Jump to C function# that processes interrupt requests jal do_irq# Restore all registersExample MIPS processor23 / 26/ Kernel stackDefinitionKernel has its own stack, located in kernel memory Different from process’ stack User processmain() {scanf(); }scanf() {read(0, …);}read() {asm(“syscall”);}Kernelhandle_sys:SAVE_ALLjal do_sysRESTORE_ALLdo_sys() {read_sys();}read_sys() {… } PC SPProcessor(user) main scanf readUser stackKernel stackRegister File24 / 26/ Kernel stackContext savingKernel stack is used to save associated process contextUser processmain() {scanf(); }scanf() {read(0, …);}read() {asm(“syscall”);}Kernelhandle_sys:SAVE_ALLjal do_sysRESTORE_ALLdo_sys() {read_sys();}read_sys() {… } PC SPProcessor(kernel) main scanf readProcess ctx:CPU registers PC, SP do_sys read_sys User stackNot a good idea to reuse process’s stack pointerReliability: no guarantee user stack is valid Security: kernel data shouldn’t leak to user spaceKernel stackRegister File 25 / 26/ Kernel stackOne kernel stack per processKernel saves its own state when switching between two processesP1 user stack main scanf readP2 user stackuser kernelP2 user stack main mainticksyscallcontext switchcontext switch P1 user ctx read_sys ctx switch P1 kernel ctx P2 user ctx timer INT ctx switch P2 kernel ctx P2 user ctx timer INT ctx switch P2 kernel ctx P1 user ctx timer INT ctx switch P1 kernel ctxP2 kernel stackP1 kernel stackP1 kernel stackP2 kernel stack26 / 26/
Reviews
There are no reviews yet.