Interrupts, Exceptions, and System Calls: Chester Rebeiro IIT Madras
Interrupts, Exceptions, and System Calls: Chester Rebeiro IIT Madras
System Calls
Chester Rebeiro
IIT Madras
OS & Events
• OS is event driven
– i.e. executes only when there is an interrupt,
trap, or system call
OS
30
Privilege level
13
User process 1 User process 2
event
time
2
Why event driven design?
• OS cannot trust user processes
– User processes may be buggy or malicious
– User process crash should not affect OS
• OS needs to guarantee fairness to all user
processes
– One process cannot ‘hog’ CPU time
– Timer interrupts
3
Event Types
Events
Interrupts Exceptions
4
Events
• Interrupts : raised by hardware or
programs to get OS attention
– Types
• Hardware interrupts : raised by external hardware
devices
• Software Interrupts : raised by user programs
5
Event view of CPU
Execute Instruction
Where?
If event Execute event
yes in handler
no
6
Exception & Interrupt Vectors
Event occured What to execute next?
7
Exception and Interrupt Vectors
8
xv6 Interrupt Vectors
• 0 to 31 reserved by Intel
• 32 to 63 used for hardware interrupts
T_IRQ0 = 32 (added to all hardware IRQs to
scale them)
• 64 used for system call interrupt
Events
Interrupts Exceptions
10
Why Hardware Interrupts?
• Several devices connected to the CPU
– eg. Keyboards, mouse, network card, etc.
• These devices occasionally need to be serviced
by the CPU
– eg. Inform CPU that a key has been pressed
• These events are asynchronous i.e. we cannot
predict when they will happen.
• Need a way for the CPU to determine when a
device needs attention
11
Possible Solution : Polling
• CPU periodically queries device to
determine if they need attention
• Useful when device often needs to send
information
– For example in data acquisition systems
• If device does not need attention often,
– Polling wastes CPU time
12
Interrupts
• Each device signals to the CPU that it wants to be serviced
• Generally CPUs have 2 pins
– INT : Interrupt
– NMI : Non maskable – for very critical signals
• How to support more than two interrupts?
Device 2
INT
CPU
Device 1
NMI
13
8259 Programmable Interrupt Controller
14
Interrupts in legacy CPUs
15
Edge vs Level Interrupts
• Level triggered Interrupt : as long as the IRQ line is
asserted you get an interrupt.
– Level interrupt still active even after interrupt service is complete
– Stopping interrupt would require physically deactivating the
interrupt
• Edge triggered Interrupt : Exactly one interrupt occurs
when IRQ line is asserted
– To get a new interrupt, the IRQ line must become inactive and
then become active again
16
Edge vs Level Interrupts
(the crying baby… an analogy)
• Level triggered interrupt :
– when baby cries (interrupt) stop what you are doing and feed the
baby
– then put the baby down
– if baby still cries (interrupt again) continue feeding
• Edge triggered interrupt
– eg. Baby cry monitor, where light turns red when baby is crying.
The light is turned off by a push button switch
• if baby cries and stops immediately you see that the baby has cried
(level triggered would have missed this)
• if the baby cries and you press the push buttton, the light turns off,
and remains off even though the button is pressed
http://venkateshabbarapu.blogspot.in/2013/03/edge-triggered-vs-level-triggered.html 17
Spurious Interrupts
Consider the following Sequence
1. Device asserts level triggered interrupt
2. PIC tells CPU that there is an interrupt
3. CPU acknowledges and waits for PIC to send interrupt vector
4. However, device de-asserts interrupt. What does the PIC do?
18
Advanced Programmable Interrupt
Controller (APIC)
• External interrupts are routed from peripherals to CPUs in multi processor systems
through APIC
• APIC distributes and prioritizes interrupts to processors
• Interrupts can be configured as edge or level triggered
• Comprises of two components
– Local APIC (LAPIC)
– I/O APIC
• APICs communicate through a special 3-wire APIC bus.
– In more recent processors, they communicate over the system bus
19
LAPIC and I/OAPIC
• LAPIC :
– Receives interrupts from I/O APIC and routes it to the
local CPU
– Can also receive local interrupts (such as from thermal
sensor, internal timer, etc)
– Send and receive IPIs (Inter processor interrupts)
• IPIs used to distribute interrupts between processors or
execute system wide functions like booting, load distribution,
etc.
• I/O APIC
– Present in chipset (north bridge)
– Used to route external interrupts to local APIC
20
I/O APIC Configuration in xv6
• IO APIC : 82093AA I/O APIC
• Function : ioapicinit (in ioapic.c)
• All interrupts configured during boot up as
– Active high
– Edge triggered
– Disabled (interrupt masked)
• Device drivers selectively turn on interrupts using
ioapicenable
– Three devices turn on interrupts in xv6
• UART (uart.c)
• IDE (ide.c)
• Keyboard (console.c)
3
interrupt 0
1 2
23
What more happens when there is
an Interrupt?
3 X86 saves the SS, ESP, EFLAGS,
CS, EIP, error code on stack
Basic program state saved (restored by iret instruction).
Suspends current task.
4
How does hardware find the OS
Jump to interrupt handler interrupt handler?
stacks
– a user space stack Kernel Stack
for process
Accessible by
kernel
Heap
Accessible by
user process
User Stack
Data
Text
(instructions)
26
To Switch or not to Switch
Executing in Executing in
Kernel space User space
Selected Descriptor =
Base Address + (Vector * 8)
31
Interrupt Gate Descriptor
1 Segment present
points to offset in the segment 0 Segment absent
which contains the interrupt handler
(higher order bits) privilege level
(obtained from
either the PIC or APIC) Done
automatically
IDTR by CPU
64 bytes
33
Setting up IDT in xv6
vector i:
vector0 push 0
push i
vector1 Jmp alltraps
vector2 Error code:
Hardware pushes error
---
Code for some exceptions.
--- For others, xv6 pushes 0.
vector i
---
vector255
alltraps
Creates a trapframe
Stack frame used for
interrupt
Invokes trap
(3350 [33])
only if stack
SS
changed
By hardware
SS
ESP
EFLAGS
CS
EIP
Error Code Pushed by
Trap Number
ds
hardware or
es software
By software
…
eax
ecx
… argument for
esi
edi trap
esp (pointer to this trapframe)
ESP
(empty) trapframe
p->kstack
(empty)
38
4
Interrupt Handlers
• Typical Interrupt Handler
– Save additional CPU context (written in assembly)
(done by alltraps in xv6)
– Process interrupt (communicate with I/O devices)
– Invoke kernel scheduler
– Restore CPU context and return (written in assembly)
39
Interrupt Latency
time needed to service an interrupt
OS
30
Privilege level
13
User process 1 User process 2
40
Importance of Interrupt Latency
• Real time systems
– OS should ‘guarantee’ interrupt latency is less than a
specified value
• Minimum Interrupt Latency
– Mostly due to the interrupt controller
• Maximum Interrupt Latency
– Due to the OS
– Occurs when interrupt handler cannot be serviced
immediately
• Eg. when OS executing atomic operations, interrupt handler
would need to wait till completion of atomic operations.
Atomic Operations
Interrupt handler
Global variable :
int x;
Solution : make the part of code atomic (i.e. disable interrupts while executing
this code)
Nested Interrupts
Interrupt handler 2
Interrupt handler 1
interrupt
interrupt
• Typically interrupts disabled until handler executes
– This reduces system responsiveness
• To improve responsiveness, enable Interrupts within handlers
– This often causes nested interrupts
– Makes system more responsive but difficult to develop and validate
• Interrupt handler approach: design interrupt handlers to be small so that
nested interrupts are less likely
Small Interrupt Handlers
• Do as little as possible in the interrupt
handler
– Often just queue a work item or set a flag
• Defer non-critical actions till later
Top and Bottom Half Technique
(Linux)
• Top half : do minimum work and return from
interrupt handler
– Saving registers
– Unmasking other interrupts
– Restore registers and return to previous context
• Bottom half : deferred processing
– eg. Workqueue
– Can be interrupted
Interrupt Handlers in xv6
Events
Interrupts Exceptions
50
Hardware vs Software
Interrupt
Hardware Interrupt Software Interrupt
.
Device
INT .
CPU INT x
.
.
51
Software Interrupt
Software interrupt used
for implementing 3
system calls Process
– In Linux INT 128, is
used for system calls
System Calls
– In xv6, INT 64 is used INT 64
for system calls
Kernel
0
52
Example (write system call)
libc invocation
User
space write(STDOUT)
int
Int Handler
Kernel
space
Implementation
of
write syscall
System call processing in kernel
Almost similar to hardware interrupts
3
Back to user
INT 64
process
if vector = 64
0 vectors.S alltraps trap syscall
(alltraps.S) (trap.c) (syscall.c)
Executes the
System calls
54
System Calls in xv6
55
System Call Number
System call number used to distinguish between system calls
System call numbers System call handlers
System
call number
mov x, %eax
INT 64
return is generally
‘int’ (or equivalent)
sometimes ‘void’ What OS resource is the target
here?
int used to denote completion For example a file, device, etc.
status of system call sometimes
also has additional information If not specified, generally means
like number of bytes written to the current process
file
57
Passing Parameters
in System Calls
• Passing parameters to system calls not similar
to passing parameters in function calls
– Recall stack changes from user mode stack to kernel
stack.
• Typical Methods
– Pass by Registers (eg. Linux)
– Pass via user mode stack (eg. xv6)
• Complex
– Pass via a designated memory region
• Address passed through registers
58
Pass By Registers (Linux)
• System calls with fewer than 6 parameters
passed in registers
– %eax (sys call number), %ebx, %ecx,, %esi, %edi,
%ebp
• If 6 or more arguments
– Pass pointer to block structure containing argument
list
• Max size of argument is the register size (eg. 32
bit)
– Larger pointers passed through pointers
59
Pass via User Mode Stack (xv6)
User stack trapframe
param1 SS
ESP ESP pushed by hardware
User process param2
param3 EFLAGS contains user mode stack
push param1 CS pointer
push param2 EIP
push param3 Error Code
mov sysnum, %eax Trap Number
ds
int 64
es
…
eax
ecx
… proc entry
esi for process
edi
ESP Points to trapframe
(empty)
(empty)
61
Events
Events
Interrupts Exceptions
62
Exception Sources
– Program-Error Exceptions
• Eg. divide by zero
– Software Generated Exceptions
• Example INTO, INT 3, BOUND
• INT 3 is a break point exception
• INTO overflow instruction
• BOUND, Bound range exceeded
– Machine-Check Exceptions
• Exception occurring due to a hardware error (eg. System bus error,
parity errors in memory, cache memory errors)
63
Exception Types
Exceptions
Faults Traps
Aborts
64
Faults
Exception that generally can be corrected.
Once corrected, the program can continue execution.
Examples :
Divide by zero error
Invalid Opcode
Device not available
Segment not present
Page not present
65
Traps
Traps are reported immediately after the
execution of the trapping instruction.
Examples:
Breakpoint
Overflow
Debug instructions
66
Aborts
Severe unrecoverable errors
Examples
Double fault : occurs when an exception is
unhandled or when an exception occurs while
the CPU is trying to call an exception handler.
Machine Check : internal errors in hardware
detected. Such as bad memory, bus errors,
cache errors, etc.
67