Study Notes
B.Tech CSE — Semester 5
OS

Operating Systems

Process Management · CPU Scheduling · Synchronization · Deadlocks · Memory Management · Paging · Virtual Memory · File Management · Disk Scheduling

All 5 Units / Exam-Focused / MAKAUT Pattern
01

Introduction to Operating Systems

OS Definition · Evolution · OS Services · System Calls · Resource Manager · Kernel Architectures · Virtual Machines

Quick Revision: OS is a program that manages hardware and software resources. Evolution: Serial → Batch → Multiprogrammed → Time-Sharing → Distributed → Real-Time → Embedded. System calls: Process Control, File Management, Device Management, Information Maintenance, Communication. Kernel types: Monolithic (fast, risky), Microkernel (stable, slow), Hybrid (balanced), Layered (debuggable), Modular (flexible).

Unit 1 — 1 Mark Questions 1M

  1. What is an Operating System?
    An Operating System (OS) is a system software that acts as an interface between the user and the computer hardware, managing hardware resources and providing services to application programs.
  2. What are the main goals of an OS?
    (a) User goals: Convenient, easy to use, safe, fast.
    (b) System goals: Easy to design, implement, maintain, flexibility, reliability, efficiency, no-wait.
  3. Name the different types of OS based on interaction.
    Batch OS, Multiprogrammed OS, Time-Sharing OS, Distributed OS, Real-Time OS, Embedded OS, Network OS, Mobile OS.
  4. What is a Batch OS?
    In a Batch OS, users submit jobs to an operator who batches similar jobs together and processes them sequentially. No direct user interaction. Examples: Payroll processing, bank statements.
  5. What is a Multiprogrammed OS?
    A multiprogrammed OS keeps multiple programs in memory and switches between them when one program waits for I/O, thus maximizing CPU utilization.
  6. What is a Time-Sharing OS?
    A time-sharing OS uses CPU scheduling and multiprogramming to provide interactive use of the computer. Each user gets a small quantum of CPU time in a round-robin fashion. Examples: Unix, Linux.
  7. What is a Distributed OS?
    A Distributed OS manages a collection of independent computers that appear to users as a single coherent system. Resources are shared across the network. Examples: LOCUS, Amoeba.
  8. What is a Real-Time OS (RTOS)?
    An RTOS is designed to serve real-time applications where data must be processed within strict time constraints. Two types: Hard RTOS (missed deadline = failure) and Soft RTOS (occasional misses tolerated). Examples: VxWorks, QNX.
  9. What is an Embedded OS?
    An Embedded OS is designed to run on embedded systems (special-purpose devices with limited resources). Examples: Embedded Linux, VxWorks, Windows CE, FreeRTOS.
  10. What is a Kernel?
    The kernel is the core component of an OS that resides in memory and provides the most basic services. It manages processes, memory, I/O, and system calls.
  11. What is a System Call?
    A system call is a mechanism that allows a program to request a service from the operating system kernel. It provides the interface between a process and the OS.
  12. Name the five types of system calls.
    (1) Process Control, (2) File Management, (3) Device Management, (4) Information Maintenance, (5) Communication.
  13. What is a Virtual Machine?
    A Virtual Machine (VM) is a software emulation of a physical computer that runs an operating system as if it were installed on actual hardware. Examples: VMware, VirtualBox, Hyper-V.
  14. What is the difference between Monolithic and Microkernel?
    Monolithic: Entire OS in kernel space (single address space). Faster but less stable.
    Microkernel: Only essential services in kernel space. Slower but more stable and modular.
  15. What is a Hybrid Kernel?
    A Hybrid Kernel combines features of both monolithic and microkernel architectures. It keeps some services in kernel space for performance while moving others to user space. Example: Windows NT, macOS XNU.

Unit 1 — 5 Mark Questions 5M

  1. Explain the evolution of Operating Systems with their characteristics. [2022]
    (1) Serial Processing (No OS): Programs loaded manually, one at a time. No scheduling, no resource sharing. Setup time was significant.

    (2) Batch Systems: Jobs grouped into batches processed sequentially by an operator. Reduced setup time. Still no interaction, one job at a time. Examples: IBM OS/360.

    (3) Multiprogrammed Systems: Multiple programs in memory simultaneously. When one program waits for I/O, CPU switches to another. Increases CPU utilization and throughput.

    (4) Time-Sharing Systems: CPU time divided into time slices (quantum). Multiple users interact simultaneously. Uses CPU scheduling and multiprogramming. Examples: Unix, Linux.

    (5) Distributed Systems: Collection of autonomous computers connected via network. Appear as single system. Resource sharing, fault tolerance.

    (6) Real-Time Systems: Designed for time-critical applications. Hard RTOS (strict deadlines) vs Soft RTOS (flexible deadlines).

    (7) Embedded Systems: Specialized OS for dedicated devices. Resource-constrained, highly reliable. Examples: Automotive, IoT devices.
  2. Explain OS services with examples. [2021]
    OS Services are functions provided by the OS to assist users:

    (1) User Interface (UI): CLI (Command Line Interface) or GUI (Graphical User Interface). CLI: type commands. GUI: icons, windows, mouse.

    (2) Program Execution: Load and run user programs in memory, handle I/O, terminate execution.

    (3) I/O Operations: Efficient and protected I/O to devices (disks, printers, terminals).

    (4) File System Manipulation: Create, delete, read, write files. Manage directories, access control.

    (5) Communications: Inter-process communication (IPC) via shared memory or message passing.

    (6) Error Detection: Detect and handle errors in CPU, memory, I/O devices, user programs.

    (7) Resource Allocation: Allocate CPU, memory, I/O devices among competing processes.

    (8) Accounting: Keep track of resource usage by each user/process for billing or statistics.

    (9) Protection & Security: Prevent unauthorized access, authenticate users, ensure data integrity.
  3. Explain types of system calls with examples. [2023]
    System calls allow user programs to request services from the kernel:

    (1) Process Control: end, abort, load, execute, create/end process, get/set process attributes, wait/signal event.
      Example: fork(), exit(), exec(), wait().

    (2) File Management: create, delete, open, close, read, write, get/set file attributes, reposition directory.
      Example: open(), read(), write(), close(), unlink().

    (3) Device Management: request/release device, read/write/position device, get/set device attributes.
      Example: ioctl(), read(), write().

    (4) Information Maintenance: get/set time or date, get/set system data, get/set process/user/file attributes.
      Example: time(), getpid(), alarm().

    (5) Communication: create/delete connection, send/receive messages, transfer status info.
      Example: pipe(), socket(), send(), receive(), msgrcv(), msgsnd().
  4. Explain OS as a Resource Manager and Virtual Machine concepts.
    OS as Resource Manager: The OS manages all system resources — CPU, memory, I/O devices, files, and data. It decides which process gets which resource, when, and for how long. Functions include allocation, deallocation, protection, sharing, and monitoring.

    Resource Allocation Approaches:
    (a) Pre-emptive: OS can forcibly take a resource from a process.
    (b) Non-preemptive: Process voluntarily releases resources.

    Virtual Machine: A VM abstracts the physical hardware into multiple execution environments. Each VM believes it has dedicated hardware. Benefits: OS independence, security, testing environments, server consolidation. Types: Full virtualization (VMware), Paravirtualization (Xen), Hardware-assisted (Intel VT-x).
  5. Explain different types of Real-Time Operating Systems.
    (1) Hard Real-Time OS: Must meet deadlines strictly. Missing a deadline can cause catastrophic failure. No buffering, small data, fast response (<1 sec). Examples: Flight control systems, Air traffic control, Medical systems (pacemakers).

    (2) Soft Real-Time OS: Missing an occasional deadline is acceptable. Uses statistical guarantees. Examples: Multimedia systems, Online transaction processing.

    Characteristics of RTOS:
    • Context switching time is minimized
    • Minimal interrupt latency
    • Task scheduling based on priority (usually preemptive)
    • Reliable and predictable timing
    • Small kernel size (often microkernel)

Unit 1 — 15 Mark Questions 15M

  1. Explain the different types of Operating Systems in detail with examples. Compare Batch, Multiprogrammed, Time-Sharing, Distributed, and Real-Time OS. [2023, 2022]

    1. Serial/Batch Operating System:
    Users prepare programs and data on offline devices (punched cards, magnetic tapes). Jobs are batched together and processed sequentially by an operator. No user interaction during execution. Main problem: Idle time between jobs (I/O time wasted).

    2. Multiprogrammed Operating System:
    Multiple programs are kept in memory simultaneously. When a running program requests I/O (which takes time), the OS switches to another ready program. This overlap of I/O and computation keeps CPU busy. Requirements: Memory management (to hold multiple programs), CPU scheduling (to select next program).

    3. Time-Sharing Operating System:
    Extension of multiprogramming. CPU executes multiple jobs by switching rapidly between them (time quantum = 10-100 ms). Users interact directly with the system. Each user has at least one separate program in memory. Key features: Quick response time, online user interaction, parallel execution illusion. Requires Memory Protection and Timer.

    4. Distributed Operating System:
    A collection of independent, networked, heterogeneous computers working together to provide a single computing environment. Users access remote resources transparently. Advantages: Resource sharing, computation speedup, reliability, communication. Examples: Distributed UNIX, LOCUS, Amoeba.

    5. Real-Time Operating System (RTOS):
    Well-defined fixed time constraints. Processing must be done within defined time or system fails. Used in embedded systems, industrial robots, spacecraft, military systems. Two categories:
    • Hard Real-Time: Mission-critical, deadline must be met (Flight control, Medical systems).
    • Soft Real-Time: Deadline misses degrade quality but don't cause failure (Video streaming, Online booking).

    Comparison Table:
    FeatureBatchMultiprogrammedTime-SharingDistributedReal-Time
    User InteractionNoneNoneDirectIndirectLimited/None
    CPU UtilizationLowHighVery HighHighDepends
    Resource SharingSequentialConcurrentConcurrentNetwork-basedConcurrent
    Response TimeHoursMinutesSecondsDependsMicroseconds
    ExamplesPayrollMainframe OSUnix, LinuxLOCUSVxWorks, QNX
  2. Explain OS kernel architectures in detail — Monolithic, Layered, Modular, Microkernel, and Hybrid Kernels. Provide a detailed comparison. [2023, 2022]

    1. Monolithic Kernel:
    The entire OS (process management, memory management, file systems, device drivers, IPC) runs in kernel mode as a single large process. All services are part of the kernel and can communicate directly.
    • Advantages: Fast (direct function calls), efficient, less context switching.
    • Disadvantages: Large codebase, debugging difficult, system crash if one service fails, poor maintainability, security risk.
    • Examples: Traditional Unix, Linux, MS-DOS.

    2. Layered Kernel:
    OS is organized in layers, each providing services to the layer above and using services of the layer below. Layer 0 is hardware, top layer is user interface.
    • Advantages: Easy to debug and verify, simpler construction, modular.
    • Disadvantages: Overhead of layer transitions, difficult to define layers properly, less efficient.
    • Examples: THE (Dijkstra), VAX/VMS.

    3. Modular Kernel:
    OS core is minimal. Modules (like device drivers, file systems) are loaded dynamically as needed. Combines benefits of monolithic (speed) and microkernel (modularity).
    • Advantages: Flexible, faster than microkernel, easy to add features.
    • Disadvantages: Module management complexity, potential instability from buggy modules.
    • Examples: Modern Linux (Loadable Kernel Modules - LKMs), Solaris.

    4. Microkernel:
    Only essential functions (IPC, basic scheduling, memory management) run in kernel mode. All other services (file systems, device drivers) run as user-space processes. Communication via message passing.
    • Advantages: Highly stable (crash in one service doesn't crash OS), extensible, portable, secure.
    • Disadvantages: Performance overhead (message passing, context switches), larger memory footprint.
    • Examples: Mach (macOS), Minix, QNX, L4.

    5. Hybrid Kernel:
    Combines speed of monolithic with modularity of microkernel. Some services in kernel space for speed, others in user space for stability.
    • Advantages: Balanced performance and stability.
    • Disadvantages: Complexity of design.
    • Examples: Windows NT (NT Kernel), macOS XNU (XNU = Mach + BSD).

    Detailed Comparison Table:
    AspectMonolithicLayeredModularMicrokernelHybrid
    Kernel SizeLargeMediumSmall coreVery SmallMedium
    PerformanceHighLowHighLowMedium-High
    StabilityLowMediumMediumHighHigh
    ExtensibilityPoorPoorGoodExcellentGood
    DebuggingDifficultEasyModerateEasyModerate
    SecurityLowMediumMediumHighMedium-High
    PortabilityLowLowMediumHighMedium
    ExamplesLinux, UnixTHEModern LinuxMinix, QNXWindows NT, XNU
  3. Explain Virtual Machines in detail. Discuss their types, benefits, and implementation. Also explain system calls and their role in OS. [2022]

    Virtual Machines:
    A VM is a software emulation of a computer system that runs programs as if they were on a real machine. The VMM (Virtual Machine Monitor) or Hypervisor manages VMs and provides the virtualized hardware interface.

    Key Concepts:
    (1) Abstraction: VM provides the same interface regardless of underlying hardware.
    (2) Isolation: Each VM is isolated from others — a crash in one doesn't affect others.
    (3) Emulation: VMM translates VM instructions to host machine instructions.

    Types of Virtualization:
    (1) Full Virtualization: Complete hardware virtualization. Guest OS runs unmodified. VMM intercepts privileged instructions. Examples: VMware Workstation, Oracle VirtualBox.
    (2) Paravirtualization: Guest OS is modified to work with VMM. Hypercalls replace privileged instructions. Better performance. Examples: Xen, UML.
    (3) Hardware-Assisted Virtualization: CPU provides virtualization support (Intel VT-x, AMD-V). Eliminates need for binary translation. Examples: KVM, Hyper-V.

    Benefits of VMs:
    • Server consolidation (multiple servers on one physical machine).
    • Testing and development environments.
    • OS migration and legacy support.
    • Disaster recovery and snapshots.
    • Security isolation (sandboxing).

    System Calls:
    System calls are the interface between user programs and the OS kernel. When a user program needs OS services, it executes a system call, which transfers control to the kernel. Common system call categories:
    (1) fork() - Create a new process
    (2) open()/close()/read()/write() - File operations
    (3) wait() - Wait for child process
    (4) exit() - Terminate process
    (5) signal() - Send signals to processes
    (6) pipe()/socket() - Inter-process communication
    (7) kill() - Terminate a process
    (8) exec() - Replace process image

    System calls are typically invoked using software interrupts (trap instructions), which switch the CPU from user mode to kernel mode.
02

Process Management

Process Concept · PCB · Process States · Scheduling Queues · Schedulers · Context Switch · Threads · CPU Scheduling Algorithms · Scheduling Criteria · Starvation & Aging

Quick Revision: Process = program in execution. PCB stores process info. States: New→Ready→Running→Waiting→Terminated. Schedulers: Long-term (admission rate), Short-term (CPU dispatch), Medium-term (swapping). Threads: User (app-level) vs Kernel (OS-managed). Models: Many-to-One, One-to-One, Many-to-Many. CPU Scheduling: FCFS (non-preemptive), SJF (optimal), Priority (starvation possible), Round Robin (time quantum). Criteria: CPU Util, Throughput, Turnaround, Waiting, Response Time. Starvation → Aging solution.

Unit 2 — 1 Mark Questions 1M

  1. What is a Process?
    A Process is a program in execution. It is an active entity that needs resources like CPU time, memory, I/O devices, and files to accomplish its task.
  2. What is a Process Control Block (PCB)?
    PCB is a data structure maintained by the OS for each process, containing: Process ID, State, Program Counter, CPU Registers, Memory Management info, Scheduling info, I/O status, Accounting info.
  3. What are the different process states?
    New: Process is being created.
    Ready: Process is ready to run, waiting for CPU.
    Running: Instructions are being executed.
    Waiting/Blocked: Process waiting for I/O or event.
    Terminated/Exit: Process has finished execution.
  4. What is a Context Switch?
    Context switch is the process of saving the state (context) of the currently running process and loading the saved state of the next process to run. It adds overhead to the system.
  5. What is a Thread?
    A Thread is the smallest unit of CPU utilization. It is a lightweight process within a process, sharing the process's code, data, and files but having its own program counter, registers, and stack.
  6. Differentiate between User-Level and Kernel-Level Threads.
    User-Level Threads: Managed by user-space thread library, OS sees only one process. Fast creation, kernel is unaware, entire process blocks if one thread blocks.
    Kernel-Level Threads: Managed by OS kernel. Slow creation, kernel can schedule threads independently, one thread blocking doesn't affect others.
  7. What are the different multithreading models?
    Many-to-One: Many user threads mapped to one kernel thread. (e.g., Green Threads)
    One-to-One: Each user thread maps to one kernel thread. (e.g., Linux, Windows)
    Many-to-Many: Many user threads multiplexed to many kernel threads. (Best of both worlds)
  8. What is CPU Scheduling?
    CPU Scheduling is the mechanism by which the OS selects a process from the ready queue to execute on the CPU when the CPU becomes idle.
  9. What are the different types of schedulers?
    Long-term Scheduler (Job Scheduler): Selects processes from disk (spool) to memory. Controls degree of multiprogramming. Invoked infrequently.
    Short-term Scheduler (CPU Scheduler): Selects process from ready queue to execute. Invoked frequently (milliseconds).
    Medium-term Scheduler (Swapper): Swaps processes between memory and disk. Can temporarily remove a process from memory (swapping out) to reduce multiprogramming.
  10. What is Starvation and Aging?
    Starvation: Low-priority processes never get CPU time because high-priority processes keep arriving.
    Aging: Solution to starvation — gradually increase the priority of waiting processes so they eventually get CPU time.
  11. What is Preemptive vs Non-preemptive Scheduling?
    Preemptive: OS can forcibly take CPU from a running process (e.g., Round Robin, SRTF).
    Non-preemptive: Process voluntarily releases CPU (e.g., FCFS, SJF non-preemptive).
  12. Define Throughput and Turnaround Time.
    Throughput: Number of processes completed per unit time.
    Turnaround Time: Time from process submission to completion = Completion Time - Arrival Time.
  13. What is Burst Time and Arrival Time?
    Burst Time: CPU time required by a process for execution.
    Arrival Time: Time at which a process enters the ready queue.
  14. What is the Dispatcher?
    The Dispatcher is the module that gives control of the CPU to the process selected by the short-term scheduler. Functions: Context switch, Switching to user mode, Jumping to the proper location in the program.

Unit 2 — 5 Mark Questions 5M

  1. Explain Process Scheduling Queues and the role of schedulers. [2022]
    Process Scheduling Queues:
    (1) Job Queue: Contains all processes in the system (on disk waiting for admission).
    (2) Ready Queue: Contains all processes in main memory that are ready to execute. New processes enter here.
    (3) Device Queue: Contains processes waiting for I/O devices (disk queue, printer queue).

    Schedulers:
    (1) Long-term Scheduler (Job Scheduler): Selects processes from the job queue and loads them into memory for execution. Controls the degree of multiprogramming. Invoked infrequently (seconds/minutes).

    (2) Short-term Scheduler (CPU Scheduler): Selects a process from the ready queue and dispatches it to the CPU. Invoked frequently (milliseconds). Performance is critical.

    (3) Medium-term Scheduler (Swapper): Removes processes from memory and stores them on disk (swapping out) to reduce multiprogramming, and swaps them back (swapping in) later. Used in time-sharing systems.
  2. Explain Threads in detail. Compare User-Level and Kernel-Level threads. Explain multithreading models. [2023]
    A Thread is the basic unit of CPU utilization. It has its own Thread ID, Program Counter, Register Set, and Stack, but shares the Code, Data, and OS Resources with other threads in the same process.

    Benefits of Threads:
    • Responsiveness: One thread can continue while others block.
    • Resource Sharing: Threads share code, data, files efficiently.
    • Economy: Creating a thread is cheaper than creating a process (less memory, faster context switch).
    • Scalability: Can use multiple CPUs in multiprocessor systems.

    User-Level Threads (ULT):
    Managed by a thread library in user space (Green threads). OS kernel is unaware of threads. Thread management done without kernel intervention. Blocking one thread blocks entire process. Examples: Green threads in Java, POSIX Pthreads.

    Kernel-Level Threads (KLT): Managed directly by the OS kernel. Thread operations require system calls. OS can schedule threads independently. One thread blocking doesn't block others. Examples: Linux (clone/pthreads), Windows Threads, Solaris.

    Multithreading Models:
    (1) Many-to-One: Many user threads → one kernel thread. Entire process blocks if one thread makes a blocking system call. No parallelism on multiprocessors.
    (2) One-to-One: Each user thread → one kernel thread. Full parallelism, no blocking of others. More overhead but better performance.
    (3) Many-to-Many: m user threads → n kernel threads. Best of both. Provides parallelism while reducing overhead.
  3. Explain CPU Scheduling Criteria in detail.
    (1) CPU Utilization: Keep CPU as busy as possible. Ideal = 100%. Typical range = 40-90%.

    (2) Throughput: Number of processes completed per unit time. Measures system capacity.

    (3) Turnaround Time: Time from process arrival to completion. = Completion Time - Arrival Time. Includes actual execution + waiting + I/O time.

    (4) Waiting Time: Total time spent in the ready queue waiting for CPU. Not including actual execution or I/O time. Minimizing waiting time is a key scheduling goal.

    (5) Response Time: Time from request submission to first response produced. Important for interactive/time-sharing systems. First response, not full output.

    Summary:
    CriterionDescriptionMinimize/Maximize
    CPU Utilization% of time CPU is busyMaximize
    ThroughputProcesses completed per unit timeMaximize
    Turnaround TimeArrival to completionMinimize
    Waiting TimeTime in ready queueMinimize
    Response TimeFirst response timeMinimize
  4. Explain FCFS and SJF CPU Scheduling algorithms with examples.
    FCFS (First Come First Served):
    Simplest scheduling algorithm. Processes are executed in order of arrival (FIFO queue). Non-preemptive. Convoy effect: short processes wait behind long ones.

    Example FCFS:
    Processes: P1(BT=24), P2(BT=3), P3(BT=3). Arrival: P1=0, P2=1, P3=2.
    Gantt: | P1(0-24) | P2(24-27) | P3(27-30) |
    Avg. Waiting Time: P1=0, P2=23, P3=26. Average = 49/3 = 16.33 ms.
    Avg. Turnaround Time: P1=24, P2=26, P3=28. Average = 78/3 = 26 ms.

    SJF (Shortest Job First):
    Selects process with smallest burst time. Optimal (minimum average waiting time). Can be preemptive (SRTF) or non-preemptive. Requires knowledge of burst times.

    Example SJF (non-preemptive):
    Processes: P1(BT=7), P2(BT=4), P3(BT=1), P4(BT=4). All arrive at time 0.
    Sorted by BT: P3(1) → P2(4) → P4(4) → P1(7)
    Gantt: | P3(0-1) | P2(1-5) | P4(5-9) | P1(9-16) |
    Avg. Waiting Time: P3=0, P2=1, P4=5, P1=9. Average = 15/4 = 3.75 ms.
    Avg. Turnaround Time: P3=1, P2=5, P4=9, P1=16. Average = 31/4 = 7.75 ms.
  5. Explain Priority Scheduling and Round Robin Scheduling with examples. Discuss starvation and aging.
    Priority Scheduling:
    Each process is assigned a priority. Process with highest priority (smallest number) gets CPU first. Can be preemptive or non-preemptive. Problem: Starvation (low-priority processes may never get CPU). Solution: Aging (gradually increase priority of waiting processes).

    Example: Processes P1(Pri=2, BT=10), P2(Pri=1, BT=1), P3(Pri=3, BT=2). Gantt: P2(0-1) → P1(1-11) → P3(11-13).

    Round Robin (RR):
    Each process gets a fixed time quantum (typically 10-100 ms). Ready queue is a circular queue. After quantum expires, process is preempted and added to end of queue. Performance depends on quantum size — too large → FCFS behavior, too small → excessive context switching.

    Example RR: Processes: P1(BT=10), P2(BT=4), P3(BT=9). Quantum=3.
    Gantt: | P1(0-3) | P2(3-6) | P3(6-9) | P1(9-12) | P2(12-14) | P3(14-17) | P1(17-19) | P3(19-21) |
    P1 completion: 19, P2 completion: 14, P3 completion: 21.
    Avg. Turnaround: P1=19, P2=14, P3=21. Average = 54/3 = 18 ms.

    Starvation: Low-priority process waits indefinitely while higher-priority processes keep arriving.
    Aging: Incrementally increases priority of waiting processes (e.g., +1 every 15 minutes) so they eventually get CPU time.

Unit 2 — 15 Mark Questions 15M

  1. Explain CPU Scheduling Algorithms in detail — FCFS, SJF, SRTF, Priority, and Round Robin. Solve numerical problems for each. [2023, 2022, 2021]

    FCFS (First Come First Served):
    Simplest algorithm. Non-preemptive. FIFO order. Long average waiting time. Convoy effect.

    Numerical Example 1 (FCFS):
    Processes: P1 (AT=0, BT=6), P2 (AT=2, BT=4), P3 (AT=4, BT=2)
    Gantt Chart:
    | P1  |     P2     | P3  |
    0     6            10    12    16
              
    Waiting Time: P1=0, P2=4, P3=6. Avg WT = (0+4+6)/3 = 3.33 ms
    Turnaround Time: P1=6, P2=8, P3=12. Avg TAT = (6+8+12)/3 = 8.67 ms

    SJF (Shortest Job First) — Non-preemptive:
    Selects process with minimum burst time. Optimal for average waiting time. Requires burst time knowledge. Can be predicted using exponential averaging.

    Numerical Example 2 (SJF):
    Processes: P1 (AT=0, BT=7), P2 (AT=2, BT=4), P3 (AT=4, BT=1), P4 (AT=5, BT=4)
    At t=0: Only P1 available → P1 starts (0-7).
    At t=7: P2, P3, P4 available. Shortest = P3 (BT=1) → P3 runs (7-8).
    At t=8: P2 and P4 available. P2 (BT=4) → P2 runs (8-12).
    At t=12: P4 runs (12-16).

    Gantt: | P1(0-7) | P3(7-8) | P2(8-12) | P4(12-16) |
    Waiting Time: P1=0, P2=6, P3=3, P4=11. Avg WT = 20/4 = 5 ms
    Turnaround Time: P1=7, P2=8, P3=4, P4=11. Avg TAT = 30/4 = 7.5 ms

    SRTF (Shortest Remaining Time First) — Preemptive SJF:
    Process with shortest remaining time gets CPU. If new process has shorter BT, current process is preempted.

    Numerical Example 3 (SRTF):
    Processes: P1 (AT=0, BT=8), P2 (AT=1, BT=4), P3 (AT=2, BT=2), P4 (AT=3, BT=1)
    t=0: P1 starts (remaining=8)
    t=1: P2 arrives (BT=4 < remaining P1=7) → P1 preempted, P2 runs
    t=2: P3 arrives (BT=2 < remaining P2=3) → P2 preempted, P3 runs (2-4)
    t=3: P4 arrives (BT=1 < remaining P3=1) → P3 preempted, P4 runs (3-4)
    t=4: P3 resumes (4-6), then P2 (6-10), then P1 (10-18)

    Gantt: | P1(0-1) | P2(1-2) | P4(3-4) | P3(4-6) | P2(6-10) | P1(10-18) |
    WT: P1=10, P2=3, P3=2, P4=0. Avg WT = 15/4 = 3.75 ms
    TAT: P1=18, P2=9, P3=4, P4=1. Avg TAT = 32/4 = 8 ms

    Priority Scheduling:
    Priority assigned to each process. Lower number = higher priority. Can cause starvation → solved by aging.

    Example: P1(Pri=2, BT=10), P2(Pri=1, BT=1), P3(Pri=3, BT=2).
    Gantt: | P2(0-1) | P1(1-11) | P3(11-13) |
    WT: P1=1, P2=0, P3=9. Avg WT = 3.33 ms
    TAT: P1=11, P2=1, P3=11. Avg TAT = 7.67 ms

    Round Robin (RR):
    Each process gets a time quantum. Circular queue. Context switch after quantum.

    Example: P1(BT=10), P2(BT=4), P3(BT=9). Quantum=3.
    Gantt: | P1(0-3) | P2(3-6) | P3(6-9) | P1(9-12) | P2(12-14) | P3(14-17) | P1(17-19) | P3(19-21) |
    Completion: P1=19, P2=14, P3=21
    TAT: P1=19, P2=14, P3=21. Avg TAT = 18 ms
    WT: P1=9, P2=10, P3=12. Avg WT = 31/3 = 10.33 ms
  2. Explain different process scheduling queues and schedulers. Explain the context switch overhead and dispatcher. [2021]

    Process Scheduling Queues:
    The OS maintains several queues for process scheduling:
    (1) Job Queue: Contains all processes in the system that have been submitted. Stored on disk waiting to be admitted to memory.
    (2) Ready Queue: Contains processes in memory that are ready and waiting to execute. Newly admitted processes enter here.
    (3) Device Queue: A separate queue for each I/O device. Contains processes waiting for that specific device.

    Schedulers:
    (1) Long-term Scheduler (Job Scheduler):
    • Selects processes from job queue and loads into memory.
    • Controls degree of multiprogramming (number of processes in memory).
    • Invoked infrequently (seconds or minutes).
    • Aims for good mix of I/O-bound and CPU-bound processes.

    (2) Short-term Scheduler (CPU Scheduler):
    • Selects a process from the ready queue and dispatches it to CPU.
    • Must be fast (< 10 ms) to avoid CPU idle time.
    • Invoked frequently (every 10-100 ms).

    (3) Medium-term Scheduler (Swapper):
    • Temporarily removes processes from memory (swapping out) to disk.
    • Swaps them back (swapping in) when memory is available.
    • Reduces degree of multiprogramming to handle memory pressure.

    Context Switch:
    When the CPU switches from executing one process to another, the OS must:
    (1) Save the state (context) of the current process: registers, program counter, stack pointer.
    (2) Load the saved state of the next process.
    (3) Update PCB and scheduling information.
    Context switch is pure overhead — no useful work is done. Speed depends on hardware support (special registers, tagged TLBs).

    Dispatcher:
    The dispatcher is the module that transfers control of the CPU to the selected process. It performs:
    (1) Context switch
    (2) Switch to user mode
    (3) Jump to the proper location in the user program
    Dispatch Latency is the time it takes for the dispatcher to stop one process and start another. Minimizing dispatch latency is important for real-time systems.
03

Process Synchronization & Deadlocks

Critical Section Problem · Race Condition · Synchronization Requirements · Peterson's Solution · Semaphores · Classical Problems · Deadlock Conditions · Prevention · Avoidance · Banker's Algorithm · Recovery

Quick Revision: Critical section = code accessing shared resources. Race condition = incorrect result from concurrent access. Requirements: Mutual Exclusion, Progress, Bounded Waiting. Peterson's solution = software solution for 2 processes. Semaphores: Binary (0/1) and Counting (integer). Classical problems: Producer-Consumer, Reader-Writer, Dining Philosophers. Deadlock conditions: ME, Hold & Wait, No Preemption, Circular Wait. Prevention = eliminate one condition. Avoidance = Banker's algorithm. Recovery = kill process/preempt resource.

Unit 3 — 1 Mark Questions 1M

  1. What is a Critical Section?
    A Critical Section is the portion of code in a process where shared variables or resources are accessed. Only one process should be allowed to execute in its critical section at a time.
  2. What is a Race Condition?
    A Race Condition occurs when multiple processes access and manipulate shared data concurrently, and the outcome depends on the order of execution, leading to unpredictable results.
  3. What are the three requirements for solving the Critical Section Problem?
    (1) Mutual Exclusion: Only one process can be in critical section at a time.
    (2) Progress: If no process is in critical section and some want to enter, the decision must be made quickly.
    (3) Bounded Waiting: A process waiting to enter CS must eventually get access (no starvation).
  4. What is Peterson's Solution?
    Peterson's Solution is a software-based algorithm for mutual exclusion in the critical section problem for two processes. Uses two shared variables: flag[i] (process i wants to enter) and turn (whose turn it is). Works for two processes only.
  5. What is a Semaphore?
    A Semaphore is a synchronization variable (integer variable) used to solve the critical section problem. It supports two atomic operations: wait() (P) and signal() (V).
  6. What are the types of Semaphores?
    Binary Semaphore (Mutex): Value is 0 or 1. Used for mutual exclusion.
    Counting Semaphore: Value can be any non-negative integer. Used for counting resources (e.g., counting available printers).
  7. What are the Classical Synchronization Problems?
    (1) Producer-Consumer Problem: Producer produces items, consumer consumes them through a bounded buffer.
    (2) Reader-Writer Problem: Multiple readers can read simultaneously, but only one writer can write at a time.
    (3) Dining Philosophers Problem: N philosophers alternate between thinking and eating, sharing N forks (chopsticks).
  8. What is Deadlock?
    A Deadlock is a situation where a set of processes are blocked because each process holds a resource and waits for another resource held by another process in the set.
  9. State the four necessary conditions for Deadlock.
    (1) Mutual Exclusion: Only one process can use a resource at a time.
    (2) Hold and Wait: Process holds resources and requests new ones.
    (3) No Preemption: Resources cannot be forcibly taken away.
    (4) Circular Wait: Circular chain of processes, each waiting for resource held by next process.
  10. What are the four approaches to handle Deadlocks?
    (1) Deadlock Prevention: Ensure at least one necessary condition never holds.
    (2) Deadlock Avoidance: OS decides dynamically whether to grant resource requests (Banker's Algorithm).
    (3) Deadlock Detection & Recovery: Allow deadlocks, detect them, then recover.
    (4) Deadlock Ignorance: Pretend deadlocks never occur (used by Unix, Windows).

Unit 3 — 5 Mark Questions 5M

  1. Explain the Critical Section Problem and its requirements. Explain Peterson's Solution for two processes. [2022, 2021]
    Critical Section Problem:
    The problem of designing a protocol for cooperating processes to share data so that data consistency is maintained. Each process has a Critical Section (CS) — the code segment where shared data is accessed. Only one process should execute in its CS at a time.

    Requirements:
    (1) Mutual Exclusion: If process P1 is in CS, no other process can be in its CS.
    (2) Progress: If no process is in CS and some want to enter, the decision must not be postponed indefinitely.
    (3) Bounded Waiting: There is a limit on how many times other processes can enter CS after a process requests entry.

    Peterson's Solution (for 2 processes):
    Uses two shared variables: flag[i] (boolean, indicates process i wants to enter CS) and turn (indicates whose turn it is).

    // Shared variables:
    boolean flag[2];  // Initially false
    int turn;          // 0 or 1
    
    // Process i (other process is j=1-i):
    do {
        flag[i] = true;
        turn = j;
        while (flag[j] && turn == j);  // Wait
    
        // Critical Section
    
        flag[i] = false;
    
        // Remainder Section
    } while (true);
              
    How it works:
    A process sets its flag to true (wants to enter), gives turn to the other, then waits only if the other also wants to enter AND it's the other's turn. This ensures mutual exclusion, progress, and bounded waiting. Limited to 2 processes only.
  2. Explain Semaphores in detail with types. Solve the Producer-Consumer problem using semaphores. [2023]
    Semaphore: A synchronization primitive — an integer variable accessed only through two atomic operations: wait(S) (P) and signal(S) (V).

    wait(S): Decrements S. If S becomes negative, process blocks.
    signal(S): Increments S. If S ≤ 0, wake up a blocked process.

    Types:
    (1) Binary Semaphore (Mutex): Value 0 or 1. Used for mutual exclusion. Also called Mutex Lock.
    (2) Counting Semaphore: Integer ≥ 0. Can take any non-negative value. Used to control access to resources with multiple instances.

    Producer-Consumer Problem using Semaphores:
    Problem: Producer produces items, puts them in buffer. Consumer takes items from buffer. Buffer has finite size. Need synchronization to avoid overproduction/underproduction.

    semaphore mutex = 1;       // Mutual exclusion for buffer access
    semaphore empty = n;       // Number of empty slots in buffer
    semaphore full = 0;        // Number of filled slots in buffer
    int buffer[n];             // Shared circular buffer
    int in = 0, out = 0;      // Buffer indices
    
    // Producer Process:
    do {
        // Produce an item
        item = produce_item();
    
        wait(empty);           // Wait for empty slot
        wait(mutex);           // Enter critical section
    
        buffer[in] = item;
        in = (in + 1) % n;
    
        signal(mutex);         // Exit critical section
        signal(full);          // Signal one item available
    } while (true);
    
    // Consumer Process:
    do {
        wait(full);            // Wait for item to consume
        wait(mutex);           // Enter critical section
    
        item = buffer[out];
        out = (out + 1) % n;
    
        signal(mutex);         // Exit critical section
        signal(empty);         // Signal one empty slot
    
        // Consume the item
        consume_item(item);
    } while (true);
              
    Explanation:
    empty semaphore ensures producer doesn't overflow buffer.
    full semaphore ensures consumer doesn't underflow buffer.
    mutex ensures mutual exclusion for buffer access.
  3. Explain the Reader-Writer Problem with solutions.
    Problem: Multiple processes want to access a shared data file. Readers only read (no modification). Writers both read and write. Constraints:
    • Any number of readers can read simultaneously.
    • Only one writer can write at a time.
    • No reader and writer can be in CS simultaneously.

    Reader's Priority Solution:
    First reader locks the mutex. Subsequent readers increment read_count. Last reader releases rw_mutex. Writer uses rw_mutex.

    Problem: Writers may starve if readers keep coming.

    Writer's Priority Solution:
    Writer gets priority over readers. A service_queue mutex ensures FIFO order. Reader waits for both its turn and no pending writers.

    Fair Solution (Third Readers-Writers Problem):
    Neither readers nor writers starve. Each gets a fair chance. Uses a queue-based semaphore approach.
  4. Explain the Dining Philosophers Problem and its solution using semaphores. [2021]
    Problem: N philosophers sit around a circular table. Each philosopher alternates between thinking and eating. To eat, a philosopher needs two chopsticks (forks) — the one on left and right. There are N chopsticks, one between each pair of philosophers.

    Solution using Semaphores:
    Each chopstick is a semaphore (value 1). Philosopher i picks up left fork, then right fork, eats, puts both down.

    semaphore chopstick[5];   // One semaphore per chopstick
    
    void philosopher(int i) {
        do {
            think();
    
            wait(chopstick[i]);        // Pick up left chopstick
            wait(chopstick[(i+1)%5]);  // Pick up right chopstick
    
            eat();
    
            signal(chopstick[i]);        // Put down left chopstick
            signal(chopstick[(i+1)%5]);  // Put down right chopstick
        } while (true);
    }
              
    Deadlock possibility: If all philosophers pick up left fork simultaneously, all wait for right fork → deadlock!

    Solutions to prevent deadlock:
    (1) Allow at most N-1 philosophers to sit at the table.
    (2) Odd-numbered philosophers pick up left then right; even-numbered pick up right then left.
    (3) One philosopher picks up forks in reverse order (right first, then left).

Unit 3 — 15 Mark Questions 15M

  1. Explain Deadlock in detail. State and explain the four necessary conditions for deadlock. Explain Deadlock Prevention, Avoidance, Detection & Recovery approaches in detail. [2023, 2022, 2021]

    What is Deadlock?
    A deadlock is a situation where a set of processes are blocked because each process holds a resource and waits for another resource held by another process in the set. No process can proceed until some other process releases a needed resource.

    Example: Two processes P1 and P2, two resources R1 and R2. P1 holds R1, waits for R2. P2 holds R2, waits for R1. Neither can proceed — deadlock.

    Four Necessary Conditions (ALL must hold simultaneously):
    (1) Mutual Exclusion: Only one process can use a resource at a time. At least one resource must be non-sharable.
    (2) Hold and Wait: A process holding at least one resource is waiting to acquire additional resources held by other processes.
    (3) No Preemption: Resources cannot be forcibly taken away from a process; they must be released voluntarily.
    (4) Circular Wait: There exists a circular chain of processes {P1, P2, ..., Pn} where P1 waits for resource held by P2, P2 waits for resource held by P3, ..., Pn waits for resource held by P1.

    Approaches to Handle Deadlock:

    1. Deadlock Prevention:
    Ensure at least one of the four necessary conditions never holds.
    • Mutual Exclusion: Make resources sharable (not possible for all resources).
    • Hold and Wait: Require processes to request all resources at once (all-or-none). Low resource utilization.
    • No Preemption: Allow OS to preempt resources from processes (e.g., suspend, save state, reallocate).
    • Circular Wait: Impose ordering on resources. Processes must request resources in increasing order. Eliminates circular chain.

    2. Deadlock Avoidance:
    OS examines resource allocation state dynamically to ensure no circular wait can occur. Requires advance knowledge of maximum resource needs. Uses Banker's Algorithm. Suitable only when number of processes and resources is small.

    3. Deadlock Detection & Recovery:
    Allow deadlocks to occur, then detect and recover.
    • Detection: Use Resource Allocation Graph + Reduction algorithm, or Banker's Safety algorithm extended.
    • Recovery: (a) Process termination (abort all deadlocked or one-by-one), (b) Resource Preemption (select victim, rollback).

    4. Deadlock Ignorance (Ostrich Algorithm):
    Assume deadlocks never occur. Most OS (Unix, Linux, Windows) use this because deadlocks are rare and prevention/avoidance is expensive. If deadlock occurs, system is rebooted.
  2. Explain Banker's Algorithm in detail. Solve a complete numerical example with safety algorithm. [2023, 2022]

    Banker's Algorithm:
    A deadlock avoidance algorithm proposed by Dijkstra. Works like a bank: the OS acts as a banker. Each process must declare maximum resource needs. The OS only grants a request if the system remains in a safe state after allocation.

    Data Structures:
    (1) Available[m]: Available instances of each resource type.
    (2) Max[n][m]: Maximum demand of each process.
    (3) Allocation[n][m]: Current allocation to each process.
    (4) Need[n][m]: Remaining needs. Need = Max - Allocation.

    Safety Algorithm:
    (1) Initialize Work = Available, Finish[i] = false for all i.
    (2) Find i such that: Finish[i] = false AND Need[i] ≤ Work.
    (3) If found: Work = Work + Allocation[i], Finish[i] = true, go to step 2.
    (4) If Finish[i] = true for all i → System is SAFE. Else → UNSAFE (may deadlock).

    Resource Request Algorithm:
    (1) If Request[i] ≤ Need[i]: proceed. Else → Error (exceeds maximum).
    (2) If Request[i] ≤ Available: pretend to allocate and run Safety Algorithm. Else → Process must wait.

    Complete Numerical Example:
    Given: 5 Processes (P0-P4), 3 Resource types (A, B, C).
    Allocation Matrix:
             A  B  C
      P0   0  1  0
      P1   2  0  0
      P2   3  0  2
      P3   2  1  1
      P4   0  0  2

    Max Matrix:
             A  B  C
      P0   7  5  3
      P1   3  2  2
      P2   9  0  2
      P3   2  2  2
      P4   4  3  3

    Available = (3, 3, 2)

    Need Matrix (Max - Allocation):
             A  B  C
      P0   7  4  3
      P1   1  2  2
      P2   6  0  0
      P3   0  1  1
      P4   4  3  1

    Safety Algorithm Execution:
    Work = (3, 3, 2), Finish = [F,F,F,F,F]

    Step 1: Find process with Need ≤ Work:
      P1: Need=(1,2,2) ≤ (3,3,2) ✓
      Work = (3,3,2) + Allocation(P1)=(2,0,0) = (5,3,2)
      Finish[P1] = T

    Step 2: Check remaining:
      P3: Need=(0,1,1) ≤ (5,3,2) ✓
      Work = (5,3,2) + Allocation(P3)=(2,1,1) = (7,4,3)
      Finish[P3] = T

    Step 3:
      P4: Need=(4,3,1) ≤ (7,4,3) ✓
      Work = (7,4,3) + Allocation(P4)=(0,0,2) = (7,4,5)
      Finish[P4] = T

    Step 4:
      P0: Need=(7,4,3) ≤ (7,4,5) ✓
      Work = (7,4,5) + Allocation(P0)=(0,1,0) = (7,5,5)
      Finish[P0] = T

    Step 5:
      P2: Need=(6,0,0) ≤ (7,5,5) ✓
      Work = (7,5,5) + Allocation(P2)=(3,0,2) = (10,5,7)
      Finish[P2] = T

    All processes Finish = TRUE → System is SAFE.
    Safe Sequence: P1 → P3 → P4 → P0 → P2

    Resource Request Example:
    If P1 requests (1, 0, 2):
    • Request ≤ Need(P1)=(1,2,2) ✓
    • Request ≤ Available=(3,3,2) ✓
    • New Available = (2,3,0). Run Safety Algorithm → UNSAFE.
      Work = (2,3,0). P3 needs (0,1,1) — C check: 1 ≤ 0? NO. Cannot proceed.
      Granting P1's request would leave insufficient resources for others → Request DENIED.
04

Memory Management

Memory Hierarchy · Memory Allocation · Fragmentation · Paging · Page Table · TLB · Segmentation · Virtual Memory · Demand Paging · Page Replacement Algorithms · Thrashing · Working Set Model

Quick Revision: Memory Hierarchy: Registers → Cache → RAM → Disk. Fixed/Variable partitioning. Internal/External fragmentation. Paging: divide into fixed-size pages/frames. Page table maps page # to frame #. TLB caches page table entries. Segmentation: variable-length logical segments. Virtual Memory: Demand paging + page replacement. Page replacement: FIFO (Belady's anomaly), OPTIMAL (theoretical), LRU (practical). Thrashing: too many page faults → CPU utilization drops. Working Set Model prevents thrashing. Page Fault Frequency (PFF) approach.

Unit 4 — 1 Mark Questions 1M

  1. What is Memory Management?
    Memory Management is the OS function responsible for managing the computer's primary memory. It keeps track of which parts of memory are being used and by whom, decides which process gets memory, and deallocates memory when no longer needed.
  2. What is the Memory Hierarchy?
    Registers → L1 Cache → L2 Cache → L3 Cache → Main Memory (RAM) → SSD → HDD. Each level is slower but larger than the previous. OS manages virtual memory to extend the illusion of more RAM.
  3. What is Internal Fragmentation?
    Internal Fragmentation occurs when fixed-size memory blocks are allocated to processes, and the unused portion within the allocated block is wasted. Occurs in fixed partitioning and paging.
  4. What is External Fragmentation?
    External Fragmentation occurs when enough total memory exists to satisfy a request, but it is not contiguous. Occurs in variable partitioning. Solved by Compaction (relocating processes to make one large free block) or Paging.
  5. What is Paging?
    Paging is a memory management scheme that divides physical memory into fixed-size blocks called frames, and logical memory into blocks of the same size called pages. The OS maps pages to frames using a page table. Eliminates external fragmentation.
  6. What is a Page Table?
    A Page Table is a data structure that maps each logical page number to its physical frame number. Stored in memory. Each process has its own page table.
  7. What is a TLB (Translation Lookaside Buffer)?
    TLB is a small, fast associative cache in the MMU that stores recently used page table entries. If the page number is found in TLB (TLB hit), physical address is found quickly. If not (TLB miss), the page table in memory is accessed.
  8. What is Segmentation?
    Segmentation divides logical memory into variable-size segments (code, data, stack, heap). Each segment has a name and length. A segment table maps segment number to base address and limit. Better reflects programmer's view of memory than paging.
  9. What is Virtual Memory?
    Virtual Memory is a memory management technique that gives processes the illusion of having more memory than physically available. It uses demand paging (load pages only when needed) and page replacement (swap out pages when memory is full).
  10. What is a Page Fault?
    A Page Fault occurs when a process accesses a page that is not in physical memory (not in RAM). The OS must bring the page from disk into memory, which causes significant overhead (milliseconds vs nanoseconds for RAM).
  11. What is Demand Paging?
    Demand Paging is a technique where pages are loaded into memory only when they are needed (on demand), not all at once. A "lazy swapper" loads pages on demand. Reduces initial load time and memory usage.
  12. What is Thrashing?
    Thrashing occurs when a process spends more time swapping pages in and out of memory than executing. Happens when the degree of multiprogramming is too high. Causes CPU utilization to drop dramatically.
  13. What is Belady's Anomaly?
    Belady's Anomaly is the counter-intuitive phenomenon where increasing the number of page frames can increase the number of page faults (for FIFO page replacement).
  14. What is the Working Set Model?
    The Working Set Model approximates the set of pages a process needs to keep in memory to avoid thrashing. The OS monitors the working set of each process and ensures it stays in memory. Used for dynamic allocation of frames.
  15. What is Page Fault Frequency (PFF)?
    PFF approach monitors the rate of page faults for each process. If page fault rate is too high → allocate more frames (thrashing risk). If too low → remove frames (memory waste). Adjusts allocation dynamically.

Unit 4 — 5 Mark Questions 5M

  1. Explain Paging in detail with an example. Explain Page Table and TLB. [2023, 2022]
    Paging: Physical memory is divided into fixed-size blocks called frames (typically 4KB to 4MB). Logical memory is divided into blocks of the same size called pages. A page table maps page numbers to frame numbers. No external fragmentation, but internal fragmentation may occur.

    Address Translation:
    Logical Address = Page Number (p) + Page Offset (d)
    Physical Address = Frame Number (f) + Page Offset (d)

    Example: Logical address space = 2^16 = 64KB, Page size = 4KB (2^12).
    Number of pages = 64KB/4KB = 16. Page number = 4 bits, Offset = 12 bits.
    Physical memory = 32KB = 8 frames. Frame number = 3 bits.
    Logical address 7174 (binary: 0001 1100 0100 0110):
      Page # = 0001 = 1, Offset = 100 0010 0110
    If page 1 is at frame 5: Physical address = 101 100 0010 0110 = 5 × 4096 + 718 = 26,998

    Page Table: Array of frame numbers indexed by page number. Each entry: Valid bit, Frame number, Protection bits, Modified bit, Reference bit.

    TLB (Translation Lookaside Buffer):
    Special cache for page table entries. Stores (Page #, Frame #) pairs. If TLB hit → fast translation. If TLB miss → access memory page table. Effective Memory Access Time (EMAT) = (1-α) × m + α × (m + m) + m = m + α × m, where α = TLB hit ratio, m = memory access time.
  2. Explain Segmentation and Paged Segmentation. [2021]
    Segmentation:
    Logical memory is divided into variable-size segments based on logical units: Code segment, Data segment, Stack segment, Heap segment. Each segment has a segment number and offset within the segment. A segment table maps each segment to base physical address and limit (length).

    Advantages: Reflects programmer's view of memory, allows sharing of code segments, enables protection at segment level.
    Disadvantages: External fragmentation, variable-size allocation overhead.

    Paged Segmentation (Segmented Paging):
    Combines benefits of both paging and segmentation. Each segment is divided into pages. Each segment has its own page table. Logical address = Segment Number + Page Number within Segment + Offset.

    Structure:
    • Segment Table: Each entry points to a Page Table for that segment.
    • Page Table: Maps page number to frame number within the segment.
    • Offset: Displacement within the page.

    Advantages: No external fragmentation, logical view of memory, memory protection at segment level. Used in Intel 80386+ architecture.
  3. Explain Virtual Memory and Demand Paging. What is Thrashing and how is it prevented? [2022]
    Virtual Memory:
    A technique that separates user logical memory from physical memory. Only part of the program needs to be in memory for execution. Logical address space can be larger than physical memory. Implemented using Demand Paging and Page Replacement.

    Demand Paging:
    Pages are loaded only when they are needed (on demand). A valid-invalid bit in the page table indicates whether a page is in memory (valid) or on disk (invalid). When an invalid page is accessed → Page Fault → OS loads page from disk.

    Page Fault Service Time:
    (1) Trap to OS, save process state.
    (2) Check if page reference is valid (legal address).
    (3) Find free frame (or use page replacement).
    (4) Read page from disk into frame.
    (5) Update page table.
    (6) Restart process.
    Effective Access Time = (1-p) × m + p × (page_fault_time + m), where p = page fault rate.

    Thrashing:
    Occurs when the degree of multiprogramming is too high, causing each process to have fewer frames than its working set. Result: constant page faults, CPU spends most time swapping pages. CPU utilization drops to near zero.

    Prevention of Thrashing:
    (1) Working Set Model: Monitor working set of each process. Allocate enough frames for working set.
    (2) Page Fault Frequency (PFF): If PFF too high → allocate more frames. If PFF too low → remove frames.
    (3) Local vs Global Replacement: Local replacement (process replaces its own pages) prevents one process from thrashing from affecting others.
  4. Explain Page Replacement Algorithms with examples. [2023]
    When a page fault occurs and no free frame exists, the OS must replace an existing page. Page replacement algorithms decide which page to evict.

    FIFO (First-In First-Out):
    Oldest page in memory is replaced. Easy to implement. Suffers from Belady's Anomaly.

    Example FIFO: Reference string: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5. Frames = 3.
    Faults: 1,2,3,4,5,3,4,5 = 8 faults (with OPTIMAL, for comparison)
    FIFO with 3 frames: approximately 9 faults
    FIFO with 4 frames: approximately 10 faults (Belady's Anomaly!)

    OPTIMAL (OPT):
    Replace the page that will not be used for the longest time in the future. Theoretical minimum page faults. Requires future knowledge.
    Total Page Faults (OPT, 3 frames): 8

    LRU (Least Recently Used):
    Replace the page that has not been used for the longest time. Uses past behavior as approximation of future. Can be implemented using counters or stack. Low overhead.
    Total Page Faults (LRU, 3 frames): 9

    Summary (Reference string: 1,2,3,4,1,2,5,1,2,3,4,5, 3 frames):
    AlgorithmPage Faults
    FIFO~9
    OPTIMAL8
    LRU9
  5. Explain Frame Allocation strategies and Thrashing in detail.
    Frame Allocation:
    When a process needs frames, the OS must decide how many frames to allocate:

    (1) Equal Allocation: m frames divided equally among n processes. Each gets m/n frames.
    (2) Proportional Allocation: Frames allocated in proportion to process size. Process i gets (size_i / total_size) × m frames.
    (3) Priority Allocation: Proportional allocation considering priority. Higher-priority processes get more frames.

    Thrashing:
    Cause: Degree of multiprogramming too high → each process has fewer frames than its working set → constant page faults.

    How to Detect Thrashing:
    Monitor CPU utilization. If CPU utilization drops and page fault rate rises significantly → thrashing.

    Prevention:
    (1) Working Set Model: Track working set window (recent k references). Allocate enough frames for the working set. Δ (delta) is the working set size parameter.
    (2) Page-Fault Frequency (PFF): Define upper and lower bounds on page fault rate. If rate exceeds upper bound, allocate more frames. If below lower bound, deallocate frames.

    Recovery: If thrashing occurs, reduce degree of multiprogramming (swap out entire processes) to free frames.

Unit 4 — 15 Mark Questions 15M

  1. Explain Paging, Page Tables, and TLB in detail. Solve address translation problems with examples. [2023, 2022]

    Paging Mechanism:
    Physical memory is divided into fixed-size blocks called frames (size: power of 2, typically 4KB). Logical memory is divided into blocks of the same size called pages. Each page can be placed in any available frame. The OS maintains a page table for each process.

    Address Translation:
    The Memory Management Unit (MMU) translates logical addresses to physical addresses:
    (1) Page number (p) is looked up in the page table.
    (2) Page table returns the corresponding frame number (f).
    (3) Physical address = f × page_size + offset.

    Example 1:
    Page size = 4KB (2^12). Logical address = 16 bits. Physical memory = 32KB.
    Logical address has: 4 bits page number + 12 bits offset.
    Physical address has: 5 bits frame number + 12 bits offset.
    Given page table: Page 0 → Frame 5, Page 1 → Frame 6, Page 2 → Frame 4.
    Translate logical address 3728 (binary: 0000 1110 1011 1000):
      Page # = 0000 = 0, Offset = 1110 1011 1000 = 1848
      Frame # for page 0 = 5
      Physical address = 5 × 4096 + 1848 = 21,728 (binary: 101 0101 1001 1000)

    Example 2:
    Page size = 1KB (2^10). Logical address space = 64KB (16 bits).
    Page # = 6 bits, Offset = 10 bits.
    Given: Page 2 is at Frame 8. Logical address 3500.
      3500 = 0000 0011 0111 0100
      Page # = 0000 00 = 0, Offset = 11 0111 0100 = 500
      Frame 0 = Frame 3 (from page table)
      Physical = 3 × 1024 + 500 = 3572

    Page Table Structure:
    Each Page Table Entry (PTE) contains:
    (1) Frame Number: Physical frame where page resides.
    (2) Valid Bit: Indicates if page is in memory (1) or on disk (0).
    (3) Protection Bits: Read, Write, Execute permissions.
    (4) Modified (Dirty) Bit: Indicates if page has been modified since loaded.
    (5) Reference Bit: Indicates page has been accessed (for LRU).

    TLB (Translation Lookaside Buffer):
    A small, fast associative cache in the MMU that stores recently used (Page #, Frame #) pairs.

    Effective Memory Access Time (EMAT):
    With TLB: EMAT = (1-α) × 2m + α × m = m + α × m
    Where: α = TLB hit ratio, m = memory access time.

    Example: Memory access = 100 ns, TLB hit ratio = 98%.
    EMAT = 100 + 0.98 × 100 = 198 ns (vs 200 ns without TLB).
  2. Explain Page Replacement Algorithms in detail with worked numerical examples. Calculate page faults for FIFO, OPTIMAL, and LRU. Explain Belady's Anomaly. [2023, 2022, 2021]

    Page Replacement:
    When a page fault occurs and no free frame is available, the OS must replace an existing page. Page replacement algorithms decide which page to evict.

    FIFO (First-In First-Out):
    Oldest page in memory is replaced. Uses a queue. Easy to implement. Poor performance.

    Numerical Example 1 (FIFO):
    Reference String: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1
    Number of Frames = 3

    Step-by-step FIFO simulation:
    Ref  | F1 | F2 | F3 | Fault?
    7     | 7  |    |    | Y (new)
    0     | 7  | 0  |    | Y
    1     | 7  | 0  | 1  | Y
    2     | 2  | 0  | 1  | Y  (7 evicted - oldest)
    0     | 2  | 0  | 1  | N  (hit)
    3     | 2  | 3  | 1  | Y  (0 evicted)
    0     | 2  | 3  | 0  | Y  (1 evicted)
    4     | 4  | 3  | 0  | Y  (2 evicted)
    2     | 4  | 2  | 0  | Y  (3 evicted)
    3     | 4  | 2  | 3  | Y  (0 evicted)
    0     | 0  | 2  | 3  | Y  (4 evicted)
    3     | 0  | 2  | 3  | N  (hit)
    2     | 0  | 2  | 3  | N  (hit)
    1     | 1  | 2  | 3  | Y  (0 evicted)
    2     | 1  | 2  | 3  | N  (hit)
    0     | 0  | 2  | 3  | Y  (1 evicted)
    1     | 1  | 2  | 3  | Y  (0 evicted)
    7     | 7  | 2  | 3  | Y  (1 evicted)
    0     | 0  | 2  | 3  | Y  (7 evicted)
    1     | 1  | 2  | 3  | Y  (0 evicted)
    
    Total Page Faults (FIFO, 3 frames): 15
              

    OPTIMAL (OPT) — OPT:
    Replace the page whose next use is farthest in the future (or never used again).
    Total Page Faults (OPT, 3 frames): 9

    LRU (Least Recently Used):
    Replace the page that hasn't been used for the longest time.
    Total Page Faults (LRU, 3 frames): 12

    Belady's Anomaly:
    Increasing frames can increase page faults (for FIFO only).
    With 4 frames, FIFO might give MORE faults than with 3 frames.
    Optimal and LRU are stack algorithms — they never exhibit Belady's Anomaly.

    Page Fault Count Comparison (Reference String above):
    Algorithm3 Frames4 Frames
    FIFO1516 (Belady's Anomaly!)
    OPTIMAL98
    LRU1210
05

File Management & Disk Scheduling

File Concept · File Attributes · File Types · Access Methods · Directory Structure · File Allocation Methods · Free Space Management · Disk Structure · Disk Scheduling Algorithms · Head Movement Calculation

Quick Revision: File = named collection of related information. Attributes: name, type, size, location, protection, date/time. Access: Sequential, Direct/Random, Indexed. Directory structures: Single-level, Two-level, Tree/Acyclic, Cyclic, Graph/DAG. File allocation: Contiguous (fast, external frag), Linked (no external frag, slow access), Indexed (index block, supports direct access). Free space: Bitmap, Linked list, Grouping, Indexing. Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK.

Unit 5 — 1 Mark Questions 1M

  1. What is a File?
    A File is a named collection of related information stored on a secondary storage device (disk). It is the smallest unit of logical secondary storage.
  2. What are file attributes?
    Name, Identifier (unique number), Type (text/binary/executable), Location (pointer to file on device), Size, Protection (access control), Time, Date, User Identification.
  3. What are the types of files?
    (1) Text files: ASCII/Unicode characters (.txt, .c, .html)
    (2) Binary files: Binary data (.exe, .jpg, .pdf)
    (3) Source files: Program source code (.c, .java, .py)
    (4) Executable files: Machine code (.exe, .out, .elf)
  4. What are file access methods?
    (1) Sequential Access: Read/write in order (like tape).
    (2) Direct/Random Access: Read/write at any position (like disk).
    (3) Indexed Access: Use an index block to locate records (like databases).
  5. What is a Directory?
    A Directory is a file that contains the names and attributes of other files. It can also contain subdirectories. Each directory entry maps a filename to its file control block (FCB) / inode.
  6. Name different directory structures.
    (1) Single-Level, (2) Two-Level, (3) Tree Structure/Acyclic Graph, (4) Cyclic Graph, (5) General Graph.
  7. What is a Path Name?
    A path name is the location of a file or directory in the file system. Absolute path: from root (e.g., /home/user/file.txt). Relative path: from current directory (e.g., ../documents/file.txt).
  8. What are file allocation methods?
    (1) Contiguous: File occupies contiguous blocks on disk.
    (2) Linked: File blocks are linked via pointers (linked list).
    (3) Indexed: All pointers stored in an index block.
  9. What is a Disk Scheduling Algorithm?
    Disk Scheduling is the OS mechanism for deciding the order in which disk I/O requests are served, with the goal of minimizing seek time and improving disk throughput.
  10. What is Seek Time and Rotational Latency?
    Seek Time: Time for the disk head to move to the correct track/cylinder.
    Rotational Latency: Time for the desired sector to rotate to the head position (average = half a rotation).
    Transfer Time: Time to actually transfer data once head is at correct position.

Unit 5 — 5 Mark Questions 5M

  1. Explain different file access methods and directory structures in detail. [2022]
    File Access Methods:
    (1) Sequential Access: Information is processed in order. Most common (editors, compilers). Simulates tape. Operations: read next, write next, reset to beginning, skip n records.

    (2) Direct Access: File is a numbered sequence of blocks/records. Any block can be read/written directly using block number. Used by databases. Random access.

    (3) Indexed Access: Build an index structure for the file. Index block contains pointers to actual data blocks. Allows both sequential and random access. Used by databases and file systems (Unix i-node).

    Directory Structures:
    (1) Single-Level Directory: All files in one directory. Simple but no organization. Name collisions possible. Limited to one user.

    (2) Two-Level Directory: Each user has a separate user file directory (UFD) pointed to by a master file directory (MFD). Eliminates name collisions across users. Still no subdirectories.

    (3) Tree-Structured (Acyclic) Directory: Hierarchical tree. Each directory can have subdirectories and files. Path names: absolute (from root) or relative (from current). Supports grouping, search paths, current working directory. Examples: Unix, Windows.

    (4) Cyclic Graph Directory: Tree with shared files (subdirectories can appear in multiple parent directories). Allows file sharing via links.

    (5) General Graph Directory: Fully connected graph. Cycles possible. Need garbage collection or reference counting to handle deletion of shared files.
  2. Explain file allocation methods in detail. Compare Contiguous, Linked, and Indexed allocation. [2023, 2021]
    Contiguous Allocation:
    Each file occupies a set of contiguous blocks on the disk. Starting address and length (in blocks) are stored in the directory.
    • Advantages: Simple, supports direct access, fast sequential access (few seeks).
    • Disadvantages: External fragmentation, file size must be known in advance, difficult to grow files.

    Linked Allocation:
    Each file is a linked list of disk blocks scattered anywhere on the disk. Each block contains a pointer to the next block. Directory only stores address of first and last blocks.
    • Advantages: No external fragmentation, files can grow easily.
    • Disadvantages: No direct access (must traverse list), pointer overhead, reliability (broken pointer = lost file).
    • Variation: File Allocation Table (FAT) — all pointers in one table at the start of the volume.

    Indexed Allocation:
    All pointers to blocks of a file are stored in an Index Block. Directory stores address of the index block. Index block contains n pointers to n data blocks.
    • Advantages: Supports direct access, no external fragmentation.
    • Disadvantages: Overhead of index block (wasted space for small files).
    • Variations: Linked scheme (multiple index blocks), Multi-level index (Unix i-node), Combined scheme.

    Comparison Table:
    FeatureContiguousLinkedIndexed
    External FragmentationYesNoNo
    Direct AccessYesNoYes
    File GrowthDifficultEasyEasy
    OverheadMinimalPointer per blockIndex block
    ReliabilityHighLow (broken link)Medium
    Access SpeedFastSlowMedium
  3. Explain Disk Scheduling Algorithms with numerical examples. Calculate total head movement for each algorithm. [2023, 2022]
    Disk Structure:
    A disk surface consists of concentric tracks. Each track is divided into sectors. A cylinder is the set of tracks at the same radius across all platters. The read/write head moves between tracks (seek).

    FCFS (First Come First Served):
    Requests served in order of arrival. Simple, fair, but generally poor performance. No starvation.

    Numerical Example for All Algorithms:
    Disk has 200 tracks (0-199). Head starts at track 50.
    Request queue: 98, 183, 37, 122, 14, 124, 65, 67

    FCFS: 50 → 98 → 183 → 37 → 122 → 14 → 124 → 65 → 67
    Head movement: |98-50| + |183-98| + |37-183| + |122-37| + |14-122| + |124-14| + |65-124| + |67-65|
      = 48 + 85 + 146 + 85 + 108 + 110 + 59 + 2 = 643

    SSTF (Shortest Seek Time First):
    Serve the request closest to the current head position. Shortest seek first. Non-uniform wait, possible starvation.
    50 → 65 (15) → 67 (2) → 37 (30) → 14 (23) → 98 (84) → 122 (24) → 124 (2) → 183 (59)
    Total = 15+2+30+23+84+24+2+59 = 239

    SCAN (Elevator Algorithm):
    Head moves in one direction serving requests, then reverses at the end. Like an elevator.
    Direction: towards higher tracks first.
    50 → 65 → 67 → 98 → 122 → 124 → 183 → 199 → 37 → 14
    Movement: 15+2+31+24+2+59+16+162+23 = 354

    C-SCAN (Circular SCAN):
    Head moves in one direction serving requests, then jumps back to start without serving. More uniform wait time.
    50 → 65 → 67 → 98 → 122 → 124 → 183 → 199 → 0 → 14 → 37
    Movement: 15+2+31+24+2+59+16+199+14+23 = 385

    LOOK:
    Like SCAN but head only goes as far as the last request in each direction.
    50 → 65 → 67 → 98 → 122 → 124 → 183 → 37 → 14
    Movement: 15+2+31+24+2+59+146+23 = 302

    C-LOOK:
    Like C-SCAN but head only goes to extreme requests, then jumps back.
    50 → 65 → 67 → 98 → 122 → 124 → 183 → 14 → 37
    Movement: 15+2+31+24+2+59+169+23 = 325

    Summary (Total Head Movement):
    AlgorithmTotal Head Movement% of FCFS
    FCFS643100%
    SSTF23937.2%
    SCAN35455.1%
    C-SCAN38559.9%
    LOOK30247.0%
    C-LOOK32550.5%
  4. Explain Free Space Management techniques in detail. [2021]
    The OS must track which disk blocks are free and which are allocated. Techniques:

    (1) Bit Vector (Bitmap): Each block is represented by one bit. 0 = free, 1 = allocated. Simple, fast. Used in UNIX. Space = n/8 bytes for n blocks. Finding k consecutive free blocks requires scanning the bitmap.

    (2) Linked List: All free blocks are linked together in a linked list. First block contains a pointer to next free block, and the free space count. No bitmap needed but traversal is expensive. Used in MS-DOS FAT (chain of free blocks).

    (3) Grouping: First free block stores addresses of n-1 free blocks, plus a pointer to the next group of n free blocks. Combines linked list and bitmap advantages.

    (4) Indexing: Use an index block (like file indexing) where the first block of the group points to index blocks containing addresses of free blocks. Can find many free blocks quickly. Example: BSD UNIX uses 8192-bit (1024-block) index blocks.

    Comparison:
    MethodSpeedSpace OverheadComplexity
    BitmapFast scanLow (1 bit/block)Simple
    Linked ListSlow traversalLow (1 pointer/block)Simple
    GroupingMediumMediumMedium
    IndexingFastMediumComplex

Unit 5 — 15 Mark Questions 15M

  1. Explain Disk Scheduling Algorithms in detail. Solve numerical problems for FCFS, SSTF, SCAN, C-SCAN, LOOK, and C-LOOK. Discuss their performance comparison. [2023, 2022, 2021]

    Disk Structure:
    A magnetic disk consists of one or more platters. Each platter has two surfaces. Each surface has concentric tracks. Each track is divided into sectors (typically 512 bytes or 4KB). A cylinder is the set of tracks at the same radius on all surfaces. The disk head reads/writes data by moving across tracks.

    Disk Access Time = Seek Time + Rotational Latency + Transfer Time

    Algorithm Descriptions:
    (1) FCFS: Serve requests in arrival order. Simple, fair, but generally poor performance. No starvation.
    (2) SSTF: Serve request closest to current head position. Good performance but can cause starvation of outer/inner track requests.
    (3) SCAN: Head moves in one direction, serves all requests, then reverses. Like elevator. Good average seek time. Can cause "arm stickiness" at ends.
    (4) C-SCAN: Like SCAN but head only services requests in one direction, then jumps back to start. More uniform wait time.
    (5) LOOK: Like SCAN but head reverses at last request, not at disk end. More efficient.
    (6) C-LOOK: Like C-SCAN but head jumps between last and first request.

    Complete Numerical Example:
    Disk cylinders: 0 to 199. Current head position: 50.
    Request queue (in order of arrival): 98, 183, 37, 122, 14, 124, 65, 67

    FCFS:
    Order: 50→98→183→37→122→14→124→65→67
    Distances: 48+85+146+85+108+110+59+2 = 643 cylinders

    SSTF:
    Order: 50→65→67→37→14→98→122→124→183
    Distances: 15+2+30+23+84+24+2+59 = 239 cylinders
    (Starvation risk: requests at far tracks may wait indefinitely)

    SCAN (direction: increasing):
    Order: 50→65→67→98→122→124→183→199→37→14
    Distances: 15+2+31+24+2+59+16+162+23 = 354 cylinders

    C-SCAN (direction: increasing):
    Order: 50→65→67→98→122→124→183→199→0→14→37
    Distances: 15+2+31+24+2+59+16+199+14+23 = 385 cylinders

    LOOK (direction: increasing):
    Order: 50→65→67→98→122→124→183→37→14
    Distances: 15+2+31+24+2+59+146+23 = 302 cylinders

    C-LOOK:
    Order: 50→65→67→98→122→124→183→14→37
    Distances: 15+2+31+24+2+59+169+23 = 325 cylinders

    Performance Comparison:
    AlgorithmTotal MovementAvg SeekFairnessStarvation
    FCFS64380.4ExcellentNone
    SSTF23929.9PoorPossible
    SCAN35444.3GoodNone
    C-SCAN38548.1BetterNone
    LOOK30237.8GoodNone
    C-LOOK32540.6BetterNone
  2. Explain File System implementation in detail. Discuss File Allocation, Free Space Management, and Directory Implementation. [2022]

    File Allocation Methods (detailed):
    (1) Contiguous Allocation: File blocks are consecutive on disk. Directory stores starting address and length. Supports random access (seek to block i = starting + i × block_size). Problem: External fragmentation (compaction needed), difficulty growing files. Allocation strategies: First-fit, Best-fit, Worst-fit.

    (2) Linked Allocation: Each block has a pointer to the next. Directory stores address of first and last blocks. No external fragmentation. Only sequential access possible. FAT variant: File Allocation Table has one entry per block, forming a linked list in memory.

    (3) Indexed Allocation: All pointers to blocks of a file are stored in an Index Block. Directory stores address of index block. Supports random access. Problem: Index block overhead. Solutions: Linked scheme (chain index blocks), Multi-level index (Unix i-node), Combined scheme.

    Free Space Management:
    (1) Bit Vector: 1 bit per block. Compact. Good for finding contiguous free blocks by scanning.
    (2) Linked List: Free blocks linked together. Zero overhead. Finding k contiguous blocks requires traversing k blocks.
    (3) Grouping: Store addresses of multiple free blocks in the first free block. Efficient allocation.
    (4) Counting: Store address + count of consecutive free blocks. Efficient for contiguous allocation.
    (5) Space Maps: Used by Btrfs. Bitmap-based but more sophisticated. Log-structured.

    Directory Implementation:
    (1) Linear List: Simple list of (filename, file attributes, disk address) entries. Search is O(n). Easy to implement.
    (2) Hash Table: Filename hashed to a bucket. Hash table points to linear list entries. Fast search (O(1) average). Collision handling needed. Most common implementation.
    (3) B-Tree: Directory stored as B+ tree. Efficient for very large directories. Supports sorted access and range queries. Used by Btrfs, ZFS, NTFS.
Quick Reference / Formulas & Important Points

CPU Scheduling Formulas

FormulaDescription
Turnaround Time = Completion Time - Arrival TimeTotal time in system
Waiting Time = Turnaround Time - Burst TimeTime spent waiting in ready queue
Response Time = First Response - Arrival TimeTime to first response (interactive)
CPU Utilization = CPU Busy Time / Total TimePercentage of time CPU is busy
Throughput = Number of processes / Total timeProcesses completed per unit time
Dispatch Latency = Context switch + Mode switchTime to start a process
EMAT = m + α × mEffective Memory Access Time with TLB

Memory Management Formulas

FormulaDescription
Page Size = 2^n bytesAlways a power of 2
Pages = Logical Address Space / Page SizeNumber of pages in process
Frames = Physical Memory / Page SizeNumber of frames in memory
Page Table Size = Pages × Page Table Entry SizeMemory needed for page table
Physical Address = Frame × Page Size + OffsetAddress translation formula
EMAT = m + α × mEffective access time (TLB hit = 1 mem access)
Page Fault Rate p = Page Faults / Total ReferencesFrequency of page faults
Effective AT = (1-p) × m + p × page_fault_timeAvg memory access time

Disk Scheduling Formulas

FormulaDescription
Total Head Movement = Σ |Current - Next|Sum of all seek distances
Average Seek = Total Head Movement / (n-1)Average per request
Disk Access Time = Seek Time + Rotational Latency + Transfer TimeComplete disk access
Rotational Latency (avg) = (1/2) × (60/RPM) × 1000 msAverage rotation delay
Transfer Time = (Bytes / Sector) / (Bytes per track × RPM)Data transfer time
Bandwidth = Bytes Transferred / Total TimeData transfer rate

Comparison Tables — At a Glance

Kernel Architectures (Speed: High → Low):
Monolithic > Hybrid > Modular > Layered > Microkernel

Kernel Architectures (Stability: Low → High):
Monolithic < Hybrid < Modular < Layered < Microkernel

Thread Models (Performance: High → Low):
One-to-One > Many-to-Many > Many-to-One

CPU Scheduling (Preemptive):
SRTF, Round Robin, Priority (preemptive), Multilevel Feedback Queue

CPU Scheduling (Non-preemptive):
FCFS, SJF, Priority (non-preemptive), HRRN

Deadlock Approaches (Preventive → Reactive):
Prevention (no condition) → Avoidance (Banker's) → Detection & Recovery → Ignorance

Exam Tips & Common Mistakes

Unit 1: Remember all OS types with examples. Know 5 system call categories. Monolithic vs Microkernel is a favorite 15M question. Virtual machines = hypervisor abstraction.

Unit 2: Always draw Gantt charts for scheduling problems. FCFS has convoy effect. SJF is optimal but requires burst time prediction. Round Robin performance depends on quantum. Starvation → Aging solution.

Unit 3: Peterson's algorithm works for 2 processes only. Producer-Consumer needs 3 semaphores. Banker's algorithm: Safety sequence is key. Deadlock conditions ALL must hold. Dining Philosophers deadlock = all pick left fork simultaneously.

Unit 4: Internal frag in fixed partition + paging. External frag in variable partition. Page fault count: OPTIMAL < LRU < FIFO generally. Belady's anomaly is FIFO-only. Thrashing prevention = Working Set or PFF. EMAT formula with TLB.

Unit 5: Contiguous = fast but external frag. Linked = no external frag but no direct access. Indexed = best compromise. SSTF is most efficient but unfair. C-SCAN gives most uniform wait. Disk structure: Platters → Tracks → Sectors → Cylinders.

OS Study Notes — Operating Systems — Semester 5 All 5 Units Covered — Exam-Focused