NET3001 6 Interrupts

Embed Size (px)

Citation preview

  • 8/3/2019 NET3001 6 Interrupts

    1/44

    NET3001

    Interrupts

  • 8/3/2019 NET3001 6 Interrupts

    2/44

    Interrupts concepts

    Programs runs synchronously CPU: fetch-execute cycle (clocked operation). Activities performed according to order of instructions in

    program What is an interrupt?

    Special event requiring CPU to stop normal programexecution and perform some service related to that event.

    Examples: timer completion, I/O event, timeout, I/O

    completion, illegal opcode, arithmetic overflow, divide-by-0,etc.

    Interrupts allow forasynchronous execution of serviceroutines

    Example : Classroom questions.

  • 8/3/2019 NET3001 6 Interrupts

    3/44

    Why are Interrupts Used ?

    Coordinate the CPU with activities of I/O devices I/O devices under control of their own circuitry

    Data for I/O not under the control of CPU (fire alarm)

    Data transfer require CPU and I/O device to synchronize Device Response times: at least one order of magnitude

    slower than instruction execution

    CPU response time: want immediate action, preventingCPU from being tied up

    Remind the CPU to perform routine tasks.

    Provide a graceful way to handle software/hardware

    errors

  • 8/3/2019 NET3001 6 Interrupts

    4/44

    Originally appeared as synchronization mechanism between CPU- I/O

    End of I/O: device informs data transfer successful.

    Timer: a given amount of time elapsed

    Parity error in memory (memory checking circuits). Wrong Opcode: Control Unit detects non existing opcode

    Requires a wired connection to the CPU

    Hardware Interrupt : signal issued by circuitry (event)

    CPU interrupt response: temporarily branches to execute servicesprovided by Interrupt Service Routine (ISR) (executing programdelayed for a while).

    Hardware event triggers software response (internal CPU circuitry)

    Interrupt Mechanism

    CPU Device

  • 8/3/2019 NET3001 6 Interrupts

    5/44

    Real Time Programming

    Polling Polling: CPU asks all the devices whether there

    is anything to do. sequential programming: next instruction determined

    by control transfer instructions:

    /* polling */

    while (1) {

    if (keyPressed())

    doKeyStuff();if (timePassed())

    doOtherStuff();

    }

  • 8/3/2019 NET3001 6 Interrupts

    6/44

    Real Time ProgrammingInterrupts

    Physical events (or time) causes interrupt Interrupted processing: CPU doesnt know it

    was interrupted temporarily suspend current thread of control runs ISR resumes suspended thread of control

  • 8/3/2019 NET3001 6 Interrupts

    7/44

  • 8/3/2019 NET3001 6 Interrupts

    8/44

  • 8/3/2019 NET3001 6 Interrupts

    9/44

  • 8/3/2019 NET3001 6 Interrupts

    10/44

  • 8/3/2019 NET3001 6 Interrupts

    11/44

    Interrupt Properties Maskable

    Interrupt Maskability Maskable interrupts can be ignored/postponed

    by the CPU

    Enabled before interrupting the CPU (setting anassociated enable flag).

    NonMaskable interrupts cannot be ignored bythe CPU

    Interrupt requestpending: active but not yetserviced May or may not be serviced (depending on

    whether or not it is enabled)

  • 8/3/2019 NET3001 6 Interrupts

    12/44

  • 8/3/2019 NET3001 6 Interrupts

    13/44

  • 8/3/2019 NET3001 6 Interrupts

    14/44

  • 8/3/2019 NET3001 6 Interrupts

    15/44

  • 8/3/2019 NET3001 6 Interrupts

    16/44

    STM32 Interrupt ProcessingSequence

    When does the MCU recognize interruptrequests? When it reaches a point where it can remember

    the execution of the current instruction Why?

    after we return from interrupt, we need tocontinue operating as if nothing had happened!

  • 8/3/2019 NET3001 6 Interrupts

    17/44

    Interrupt Processing Sequence

    On the STM32, the interrupt service cycleincludes:

    1. finish the current instruction or take it to the stage where it can be remembered2. save the critical registers on the stack

    PSR, PC, LR, r12, r3, r2, r1, r0

    3. put 0xFFFF.FFF9 into LR (r14)4. fetch the appropriate vector into PC (r15)

  • 8/3/2019 NET3001 6 Interrupts

    18/44

    Interrupt Properties : Priority

    What happens if two interrupts occur at thesame time ?

    CPU assigns priority to each potential source

    First, priority STM32 Priority : Assigned in order of their

    position in the vector table Increasing priority at higher address

    Reset : highest priority

    Timer : lower priority

  • 8/3/2019 NET3001 6 Interrupts

    19/44

    STM32 Interrupt Vector Table

    Address Usage

    0x0000 starting value of the stack pointer

    0x0004 staring location of the program

    0x0008

    0x000C..380x003C

    0x0040..54

    0x0058 EXTI pin 0

    0x005C EXTI pin 1 (our keyboard)

    0x0060 EXTI pin 20x0064 EXTI pin 3

    0x0068 EXTI pin 4

    non maskable interrupt

    ....there are 12 others, spec'd by ARMSysTick interrupt

    ....various others, spec'd by ST

    ......and many others

  • 8/3/2019 NET3001 6 Interrupts

    20/44

    Interrupt Vectors in C

    /* do nothing functions */

    void default_isr (void) { return; }

    #define STACK_TOP 0x20002000

    extern void _start(void);

    /* vector table */

    void (*myvectors[])(void) __attribute__ ((section(".vectors")))= {

    (void(*)(void)) STACK_TOP, // stack pointer

    _start, // code entry point

    default_isr, // handle non-maskable interrupts

    default_isr, // handle hard faults0,0,0,0, /* 10...1f */

    0,0,0,0, /* 20...2f */

    0,0,0,timer_isr, /* 30...3f */

    0,0,0,0, /* 40...4f */

    0,0,0,key_isr /* 50...5f */

    };

  • 8/3/2019 NET3001 6 Interrupts

    21/44

    Interrupt Service Routine

    ISR is the term usually used for the subroutinethat handles the interrupt on the way in, you should disable global interrupts

    I recommend dint() on many devices, the local interrupt is disabled, and

    blocks further interrupts ofthis type some time in the routine, you probably want to clear the

    IFLG to allow more interrupts ofthis type I recommend you do this on the way out this is called acknowledging the interrupt

    just before you return, you should enable interrupts eint()

  • 8/3/2019 NET3001 6 Interrupts

    22/44

    Interrupt Properties : Priority

    What if an interrupt occurs during the execution of theprevious ISR?

    Answer: interrupt processing sequence

    Scenario 1: ISR for a low-priority interrupt is runningwhen a higher-priority interrupt occurs.

    Scenario 2: ISR for a high-priority interrupt is runningwhen a lower-priority interrupt occurs.

    Scenario 3: ISR is running when a reset occurs.

    St f I t t

  • 8/3/2019 NET3001 6 Interrupts

    23/44

    Steps of InterruptProgramming

    Step 1. Initialize the interrupt vector table (Install the vector) assembly: use the .vectors section and position the

    .word pointer to your ISR C: add the entry to the vector array

    Step 2. Write the interrupt service routine assembly: it's just a subroutine you mustobey the EABI !! don't use r4....r11

    C: it's just a subroutine our compiler makes code that is EABI

    Step 3. Re-enable the interrupt hardware If you disable global interrupts, make sure to re-enable

    global interrupts

  • 8/3/2019 NET3001 6 Interrupts

    24/44

    Simple Keypad Driver

    Program displays all keystrokes on the 7 segmentdisplay

    Runs forever Interrupt-driven : Port A interrupts signal key press

    char key = 0xFF;

    main(){; Init Hardware; Enable interruptseint();for (;;) {while (key == 0xFF)

    {}show7Seg(key);key = 0xFF

    }

    keyboard_isr(void) {

    small delaymeasure voltage

    convert to key numberkey = key number

    acknowledge irqreturn

    }

    E l I t t D i

  • 8/3/2019 NET3001 6 Interrupts

    25/44

    Example : Interrupt DrivenKeypad

    unsigned char key = 0xFF;

    int main(void) {

    initHardware(); // power up; enable LEDs

    /* set up the keyboard interrupt */

    EXTI->IMR |= 2; // enable interrupt from bit 1

    EXTI->RTSR |= 2; // interrupt on rising edgeAFIO->EXTICR[0] |= 0; // select the interrupt from port A

    NVIC->ISER[0] |= (1

  • 8/3/2019 NET3001 6 Interrupts

    26/44

    Example : Interrupt DrivenKeypad ISR

    void key_isr(void) {

    int r;

    // measure the A/D value on keyboard pin

    r = measureKey();// convert this to a key value and set the global

    key = convertKeyMeasuretoKey(r);

    // force the interrupt flag down,

    // to get ready for nextEXTI->PR |= 2;

    }

    // now you must add this routine to the vector table

    Programming Interrupts in C

  • 8/3/2019 NET3001 6 Interrupts

    27/44

    Programming Interrupts in CARM vs others

    in ARM/Cortex, the ISR is just another subroutine this works because of the EABI

    void timer_isr(void) {

    // do things at interrupt time

    // and reset the interrupt request (acknowledge) if req'd

    }

    in other architectures, the ISR must be declared as aspecial kind of subroutine with certain properties the address of the ISR is added to the vector table the ISR ends with an reti instruction

    so you must not call your ISR as a normal subroutine

    the ISR preserves all registersinterrupt (TIMERB1_VECTOR) timerB_isr(void) {

    // do things at interrupt time

    // and reset the interrupt request

    } //

  • 8/3/2019 NET3001 6 Interrupts

    28/44

    ISR

    yourInterrupt Service Routine should perform any high speed operations required otherwise, do as little as possible

    finish by resetting the interrupt request on the STM32, some types of interrupt are automatically

    reset, such as SysTick most interrupts require a manual reset for example, the keyboard (PortA interrupts) must finish

    with the lineEXTI->PR |= 2; // reset the PendingRequest, bit 1 this process is often called acknowledging the interrupt

    C Example : Interrupt Driven

  • 8/3/2019 NET3001 6 Interrupts

    29/44

    C Example : Interrupt DrivenKeypad

    voidK_ISR(void) { // you can use any nameint r;

    r = measureKeyboard();

    key = convertKeyMeasuretoKey(r);

    EXTI->PR |= 2; // acknowledge the interrupt}

    C Example : Interrupt Driven

  • 8/3/2019 NET3001 6 Interrupts

    30/44

    C Example : Interrupt DrivenKeypad

    /* this version turns interrupts back on immediately */

    voidKISR(void) { // you can use any nameint r;

    eint(); // turn global interrupts back on// we won't get another keyboard interrupt, because// the P2IFG bit is still set// we MIGHT get a timer interrupt, but that's ok

    r = measureKeyboard();

    key = convertKeyMeasuretoKey(r);

    EXTI->PR |= 2; // acknowledge the interrupt

    }

    Asm Example : Interrupt Driven

  • 8/3/2019 NET3001 6 Interrupts

    31/44

    Asm Example : Interrupt DrivenKeypad

    .textkisr: push {lr}

    bl measureKeyboard // returns the key value in r0

    // this routine sends r0 as its argument and returns r0bl convertKeyMeasuretoKey

    ldr r1,=key // save itstrb r0,[r1]

    ; clear the interrupt request bit (acknowlege)ldr r1,=EXTIldr r0,[r1,#PR]

    orr r0,r0,#2str r0,[r1,#PR]

    pop {pc} // and return from ISR

    .section .vectors, a

    .org 0x5c

    .word kisr

  • 8/3/2019 NET3001 6 Interrupts

    32/44

    Interrupt Latency & Overhead

    Latency (Response time) Delay from the time that an interrupt occurs until it is

    serviced.

    Overhead Time taken to perform a service, over and above the

    service itself. Interrupt overhead.

    saving registers, then jump to isr (= 11 cycles)

    restore the registers at the end, then jump (11 cycles)

    22 cycles = 2.8 sec for a 1MHz clock.

    Subroutine overhead for EABI

    push registers to save

    establish the frame sp->r7

    pop the regs on the way out

    Interrupts do provide short latency (if enabled) but incur overhead.

    S mmar of Interr pt Coding

  • 8/3/2019 NET3001 6 Interrupts

    33/44

    Summary of Interrupt Coding

    in Assembler in main code

    enable interrupts EINT

    in ISR

    write it to conform to EABI ack the interrupt

    write the IRQ vector

    in C in your main code

    enable interrupts eint()

    write the ISR

    ack the interrupt

    add the ISR name to the vector table

    in both cases

    be quick in the ISR, do your heavy work in the main code

    Interrupt-Driven versus Polled

  • 8/3/2019 NET3001 6 Interrupts

    34/44

    Interrupt-Driven versus PolledI/O

    PollingPro: shortest CPU latency (response time) if busy-

    waitingCon: either CPU cant do other work orthe devices

    latency dependent on the amount of other work.

    InterruptsPros: - Deterministic latency for a device

    - CPU can perform other work when idle

    - Software structure remains clean when handling manyinterrupts

    Con: Interrupt Overhead Saving and restoring of CPU status and other registers.

    A l i f I t t D i

  • 8/3/2019 NET3001 6 Interrupts

    35/44

    Analysis of Interrupt-DrivenProgram Behaviour

    The software is separated into background andforeground threads of control

    CPU Utilization Diagram

    time

    main init ISR main ISR main ISR

    1st Interrupt 2nd Interrupt 3rd Interrupt

    What is this value ?Is it deterministic ?At what point in main() is it interrupting

    B h i A l i f

  • 8/3/2019 NET3001 6 Interrupts

    36/44

    Behaviour Analysis ofInterrupt-Driven Program

    Thread Diagrammain ISR Time

    char = keystrokeRTI

    char = keystrokeRTI

    Interrupt

    What is this value ?Is it deterministic ?At what point in main() isit interrupting

    Event Driven Thinking : An

  • 8/3/2019 NET3001 6 Interrupts

    37/44

    Event-Driven Thinking : AnInterference Scenario

    In the main loop :

    Where can interrupts happen ?

    Can any data be lost ?

    waiting:ldr r1,=key // address of key

    ldrb r0,[r1]cmp r0, #0xffbeq waiting

    ldr r2,=sevenSegLUTldrb r0,[r2,r0] // convert from key to 7 seg patternldr r2,=PCOUTstrb r0,[r2]

    mov r0,#0xFFstrb r0,[r1] // and write a 0 back into keyment

    b #waiting

    E ent Dri en Thinking An

  • 8/3/2019 NET3001 6 Interrupts

    38/44

    Event-Driven Thinking : AnInterference Scenario

    In the main loop :

    Where can interrupts happen ?

    Can any data be lost ?

    waiting:ldr r1,=keyldrb r0,[r1] // read keycmp r0,#0xFFbeq waiting

    ldr r2,=sevenSegLUTldrb r0,[r2,r0] // convert key value to 7seg patternldr r2,=PCOUT

    strb r0,[r2] // light up the 7 seg LED'smov r0,#0xFFstrb r0,[r1] // and reset key to 0xFF

    b waiting

    E t D i Thi ki A

  • 8/3/2019 NET3001 6 Interrupts

    39/44

    Event-Driven Thinking : AnInterference Scenario

    Interference : what are the chances of key being

    corrupted?

    Critical Sections : how can we protect key and preventthe corruption?

    Just an introduction . more to come.

    Types of Computer Event Flow

  • 8/3/2019 NET3001 6 Interrupts

    40/44

    Types of Computer Event Flow

    Polled, inline code, no O/S like the code we've been creating

    Polled, inline code, with an O/S like the code you wrote in earlier courses

    Interrupt based I/O, no O/S like the code for the next few assignments

    Interrupt based I/O, serviced by the O/S like small operating systems: OS9

    Cooperative multi-tasking like Windows 3/95, original Mac OS Preemptive multi-tasking

    like QNX

    Preemptive multi-tasking with virtual memory like Unix, Linux, WindowsNT/XP, Mac OSX

    Simple code flow

  • 8/3/2019 NET3001 6 Interrupts

    41/44

    Simple code flow

    Polled, inline code, no O/S written just as a loop of read/test/decide/act

    it's tricky to appear to do 2 or more things at

    once it's difficult to modify

    Polled, inline code, with an O/S again, a loop, except the access to I/O is done

    by calling back into the O/S for services (viasubroutine calls)

    OS interaction with interrupts

  • 8/3/2019 NET3001 6 Interrupts

    42/44

    OS interaction with interrupts

    Interrupt based I/O, no O/S quicker response to events

    still need a main task that handles the doing 2 things at once loop

    Interrupt based I/O, serviced by the O/S the O/S deals with common tasks:

    get a key, detect an action

    measure the passage of time

    measure the battery

    read/write to disk/flash you still end up calling the O/S for services, via subroutines

    More sophisticated O/S

  • 8/3/2019 NET3001 6 Interrupts

    43/44

    interaction

    Cooperative multi-tasking The situation is turned around: THE O/S CALLS

    YOUR PROGRAM AS A SUBROUTINE! you must write your code as a subroutine, and it should

    act quickly and return ASAP yes, you ARE allowed to call back into the O/S

    this creates deep nests of calling/call-back

    the rest of this course deals with cooperative

    multitasking

    More sophisticated O/Si i

  • 8/3/2019 NET3001 6 Interrupts

    44/44

    interaction

    Preemptive multi-tasking You can write your program as if it's the only one, and

    the O/S will switch back and forth between other

    programs, making it appear that 2 things arehappening at once

    You can call on the O/S for services, but quite often,the O/S will wait on your call, for the service tofinish.

    not covered in this course