CSC 230:
Interrupts, Exceptions, Traps
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 1
Interrupts
• Before interrupts: polling
• The interrupt concept
• Implementing interrupt handlers • Nested interrupts
• Exceptions and traps
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 2
Motivation: input/output
• Computer systems consist of a collection of hardware components:
– CPU
– main memory
– data and address buses
– control bus
– input & output devices (I/O devices)
• Most I/O devices are physically distinct from other computer- system components
– Although they are interfaced with the CPU …
– … they can operate independently of the CPU.
• Example: keyboard
– Even though it may be built-in to your laptop…
– … it is considered a separate device in the computer system.
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 3
Keyboard in computer system
University of Victoria
CSC 230: Computer Architecture and Assembly Language
This diagram abstracts away some details such as the University
Department of Computer Science
Interrupts, Traps, and Exceptions: Slide 4
Serial Bus (USB) often used with keyboard-to-computer connection.
What is a keyboard?
A familiar input device
Physical keypresses must be converted into electrical signals
Digital logic is needed to convert those electrical signals into information that (i.e., keypress events) that can be read by a CPU.
University of Victoria
CSC 230: Computer Architecture and Assembly Language
Department of Computer Science
Interrupts, Traps, and Exceptions: Slide 5
Images: https://bit.ly/3f9v1Nm; https://bit.ly/31PizP1; https://bit.ly/2AzkTyt
CPU to keyboard…
Control register indicates whether or not a keyboard event has occurred.
Data register holds the value of the key pressed (if there is a keyboard event).
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 6
One method
• Polling is where:
– Some device external to the main CPU (i.e., low-level hardware, timer, I/O interface) …
– … has some kind of state that much be checked by the CPU for readiness …
– … and for which some action must be taken .. (i.e., a value is ready to be input from a device; a device is ready to receive a value for output; the timer has reached its maximum value; etc.s) …
– … and that state is checked — and actions taken – – via code contained within an infinite loop.
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 7
One method
• Therefore:
– We can write a program that constantly checks the keyboard’s control register for a keypress event.
– If code detects that a key is pressed, its value is transferred out of the keyboard’s data register and into the CPU
• Ifadevice’scontrolanddataregisterscanbe accessed as memory addresses:
– Then we say the keyboard registers are mapped to memory.
– That is, we have memory mapped I/O
– CPU uses memory loads & stores to interact with device
• Otherwise:
– Must use special IO port instructions on the CPU
University of Victoria
CSC 230: Computer Architecture and Assembly Language
Department of Computer Science
Interrupts, Traps, and Exceptions: Slide 8
Keyboard is memory-mapped to these two addresses.
If bit 0 of control register is set, then there was a key pressed.
If a key was pressed, it must be retrieved from the keyboard’s data register.
.data
.eqv KEYBOARD_CONTROL_REGISTER 0xffff0000
Recall: timers
.eqv KEYBOARD_DATA_REGISTER 0xffff0004 NL: .asciiz “\n”
.text
polling_loop:
la $s0, KEYBOARD_CONTROL_REGISTER
lb $t0, 0($s0)
andi $t0, $t0, 0x01
beq $t0, $zero, polling_loop
la $s1, KEYBOARD_DATA_REGISTER lb $t1, 0($s1)
add $a0, $zero, $t1 addi $v0, $zero, 11 syscall
la $a0, NL
addi $v0, $zero, 4 syscall
This code simply echoes to the
console the key that was pressed
beq $zero, $zero, polling_loop
(one character per line).
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 9
Polling: pluses, minuses
• Polling is a relatively straightforward technique
– Wemuststillfigureouthowtowritecodetodetectwhen devices are ready for activity …
– …butthatisnotterriblyhard.
• As we have more devices or device events that must be managed by our code, we just add more elif clauses to our loop
– Ifwehadakeyboarddeviceandatimerdevice,ourloop would need to check both devices in each iteration.
• Two big downsides:
– Evenifnodeviceisreadyforaction,theCPUisstillbusy going around and around and around in the loop consuming CPU cycle
– Mixingpollingcodewithnon-pollingcodecanbe
difficult.
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 10
We can do better
• Workingwithlow-leveldevicesisaveryimportant part of any computer system
• Writingcodeforsuchdevicesisalwaystricky
• Soratherthanpolling…
– … that is, instead of our code constantly checking for a condition to be true …
• …weinsteadinformthecomputerthateventsof interest our program should cause one of our own functions to be executed …
• …andthatthisfunctionexecutionmusthappen automatically, regardless of what the rest of our code is doing at the time of the event!
• (Firealarmvs.screamingchild)
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 11
What does it mean to be interrupted?
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language
From: https://www.youtube.com/watch?v=Mh4f9AYRCZY
Interrupts, Traps, and Exceptions: Slide 12
Interrupt
• An event (signal) that can interrupt the control flow of the currently running program in order to execute a task on behalf of that event.
• These events can be triggered by:
– externalsignals(e.g.,externaltotheCPUsuchasI/O devices)
– internalsignals(e.g.,internaltotheCPUsuchastimers,CPU errors)
• The running program is temporarily suspended while the task is completed
– Thistaskusuallyissomefunctionspeciallywrittenfor handling the event (i.e., interrupt handler)
– TheCPUtakescareoftransferringcontroltotheinterrupt handler and back to the interrupted running program.
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 13
Timer diagrams
A:
Device P generates an event, it is handled after a short delay
B:
Device Q generates an event, it is handled after a short delay
C:
Device P generates an event, while device Q generates an event when P’s handle is executing.
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 14
Notice that any any one point in
time, only a thick black line or thick green line is active.
Implicit / explicit
• The main code does not know an interrupt has occurred
– That is, the main code does not call the interrupt-handler function
– Transfer of control to handler is managed by the CPU
• However, the interrupt handler function does explicitly cause control to return to interrupted code
– Using eret instead jr $ra
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 15
Interrupts can feel complicated
• Understandinghowtoprogramwithinterruptscan seem a bit tricky at first
• Someactionsoccurautomatically,othersrequire explicit actions on our part, and ultimately many things will be happening simultaneously in the hardware at runtime.
• Regardless:
– Everything ultimately depends upon something we ourselves indicate in our code!
– As long as we are clear about where we write code to configure interrupt handlers…
– … and as long as we very carefully write those handlers …
– … then coding can proceed in a straightforward fashion.
University of Victoria CSC 230: Computer Architecture and Assembly Language
Department of Computer Science Interrupts, Traps, and Exceptions: Slide 16
Overall idea
1. With interrupts disabled, code that configures the interrupt handler mappings is itself executed
2. With this configuration complete, enable interrupts
3. Start to execute our regular code
4. If an event occurs that is associated with an enabled interrupt…
a) … the CPU pauses where we are in our code …
b) … transfers control to the correct handler for that event …
c) … and that handler (normally) disables interrupts on the CPU …
d) … after which it does its work …
e) … and when the handler is finished, the second-to-last thing it does in re-enable interrupts …
f) … and the last thing it does is causes the CPU to return
control to where we originally paused.
University of Victoria
CSC 230: Computer Architecture and Assembly Language
Department of Computer Science
Interrupts, Traps, and Exceptions: Slide 17
Timer diagrams
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 18
Important
• Interruptsarenotarbitraryprogrammaticthings
– They are not the same as threads in multithreaded programming
– They are not used to implement multicore algorithms
• TheCPUarchitecturewillusuallydefinethesetof interrupts it can recognize
– These interrupts are usually coupled to expected hardware devices
– Some are to internal resources (such as timers)
• Programmingforinterruptsthereforemeans knowing something about what the CPU supports
• MIPS32causeregister University of Victoria
Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 19
Timer diagrams
The eight bits in IP7:0 are mapped as one bit per interrupt type.
Handler-dispatch code must examine this field and determine which bit is set.
The bit set then is used to decide what specific handler’s code to execute.
Bits shown with 0 are hardwired to be unset.
ExcCode is zero if the kernel-entry event is an interrupt.
Other bits with
other letters have
different purposes
(i.e., much-to-much
University of Victoria Department of Compute
detail for our
course!)
r Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Tracpsa, aundsEexceprtioensg: Silidset20er
(Coproc0 $13)
Programming for interrupts
• kernel vector entry: special address in computer’s memory used exclusively for any transfer into kernel code
– 0x80000180 in MIPS32
• Interrupt handler: A function that must be correctly
implemented for the device
– Requires knowledge of the device (obtained from a datasheet)
• Enabling some specific interrupt flag
– This is for the actual device to permit it to raise interrupts
• Once all devices / interrupts are properly established…
– … only then enable global interrupts.
– That is, until then these devices can be generating events and attempting to raise interrupts, but the CPU ignores them.
– Only when global interrupts are enabled will the CPU transfer control to and from our handlers.
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 21
When ie is unset, all CPU interrupts are disabled.
When ie is set, all CPU interrupts are enabled.
Only privileged code may set or unset bits in CPU status register.
Timer diagrams
ksu is the CPU privilege level
00 = kernel
10 = user
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language coImnteprruptse, Trapss, atndaExtceuptsionsr: Selidge 2i2ster
(Coproc0 $12)
Interrupt handler
• Handlersaremeanttousethesmallestamountof code necessary to deal with the interrupt
– For I/O devices, this would be reading bytes from, or writing bytes to, the registers of the device.
– For timers, this would involve setting status variables to important values
• Codewithinaninterrupt-handlerfunctionvery rarely calls other functions
– The time spent handling one interrupt is unavailable for handling those from other devices…
– … and given the time sensitivity of device behavior, missing another device’s interrupt could be disastrous.
• Finally:handlersmustensuretheinterruptedcode can safely resume operation after handler is finished
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 23
Examine bit 8 of “cause” to see if bit is set…
Reached here because bit 8 was set in the cause register. Code here is a bit trivial (to keep the slide simpler).
Must use special mfc0 instruction to read Coproc0 registers
.ktext 0x80000180
Timer diagrams
kernel_entry:
mfc0 $k0, $13
andi $k1, $k0, 0x7c
srl $k1, $k1, 2
beq $zero, $k1, is_interrupt
is_exception:
# empty for now
beq $zero, $zero, exit_kernel
is_interrupt:
andi $k1, $k0, 0x0100
bne $k1, $zero, is_kb_interrupt
# check for other interrupt types? # …
beq $zero, $zero, exit_kernel
is_kb_interrupt:
addi $t6, $t6, 1
la $k0, 0xffff0004
lw $t7, 0($k0)
beq $zero, $zero, exit_kernel
# other handlers? exit_kerneUln:iversity of Victoria
CSC
eret
Department of Computer Science
Mask out ExcCode bits
Must exit the kernel and restart the .text instruction when
230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 24
control was transferred to the kernel.
Enabling interrupts
• Therearetwostageshere:
A. Enabling the interrupts for the device itself
B. Enabling the CPU to respond to interrupts in general.
• SometimesStageAisthesamethingas“turningon interrupts at the device’s end”
– In MARS, we can this for the Keyboard MMIO Simulator by setting bit 1 of its control register.
– That is, setting that bit has the same effect as enabling interrupts to occur for this I/O device
• StageBisthemainCPU’sswitch(setbitieinthe Coproc0 status register)
• Thereforetheusualformatofcode:
– Set up all handlers, enable interrupts on all devices
– Once this is done, then (and only then!) perform sei
University of Victoria
Interrupts, Traps, and Exceptions: Slide 25
Department of Computer Science
CSC 230: Computer Architecture and Assembly Language
Multi-level interrupts
• Our examples have assumed that only a single interrupt event can be handled at any one time
• In MIPS32, normally interrupts from all devices are treated equal
• Other computer architectures support multi-level interrupts
– Hereadeviceanditsinterrupthasa“priority”…
– …suchthatinterruptsfromhigher-prioritydevicesare permitted to interrupt the handlers for lower-priority devices
• This makes sense:
– Somedevicesgenerateeventsinfrequently(e.g., keyboards)…
– Whileotherdevicesimplementeventsfarmorefrequently
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 26
(e.g., network cards)
University of Victoria Department of Computer Science
If device Q had a higher priority than device P…
Timer diagrams
University of Victoria Department of Computer Science
C:
Device P generates an event, but during its handling there is an event from device Q — and so device Q (with higher priority) has its interrupt serviced.
CSC 2O30n:cCoemptuhtear Atrchiitsectduroenaned,AsstehmeblyhLanngudalgers
for P is resumed.
Interrupts, Traps, and Exceptions: Slide 27
Multi-level interrupts
• Somehardwaresupportisneededformulti-level interrupts
• InMIPS32:
– A field called Interrupt Priority Level (IPL) is
available in the CPU status register.
– Kernel-entry code must examine this field and compare it’s value with the level of other interrupts that have handling in progress
– If the level of the new interrupt is higher, then handling in progress is suspended; when the higher-priority interrupt is completely handled, the suspended handler is resumed.
• Note:multi-levelinterruptsareverytrickyto
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 28
implement
University of Victoria Department of Computer Science
Critical section code
• Sometimeswemaywritecodeforwhichinterrupts might cause a problem
• Example:
– Timer interrupts are often used by operating systems to force switching between processes.
– However, code in the OS may want to avoid such a switch for some sensitive code
– Therefore the OS will disable interrupts before that sensitive code, and re-enable them afterwards
• Mustthereforeensureallmemorylocationsand status register fields are set without any chance of further interruptions!
• (Solutionstosimilarcritical-sectionproblemsisa
topic in CSC 360).
Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 29
University of Victoria
Interrupts, exceptions, traps
• When interrupts are enabled, it is possible for control to be transferred from .text code to .ktext code and back.
• Interrupts are always caused by some external event
– That is, some kind of physical device.
• However, there are ways in which such control can be transferred into the kernel
– These are caused by internal events, and are either called exceptions or traps
– Example: what happens with a syscall
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 30
Timer diagrams
WARNING!
The term exception as used here in these slides does not refer to Java, C++, or Python exceptions or their exception handling.
Hardware exceptions are a
completely different beast!
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 31
syscall
• User mode vs. kernel mode
– User mode has lower privileges
– Kernel mode has higher privileges
• Only when the CPU is in kernel mode may instructions that work with hardware be executed.
– That is, only kernel code is permitted to directly access I/O registers, or change the status register.
– If user-mode code attempts to access these
resources or change status, either the instruction is
ignored or there is a transfer in the kernel in order
to terminate the program.
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 32
University of Victoria
Department of Computer Science
syscall
• User code must therefore request actions be taken on its behalf by the kernel
– Thesystemcallinterfaceresemblesamenuofactionsthat can be taken by the kernel.
• The user code (in .text):
1. Indicates the action to be taken by storing a specific value
in $v0 (i.e., 4 for the “print string to console” action)
2. Copies needed parameters into argument registers (e.g.,
address of null-terminated string placed in $a0)
3. syscall instruction is executed
4. kernel is entered, CPU mode switches to kernel mode
5. kernel examines $v0; if value is valid, dispatches to code that does the action; if value is invalid, indicates an error
6. after action is performed or error is determined, CPU switches back to user mode and executes instruction
following the syscall. Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 33
University of Victoria
syscall, exceptions
• syscall is implemented as an exception
• Whencontrolistransferredtokernel-entrycode,
that code examines ExcCode field in cause register – If 0: interrupt
– If 4: address error
– If 6: bus error
– If8:syscall
– If 9: break (i.e., used by debuggers)
– If 10: illegal instruction
– If 30: cache error
– There are 32 codes in total, so what appears above is partial list.
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 34
trap
• Somepractitionersgroupinterruptsandexceptions into the larger group of traps
– i.e., the individuals consider a trap to be any event – internal or external – that causes transfer of control into the kernel
• MIPS32hasseveraldistincttrapinstructions:
– teq, tne, tlt, tgei, etc. etc.
– Like a branch instruction, they perform some kind of comparison.
– Unlike a branch instruction, a successful comparison causes a TRAP exception (i.e., ExcCode of 13).
– Assumption here is that code using such trap
instructions has a handler for TRAP in the kernel.
University of Victoria Department of Computer Science
CSC 230: Computer Architecture and Assembly Language Interrupts, Traps, and Exceptions: Slide 35