Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 Exception & Interruption

Similar presentations


Presentation on theme: "Chapter 9 Exception & Interruption"— Presentation transcript:

1 Chapter 9 Exception & Interruption
Optimization Technique in Embedded System (ARM) April

2 Introduction At the “heart” of an embedded system lie the exception handlers. They are responsible for handling errors, and other events generated by the external system. Efficient handlers can dramatically improve system performance. The process of determining a good handler method can be complicated, challenging, and fun.

3 Agenda This chapter is divided into three main sections,
Exception handling Covers the specific details of how the ARM processor handles exception. Interruption ARM defines an interrupt as a special type of exception. This section discuss the use of interrupt requests, as well as introducing some of the common terms, features, and mechanisms surrounding interrupt handling. Interruption handling Provides a set of interrupt handling methods.

4 Overview Exception and Interruption
Handle the system faults, I/O’s interruption OS support: SWI, memory protect Optimizing exception/interruption handling Make the frequent Exception/Interruption fast Challenges ARM provides seven exceptions Reset, Undefined Instruction, SWI, D-Abort, I-Abort, IRQ, FIQ

5 * ARM Processor Mode and Exception * Link Register Offsets
9.1 Exception Handling * ARM Processor Mode and Exception * Vector Table * Exception Priority * Link Register Offsets

6 Exception Exception Exception Handler Terms
is any condition that halt the normal execution. e.g., Reset, memory fail, undef-instr., SWI, external. Exception Handler Most exceptions have an associated software -- “exception handler”, a software routine that executes when an exception occurs. check the cause, then handle it. Terms ARM Processor Mode, Vector Table, Priorities Linker Register (return address)

7 9.1.1 ARM Exceptions and Modes
Each exception causes the core to enter a specific mode. When an exception causes a mode change, the core automatically Save the CPSR to SPSR of the exception mode Save the PC to LR of the exception mode Sets the CPSR to the exception mode Sets PC to the address of the exception handler

8 Processor Modes Processor Modes Description User usr
Normal program execution mode FIQ fiq Support high speed channel (data transfer) IRQ irq General purpose interrupt handling Supervisor svc Protected mode for OS Abort abt Memory Protection Undefined und Supports SW emulation of HW coprocessor System sys Runs privileged OS tasks

9 Change Mode Mode changes
can be made under SW control, or can be caused by external interrupts or exception processing.

10 Privileged, Exception Mode
Privileged & Exception Modes Modes other than User mode are known as privileged modes. They have full access to system resources, and can change mode freely. Five of them are known as “exception modes” FIQ, IRQ, SVC, ABT, UNDEF Except only the System mode Which means System cannot be entered from any exception, instead it’s entered by changing CPSR mode bit.

11 System Mode System Mode It’s not entered by any exception
It has exactly the same registers available as User mode. It is used for User code that need privilege to access OS resource.

12 9.1.2 Vector Table Vector table in ARM
is a table of “branch” instructions, rather than a table of addresses (pointers) as in 8086; Address Exception 0x0000,0000 Reset 0x0000,0004 Undefined 0x0000,0008 SWI 0x0000,000c Prefetch Abort 0x0000,0010 Data Abort 0x0000,0014 Reserved 0x0000,0018 IRQ 0x0000,001c FIQ

13 Forms of Vector Entry The entries commonly contain branch instructions of one of the following forms B <addr> This branch instruction provide a branch relative from PC; LDR pc, [pc, #offset] This load register instruction loads the handler address from memory to the PC. The address is an absolute 32-bit value stored close to the vector table. LDR pc, [pc, #-0xff0] This specific instruction is only used when a vector interrupt controller is present (VIC PL190). This load-register instruction loads a specific routine address from address 0xfffff030. MOV pc, #immediate This move instruction copies an immediate value into the PC. It lest you span the full address space but at limited alignment (the address must be an 8-bit immediate rotated right by an even number of bits).

14 Example Entries of a Vector Table

15 9.1.3 Exception Priorities Exceptions can occur simultaneously.
So, the processor has to adopt a priority mechanism.

16 About “handler” The Reset exception is the highest priority exception.
Initialize the system (memory, cache) Initialize the external source before I or F enabled. Set up the stacks for all processor mode. Be careful in handler During the first few instructions of the handler, it is assumed that no exception or interrupts will occur. Also, the code should be designed to avoid SWIs, undefined instructions, and memory accesses that may abort, that is, the handler is carefully implemented to avoid further triggering of an exception.

17 About “priority” Can FIQ be serviced inside DABT handler ?
Yes. DABT occurs when the memory controller or MMU indicates an invalid memory address (e.g., no physical memory for an address), or when current read/write attempting without correct access permissions. An FIQ exception can be raised within a DABT handler, since FIQ exception are not disabled.

18 Should It Be Interrupted ?
Cannot Be Interrupted Yes No By Self DABT FIQ IRQ and below - IRQ FIQ, DABT PABT SWI UDEF

19 Entering an exception What happens on exception occurs
R14_<exception_mode> = return link; SPSR_<exception_mode> = CPSR; /*Save CPSR*/ CPSR[4:0] = Exception Mode num; CPSR[5] = 0; /* ARM state */ if <exception_mode> == RESET or FIQ CPSR[6] = 1; /* Disable FIQ */ CPSR[7] = 1; /* Disable INT */ PC = exception vector address

20 9.1.4 On Return in Handler Linker Register Offset
Recommended code for handler exiting. Entry Instruction Return R14 save PC meaning BL MOV PC, R14 PC+4 On return, PC will point to the address of BL, SWI, or LD/ST. “Linker(R14)” always save the PC on exception. SWI MOVS PC, R14_svc UDEF MOVS PC, R14_und PABT SUBS PC, R14_abt, #4 DABT SUBS PC, R14_abt, #8 PC+8 FIQ Where, PC point to the address of still NOT EX-passed instr. IRQ RESET

21 Leaving an exception What should handler do on exit
PC = LR – <offset_XXX>; // Jump CPSR = SPSR; // XXX[S] instruction Clearing the interrupt DISABLE flags (set on entry) Note: T-bit (Thumb) The action of restoring the CPSR from the SPSR automatically reset the T-bit to whatever value it held immediately prior to the exception.

22 9.2 Interrupts & Assigning interrupts & Interrupt latency
& IRQ and FIQ exception & Basic interrupt stack design and implementation

23 Types of Interrupts There are two types of interrupts available on the ARM processor. The first type causes an exception raised by an external peripheral – namely, IRQ, FIQ; The second type is a specific instruction that cause an exception – the SWI instruction. Both types suspend the normal flow of a program.

24 9.2.1 Assigning Interrupts A system designer can decide which hardware peripheral can produce which interrupt request. This decision can be made in hardware or software (or both) and depends upon the embedded system being used. An Interruption Controller (IC) connects multiple external interrupts to one of the two ARM interrupt requests. Sophisticated controller can be programmed to allow an external interrupt source to cause either an IRQ or FIQ exception.

25 Standard Design Principle
When it comes to assigning interrupts, system designer have adopted a standard design practice: Software Interrupt are normally reserved to call privilege OS routines. (e.g., SWI) Interrupt Request are normally assigned for general-purpose interrupts. (e.g., timer tends to be an IRQ) Fast Interrupt Request are normally reserved for a single interrupt source that require a fast response time. (e.g., DMA specifically used to move blocks of memory)

26 9.2.2 Interrupt Latency Interrupt-driven embedded systems have to fight a battle with interrupt latency latency: the interval of time from an external interrupt request signal being raised to the first fetch of an instruction of a specific interrupt service routine (ISR). System architects must balance the system design to handle multiple simultaneous interrupt sources and minimize interrupt latency. If the interrupts are not handled in a timely manner, then system will exhibit slow response times.

27 Minimize Interrupt Latency
Software handlers have two main methods to minimize interrupt latency. (1) Nested interrupt handler This is achieved by re-enabling the interrupts as soon as the interrupt source has been serviced (so it will not generate more interrupts) but before the interrupt handling is complete. (2) Prioritization You program the IC to ignore interrupts of the same or lower priority than the interrupt you are handling. So, only a high-priority task can interrupt your handler. (You then re-enable interrupts) Conculsion The processor spends time in the low-priority interrupts until a higher-priority interrupt occurs. Therefore, higher-priority interrupts have a lower average interrupt latency than the lower-priority interrupts.

28 9.2.3 IRQ and FIQ Exceptions IRQ and FIQ exceptions only occur when a specific interrupt mask is cleared in the CPSR. The ARM processor will continue executing the current instruction in the execution stage of the pipeline before handling the interrupt. An important factor in designing a deterministic interrupt handler since some instruction require more cycle to complete the execution stage.

29 Standard Procedure of IRQ or FIQ Handling
1. Processor changes to a specific interrupt request mode, which reflects the interrupt being raised. 2. The previous mode’s CPSR is saved into the SPSR of the new interrupt request mode (callee). 3. The PC is saved in the LR of the new interrupt request mode (callee). 4. Interrupt/s are disabled – either the IRQ or both IRQ and FIQ exceptions are disabled in the CPSR. This immediately stops another interrupt request of the same type being raised. 5. The processor branches to a specific entry in the vector table.

30 Enabling/Disabling FIQ and IRQ Exception
The ARM processor core has a simple procedure to manually enable and disable interrupts that involves modifying the CPSR when the processor is in a privileged mode.

31 Details of Exceptions (ARM7)
Ref. DDI0210B_7TDMI_R4.pdf

32 1. FIQ Fast Interrupt Request(FIQ) To be as fast as possible On return
is designed to support Data Transfers or Channel Processes. To be as fast as possible In FIQ mode, eight banked registers remove the requirement for register saving, which reduces context switching overhead. On return SUBS PC, R14_fiq, #4 IF ID EX

33 2. IRQ Interrupt Request(FIQ) is caused by a LOW level on the nIRQ input. On return SUBS PC, R14_fiq, #4 IF ID EX

34 3. ABORTs An “abort” indicates that the current memory access cannot be completed. “Abort” is signaled by the external ABORT input. The ARM7TDMI processor checks the abort exception at the end of memory access cycles. The abort mechanism allows the implementation of a demand-paged virtual memory system. In such a system, the processor is allowed to generate arbitrary address. When the data at the address is unavailable, the Memory Management Unit (MMU) signals an abort. There are two types of aborts: Prefetch and Data.

35 What to do by ABORT handler
The abort handler must then: Work out the cause of the abort and make the requested data available Load the instruction that cause the abort using an "LDR Rn, [R14_abt,#-8]" instruction to determine whether that instruction specifies base register write-back (a problem). If it does, the abort handler must then: determine from the instruction what the offset applied to the base register by the write-back was apply the opposite offset to the value that will be reloaded into the base register when the abort handler returns This ensures that when the instruction is retired, the base register will have been restored to the value it had when the instruction was originally executed.

36 3a. Prefetch Abort Prefetch Abort On return
When a Prefetch Abort occurs, the ARM7TDMI processor marks the prefetched instruction as "invalid", but does not take the exception until the instruction reaches the EX stage of the pipeline. If the instruction is not executed, for example because it fails its condition codes or because a branch occurs while it is in the pipeline, the abort does not take place. On return SUBS PC, R14_abt, #4 // retry the aborted instruction IF INVALID ID

37 3b. Data Abort As a Data Abort occurs, actions taken depends on the instruction type: For LDR/STR (single data transfer): handler should care “base register write-back”. In ARM7, HW will prevent the destination register overwriting of dest-register with the loaded data. SWP (swapping): suppress the write operation. LDM/STM (multiple data transfer): preserve the dest-register until all memory loading have been successful. On return SUBS PC, R14_abt, #8 // retry the aborted instruction IF ID EX

38 4. SWI Software Interrupt Instruction (SWI) is used to enter Supervisor mode. The “SWI function number” is extracted from opcode (rather than operands) by handler. On return MOVS PC, R14_svc IF ID EX

39 5. UDEF When processor encounters an instruction that neither itself, nor any coprocessor in the system can handle, The core takes the “undefined instruction” trap. Emulation the “failed” instruction Software can use this mechanism to Extend the ARM instruction set by emulating Undefined coprocessor instructions. On return MOVS PC, R14_und // Restore CPSR, and go next IF ID EX

40 9.2.4 Basic Interrupt Stack Design
Exceptions handlers make extensive use of stack (compared to function call). SP_<mode>: individual sp pointer for each mode; The design of the exception stacks depends upon these factors OS requirement: each OS has its own requirements for stack design. Target Hardware: physical limit to the size and position of the stack in memory Location: where in the memory map the stack begins. Stack Size: depends upon the type of handler, nested (need more space) or non-nested.

41 Stack Overflow Problem
A Good stack design tries to avoid “stack overflow” – where the stack extends beyond the allocated memory. There are software techniques that identify overflow and allow corrective measures to take place to repair the stack before irreparable memory corruption occurs. The two main methods are (1) Memory Protection (2) call a “Stack Checking” function at the start of each routine.

42 Typical Memory Layout Where stack resides ? INT Stack User Stack
User heap User heap Text 0x Text INT Stack Vector Table Vector Table 0x 0x Type A Type B

43 Multiple Stacks Placement of stacks Three stack Note User Stack
0x0002,0000 User Stack Placement of stacks Individual stack for each Mode. Three stack SVC, IRQ, USER Note Q: CPSR cannot be modified (to change mode) in User Mode ? A: System and User mode share the all registers. So, SP pointer can be set in SYS mode. User heap User Data Text 0x0000,8000 IRQ Stack 0x SVC Stack Vector Table 0x0000,0000

44 9.3 Interrupt Handling Schemes

45 How to process an Interrupt
The schemes covered are the following Nonnested: one-by-one, exclusive. Nested: multiple processing without priority assignment. Re-entrant: multiple processing with priority. Prioritized: simple, direct, standard, group VIC(PL190) based ISR

46 9.3.1 Nonnested INT processing
The simplest interrupt handler is a handler that is nonnested: the interrupts are disabled until the control is return back to the interrupt task or process. This scheme is not suitable for complex embedded system that service multiple interrupts with differing priority levels. Stages 1. Disable interrupts: When the IRQ is raised, the ARM processor will disable further IRQ exceptions. The processor Mode is set, CPSR is copied to SPSR_irq, PC is set to point to Vector Table entry. 2. Save Context: On entry the handler code saves a subset of the current processor mode nonbanked registers. 3. Interrupt handler: Identify the external interrupt source and executes the appropriate interrupt service routine (ISR). 3. Restore Context 4. Enable Interrupts: Finally, PC and CPSR are set back.

47 case: non-nest For example Note interrupt_handler
SUB r14, r14, #4 // linker offset STMFD r13!, {r0-r3, r12, r14} //save CTX call <ISR> LDMFD r13!, {r0-r3, r12, pc} //restore CTX Note r0~3 and r12 are also preserved because of the ATPCS. This allows and ATPCS-compliant subroutine to be called within the handler.

48 9.3.2 Nested INT Processing A nested interrupt handler allows for another interrupt to occur within the currently called handler. This is achieved by reenabling the interrupts before the handler has fully serviced the current interrupt. For a real-time system, this complex the system, but get performance. Timing Issues The additional complexity introduce the possibility of subtle timing issues. it’s usually solved by protecting the context restoration from interruption, so that the next interrupt will not fill the stack (cause stack flow) or corrupt any of the registers.

49 Nested Interrupt Handler
Q: Why need to switch from IRQ to SVC? A: Because reenable INT in IRQ mode would lead to possible linker (r14_irq) corruption. Disable INT CTX Saving ISR Reschedule (include itself) Context Switching * Change mode from IRQ to SVC * Dump IRQ stack to SVC stack) Restore CTX Enable INT new ISR

50 Nested IRQ ISR (1) nestedInterruptHandler ; instruction state : comment SUB r14,r14,# ; 2 : STMDB r13!,{r0-r3,r12,r14} ; 2 : save context ; <service interrupt> BL read_RescheduleFlag ; 3 : more processing CMP r0,# ; 3 : if processing? LDMNEIA r13!,{r0-r3,r12,pc}^ ; 4 : then return MRS r2,SPSR ; 5 : copy SPSR_irq MOV r0,r ; 5 : copy r13_irq ADD r13,r13,#6* ; 5 : empty IRQ stack MRS r1,CPSR ; 6 : copy CPSR BIC r1,r1,#Maskmd ; 6 : ORR r1,r1,#SVC32md ; 6 : MSR CPSR_c,r ; 6 : change SVC mode Change to SVC mode, and Discard IRQ context (empty IRQ’s stack)

51 Nested IRQ ISR (2) (1) (2) (3) SUB r13,r13,#FRAME_SIZE-FRAME_R4
; 7 : make stack space STMIA r13,{r4-r11} ; 7 : save r4-r11 LDMIA r0,{r4-r9} ; 7 : r4-r9 IRQ stack BIC r1,r1,#I_Bit ; 8 : MSR CPSR_c,r ; 8 : enable int STMDB r13!,{r4-r7} ; 9 : save r4-r7 SVC STR r2,[r13,#FRAME_PSR] ; 9 : save PSR STR r8,[r13,#FRAME_R12] ; 9 : save r12 STR r9,[r13,#FRAME_PC] ; 9 : save pc STR r14,[r13,#FRAME_LR] ; 9 : save lr (1) Save the current SVC context in case the further interrupts Because INT will be enabled soon. (2) Dump out the prev-IRQ context saved in IRQ stack IRQ context is “disappearing” (3) Transfer RETURN control to SVC Copy the context of prev-IRQ into SVC stack (then SVC can return back directly, bypass the IRQ handler ) (1) (2) (3)

52 Nested IRQ ISR (3) ; <complete interrupt service routine>
LDMIA r13!,{r0-r12,r14} ; 11 : restore context MSR SPSR_cxsf,r ; 11 : restore SPSR LDMIA r13!,{r14,pc}^ ; 11 : return

53 9.3.3 Reentrant Interrupt Handler
A reentrant interrupt handler is a method of handling multiple interrupts where interrupts are filtered by priority Which is important if there is a requirement that interrupt with high priority have a lower latency. The basic difference between a reentrant and a nested interrupt handler is (1) Interrupts are reenabled early on in the reentrant interrupt handler. (2) Interrupts are prioritized.

54 How to enable Re-entrant
Disable INT CTX Saving Switch to SVC mode (Copy current stack to SVC stack) Enable EXC Reschedule ISR Don’t worry ! Has switched to SVC early. Restore CTX Enable IRQ CTX Saving Restore CTX new ISR

55 case: Re-entrant Code (1)
Save CTX into IRQ’s stack reentrantInterruptHandler ; instruction state : comment SUB r14, r14, # ; 2 : r14_irq-=4 STR r14, [r13, #IRQ_R14] ; 2 : save r14_irq MRS r14, SPSR ; 2 : copy SPSR STR r14, [r13, #IRQ_SPSR] ; 2 : save SPSR STR r0, [r13, #IRQ_R0] ; 2 : save r0 MOV r0, r ; 2 : copy r13_irq Change to SVC mode MRS r14, CPSR ; 3 : copy CPSR BIC r14, r14, #Maskmd ; 3 : ORR r14, r14, #SVC32md ; 3 : MSR CPSR_c, r ; 3 : enter SVC mode

56 case: Re-entrant Code (2)
Dump IRQ’s stack to SVC’s stack STR r14, [r13, #-8]! ; 4 : save r14 LDR r14, [r0, #IRQ_R14] ; 4 : r14_svc=r14_irq STR r14, [r13, #4] ; 4 : save r14_irq LDR r14, [r0, #IRQ_SPSR] ; 4 : r14_svc=SPSR_irq LDR r0, [r0, #IRQ_R0] ; 4 : restore r0 Save CTX in SVC mode STMDB r13!, {r0-r3,r8,r12,r14} ; 4 : save context Disable current IRQs, will enable IRQ later LDR r14, =ic_Base ; 5 : int crtl address LDR r8, [r14, #IRQStatus] ; 5 : get int status STR r8, [r14, #IRQEnableClear] ; 5 : clear interrupts

57 case: Re-entrant Code (3)
Enable IRQ (except external IRQs) MRS r14, CPSR ; 6 : r14_svc=CPSR BIC r14, r14, #I_Bit ; 6 : MSR CPSR_c, r ; 6 : clear IRQ int (I-bit) Call ISR BL process_Interrupt ; 7 : call ISR Enable external IRQs LDR r14, =ic_Base ; 9 : int ctrl address STR r8, [r14, #IRQEnableSet] ; 9 : enable ints Schedule another IRQ BL read_RescheduleFlag ; 9 : more processing

58 case: Re-entrant Code (4)
If no more IRQ, then Return CMP r0, # ; 8 : if processing LDMNEIA r13!, {r0-r3,r8,r12,r14} ; 8 : then load context MSRNE SPSR_cxsf, r ; 8 : update SPSR LDMNEIA r13!, {r14, pc}^ ; 8 : return Else, Save CTX, again (recursively) LDMIA r13!, {r0-r3, r8} ; 10 : else load reg STMDB r13!, {r0-r11} ; 10 : save context BL continue_Servicing ; 11 : continue service Return at last LDMIA r13!, {r0-r12, r14} ; 12 : restore context MSR SPSR_cxsf, r ; 12 : update SPSR LDMIA r13!, {r14, pc}^ ; 12 : return

59 9.3.4 Prioritized Simple Interrupt Handler
Nested vs. Prioritized Both the nonnested interrupt handler and the nested interrupt handler service interrupts on a “first-come-first-served” basis. In comparison, the prioritized interrupt handler will associate a priority level with a particular interrupt source. Methods of handling prioritization can either be achieved in hardware or software. In SW method, external IC should provide functions, like Set/Clear MASK bits, Read STATUE and SOURCE.

60 Prioritized Algorithm
A Good Priority Scheduling Algorithm based on standard interrupt controller in ARM. Winner CTX Saving (full) Disable INT Scheduing ISR CTX Saving (least) Read STATUS Schedule (Priority) Mask Victims (low-pri) Jump to Winner Enable INT Return

61 9.3.5 Standard Prioritized Simple priority Alternative – Early start
make decision by searching all INTs (less efficient); Determinate response time (good for real-time) Alternative – Early start Search from HIGH to LOW

62 9.3.6 Direct Prioritized What make the differences
Reduced handler entry Some of the processing is moved out of handler into the individual ISRs. e.g. MASK setting to disable lower INTs than itself Direct branch (rather than Table-driven) Disadvantage There is a small amount of code duplication among individual ISRs.

63 9.3.7 Group Prioritized Tradeoff Still challenge
Divide all into groups: Same priority in one group To be faster than 9.3.5 Reduce searching latency Reduce masking latency To be simple and less redundancy code than 9.3.6 Suitable for massive INTs handling Still challenge Good division means good tradeoff: balance, jam, etc.

64 9.3.8 VIC PL190 Based ISR To take advantage of the vector interrupt controller, the IRQ vector entry has to be modified. 0x0000,0018 LDR pc, [pc, #-0xff0] // jump NOTE: current_PC = 0x This instruction load an ISR address from the memory location “0xffff,f030” into the PC which bypass any interrupt handler since the interrupt source can be obtained directly from the hardware. It also reduce interrupt latency since there is only a single jump to a specific ISR.

65 case: ISR Code with VIC vectorServiceRoutine SUB r14,r14,#4 ; r14-=4
STMFD r13!, {r0-r3,r12,r14} ; save context MRS r12, spsr ; copy spsr STMFD r13!,{r12} ; save spsr MSR cpsr_c, #INTON|SYS32md ; cpsr_c=ift_system ; <insert code> MSR cpsr_c, #I_Bit|IRQ32md ; cpsr_c=Ift_irq LDMFD r13!, {r12} ; restore r12 (spsr_irq) MSR spsr_cxsf, r ; restore spsr LDR r1,=VICVectorAddr ; load VectorAddress STR r0, [r1] ; acknowledge VIC LDMFD r13!, {r0-r3,r12,pc}^ ; return

66 9.4 Summary An exception changes the normal sequential execution of instructions. There are seven exceptions Data Abort, Fast Interrupt Request, Prefetch Abort, Software Interrupt, Reset, and Undefined Instruction. Each exception has an associated ARM mode When an exception is raised, the processor goes into a specific mode and branches to an entry in the vector table. Each exception also has a priority level. Interrupts are a special type of exception that caused by an external peripheral. The IRQ exception is used for general operating system activities. The FIQ exception is normally reserved for a single interrupt source. Interrupt latency is the interval of time from a an external interrupt request signal being raised to the first fetch of an instruction of a specific interrupt service routine (ISR).


Download ppt "Chapter 9 Exception & Interruption"

Similar presentations


Ads by Google