Вы находитесь на странице: 1из 17

Exception & Interrupt

Asst. Prof. Dr. Surin Kittitornkun


Dept. of Computer Engineering,
Faculty of Engineering, KMITL

Outline
! Cortex M3 Processor Modes
! Exception Types
! Exception Handling
! Exception/Interrupt Priorities
! Exception Vector
! Interrupts
! Vectored Interrupt Controller
! Interrupt Handlers
! Interrupt Examples

6-2
Cortex-M3 Processor Modes
ARM Cortex-M3

Privileged Aborts
Supervisor Interrupts
Handler Mode Reset
Operating
System
System Call (SVCall)
Undefined Instruction

User Non-Privileged
Thread Mode Application code

Memory

Instructions & Data

Exception Types
! Exceptions caused by executing an instruction
" Software interrupts
" Undefined instruction
" Prefetch abort (accessing an invalid address)
! Exceptions caused as a side effect of an instruction
" Data abort
! Exceptions unrelated to instruction execution
" Reset
" IRQ - Usually generated by external peripherals
" FIQ - Usually generated by external peripherals

6-4
Cortex-M3 Exception Handling
" Reset : power-on or system reset
" NMI : cannot be stopped or preempted by any exception other than reset
" Faults
! Hard Fault : default Fault or any fault unable to activate
! Memory Manage : MPU violations
! Bus Fault : prefetch and memory access violations
! Usage Fault : undef instructions, divide by zero, etc.

" SVCall : privileged OS requests


" Debug Monitor : debug monitor program
" PendSV : pending SVCalls
" SysTick Interrupt : internal sys timer, i.e., used by RTOS to periodically check
resources or peripherals

" External Interrupt : i.e., external peripherals

Exception Handling
! Exception types:
" Reset, Non-maskable Interrupts (NMI), Faults, PendSV,
SVCall, External Interrupt, SysTick Interrupt
! Exceptionsprocessed in Handler mode
(except Reset)
" Exceptions always run in privileged mode
! Interrupt handling
" Interrupts are a sub-class of exception
" Automatic save and restore of processor registers (xPSR,
PC, LR, R12, R3-R0)
" Allows handler to be written entirely in C
Reset Behaviour Main
5

4
Reset Handler

0x04 Reset Handler Vector


1 0x00 Initial value of MSP r13 (MSP)
2

1. A reset occurs (Reset input was asserted)


2. Load MSP (Main Stack Pointer) register initial value
from address 0x00
3. Load reset handler vector address from address 0x04
4. Reset handler executes in Thread Mode
5. Optional: Reset handler branches to the main program

Exception handling process


1. Save processor status
Main " Copies CPSR into SPSR_<mode>
Application " Stores the return address in LR_<mode>
" Adjusts LR based on exception type
2. Change processor status for exception
" Mode field bits
" ARM or Thumb state
" Interrupt disable bits (if appropriate)
" Sets PC to vector address
Exception
3. Execute exception handler
handler " <users code>
4. Return to main application
" Restore CPSR from SPSR_<mode>
" Restore PC from LR_<mode>
! 1 and 2 performed automatically by the core
! 3 and 4 responsibility of software
Exception Behaviour
1. Exception occurs
Main
" Current instruction 4

stream stops 3
" Processor accesses 1
Exception Handler
vector table
2
2. Vector address for the
Exception Vector
exception loaded from the
vector table
3. Exception handler executes
in Handler (Privilege) Mode
4. Exception handler returns
to main

When an exception occurs ...


! The ARM:
" Copies CPSR into SPSR_<mode>
" Sets appropriate CPSR bits
! mode field bits - exceptions accompanied by a
mode change.
! Interrupt disable flags if appropriate.

" Maps in appropriate banked registers


! No actual data movement so done in zero time .

" Stores the return address (PC-4) in LR_<mode>


" Sets PC to vector address
! Forcing branch to exception handler

6-10
Exception Handling
! When an exception occurs
" The exception is latched.
" The normal program execution is stopped.
" The current PC and CPU mode is preserved.
" The PC is forced to the corresponding vector location
" Program execution continues from this point
" For the IRQ and FIQ exceptions
! when the exception has been processed the environment
restored and the PC reloaded so that the original program
can resume.
! The event that caused the exception must be cleared.

6-11

Registers
To return to previous mode (and main program) ...
! Need to do two things:
" Restore CPSR from SPSR_<mode>
" Restore PC using return address stored in LR_<mode>
! Can be done in one instruction, which depends upon exception:
" For SWI and Undefined Instruction
! MOVS pc, lr

" For FIQ, IRQ and Prefetch Abort


! SUBS pc, lr, #4

" For Data Abort


! SUBS pc, lr, #8

! Adding the S in privileged mode with copies SPSR into CPSR


" This will automatically restore the original mode,
interrupt settings and condition codes.

6-13

Vector Table for ARMv7-M


! First entry contains initial Main SP Address Vector #

! All other entries are addresses for 0x40 + 4*N External N 16 + N


exception handlers
" Must always have LSBit = 1 (for 0x40 External 0 16
Thumb) 0x3C SysTick 15
! Table has up to 496 external 0x38 PendSV 14
interrupts
0x34 Reserved 13
" Implementation-defined
0x30 Debug Monitor 12
" Maximum table size is 2048 bytes
0x2C SVC 11
! Table may be relocated
0x1C to 0x28 Reserved (x4) 7-10
" Use Vector Table Offset Register
0x18 Usage Fault 6
" Still require minimal table entries
at 0x0 for booting the core 0x14 Bus Fault 5

! Each exception has a vector number 0x10 Mem Manage Fault 4

" Used in Interrupt Control and


0x0C Hard Fault 3
State Register to indicate the 0x08 NMI 2
active or pending exception type 0x04 Reset 1
! Table can be generated using C code 0x00 Initial Main SP N/A
" Example provided later
Exception Vectors
; Taken from the assembler startup file.
; Exception Vectors
; Mapped to Address 0.
; Absolute addressing mode must be used.
; Dummy Handlers are implemented as infinite loops which can be modified.

Vectors LDR PC, Reset_Addr


LDR PC, Undef_Addr
LDR PC, SWI_Addr
LDR PC, PAbt_Addr
LDR PC, DAbt_Addr
NOP ;Reserved Vector
LDR PC, IRQ_Addr
LDR PC, [PC, #-0x0120] ;Vector from VicVectAddr
LDR PC, FIQ_Addr

6-15

Cont.

Reset_Addr DCD Reset_Handler


Undef_Addr DCD Undef_Handler
SWI_Addr DCD SWI_Handler
PAbt_Addr DCD PAbt_Handler
DAbt_Addr DCD DAbt_Handler
DCD 0 ; Reserved Address
IRQ_Addr DCD IRQ_Handler
FIQ_Addr DCD FIQ_Handler

Undef_Handler B Undef_Handler ;Tight loops


SWI_Handler B SWI_Handler
PAbt_Handler B PAbt_Handler
DAbt_Handler B DAbt_Handler
IRQ_Handler B IRQ_Handler
FIQ_Handler B FIQ_Handler

6-16
Cortex-M3 Interrupt Handling
! One Non-Maskable Interrupt (INTNMI) supported
! 1-240 prioritizable interrupts supported
" Interrupts can be masked
" Implementation option selects number of interrupts supported
! Nested Vectored Interrupt Controller (NVIC) is tightly coupled with processor core
! Interrupt inputs are active HIGH

INTNMI

1-240 Interrupts NVIC


Cortex-M3

INTISR[239:0] Processor Core

Cortex-M3

Interrupts diagrammatically
Each interrupt is
individually enabled

Read by IRQ handler


and put into Program
Counter (PC)
Interrupt
signals from
32 sources Select which interrupts are
FIQ and which are
vectored IRQ
6-18
Vectored IRQs
IRQ status[0:31]

6-19

Vectored IRQ process


Each of the 32 interrupt sources from the various peripherals is
allocated a slot in the table. Eg. Timer 0 is allocated the number 4,
external interrupt 0 is allocated to 14. Vector
IRQ
Address
Priority encoder Vector
0 Address
1
Timer 0 Vec 0
4 Lvl 9
Vec 1
Interrupt Sourcs

Vec 2
Vec 3
14 Lvl 15 X Vec 4
.
Vec 31

31
6-20
Interrupt Handling
Flowchart

Interrupt Service Routine Entry


! When receiving an interrupt the processor will finish the
current instruction for most instructions
! To minimize interrupt latency, the processor can take an
interrupt during the execution of a multi-cycle instruction - see
next slide
! Processor state automatically saved to the current stack: 8
registers are pushed: PC, R0-R3, R12, LR, xPSR to stack
! During (or after) state saving the address of the ISR is read
from the Vector Table
! Link Register is modified for interrupt return
! First instruction of ISR executed
" For
Cortex-M3 or Cortex-M4 the total latency is normally
12 cycles, however, interrupt late-arrival and interrupt tail-
chaining can improve IRQ latency
! ISR executes from Handler mode with Main stack

Return from Interrupt
Flowchart

Returning From Interrupt


! CPU returns from interrupt with the following instructions when the PC is loaded
with magic value of 0xFFFF_FFFX (same format as EXC_RETURN)
" LDR PC, ..
" LDM/POP which includes loading the PC
" BX LR (most common) ; Branch, PC<=LR
! If no interrupts are pending, foreground state is restored
" Stack and state specified by EXC_RETURN is used
" Context restore on Cortex-M3 and Cortex-M4 requires 10 cycles
! If other interrupts are pending, the highest priority may be serviced
" Serviced if interrupt priority is higher than the foregrounds base priority
" Latency for servicing new interrupt is only 6 cycles on M3/M4 (state already
saved)
! If state restore is interrupted, it is abandoned
" New ISR executed without state saving (original state still intact and valid)
" Must still fetch new vector and refill pipeline (6-cycle latency on M3/M4)


Multiple Interrupt Handling Example
Higher Priority

IRQ1

IRQ2

IRQ3

Base CPU
Time
Core Execution Foreground ISR2 ISR1 ISR2 ISR3 Foreground
(ISR 2 resumes)

Keil 'C' Language Extensions


! The C Compiler allows designation of a 'C' function
as an Interrupt Handler by adding __irq after the
function header in both the function declaration and
the function definition.
void IntHandler(void) __irq;
! The Interrupt handler cannot accept any input
arguments i.e the argument list must be (void)
! Also the return type MUST be void.
! An interrupt handler function MUST NEVER be
called directly from the main program code!!
! The Interrupt Handler is only invoked by the
hardware interrupt vectoring mechanism.
6-26
To summarise the procedure
! Configure the peripheral i.e. enable interrupts
within the peripheral
! Enable the peripheral bit within the VIC
! Select to use either the FIQ or IRQ interrupt
! Set the priority of the interrupt 0-15 (0 highest)
! Set the Vector address for the interrupt handler
" FIQ - fixed at address 0x0000001C
" IRQ - set vector address in relevant slot of VIC

! Write the interrupt handler, which should


terminate by clearing the request before returning.
6-27

Interrupt usage
! Used for non periodic and/or asynchronous
events.
! Avoids polling which is potentially wasteful of CPU
processing time.
! Allows the main program to be seen as a
background task and the interrupts as higher
priority tasks or events that must take precedence.
! Good for responding to events and data input.
! Avoids loss of input data which could happen with
polling
6-28
The Interrupt Handler
! Interrupt handler routine
" localvariables are created on each invocation
" use static keyword to preserve local variable value
between invocations e.g. static int value = 0;
! Data communication between main program and
ISR is via shared global variables.
" thisintroduces mutual exclusion problems
" Cannot access a common resource concurrently from
two execution threads (concurrent access)
! Other problems - Re-entrancy of functions
" The ISR calls a function that was being executed
when this interrupt occurred.
6-29

Ex: Interrupt Handler in C


! The example routine below reads a byte from
location 0xc0000000 and writes it to location
0xc0000004.

void __irq IRQHandler (void)


{
volatile char *base = (char *) 0xc0000000;
*(base+4) = *base;
}

6-30
Ex: Installing this Handler
! This IRQHandler function can be installed by the main
program:
int main()
{
unsigned *irqvec = (unsigned *)0x18;
*irqvec = Install_Handler ((unsigned)IRQHandler,
(unsigned)irqvec);
return 0;
}

6-31

Ex: Install_Handler Routine


! This implements the method described for loading the
vector table discussed earlier in this presentation.
! It returns the encoding that represents the branch
instruction that should be placed in the appropriate
vector.
unsigned Install_Handler (unsigned routine, unsigned vector) {
/* To succeed routine must be within 32Mb of vector */
unsigned vec;
vec =((routine - vector - 0x8) >>2)
if (vec & 0xff000000) flag_error( Out of range handler );
vec = 0xea000000 | vec
return vec;
}

6-32
Ex: Data Buffering and Interrupts
! Decouples main program from interrupt handler
! Moves data processing from the interrupt
handler in to the main program
! Use of "Circular Buffers" to provide optimum
buffer usage.
Data Buffer Main program
Interrupt Handler (size = N)
Rdptr
X0 Read data from
Input data from X1 buffer and
peripheral and Wrptr
X2 processes it.
store in buffer. Move Rdptr and
Move Wrptr decrement
pointer and count
increment count Count = 3
6-33

Ex: Data Buffering and Interrupts


! Interrupt Handler ! Part of main program
input X if (count > 0)
if (count < N) { //process all data
{ //store in buffer while (count > 0)
Buffer[Wrptr] = X {
Wrptr++ val = Buffer[Rdptr]
if (Wrptr == N) Rdptr++
{ if (Rdptr == N)
Wptr = 0 {
} Rdptr = 0
count++ }
} count--
//process val
What if count == N? }
What about mutual exclusion? }
What are initial values? 6-34