interrupt exceptions

32
Presented by Sateesh Kumar G Interrupts and Exception “Learn today , Lead Tomorrow”

Upload: sat-kg

Post on 13-Apr-2017

109 views

Category:

Technology


0 download

TRANSCRIPT

Presented bySateesh Kumar G

Interrupts and Exception

“Learn today , Lead Tomorrow”

The Hardware Part Interrupts and Exceptions Exception Types and Handling Interrupt Request Lines (IRQs) Programmable Interrupt Controllers (PIC) Interrupt Descriptor Table (IDT) Hardware Dispatching of Interrupts

The Software Part Nested Execution Kernel Stacks SoftIRQs, Tasklets Work Queues Threaded Interrupts

Contents

Sateesh kg

Simplified ArchitectureSateesh kg

CentralProcessing

Unit

MainMemory

I/Odevice

I/Odevice

I/Odevice

I/Odevice

system bus

CPU fetch-execute-check interruptSateesh kg

Fetch instruction at IP

Advance IP to next instruction

Decode the fetched instruction

Execute the decoded instruction

Interrupt?

no

Save context

Get INTR ID

Lookup ISR

Execute ISR

yes IRET

User Program

IP

ld

add

st

mul

ld

sub

bne

add

jmp

InterruptsSateesh kg

An interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention.

Hardware interrupts are used by devices to communicate that they require attention from the operating system.

A software interrupt is caused either by an exceptional condition in the processor itself, or a special instruction in the instruction set which causes an interrupt when it is executed.

Forcibly change normal flow of control Similar to context switch (but lighter weight)

Hardware saves some context on stack; Includes interrupted instruction if restart needed Enters kernel at a specific point; kernel then figures out which interrupt handler should run Execution resumes with special “iret” instruction

Many different types of interrupts

Interrupts trigger typesSateesh kg

Level-triggeredA level-triggered interrupt is an interrupt signalled by maintaining the interrupt line at a high or low level. A device wishing to signal a Level-triggered interrupt drives the interrupt request line to its active level (high or low), and then holds it at that level until it is serviced. It ceases asserting the line when the CPU commands it to or otherwise handles the condition that caused it to signal the interrupt.

Edge-triggeredAn edge-triggered interrupt is an interrupt signalled by a level transition on the interrupt line, either a falling edge (high to low) or a rising edge (low to high). A device, wishing to signal an interrupt, drives a pulse onto the line and then releases the line to its inactive state. If the pulse is too short to be detected by polled I/O then special hardware may be required to detect the edge.

Interrupts trigger types … contdSateesh kg

HybridSome systems use a hybrid of level-triggered and edge-triggered signalling. The hardware not only looks for an edge, but it also verifies that the interrupt signal stays active for a certain period of time.

Message-signaledA message-signalled interrupt does not use a physical interrupt line. Instead, a device signals its request for service by sending a short message over some communications medium, typically a computer bus. The message might be of a type reserved for interrupts, or it might be of some pre-existing type such as a memory write.

DoorbellIn a push button analogy applied to computer systems, the term doorbell or doorbell interrupt is often used to describe a mechanism whereby a software system can signal or notify a computer hardware device that there is some work to be done.

Types of InterruptsSateesh kg

Asynchronous From external source, such as I/O device Not related to instruction being executed

Synchronous (also called exceptions) Processor-detected exceptions:

Faults — correctable; offending instruction is retried Traps — often for debugging; instruction is not retried Aborts — major error (hardware failure)

Programmed exceptions: Requests for kernel intervention (software intr/syscalls)

FaultsSateesh kg

Instruction would be illegal to execute Examples:

Writing to a memory segment marked ‘read-only’ Reading from an unavailable memory segment (on disk) Executing a ‘privileged’ instruction

Detected before incrementing the IP The causes of ‘faults’ can often be ‘fixed’ If a ‘problem’ can be remedied, then the CPU can just resume its execution-cycle

TrapsSateesh kg

Instruction would be illegal to execute Examples:

Writing to a memory segment marked ‘read-only’ Reading from an unavailable memory segment (on disk) Executing a ‘privileged’ instruction

Detected before incrementing the IP The causes of ‘faults’ can often be ‘fixed’ If a ‘problem’ can be remedied, then the CPU can just resume its execution-cycle

Error ExceptionsSateesh kg

Most error exceptions — divide by zero, invalid operation, illegal memory reference, etc. — translate directly into signals

This isn’t a coincidence. . . The kernel’s job is fairly simple: send the appropriate signal to the current process

force_sig(sig_number, current); That will probably kill the process, but that’s not the concern of the exception handler One important exception: page fault An exception can (infrequently) happen in the kernel

die( ); // kernel oops

Intel Reserved ID numbersSateesh kg

Of the 256 possible interrupt ID numbers, Intel reserves the first 32 for ‘exceptions’ OS’s such as Linux are free to use the remaining 224 available interrupt ID numbers for their own purposes

(e.g., for service-requests from external devices, or for other purposes such as system-calls) Examples: 0: divide-overflow fault 6: Undefined Opcode7: Co-processor Not Available11: Segment-Not-Present fault12: Stack fault13: General Protection Exception14: Page-Fault Exception

Hardware InterruptsSateesh kg

I/O devices have (unique or shared) Interrupt Request Lines (IRQs)IRQs are mapped by special hardware to interrupt vectors, and passed to

the CPUThis hardware is called a Programmable Interrupt Controller (PIC)

x86CPU

MasterPIC

(8259)

SlavePIC

(8259)INTR

Programmable Interval-TimerKeyboard Controller

Real-Time Clock

Legacy PC Design (for single-proc

systems)

SCSI Disk

Ethernet

IRQs

Interrupt ControllerSateesh kg

Responsible for telling the CPU when a specific external device wishes to ‘interrupt’

Needs to tell the CPU which one among several devices is the one needing service

PIC translates IRQ to vector Raises interrupt to CPU Vector available in register Waits for ack from CPU

Interrupts can have varying priorities PIC also needs to prioritize multiple requests

Possible to “mask” (disable) interrupts at PIC or CPU Early systems cascaded two 8 input chips (8259A)

Example : Interrupt on x86Sateesh kg

80386 core has one interrupt line, one interrupt acknowledge line Interrupt sequence:

Interrupt controller raises INT line80386 core pulses INTA line low, allowing INT to go low80386 core pulses INTA line low again, signaling controller to put interrupt number on data bus

INT:

INTA:

Data bus: Interrupt #

Multiple Logical ProcessorsSateesh kg

Multi-CORE CPU

CPU0

CPU1 I/O

APICLOCALAPIC

LOCALAPIC

Advanced Programmable Interrupt Controller is needed to perform ‘routing’ of I/O requests from peripherals to CPUs

(The legacy PICs are masked when the APICs are enabled)

APIC , IO-APIC, LAPICSateesh kg

Advanced PIC (APIC) for SMP systems Used in all modern systems Interrupts “routed” to CPU over system bus IPI: inter-processor interrupt

Local APIC (LAPIC) versus “frontend” IO-APIC Devices connect to front-end IO-APIC IO-APIC communicates (over bus) with Local APIC

Interrupt routing Allows broadcast or selective routing of interrupts Ability to distribute interrupt handling load Routes to lowest priority process

Special register: Task Priority Register (TPR) Arbitrates (round-robin) if equal priority

Hardware to SoftwareSateesh kg

PIC CPU

Memory Bus

INTR

0

N

IRQs

IDT0

255

handler

idtr

Mask points

vector

Assigning IRQs to DevicesSateesh kg

IRQ assignment is hardware-dependent Sometimes it’s hardwired, sometimes it’s set physically, sometimes it’s programmable PCI bus usually assigns IRQs at boot Some IRQs are fixed by the architecture

IRQ0: Interval timer IRQ2: Cascade pin for 8259A

Linux device drivers request IRQs when the device is opened Note: especially useful for dynamically-loaded drivers, such as for USB or PCMCIA devices Two devices that aren’t used at the same time can share an IRQ, even if the hardware doesn’t

support simultaneous sharing

Assigning IRQs to DevicesSateesh kg

IRQ 0 – system timer (cannot be changed)IRQ 1 – keyboard controller (cannot be changed)IRQ 2 – cascaded signals from IRQs 8–15 (any devices configured to use IRQ 2 will actually be using IRQ 9)IRQ 3 – serial port controller for serial port 2 (shared with serial port 4, if present)IRQ 4 – serial port controller for serial port 1 (shared with serial port 3, if present)IRQ 5 – parallel port 2 and 3  or  sound cardIRQ 6 – floppy disk controllerIRQ 7 – parallel port 1. It is used for printers or for any parallel port if a printer is not present. It can also be potentially be shared with a secondary sound card with careful management of the port.IRQ 8 – real-time clock (RTC)IRQ 9 – Advanced Configuration and Power Interface (ACPI) system control interrupt on Intel chipsets.[1] Other chipset manufacturers might use another interrupt for this purpose, or make it available for the use of peripherals (any devices configured to use IRQ 2 will actually be using IRQ 9)IRQ 10 – The Interrupt is left open for the use of peripherals (open interrupt/available, SCSI or NIC)IRQ 11 – The Interrupt is left open for the use of peripherals (open interrupt/available, SCSI or NIC)IRQ 12 – mouse on PS/2 connectorIRQ 13 – CPU co-processor  or  integrated floating point unit  or  inter-processor interrupt (use depends on OS)IRQ 14 – primary ATA channel (ATA interface usually serves hard disk drives and CD drives)IRQ 15 – secondary ATA channel

Assigning Vectors to IRQSateesh kg

Vector: index (0-255) into interrupt descriptor table Vectors usually IRQ# + 32

Below 32 reserved for non-maskable intr & exceptions Maskable interrupts can be assigned as needed Vector 128 used for syscall Vectors 251-255 used for IPI

Assigning Vectors to IRQSateesh kg

Vector Hex number Description

0-19 0x0 – 0x13 Non-maskable interrupt & Exception

20 - 31 0x14 – 0x1F Inter Reserved

32 – 127 0x20 – 0x7F External Interrupt (IRQs)

128 0x80 Software Interrupt (system call exception)

129 – 238 0x81 – 0xEE External Interrupts (IRQs)

239 0xEF Local APIC Timer Interrupt

240 0xF0 Local APIC Thermal Interrupt

241 – 250 0xF1 – 0xFA Reserved for future use

251 – 253 0xFB – 0XFD Inter Processor Interrupts

254 0xFE Local APIC Error Interrupt

255 0xFF Local APIC Spurious interrupts

0- 31 - Synchronous Interrupts (e.g page fault)0-19 - watchdog timers20 – 31 - inter reserved32 – 127 - External Interrupts (IRQs)32 – 127 - What linux do is , responsible for calling only one

function called do_IRQ() for every interrupt in the hardware do_IRQ() runs(default handler)

Interrupt Descriptor tableSateesh kg

The ‘entry-point’ to the interrupt-handler is located via the Interrupt Descriptor Table (IDT)

IDT: “gate descriptors” Segment selector + offset for handler Descriptor Privilege Level (DPL) Gates (slightly different ways of entering kernel)

Task gate: includes TSS to transfer to (not used by Linux) Interrupt gate: disables further interrupts Trap gate: further interrupts still allowed

Interrupt MaskingSateesh kg

Two different types: global and per-IRQ Global — delays all interrupts Selective — individual IRQs can be masked selectively Selective masking is usually what’s needed — interference most common from two interrupts of the same

type

Putting it All togetherSateesh kg

PIC CPU

Memory Bus

INTR

0

N

IRQs0

255

idtr

Mask points

vector

IDT

Dispatching InterruptsSateesh kg

Each interrupt has to be handled by a special device- or trap-specific routine Interrupt Descriptor Table (IDT) has gate descriptors for each interrupt vector Hardware locates the proper gate descriptor for this interrupt vector, and locates the new context A new stack pointer, program counter, CPU and memory state, etc., are loaded Global interrupt mask set The old program counter, stack pointer, CPU and memory state, etc., are saved on the new stack The specific handler is invoked

Sateesh kgSateesh kg

do_IRQ()do_irq( ) is function of process 0do_irq() starts, it will verify with interrupt controller and query about the which IRQ line is called and lookedup in the descriptor table.

Linux kernel configures do_irq() routine as default response function for all external interrupts.do_irq() is routine of process 0, which is responsible for allocation of interrupt stack and invoking appropriate interrupt service functions.If the kernel is configured for 8K stack, the so_irq() uses 8K stack (by default 8K stack). If the kernel is configured for 4K stack, the do_irq() will allocate another 4K stack for irq's.

Steps of do_irq( ) Finds interrupt request lines on which interrupt signal was triggered.Lookup irq table (IDT) for address of required interrupt routine.Invoke registered ISR'sEnable IRQ line.Execute other priority workInvoke process scheduler

do_irq() -> IDT lookup -> picks up ISR

Sateesh kgSateesh kg

Interrupt LatencyAmount of time spent by the system in response to interrupt signal.If letancy is high Application will starveanother interrupt will also blockcannot generate another irq on same line.Total amount of time spent by system in response to the interrupt.

Factor contributing to interrupt letancy:l Hardware letancyl Kernel letancyl Interrupt handler letancyl Soft Interrupt letancyl Scheduler latencycheck on high priority task in runqueuecall to signal handler to these taskstake task assign CPU time(in latest kernel scheduler time is fixed (2.6 later))

Sateesh kgSateesh kg

Design of ISR

Design of interrupt service routine.

Case study: EthernetWhen Ethernet receives packet, hardware sends an interrupt of packet arrival. How to handle to handle interrupt or write ISR.

Steps:Allocate buffer (hold packet for Transmission, Reception)copy the packet from card to allocated bufferProcess the packet if requiredDeliver to upper layer for further processing.

Sateesh kgSateesh kg

Design of ISR

my_ISR {

1. Allocate buffer (hold packet for Transmission, Reception)2. copy the packet from card to allocated buffer3. Process the packet if required4. Deliver to upper layer for further processing.

}

Case 2: Simple pseudo code of an interrupt handler that responds the reception of the packet on the network device

Sateesh kgSateesh kg

Do's and Don'ts

Guide lines: Don'ts :avoid calling dynamic memory allocation routinesavoid transfer data between buffer blocks synchronizationavoid contending for access of global data structures (acquiring lock will block)avoid operations on user space addresscall to scheduleravoid calls to operation which are non-atomic (probably which locks)

Do's:use pre-allocated buffersconsider using DMA whenever data needs to be transferred between device and memory.Consider using first CPU data whenever needed (per CPU data)Identify non-critical work and use appropriate deferential routine to execute then when system is idle or other scheduler time

Sateesh kgSateesh kg

Handling of interrupt in software....… next session

Thank You