0% found this document useful (0 votes)
3 views27 pages

Microprocessor

The document discusses memory management in the 80386 microprocessor, detailing address translation processes in both real and protected modes, including segment and paging translation. It explains the roles of logical, linear, and physical addresses, as well as descriptor tables and their instructions. Additionally, it covers the importance of protection in multitasking systems and the rules governing privilege levels for secure memory access.

Uploaded by

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

Microprocessor

The document discusses memory management in the 80386 microprocessor, detailing address translation processes in both real and protected modes, including segment and paging translation. It explains the roles of logical, linear, and physical addresses, as well as descriptor tables and their instructions. Additionally, it covers the importance of protection in multitasking systems and the rules governing privilege levels for secure memory access.

Uploaded by

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

Microprocessor

Unit 3 : Memory Management

3.1 Complete Address Translation


In real mode, The 80386 forms the physical address by moving the segment selector (which is
part of the logical address) left by 4 bits (multiplying by 16) and then adding the offset to it.
In protected mode, the processor converts logical addresses (addresses used by programs)
into physical addresses (actual locations in memory) in two steps:
Segment Translation: The segment selector shows where the segment starts. This starting
address is added to the 32-bit offset to get the linear address.
Page Translation: If paging is enabled, the linear address is converted into the physical address
using page tables, it depends on whether paging is turned on. If paging is not enabled, the
linear address is directly used as the physical address.

3.2 Segment Translation in 80386


In the 80386 protected mode, segment translation is the process of converting a logical
address into a linear address. A logical address consists of two parts:
Segment Selector (16-bit)
Offset (32-bit effective address)

The translation involves the following steps:


1. Segment Selector to Descriptor:
The segment selector is used to locate the segment descriptor in either the Global Descriptor
Table (GDT) or Local Descriptor Table (LDT). It contains:
Index (points to the descriptor)
TI bit (to choose GDT or LDT)
RPL (Privilege Level)
2. Descriptor to Base Address:
The segment descriptor contains:
32-bit Base Address
Segment Limit
Access Rights and Flags
The CPU extracts the base address of the segment from the descriptor.
3. Forming the Linear Address:
The base address from the descriptor is added to the 32-bit offset to generate the 32-bit linear
address
If paging is disabled, the linear address becomes the physical address. If paging is enabled, this
linear address undergoes a second step (paging translation) to become the physical address.
3.3 Paging Translation
In protected mode, the 80386 processor supports paging as an optional second stage of
address translation. It converts a linear address into a physical address using a two-level
paging mechanism.
Steps in Paging Translation:
Linear Address Structure (32-bit):
The 32-bit linear address is divided into three fields:
Dir: Index into the Page Directory
Page: Index into the Page Table
Offset: Offset within the 4KB physical page

Page Directory Access:


The CR3 register holds the Page Directory Base Address.
Using the Dir field, the CPU locates the Page Table Address from the page directory entry.

Page Table Access:


The Page field indexes into the selected Page Table to fetch the Page Frame Base Address.

Forming the Physical Address:


The Page Frame Base Address is added to the 12-bit Offset to produce the final Physical
Address.

Page Tables : Paging is a memory management method in 80386 used to divide the linear
address space into small pages (each 4 KB).
Instead of storing entire programs in one segment, paging breaks memory into equal-sized
blocks for efficient access and protection.
PDE (Page Directory Entry) Descriptor : A PDE is one entry in the Page Directory. Each PDE
points to a Page Table.
Contains:
Base address of the Page Table
Flags like:
P (Present): 1 if page table is in memory
R/W (Read/Write): access rights
U/S (User/Supervisor): user mode or kernel
PTE (Page Table Entry) Descriptor : A PTE is one entry in a Page Table. Each PTE points to a
physical memory page (4 KB).
Contains:
Base address of a 4 KB physical memory page
Flags similar to PDE:
P (Present): 1 if page is in memory
R/W: Read or write permission
U/S: User or system level
3.4 Logical address
A logical address is the address generated by the CPU during program execution.
It consists of:
Segment Selector (16-bit)
Offset (32-bit)
In protected mode, it is represented as:
Logical Address = Segment Selector : Offset
This address needs to be translated before accessing memory.

3.5 Linear Address


A linear address is the intermediate address obtained after segment translation.
It is calculated as:
Linear Address = Segment Base Address + Offset
If paging is disabled, the linear address is directly used as the physical address. If paging is
enabled, it is further translated.

3.6 Physical Address


The physical address is the actual address in the RAM (main memory) where data/instructions
are stored.
If paging is enabled:
Physical Address = Page Frame Base + Offset
This is the final address sent to the memory unit to fetch/store data.

3.7 Descriptor Table Instructions in 80386


1. LGDT – Load Global Descriptor Table Register
Full Form: Load Global Descriptor Table
Syntax: LGDT mem
Description: Loads the base address and limit of the Global Descriptor Table (GDT) from
memory into the GDTR register.
2. SGDT – Store Global Descriptor Table Register
Full Form: Store Global Descriptor Table
Syntax: SGDT mem
Description: Stores the current contents of the GDTR register into the specified memory
location.
3. LLDT – Load Local Descriptor Table Register
Full Form: Load Local Descriptor Table
Syntax: LLDT reg/mem16
Description: Loads a segment selector into the LDTR (Local Descriptor Table Register).
4. SLDT – Store Local Descriptor Table Register
Full Form: Store Local Descriptor Table
Syntax: SLDT reg/mem16
Description: Stores the current selector from the LDTR into memory or a register.
5. LIDT – Load Interrupt Descriptor Table Register
Full Form: Load Interrupt Descriptor Table
Syntax: LIDT mem
Description: Loads the base and limit of the Interrupt Descriptor Table (IDT) into the IDTR
register.
6. SIDT – Store Interrupt Descriptor Table Register
Full Form: Store Interrupt Descriptor Table
Syntax: SIDT mem
Description: Stores the contents of the IDTR register to memory.

3.8 Segment Descriptors : System and Non-System Descriptors


In Protected Mode, the 80386 microprocessor uses segment descriptors to define the
properties of memory segments

1. System Descriptors :
These descriptors are used by the Operating System to manage special system functions like
task switching, interrupt handling, and segmentation.
The S bit = 0 in the descriptor indicates a system descriptor.
Types :
LDT Descriptor (Local Descriptor Table)
Points to the base and limit of the LDT.
Allows each task to have its own private segment descriptors.
Stored in GDT and loaded using the LLDT instruction.
TSS Descriptor (Task State Segment)
Defines a special segment that stores task context (registers, stack pointers, etc.).
Enables hardware task switching.
TSS is essential for multitasking environments.
Accessed using LTR (Load Task Register) and JMP/CALL Task instructions.
Gate Descriptors
Used to control transfer of control between segments, especially across different privilege
levels. Gates include:
Call Gate: Allows controlled access to higher privilege procedures.
Interrupt Gate: Used in IDT to handle hardware interrupts.
Trap Gate: Similar to interrupt gate but doesn't disable interrupts.
Task Gate: Points to a TSS for task switching via interrupts.

2. Non-System Descriptors
These are the code and data segments used by application programs.
The S bit = 1 indicates a non-system descriptor.
Types :
Code Segment Descriptor
Stores program instructions (executable code).
Accessed by the CS (Code Segment) register.
Can be marked readable or conforming (for privilege level transitions).
Data Segment Descriptor
Stores variables, constants, and stack.
Accessed via DS, ES, SS, FS, GS registers.
Can be marked readable/writable.
May grow upwards or downwards (like stack segments).
3.9 GDTR
The GDTR (Global Descriptor Table Register) is a special register in the 80386 microprocessor
used to manage memory segmentation in protected mode.
GDTR holds the base address and limit of the Global Descriptor Table (GDT), which contains
segment descriptors used to define code, data, and system segments globally across tasks.

Contents of GDTR:
Field Size Description
Base 32 bits Points to the starting address of GDT
Limit 16 bits Specifies the size (length) of GDT in bytes minus one
GDTR itself is not part of memory; it's an internal CPU register.
It is loaded using the LGDT instruction and stored using SGDT.

3.10 LDTR
The LDTR (Local Descriptor Table Register) is a special register in the 80386 microprocessor
that holds information about the Local Descriptor Table (LDT), which provides task-specific
segment descriptors.
LDTR points to the LDT, which stores the code, data, and stack segments for a specific task.
Contents of LDTR:
LDTR itself holds a selector that points to an LDT descriptor located in the Global Descriptor
Table (GDT). This descriptor provides:

Field Size Description


Base 32 bits Base address of the LDT in memory
Limit 16 bits Size of the LDT in bytes minus one
Flags -- Access rights and segment type info

3.11 IDTR
The IDTR (Interrupt Descriptor Table Register) is a special 80386 CPU register that holds the
base address and limit of the Interrupt Descriptor Table (IDT). The IDT is used for handling
interrupts and exceptions.
IDTR tells the processor where the IDT is, which holds the addresses of routines that handle
hardware and software interrupts.
Contents of IDTR:
Field Size Description
Base 32 bits Starting address of the Interrupt Descriptor Table
Limit 16 bits Size of the IDT in bytes minus one

IDTR is loaded using the LIDT instruction and stored using the SIDT instruction.
The IDT can contain up to 256 entries (0 to 255 interrupt vectors).

3.12 Difference Between GDTR,LDTR and IDTR


GDTR (Global Descriptor LDTR (Local Descriptor IDTR (Interrupt Descriptor
Point
Table Register) Table Register) Table Register)
Holds the base and limit Holds the base and Holds the base and limit for
Purpose
for the GDT. limit for the LDT. the IDT.
Global segments in Local segments for Interrupt handling
Used By
memory. specific tasks. routines.
Refers to the Local
Descriptor Refers to the Global Refers to the Interrupt
Descriptor Table
Table Descriptor Table (GDT). Descriptor Table (IDT).
(LDT).
All processes in the Specific to a particular Used for interrupt handling
Accessed By
system. process or task. by the CPU.
Managed by the Managed by the
Managed by the operating
Control operating system operating system per
system globally.
globally. task.
Size 8 bytes (base + limit). 8 bytes (base + limit). 8 bytes (base + limit).
Used for global memory Provides protection Used for interrupt
Protection
protection. for local memory. protection.
Limits the size of the Limits the size of the Limits the size of the
Limit
global address space. local address space. interrupt table.

3.13 General Format Of Descriptor


Base: This is where the segment starts in memory. It helps the 80386 processor know where
the segment is located in the memory space (which can be up to 4GB).
Limit: This tells how big the segment is. The 80386 combines two parts of the limit to form a
20-bit value. It can interpret this value in two ways:
If the Granularity bit (G) is 0: The limit is in bytes, and the segment can be up to 1MB
(1,048,576 bytes).
If the Granularity bit (G) is 1: The limit is in 4KB units, and the segment can be up to 4GB
(4,294,967,296 bytes).
Granularity bit: This bit tells how the limit should be read:
0 means the limit is in bytes (small units).
1 means the limit is in 4KB chunks (larger units).
Reserved (0): This bit is reserved by Intel, meaning you can't use it or change it. It's there for
future processors.
AVL/U (User Bit): This bit is ignored by the processor. It’s for the operating system or users to
use for their own purposes.
Access Rights Byte:
P (Present Bit): This bit tells if the segment is loaded in memory. If it’s 0, trying to access this
segment will cause an error.
DPL (Descriptor Privilege Level): This tells how "important" or "privileged" a segment is. A
higher DPL means higher privileges (more control).
S (System Bit): If this bit is 1, it means the segment is either a code or data segment. If it's 0,
it’s a system segment.
Type: This defines what kind of segment it is (like data, code, or system).
A (Accessed Bit): The processor automatically sets this bit whenever the segment is accessed.
It helps track when the segment has been used.

3.14 General Selector Format


In 80386, a selector is a 16-bit value used to choose a segment from memory. It tells the CPU
which segment to use.
The selector is divided into 3 parts:

Index (13 bits) –


This is the biggest part (bits 3 to 15).
It gives the entry number in the descriptor table.
The descriptor tells where the segment starts and other details.

TI (Table Indicator - 1 bit) –


Bit 2 of the selector.
Tells which table to use:
0 = GDT (Global Descriptor Table)
1 = LDT (Local Descriptor Table)

RPL (Requestor’s Privilege Level - 2 bits) –


Bits 0 and 1.
Shows the privilege level (0 = highest, 3 = lowest).
Used for protection and access control.
3.15 Explain GDT,LDT and IDT
1. GDT (Global Descriptor Table)
GDT is used to define all global segments.
It is common for all programs in the system.
Each entry in GDT is a segment descriptor – it gives the base address, limit, and access rights
of a segment.
Example segments in GDT: Code, Data, Stack, Video memory, etc.
GDT is always used when TI bit = 0 in the selector.

2. LDT (Local Descriptor Table)


LDT is used for per-process segment definitions.
Each program (task) can have its own LDT.
It allows multi-tasking, where each task has a different memory view.
LDT also has segment descriptors like GDT.
LDT is used when TI bit = 1 in the selector.

3. IDT (Interrupt Descriptor Table)


IDT is used to handle interrupts and exceptions.
Each entry in IDT is an interrupt descriptor.
It gives the address of the Interrupt Service Routine (ISR).
IDT is used when an interrupt or exception occurs.
Example: Divide by zero, page fault, keyboard interrupt, etc.

Unit 4 : Protection

4.1 Need Of Protection


In multitasking or multi-user operating systems, problems can happen when two or more
users try to read and change the same memory at the same time. This part of the program is
called the critical section, and it must be protected so that only one task can access it at a
time.

Another important part that needs protection is the operating system code. If a user program
has a wrong address, it might overwrite and damage important system data. This can cause
the system to lock up, and the only way to fix it is by restarting the system.

To prevent such problems in multitasking systems, special methods are used to keep the
system safe and running properly.

4.2 Rules of Protection Check


1. CPL (Current Privilege Level)
CPL is the current privilege level of a running program or task in the CPU.
It can be 0 (highest privilege - kernel) to 3 (lowest privilege - user).
It helps the CPU control access to memory and hardware to prevent unauthorized access.

2. DPL (Descriptor Privilege Level)


DPL is the privilege level assigned to a segment (like code or data).
Also ranges from 0 to 3.
A program can only access a segment if its CPL ≤ DPL, ensuring secure access control.

3. RPL (Requested Privilege Level)


RPL is stored in the segment selector when a task wants to access a segment.
It shows the requested level of access.
CPU uses max(CPL, RPL) to decide if access to a segment (with DPL) is allowed.

4. IOPL (I/O Privilege Level)


IOPL controls the ability to execute I/O instructions (like IN, OUT).
Stored in the EFLAGS register, ranges from 0 (highest) to 3 (lowest).
Only tasks with CPL ≤ IOPL can perform I/O operations directly.

5. TSS (Task State Segment)


TSS is a special data structure used in task switching.
It stores CPU register values, stack pointers, and other task-specific data.
Helps the CPU save and restore task states when switching between tasks.

6. GDT (Global Descriptor Table)


GDT is a table that stores descriptors for global segments (code, data, TSS).
Used by the CPU to understand the size, location, and access rights of memory areas.
Shared by all tasks in the system.

7. LDT (Local Descriptor Table)


LDT is similar to GDT but is specific to a particular task.
Stores descriptors for that task’s private segments.
Allows different tasks to have separate views of memory for protection and multitasking.

4.3 5 Aspects of Protection in 80386


1. Type Checking
The 80386 keeps track of what kind of data is stored in each memory segment — like code,
data, or stack. It makes sure that each segment is used correctly
If a program tries to do something wrong (like run data as code), the processor stops it. This
helps avoid bugs and protects the system from malware or accidental misuse.

2. Limit Checking
Each memory segment in 80386 has a limit (size). When a program runs, the processor checks
whether it's trying to access memory within that limit.
If the program tries to go beyond its allowed memory, the CPU gives an error
It ensures that each program stays within its own memory boundaries.

3. Restriction of Addressable Domain


In 80386, a program can only "see" and access certain areas of memory
The processor blocks programs from accessing memory they shouldn't use.
This protects the system from crashes or security risks caused by one program interfering with
another.

4. Restriction of Procedure Entry Points


Programs often call functions or procedures. In 80386, the CPU makes sure that:
A program can only enter procedures at allowed entry points.
It cannot jump to random places inside another function.

5. Restriction of Instruction Set


Some instructions in 80386 are very powerful
These are called privileged instructions.
Only the operating system or trusted software running in a special mode (Ring 0) can use
them.
If a normal program tries to use them, the processor blocks it.

4.4 Page Level Protection Aspects


Restricting Addressable Domain :
The U/S bit (User/Supervisor bit) controls who can access a memory page.
U/S = 0, the page is meant for the operating system or system software (supervisor level).
When the CPU is working in supervisor mode, it can access all pages.
If U/S = 1, the page is meant for normal user programs.
When the CPU is in user mode, it can access only user-level pages.

Type Checking :
There are two types of page access:
Read-only (if R/W = 1)
Read and Write (if R/W = 0)
In supervisor mode, all pages can be read and written.
In user mode, the CPU checks the R/W bit:
If R/W = 1, the page can be read-only.
If R/W = 0, the page can be read and written.
Also, a program running in user mode cannot access memory meant for the supervisor (OS).

4.5 Various fields in Page Level Protection.


Page level protection in 80386 ensures that only authorized programs or users can access
certain areas of memory. It uses flag bits in the Page Directory Entries (PDEs) and Page Table
Entries (PTEs) to control this access.

Field Full Name Role in Protection Simple Meaning


1 = Page is in memory0 = Is the page available or
P Present
Page fault occurs missing?
0 = Read-only1 = Read & Can the page be written
R/W Read/Write
write allowed to?

0 = Supervisor (kernel-only)1 Who is allowed to use this


U/S User/Supervisor
= User access allowed page?

Set to 1 when the page is Helps in tracking usage for


A Accessed
accessed (CPU sets this) optimization
Set when a write occurs to Has the page been
D Dirty (only in PTE)
the page modified?
OS can use it for custom
AVL Available to software Reserved for OS/software use
features
PS Page Size (only in 0 = 4 KB page1 = 4 MB page Size of the page being
PDE) referred to
Global (in PTE, if Prevents TLB flush on task Keeps frequently-used
G
enabled) switch pages cached

4.6 Different levels of protection


Ring 0 (Privilege Level 0 – Most Powerful)
This is the highest privilege level.
Only Operating System kernel code runs here.
It has full access to hardware, memory, and all CPU instructions.
Can execute privileged instructions like enabling paging or handling interrupts.
Example: Windows or Linux kernel code.

Ring 1 (Privilege Level 1)


Used for device drivers or critical system services.
Less privileged than Ring 0 but more than user-level code.
It can access hardware and memory, but not as freely as Ring 0.
Rarely used in many modern OSes (often skipped).

Ring 2 (Privilege Level 2)


Used for system-level utilities that need more access than user apps.
Has access to specific memory areas but not kernel space.
Also rarely used — modern OSes usually use only Ring 0 and Ring 3.

Ring 3 (Privilege Level 3 – Least Powerful)


This is where user applications run (like Chrome, Word, games).
They have the least access and cannot directly talk to hardware.
If they want to do so, they must request help from the OS using system calls.
Prevents user programs from crashing or harming the system.

4.7 What is call gate? Explain how it is used in calling functions with higher privilege
levels.
Call Gate:
A Call Gate is a mechanism in the 80386DX microprocessor that allows a program running in a
lower privilege level (user mode) to safely call a function that runs in a higher privilege level
(kernel mode).
Privilege Levels (PL): The 80386DX processor has different privilege levels:
PL0 (Kernel mode): High privilege, can access all system resources.
PL3 (User mode): Low privilege, restricted access to system resources.

Need for Call Gate: When a program in user mode (PL3) wants to call a function in kernel
mode (PL0), it can't do so directly. This is because of security reasons. The Call Gate acts as a
safe entry point for this transition.

Functioning of Call Gate:


The Call Gate checks if the program can safely switch from user mode to kernel mode.
It then switches the privilege level from PL3 to PL0 and allows the call to the kernel function.
After the function completes, the program is returned back to user mode (PL3).

4.8 How control transfer instructions are executed using the call gate in the system
Control transfer instructions (such as CALL, RET, JMP) are used to transfer control from one
part of a program to another.

Control Transfer Process:


The program uses a control transfer instruction (like CALL).
The instruction checks the privilege level of the caller and called function.
If the called function is in a higher privilege level (like kernel mode), the Call Gate is used to
perform the transition.
The Call Gate ensures the privilege level is switched from PL3 (user mode) to PL0 (kernel
mode) safely.
After the function in kernel mode completes, control is transferred back to user mode, and the
privilege level is switched back from PL0 to PL3.

4.9 Combining Segment Protection and Page-Level Protection


The 80386 microprocessor uses two types of memory protection: segment protection and
page-level protection, which work together to ensure memory safety and control access.
Segment Protection:
Memory is divided into segments, each with its own access rights (read, write, execute) and
privilege level (PL0 to PL3).
Segments help protect larger areas of memory, ensuring that user programs cannot access
sensitive kernel code.
Page-Level Protection:
Memory is also divided into smaller units called pages (usually 4KB).
Each page has its own access rights (read, write, execute), and protection can be applied to
individual pages, offering finer control.
Combination:
Segment protection controls large memory areas, while page-level protection gives more
detailed control over individual pages.
This combination ensures that programs in lower privilege levels (user mode) cannot access
critical system areas in higher privilege levels (kernel mode).
4.10 Privilege Instructions
CLTS (Clear Task-Switched Flag):
Clears a flag that shows if a task switch has occurred. It’s used to reset the system after a task
switch.

HLT (Halt Processor):


Stops the processor from running. It’s used to halt the system, usually for debugging.

LGDT (Load GDT Register):


Loads the address of the Global Descriptor Table (GDT) into a register.
The GDT is used to define memory segments.

LIDT (Load IDT Register):


Loads the address of the Interrupt Descriptor Table (IDT) into a register.
The IDT helps handle interrupts by pointing to the interrupt routines.

LLDT (Load LDT Register):


Loads the address of the Local Descriptor Table (LDT) into a register.
The LDT is used for memory segments specific to a task or process.

LMSW (Load Machine Status Word):


Loads the Machine Status Word (MSW) with a new value.
The MSW holds flags that control how the processor works, like task switching.

LTR (Load Task Register):


Loads the Task Register (TR) with the address of the Task State Segment (TSS).
The TR helps manage task switching in the system.

MOV to/from CRn (Move to/from Control Register n):


Moves data to or from control registers (CR0 to CR4).
These control system settings, like paging or memory protection.

MOV to/from DRn (Move to/from Debug Register n):


Moves data to or from debug registers (DR0 to DR7).
These are used for debugging and setting breakpoints.

MOV to/from TRn (Move to/from Test Register n):


Moves data to or from test registers (TR0 to TR7).
These are used for testing purposes during debugging.

Unit 5 : Multitasking and Virtual 8086 Mode

5.1 Multitasking
Multitasking is the ability of a computer to run more than one program or task at the same
time.
The 80386 has special registers, special data structure for protecting multitasking system :
1. Task State Segment (TSS)
2. Task State Segment Descriptor
3. Task Register
4. Task Gate Descriptor

5.2 Task State Segment (TSS)


TSS is a special memory area used by the 80386 microprocessor to manage multitasking. It
stores all the important details of a task, so the CPU can stop one task and start another, and
later resume the first task from where it stopped.
TSS is not accessible by normal programs. Only the CPU can access and use it.
TSS has two parts:
1. Dynamic Set (Updated by CPU)
2. Static Set (Read-only)

1. Dynamic Set (Updated by CPU)


This part is automatically saved when the CPU switches tasks. It stores:
General Registers: EAX, EBX, ECX, EDX, ESP, EBP, ESI, EDI
Segment Registers: CS, DS, SS, ES, FS, GS
EFLAGS Register: Stores condition flags
EIP Register: Holds the address of next instruction
Back Link: Helps return to the previous task
These values help the CPU pause and later restart a task exactly from where it left off.

2. Static Set (Read-only)


This part contains fixed information for the task. It stores:
LDT Selector: For accessing the task's local data
PDBR: Used for paging (virtual memory)
Stack Pointers for privilege levels 0, 1, 2 (used when CPU changes privilege levels)
T-bit: Used for debugging during task switch
I/O Map Offset: Controls which I/O ports the task can access
When CPU changes the privilege level (like from user to kernel mode), it also switches the
stack using this info.

5.3 TSS Descriptor


Just like other segments in 80386, the Task State Segment (TSS) is also defined using a TSS
descriptor.
This descriptor contains several fields, just like any other segment descriptor.

Important Fields in TSS Descriptor:


B-bit (Busy bit):
Indicates whether the task is currently running.
If the bit is set, it means the task is busy. This prevents the CPU from switching to a task that is
already running.
Base, Limit, DPL, G-bit, P-bit:
These fields work the same way as in other segment descriptors.
Base: Starting address of TSS
Limit: Size of the TSS (should be at least 104 bytes)
DPL (Descriptor Privilege Level): Who can access the TSS
G-bit (Granularity bit) and P-bit (Present bit): Control segment size and presence

To access or switch to a task using the TSS descriptor, the current privilege level (CPL) must be
≤ DPL of the TSS descriptor.
To keep task switching secure, the DPL is usually set to 0, allowing only trusted (privilege level
0) software like the operating system to switch tasks.

5.4 Task Register


The Task Register (TR) is used to point to the Task State Segment (TSS) of the currently running
task. It helps the CPU know which task is active.

Structure of Task Register:


TR has two parts:
Visible Portion:
Can be seen and modified by instructions
Holds a selector that points to the TSS descriptor in the Global Descriptor Table (GDT)
Invisible Portion (Hidden):
Cannot be accessed directly
Stores the base address and limit of the TSS
These values are cached by the CPU for faster access, so it doesn’t need to fetch them from
memory every time.

Instructions Related to TR:


LTR (Load Task Register):
Loads both the visible and invisible parts of the TR
Fills visible part with selector and invisible part with base and limit from the TSS descriptor
Privileged instruction (can only be run at CPL = 0)
STR (Store Task Register):
Stores only the visible portion (selector) of the TR into a general register or memory
Not a privileged instruction, so it can be used in user programs
5.5 Task Gate Descriptor
A Task Gate is a special type of system gate used to switch from one task to another. It does
not define a memory segment like normal segment descriptors. Instead, it gives protected
access to a Task State Segment (TSS).

Features of Task Gate:


It has its own descriptor called a Task Gate Descriptor.
This descriptor contains a selector that points to a TSS descriptor, which identifies the task to
be started.
A task gate provides indirect access to TSS.
Like call gates, task gates can be used in FAR CALL and FAR JMP instructions.

Privilege Control (DPL Rule):


Every task gate has a DPL (Descriptor Privilege Level) field.
To access a task gate, the following condition must be met:
MAX (CPL, RPL) ≤ DPL of the task gate

5.6 Task Switching


The 80386 processor supports task switching, which means changing from one task (program)
to another. Each task has its own Task State Segment (TSS), which stores the context
(registers, stack, etc.).
After every task switch, the new task is marked “busy” using the B-bit in the TSS descriptor.
A task cannot switch to another task that is already busy. This prevents errors.

80386 switches tasks in 4 ways:


Long JMP or CALL to a TSS Descriptor:
Direct jump to another task using its TSS. Used by OS to switch tasks at the end of time slice.
JMP or CALL to a Task Gate:
Task gate points to the new TSS. Useful for controlling access using privilege levels.
Interrupt Uses Task Gate:
The interrupt descriptor table contains a task gate which switches to a task when an interrupt
occurs.
IRET with NT Bit Set:
When the NT (Nested Task) bit is set in EFLAGS, IRET returns control to the previous task using
the back link.

Steps in Task Switching (Without Task Gate):


Privilege Check:
TSS DPL is checked with CPL and RPL. If allowed, switch proceeds.
Limit & Presence Check:
Checks if the TSS is present and has a valid size.
Save Current Task State:
Current register values and flags are saved in current TSS. Back link is updated.
Load New Task Register (TR):
TR is loaded with selector of the new TSS. TS bit is set, and new TSS is marked busy.
Resume New Task:
80386 starts running the new task using the new CS and EIP (instruction pointer).

//Steps in Task Switching (Using Task Gate):


//Privilege Check:
//Only DPL of Task Gate is checked (not TSS DPL). If CPL and RPL allow, switch continues.
//Other Steps Same as Direct Switch:
//The only difference is that the TSS selector is fetched indirectly through the task gate.

5.7 Nested Tasks / Task Linking


Nested tasks are like nested subroutines in programming. If a task switch happens due to a
FAR CALL instruction or an exception, the new task is considered nested within the task that
called it.
Back Link:
The Back Link is a special field in the TSS (Task State Segment) that tracks the previous task. It
acts like a call/return stack. When a task finishes, it uses the IRET (Interrupt Return) instruction
to switch back to the previous task, using the Back Link.
NT (Nested Task) Flag:
The NT flag in the EFLAGS register indicates whether the task is nested. If set, it means the
current task is nested and will return to the previous task using IRET.

5.8 Features of Virtual 8086 Mode


Switch Between Modes:
The 80386 can switch between protected mode and virtual 8086 mode to run 8086 programs
alongside modern tasks.

Multiple 8086 Programs:


It can run several 8086 or 80186 programs as separate tasks in virtual 8086 mode while still
being in protected mode.

1 MB Memory Limit:
Each task in virtual 8086 mode has access to 1 MB of memory, just like the original 8086
processor.

Linear Addressing:
The 80386 uses segment and offset registers to generate linear addresses instead of physical
addresses.

Page Translation:
The linear address is converted to a physical address using page translation, allowing the task
to use any physical address in the 4 GB memory space.

I/O Control:
The 80386 can manage I/O and interrupts in virtual 8086 mode. Software can control which
programs have access to I/O ports by setting Input/Output Privilege Level (IOPL).

Interrupt Handling:
Virtual 8086 mode supports interrupts and exceptions while keeping tasks isolated and secure
from each other.

Real Mode Compatibility:


In this mode, the 80386 behaves like the older 8086 processor, making it compatible with
legacy software.

Task Isolation:
Each virtual 8086 task runs in an isolated environment, preventing one task from interfering
with another.

5.9 Linear address formation in virtual mode


Segment Registers and Offsets:
In virtual 8086 mode, the segment registers don't directly point to memory like in protected
mode. Instead, they are used to create a linear address by adding them to an offset (effective
address).

Creating the Linear Address:


The segment register is shifted left by 4 bits (multiplied by 16) and then added to the offset to
form a linear address.
If there’s a carry during the addition, the address is still valid as a linear address.

Address Range:
The linear address can range from 0 to 10FFEFH, which is about 1 MB plus 64 KB. This is the
space the task can use in virtual 8086 mode.
32-bit Linear Address:
The 80386 uses 32-bit linear addresses, which means it can handle larger addresses, even
though the 8086 could only use 21 bits.
These 32-bit addresses can be mapped to any physical address using page tables.

Address Size Limit:


The 80386 supports 32-bit addresses, but they must not go beyond 65535 to remain
compatible with 80286 real mode.
If the address is too large, a fault occurs (interrupt 12 or 13 with no error code).

5.10 Structure of V86 Task


V86 Mode Operation:
The 80386 enters V86 mode to execute an 8086 program and can return to protected mode to
execute the monitor or other tasks.

Requirements for 8086 Program in V86 Mode:


To run successfully in V86 mode, an 8086 program needs the following:
A V86 monitor (which runs in protected mode at privilege level 0).
Operating-system services.

Role of V86 Monitor:


The V86 monitor is 80386 protected-mode code running at privilege level 0.
It mainly handles initialization and exception handling.
Executable-segment descriptors for the monitor must be available in the GDT or LDT of the
task.
The monitor can use linear addresses above 10FFEFH, which are reserved for the V86 monitor,
the operating system, and other system software.

Handling the 8086 Operating System:


There are two ways to implement the 8086 operating system:
a. 8086 Operating System as Part of 8086 Code:
This is useful when:
The 8086 application code modifies the operating system.
There isn’t enough time to rewrite the 8086 operating system as 80386 code.
b. 8086 Operating System Emulated in V86 Monitor:
This method is preferable when:
Operating system functions can be easily managed across multiple V86 tasks.
The functions of the 8086 OS can be easily emulated by making calls to the 80386 OS.
5.11 Using paging for V86 Tasks
Paging is not needed for one V86 task, but it is useful in these cases:
Many V86 tasks – When we run many V86 tasks, paging helps to give each task its own
memory area.
Megabyte wrap – Paging helps to copy the 8086 feature where memory wraps around after 1
MB (just like in old systems).
More virtual memory – Paging allows us to use more memory than the real physical memory
available.
Sharing common code – If many 8086 programs use the same OS or ROM code, paging helps
them share it without copying.
Control memory-mapped I/O – Paging helps to manage or block access to special memory
areas like I/O devices.

5.12 Protection within a V86 Tasks


In Virtual 8086 (V86) mode, hardware protection using descriptors is not available. So, to
protect the system, we can use these two methods:
Reserve memory area – Keep the first 1 MB (plus 64 KB) of memory only for the 8086
program. This way, the 8086 program cannot access memory outside this range.
Use U/S (User/Supervisor) bit – In paging, use the U/S bit to protect system software. V86
mode runs at privilege level 3 (user mode), so it cannot access pages marked as supervisor
(level 0). This keeps system software safe from the 8086 program.

5.13 Entering and Leaving Virtual 8086 (V86) Mode


When 80386 Enters V86 Mode:
80386 can enter Virtual 8086 mode in these ways:
Interrupt to a task gate – If an interrupt occurs and it leads to a task gate, V86 mode may be
entered.
By OS scheduler – The operating system can switch to V86 mode during task scheduling.
IRET with NT flag set – If IRET (return from interrupt) is done and the NT (Nested Task) flag is
set, V86 mode can be entered.

How 80386 Enters V86 Mode:


Task Switch – When switching to a new task using TSS (Task State Segment), if the VM bit in
EFLAGS is 1, the CPU enters V86 mode. If VM bit is 0, it enters protected mode.
IRET instruction – If IRET is executed in privilege level 0, it can change the VM bit to 1,
entering V86 mode.

How 80386 Leaves V86 Mode:


80386 leaves V86 mode when an interrupt or exception happens.
Task Switch – If an interrupt causes a task switch to a task with VM bit = 0 (or to a 286 task),
the CPU clears VM bit and enters protected mode.
Interrupt to level 0 procedure – If an interrupt goes to a privilege level 0 code, VM bit is
cleared and CPU goes back to protected mode.
5.14 Difference between Real, Protected and Virtual 8086 Modes
Feature Real Mode Protected Mode Virtual 8086 Mode (V86)
Addressing 20-bit 32-bit 20-bit
Memory Access Up to 1 MB Up to 4 GB Up to 1 MB
Protection No protection Full protection Protection using paging
Multitasking Not supported Supported Supported using tasks
Paging Not available Available Available
Modern OS and Running DOS programs
Used For Old DOS programs
applications under OS
Similar to Real Mode (in a
Speed Fast but unsafe Slower but secure
VM)
Runs at level 3 (user
Privilege Levels No privilege levels 4 levels (0 to 3)
mode)
Switching Needs Protected Mode
No Yes (to enter)
Required? to enter
Handled through
Interrupt Handling Simple Advanced
Protected Mode
EFLAGS VM Bit Not used Used only in switching Set to 1
Used by modern OS Used to run DOS in
System Use Early systems (DOS)
(Windows/Linux) modern OS

Unit 6 : Interrupts, Exceptions and Introduction to Micro-controllers

6.1 Types of Exceptions


1. Faults
Faults are detected before or during instruction execution.
If detected during execution, the processor goes back to the state before the instruction.
So, the instruction can be restarted after solving the issue.
Example: Page fault.
2. Traps
Traps are detected after the instruction is completed.
Used for debugging or system calls.
The instruction cannot be restarted, but the program continues.
Example: Breakpoint.
3. Aborts
Aborts are for serious errors.
The processor cannot find the exact instruction causing the error.
The program cannot be restarted.
Example: Memory or hardware failure.

6.2 Process of Handling Interrupts


Interrupt Occurs:
When an interrupt occurs, the Interrupt ID (vector number) is used to locate the Interrupt
Gate or Trap Gate in the IDT (Interrupt Descriptor Table).
Accessing Descriptor:
The gate descriptor (in IDT) provides two important values:
Offset – location of entry point (ISR) in the code.
Selector – used to locate Segment Descriptor in LDT (Local Descriptor Table) or GDT (Global
Descriptor Table).
Segment Descriptor:
The Segment Descriptor gives the Base address of the Executable Segment (code segment)
that contains the ISR (Interrupt Service Routine).
Final ISR Address:
The Base (from segment descriptor) + Offset (from gate descriptor) gives the exact address of
the Entry Point of the ISR.
Execution:
The processor now jumps to the ISR and executes the interrupt service routine.
IDTR Role:
The base address and size of the IDT is stored in IDTR (Interrupt Descriptor Table Register).
LIDT and SIDT instructions are used to load and store the IDT info.

6.3 Enabling and Disabling Interrupts


1. Interrupt Flag (IF) in EFLAGS Register:
The IF (Interrupt Flag) bit in the EFLAGS register controls whether the CPU will respond to
maskable interrupts (INTR).
If IF = 1, interrupts are enabled.
If IF = 0, interrupts are disabled.

2. Enabling Interrupts:
The STI (Set Interrupt Flag) instruction is used.
It sets the IF bit to 1.
After execution, the CPU can accept maskable hardware interrupts.

3. Disabling Interrupts:
The CLI (Clear Interrupt Flag) instruction is used.
It clears the IF bit (sets it to 0).
After execution, the CPU ignores all maskable hardware interrupts.
NMI (Non-Maskable Interrupts) cannot be disabled using CLI.

6.4 Exceptions
i) Divide Error:
Cause: This exception occurs when there is an error during a division operation.
Example: If the program tries to divide by zero or the result of a division is too large for the
processor to handle.
ii) Invalid Op Code:
Cause: This occurs when the processor encounters an unknown or invalid instruction in the
program.
Example: If the program tries to execute an instruction that is not recognized by the CPU.
iii) Overflow:
Cause: An overflow exception happens when a result of a mathematical operation exceeds the
range that can be represented by the data type.
Example: If a result of addition or multiplication is too large for the given number of bits to
handle.
iv) Stack Fault:
Cause: A stack fault happens when there is an error related to stack operations, such as
accessing memory outside the valid stack region or exceeding stack space.
Example: Trying to push too many items onto the stack or accessing an invalid address.
v) Debug Exception:
Cause: This exception occurs when the CPU detects a condition for debugging, usually when a
debug breakpoint is hit or there is a specific condition.
Example: When a program runs under a debugger, and a breakpoint is triggered to pause the
execution for inspection.
vi) Breakpoint Exception:
Cause: This exception occurs when a breakpoint instruction is encountered in the program.
Example: A breakpoint instruction is inserted intentionally in the code during debugging to
pause execution at a certain point.

6.5 Interrupt Descriptor Table


In protection mode, every interrupt or exception has a special entry called a descriptor. This
descriptor tells the system which routine (code) to use when handling the interrupt or
exception. All these descriptors are stored in a special table called the Interrupt Descriptor
Table (IDT), which can be placed anywhere in the memory.
The IDT is like a list of 8 descriptors. The address and size of this list are stored in a special
register called the Interrupt Descriptor Table Register (IDTR).
To load or save the information in the IDTR, two commands are used: LIDT (Load IDT) and SIDT
(Store IDT).
The IDT can have up to 256 descriptors because there are 256 possible identifiers.
There are three types of descriptors:
Trap Gate Descriptor
Interrupt Gate Descriptor
Task Gate Descriptor
If any unknown type of descriptor is found in the IDT when an exception occurs, the processor
will create a general protection fault.

6.6 Types of descriptors in IDT


Trap Gate Descriptor:
It helps the CPU handle software errors. When something goes wrong, it stops and runs a
specific routine to fix it.
Interrupt Gate Descriptor:
It helps the CPU handle hardware signals, like when you press a key. It stops the current task
to process the hardware interrupt.
Task Gate Descriptor:
It allows the CPU to switch between tasks. It saves the current task and starts a new one.

6.7 Trap Gate vs Interrupt Gate


Point Trap Gate Interrupt Gate
1. Purpose Handles software interrupts. Handles hardware interrupts.
Triggered by software or program Triggered by hardware devices like
2. Trigger
issues. keyboard.
Used to handle signals from
3. Usage Used to handle software exceptions.
hardware.
Allows the program to continue Stops the program to handle
4. Execution
after handling. hardware events.
5. Type of Interrupt Software-generated interrupts. Hardware-generated interrupts.
Saves program state, then returns
6. CPU Behavior Saves program state and continues.
after handling.
Handling division by zero or memory
7. Example Keyboard input or mouse click.
access errors.
Points to a hardware interrupt
8. Entry Point Points to a software service routine.
handler.
A type of interrupt gate used for A type of interrupt gate used for
9. Gate Type
software. hardware.
Often lower priority than hardware Has higher priority than regular
10. Priority
interrupts. tasks.

6.8 8051 microcontroller features


8-bit Processor: It processes 8 bits of data at once, making it easy to work with small data.
4KB ROM: It has 4KB of built-in memory to store your program.
128 Bytes RAM: It has 128 bytes of memory for temporary data storage while running
programs.
4 I/O Ports: It has 4 ports to connect to external devices like LEDs or switches.
16-bit Timer: It has two timers that help measure time or count events.
Serial Communication: It can send and receive data using serial communication, connecting
with other devices.
Bit-level Access: You can access individual bits in memory for specific control tasks.
Boolean Operations: It can perform simple logical operations like AND, OR, and NOT directly.
Clock Speed: It runs at a speed of 12 MHz, which determines how fast it works.
Interrupt System: It can respond to external events quickly by interrupting the current task.
Built-in Oscillator: It has a built-in clock, so no extra clock is needed for the microcontroller.
Low Power Consumption: It uses less power, making it good for battery-powered devices.

6.9 Applications of microcontrollers


Home Automation: Micro-controllers are used to control smart home devices like lights, fans,
and security systems remotely.
Robotics: They control the movement and functions of robots, like sensors, motors, and
cameras.
Automobile Systems: Micro-controllers are found in car systems like engine control units
(ECUs), airbags, and anti-lock braking systems (ABS).
Medical Devices: Used in devices like heart rate monitors, insulin pumps, and blood pressure
monitors for accurate and automated measurements.
Appliances: Micro-controllers manage the operation of household appliances such as washing
machines, microwaves, and refrigerators.
Toys: Many electronic toys use micro-controllers to control movements, sounds, and lights.
Industrial Automation: Micro-controllers control machines, assembly lines, and robotic arms
in factories to improve efficiency.
Wearable Devices: Smartwatches and fitness trackers use microcontrollers to monitor health
data like steps, heart rate, and sleep.
Consumer Electronics: They are used in TVs, cameras, and audio systems to control features
like volume, channel selection, and more.
Security Systems: Micro-controllers are used in alarm systems, surveillance cameras, and
access control devices to enhance safety.
Agriculture: They control automated irrigation systems, greenhouse environments, and
monitoring systems for crops.
Energy Meters: Micro-controllers are used to measure and display electricity or water usage
in energy meters.

6.10 Differentiate between Microprocessor and Microcontroller.


Point Microprocessor Microcontroller
A device that controls devices
1. Definition A device that processes data.
and systems.
Performs calculations and Controls devices and runs
2. Function
processing tasks. applications.
Has built-in memory (RAM,
3. Memory External memory is required.
ROM).
Lower processing power
4. Processing Power Higher processing power.
compared to microprocessors.
Includes CPU, memory, and
5. Components Only the processor (CPU).
peripherals.
Used in embedded systems like
6. Use Used in computers, laptops, etc.
toys, appliances, etc.
More complex, used for general
7. Complexity Simpler, used for specific tasks.
tasks.
Generally cheaper due to
8. Cost Generally more expensive.
integrated parts.
9. Power Consumption Higher power consumption. Lower power consumption.
Slower compared to
10. Speed Faster processing speed.
microprocessors.
11. Example Intel i7, AMD Ryzen. 8051, Arduino, PIC.
Used in embedded systems,
12. Application Used in desktops, laptops, servers.
consumer electronics, etc.

6.11 Architecture of a Typical Microcontroller


CPU (Central Processing Unit):
It is the brain of the microcontroller. It processes all data and controls other parts of the
microcontroller.
On-Chip ROM (Read Only Memory):
This stores the program code permanently. It does not lose data when power is off.
On-Chip RAM (Random Access Memory):
This is used to store temporary data while the program runs.
Interrupt Control:
Interrupts allow the CPU to pause the current task and execute important tasks immediately.
Timers/Counters (Timer 0 and Timer 1):
These are used for timing operations and counting external events.
Oscillator (OSC):
It provides the clock signal required to run the microcontroller. It connects to a crystal for
timing.
Bus Control:
It connects the CPU with memory and I/O devices. It controls the data flow inside the
microcontroller.
4 I/O Ports (P0, P1, P2, P3):
These are used to connect the microcontroller to external devices like LEDs, motors, sensors,
etc.
Serial Port (TXD and RXD):
It is used for communication with other devices like computers or other microcontrollers.

You might also like