Operating Systems and Internetworking Study Guide

Fundamentals of Operating Systems and Computer Organization

  • Operating System Definition and Roles:

    • An Operating System (OS) is core system software that manages computer hardware resources, controls execution, arbitrates resource contention, and provides common services for application programs.

    • It operates as an Extended Machine (virtual machine): abstracts messy low-level hardware details (such as reading and writing disk controller registers, servicing interrupts, and bus timing) into clean, high-level, uniform abstractions such as files, processes, and virtual address spaces.

    • It operates as a Resource Manager: multiprogramming systems execute multiple concurrent tasks that compete for the CPU, physical memory, and I/O devices; the OS arbitrates these competing requests systematically, safely, and equitably.

    • The OS is distinct from the desktop environment or Graphical User Interface (GUI), which runs as application-level software in user space.

  • Processor Execution Modes and Hardware Privilege:

    • Typical microprocessors feature hardware-enforced execution privileges controlled by flags in internal registers, traditionally termed the Program Status Word (PSW) or Processor State Register (PSR) (e.g., bit 00 of Control Register CR0CR0 on modern x86 architectures).

    • User Mode (Protected Mode): Application programs execute under restricted hardware privileges. Direct execution of privileged machine instructions (such as IN, OUT, hardware status register alterations, and interrupt descriptor table manipulation) is strictly prohibited by hardware logic.

    • Kernel Mode (Supervisor Mode / Protected Mode): The OS kernel executes with unrestricted hardware access, enabling direct execution of all machine instructions, raw memory address manipulation, and direct hardware peripheral I/O.

    • Any application-level request for physical I/O or low-level resource management must be mediated by the operating system kernel.

Operating system layers and execution modes
  • Central Processing Unit (CPU) Hardware Components:

    • Control Unit (CU): Fetches instructions from memory, decodes opcodes and operands, and coordinates datapaths by asserting control lines (multiplexers) across internal functional units.

    • Arithmetic Logic Unit (ALU): Carries out arithmetic operations (addition, subtraction, multiplication) and logical bitwise operations (AND, OR, NOR, bit-shifts).

    • Registers: Miniature, ultra-fast memory units situated directly inside the CPU die that hold operands, addresses, and execution state.

      • Access latency is less than a single clock cycle (substantially faster than level-1 caches or external dynamic RAM).

      • Common registers include the Program Counter (PC) (stores the memory address of the next instruction to fetch), the Instruction Register (IR) (holds the instruction currently being decoded), the Memory Address Register (MAR) (holds the memory address referenced by an access operation), the Memory Buffer Register (MBR) (stores data read from or written to memory), and the Processor State Register (PSR) (tracks condition flags and execution mode).

    • General-Purpose Registers (GPRs): Fast working memory used by machine instructions for intermediate arithmetic and data movement.

      • x86 architectures provide a limited set of GPRs (e.g., EAX as the accumulator for arithmetic and multiplication; EBX as the base register for memory addressing; ECX as the counter for loops; EDX for multiply/divide operations; ESI and EDI as source/destination index registers; EBP as the stack base pointer; ESP as the stack pointer).

CPU internal organization and datapath
  • Interrupts and Interrupt Handling:

    • An interrupt is an asynchronous electrical signal asserted by an I/O device controller to capture the CPU's attention when data is ready or an operation completes.

    • Upon receipt of an interrupt signal, the CPU completes its current instruction, suspends the executing program, saves machine registers, and switches into kernel mode.

    • The CPU uses the Interrupt Request (IRQ) number to index into the Interrupt Descriptor Table (IDT) (loaded at boot time via instructions like LIDT on x86) and jumps to the address of the corresponding kernel Interrupt Handler.

    • Interrupt handlers constitute the reactive engine of the operating system: all process scheduling, I/O handling, and system call dispatches originate via interrupts or software traps.

Processor Architectures: RISC versus CISC

  • Instruction Set Architecture (ISA):

    • The ISA provides the logical boundary and operational interface between software and hardware. It defines the machine code instructions, addressing modes, registers, memory models, and exception mechanisms available to programmers and compilers.

  • Comparison of Architectural Paradigms:

    • Reduced Instruction Set Computer (RISC):

      • Instruction Length and Encoding: Uniform, fixed instruction lengths (exactly 4 bytes4\,\text{bytes} or 32 bits32\,\text{bits} in MIPS-32 and standard ARM), formatted into a small set of consistent bit-fields.

      • Register Architecture: Large register files containing numerous general-purpose registers (3232 registers in MIPS and standard 64-bit ARM architectures).

      • Memory Architecture: Pure Load/Store architecture. Arithmetic and logical instructions operate exclusively on registers; no arithmetic instruction can reference memory directly.

      • Addressing Modes: Small set of simple addressing modes (typically base register plus immediate offset).

      • Design Philosophy: Prioritizes simple, single-cycle instructions that can be easily pipelined. Compilers optimize code by keeping intermediate values inside the extensive register set.

    • Complex Instruction Set Computer (CISC):

      • Instruction Length and Encoding: Highly variable instruction lengths (1 byte1\,\text{byte} to 15+ bytes15+\,\text{bytes} on x86) with complex, irregular encodings.

      • Register Architecture: Small set of specialized or general-purpose registers (≈4\approx 4 to 88 legacy GPRs on classic x86 architectures).

      • Memory Architecture: Memory-to-register and memory-to-memory operations. Single instructions (such as ADD [EBX], EAX) can read operands from memory, perform arithmetic, and write results back to memory.

      • Addressing Modes: Wide variety of complex, specialized addressing modes.

      • Design Philosophy: Emphasizes dense machine code, implementing high-level operations directly in hardware to minimize program binary size at the expense of decode and pipeline complexity.

  • CISC Translation in Modern Processors:

    • High-performance CISC processors (such as the Intel Pentium, Intel Core series, and AMD x86 implementations like Barcelona) are internally hybrid engines: front-end hardware decodes complex x86 machine instructions into a stream of simpler, uniform, internal RISC-like micro-operations (μops\mu\text{ops}), which are then executed by an out-of-order pipelined execution core.

The MIPS Architecture, Instruction Formats, and Datapaths

  • MIPS Register Structure and Conventions:

    • MIPS architectures provide 3232 general-purpose registers, each 32 bits32\,\text{bits} (1 word1\,\text{word}) wide. Because 32=2532 = 2^5, exactly 5 bits5\,\text{bits} are required to index any register within an instruction.

    • By convention, software tools and assembly programmers adhere to the following assignments:

      • $zero (Register 00): Constant hardwired value of 00.

      • $at (Register 11): Reserved for the assembler.

      • $v0 - $v1 (Registers 2−32 - 3): Values for expression evaluation and function returns.

      • $a0 - $a3 (Registers 4−74 - 7): Function argument passing.

      • $t0 - $t7 (Registers 8−158 - 15): Temporary registers (caller-saved; not preserved across calls).

      • $s0 - $s7 (Registers 16−2316 - 23): Saved registers (callee-saved; preserved across calls).

      • $t8 - $t9 (Registers 24−2524 - 25): Additional temporary registers.

      • $k0 - $k1 (Registers 26−2726 - 27): Reserved for the operating system kernel.

      • $gp (Register 2828): Global Pointer (points to static data).

      • $sp (Register 2929): Stack Pointer (points to the top of the stack).

      • $fp (Register 3030): Frame Pointer (points to the base of the current stack frame).

      • $ra (Register 3131): Return Address (stores return address from subroutine calls).

MIPS register names and conventions
  • Instruction Formats:

    • R-Format (Register/Arithmetic): Used for register-to-register arithmetic and logical operations.

      • op (bits 31−2631 - 26, 6 bits6\,\text{bits}): Opcode (always 00 for standard R-format).

      • rs (bits 25−2125 - 21, 5 bits5\,\text{bits}): First source register.

      • rt (bits 20−1620 - 16, 5 bits5\,\text{bits}): Second source register.

      • rd (bits 15−1115 - 11, 5 bits5\,\text{bits}): Destination register that receives the result.

      • shamt (bits 10−610 - 6, 5 bits5\,\text{bits}): Shift amount (used in shift instructions, otherwise 00).

      • funct (bits 5−05 - 0, 6 bits6\,\text{bits}): Specific function code that dictates the operation (e.g., addition, subtraction).

    • I-Format (Immediate / Memory Access / Conditional Branch): Used for instructions with immediate operands, loads, stores, and branches.

      • op (bits 31−2631 - 26, 6 bits6\,\text{bits}): Opcode defining instruction type.

      • rs (bits 25−2125 - 21, 5 bits5\,\text{bits}): Source/base register.

      • rt (bits 20−1620 - 16, 5 bits5\,\text{bits}): Destination register (for load/immediate) or second comparison register (for branch).

      • immed / address offset (bits 15−015 - 0, 16 bits16\,\text{bits}): Immediate numeric constant or memory address offset.

    • J-Format (Unconditional Jump):

      • op (bits 31−2631 - 26, 6 bits6\,\text{bits}): Opcode.

      • target (bits 25−025 - 0, 26 bits26\,\text{bits}): Jump target address.

  • Datapaths for Core Instructions:

    • Register Addition (add $t0, $s1, $s2):

      • The PC outputs the instruction address to Instruction Memory, retrieving the 32 bit32\,\text{bit} instruction word.

      • Bits 25−2125 - 21 ($s1) and 20−1620 - 16 ($s2) select the read registers from the Register File, outputting their contents to the ALU.

      • Bits 5−05 - 0 (funct) direct the ALU Control to configure the ALU for addition.

      • The ALU computes the sum s1+s2s1 + s2 and routes the result directly back to the Register File, writing into register $t0 (indexed by bits 15−1115 - 11, rd).

    • Load Word (lw s1,20(s1, 20(s2)):

      • The PC fetches the I-format instruction from Instruction Memory.

      • Bits 25−2125 - 21 ($s2) index the Register File to retrieve the base memory address.

      • Bits 15−015 - 0 (immediate value 2020) are sign-extended to 32 bits32\,\text{bits} and routed to the second ALU input.

      • The ALU adds the base address and offset (s2+20s2 + 20), outputting the computed effective physical/virtual address to Data Memory.

      • Data Memory reads the 32 bit32\,\text{bit} word at that address, routing it to the Register File, which writes it into $s1 (indexed by bits 20−1620 - 16, rt).

Memory offset addressing in load word
  • Branch On Equal (beq $s1, $s2, -12):

    • The PC fetches the instruction from Instruction Memory.

    • Concurrently, a dedicated adder calculates the sequential next instruction address: PC+4\text{PC} + 4.

    • Bits 25−2125 - 21 ($s1) and 20−1620 - 16 ($s2) feed register operands to the ALU, which performs subtraction (s1−s2s1 - s2).

    • Simultaneously, the branch offset (bits 15−015 - 0, value −12-12) is sign-extended, shifted left by 2 bits2\,\text{bits} (×4\times 4 bytes), and added to PC+4\text{PC} + 4 in an auxiliary branch adder.

    • If the ALU result is zero (indicating s1==s2s1 == s2), the ALU Zero line is asserted, prompting the control multiplexer to load the branch target address into the PC; otherwise, the PC advances to PC+4\text{PC} + 4.

Pipelining, Instruction-Level Parallelism, and Processor Scaling

  • Principles of Pipelining:

    • Pipelining implements Instruction-Level Parallelism (ILP) by dividing instruction execution into consecutive functional stages arranged like an industrial assembly line.

    • The Laundry Analogy: Washing, drying, and folding loads sequentially takes substantial time per load. Overlapping these tasks (washing the second load while the first load is in the dryer and the zeroth load is being folded) increases total system throughput without reducing the latency required to launder an individual load.

Laundry production line pipeline analogy
  • Classic 5-Stage RISC Pipeline:

    • 1. IF (Instruction Fetch): Fetches the instruction word from the instruction cache using the PC and increments the PC.

    • 2. ID (Instruction Decode & Register Read): Decodes the instruction opcode and reads source operand values from the register file.

    • 3. EX (Execute / Address Calculation): Performs ALU calculations, effective memory address computations, or branch condition evaluations.

    • 4. MEM (Memory Access): Reads from or writes to the data cache for load and store instructions.

    • 5. WB (Write Back): Writes the computed result or loaded memory value back into the destination register.

    • Clocking and Resource Sharing: Each stage occupies exactly one clock cycle. The Register File is accessed by both ID (reading) and WB (writing); this structural conflict is resolved by having WB write in the first half of the clock cycle and ID read in the second half.

    • Performance Speedup: Under ideal conditions, a pipeline of depth k=5k = 5 stages completes one instruction per clock cycle in steady state, yielding a theoretical speedup approaching 5×5\times over unpipelined serial execution (4−54 - 5 cycles per instruction).

  • Multiple Issue and Superscalar Processors:

    • Multiple Issue: Expands ILP beyond one instruction per cycle by fetching, decoding, and issuing multiple instructions concurrently, requiring replicated execution units (e.g., separate integer ALUs, multipliers, floating-point units, and load/store units).

    • Static Multiple Issue (VLIW / Itanium): Compilers bundle conflict-free, independent instructions into long instruction words in advance of runtime.

    • Superscalar Processors: Processors dynamically detect data dependencies and schedule multiple instructions across parallel functional units at execution time (e.g., Intel Pentium, AMD processors).

    • Dynamic Out-of-Order Execution Architecture:

      • In-Order Fetch and Decode: Instructions are fetched sequentially and placed into internal instruction buffers.

      • Reservation Stations: Instructions wait in reservation stations until their source operands become available.

      • Out-of-Order Execution: As soon as operands are ready, instructions dispatch to free functional units, executing out of original program order.

      • Commit Unit (Reorder Buffer): Ensures precise architectural exceptions and logical program order by retiring completed instructions in strict in-order program sequence.

Superscalar pipeline datapath with out of order execute
  • Limits of ILP and the Multi-Core Transition:

    • Historically, exponential improvements in processor throughput were sustained by increasing clock frequencies and deepening execution pipelines.

    • Around 2005, clock speed scaling stalled at approximately 3.5 GHz3.5\,\text{GHz} due to the Power Wall and the breakdown of Dennard Scaling (dynamic power density escalated disproportionately with frequency, creating unsustainable heat dissipation and cooling limitations).

    • While transistor density continues to increase (Moore's Law), manufacturers shifted from higher clock rates on monolithic single cores to integrating multiple independent processing cores on a single semiconductor die.

Historical microprocessor performance scaling trends
  • Multi-Core versus Many-Core Systems:

    • Multi-Core Processors (e.g., Intel Core i7/i9, Xeon, AMD Ryzen):

      • Core Count: Small number of cores (typically 22 to 6464 cores).

      • Core Architecture: Highly complex, powerful, out-of-order execution pipelines with large hierarchical L1/L2/L3 caches optimized for low single-thread latency and diverse workloads.

      • Memory Architecture: Centralized shared memory model with hardware-managed cache coherence circuitry.

      • Programming Model: Executes standard multi-threaded and single-threaded software transparently.

    • Many-Core Processors (e.g., Graphics Processing Units - GPUs):

      • Core Count: Massive core arrays containing hundreds to thousands of smaller processing elements.

      • Core Architecture: Extremely simple, power-efficient, in-order pipelines designed to optimize aggregate computational throughput over single-thread execution latency.

      • Memory Architecture: Distributed or banked memory hierarchies relying heavily on streaming execution models.

      • Programming Model: Requires specialized, massively parallel data-parallel programming paradigms (e.g., CUDA, OpenCL) targeting tasks that break down into thousands of simultaneous threads (such as AI/ML matrix computations and graphics processing).

Comparison of CPU versus GPU silicon die architectures

Process Management, Scheduling, and System Calls

  • Process Concept and Memory Structure:

    • A program is a passive, static sequence of instructions stored on secondary media (disk).

    • A process is an active, executing instance of a program, encompassing the program counter, CPU registers, stack, and a dedicated virtual address space.

    • Logical Memory Layout: A process address space is partitioned into:

      • Text Section: Read-only segment containing compiled machine code instructions.

      • Data Section: Stores global and static variables initialized at load time.

      • Heap: Dynamically allocated memory space managed at runtime (e.g., via malloc() or new).

      • Stack: Dynamic memory containing temporary activation records (subroutine parameters, return addresses, and local automatic variables).

  • Process Control Block (PCB):

    • The OS kernel maintains a table of PCBs in protected memory to represent every process. The PCB tracks:

      • Process Management: Hardware register snapshots, Program Counter (PC), Program Status Word (PSW), Stack Pointer (SP), Process ID (PID), Parent Process ID (PPID), Process Group, User ID, priority, scheduling parameters, signals, and accounting timers.

      • Memory Management: Base pointers to text, data, and stack segments, as well as page tables.

      • File Management: Root directory, current working directory, and file descriptor tables.

Process control block data structure layout
  • Process States and State Transitions:

    • New: The process is currently being allocated and initialized by the operating system.

    • Ready: The process resides in main memory, possessing all necessary resources, waiting in the ready queue to be allocated a CPU time slice.

    • Running: Process instructions are actively executing on a physical CPU core.

    • Blocked / Waiting: The process cannot execute until an external event completes (such as I/O data availability, a semaphore signal, or timer expiration).

    • Terminated: The process has completed execution; execution state is retained until retrieved by a parent process.

Five-state process lifecycle transition model
  • Multitasking, Context Switching, and Scheduling:

    • Multitasking shares a single physical CPU core among multiple active processes via rapid Time-Sharing.

    • Each process runs for a maximum time slice called a quantum (typically ≈10 ms\approx 10\,\text{ms}).

    • Context Switch Mechanism: Triggered by a timer interrupt or a blocking system call. The CPU switches to kernel mode, stores the hardware registers into the running process's PCB, enqueues the PCB, executes the scheduler algorithm to select the next ready process, loads that process's registers from its PCB into the CPU hardware, switches to user mode, and branches to its saved Program Counter.

    • The Dispatcher is the low-level operating system module responsible for performing the register swapping, mode switching, and jump operations involved in context switching.

Process scheduling and context switching workflow
  • System Call Execution Flow:

    • User programs invoke operating system services using system calls, which appear syntactically as standard function calls in high-level programming languages.

    • Because user-mode applications cannot modify privileged processor registers directly, the user-space wrapper executes a specialized software interrupt or trap (such as INT SYSVEC on x86 architectures).

    • The trap triggers a hardware transition to kernel mode and indexes into the Interrupt Vector Table to execute the kernel system call handler, which inspects arguments, executes privileged hardware operations, and returns results to user space.

Comparison table of core UNIX and Win32 system calls

Concurrency, Synchronization, and Mutual Exclusion

  • Concurrency, Threads, and Non-Determinism:

    • A thread is an independent stream of instructions executing within a process. Threads within the same process share their virtual address space, heap, open files, and global data, but maintain independent Program Counters, register sets, and private stacks.

    • In concurrent execution, instruction streams from different threads interleave arbitrarily depending on thread scheduling, dynamic latencies, and clock speeds.

    • For two threads containing nn and mm atomic instructions respectively, the total number of distinct, valid interleaved execution sequences is calculated using the binomial coefficient:         Total Sequences=(n+mn)=(n+m)!n!⋅m!\text{Total Sequences} = \binom{n+m}{n} = \frac{(n+m)!}{n! \cdot m!}

    • Because interleavings are non-deterministic, concurrent programs that manipulate uncoordinated shared resources can exhibit intermittent, hard-to-reproduce bugs.

Comparison of concurrency versus true hardware parallelism
  • Interference, Critical Sections, and Race Conditions:

    • Race Condition: A flaw where the outcome of concurrent execution depends unpredictably on the precise order or timing of thread instruction execution.

    • Critical Section: A segment of code that accesses or modifies shared data structures and must be executed atomically without interference from other concurrent threads.

    • Interference Example: Consider a shared counter c initialized to 00, updated concurrently by Thread A (x = c; c = x + 1;) and Thread B (y = c; c = y + 1;):

      • Intended Execution: One thread completes both read and write operations before the second begins; final counter value is c=2c = 2.

      • Interleaved Execution: Thread A reads c (00) into x; Thread B preempts and reads c (00) into y; Thread B writes c=1c = 1; Thread A resumes and writes its stale computation c=x+1=1c = x + 1 = 1. One update is lost entirely.

      • Fast Race (Extreme Worst-Case Scheduling): If two threads without mutual exclusion each attempt N=1,000,000,000N = 1,000,000,000 increments on a shared counter c initialized to 00, the theoretical minimum final value of c is as low as 22 (rather than 2,000,000,0002,000,000,000). In general, for N≥2N \ge 2 uncoordinated concurrent increments, the final value of c can span any integer in the range [2,2N][2, 2N].

  • Software Approaches to Mutual Exclusion:

    • 1. Naive Lock Variable: Uses a shared boolean flag lock initialized to false (while(lock); lock = true; <CS>; lock = false;).

      • Failure Mode: Fails safety. If Thread 0 observes lock == false and is preempted before setting lock = true, Thread 1 also reads lock == false and enters its critical section. Both threads execute inside their critical sections simultaneously.

    • 2. Alternating Turns: Uses a shared integer turn initialized to 00 (while(turn != i); <CS>; turn = j;).

      • Failure Mode: Guarantees safety, but violates progress. Enforces strict alternation (0,1,0,1,…0, 1, 0, 1, \dots). If Thread 1 remains in its non-critical work indefinitely, Thread 0 is blocked forever from re-entering its critical section.

    • 3. Interested Flags: Uses shared flags interested[0] and interested[1] (interested[i] = true; while(interested[j]); <CS>; interested[i] = false;).

      • Failure Mode: Guarantees safety, but violates progress. If Thread 0 and Thread 1 both set their respective interested flags to true before checking the loop condition, both threads loop indefinitely in mutual deadlock.

    • 4. Peterson’s Algorithm (1981):

      • Combines interested flags with a turn variable that yields priority: text interested[i] = true; turn = j; while (interested[j] && turn == j) do nothing; << critical section >> interested[i] = false; << normal work >> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

      • Correctness: Satisfies mutual exclusion (safety), guarantees progress, and prevents starvation for two threads.

  • Hardware and Operating System Synchronization Primitives:

    • Test-and-Set Lock (TSL): Hardware instruction that atomically reads a memory word and sets it to a non-zero value in a single memory bus cycle (e.g., XCHG on x86). Avoids software race conditions, but still relies on CPU-intensive busy waiting (spinlocks).

    • Semaphores (Dijkstra, 1965):

      • A protected integer variable SS accessed exclusively via two atomic operations:

        • P(S)P(S) (or wait): Decrements the semaphore value by 11 (S=S−1S = S - 1). If the resulting value is less than 00, the calling thread is blocked and placed on the semaphore's wait queue.

        • V(S)V(S) (or signal): Increments the semaphore value by 11 (S=S+1S = S + 1). If blocked threads exist, one is unblocked and moved to the ready queue.

      • A semaphore's value can never drop below zero in user perception. If S=0S = 0, any thread executing P(S)P(S) blocks immediately until another thread executes V(S)V(S).

      • Binary Semaphore (Mutex): Initialized to 11, used for mutual exclusion.

      • Counting Semaphore: Initialized to resource capacity NN, tracks resource pools.

      • Notification Synchronization: Semaphore initialized to 00. Thread jj executes P(S)P(S) and blocks until Thread ii completes an action and signals via V(S)V(S).

    • Monitors and High-Level Language Primitives:

      • Java: Uses monitor locks via the synchronized keyword on instance and static methods, guaranteeing that only one thread executes a synchronized block on a target object at a time. Notification is achieved via wait(), notify(), and notifyAll().

      • Python: The threading module provides higher-level synchronization abstractions including Lock (implemented via OS semaphores), RLock (reentrant locks), Semaphore, and Barrier.

Deadlock: Modeling, Detection, and Avoidance

  • Deadlock Definition and Necessary Conditions:

    • A deadlock is a permanent state where a set of processes or threads are blocked indefinitely because each holds resources that others require, and none can proceed without acquiring them.

  • Resource Allocation Graphs (RAG):

    • A directed bipartite graph where processes are represented as circular nodes (PP) and resource classes are represented as rectangular nodes (RR).

    • Request Edge: A directed arrow from Process to Resource (Pi→RjP_i \rightarrow R_j) indicates process PiP_i is blocked waiting for resource RjR_j.

    • Assignment Edge: A directed arrow from Resource to Process (Rj→PiR_j \rightarrow P_i) indicates resource RjR_j is allocated to and held by process PiP_i.

    • Cycle Rule: If a Resource Allocation Graph contains no directed cycles, the system is guaranteed deadlock-free. If each resource class contains exactly one unit, a directed cycle is both a necessary and sufficient condition for deadlock.

Resource allocation graph with resource deadlock
  • Progression to Deadlock and State Trajectory Space:

    • Consider Process A (requesting resource RR, then SS, then releasing them) and Process B (requesting resource SS, then RR, then releasing them):

      • Mutual exclusion creates forbidden spatial regions in the two-dimensional instruction-progress state space (a region forbidden because RR cannot be shared, and another forbidden because SS cannot be shared).

      • System progress is strictly monotonic (trajectories can only move up and to the right).

      • If the system enters an unsafe region, it is inevitably channeled into the intersection of the forbidden regions, creating a deadlock state where neither process can advance.

Step-by-step formation of resource allocation graph deadlock cycle
  • Deadlock Strategies:

    • Deadlock Detection and Recovery:

      • The system allows requests to proceed without restrictions, periodically running a cycle-detection algorithm on the Resource Allocation Graph.

      • Recovery: Terminating processes (killing threads until the cycle breaks) or preempting resources and rolling back transaction states (standard in database management systems).

    • Deadlock Avoidance (The Banker's Algorithm - Dijkstra, 1965):

      • Requires processes to declare their maximum potential resource claims in advance.

      • When a resource is requested, the operating system temporarily simulates the allocation and evaluates whether the resulting state is safe.

      • Safe State: A state from which there exists at least one valid sequence of execution where all processes can acquire their maximum declared needs and finish.

      • If the simulated state is unsafe, the allocation request is denied or delayed until other processes release resources, keeping the system permanently out of unsafe regions.

Resource allocation graph cycle reduction for deadlock detection

Virtual Memory and Paging Architectures

  • Memory Abstraction and Addressing Challenges:

    • Early computing relied on raw physical memory addressing, which caused severe limitations:

      • Relocation Problem: Compilers and linkers generate code with hardcoded memory jump targets (e.g., JMP 28). If multiple programs run simultaneously, they cannot all be loaded at physical address 00, requiring static or dynamic code relocation.

      • Protection Problem: Without hardware memory isolation, errant or malicious programs can overwrite the memory of other processes or corrupt operating system kernel structures.

    • Virtual Memory Abstraction: Virtual memory isolates each process into its own large, private, contiguous virtual address space ranging from 00 to 232−12^{32} - 1 (4 GB4\,\text{GB} on 32-bit CPUs) or 00 to 264−12^{64} - 1 (≈18.4 quintillion bytes\approx 18.4\,\text{quintillion bytes} on 64-bit CPUs).

Memory relocation problem with hardcoded jumps
  • Paging Mechanics and Translation Calculations:

    • The virtual address space is broken into fixed-sized blocks called Pages (typically 4 KB=4096 bytes4\,\text{KB} = 4096\,\text{bytes}).

    • Physical memory (RAM) is partitioned into identical fixed-sized units called Page Frames.

    • A hardware Memory Management Unit (MMU) translates virtual addresses issued by the CPU into physical addresses passed across the bus to physical RAM.

    • Mathematical Address Translation: Given a virtual address VV and a page size S=4096 bytesS = 4096\,\text{bytes}:         Page Number=⌊V/S⌋\text{Page Number} = \lfloor V / S \rfloor         Offset=V(modS)=V−(Page Number×S)\text{Offset} = V \pmod S = V - (\text{Page Number} \times S)         Physical Address=(Frame Number×S)+Offset\text{Physical Address} = (\text{Frame Number} \times S) + \text{Offset}

    • Worked Example 1: Virtual address V=21480V = 21480, Page size S=4096S = 4096:

      • Page Number=⌊21480/4096⌋=5\text{Page Number} = \lfloor 21480 / 4096 \rfloor = 5

      • Offset=21480−(5×4096)=21480−20480=1000\text{Offset} = 21480 - (5 \times 4096) = 21480 - 20480 = 1000

      • If Page 55 maps to Physical Frame 44 in the page table, the physical address is:             Physical Address=(4×4096)+1000=16384+1000=17384\text{Physical Address} = (4 \times 4096) + 1000 = 16384 + 1000 = 17384

    • Worked Example 2: Instruction MOV EAX, [8196] issued. Page size 40964096:

      • 8196=(2×4096)+48196 = (2 \times 4096) + 4, indicating Page 22, Offset 44.

      • Page 22 maps to Frame 66. Physical address is (6×4096)+4=24576+4=24580(6 \times 4096) + 4 = 24576 + 4 = 24580.

Hardware memory management unit address translation
  • Page Table Implementation and Page Faults:

    • The Page Table is an in-memory data structure maintained per-process by the operating system and referenced by the MMU.

    • Each Page Table Entry (PTE) contains the mapped Frame Number, a Present/Absent Bit (valid bit, indicates if the page resides in physical RAM), and a Dirty Bit (indicates if the page was written to while in RAM).

    • Page Fault Handling: When an instruction references a virtual address whose Present/Absent bit is 00 (unmapped page):

      1. The MMU hardware cannot resolve the address and raises a page fault exception (software trap).

      2. The CPU suspends the active process and jumps to the operating system's kernel page fault handler.

      3. The kernel chooses an existing page frame to evict using a Page Replacement Algorithm (PRA) (such as FIFO, Clock, Second Chance, Not Recently Used, or Least Recently Used).

      4. If the evicted victim page's dirty bit is set, its contents are written out to secondary storage (paging file/swap space on disk); if not dirty, it is overwritten directly.

      5. The missing page data is read from disk into the freed physical page frame.

      6. The page table is updated (Present bit set to 11, frame number assigned), and the faulting process restarts execution at the exact instruction that triggered the page fault.

Paging address space mapping virtual pages to frames
  • Scalable Page Table Architectures:

    • Translation Lookaside Buffer (TLB): A fully associative, high-speed hardware cache built into the MMU that caches recently used virtual-to-physical address mappings, preventing the overhead of memory lookups on every single instruction.

    • Two-Level Page Table (for 32-bit architectures): A flat page table with 4 KB4\,\text{KB} pages contains 220≈1062^{20} \approx 10^6 entries per process. A two-level structure splits a 32-bit virtual address into a 10-bit top-level Page Table Directory (PT1), a 10-bit second-level Page Table (PT2), and a 12-bit page offset. Second-level page tables for unused address regions are never allocated in RAM.

    • Inverted Page Table (for 64-bit architectures): Flat 64-bit page tables require 2522^{52} entries (≈4 quadrillion\approx 4\,\text{quadrillion}), which is unfeasible. An inverted page table maintains exactly one entry per physical memory frame indexed via a cryptographic hash of the process ID and virtual page number.

Two-level hierarchical page table structure

File Systems: Design, Structures, and Case Studies

  • File Abstraction, Primitives, and Metadata:

    • A file is a named, persistent logical abstraction of secondary storage. Operating system primitives exposed as system calls include create, delete, open (loads file metadata into memory), close (purges memory metadata), read, write, and seek (adjusts the current file read/write position pointer).

    • Metadata (File Attributes): System data describing the file (file type, size, protection/access permissions, timestamps, owner user/group ID, and disk location pointers). Metadata is stored separately from the file's payload data.

  • Directory Hierarchies and Storage Units:

    • A directory is a specialized file containing directory entries that map human-readable filenames to internal filesystem identifiers (such as cluster IDs or inode numbers).

    • Filesystems organize directories into inverted trees starting at a root directory (/ in UNIX/Linux, \ in Windows). Path traversal resolves step-by-step from the root directory through intermediate child directory files.

    • Secondary storage (HDDs, SSDs) allocates storage in fixed-size units known as Blocks (UNIX) or Clusters (Windows), each composed of multiple contiguous hardware sectors (typically 1 KB,2 KB,4 KB1\,\text{KB}, 2\,\text{KB}, 4\,\text{KB}).

Hierarchical tree-structured filesystem directory graph
  • Case Study 1: File Allocation Table (FAT12, FAT16, FAT32):

    • Architecture: A directory entry is exactly 32 bytes32\,\text{bytes} long and contains the filename, attributes, timestamps, file size, and a single pointer identifying the file's first data cluster.

    • The FAT Structure: Implements linked-list block allocation using a centralized table located at the start of the disk partition. The table contains an entry for every cluster in the data area. The value stored in an entry is the index of the next cluster in the file, or an End-Of-File (EOF) marker.

    • Disk Layout: Reserved Area (contains the boot sector), FAT Area (primary and duplicate backup copies of the FAT), Root Directory (fixed in FAT12/16, stored in data area in FAT32), and the Data Area.

Disk layout comparison of FAT12/16 and FAT32Linked-list file block allocation using a File Allocation Table
  • Case Study 2: Linux Extended File System (Ext4 / UNIX Inodes):

    • Inode Architecture: Every file and directory is identified by a unique index node (inode), typically 128 bytes128\,\text{bytes} in size, which contains all file metadata (permissions, owner, size, timestamps) and an array of disk block pointers.

    • Addressing: Classic inodes contain direct block pointers (pointing directly to data blocks), a single indirect pointer (pointing to a disk block filled with block addresses), a double indirect pointer, and a triple indirect pointer, supporting very large files efficiently.

    • UNIX Directory Structure: A directory in UNIX is simply an inode whose data blocks store a list of filename-to-inode-number bindings (e.g., mapping passwd to inode 893 inside directory inode 471 for /etc).

  • Case Study 3: New Technology File System (NTFS):

    • Master File Table (MFT): The structural core of NTFS. Contains fixed-size records (1 KB1\,\text{KB} each) representing every file and folder in the volume.

    • Attributes and Streams: Every element of an NTFS file is an attribute (e.g., STANDARDINFORMATION</code>,<code>STANDARD_INFORMATION</code>, <code>FILE_NAME, DATA</code>).</p></li><li><p><em>ResidentversusNon−ResidentData:</em>Ifafileissmall,itscontentisstoreddirectlyinsidetheMFTrecord(residentattribute).IfthedataexceedsMFTrecordspace,theattributebecomesnon−resident:thedataisstoredinclustersacrossthediskvolume,andtheMFTrecordstoresclusterrunextents(startingclusternumberandlength).</p></li><li><p><em>Self−Containment:</em>TheMFTitselfistreatedasafile(<code>DATA</code>).</p></li><li><p><em>Resident versus Non-Resident Data:</em> If a file is small, its content is stored directly inside the MFT record (resident attribute). If the data exceeds MFT record space, the attribute becomes non-resident: the data is stored in clusters across the disk volume, and the MFT record stores cluster run extents (starting cluster number and length).</p></li><li><p><em>Self-Containment:</em> The MFT itself is treated as a file (<code>MFT) located within the volume's cluster space.

NTFS Master File Table record structure with non-resident data

Inter-Process Communication (IPC)

  • IPC Classifications and Models:

    • Because processes occupy isolated virtual address spaces, data exchange requires explicit OS-mediated Inter-Process Communication (IPC).

    • Pipes: Unidirectional byte streams operating as bounded FIFO buffers managed in kernel memory (typically 64 KB64\,\text{KB} in Linux). Writing blocks if the buffer is full; reading blocks if the buffer is empty. Used heavily in UNIX shells (e.g., ls | more).

    • Shared Memory: Processes invoke specialized system calls (or memory-mapped files via POSIX mmap()) to map identical physical memory frames into their separate virtual address spaces, providing high-speed communication that requires semaphores to prevent race conditions.

    • Message Passing: Processes communicate by sending and receiving discrete, formatted messages over message queues (e.g., POSIX message queues, JMS, MPI). Can use zero-capacity buffers (rendezvous; sender blocks until receiver arrives), bounded capacity, or unbounded capacity.

    • Sockets: Bidirectional communication endpoints used for stream-oriented (TCP) or datagram-oriented (UDP) communication across network boundaries or locally on the same host.

      • Server Socket Workflow: socket() creates endpoint; bind() attaches to IP and port; listen() enables incoming connection queue; accept() blocks until a client connects, returning a new dedicated data socket.

      • Client Socket Workflow: socket() creates endpoint; connect() initiates TCP handshake with server IP/port; send() and recv() exchange byte arrays.

    • Remote Procedure Call (RPC):

      • Abstracts distributed network communication to appear syntactically as a standard local procedure call.

      • Relies on client stubs to marshal procedure arguments into network messages using standardized formats like External Data Representation (XDR) (resolving endianness and data representation differences) and server stubs to unmarshal requests and execute local routines.

      • Implementations: Java RMI, CORBA, SOAP Web Services, Windows Communication Foundation (WCF), and Network File System (NFS).

Internetworking Fundamentals, IPv4 Addressing, and Subnetting

  • Network Layer (Layer 3) Operations:

    • The network layer provides end-to-end logical packet delivery across interconnected heterogeneous networks.

    • Operates a connectionless, best-effort, unreliable delivery service: packets (datagrams) are routed independently and may be dropped, duplicated, delayed, or arrive out of order without Layer 3 error recovery.

  • IPv4 Address Structure:

    • An IPv4 address is a 32 bit32\,\text{bit} binary string divided into four 8 bit8\,\text{bit} fields (octets), formatted for human readability in dotted-decimal notation (e.g., 194.168.4.100).

    • The address is structurally partitioned into two components: the Network ID (prefix, identifying the physical network) and the Host ID (identifying the specific host interface on that network).

  • Classful IPv4 Addressing Architecture:

    • Class A: Leading bit 0. Network ID = 8 bits8\,\text{bits}, Host ID = 24 bits24\,\text{bits}. Dotted-decimal range: 1.0.0.0 through 126.255.255.255. Default mask: 255.0.0.0 (/8). Provides 224−2=16,777,2142^{24} - 2 = 16,777,214 usable host addresses per network.

    • Class B: Leading bits 10. Network ID = 16 bits16\,\text{bits}, Host ID = 16 bits16\,\text{bits}. Dotted-decimal range: 128.0.0.0 through 191.255.255.255. Default mask: 255.255.0.0 (/16). Provides 216−2=65,5342^{16} - 2 = 65,534 usable host addresses per network.

    • Class C: Leading bits 110. Network ID = 24 bits24\,\text{bits}, Host ID = 8 bits8\,\text{bits}. Dotted-decimal range: 192.0.0.0 through 223.255.255.255. Default mask: 255.255.255.0 (/24). Provides 28−2=2542^8 - 2 = 254 usable host addresses per network.

    • Class D (Multicast): Leading bits 1110. Dotted-decimal range: 224.0.0.0 through 239.255.255.255.

    • Class E (Experimental): Leading bits 1111. Dotted-decimal range: 240.0.0.0 through 255.255.255.255.

  • Special and Private IPv4 Addresses:

    • Loopback Address: 127.0.0.0/8 (specifically 127.0.0.1, representing the local host interface).

    • Unspecified Address: 0.0.0.0 (indicates the current host on the local network; default route wildcard).

    • Limited Broadcast: 255.255.255.255 (broadcasts to all hosts on the local physical link; not forwarded by routers).

    • Directed Broadcast: All Host ID bits set to 1 (e.g., 134.86.255.255 on network 134.86.0.0/16).

    • Private RFC 1918 Address Ranges (Non-Internet Routable):

      • Class A: 10.0.0.0 to 10.255.255.255 (10.0.0.0/8)

      • Class B: 172.16.0.0 to 172.31.255.255 (172.16.0.0/12)

      • Class C: 192.168.0.0 to 192.168.255.255 (192.168.0.0/16)

  • Subnetting and the 2n−22^n - 2 Rule:

    • Subnetting borrows nn bits from the Host ID field to create an intermediate Subnet ID.

    • Borrowing nn bits yields 2n2^n subnets. The remaining hh bits in the Host ID provide 2h−22^h - 2 assignable, usable host IP addresses per subnet (subtracting the subnet network address where all host bits are 0, and the subnet broadcast address where all host bits are 1).

    • Class C Worked Example: Network 193.1.1.0/24. Requirement: Create 88 subnets.

      • 2n≥8  ⟹  n=3 bits2^n \ge 8 \implies n = 3\,\text{bits} borrowed from Host ID.

      • Remaining host bits: h=8−3=5 bitsh = 8 - 3 = 5\,\text{bits}.

      • Addresses per subnet: Total = 25=322^5 = 32; Usable hosts = 32−2=3032 - 2 = 30.

      • Custom Subnet Mask: 24+3=27 bits24 + 3 = 27\,\text{bits} (/27 or 255.255.255.224).

      • Block increment: 3232. Subnets: #0: 193.1.1.0/27, #1: 193.1.1.32/27, #2: 193.1.1.64/27, #3: 193.1.1.96/27, #4: 193.1.1.128/27, #5: 193.1.1.160/27, #6: 193.1.1.192/27, #7: 193.1.1.224/27.

    • Class B Expansion Worked Example: Network 182.145.0.0/16. Current network has 7 subnets; expected to double subnets (7×2=147 \times 2 = 14) and double hosts per subnet (up to 320×2=640320 \times 2 = 640 usable hosts):

      • Borrowing 4 bits4\,\text{bits} yields 24=16 subnets2^4 = 16\,\text{subnets} (≥14\ge 14).

      • Remaining host bits: 16−4=12 bits16 - 4 = 12\,\text{bits}, providing 212=40962^{12} = 4096 total addresses and 40944094 usable host addresses (≥640\ge 640).

      • Custom Subnet Mask: 255.255.240.0 (/20).

      • Block increment in third octet: 4096/256=164096 / 256 = 16.

      • Subnet 1: 182.145.0.0 - 182.145.15.255

      • Subnet 2: 182.145.16.0 - 182.145.31.255 (First usable: 182.145.16.1; Broadcast: 182.145.47.255 per exam solutions sheet)

      • Subnet 3: 182.145.32.0 - 182.145.47.255

Variable Length Subnet Masking (VLSM) and Supernetting (CIDR)

  • Variable Length Subnet Masking (VLSM):

    • Classful subnetting enforces uniform subnet masks, wasting IP addresses on small networks (e.g., assigning a /24 mask to a 2-host router-to-router WAN link wastes 252252 addresses).

    • VLSM allows multiple different subnet masks to be deployed across the same network address space, breaking subnets into variable-sized sub-subnets matching actual host requirements.

    • Design Principle: Always sort subnet requirements and allocate addresses starting with the largest host requirements first, moving sequentially down to the smallest.

  • VLSM Comprehensive Case Studies:

    • Case Study 1: Enterprise Address 192.168.16.0/24

      • London (120120 hosts): Needs /25 (128128 addresses). Allocated Subnet A: 192.168.16.0/25 (Usable: 192.168.16.1 to .126; Broadcast: 192.168.16.127).

      • Southampton (6060 hosts): Needs /26 (6464 addresses). Allocated Subnet B: 192.168.16.128/26 (Usable: 192.168.16.129 to .190; Broadcast: 192.168.16.191).

      • Portsmouth (2020 hosts): Needs /27 (3232 addresses). Allocated Subnet C: 192.168.16.192/27 (Usable: 192.168.16.193 to .222; Broadcast: 192.168.16.223).

      • WAN Link 1 (22 hosts): Needs /30 (44 addresses). Allocated Subnet D: 192.168.16.224/30 (Usable: 192.168.16.225 to .226; Broadcast: 192.168.16.227).

      • WAN Link 2 (22 hosts): Needs /30 (44 addresses). Allocated Subnet E: 192.168.16.228/30 (Usable: 192.168.16.229 to .230; Broadcast: 192.168.16.231).

    • Case Study 2: Campus Network 223.13.3.0/24 (6 Subnets Total: 4 LANs, 2 WAN links)

      • Subnet 1 (17+40=5717 + 40 = 57 hosts): Allocated 223.13.3.0/26 (Usable: .1 to .62; Broadcast: .63).

      • Subnet 2 (35+18=5335 + 18 = 53 hosts): Allocated 223.13.3.64/26 (Usable: .65 to .126; Broadcast: .127).

      • Subnet 3 (23+15=3823 + 15 = 38 hosts): Allocated 223.13.3.128/26 (Usable: .129 to .190; Broadcast: .191).

      • Subnet 4 (1212 hosts): Allocated 223.13.3.192/28 (Usable: .193 to .206; Broadcast: .207).

      • WAN Link 1 (22 hosts): Allocated 223.13.3.208/30 (Usable: .209 to .210; Broadcast: .211).

      • WAN Link 2 (22 hosts): Allocated 223.13.3.212/30 (Usable: .213 to .214; Broadcast: .215).

  • Supernetting and Classless Inter-Domain Routing (CIDR):

    • Supernetting aggregates multiple contiguous small network blocks (such as adjacent Class C /24 networks) into a single larger route entry with a shorter prefix (e.g., /22).

    • Common Bits Method: Convert the network addresses to binary and identify the contiguous matching bits from left to right.

    • Worked Example: An ISP holds four contiguous Class B blocks: 149.8.0.0/16, 149.9.0.0/16, 149.10.0.0/16, 149.11.0.0/16:

      • 149.8.0.0 = 10010101.00001000.00000000.00000000

      • 149.9.0.0 = 10010101.00001001.00000000.00000000

      • 149.10.0.0 = 10010101.00001010.00000000.00000000

      • 149.11.0.0 = 10010101.00001011.00000000.00000000

      • The first 14 bits14\,\text{bits} (10010101.000010xx) are identical across all four addresses.

      • Supernet Mask: /14 or 11111111.11111100.00000000.00000000 (255.252.0.0).

      • Supernet Address: 149.8.0.0/14.

    • Restrictions: Aggregated networks must be strictly contiguous and aligned on powers of 22. The supernet address is always the network address of the first block.

Core Network Infrastructure Services: DHCP and DNS

  • Dynamic Host Configuration Protocol (DHCP):

    • Standardized in 1993 (RFC 2131) as an evolution of the Bootstrap Protocol (BOOTP) to dynamically distribute IP addresses, subnet masks, default gateways, and DNS server addresses with minimal administrative intervention.

    • Operates over UDP using Port 6767 (Server) and Port 6868 (Client).

    • DORA Protocol Sequence:

      1. DHCPDISCOVER: Client broadcasts over the local network to locate available DHCP servers.

      2. DHCPOFFER: Servers unicast or broadcast configuration parameter offers.

      3. DHCPREQUEST: Client broadcasts its acceptance of a specific server offer (informing other servers that their offers were declined).

      4. DHCPACK: The chosen server commits the lease and sends an acknowledgment packet to the client.

      5. DHCPRELEASE: The client explicitly relinquishes its assigned IP address upon graceful shutdown, returning it to the address pool.

    • Lease Renewals: When 50%50\% of the lease duration expires, the client sends a unicast DHCPREQUEST to renew the lease. If unacknowledged, at 87.5%87.5\% of the lease duration, the client broadcasts to all available DHCP servers.

    • Vulnerabilities: Inherently unauthenticated UDP communication; vulnerable to rogue DHCP servers (supplying malicious gateway or DNS parameters) and DHCP starvation attacks (exhausting the IP pool via spoofed MAC addresses).

DHCP protocol message exchange sequence
  • Domain Name System (DNS):

    • A globally distributed, hierarchical database system that maps human-friendly domain names to numeric IP addresses.

    • Namespace Constraints: Inverted tree structure with a maximum hierarchy depth of 127 levels127\,\text{levels}; domain names are limited to 255 characters255\,\text{characters}.

    • Transport Ports: Operates over Port 5353 using UDP for client-to-server queries, and TCP for zone transfers and messages exceeding 512 bytes512\,\text{bytes}.

    • Hierarchy Levels: Root Domain (.) →\rightarrow Top-Level Domains (TLDs, such as generic .com, .org and country-code .uk, .us) →\rightarrow Second-Level Domains (e.g., port.ac.uk) →\rightarrow Subdomains.

Structure of a complete URL with subdomain
  • Name Server Roles: Authoritative Servers maintain master zone files (Primary servers support dynamic editing; Secondary servers receive replicated read-only zone data). Non-Authoritative (Caching) Servers query authoritative systems on behalf of resolvers and cache results locally.

  • Resolution Methods:

    • Recursive Resolution: The local DNS server handles the entire query process, querying each level of the hierarchy on the client's behalf and returning the final answer.

    • Iterative Resolution: The queried name server returns the best referral it has (pointing to root servers, TLD servers, or authoritative name servers), requiring the querying resolver to issue successive queries down the tree.

  • Root Nameserver Architecture: Published across 1313 logical root server clusters (A through M), operated globally by independent entities (including Verisign, USC-ISI, Cogent, University of Maryland, NASA Ames, ISC, US DoD, RIPE NCC, ICANN, and WIDE). Root servers handle ≈3000 queries/sec\approx 3000\,\text{queries/sec} normally, with proven resilience under DDoS attacks exceeding 50,000 queries/sec50,000\,\text{queries/sec}.

Iterative versus recursive DNS resolution comparison

Routing Principles, Routing Tables, and Protocol Classification

  • Routing Function and Mechanics:

    • Routing is the layer-3 process of selecting paths and forwarding packets from a source network to a destination across intermediate routers.

    • Routers maintain internal Routing Tables containing network prefix entries rather than end-to-end paths; routers make next-hop forwarding decisions on a per-hop basis.

  • Routing Table Structure and Elements:

    • Code: The mechanism that discovered the route (C = Directly Connected, S = Static, R = RIP, O = OSPF, B = BGP).

    • Destination Network and Mask: Target IP network and prefix length.

    • Administrative Distance (AD): Metric of trustworthiness used when multiple protocols report routes to the same destination. Lower values are preferred (Directly Connected = 00, Static = 11, eBGP = 2020, OSPF = 110110, RIP = 120120).

    • Routing Cost / Metric: Calculated path cost based on protocol variables (hops, bandwidth, delay).

    • Next Hop: The IP address of the adjacent router interface that receives the forwarded packet.

    • Outgoing Interface: The local physical port (E0 for Ethernet, S0 for Serial) through which the packet departs.

  • Static versus Dynamic Routing:

    • Static Routing: Manually entered by an administrator. Extremely low CPU and memory overhead; completely deterministic and secure (no routing advertisements sent over links). Highly vulnerable to link and router failures; requires manual reconfiguration to adapt to topology changes.

    • Dynamic Routing: Protocols automatically discover networks, share topology information, populate routing tables, and dynamically reroute traffic around failed links. Consumes network bandwidth and CPU cycles; more complex to configure; susceptible to false route injection.

  • Protocol Classification Taxonomies:

    • Interior Gateway Protocols (IGP): Designed to route traffic within a single Autonomous System (e.g., RIP, OSPF, EIGRP, IS-IS).

    • Exterior Gateway Protocols (EGP): Designed to route traffic between distinct Autonomous Systems across the public Internet core (e.g., BGP).

    • Algorithmic Classification:

      • Distance Vector: Routers periodically share their entire routing table with immediate neighbors ("routing by rumor"; e.g., RIP).

      • Link-State: Routers flood link status advertisements across the area, allowing each node to construct an identical topology map and compute shortest paths (e.g., OSPF, IS-IS).

      • Path Vector: Advertises explicit sequences of Autonomous Systems traversed to reach destination prefixes, enforcing policy-driven routing (e.g., BGP).

Distance Vector Routing and Routing Information Protocol (RIP)

  • Operational Principles of RIP (RFC 2453):

    • Distance vector IGP based on the distributed Bellman-Ford algorithm.

    • Metric: Hop count only (number of routers traversed). Ignores line bandwidth, delay, load, and reliability.

    • Hop Limit: Maximum usable hop count is 1515. A metric of 1616 indicates an unreachable destination.

    • RIPv1 vs. RIPv2: RIPv1 is a legacy classful protocol broadcasting updates to 255.255.255.255. RIPv2 supports CIDR/VLSM, multicasts updates to 224.0.0.9, and supports simple password and MD5 cryptographic authentication.

    • Chatty Nature: By default, RIP broadcasts/multicasts its entire routing table every 30 seconds30\,\text{seconds}, consuming considerable link bandwidth on slow lines.

  • RIP Timers:

    • Update Timer (30 seconds30\,\text{seconds}): Interval between periodic full routing table transmissions. Includes random jitter to prevent neighboring routers from synchronizing update transmissions.

    • Invalid Timer (180 seconds180\,\text{seconds}): Time allowed to elapse without receiving updates for an active route before marking it invalid. The metric is set to 1616 (Route Poisoning).

    • Hold Down Timer (180 seconds180\,\text{seconds}): Freezes route state upon receiving an update that invalidates or increases path cost, ignoring subsequent alternative route announcements for that duration to suppress route flapping.

    • Flush Timer (240 seconds240\,\text{seconds}): Total time after which a dead route is permanently expunged from the routing table (60 seconds60\,\text{seconds} after the invalid timer expires).

  • Routing Loops and Prevention Mechanisms:

    • Routing Loop: A condition where two or more routers continuously bounce packets back and forth due to inconsistent or stale routing tables caused by slow convergence.

    • Split Horizon: Enforces the rule: Never advertise a route back out the same interface through which it was learned.

    • Poison Reverse: Explicitly sends an update back to the source advertising the learned route with a metric of 1616 (unreachable), overriding any potential looping state.

    • Triggered Updates: Bypasses the 30-second timer to send immediate update packets containing only the affected prefix when a link status changes.

    • Counting to Infinity Limitation: Capping valid hops at 1515 guarantees that routing loops terminate when the metric increments to 1616.

Link-State Routing and Open Shortest Path First (OSPF)

  • Principles of OSPF:

    • Open-standard link-state IGP designed to overcome RIP limitations (eliminates the 15-hop limit, converges rapidly, and prevents loops).

    • Metric: Cost, inversely proportional to link bandwidth (Cisco default: Cost=108/Bandwidth in bps\text{Cost} = 10^8 / \text{Bandwidth in bps}; values range from 11 to 6553565535). Faster links receive lower cost values.

  • OSPF Startup Sequence (5 Steps to Initiate Routing):

    1. Establish Neighbors: Routers periodically send HELLO packets (every 10 seconds10\,\text{seconds} to multicast 224.0.0.5) across common links to discover neighbors.

    2. Establish Adjacencies: Routers evaluate neighbor relationships and form adjacencies to synchronize their Link-State Databases (LSDB).

    3. Run SPF Algorithm: Each router runs Dijkstra's Shortest Path First (SPF) algorithm independently on its LSDB.

    4. Populate the Route Table: The router constructs a Shortest Path Tree with itself at the root, selects lowest-cost paths to all subnets, and installs them into the routing table.

    5. Commence Routing: Forwards live user traffic across computed optimal paths.

Steps to initiate routing in an OSPF area
  • Link State Advertisements (LSAs) and Flooding:

    • Routers advertise only the state and cost of their directly connected links via LSAs.

    • LSAs are reliably flooded throughout the area (re-flooded every 30 minutes30\,\text{minutes}). When all routers in an area hold identical LSDBs, the area is converged.

  • OSPF Hierarchical Area Design:

    • Backbone Area (Area 0): The core transit area to which all other areas must physically or virtually connect.

    • Area Border Routers (ABRs): Routers residing on the boundary between Area 0 and non-backbone areas.

    • Efficiency Gains: Detailed topology LSAs are restricted to their local area. ABRs aggregate subnets and propagate small summary LSAs between areas, shielding internal routers from foreign topology recalculations and reducing CPU/memory utilization.

Hierarchical OSPF area architecture with border router
  • Network Types and Designated Routers:

    • Broadcast Multi-Access (Ethernet): Automatically elects a Designated Router (DR) and a Backup Designated Router (BDR) to avoid full mesh adjacencies (n(n−1)/2n(n-1)/2 connections). All other routers form adjacencies only with the DR/BDR, exchanging LSAs via multicast 224.0.0.6.

    • Point-to-Point (T1, serial lines): Adjacency forms automatically between the two endpoints; no DR/BDR is elected.

    • Non-Broadcast Multi-Access (NBMA - Frame Relay, ATM): Requires manual neighbor configuration (neighbor command) or point-to-multipoint sub-interface configurations.

Exterior Routing and Border Gateway Protocol (BGP-4)

  • Path Vector Principles and BGP-4 Overview:

    • BGP-4 (RFC 1771 / RFC 4271) is the standard inter-domain routing protocol of the global Internet, supporting Classless Inter-Domain Routing (CIDR) and route aggregation.

    • Operates as a Path Vector protocol: advertises complete autonomous system traversal paths rather than raw distance metrics or internal link states.

  • Autonomous Systems and Numbering:

    • Autonomous System (AS): A collection of connected networks under unified technical and administrative management that presents a common routing policy to the Internet.

    • Autonomous System Number (ASN): Unique identifier assigned globally by the Internet Assigned Numbers Authority (IANA) through Regional Internet Registries (ARIN, RIPE NCC, APNIC, LACNIC, AfriNIC).

      • Public ASNs: 1 - 64511 (globally routable across the Internet backbone).

      • Private ASNs: 64512 - 65535 (reserved for internal enterprise peering; stripped before entering the public Internet).

      • Example: University of Portsmouth uses ASN 786 (JANET Jisc Services Limited).

Autonomous system architecture with multiple ISP peering
  • BGP Operational Mechanics:

    • BGP Peer Discovery: BGP routers do not discover neighbors dynamically. Peers must be explicitly configured manually by administrators.

    • Transport Connection: BGP opens a reliable TCP connection on Port 179179 between peers.

    • Database Structure: Maintains Adj-RIB-In (unprocessed incoming routes from peers), Loc-RIB (routes chosen by the local decision process), and Adj-RIB-Out (routes selected for advertisement to peers).

    • Update Model: The entire routing table is exchanged once when the TCP session initializes; subsequent updates are purely event-driven, incremental triggered updates.

  • BGP Path Determination (Three-Phase Decision Process):

    • Phase 1: Calculates degree of preference for each candidate route in Adj-RIB-In using local policies and the LOCAL_PREF attribute.

    • Phase 2: Selects best routes for installation into Loc-RIB. Verifies next-hop reachability via NEXT_HOP, evaluates AS_PATH (routes containing the local ASN are dropped immediately to prevent loops), and breaks ties using strict hierarchical rules:

      1. Highest Local Preference (LOCAL_PREF).

      2. Shortest AS-Path length (AS_PATH).

      3. Lowest Origin code.

      4. Lowest Multi-Exit Discriminator (MED).

      5. eBGP routes preferred over iBGP routes.

      6. Lowest interior IGP cost to the next hop.

      7. Lowest BGP Router ID.

      8. Lowest peer IP address.

    • Phase 3: Disseminates routes from Loc-RIB to neighboring peers via Adj-RIB-Out according to outbound routing policies.

  • Case Studies in BGP Failure and Misconfiguration:

    • SuproNet Czech ISP Incident (February 16, 2009): A misconfigured router belonging to Czech ISP SuproNet generated BGP updates with excessively long AS-paths. The malformed updates triggered memory exhaustion and CPU crashes across border routers worldwide, causing widespread global outages.

    • Pakistan YouTube Hijack (February 25, 2008): Pakistan Telecom, attempting to block domestic access to YouTube, announced an unauthorized, highly specific BGP route (208.65.153.0/24) for YouTube's parent prefix (208.65.152.0/22). Due to standard longest-prefix match routing, this false route propagated globally, blackholing worldwide YouTube traffic for several hours.

Network Routing Security and Router Hardening

  • Security Architecture Dimensions:

    • CIA Triad:

      • Confidentiality: Protecting network packets and device configurations from unauthorized inspection.

      • Integrity: Ensuring routing announcements, firmware, and payload data are not modified in transit.

      • Availability: Guaranteeing network devices and routing paths remain accessible to legitimate users.

    • AAA Framework:

      • Authentication: Verifying the identity of users and peer routers.

      • Authorization: Granting legitimate access privileges while restricting unauthorized resources.

      • Accounting (Auditing): Logging and tracking user and administrative actions back to specific identities.

Network security CIA triad model
  • Common Router Vulnerabilities and Security Incidents:

    • Default and Weak Administrative Credentials: Leaving default factory passwords (admin/admin, admin/password) enabled allows remote attackers to compromise edge routers. Incident: A Huawei enterprise router belonging to Oman's Muscat Securities Market (MSM) remained accessible via Telnet with credentials admin/admin (uncovered by researcher Victor Gevers, Dutch GDI Foundation).

Table of default consumer router administrative credentials
*   **Undocumented Backdoors and Outdated Firmware:** Unpatched firmware exposes management interfaces to exploitation. *Incident:* An undocumented testing backdoor on TCP port 3276432764 across multiple Cisco small-business routers allowed attackers to access administrator credentials and issue arbitrary root commands.
*   **Denial of Service (DoS) Vulnerabilities:** Crafted malicious network packets can force router kernel panics. *Incident:* Cisco bug `CSCsz71787` caused router crashes and reboots when processing specific UDP and IP protocol 9191 packets under Data Link Switching (DLSw).
*   **Routing Table Poisoning (RTP):** Attackers insert a rogue router onto a shared subnet; the rogue router injects fabricated routing updates, poisoning legitimate routing tables to intercept (man-in-the-middle), reroute, or blackhole network traffic.
  • Router Hardening Best Practices:

    • Enforce strong password policies with cryptographic storage.

    • Disable unnecessary network services and daemons (such as Telnet, HTTP, finger, and CDP).

    • Relocate management interfaces to non-standard ports or dedicated out-of-band management VLANs.

    • Apply firmware security patches regularly.

    • Implement physical port and console security.

    • Enable cryptographic authentication on all inter-router routing protocols.

  • Routing Protocol Authentication Mechanisms:

    • RIPv2 Authentication: Supports cleartext password authentication or MD5 cryptographic checksum authentication configured directly on router interfaces: text R1(config)# key chain RIP_KEY R1(config-keychain)# key 1 R1(config-keychain-key)# key-string cosine R1(config)# int s0/0/0 R1(config-if)# ip rip authentication mode md5 R1(config-if)# ip rip authentication key-chain RIP_KEY &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • OSPFv2 Authentication: OSPF headers define explicit authentication fields (AuType): AuType 0 = Null authentication; AuType 1 = Simple password (8-byte cleartext); AuType 2 = Cryptographic authentication (MD5 digest verified using shared secret keys and sequence numbers to prevent replay attacks). OSPF packets travel directly over IP (protocol number 8989).

Dynamic Routing Algorithms and Routing Table Analysis

  • Network Graph Topology Analysis (Worked Network Problem):

    • Consider a weighted network topology with nodes A,B,C,D,E,F,G,HA, B, C, D, E, F, G, H and the following link delays:

      • Link(A,B)=1\text{Link}(A, B) = 1, Link(A,C)=4\text{Link}(A, C) = 4

      • Link(B,C)=2\text{Link}(B, C) = 2, Link(B,D)=9\text{Link}(B, D) = 9, Link(B,G)=4\text{Link}(B, G) = 4, Link(B,H)=2\text{Link}(B, H) = 2

      • Link(C,D)=1\text{Link}(C, D) = 1

      • Link(D,E)=1\text{Link}(D, E) = 1, Link(D,F)=3\text{Link}(D, F) = 3, Link(D,G)=1\text{Link}(D, G) = 1

      • Link(E,F)=1\text{Link}(E, F) = 1

      • Link(F,G)=6\text{Link}(F, G) = 6

      • Link(G,H)=14\text{Link}(G, H) = 14

Weighted graph network topology for routing algorithms
  • Link-State (Dijkstra SPF) Shortest Paths from Router D:

    • To Destination A: Path is D−C−B−AD - C - B - A, Next Hop = CC, Total Delay Cost = 1+2+1=4 ms1 + 2 + 1 = 4\,\text{ms}.

    • To Destination B: Path is D−C−BD - C - B, Next Hop = CC, Total Delay Cost = 1+2=3 ms1 + 2 = 3\,\text{ms}.

    • To Destination C: Path is D−CD - C, Next Hop = CC, Total Delay Cost = 1 ms1\,\text{ms}.

    • To Destination E: Path is D−ED - E, Next Hop = EE, Total Delay Cost = 1 ms1\,\text{ms}.

    • To Destination F: Path is D−E−FD - E - F, Next Hop = EE, Total Delay Cost = 1+1=2 ms1 + 1 = 2\,\text{ms}.

    • To Destination G: Path is D−GD - G, Next Hop = GG, Total Delay Cost = 1 ms1\,\text{ms}.

    • To Destination H: Path is D−C−B−HD - C - B - H, Next Hop = CC, Total Delay Cost = 1+2+2=5 ms1 + 2 + 2 = 5\,\text{ms}.

  • Comparison with Distance Vector (Hop Count vs. Delay Metrics) from Router D:

    • Destination A: Distance Vector via lowest hop count identifies two paths (D−C−AD - C - A at 2 hops2\,\text{hops} with delay 5 ms5\,\text{ms}; D−B−AD - B - A at 2 hops2\,\text{hops} with delay 10 ms10\,\text{ms}). In contrast, Link-State selects D−C−B−AD - C - B - A (3 hops3\,\text{hops}, but lowest delay of 4 ms4\,\text{ms}).

    • Destination B: Distance Vector via hop count selects direct link D−BD - B (1 hop1\,\text{hop}, delay 9 ms9\,\text{ms}). Link-State selects D−C−BD - C - B (2 hops2\,\text{hops}, delay 3 ms3\,\text{ms}).

    • Destination F: Distance Vector selects direct link D−FD - F (1 hop1\,\text{hop}, delay 3 ms3\,\text{ms}). Link-State selects D−E−FD - E - F (2 hops2\,\text{hops}, delay 2 ms2\,\text{ms}).

    • Destination H: Distance Vector selects D−B−HD - B - H (2 hops2\,\text{hops}, delay 11 ms11\,\text{ms}) or D−G−HD - G - H (2 hops2\,\text{hops}, delay 15 ms15\,\text{ms}). Link-State selects D−C−B−HD - C - B - H (3 hops3\,\text{hops}, delay 5 ms5\,\text{ms}).

Routing table comparing Distance Vector hops to Link State delay
  • Windows Host Route Table Inspection:

    • An inspection of an active workstation route table (route print) reveals the internal hierarchy:

      • 0.0.0.0 / 0.0.0.0: Default Gateway entry forwarding external traffic out the local network interface.

      • 127.0.0.0 / 255.0.0.0: Loopback network pointing to gateway 127.0.0.1.

      • 127.0.0.1 / 255.255.255.255: Host loopback interface.

      • 148.197.34.0 / 255.255.255.0: Local physical network subnet, marked as On-link on interface 148.197.34.119.

      • 148.197.34.119 / 255.255.255.255: Specific IP address assigned to the host NIC.

      • 148.197.34.255 / 255.255.255.255: Subnet broadcast address.

      • 224.0.0.0 / 240.0.0.0: Multicast route definition mapped to local interfaces.

      • 255.255.255.255 / 255.255.255.255: Limited broadcast route.

Windows active IPv4 routing table extract