CSC167 Microprocessor

MicroprocessorUnit 415 min read

8086 Architecture, Instructions & Programming: Segments, Registers, and Real Mode

Unit 4 of Microprocessor covers the 8086’s 16-bit architecture, segmented memory model, register organization, instruction set (data transfer, arithmetic, logic, control), and programming basics—with real-world ties to embedded systems, DOS-era apps, and modern x86 compatibility.

TAKEAWAYS:

  • The 8086 uses a segmented memory model (CS:IP, DS:SI/DI, SS:SP) to address 1 MB of memory via 16-bit registers and 20-bit physical addresses.
  • Registers are divided into general-purpose (AX, BX, CX, DX), pointer/index (SP, BP, SI, DI), and segment (CS, DS, SS, ES) registers, each with specific roles in addressing and operations.
  • Instructions are classified into 5 groups: data transfer, arithmetic, logic, control transfer, and string operations, with prefixes (e.g., REP, LOCK) for advanced use.
  • The instruction cycle involves fetching (M-cycle) and executing (T-states) instructions, with the 8086 using a 4-phase bus cycle (T1–T4) for memory/I/O access.
  • Real Mode (vs. Protected Mode) allows direct memory access but lacks hardware protection, used in legacy DOS and bootloaders.
  • Programming examples include stack operations (PUSH/POP), loop control (LOOP), and segmented addressing (e.g., loading data from [BX+SI]).

1. Architecture Overview: The 8086’s Core Design

The 8086 is an intel 16-bit microprocessor introduced in 1978, designed for personal computers. It introduced key innovations like segmented memory and a 16-bit ALU, laying the foundation for modern x86 processors. Unlike the 8085 (8-bit), the 8086 uses a 16-bit data bus and 20-bit address bus, allowing it to access 1 MB of memory (2²⁰ bytes).

Key Features:

  • 16-bit internal architecture but 20-bit external address bus (via multiplexing).
  • Two 8-bit ALUs working in parallel for efficiency.
  • 14 general-purpose registers (8-bit and 16-bit variants).
  • Segmented memory model (CS, DS, SS, ES registers).
  • Interrupt-driven I/O (via IN/OUT instructions or DMA).

Why Segmented Memory?

The 8086’s 16-bit registers cannot directly address 1 MB (2²⁰ bytes). Instead, it uses segment registers (CS, DS, SS, ES) to define 16-bit base addresses, combined with 16-bit offsets (e.g., BX, SI) to compute a 20-bit physical address:

Physical Address = (Segment Register × 16) + Offset

Example: If CS = 1000H and IP = 0100H, the physical address is:

1000H × 16 = 10000H
10000H + 0100H = 10100H (40 KB)

classDiagram
    class Registers {
        +AX, BX, CX, DX (16-bit)
        +AH, AL, BH, BL, etc. (8-bit halves)
        +SP, BP, SI, DI (Pointer/Index)
        +CS, DS, SS, ES (Segment)
        +IP (Instruction Pointer)
        +FLAGS (Status Register)
    }
    class Memory {
        +CS:IP (Code Segment)
        +DS:SI/DI (Data Segment)
        +SS:SP (Stack Segment)
        +ES (Extra Segment)
    }
    Registers --> Memory : "Addresses via Seg:Offset"

Caption: 8086 Register Organization and Segmented Memory Model


2. Registers: The 8086’s Workhorses

The 8086 has 14 registers, categorized as follows:

Type Registers Purpose
General-Purpose AX, BX, CX, DX Accumulator (AX), Base (BX), Counter (CX), Data (DX)
Pointer/Index SP, BP, SI, DI Stack Pointer (SP), Base Pointer (BP), Source/Index (SI/DI)
Segment CS, DS, SS, ES Code Segment (CS), Data Segment (DS), Stack Segment (SS), Extra Segment (ES)
Special IP, FLAGS Instruction Pointer (IP), Status Flags (FLAGS)

Key Registers Explained:

  1. AX (Accumulator):

    • Used in arithmetic/logic operations (e.g., ADD AX, BX).
    • Can be split into AH (high byte) and AL (low byte).
    • Example: MOV AL, 32H loads 32H into the low byte of AX.
  2. IP (Instruction Pointer):

    • Points to the next instruction in the Code Segment (CS).
    • Automatically increments after each instruction fetch.
  3. FLAGS Register:

    • 16-bit register storing status flags (e.g., CF for Carry, ZF for Zero, SF for Sign).
    • Used for conditional jumps (e.g., JZ jumps if ZF=1).
  4. Stack Pointer (SP) and Base Pointer (BP):

    • SP tracks the top of the stack in the Stack Segment (SS).
    • BP is used for accessing local variables in functions (e.g., [BP+2]).

REAL WORLD:

  • eSewa App (Nepal): When you pay a bill via eSewa, the backend server (often running on x86 processors) uses segmented memory to manage multiple user transactions simultaneously. The DS register might point to a segment storing user data, while CS points to the code handling payments. The stack (SS:SP) is used to save return addresses for nested function calls (e.g., validation → payment processing → confirmation).

  • Khalti’s Payment Gateway: Khalti’s servers use 8086-like segmented addressing (in modern x86-64 mode) to isolate different services (authentication, transaction logging, fraud detection). The ES segment might hold encrypted transaction data, while DS holds decrypted user inputs.

  • Pathao’s Ride Allocation: Pathao’s backend uses bitwise logic operations (e.g., AND, OR) to manage driver availability flags. For example:

    MOV AL, [DriverStatus]  ; Load driver's status (bitmask)
    AND AL, 00000010B       ; Check if driver is "available" (bit 1 set)
    JZ  NotAvailable        ; Jump if zero (not available)
    

3. Instruction Set: The 8086’s Command Language

The 8086 instruction set is divided into 5 categories:

A. Data Transfer Instructions

Move data between registers, memory, and I/O.

  • MOV: Move data (e.g., MOV AX, BX).
  • PUSH/POP: Stack operations (e.g., PUSH AX saves AX to stack; POP BX restores to BX).
  • XCHG: Exchange registers (e.g., XCHG AX, BX).
  • LEA: Load Effective Address (e.g., LEA BX, [SI+DI]).

Example: Stack Operations

MOV AX, 1234H    ; Load AX with 1234H
PUSH AX          ; Push AX onto stack (SS:SP decremented by 2)
POP BX           ; Pop from stack into BX

Trace:

  1. Before PUSH AX: SP = 0FFEH, [SS:0FFE] = ?, [SS:0FFF] = ?
  2. After PUSH AX: SP = 0FFCH, [SS:0FFCH] = 34H, [SS:0FFDH] = 12H
  3. After POP BX: BX = 1234H, SP = 0FFEH

sequenceDiagram
    participant CPU
    participant Stack
    CPU->>Stack: PUSH AX (SP--; [SS:SP] = AX)
    Stack-->>CPU: Stack grows downward
    CPU->>Stack: POP BX (BX = [SS:SP]; SP++)

Caption: Stack Operations in 8086 (PUSH/POP)


B. Arithmetic Instructions

Perform math operations.

  • ADD, SUB, INC, DEC: Basic arithmetic.
  • MUL, DIV, IMUL, IDIV: Multiplication/division (unsigned/signed).
  • CMP: Compare two values (sets flags).

Example: Loan Interest Calculation (Nepal Bank Scenario) A bank calculates monthly interest on a loan using the formula:

Interest = Principal × Rate × Time / 100

In 8086 assembly:

MOV AX, Principal   ; AX = 100000 (1 lakh)
MOV BX, 10          ; BX = 10% rate
MUL BX              ; AX = AX × BX = 1000000 (overflows!)
; Use 32-bit multiplication (DX:AX)
MOV AX, Principal
MOV BX, Rate
MOV CX, Time
IMUL BX             ; AX = AX × BX (signed)
IMUL CX             ; DX:AX = AX × CX
MOV BX, 100
IDIV BX             ; AX = (DX:AX) / 100 (quotient)

Note: The 8086 lacks native 32-bit ops, so we use DX:AX for large numbers.


C. Logic Instructions

Bitwise operations.

  • AND, OR, XOR, NOT: Logical operations.
  • TEST: Combine AND with CMP (sets flags but discards result).

Example: Daraz Order Status Flags Daraz might use bitmask flags to track order status:

MOV AL, OrderStatus ; AL = 00001101B (Paid + Shipped)
AND AL, 00000010B   ; Check if "Shipped" bit (bit 1) is set
JZ NotShipped       ; Jump if not shipped

Flags:

  • Bit 0: 00000001B = Paid
  • Bit 1: 00000010B = Shipped
  • Bit 2: 00000100B = Delivered

D. Control Transfer Instructions

Change program flow.

  • JMP: Unconditional jump.
  • CALL/RET: Function calls.
  • LOOP: Loop control (e.g., LOOP Label decrements CX and jumps if CX ≠ 0).
  • Conditional jumps: JZ, JNZ, JC, JNC, etc.

Example: Traffic Light Control (Kathmandu Roads) A traffic light controller might use a loop to cycle through states:

MOV CX, 3          ; 3 states: Red, Yellow, Green
RedLight:
    ; Turn on red light
    LOOP GreenLight ; Decrement CX; jump if CX ≠ 0
GreenLight:
    ; Turn on green light
    JMP RedLight     ; Repeat

stateDiagram-v2
    [*] --> RedLight
    RedLight --> YellowLight : "After 30 sec"
    YellowLight --> GreenLight : "After 5 sec"
    GreenLight --> RedLight : "After 45 sec"

Caption: Traffic Light State Machine (8086 Assembly)


E. String Instructions

Process arrays/strings.

  • MOVSB, CMPSB, SCASB: Move, compare, scan bytes.
  • Prefixes:
    • REP: Repeat until CX=0 (e.g., REP MOVSB copies CX bytes).
    • REPE/REPNE: Repeat while equal/not equal.

Example: Copying a String (eSewa User Data)

LEA SI, SourceString   ; SI = address of source
LEA DI, DestString     ; DI = address of destination
MOV CX, 20             ; Copy 20 bytes
CLD                    ; Clear direction flag (auto-increment SI/DI)
REP MOVSB              ; Repeat MOVSB CX times

4. Instruction Cycle and Timing

The 8086 executes instructions in machine cycles, each divided into T-states (clock cycles). A typical instruction cycle involves:

  1. Fetch Cycle (M-cycle):

    • T1: Address sent on bus (multiplexed with AD0–AD7).
    • T2: Memory/I/O responds with data.
    • T3: Data latched into CPU.
    • T4: Next cycle begins.
  2. Execution Cycle (T-states):

    • Decode and execute the instruction.

Example: Timing Diagram for MVI A, 32H (8085-style, but concept applies) (Note: The 8086 uses a 4-phase bus cycle, but the 8085’s 5-phase cycle is often taught for comparison.)


Caption: Simplified 8086 Fetch Cycle (4-Phase Bus)


5. Real Mode vs. Protected Mode (Brief Introduction)

The 8086 operates in Real Mode, where:

  • No memory protection: Any process can access any memory.
  • 20-bit addressing: Limited to 1 MB.
  • No privilege levels: All code runs at ring 0.

Later x86 processors (80286+) added Protected Mode, enabling:

  • Memory segmentation with limits (prevents overwrites).
  • Privilege levels (ring 0–3 for OS/kernel vs. apps).
  • Virtual memory (paging).

Example: Why Real Mode is Used in Bootloaders When a PC boots, the BIOS loads the MBR (Master Boot Record) into memory and jumps to it in Real Mode because:

  1. The BIOS itself runs in Real Mode.
  2. Protected Mode requires enabling via LGDT and LMSW instructions, which are complex for early boot.

6. Programming Example: Factorial Calculation

Problem: Compute 5! (120) using 8086 assembly. Approach: Use a loop with CX as counter and AX as accumulator.

MOV AX, 1          ; Initialize result (AX = 1)
MOV CX, 5          ; Compute 5!
FactorialLoop:
    MUL CX          ; AX = AX × CX
    LOOP FactorialLoop

Trace:

Step AX (Result) CX (Counter) Action
1 1 5 Start
2 5 (1×5) 4 MUL 5; LOOP
3 20 (5×4) 3 MUL 4; LOOP
4 60 (20×3) 2 MUL 3; LOOP
5 120 (60×2) 1 MUL 2; LOOP
6 120 0 LOOP ends (CX=0)

REAL WORLD:

  • NTC’s Billing System: NTC’s billing software (running on legacy x86 servers) might use factorial-like loops to calculate complex tariffs (e.g., volume discounts). For example:
    MOV AX, 1        ; Base unit cost
    MOV CX, 100      ; 100 units purchased
    MOV BX, 10       ; Discount threshold
    CMP CX, BX
    JL NoDiscount     ; Jump if CX < BX
    ; Apply 10% discount (multiply by 0.9)
    MOV DX, 0        ; Clear upper 16 bits
    MOV AX, 90       ; 90% of cost (AX = AX × 90/100)
    IMUL CX          ; AX = AX × CX (total cost)
    JMP EndCalc
    NoDiscount:
        IMUL CX      ; AX = AX × CX (no discount)
    EndCalc:
    

7. Common Pitfalls and Best Practices

  1. Segment Overlap:

    • Ensure segments do not overlap unintentionally (e.g., CS and DS pointing to the same memory).
    • Fix: Use ORG directives in assemblers to define segment offsets.
  2. Stack Overflow:

    • The stack grows downward. If SP underflows (points to invalid memory), the program crashes.
    • Fix: Initialize SP to a high memory address (e.g., MOV SP, 0FFFFH).
  3. Flag Dependence:

    • Instructions like CMP set flags but discard results. Always check flags after comparisons.
    • Example:
      CMP AX, BX      ; Sets flags but AX unchanged
      JE Equal        ; Jump if AX == BX
      
  4. 16-bit Limitations:

    • The 8086 cannot directly address >1 MB. Use far jumps (JMP FAR) for inter-segment jumps.
    • Example:
      JMP FAR PTR NewSegment:NewOffset
      

In the Real World

  1. WhatsApp (Signal Protocol):

    • WhatsApp’s encryption uses bitwise XOR operations (similar to XOR in 8086) for symmetric key derivation. For example, when you send a message, the client and server perform:
      Key = SharedSecret XOR Nonce
      
      This is analogous to:
      MOV AL, SharedSecret
      XOR AL, Nonce
      
  2. Google’s Data Centers (x86 Servers):

    • Modern x86 servers (descendants of the 8086) use segmented addressing in legacy compatibility modes. For example:
      • A web server might load HTML pages from DS:SI (data segment) while executing code from CS:IP.
      • The stack (SS:SP) is used for recursive function calls in handling thousands of HTTP requests.
  3. Nepal Rastra Bank’s Core Banking System:

    • The bank’s mainframe uses 8086-style assembly (or emulated environments) for critical transactions like:
      • Loan amortization schedules (using LOOP and arithmetic ops).
      • Fraud detection (bitmask checks with AND/TEST).
      • Audit logs (stack-based function call tracking).

Exam Tip

  1. Draw the Block Diagram:

    • Always draw the 8086’s internal architecture (EU, BU, BIU) and register organization in exams. Label:
      • EU (Execution Unit): ALU, FLAGS, general registers.
      • BU (Bus Unit): Address multiplexer, data bus.
      • BIU (Bus Interface Unit): Instruction queue, segment registers.
  2. Segmented Addressing is Key:

    • Questions often ask for physical address calculations. Practice:
      Given: CS = 2000H, IP = 0050H → Physical Address = ?
      Answer: 2000H × 16 = 20000H; 20000H + 0050H = 20050H
      
  3. Instruction Cycle vs. Machine Cycle:

    • Instruction Cycle: Time to fetch and execute one instruction.
    • Machine Cycle: One bus operation (e.g., memory read/write). An instruction may require multiple machine cycles.
  4. PUSH/POP and Stack:

    • PUSH decrements SP by 2 (for 16-bit data) before storing.
    • POP reads from [SS:SP] and increments SP by 2.
    • Example Question: "If SP = 0FFEH before PUSH AX and AX = 1234H, what is [SS:0FFCH] after the push?" Answer: 34H (low byte of AX).
  5. Real Mode vs. Protected Mode:

    • Real Mode: No protection, 1 MB limit (used in DOS, bootloaders).
    • Protected Mode: Segmentation with limits, privilege levels (used in OS kernels).
    • Exam Trick: The 80286 introduced Protected Mode; the 8086 only has Real Mode.
  6. Common Exam Questions:

    • Trace an instruction (e.g., MOV AX, [BX+SI]).
    • Explain the role of CS:IP (code segment and instruction pointer).
    • Difference between JMP and CALL (CALL pushes return address; JMP does not).
    • Why is the 8086 address bus multiplexed? Answer: To reduce pin count (AD0–AD7 are reused for data).

8086 microprocessor block diagram**Internal architecture of the 8086 showing EU, BU, and BIU (Image: Harkonnen2, CC BY-SA 3.0, via Wikimedia Commons)

Based on the TU BSc CSIT syllabus for Microprocessor (CSC167), unit 4.

Discussion

Loading…