0% found this document useful (0 votes)
11 views

microprocessor and assembly

The document is an individual assignment from Jimma University Agaro Campus focusing on microprocessors and assembly language, specifically discussing interrupts and their handling processes. It covers various types of interrupts, including hardware and software interrupts, along with detailed explanations of interrupt instructions and the differences between real mode and protected mode. Additionally, it outlines the role of the Interrupt Flag and provides practical assembly language examples to illustrate the concepts discussed.

Uploaded by

gbonsa2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

microprocessor and assembly

The document is an individual assignment from Jimma University Agaro Campus focusing on microprocessors and assembly language, specifically discussing interrupts and their handling processes. It covers various types of interrupts, including hardware and software interrupts, along with detailed explanations of interrupt instructions and the differences between real mode and protected mode. Additionally, it outlines the role of the Interrupt Flag and provides practical assembly language examples to illustrate the concepts discussed.

Uploaded by

gbonsa2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Jimma University Agaro Campus

Department of Computing

Microprocessor and assembly language


Individual Assignment

Name ID
1. Gemechu Bonsa -------------------------RU0913/15

0
Contents

1.Interrupts.................................................................................................................................................3
Interrupt Handling Process......................................................................................................................3
Assembly Language and Interrupts:........................................................................................................3
Breakdown:.............................................................................................................................................4
Real-World Application:...........................................................................................................................5
2. Types of Interrupts:.................................................................................................................................5
Hardware Interrupts................................................................................................................................5
Software Interrupts in Microprocessors..................................................................................................6
3. Interrupt Instructions:.............................................................................................................................8
INT Instruction.........................................................................................................................................8
INTO Instruction......................................................................................................................................8
INT 3 Instruction......................................................................................................................................9
IRET Instruction.....................................................................................................................................10
4. Real Mode vs. Protected Mode:............................................................................................................11
Real Mode.............................................................................................................................................11
Characteristics:......................................................................................................................................11
Limitations of Real Mode:......................................................................................................................11
Protected Mode....................................................................................................................................12
Characteristics:......................................................................................................................................12
Addressing Real Mode Limitations:.......................................................................................................12
5. Interrupt Flag Bits:.............................................................................................................................14
Interrupt Flag (IF)...................................................................................................................................14
Role of the Interrupt Flag (IF):...............................................................................................................14
Impact on Interrupt Processing:............................................................................................................14
Example Scenario:.................................................................................................................................15
6. Interrupt Vector Table:..........................................................................................................................16
Structure of the Interrupt Vector Table (IVT)........................................................................................16
Key Characteristics:...............................................................................................................................16

1
Storing an Interrupt Vector...................................................................................................................16
Example of IVT Entry:............................................................................................................................16
Using the IVT During Interrupt Processing.............................................................................................17
7. Steps in Interrupt Processing:................................................................................................................18
Basic Steps in Interrupt Processing........................................................................................................18
What Happens to the CPU State and Registers.....................................................................................19
8. Handling Hardware Interrupts:..............................................................................................................21
Mechanism of Handling Hardware Interrupts.......................................................................................21
Roles of the Interrupt Controller and the CPU.......................................................................................22
Interrupt Controller:..........................................................................................................................22
CPU:...................................................................................................................................................22
9. Nested Interrupts:.................................................................................................................................23
Nested Interrupts:.................................................................................................................................23
Effects on System Performance:............................................................................................................23
Managing Nested Interrupts:................................................................................................................24
10. Practical Application:...........................................................................................................................26
Keyboard Interrupt (IRQ1).....................................................................................................................26
Reference:.................................................................................................................................................29

2
1.Interrupts
Microprocessors rely heavily on interrupts to efficiently manage tasks and respond to
events. Interrupts are essentially a way for the processor to pause its current task, handle
a specific event, and then resume its previous activity. This mechanism is crucial for
multitasking and real-time processing.

Interrupt Handling Process


 Interrupt Request (IRQ): When an interrupt request occurs, the microprocessor
detects this signal.
 Saving the Current State: The current state of the processor, including the program
counter and registers, is saved to ensure that the interrupted task can resume later.
 Executing the Interrupt Service Routine (ISR): The processor jumps to a predefined
memory location where the ISR is stored. The ISR handles the specific interrupt.
 Restoring the State: After the ISR finishes, the processor restores its previous state
and resumes the interrupted task.

Assembly Language and Interrupts:


In assembly language, handling interrupts involves using specific instructions and
setting up ISRs. Here's a simplified example using x86 assembly language:

section .data
msg db 'Interrupt Handled!', 0

section .bss

section .text
global _start

_start:
; Enable interrupts
sti

; Trigger interrupt
int 0x80

; Print message

3
mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, 17
int 0x80

; Exit
mov eax, 1
xor ebx, ebx
int 0x80

section .interrupt
; Define Interrupt Service Routine (ISR)
ISR:
; Code to handle the interrupt
iret

Breakdown:
 Enable Interrupts (`sti`): The `sti` instruction enables interrupts in the x86
architecture.
 Trigger Interrupt (`int 0x80`): The `int` instruction generates a software interrupt.
In this case, `0x80` is used to make a system call.
 ISR (`section .interrupt`): The ISR is defined to handle the interrupt. The `iret`
instruction is used to return from the interrupt, restoring the processor's state.

Real-World Application:
In microcontroller programming, interrupts are used extensively to handle events like
button presses, sensor inputs, and communication protocols. For example, in an
embedded system controlling a robot, timer interrupts might be used to update the
robot's position at precise intervals, while external interrupts handle sensor readings and
obstacle detection.

4
2. Types of Interrupts:
Hardware Interrupts
Hardware interrupts are signals generated by external hardware devices to notify the
processor of an event that requires immediate attention. These interrupts are essential for
real-time applications and efficient hardware management.

Example: Timer Interrupts


Consider a scenario where a timer generates periodic interrupts to ensure tasks are
executed at regular intervals. Here's how it can be implemented in assembly language for
an x86 processor:

section .data
msg db 'Timer Interrupt Handled!', 0

section .bss

section .text
global _start

_start:
; Set up timer interrupt
mov al, 0x36
out 0x43, al ; Command port of PIC
mov al, 0x9C
out 0x40, al ; Lower byte of divisor
mov al, 0x2E
out 0x40, al ; Upper byte of divisor

; Enable interrupts
sti

; Infinite loop to keep the program running


hlt
jmp hlt

section .interrupt
; Define Timer Interrupt Service Routine (ISR)
timer_isr:

5
; Handle the timer interrupt
mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, 23
int 0x80

; Send End of Interrupt (EOI) signal to PIC


mov al, 0x20
out 0x20, al

; Return from interrupt


iret
Explanation:
1. Setting Up Timer: The timer interrupt is configured using the Programmable Interval
Timer (PIT). The `out` instructions configure the timer to generate interrupts at
regular intervals.
2. Enable Interrupts: The `sti` instruction enables interrupts, allowing the processor to
respond to the timer interrupts.
3. ISR Handling: The `timer_isr` routine handles the timer interrupt by printing a
message and sending an End of Interrupt (EOI) signal to the Programmable Interrupt
Controller (PIC) before returning control to the main program using `iret`.

Software Interrupts in Microprocessors


Software interrupts are generated by software instructions to invoke specific actions
within the processor, such as system calls, error handling, or inter-process
communication.

Example: System Call


Let's look at a system call to write a message to the console in x86 assembly language:

section .data
msg db 'System Call Handled!', 0

section .text
global _start

_start:
; Trigger software interrupt for system call

6
mov eax, 4 ; syscall number for write
mov ebx, 1 ; file descriptor for stdout
mov ecx, msg ; pointer to message
mov edx, 20 ; message length
int 0x80 ; software interrupt to invoke system call

; Exit
mov eax, 1 ; syscall number for exit
xor ebx, ebx ; exit code 0
int 0x80 ; software interrupt to invoke system call

Explanation:
 System Call Invocation: The `mov` instructions set up the parameters for the
system call (write to console). The `int 0x80` instruction generates a software
interrupt to invoke the system call.
 Handling System Call: The operating system handles the software interrupt,
performs the requested action (writing the message), and returns control to the
program.

 Significance of Interrupts
o Hardware Interrupts: Enable efficient real-time processing by allowing
the processor to respond quickly to external events without constant
polling.
o Software Interrupts: Facilitate controlled execution of system calls, error
handling, and inter-process communication, ensuring orderly and
predictable program execution.

3. Interrupt Instructions:
INT Instruction
The `INT` instruction generates a software interrupt. It takes an interrupt vector number
as an operand and invokes the corresponding interrupt service routine (ISR).

Example:

section .data
msg db 'Software Interrupt Handled!', 0

section .text

7
global _start

_start:
; Trigger software interrupt with vector 0x80
int 0x80

; Print message
mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, 26
int 0x80

; Exit
mov eax, 1
xor ebx, ebx
int 0x80

INTO Instruction
The `INTO` instruction generates a software interrupt if the overflow flag (OF) is set. It
is used to handle overflow errors.

Example:

section .data
msg db 'Overflow Interrupt Handled!', 0

section .text
global _start

_start:
; Set up for overflow
mov al, 0x7F
add al, 0x01 ; This will set the overflow flag (OF)

; Trigger overflow interrupt if OF is set


into

; Print message

8
mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, 26
int 0x80

; Exit
mov eax, 1
xor ebx, ebx
int 0x80

INT 3 Instruction
The `INT 3` instruction generates a breakpoint interrupt. It is commonly used by
debuggers to set breakpoints in the code.

Example
section .data
msg db 'Breakpoint Interrupt Handled!', 0

section .text
global _start

_start:
; Trigger breakpoint interrupt
int 3

; Print message
mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, 27
int 0x80

; Exit
mov eax, 1
xor ebx, ebx
int 0x80

9
IRET Instruction
The `IRET` (Interrupt Return) instruction is used to return from an interrupt service
routine (ISR). It restores the processor's state and resumes normal execution.

Example

section .data

section .bss

section .text
global _start

_start:
; Enable interrupts
sti

; Trigger software interrupt with vector 0x80


int 0x80

; Infinite loop to keep the program running


hlt
jmp hlt

section .interrupt
; Define Interrupt Service Routine (ISR)
isr_80:
; Handle the interrupt
; ...

; Return from interrupt


iret

10
4. Real Mode vs. Protected Mode:
Real Mode
Real mode is the operating mode of x86-compatible processors, which starts when the
system boots up. It provides direct access to all memory, I/O addresses, and hardware
resources.

Characteristics:
 Interrupt Handling: In real mode, interrupt handling is straightforward. Interrupt
vectors are stored in the Interrupt Vector Table (IVT) located at the beginning of
memory (starting at address 0x0000:0x0000). Each interrupt vector is 4 bytes in
size, containing the address of the Interrupt Service Routine (ISR).

 Memory Addressing: Real mode uses a 20-bit segmented memory model,


allowing access to a maximum of 1 MB of memory. Segments are combined
with offsets to form physical addresses.

 Privilege Levels: There are no privilege levels in real mode, meaning all code
runs with full access to system resources, posing security risks.

Limitations of Real Mode:


 Limited Memory Access: Only 1 MB of memory can be addressed, which is
insufficient for modern applications.
 No Protection: There are no mechanisms to protect memory or resources, leading
to potential system crashes or instability if a program misbehaves.
 No Multitasking: Real mode does not support hardware-based multitasking,
making it difficult to run multiple processes simultaneously.

Protected Mode
Protected mode is an advanced operating mode of x86-compatible processors that
provides enhanced features such as extended memory access, hardware-based
multitasking, and improved security through privilege levels.

Characteristics:
 Interrupt Handling: In protected mode, interrupt handling is more sophisticated.
Interrupt vectors are stored in the Interrupt Descriptor Table (IDT). Each entry in
the IDT points to an ISR and includes additional information like privilege

11
levels.

 Memory Addressing: Protected mode uses a 32-bit flat memory model, allowing
access to up to 4 GB of memory. Memory is divided into segments with
descriptors stored in the Global Descriptor Table (GDT).

 Privilege Levels: Protected mode introduces privilege levels (rings), providing


different levels of access to system resources. Ring 0 has the highest privilege
(kernel mode), while Ring 3 has the lowest (user mode).

Addressing Real Mode Limitations:


 Extended Memory Access: Protected mode allows addressing up to 4 GB of
memory, significantly expanding the memory available to applications.
 Memory and Resource Protection: Segmentation and paging provide mechanisms
to protect memory and resources, preventing programs from accessing
unauthorized areas.
 Hardware-Based Multitasking: Protected mode supports hardware-based
multitasking, allowing the processor to manage multiple tasks and improve
system efficiency.

Example:
In protected mode, setting up an interrupt vector involves configuring the IDT, GDT,
and privilege levels, ensuring that only authorized code can handle certain interrupts.

section .data
gdt_start: dd 0x00000000, 0x00000000 ; Null descriptor
code_seg: dd 0x0000FFFF, 0x00CF9A00 ; Code segment descriptor
data_seg: dd 0x0000FFFF, 0x00CF9200 ; Data segment descriptor
gdt_end:

section .bss

section .text
global _start

_start:
; Load GDT
lgdt [gdt_start]

12
; Enable protected mode
mov eax, cr0
or eax, 1
mov cr0, eax

; Jump to protected mode code segment


jmp 08h:protected_mode_start

protected_mode_start:
; Set up data segments
mov ax, 10h
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax

; Set up IDT and other tasks


; ...

; Enable interrupts
sti

; Infinite loop to keep the program running


hlt
jmp hlt

5. Interrupt Flag Bits:


Interrupt Flag (IF)
The Interrupt Flag (IF) is a specific bit in the processor's flag register (EFLAGS in x86
architecture). It plays a crucial role in managing the handling of hardware interrupts.

Role of the Interrupt Flag (IF):


o Enabling Interrupts (IF = 1): When the IF is set (1), the processor will
acknowledge and respond to hardware interrupts. This means that when
an external interrupt request is received, the processor will pause its

13
current execution to handle the interrupt by executing the corresponding
Interrupt Service Routine (ISR).
o Disabling Interrupts (IF = 0): When the IF is cleared (0), the processor
will ignore hardware interrupts, effectively preventing the processor from
being interrupted by external events. This can be useful in critical
sections of code where interrupts could cause instability or inconsistency.

Impact on Interrupt Processing:


The state of the IF directly affects whether the processor will process hardware
interrupts:

 IF Set (Interrupts Enabled):


o The processor will recognize and handle hardware interrupts. Upon
receiving an interrupt request, the processor saves its current state (e.g.,
program counter, registers), jumps to the ISR, executes the ISR, and then
resumes the previous execution by restoring the saved state.
o This enables real-time responsiveness, allowing the processor to handle
time-critical tasks, such as responding to input from peripherals (e.g.,
keyboards, mice) or managing periodic tasks via timer interrupts.

 IF Cleared (Interrupts Disabled):


o The processor will ignore hardware interrupts, continuing its current
execution without interruption. This ensures that critical sections of code
can execute without interference, which is essential for maintaining data
integrity and preventing race conditions.
o However, it also means that time-sensitive tasks may be delayed if
interrupts are disabled for too long.

Assembly Code Examples:


Enabling Interrupts (IF = 1):

sti ; Set Interrupt Flag (Enable interrupts)

Disabling Interrupts (IF = 0):

cli ; Clear Interrupt Flag (Disable interrupts)

14
Example Scenario:
Consider a scenario where a program needs to perform a critical section of code without
being interrupted. The interrupts are disabled using `cli` before entering the critical
section and re-enabled using `sti` after the critical section is completed:

section .data
critical_section_msg db 'Critical section in progress...', 0

section .text
global _start

_start:
; Disable interrupts to protect critical section
cli

; Perform critical section of code


mov eax, 4
mov ebx, 1
mov ecx, critical_section_msg
mov edx, 29
int 0x80

; Enable interrupts after critical section is complete


sti

; Exit
mov eax, 1
xor ebx, ebx
int 0x80

6. Interrupt Vector Table:

The Interrupt Vector Table (IVT)is a crucial data structure in a microprocessor system
that maps interrupt requests to their corresponding interrupt service routines (ISRs). It
provides a way for the processor to quickly locate and execute the correct ISR when an
interrupt occurs.

15
Structure of the Interrupt Vector Table (IVT)
The IVT is typically located at the beginning of the memory address space. In x86
architecture, it starts at address 0x0000:0x0000. The table consists of a series of entries,
each entry corresponding to a specific interrupt vector number.

Key Characteristics:
o Number of Entries: The IVT has 256 entries, each corresponding to an
interrupt vector number ranging from 0 to 255.
o Entry Size: Each entry in the IVT is 4 bytes long, divided into two 2-byte
fields:
o Offset (2 bytes): The offset of the ISR within the segment.
o Segment Selector (2 bytes): The segment selector indicating the segment
where the ISR is located.

Storing an Interrupt Vector


When an interrupt vector is stored in the IVT, it includes the segment selector and offset
address of the ISR. For example, an entry for interrupt vector 0x20 might look like this:

 Segment Selector: The segment where the ISR is located.


 Offset: The specific address within the segment where the ISR starts.

Example of IVT Entry:


For an interrupt vector 0x20 with an ISR located at offset 0x1234 in segment 0x0010,
the IVT entry would be:

IVT[0x20] = 0x1234 (offset) + 0x0010 (segment selector)

Using the IVT During Interrupt Processing


When an interrupt occurs, the following steps are taken to process it:

 Interrupt Request: An interrupt request is generated by hardware or software.


 Finding the ISR: The processor uses the interrupt vector number to index into the IVT
and retrieve the address of the ISR.

16
 Saving the State: The processor saves its current state (e.g., program counter, flags,
registers) to ensure that it can return to the interrupted task later.
 Executing the ISR: The processor jumps to the ISR address obtained from the IVT and
executes the ISR to handle the interrupt.
 Returning from Interrupt: Once the ISR is completed, the processor restores its saved
state and resumes execution of the interrupted task.

Example in Assembly:

section .data
msg db 'Interrupt Handled!', 0

section .bss

section .text
global _start

_start:
; Set up IVT entry for interrupt vector 0x20
mov ax, 0x0010 ; Segment selector
mov word [0x0080], ax ; Store segment selector at IVT[0x20]
mov ax, isr_offset ; Offset of ISR
mov word [0x007E], ax ; Store offset at IVT[0x20]

; Enable interrupts
sti

; Trigger software interrupt with vector 0x20


int 0x20

; Infinite loop to keep the program running


hlt
jmp hlt

isr_offset:
; Define Interrupt Service Routine (ISR)
isr:
; Handle the interrupt
mov eax, 4
mov ebx, 1
mov ecx, msg

17
mov edx, 17
int 0x80

; Return from interrupt


iret

7. Steps in Interrupt Processing:


Basic Steps in Interrupt Processing
 Interrupt Request (IRQ): An interrupt request signal is generated by a hardware
device or a software instruction, indicating that an event requires immediate
attention.

 Saving the Current State: The processor saves its current state to ensure it can
resume execution after handling the interrupt. This typically involves:
o Saving the contents of the Program Counter (PC) or Instruction Pointer
(IP), which indicates the address of the next instruction to be executed.
o Saving the contents of the Flag Register (EFLAGS) to preserve the
current status of the processor.
o Saving general-purpose registers (such as AX, BX, CX, DX in x86) to
preserve the current working data.

 Vectoring to the Interrupt Service Routine (ISR): The processor uses the
interrupt vector number to index into the Interrupt Vector Table (IVT) and
retrieve the address of the ISR. The IVT maps each interrupt vector number to
the corresponding ISR address.

 Executing the ISR: The processor jumps to the ISR address obtained from the
IVT and executes the ISR to handle the interrupt. The ISR performs the
necessary tasks to service the interrupt, such as reading input data,
acknowledging the interrupt source, or managing error conditions.

 Restoring the Previous State: After the ISR completes its tasks, the processor
restores the previously saved state. This involves:
o Restoring the contents of the Program Counter (PC) or Instruction Pointer
(IP).
o Restoring the contents of the Flag Register (EFLAGS).
o Restoring the general-purpose registers.

18
 Resuming Execution: The processor resumes normal execution from where it
was interrupted, continuing the program flow as if the interrupt had never
occurred.

What Happens to the CPU State and Registers


When an interrupt is triggered, the following key actions occur:

 Program Counter (PC) or Instruction Pointer (IP): The current value of the PC or
IP is saved to ensure the processor can return to the interrupted instruction after
handling the interrupt.

 Flag Register (EFLAGS): The contents of the EFLAGS register are saved to
preserve the current status of the processor, including condition codes and the
interrupt flag (IF).

 General-Purpose Registers: The current values of general-purpose registers (e.g.,


AX, BX, CX, DX in x86) are saved to ensure the working data is not lost during
the interrupt processing.

 Interrupt Service Routine (ISR): The processor loads the ISR address from the
IVT and executes the ISR, performing the necessary actions to handle the
interrupt.

 Return from Interrupt (IRET): The `IRET` instruction is used to return from the
ISR. It restores the saved state of the processor, including the PC or IP,
EFLAGS, and general-purpose registers, allowing the processor to resume
normal execution.

Example in Assembly:

section .data
interrupt_msg db 'Interrupt Handled!', 0

section .text
global _start

_start:
; Enable interrupts
sti

19
; Trigger software interrupt with vector 0x20
int 0x20

; Infinite loop to keep the program running


hlt
jmp hlt

section .interrupt
; Define Interrupt Service Routine (ISR) for vector 0x20
isr_20:
; Handle the interrupt
mov eax, 4
mov ebx, 1
mov ecx, interrupt_msg
mov edx, 17
int 0x80

; Return from interrupt


iret

8. Handling Hardware Interrupts:


Mechanism of Handling Hardware Interrupts
 Interrupt Request (IRQ): A hardware device generates an interrupt request (IRQ)
signal to indicate that it needs attention from the CPU. This signal is sent to the
interrupt controller.

 Interrupt Controller: The interrupt controller (e.g., the Programmable Interrupt


Controller or PIC) receives the IRQ and prioritizes it among multiple interrupt
requests. The controller then sends an interrupt signal to the CPU, typically using
a dedicated line such as the Interrupt Request Line (IRQ line).

 CPU Interrupt Acknowledgment: Upon receiving the interrupt signal from the
interrupt controller, the CPU acknowledges the interrupt and saves its current
state. This involves saving the contents of the Program Counter (PC), Flag
Register (EFLAGS), and general-purpose registers to ensure that the CPU can
resume its previous task after handling the interrupt.

20
 Interrupt Vector Lookup: The CPU uses the interrupt vector number provided by
the interrupt controller to look up the corresponding Interrupt Service Routine
(ISR) in the Interrupt Vector Table (IVT) or Interrupt Descriptor Table (IDT).

 Executing the ISR: The CPU jumps to the address of the ISR and executes it. The
ISR performs the necessary tasks to handle the interrupt, such as reading data
from the hardware device, acknowledging the interrupt source, or managing error
conditions.

 End of Interrupt (EOI) Signal: After the ISR completes its tasks, it sends an End
of Interrupt (EOI) signal to the interrupt controller to indicate that the interrupt
has been handled.

 Restoring CPU State: The CPU restores its previously saved state, including the
Program Counter (PC), Flag Register (EFLAGS), and general-purpose registers.

 Resuming Execution: The CPU resumes normal execution from where it was
interrupted.

Roles of the Interrupt Controller and the CPU

Interrupt Controller:
o Prioritization: The interrupt controller prioritizes multiple interrupt
requests, ensuring that higher-priority interrupts are handled before
lower-priority ones.
o Interrupt Vector: The interrupt controller provides the interrupt vector
number to the CPU, indicating which ISR to execute.
o Masking and Handling: The interrupt controller can mask (disable)
certain interrupts to prevent them from being processed, allowing critical
tasks to proceed without interruption.
o EOI Handling: The interrupt controller handles the End of Interrupt (EOI)
signal from the CPU, allowing it to manage the status of active interrupts.

CPU:
o Interrupt Acknowledgment: The CPU acknowledges the interrupt signal
from the interrupt controller and saves its current state.
o ISR Execution: The CPU uses the interrupt vector number to locate and
execute the corresponding ISR.

21
o State Management: The CPU manages the saving and restoring of its
state to ensure smooth resumption of the interrupted task.
o Interrupt Flag (IF): The CPU controls the Interrupt Flag (IF) in the Flag
Register, enabling or disabling the handling of hardware interrupts as
needed.

Example in Assembly:

section .data
msg db 'Hardware Interrupt Handled!', 0

section .text
global _start

_start:
; Enable interrupts
sti

; Infinite loop to keep the program running


hlt
jmp hlt

section .interrupt
; Define Interrupt Service Routine (ISR) for hardware interrupt
isr_hardware:
; Handle the hardware interrupt
mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, 26
int 0x80

; Send End of Interrupt (EOI) signal to PIC


mov al, 0x20
out 0x20, al

; Return from interrupt


iret

22
9. Nested Interrupts:

Nested Interrupts:
Nested interrupts occur when an interrupt is allowed to interrupt another interrupt
service routine (ISR). In other words, while the CPU is handling one interrupt, another
higher-priority interrupt can preempt the current ISR, leading to a hierarchy or "nesting"
of interrupts.

Effects on System Performance:


o Improved Responsiveness: By allowing higher-priority interrupts to
preempt lower-priority ones, nested interrupts can enhance the system's
responsiveness to critical events. This is especially important in real-time
systems where timely responses to high-priority tasks are crucial.
o Increased Complexity: Handling nested interrupts adds complexity to the
system. The CPU must save and restore the state multiple times, manage
multiple ISRs, and ensure that the correct ISR executes at the right time.
o Potential for Latency: While nested interrupts improve responsiveness for
high-priority tasks, they can introduce latency for lower-priority tasks.
This is because lower-priority ISRs might be delayed or interrupted by
higher-priority ones.

Managing Nested Interrupts:


The CPU uses several mechanisms to manage nested interrupts effectively. These
include:

 Priority Levels: Each interrupt is assigned a priority level. The CPU uses these
levels to determine whether an incoming interrupt should preempt the current
ISR. Higher-priority interrupts can interrupt lower-priority ones.

 Saving and Restoring State: When an interrupt occurs, the CPU saves its current
state (e.g., program counter, flags, registers) to ensure it can resume the
interrupted task later. This process is repeated for each nested interrupt, creating
a stack of saved states.

 Interrupt Masking: The CPU can mask (disable) certain interrupts to prevent
them from preempting the current ISR. This is useful for protecting critical
sections of code that must not be interrupted.

23
 End of Interrupt (EOI): After handling an interrupt, the ISR sends an End of
Interrupt (EOI) signal to the interrupt controller, allowing it to handle the next
interrupt. In the case of nested interrupts, the CPU manages the EOI signal for
each level of nesting.

Example in Assembly:
Here's an assembly example illustrating nested interrupts with a focus on saving and
restoring the CPU state:

section .data
msg1 db 'Outer Interrupt Handled!', 0
msg2 db 'Inner Interrupt Handled!', 0

section .text
global _start

_start:
; Enable interrupts
sti

; Trigger outer interrupt with vector 0x20


int 0x20

; Infinite loop to keep the program running


hlt
jmp hlt

section .interrupt
; Define Outer Interrupt Service Routine (ISR) for vector 0x20
outer_isr:
; Save state
pushad
pushfd

; Handle outer interrupt


mov eax, 4
mov ebx, 1
mov ecx, msg1
mov edx, 23
int 0x80

24
; Trigger inner interrupt with vector 0x21
int 0x21

; Restore state
popfd
popad

; Send EOI signal


mov al, 0x20
out 0x20, al

; Return from interrupt


iret

; Define Inner Interrupt Service Routine (ISR) for vector 0x21


inner_isr:
; Save state
pushad
pushfd

; Handle inner interrupt


mov eax, 4
mov ebx, 1
mov ecx, msg2
mov edx, 23
int 0x80

; Restore state
popfd
popad

; Send EOI signal


mov al, 0x20
out 0x20, al

; Return from interrupt


iret

25
10. Practical Application:

Keyboard Interrupt (IRQ1)


In x86 architecture, the keyboard interrupt is typically assigned to interrupt vector 0x09
(IRQ1). When a key is pressed, the keyboard controller sends an interrupt request to the
CPU, which then executes the corresponding ISR.

Assembly Program

section .data
msg db 'Key Pressed: ', 0
char db 0

section .bss

section .text
global _start

_start:
; Set up the interrupt vector for keyboard (IRQ1) to point to our ISR
cli ; Disable interrupts
mov word [0x21*4], isr_key ; Set the ISR offset (low word)
mov word [0x21*4+2], cs ; Set the ISR segment (high word)
sti ; Enable interrupts

; Infinite loop to keep the program running


hlt
jmp hlt

isr_key:
; Save the state
pusha
push ds
push es
push fs
push gs

; Read the key pressed


in al, 0x60 ; Read the scan code from the keyboard controller

26
mov [char], al

; Display the key pressed message


mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, 12
int 0x80

; Display the key pressed character


mov al, [char]
mov [char+1], al
mov eax, 4
mov ebx, 1
mov ecx, char
mov edx, 1
int 0x80

; Acknowledge the interrupt


mov al, 0x20
out 0x20, al

; Restore the state


pop gs
pop fs
pop es
pop ds
popa

; Return from interrupt


iret

; This instruction lets the linker know where the code segment (CS) starts
section .startup_code
cs:
jmp _start

Explanation
 Interrupt Vector Setup:
o The program first disables interrupts using `cli`.

27
o It sets up the interrupt vector for IRQ1 (keyboard interrupt) to point to the
custom ISR (`isr_key`). This is done by setting the appropriate entry in
the interrupt vector table (IVT).
o It then re-enables interrupts using `sti`.

 ISR (Interrupt Service Routine):


o The ISR `isr_key` is defined to handle the keyboard interrupt.
o It saves the current state of the CPU registers.
o It reads the scan code from the keyboard controller port (0x60) and stores
it in the `char` variable.
o It displays a message indicating that a key was pressed, along with the
scan code.
o It sends an End of Interrupt (EOI) signal to the PIC using port 0x20.
o It restores the CPU state.
o It returns from the interrupt using the `iret` instruction.

 Infinite Loop:
o The main program enters an infinite loop using `hlt` to keep the program
running and waiting for interrupts.

Reference:
- Irvine, K. R. (2007). Assembly Language for x86 Processors (5th ed.). Prentice Hall.
- Tanenbaum, A. S. (2001). *Structured Computer Organization* (4th ed.). Pearson.

28

You might also like