50
Interrupts Interrupts And tips for R3 And tips for R3

Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Embed Size (px)

DESCRIPTION

#include int main(void) { int I; int sum=0; for (i=0; i

Citation preview

Page 1: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

InterruptsInterruptsAnd tips for R3And tips for R3

Page 2: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

What is an interrupt?What is an interrupt?An interrupt is an electronic signal that indicates an An interrupt is an electronic signal that indicates an eventevent (possibly caused by (possibly caused by

hardware or the program its self) has occurred which results in a deviation hardware or the program its self) has occurred which results in a deviation from the normal flow of execution in a process.from the normal flow of execution in a process.

In the normal flow of events, when a process is executing a program, execution In the normal flow of events, when a process is executing a program, execution proceeds sequentially from one statement to the next, unless a branching proceeds sequentially from one statement to the next, unless a branching statement is encountered.statement is encountered.

The concept of interrupts was introduced, with Atlas, and used to provide some The concept of interrupts was introduced, with Atlas, and used to provide some concurrency in computing by allowing concurrency in computing by allowing I/O devicesI/O devices to proceed with data to proceed with data transfers while the CPU performed other tasks instead of constantly transfers while the CPU performed other tasks instead of constantly pollingpolling the I/O device. An interrupt facility allows the I/O devices to the I/O device. An interrupt facility allows the I/O devices to signalsignal the the system only when service of some type is required.system only when service of some type is required.

Also interrupts are used to enable the system to keep track of the time of day Also interrupts are used to enable the system to keep track of the time of day and set alarms to time specific events.and set alarms to time specific events.

Page 3: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

#include <stdio.h>

int main(void)

{

int I;

int sum=0;

for (i=0; i<=10; i++){

sum=sum+I;

}

printf(“the final sum is %d\n”, sum);

}

Normal flow is sequential

When an interrupt signal occurs, execution in the original program is suspended, the status of the program saved, and control is transferred to a special routine called an interrupt handler that processes the interrupt, and then calls the dispatcher. The original program may then resume execution, or another may be launched

“the interrupt handler”

Page 4: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

When an interrupt occursWhen an interrupt occurs The currently executing program is temporarily suspended.The currently executing program is temporarily suspended. The context/status of the process is savedThe context/status of the process is saved Control shifts to a special routine called an interrupt handler.Control shifts to a special routine called an interrupt handler.

An interrupt handler is:An interrupt handler is: A specially written routine whose job is to evaluate the cause of A specially written routine whose job is to evaluate the cause of

the interruptthe interrupt Perform any special tasks associated with the interruptPerform any special tasks associated with the interrupt Return control back to the previously executing program at the Return control back to the previously executing program at the

EXACTEXACT statement which would have normally been executed if statement which would have normally been executed if the interrupt had not occurred.the interrupt had not occurred.

OROR to trigger a context switch to give control of the CPU to a to trigger a context switch to give control of the CPU to a different program/process.different program/process.

One of the most critical issues with respect to managing One of the most critical issues with respect to managing interrupts is that the COMPLETE status of the suspended interrupts is that the COMPLETE status of the suspended process must be correctly saved and restored.process must be correctly saved and restored.

Page 5: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Interrupts can originate in either hardware or Interrupts can originate in either hardware or software.software.

Programs issue interrupts to request the Programs issue interrupts to request the operating system’s supportoperating system’s support

Hardware issues interrupts to notify the Hardware issues interrupts to notify the processor that an asynchronous event has processor that an asynchronous event has occurred.occurred.

Page 6: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

For Example: A program might use a system call to generate an interrupt to signal that it needs data: (Example taken from Operating Systems, a systematic view, by Davis & Rajkumar)

Operating System

Dispatcher

Interrupt Handler Routine

PCB’s

Program State

A running

B ready

channel

disk

The running program

A requests input data, this triggers an interrupt, and control transfers to the interrupt handler

Page 7: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Operating System

Dispatcher

Interrupt Handler Routine

PCB’s

Program State

A blocked

B ready

channel

disk

The interrupt handler sets the running process to the blocked state, and begins execution.

Page 8: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Operating System

Dispatcher

Interrupt Handler Routine

PCB’s

Program State

A blocked

B ready

channel

disk

The interrupt handler, calls the I/O control system, which starts the I/O operation, before returning control back to the dispatcher

Page 9: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Operating System

Dispatcher

Interrupt Handler Routine

PCB’s

Program State

A blocked

B running

channel

disk

The I/O controller will continue with the I/O operation while the dispatcher launches another process. The I/O controller may generate multiple interrupts depending on whether information is transferred character by character or as a block.

Page 10: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Operating System

Dispatcher

Interrupt Handler Routine

PCB’s

Program State

A blocked

B running

channel

disk

When the operation is complete, the channel issues an interrupt, and once again the interrupt handler begins executing, the waiting process will be unblocked, and again the dispatcher is called

Page 11: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

What types of interrupts may What types of interrupts may occur?occur?

Essentially there are 4 types of hardware Essentially there are 4 types of hardware interrupts, and 2 types of software interrupts.interrupts, and 2 types of software interrupts. I/O Interrupts:I/O Interrupts:

Generated by I/O devices (via the device interface)Generated by I/O devices (via the device interface)These indicate that service is needed from a software These indicate that service is needed from a software interrupt handler:interrupt handler:

Transferring another character to or from a character by Transferring another character to or from a character by character devicecharacter device

Servicing the completion of a total I/O request (block of data Servicing the completion of a total I/O request (block of data being read or written)being read or written)

Handling of an error condition in the device (paper jam)Handling of an error condition in the device (paper jam)

Page 12: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Alert InterruptsAlert InterruptsThese result from unexpected conditions outside These result from unexpected conditions outside the computer systemthe computer systemSome keyboards contain an “interrupt key” which Some keyboards contain an “interrupt key” which can be used to activate the command handlercan be used to activate the command handlerOr in a Multiprocessor system when one CPU Or in a Multiprocessor system when one CPU signals another to signify some condition or service signals another to signify some condition or service request from the other CPUrequest from the other CPU

Page 13: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Timer interrupts:Timer interrupts:Generated by internal software timersGenerated by internal software timersCan be used to indicated that the last unit of time Can be used to indicated that the last unit of time placed into a timer has expired, which indicates placed into a timer has expired, which indicates that some activity is to occur. (running process is that some activity is to occur. (running process is to be preempted when the CPU time limit expires)to be preempted when the CPU time limit expires)Interrupts may be generated at regular intervals by Interrupts may be generated at regular intervals by a hardware clocka hardware clock

Each interrupt means that another fixed fraction of time Each interrupt means that another fixed fraction of time has expired and that the software clocks should be has expired and that the software clocks should be updated.updated.

Page 14: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Machine fault interruptsMachine fault interrupts Indicate that a hardware error has occurredIndicate that a hardware error has occurred

Memory fetch errorMemory fetch errorI/o device errorI/o device error

These interrupts typically can not be masked These interrupts typically can not be masked or ignored.or ignored.

Many OS’s simply report these errors and Many OS’s simply report these errors and terminateterminate

Others, if resources permit, try to isolate the Others, if resources permit, try to isolate the offending hardware and try to continue offending hardware and try to continue execution.execution.

Page 15: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Software generated interruptsSoftware generated interrupts

Software Interrupts are usually implemented as Software Interrupts are usually implemented as instructionsinstructions in the instruction set which cause a context in the instruction set which cause a context switch to the interrupt handler similar to a hardware switch to the interrupt handler similar to a hardware interrupt interrupt System request interrupts:System request interrupts:

Result when processes Result when processes request servicerequest service from the OS through the from the OS through the use of special instructions which generate a system request use of special instructions which generate a system request interrupt.interrupt.

The system call instruction is provided via the OS’s program The system call instruction is provided via the OS’s program interfaceinterface

Execution of this command causes a transfer of control to the Execution of this command causes a transfer of control to the OSOS

Parameters may be used to transfer arguments to the OS, Parameters may be used to transfer arguments to the OS, identifying the type of service requested.identifying the type of service requested.

The OS will analyze the request, possibly blocking the process The OS will analyze the request, possibly blocking the process requesting the service until the service is complete.requesting the service until the service is complete.

Page 16: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Program Fault InterruptsProgram Fault Interrupts Abnormal conditions that arise within the Abnormal conditions that arise within the

running programrunning programDivide by zeroDivide by zeroUnderflow/overflow during an arithmetic operationUnderflow/overflow during an arithmetic operationInvalid memory referenceInvalid memory reference

For these category of interrupts users can For these category of interrupts users can supply the address of a special routine to supply the address of a special routine to execute when the error occurs otherwise the execute when the error occurs otherwise the OS will execute a default routine (typically OS will execute a default routine (typically reporting the error and terminating execution reporting the error and terminating execution of the program)of the program)

Page 17: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Software interrupts (or exceptions) are Software interrupts (or exceptions) are synchronoussynchronous interrupts which are generated interrupts which are generated when the processor detects a predefined when the processor detects a predefined condition, such as division by 0. The exception condition, such as division by 0. The exception occurs during the machine cycle which is driven occurs during the machine cycle which is driven by a clock tick, and since they are caused by the by a clock tick, and since they are caused by the program itself there is a precise point within the program itself there is a precise point within the program at which the transfer of control to the program at which the transfer of control to the interrupt handler should occur.interrupt handler should occur.Others are Others are AsynchronousAsynchronous because even though because even though they should be serviced ASAP, the exact point at they should be serviced ASAP, the exact point at which the program should be interrupted isn’t which the program should be interrupted isn’t predetermined.. May be immediately after the predetermined.. May be immediately after the execution of the current machine instruction (at execution of the current machine instruction (at the next clock tick), or later. These are raised by the next clock tick), or later. These are raised by hardware devices at unpredictable times.hardware devices at unpredictable times.

Page 18: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Interrupt GenerationInterrupt Generation

Many interrupts begin as a signal sent to the Many interrupts begin as a signal sent to the processor when an event occurs. (interrupt-processor when an event occurs. (interrupt-request line) request line) Usually the interrupt signal is recorded when it Usually the interrupt signal is recorded when it occurs by setting a flag (bit) in a special occurs by setting a flag (bit) in a special processor register (program status word). The # processor register (program status word). The # of actual flags vary from architecture to of actual flags vary from architecture to architecture, sometimes multiple interrupts must architecture, sometimes multiple interrupts must share the same flags.share the same flags.

Page 19: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Once the interrupt is “Once the interrupt is “raisedraised” it is the job of the ” it is the job of the CPU to “CPU to “catchcatch” the interrupt, interpret it, and ” the interrupt, interpret it, and ““dispatchdispatch” the appropriate interrupt handler. The ” the appropriate interrupt handler. The handler then “clears” the interrupt by processing handler then “clears” the interrupt by processing the request (clearing the flag).the request (clearing the flag).

To successfully manage interrupts we need 3 To successfully manage interrupts we need 3 facilitiesfacilities The ability to defer interrupt handling during critical The ability to defer interrupt handling during critical

processing.processing. We need an efficient way to dispatch to the proper We need an efficient way to dispatch to the proper

interrupt handler without polling every device to see interrupt handler without polling every device to see which one initiated the interruptwhich one initiated the interrupt

We need multilevel interrupts so that the operating We need multilevel interrupts so that the operating system can service interrupts in order of importance if system can service interrupts in order of importance if multiple interrupts occur simultaneously. multiple interrupts occur simultaneously.

Page 20: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Dispatching the interrupt handlerDispatching the interrupt handler

When an interrupt occurs we need to transfer When an interrupt occurs we need to transfer control immediately to the appropriate interrupt control immediately to the appropriate interrupt handler.handler.When this transfer occurs it is CRITICAL that When this transfer occurs it is CRITICAL that some capability is provided to save the status some capability is provided to save the status (context) of the executing process.(context) of the executing process.The contents of every CPU register and the The contents of every CPU register and the status flags must be saved (possibly on the status flags must be saved (possibly on the current stack) so that they can be restored when current stack) so that they can be restored when the suspended process is resumed.the suspended process is resumed.

Page 21: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

IF interrupt IF interrupt THEN  THEN  save execution address (PC)  save execution address (PC)  save status information  save status information  transfer control to interrupt handler  transfer control to interrupt handler  ENDEND

Page 22: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

The exact transfer mechanism varies The exact transfer mechanism varies slightly from architecture to architecture slightly from architecture to architecture but most associate each interrupt with a but most associate each interrupt with a small data structure in “low memory” small data structure in “low memory” called an interrupt vector. This structure called an interrupt vector. This structure contains:contains: The address of the Interrupt handlerThe address of the Interrupt handler (maybe) a location to store the return address (maybe) a location to store the return address

and the status of the interrupted program.and the status of the interrupted program.

Page 23: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

FOR EXAMPLE:FOR EXAMPLE: In MS-DOS, interrupt In MS-DOS, interrupt

processing uses an processing uses an interrupt vector table interrupt vector table that occupies the first that occupies the first 1K bytes of memory. 1K bytes of memory. (Example taken from Operating Systems, a systematic view, by Davis & Rajkumar)

Most of the actual Most of the actual routines are found routines are found in IO.sys or in IO.sys or MSDOS.sysMSDOS.sys

Interrupt VectorsInterrupt Vectors

Address of interrupt x Address of interrupt x routineroutine

Address of interrupt y Address of interrupt y routineroutine

Address of interrupt z Address of interrupt z routineroutine

Page 24: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Interrupt VectorsInterrupt Vectors

Address of Address of interrupt x interrupt x

routineroutineAddress of Address of interrupt y interrupt y

routineroutineAddress of Address of interrupt z interrupt z

routineroutine

The interrupt consists of an electronic pulse and the address of an interrupt vector.

When the interrupt occurs hardware immediately copies the instruction pointer register (and a few other registers) to the stack!

It then loads the starting address specified in the interrupt vector into the IP.

With the next machine cycle the first instruction in the interrupt routine is fetched.

Once the interrupt is processed, the contents of the stack are copied back into the IP and the original program resumes processing.

Instruction pointer

stack

Page 25: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

A fully vectored interrupt mechanism A fully vectored interrupt mechanism provides a distinct interrupt vector for each provides a distinct interrupt vector for each interrupt. This reduces the need for a interrupt. This reduces the need for a single interrupt handler to search all single interrupt handler to search all possible sources of interrupts to determine possible sources of interrupts to determine which one needs service.which one needs service.

Page 26: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

IBM-PC is fully vectored. With distinct interrupt IBM-PC is fully vectored. With distinct interrupt vectors for each interruptvectors for each interrupt

IF interrupt IF interrupt THEN  THEN 

save execution address (Program Counter)  save execution address (Program Counter)  save status (Program Status Word)    save status (Program Status Word)   

CASE interrupt IS      CASE interrupt IS      WHEN device1: transfer control to  device1 interrupt handler      WHEN device1: transfer control to  device1 interrupt handler      WHEN device2: transfer control to  device2 interrupt handler      WHEN device2: transfer control to  device2 interrupt handler      WHEN device3: transfer control to  device3 interrupt handler      WHEN device3: transfer control to  device3 interrupt handler      WHEN device4: transfer control to  device4 interrupt handler    WHEN device4: transfer control to  device4 interrupt handler    ENDCASE  ENDCASE 

ENDIF  ENDIF 

/* In this case the cause of the interrupt can be determine without further /* In this case the cause of the interrupt can be determine without further program execution */program execution */

Page 27: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Other architectures allow multiple interrupts to share the same interrupt Other architectures allow multiple interrupts to share the same interrupt vector, by creating a limited set of interrupt categories: IBM/370vector, by creating a limited set of interrupt categories: IBM/370

Here control passes to the same first level interrupt handler, which Here control passes to the same first level interrupt handler, which must then test an addtional special register to determine which device must then test an addtional special register to determine which device

caused the interrupt.caused the interrupt.FLIH: FLIH: save registers  save registers  read interrupt_status_register  read interrupt_status_register 

CASE interrupt_status_register IS    CASE interrupt_status_register IS    WHEN device1: call device1_SLIH    WHEN device1: call device1_SLIH    WHEN device2: call device2_SLIH    WHEN device2: call device2_SLIH    WHEN device3: call device3_SLIH  WHEN device3: call device3_SLIH  ENDCASE ENDCASE 

restore registers  restore registers  RETURN from interrupt  RETURN from interrupt 

Page 28: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Ordering of Interrupts by priorityOrdering of Interrupts by priorityTypically different categories of interrupts are Typically different categories of interrupts are assigned designated priorities.assigned designated priorities.This allows the CPU to defer the handling of low-This allows the CPU to defer the handling of low-priority interrupts without masking ALL interruptspriority interrupts without masking ALL interruptsMakes it possible for a high priority interrupt to Makes it possible for a high priority interrupt to preempt the execution of a low priority interrupt.preempt the execution of a low priority interrupt.If interrupts are masked it is imperative that If interrupts are masked it is imperative that interrupts be unblocked as soon as possible.interrupts be unblocked as soon as possible.IE: The interrupts for an I/O device can be IE: The interrupts for an I/O device can be turned off while servicing an interrupt for that turned off while servicing an interrupt for that device.device.

Page 29: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Structure of an Interrupt handlerStructure of an Interrupt handler

There are several ways in which the There are several ways in which the structure and design of an interrupt structure and design of an interrupt handler must be different than that of an handler must be different than that of an ordinary procedure:ordinary procedure:

Page 30: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

1.1. A linkage must be created between the A linkage must be created between the physical interrupt and the handler, so that the physical interrupt and the handler, so that the handler will be invoked when the interrupt handler will be invoked when the interrupt occurs:occurs:

Each interrupt handler is linked to the appropriate Each interrupt handler is linked to the appropriate physical interrupt by storing its starting address in physical interrupt by storing its starting address in the associated interrupt vector location.the associated interrupt vector location.

During system initialization the OS is responsible for During system initialization the OS is responsible for setting up the interrupt vectors with the address of setting up the interrupt vectors with the address of default interrupt handlersdefault interrupt handlers

When the interrupt occurs special hardware When the interrupt occurs special hardware mechanisms access the contents of the vector, mechanisms access the contents of the vector, perhaps save some brief status data, and transfer to perhaps save some brief status data, and transfer to the specified handlerthe specified handler

Page 31: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

2) 2) Since interrupts may occur at unpredictable points in Since interrupts may occur at unpredictable points in program execution, the complete system state must be program execution, the complete system state must be preserved during interrupt handling. This means that preserved during interrupt handling. This means that after the interrupt the content of all machine registers after the interrupt the content of all machine registers must be exactly as before; moreover, all memory used must be exactly as before; moreover, all memory used by the running process, including "hidden" areas such by the running process, including "hidden" areas such as a stack, must be undisturbedas a stack, must be undisturbed..

Save all registers which could be modified by the interrupt Save all registers which could be modified by the interrupt handler onto the stack or in a private memory area.handler onto the stack or in a private memory area.

The hardware itself may save some critical registers such as The hardware itself may save some critical registers such as the status register along with the return address. the status register along with the return address.

The handler software is then expected to immediately save all The handler software is then expected to immediately save all other registers that might be used.other registers that might be used.

At termination of the handler the software must restore all At termination of the handler the software must restore all registers save by software and the hardware restores those registers save by software and the hardware restores those saved by hardwaresaved by hardware..

Page 32: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

3) 3) Parameters cannot be passed to an Parameters cannot be passed to an interrupt handler in the usual wayinterrupt handler in the usual way Interrupt handlers are not called via the Interrupt handlers are not called via the

normal call mechanism, so parameters can normal call mechanism, so parameters can not be passes via the normal mechanismnot be passes via the normal mechanism

If an handler requires data to be passed into If an handler requires data to be passed into it, then that information must be placed in a it, then that information must be placed in a special place such as a special register or on special place such as a special register or on the stack.the stack.

Page 33: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

4) 4) Because interrupt handling is a temporary Because interrupt handling is a temporary deviation from the normal execution of a deviation from the normal execution of a running process, the handler may be running process, the handler may be severely restricted in the resources it may severely restricted in the resources it may use, and in the subprograms it may calluse, and in the subprograms it may call The interrupt handler should not make use of The interrupt handler should not make use of

resources that could be allocated to another resources that could be allocated to another process. They should not normally access process. They should not normally access data files or I/O devices. Nor should they data files or I/O devices. Nor should they allocate memory or use any memory other allocate memory or use any memory other than their own.than their own.

Page 34: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

5) 5) Interrupt handlers must allow for the appropriate Interrupt handlers must allow for the appropriate handling of other interrupts while the handler is handling of other interrupts while the handler is in progress.in progress. Typically a computer many need to process Typically a computer many need to process

thousands of interrupts per second thousands of interrupts per second When an interrupt occurs, the hardware automatically When an interrupt occurs, the hardware automatically

disables other interrupts. This is necessary to avoid disables other interrupts. This is necessary to avoid confusion during the initial saving of the system state. confusion during the initial saving of the system state.

Interrupts should be re-enabled as soon as possible.Interrupts should be re-enabled as soon as possible. IF the interrupt handler is VERY short then interrupts IF the interrupt handler is VERY short then interrupts

may be left disabled until the handler terminatesmay be left disabled until the handler terminates

Page 35: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

6) 6) Interrupt handlers must complete their Interrupt handlers must complete their work in the shortest possible time, leaving work in the shortest possible time, leaving more complex follow up tasks to other more complex follow up tasks to other system or application softwaresystem or application software. . The interrupt handler should complete its work The interrupt handler should complete its work

and terminate in the shortest possible time. and terminate in the shortest possible time. In many cases it should do as little as setting In many cases it should do as little as setting

an event flag which subsequent software an event flag which subsequent software could review and process.could review and process.

Page 36: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

7) 7) Interrupt handling is subject to errors that Interrupt handling is subject to errors that are hard to reproduce, and cannot often are hard to reproduce, and cannot often be debugged by normal means.be debugged by normal means. The timing of interrupts is often not The timing of interrupts is often not

repeatable. repeatable. Sometimes only in the certain ordering of Sometimes only in the certain ordering of

interrupts do problems occur and can be interrupts do problems occur and can be difficult to solve because the exact ordering of difficult to solve because the exact ordering of interrupts can not be easily observed or interrupts can not be easily observed or repeated. repeated.

Page 37: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Tips for R3: Process InitializationTips for R3: Process Initialization

When we create processes to represent When we create processes to represent our 5 test procedures we must correctly our 5 test procedures we must correctly initialize its context by placing values into initialize its context by placing values into its stack, data segment and extra its stack, data segment and extra segment.segment.

Page 38: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

1) We need to define a special global structure to 1) We need to define a special global structure to represent the “context” of a process which is represent the “context” of a process which is automatically saved onto the processes stack automatically saved onto the processes stack when the process is interrupted:when the process is interrupted:

typedef struct context { typedef struct context { unsigned int BP, DI, SI, DS, ES; unsigned int unsigned int BP, DI, SI, DS, ES; unsigned int DX, CX, BX, AX; DX, CX, BX, AX; unsigned int IP, CS, FLAGS; unsigned int IP, CS, FLAGS; } context; } context;

context *context_p; context *context_p;

Page 39: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Recall that:Recall that:

When an interrupt occurs the HARDWARE saves the When an interrupt occurs the HARDWARE saves the flags register (PSW), CS (code segment), IP (instruction flags register (PSW), CS (code segment), IP (instruction pointer) onto the stack in this order!!!!!pointer) onto the stack in this order!!!!!Next because of the interrupt keyword being specified in Next because of the interrupt keyword being specified in the implementation of our interrupt handler: the implementation of our interrupt handler:

void interrupt sys_call_handler()void interrupt sys_call_handler()Assembler instructions will be added to the routine to Assembler instructions will be added to the routine to automatically save the following registers onto the stack:automatically save the following registers onto the stack:

AX, BX, CX, DX, ES, DS, SI, DI, AND BP AX, BX, CX, DX, ES, DS, SI, DI, AND BP

Code will also be automatically added at the end of the Code will also be automatically added at the end of the routine to restore these!!!!!routine to restore these!!!!!

Page 40: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

We need to set up the initial context of each process by We need to set up the initial context of each process by initializing the contents of its stack.initializing the contents of its stack.

The declaration of the PCB should contain The declaration of the PCB should contain a pointer to a stack of size 1k, which a pointer to a stack of size 1k, which should initially be initialized to all zeros!! should initially be initialized to all zeros!! The stack pointer should be initialized to The stack pointer should be initialized to the “highest” address in your stack (stack the “highest” address in your stack (stack address +1024) (remember that the stack address +1024) (remember that the stack grows from high memory down.)grows from high memory down.)We need to store the initial context of the We need to store the initial context of the process in the top portion of the stack!process in the top portion of the stack!

Page 41: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Pcb.stack_p = pcb.stack_base + Pcb.stack_p = pcb.stack_base + pcb.stack_size – sizeof(context);pcb.stack_size – sizeof(context);

Context_p = (context *)pcb.stack_p;Context_p = (context *)pcb.stack_p;

context_p->DS = _DS;context_p->DS = _DS;context_p->ES = _ES;context_p->ES = _ES;context_p->CS = FP_SEG(&testcontext_p->CS = FP_SEG(&testnn_R3);_R3);context_p->IP = FP_OFF(&testcontext_p->IP = FP_OFF(&testnn_R3);_R3);context_p->FLAGS = 0x200 context_p->FLAGS = 0x200

Page 42: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Process cause interrupts by:Process cause interrupts by:Each process will voluntarily give up control of Each process will voluntarily give up control of the CPU using a call to “sys_req” which will the CPU using a call to “sys_req” which will generate a system call interrupt. Processes call generate a system call interrupt. Processes call “sys_req” with two possible op_code values:“sys_req” with two possible op_code values: IDLE: which will return the process to the ready IDLE: which will return the process to the ready

queuequeue EXIT: which is a request to terminate the process, EXIT: which is a request to terminate the process,

and free the PCB.and free the PCB.

This call to sys_req will result in an interrupt This call to sys_req will result in an interrupt being generated which should be processed by being generated which should be processed by our “sys_call_hander”our “sys_call_hander”

Page 43: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Setting up “sys_call_handler”Setting up “sys_call_handler”During initialization you must set the “sys_call” vector to During initialization you must set the “sys_call” vector to contain the address of your interrupt handler. It has the contain the address of your interrupt handler. It has the prototype:prototype:

int sys_set_vec (void (*handler)()); int sys_set_vec (void (*handler)());

The single parameter handler is a pointer to your system The single parameter handler is a pointer to your system call handler. If your handler has the name sys_call, then call handler. If your handler has the name sys_call, then it should have the prototype:it should have the prototype:

void sys_call (void); void sys_call (void);

Your call to sys_set_vec, which should occur during Your call to sys_set_vec, which should occur during initialization, will have the forminitialization, will have the form

sys_set_vec(sys_call); sys_set_vec(sys_call);

Page 44: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

Sys_req passes a single parameter to your sys_call_handler, via the stackSys_req passes a single parameter to your sys_call_handler, via the stack

(previous stack contents)(previous stack contents)Buffer length pointer parameter (*count)Buffer length pointer parameter (*count)Buffer address parameter (*buffer)Buffer address parameter (*buffer)Device_id parameterDevice_id parameterOp_code parameterOp_code parameterFlagFlagCSCSIPIPAXAXBXBXCXCXDXDXESESDSDSSISIDIDIBPBP

We will need to retrieve the contents of the 1We will need to retrieve the contents of the 1stst four parameters to identify the type of four parameters to identify the type of request made by the calling process.request made by the calling process.

Page 45: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

To access these parameters we define To access these parameters we define another structure similar to the “context” another structure similar to the “context” structure:structure:

typedef struct params {typedef struct params {int op_code;int op_code;int device_id;int device_id;byte *buf_addr;byte *buf_addr;int *count_addr;int *count_addr;} params; } params;

Page 46: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

We gain access to the op_code by:We gain access to the op_code by:

The stack structure must be a named type. A pointer to this The stack structure must be a named type. A pointer to this structure is also required:structure is also required:

params *param_p; params *param_p;

Finally, the following assignment will set the pointer to the Finally, the following assignment will set the pointer to the address of the actual stack frame to be accessed:address of the actual stack frame to be accessed:

param_p = (params*)(MK_FP(_SS,_SP) + sizeof(context)); param_p = (params*)(MK_FP(_SS,_SP) + sizeof(context));

It is now possible to refer to the op_code value asIt is now possible to refer to the op_code value asparam_p->op_code.param_p->op_code.

Page 47: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

We then need to interpret this code and take the appropriate action!We then need to interpret this code and take the appropriate action!

First save a copy of the SS and SP and switch to another temporary stack. (local variables First save a copy of the SS and SP and switch to another temporary stack. (local variables should be declared as static)should be declared as static)

#define SYS_STACK_SIZE 200 #define SYS_STACK_SIZE 200 byte sys_stack[SYS_STACK_SIZE]; byte sys_stack[SYS_STACK_SIZE]; unsigned short ss_save; unsigned short ss_save; unsigned short sp_save; unsigned short sp_save;

unsigned short new_ss; unsigned short new_ss; unsigned short new_sp; unsigned short new_sp;

/* in syscall*//* in syscall*/ ss_save = _SS; ss_save = _SS; sp_save = _SP; sp_save = _SP;

new_ss = FP_SEG(sys_stack); new_ss = FP_SEG(sys_stack); new_sp = FP_OFF(sys_stack); new_sp = FP_OFF(sys_stack); new_sp += SYS_STACK_SIZE; new_sp += SYS_STACK_SIZE;

_SS = new_ss; _SS = new_ss;

SP = new_sp; SP = new_sp;

Page 48: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

set param_p point to the correct place: set param_p point to the correct place:

cop->stack_ptr = (unsigned char *) MK_FP(_SS, _SP);cop->stack_ptr = (unsigned char *) MK_FP(_SS, _SP);param_p = (params *)(cop->stack_ptr + sizeof(context));param_p = (params *)(cop->stack_ptr + sizeof(context));

if parm_p->op_code is IDLEif parm_p->op_code is IDLEchange the state of cop to readychange the state of cop to readyinsert cop to ready queue by priority insert cop to ready queue by priority else if param_p->op_code is EXITelse if param_p->op_code is EXITdelete the pcbdelete the pcbset cop to NULL set cop to NULL else set context_p->AX to error code. else set context_p->AX to error code. call dispatch() call dispatch()

Page 49: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

In the dispatcherIn the dispatcherAutomatically saves the data registers Automatically saves the data registers onto the temporary stack for the calling onto the temporary stack for the calling processprocessThen a complete outline for the dispatcher Then a complete outline for the dispatcher is:is:

Page 50: Interrupts And tips for R3. What is an interrupt? An interrupt is an electronic signal that indicates an event (possibly caused by hardware or the program

if sp_save is null, if sp_save is null, ss_save = _SS ss_save = _SS sp_save = _SP sp_save = _SP

remove the PCB at the head of the ready queue remove the PCB at the head of the ready queue

if a PCB was found set cop to this PCB if a PCB was found set cop to this PCB set _SS and _SP to the PCB's stack pointer set _SS and _SP to the PCB's stack pointer

else else set cop to NULL set cop to NULL set _SS to ss_save set _SS to ss_save set _SP to sp_save set _SP to sp_save

end if end if

"return from interrupt""return from interrupt"