EXAM PREP · PCC-CS502

Operating Systems — Unit-wise Solved Answers

Exam-grade, unit-wise model answers for the MAKAUT 70-mark pattern — OS fundamentals, CPU scheduling, semaphores, deadlocks, memory, and disk I/O — with solved numericals worked step by step.

Module 1 Questions

1
What is operating system? What are the types of operating system? What do you mean by real-time operating system? Differentiate between soft real-time and hard real-time systems. What is parallel operating system? What is distributed operating system?

Operating System (OS) is the system software that acts as an intermediary between the user of a computer and the computer hardware. It manages the machine's resources — the CPU, main memory, I/O devices and files — and allocates them to various programs for their execution in an efficient and fair manner. It provides an environment in which user programs can be developed and executed conveniently, and it must behave reasonably under all conditions, i.e. it must be reliable, protectable and efficient. Examples: Linux, Windows 11, UNIX, macOS.

Types of Operating Systems

TypeCore Idea
BatchSimilar jobs are grouped into batches; jobs execute in groups without user intervention. Jobs are placed on magnetic media and processed by a job-control program.
InteractiveDirect man-machine interaction; user programs run in real time and the user is involved in every step (time-sharing belongs here).
Time-sharingMany users share the CPU rapidly in sequence; interactive response time under about a second.
Real-timeTime constraints must be strictly met; used in process control, medical systems, air-traffic control, defence fire control.
NetworkIndividual computers on a LAN provide shared resources (files, printers) to each other.
DistributedMany physically separate machines appear to the user as a single coherent system; work is distributed among multiple machines.
ParallelMultiple processors share the OS and the file system, enabling high-speed computation (multicomputers / MIMD machines).

Real-Time Operating System (RTOS)

A real-time operating system supports real-time applications that operate under strict timing constraints: the system must produce results within a specific, predetermined time window. An RTOS guarantees that critical computations are completed within set time limits (e.g. a temperature-sensing loop in a furnace must react within milliseconds). Two flavours:

Hard Real-TimeSoft Real-Time
Meeting the deadline is a requirement; missing it means task failure and potentially catastrophic consequences.Meeting the deadline is desirable; missing it lowers quality or the importance of the result but does not cause system failure.
Example: control system for a nuclear reactor, aircraft flight control, missile fire control.Example: video streaming, voice telephony, scientific data acquisition.

Parallel & Distributed Operating Systems

A parallel operating system runs on multiple processors within a single machine, all of which share the OS and the file system; it schedules processes across several CPUs to maximise throughput. A distributed operating system manages many physically separate, possibly heterogeneous machines over a network so that the collection appears as one uniform system: the user is not aware of which machine serves a request, and data may be moved automatically between machines to balance load and improve reliability.

2
Describe the following types of operating system: (a) Batch, (b) Interactive, (c) Time-sharing, (d) Real-time, (e) Network. Mention one characteristic each of time-sharing system and batch processing system. What are the advantages and disadvantages of open-source OS? What is open-source OS?

(a) Batch Operating System

User jobs of the same type are grouped into batches and submitted to the operator; the batch is processed automatically without user intervention. A monitor (job-control program) selects and schedules the jobs, and each job is typically run to completion with the next batch job starting immediately when one finishes. Input devices load the batch on magnetic tape and output results go to a line printer. Because of no user interaction it is called Non-interactive OS.

(b) Interactive Operating System

The user programs interact with the computer system in real time — the user types commands and receives immediate feedback. Programs are stored in fast memory, response time is a fraction of a second, and the user can interrupt, alter or terminate a running program. Interactive OSs provide the most user convenience but are more complex and expensive than batch systems.

(c) Time-Sharing Operating System

The CPU is shared among many user jobs held in memory by rapidly switching among them, so each user interacts with a separate program essentially in real time. When the current process does not use the CPU for a reason (waiting on I/O), the OS gives the CPU to another process. The system must keep the response time under about a second so the system feels interactive.

(d) Real-Time Operating System

Time constraints must be strictly met. Critical computations are completed within a set time limit: the system must gather input data, process it and return results in guaranteed time (furnace temperature sensors, air-traffic booking, hospital records, bank account data, defence fire control).

(e) Network Operating System

Individual computers on a Local Area Network (LAN) work as peers: each has its own OS, memory and data, but they communicate so that shared resources — printers, files, network services — are available to all users.

Key Characteristics

  • Time-sharing: The key characteristic is rapid switching between several user programs so every user receives a quick response (response time under about 1 second).
  • Batch processing: The key characteristic is that jobs are grouped into batches and run without user interaction — the user submits a batch and does not monitor it while it runs.

Open-Source OS

An open-source operating system is one whose source code is freely available for anyone to view, modify, test and distribute — e.g. Linux, FreeBSD, Solaris, BeOS. Because the code is public, anyone can audit, debug or improve it, and it can be customised to user needs at no licensing cost.

AdvantagesDisadvantages
Source code is freely available and viewable; can be modified by anyone.The open code makes it more vulnerable to exploitation — security flaws are also open to attackers.
Reliability: bugs are found and corrected quickly by the community.Difficult to install and configure; may require expertise.
The community adds new features and supports hardware beyond official releases.Few people have knowledge of it, so user support is limited.
Usually less cost-effective (no licensing fees) than commercial OSs.Certain features of the system are not available compared to proprietary products.
3
What is the purpose of command interpreter? Why is it usually separate from the Kernel? What is Kernel?

The command interpreter (also called shell) is the program that provides the interface between the user and the operating system. Its purpose is to take commands from the user and present the output of the system's actions: the user types requests (file operations, program launches, pipeline constructions) and the shell gathers the needed parameters, requests the kernel to perform the work, and returns the results. Modern shells are programmable — they accept command sequences, loops and conditional tests from user programs.

Why separate from the kernel: The shell is not essential to the operation of the system itself; it is merely a user interface. Keeping it outside the kernel means new or improved interfaces can be added or changed without recompiling the OS — several shells (bash, zsh, PowerShell, X-windows GUIs) can coexist on the same kernel. It also isolates the part of the system most exposed to user error: a crashing shell does not take the kernel down, and the security-sensitive, privileged code is confined to the small kernel core.

Kernel: The kernel is the core part of the operating system — the part that is kept in memory at all times. It sits over the hardware and performs privileged machine operations: process and thread scheduling, memory allocation, interrupt and device handling, file-system access and protection. System programs (compilers, loaders, linkers, file utilities) run outside the kernel and use its services through system calls; the kernel is the only component that executes in kernel (privileged) mode and can execute privileged instructions. A kernel may be monolithic (all OS services in a single executable in kernel space) or microkernel (only the minimum — scheduling, IPC, memory — in kernel space, the rest in user-space servers).

4
State the functions of a system call? What is/are the main difficulties to write a program in a real-time operating system? What is spooling?

Functions of a System Call

A system call is the programmatic interface between a user-mode process and the kernel; it is entered via a trap / software interrupt that switches the CPU from user mode to kernel mode. Every privileged operation — touching hardware, creating processes, allocating memory, doing I/O — goes through a system call. Main functions, grouped by category:

  • Process control — error, exit, fork/exec (create/terminate processes).
  • File management — create, delete, open, close, read, write, get/set file attributes.
  • Device management — request a device, release a device, synchronous/asynchronous I/O, swap I/O.
  • Communications — create/delete connections, send/receive messages, broadcast datagrams, look-up network information.
  • Information maintenance — get/set time, date, system data, process or file attributes.

Difficulties in Writing Real-Time Programs

  • Strict deadlines: results must be produced within the time window; the algorithm must be proven to finish in bounded time (worst-case, not average-case).
  • Non-determinism: process execution times, arrival times and I/O service times vary; the program must be correct for every legal variation, not just the test cases.
  • Priorities and pre-emption: the code must survive being interrupted at arbitrary points and resumed; shared state needs careful locking, and locks must be released before deadlines so they cannot cause a missed deadline.
  • Memory constraints: real-time systems often have small address spaces and no paging, so dynamic allocation (heap fragmentation, pauses) is discouraged.
  • Hardware coupling: device drivers and interrupts must be handled exactly right; a bug is not a crash but a missed physical deadline.

Spooling

Spooling (Simultaneous Peripheral Operations On-Line) keeps a queue of I/O requests on disk while a device works. Classic case: a printer. The spooling program writes each print job to a spooling directory on disk and returns immediately to the user, while the daemon (spooler process) later takes jobs one by one and prints them. This decouples the user program from the slow device: the user does not wait for printing, and the printer runs continuously without idle gaps between jobs. The same principle is used for tape drives and disk buffering.

5
What is a Virtual machine? Write a case study on Unix and Windows operating systems.

A virtual machine (VM) is a complete illusion of the underlying computer system: it presents the user a consistent, uniform machine that is simpler and more useful than the physical machine. In modern usage a VM is software that executes a guest OS as if it had a real CPU and memory, using an interpreter-like virtual machine monitor (VMM / hypervisor) that traps guest instructions and emulates or maps virtual hardware to the real machine. Applications see a virtual CPU, virtual memory and virtual devices; the VMM makes them indistinguishable from real ones.

Case Study — UNIX vs Windows

UNIX: Developed at Bell Laboratories (1970s) as a small, portably-written-in-C multi-user, multi-tasking OS. Its defining ideas: everything is a file (devices, pipes, terminals), a shell written in portable language sitting on top of a kernel that talks to hardware, a hierarchical file system with a single root, and portability (C source recompiled per platform). Modern derivatives: Linux, macOS, Solaris, BSD. Strengths: multi-user, multi-tasking, high portability, rich utility set, stable kernels. Weaknesses: steeper learning curve, less consumer-level tooling.

Windows: From MS-DOS (16-bit command-based) to Windows NT, a 32-bit, multi-tasking, multi-user kernel with a hybrid kernel design (some services — file system, memory manager, network — run inside the kernel for performance, scheduling and interrupt handling stay in a small core). NT introduced the Executive (resource manager, process manager, I/O manager, cache manager) over a hardware-abstraction layer (HAL) that makes the kernel portable across CPUs. Features: 64-bit support (Windows 8/11/Server 2016), object-based design where every resource is an object with attributes, access control and handle, user-mode and kernel-mode separation, SID-based access control, and a strong GUI (Explorer) integrated with the kernel API.

AspectUNIXWindows
OriginBell Labs, 1969–73MS-DOS (1981); NT (1993)
Kernel typeMonolithic / microkernel variants (Mach, Linux monolithic)Hybrid (NT Executive)
File systemHierarchical, single root, “everything is a file”Object model; NTFS with security descriptors
SecurityUser/group/other (octal permissions)SIDs, ACLs, discretionary access control
UsersMulti-user by designMulti-user but consumer-oriented
PortabilityHigh (C, POSIX)HAL isolates hardware; NT on many CPUs
LicenseOpen source (Linux, BSD, macOS)Proprietary, commercial

Both are multi-user, multi-tasking, paged, preemptive, and support process protection, inter-process communication, virtual memory, and TCP/IP networking; they differ chiefly in kernel philosophy (monolithic vs hybrid), file model (everything-is-a-file vs object/ACL), and licensing.

6
Describe the structure of an operating system. Define the types of OS structure (Monolithic, Layered, Microkernel).

Structure of an Operating System

An OS is more than just a set of system programs and shells — it is a complex of modules that wrap the hardware. From top to bottom, the classic layered view:

  ┌────────────────────────────────────────────┐
  │  User programs   ·   Shells / System calls │
  ├────────────────────────────────────────────┤
  │  System programs: compilers, editors,      │
  │  linkers/loaders, file utils, network utils│
  ├────────────────────────────────────────────┤
  │  Operating-system software:                 │
  │  process mgmt · memory mgmt · file systems  │
  │  device drivers · networking · protection   │
  ├────────────────────────────────────────────┤
  │  Hardware: CPU · memory · disks · I/O       │
  └────────────────────────────────────────────┘

The bottom layer is the hardware itself, and each layer of OS structure is built on top of the layer beneath it. The OS provides services via system calls, and the hardware must provide an interrupt mechanism so the OS can react to devices; it also supplies special CPU states (user / kernel mode) to keep processes from tampering with the OS.

Monolithic OS Structure

All OS services are implemented in the kernel space; modules (process, memory, I/O, file, networking) can call each other directly for speed. Examples: Linux, UNIX. Advantage: communication is fast — no context switches, no address-space crossings. Disadvantage: one module bug can crash the whole OS; the kernel grows unwieldy and hard to test.

Layered OS Structure

The system is divided into layers, each using services from layers below and providing services to layers above. The hardware is at layer 0, the top layer is user services; each layer calls only the layer immediately below it. Advantage: easy to debug and test — replacing one layer does not affect others. Disadvantage: overhead: a top-level call must pass through every lower layer; most layers are actually only called by their immediate neighbours, and the layer boundary is artificial.

Microkernel OS Structure

The microkernel approach: keep the kernel as small as possible — it contains only the services that must run in kernel space: memory management, process management, communication, and the I/O basics. Additional services (file systems, device drivers, network stacks, window manager) run as user-space servers and talk to each other and to the kernel via message passing. Example: Mach, Windows NT (a hybrid between monolithic and microkernel). Advantage: extensible — new services can be added without touching the kernel; easier to test/debug, can run on different hardware; safer — a buggy driver can't crash the kernel. Disadvantage: communication between user-space modules (inter-process communication / message passing) may be slower than kernel-internal calls.

Module 2 Questions

Exam Note ★ Numericals expected on: FCFS · Shortest Job First (SJF) · SRTF (with pre-emption) · Round Robin — study the worked examples in Q4 and Q5 before the exam. ★
1
What is context switching? With the help of a state transition diagram, explain the various states of a process. How does context switch time be reduced? Write the difference between user-level thread and kernel-level thread. What are the relative advantages and disadvantages of user-level thread and kernel-level thread?

Context switching is the saving of the state of a process/thread (registers, program counter, stack, MMU state) so that it can be restored later, together with the loading of the saved state of the process/thread to be executed next. It is pure overhead — no useful work is done while the switch happens. The per-switch cost is 10–100 µs and is comparable to the cost of the work the process does in a time slice.

Process State Diagram

        +-----------+
   +----|  New      |           The process is being created.
   |    +-----+-----+
   |          | (admitted to ready queue)
   |          v
   |    +-----------+   dispatch    +------------+   exit   +---------------+
   +---> |  Ready    |-------------> |  Running   |-------->| Terminated    |
   |    +-----+-----+               +-----+------+          +---------------+
   |          ^                            |
   |          | (I/O or event completes)   | (I/O request,
   |          |                            |  pre-empt)
   |    +-----+-----+   (I/O / event)     v
   +----------|   Wait   |<---------------+  (back to ready)
      (or die) +---------+
        Note: pre-empted running goes Ready; I/O / event request goes Wait.

The key transitions: New → Ready on admission; Ready → Running when the dispatcher allocates the CPU; Running → Ready when a timer expires or a higher-priority process preempts; Running → Wait/Blocked when a process requests I/O or an event it can't complete yet; Wait → Ready when the requested I/O or event completes; and any state to Terminated when the process exits. In modern systems, processes in Wait can also be swapped (medium-term scheduling) to reduce process thrashing.

Reducing Context-Switch Time

  • Keep the PCB small and cache it so saving/restoring is a small copy.
  • Provide a fast hardware context-switch instruction (x86 SWITCHTOCONTEXT) that saves/restores registers in one instruction.
  • Use kernel-level threads: switching between threads in the same process is cheap (registers + a small kernel thread block) because the virtual memory and file descriptors stay the same; no TLB flush, no page-table reload.
  • Use a multi-level scheduler so only the short-term scheduler does a full context switch; medium-term swaps are rarer and slower but can run in the background.
  • Minimize the number of threads in the ready queue — too many threads increase preemption overhead, too few underutilise the CPU.

User-Level vs Kernel-Level Threads

AspectUser-Level Thread (ULT)Kernel-Level Thread (KLT)
Visibility to kernelUnknown to the kernel; it only sees the process.Maintained by the kernel in the OS scheduler's queue.
Switching costCheap — a context switch in user space, no system call.Expensive — requires a system call and kernel context switch.
SchedulingLibrary-level (Java thread pool, POSIX NPTL user side).Scheduled by the OS scheduler; can use all cores.
Blocked I/O effectIf one ULT blocks on I/O, the whole process is blocked.If one KLT blocks, other KLTs of the same process continue.
Multi-processor useCANNOT parallelise — one ULT uses one CPU core.CAN parallelise across all cores of the process.

Relative Advantages and Disadvantages

  • ULT advantages: fast to create/destroy and switch (no kernel transition); a user-level scheduler can specialise to the application; no kernel lock contention; cheap per switch.
  • ULT disadvantages: a blocked thread stalls the whole process; can't use multiple processors; fewer scheduling decisions — no access to kernel resources.
  • KLT advantages: can exploit multiple cores; one blocked thread does not block others; can run in parallel in multi-processor systems; kernel can schedule them intelligently.
  • KLT disadvantages: switching is expensive (system call); a KLT switch requires a kernel context switch; kernel resources and data structures are more involved, so the OS must know about each thread; creation is slower.
2
What are co-operating processes? Discuss the advantages of co-operation processes. What are the differences between process and thread? Under what condition do the following state transitions occur with respect to a process? a. Run to Ready, b. Blocked (or wait) to Ready

A cooperating process is a process whose execution can be affected by one or more other processes in the system: it shares data with other processes, communicates via messages, or coordinates to reach a shared goal. In contrast, independent processes do not affect each other. Two cooperating-process models exist: independence-based cooperation (processes are unaware of each other and the kernel mediates all synchronisation) and communication-based cooperation (processes explicitly interact via shared memory, pipes, semaphores or messages).

Advantages of Cooperating Processes

  • Information sharing: several producers and consumers exchange data — e.g. a compiler produces symbol-table entries that a link editor consumes.
  • Speed-up: large tasks (image processing, AI training) are split across cooperating processes that run in parallel.
  • Modularity: one program broken into smaller cooperating processes — a text-editor process communicates with a separate spell-checker process.
  • Convenience: one process can produce data that a user process (or the kernel) later consumes; e.g. a printer spooler receives jobs from many users.

Process vs Thread

AspectProcessThread
UnitA program in execution, with its own address space.The unit of CPU scheduling; a lightweight sub-unit of a process.
Address spaceOwn — private code, stack, data.Shares its process's code, data, open files, registers.
Creation costExpensive — new address space, PCB, TLB flush.Cheap — small thread-control block, shared memory.
Context switchExpensive — MMU state must be reloaded.Cheap — virtual memory and files are unchanged.
Failure effectKilling a process destroys all its threads.Killing a thread leaves the process and other threads running.
ConcurrencyRequires IPC (pipes, shared memory) to coordinate.Native — shared memory is automatic.

Specific State Transitions

  • (a) Running → Ready: This occurs when the currently running process is preempted — either the time slice has expired and a higher-priority process is waiting, or the running process is preempted by a hardware/software interrupt and the scheduler decides another process should run. The process's state is saved to its PCB and it returns to the ready queue to be dispatched later.
  • (b) Blocked (Wait) → Ready: This occurs when the event the process was waiting on completes — an I/O operation finishes (disk read returns to the buffer), a process it was waiting on signals that data is available, a timer fires, or a message is received. The process no longer needs the kernel to block it, so it moves back to the Ready state, and a context switch may happen to resume it.
3
What is a Process Control Block (PCB)? Discuss the structure of a Process Control Block. What is the need of a PCB? What are the contents of a PCB? Write the difference between User mode and Kernel mode? Explain the utility of a PCB for a process?

The Process Control Block (PCB) is the data structure in the kernel that represents a process; it is the process's identity in the OS. The kernel uses the PCB as a key to locate resources, and it is the block saved and restored by the dispatcher on every context switch. For each process in the system, a unique PCB is created (or reused when the process is swapped back in), and when a process terminates its PCB is freed back to the kernel. The kernel stores an index into the PCB table so it can locate every process's PCB quickly.

PCB Structure / Contents

CategoryFields
Process stateReady, Running, Waiting; priority; state-reason (which I/O or event is expected).
Process identifierUnique process ID (PID); parent PID; user/group IDs.
CPU registersProgram counter; stack pointer; general-purpose registers; condition codes; status word — saved on every context switch.
Scheduling infoPriority; pointer to the ready/waiting queues; last CPU time; CPU-time used; run-quantum limit.
Memory managementBase/limit registers, or pointers to page tables / segment tables; stack and heap limits.
I/O statusList of open files; I/O devices assigned; uncompleted I/O requests.
AccountingCPU time used; time limit; deadline; cost so far; creation and termination time.

Why the PCB is needed

Without a PCB, the kernel has no record of what is running and no state to restore on a context switch. The PCB is the central identity and context record for a process: it lets the scheduler pick a process by PID, restores its CPU by loading the saved registers, enforces protection by checking the register state (user/kernel mode bits, address limits), and tracks its resources (open files, I/O requests) so that they are not leaked when the process ends.

Utility of the PCB

  • Saved/restored on every context switch — the fast-restore path of the dispatcher.
  • Locates all resources of the process: code, stack, heap, open files, I/O.
  • Enables protection and accounting — the kernel can enforce address limits and CPU-time limits.
  • Allows the kernel to track process hierarchy (parent/child) and state transitions (which queue, which priority).
  • When the process is swapped out, the PCB tells the kernel which pages to swap; when it is swapped in, the PCB tells it what to restore.

User mode vs Kernel mode

AspectUser modeKernel mode
PrivilegeUnprivileged; cannot execute privileged instructions.Privileged; can execute all instructions including privileged ones.
Memory accessOnly its own address space.The entire physical memory, including the kernel.
Hardware accessOnly via system calls.Direct access to all devices and I/O registers.
Failure effectTerminating the user program does not crash the OS.A crash in kernel mode brings the whole system down.
ExamplesCompilers, shells, text editors, games.Scheduler, memory manager, device drivers.
4
What resources are used when a thread is created? How do they differ from those when a process is created? What do you mean by pre-emptive and non-pre-emptive scheduling? What are the different scheduling criteria? What is CPU scheduling? What are the parameters of CPU scheduling? What is "Turn Around Time"? What are the CPU scheduling criteria? Explain with examples pre-emptive and non-pre-emptive scheduling algorithms.

Resources at Thread Creation vs Process Creation

Creating a process allocates a new address space (code, data, stack, heap), a new PCB, new page-table entries, and (in some systems) copies or mappings of file descriptors. A thread, by contrast, shares the parent process's address space, open files, and signal handlers; it gets only a new thread-control block (a few hundred bytes), its own program counter, registers and stack. So thread creation is fast (no memory-mapping, no TLB flush), and context switches between threads in the same process are cheap because virtual memory is unchanged.

Pre-emptive vs Non-Preemptive Scheduling

In non-preemptive scheduling the running process keeps the CPU until it voluntarily gives it up (blocks on I/O or exits); the OS does not interrupt it. In preemptive scheduling the OS may take the CPU away on a timer or a higher-priority arrival and put it to another process — the running process is interrupted mid-burst and put back on the ready queue.

CPU Scheduling — Criteria

  • Maximise CPU utilisation — keep the CPU busy at all times (main for multiprogramming systems).
  • Maximise throughput — maximise the number of processes completed per unit time (for batch systems).
  • Minimise turnaround time — from submission to completion; TAT = CT − AT.
  • Minimise waiting time — time spent in the ready queue; WT = TAT − BT (directly affects turnaround).
  • Minimise response time — from request to first response; key for interactive and real-time systems.

Turnaround Time

The total time from process submission (arrival) to completion: TAT = CT − AT. Equivalently, TAT = WT + BT, since it includes both waiting in the ready queue and execution.

Worked Example — FCFS / SRTF / RR (quantum = 4)

Four processes, all arriving at time 0:

PIDArrivalBurst
P1024
P203
P308
P404

FCFS (non-preemptive, FIFO): P1 → P2 → P3 → P4 on the Gantt:

 0        24   27  35  39
 ├─ P1 ──┤ P2  P3  P4
 P1: CT=24  TAT=24  WT=24−24=0
 P2: CT=27  TAT=27  WT=24
 P3: CT=35  TAT=35  WT=27
 P4: CT=39  TAT=39  WT=35
 Avg TAT = (24+27+35+39)/4 = 31.25   Avg WT = 21.25

Shortest Remaining Time First (SRTF, preemptive): At every instant the smallest remaining burst wins.

 0   3   7   11  39
 P2  P3  P4  P1 (rest of 24-3=21 → P1 ends at 39)
 P2: CT=3   TAT=3
 P3: CT=7   TAT=7
 P4: CT=11  TAT=11
 P1: CT=39  TAT=39
 Avg TAT = 15   Avg WT = 15 − (3+8+4+24)/4 = 5.25

Round Robin (preemptive, q = 4):

 0   4  8  12  16  20  24  28  32  36  39
 P1  P2 P3 P4  P1  P1  P1  P1  P1  P1
 (P2 and P3 finish within their slots; P4 gets 2 slices of 2)
 P1: CT=39  TAT=39
 P2: CT=8   TAT=8
 P3: CT=12  TAT=12
 P4: CT=20  TAT=20
 Avg TAT = 19.75

The preemptive SRTF gives the minimum average turnaround, while FCFS is the worst for a long process that arrives first; RR gives a moderate, fair average response.

5
Mention the basic principle of RR (Round Robin) scheduling? Specify the impact of time quantum on its performance. What is the main objective of Multiprogramming? Given n processes to be scheduled on one processor, how many possible different schedules are there? Give a formula in terms of n.

Round Robin — Principle

RR is a preemptive FIFO-like algorithm that is the natural choice for time-sharing systems. Each process in the ready queue is served in rotation; a process at the head of the queue runs for at most one time quantum (typically 10–100 ms) and is then preempted. If it cannot finish in the slice it is requeued at the tail of the FIFO queue, so that every process gets a slice in round-robin order. Preemption (a timer) is implemented so that the slice boundary is fair; when a process's slice expires it is preempted and placed at the tail, and the next head gets a slice.

Impact of the Time Quantum

  • If the quantum is too large relative to the typical CPU burst, RR degenerates into FCFS — every process finishes in one slice, so no preemption ever happens.
  • If the quantum is too small, context switching happens too often and switch overhead dominates (the dispatcher spends more time saving/restoring state than executing user code).
  • Typical values: 10–100 ms; switching cost is 1–100 µs — so the slice must be many times larger than the switch cost but much smaller than the average CPU burst.

Objective of Multiprogramming

The main objective is to keep the CPU busy by maintaining several programs in memory. While one program waits on I/O, another can use the CPU, so CPU utilisation rises from the average utilisation of a single job to near 100% — the number of processes in memory is chosen so that there is always one ready process to run on average. Throughput also improves. (In real-time systems, throughput is traded off for response time: the objective is minimum turnaround time, not utilisation.)

Scheduling-count Formula

For n processes, the number of possible scheduling orders is n! — the number of permutations of n items. The number of actual schedules that must be generated by the OS scheduler is also bounded by n!; any algorithm that visits all of them would require (n!) exponential work. In practice, scheduling algorithms choose a schedule (not enumerate all) using a policy (FCFS, RR, priority) and a data structure (ready queue, priority queue, aging table).

6
What is the dispatcher? What is the medium-term, short-term, and long-term scheduler? Describe their functions. What is multiprocessor scheduling? What are its main features? Briefly explain multiprocessor feedback queue scheduling. What are the benefits of threads?

The Dispatcher

The dispatcher is the module that allocates the CPU to a process. It performs three tasks: (1) switch context from the outgoing process to the incoming one, (2) switch from user mode to kernel mode (set the mode bits in the PCB), and (3) restart the process at the right point (load the saved program counter). The time from when the short-term scheduler makes a decision to when the dispatcher actually dispatches that process is the dispatch latency — it should be as short as possible, since it is pure overhead.

The Three Tiers of Scheduling

LevelNameFrequency / DurationFunction
Long-termJob schedulerMinutes to hours; rarely invokedControls the degree of multiprogramming — how many processes are in the Ready state. Selects jobs from the pool and brings them into memory to run; determines whether the system will be mainly interactive or batch, or a mix. Minimises long-term load; can be the OS itself booting up or a batch loader.
Medium-termSwapping / swapperEvery few seconds to a few minutesSwaps a blocked or low-priority process out to disk (swap space) and later brings it back. Reduces the number of Ready processes (which must all fit in memory) to the desired degree of multiprogramming. Acts as a buffer between the long-term and short-term schedulers.
Short-termCPU scheduler / dispatcherMilliseconds — every time the running process blocks, timer expires, or preemption happensSelects which of the ready-state processes will run next; the most frequent scheduling decision. Runs in kernel mode; cost must be small. Implemented by the dispatcher: context switch + dispatch.

Multiprocessor Scheduling

Multiprocessor (many-CPU) scheduling differs from multi-programming in that a single process can run on more than one processor at once, and the scheduler must balance load across CPUs. Key features:

  • Load balancing: when the work is heavy on one CPU, the scheduler moves one of its ready processes to a lighter CPU; when all CPUs have roughly equal load, no need to move processes.
  • Processor affinity: a process that just ran on CPU 1 has its data in CPU 1's cache; re-running on CPU 1 hits the cache, while re-running on CPU 2 misses. The scheduler binds a process to a particular CPU (or a set of CPUs) so its cache lines stay warm — affinity improves performance. The OS can also do soft affinity: prefer the original CPU but allow re-binding under load imbalance.
  • Symmetry: the scheduler may be single (one central ready queue, a process waits on any free CPU) or per-processor (each CPU has its own ready queue and a local scheduler picks from it, then steals work from other queues — work stealing). Global queues (a single queue) minimise contention but serialise dispatch; local queues allow faster scheduling but can leave one CPU idle while another is busy.

Multiprocessor Feedback Queue Scheduling

A multi-level feedback queue for many CPUs: instead of a single FIFO ready queue, the OS maintains several ready queues — one per CPU (or one per priority) — and the scheduler feeds work into the queues that are emptiest and takes work from the queues that are fullest. Feedback is the key: when a CPU has finished a slice, it reports the load; if that load is high, subsequent slices of the same process are moved to a lighter CPU. This way the OS dynamically balances work across all CPUs in response to actual observed behaviour, not to a precomputed assumption. A simplified version: one global ready queue, each CPU picks the highest-priority ready process, and if the global queue is empty the CPU idles. A more complete version keeps per-CPU queues and moves processes (or work) between them under load pressure.

Benefits of Threads

  • Responsiveness: one thread can be blocked on a disk I/O while another updates the user interface — the UI stays responsive; a multi-threaded e-mail client can download in the background while the user composes.
  • Shared data: threads share the same address space, so sharing is free — no send()/receive() messages, no kernel-mediated IPC; a producer and consumer can share a single buffer.
  • Economy: creation, context-switch and termination costs are an order of magnitude lower than a process's — thread creation is ~200–300 ns (a few hundred bytes), while process creation is tens of µs and copies or maps a new address space.
  • Parallelism: on a multi-core machine, threads in one process can truly run in parallel on different cores; on a single core, a process can switch threads while another is blocked on I/O, achieving concurrency without multi-processing.
7
What is multithreading? What is a process? Compare SJF and SRTF. What is a thread? Draw and explain the thread life cycle. Explain types of threads with examples. What advantages do threads have over multiple processes? When is a process called a co-operating process?

Multithreading and Process

Multithreading is a technique that permits different parts of a program to run on different threads of control. A thread (lightweight process / LPW) is the basic unit of CPU utilisation: it consists of a program counter, a stack and a set of registers. It shares with other threads in the same process the process's code, data, and open files. A process is a program in execution — a running instance of a program, with its own address space, resources and a PCB. A multi-threaded application typically uses a thread pool (a pre-created group of threads that the application recycles for tasks), which amortises the cost of thread creation. Example: a web browser renders the UI on one thread, downloads a page on a second, and decodes a video on a third; the download finishes on a background thread and the UI thread updates the progress bar without blocking user input.

SJF vs SRTF

AspectSJF (Shortest Job First)SRTF (Shortest Remaining Time First)
Pre-emptionNon-preemptive — the running process runs to completion.Preemptive — when a new process with a shorter remaining burst arrives, the current process is preempted.
Decision pointWhen a process finishes (or a new one arrives and nothing is running).On every new arrival — the scheduler compares remaining times and may preempt.
OptimalityOptimal average waiting time among non-preemptive algorithms.Provably optimal minimum average waiting time overall (but it can starve long jobs).
Convoy effectA long job running can't be interrupted by a short job that just arrived.Short jobs arriving during a long job's execution preempt it, avoiding the convoy effect.
Starvation riskLong jobs starve behind short ones.Worse — a long job can starve permanently if short jobs keep arriving; cure with aging.

Thread Life Cycle

  +------+   start    +-----------+   schedule  +----------+
  | NEW  |---------->|   READY   |----------->| RUNNING  |
  +------+            +-----+-----+            +-----+----+
                        ^  |                        |  ^
                        |  | (dequeue on schedule)   |  | (re-queue on slice
  (thread termination)  |  | (I/O / mutex block)     |  |  expiry or pre-empt)
                        |  v                        v  |
                  +-----------------+            +-------+
                  | BLOCKED / WAIT  |<-----------|       |
                  +-----------------+  unblock   +-------+
   Thread is destroyed → all stacks / data freed, TCB released.
  • NEW — created by pthread_create() (POSIX) or Thread.start() (Java); not yet scheduled.
  • READY — runnable; its stack and data are initialised and it waits on the OS scheduler's ready queue.
  • RUNNING — currently executing on a CPU.
  • BLOCKED / WAIT — stopped because of I/O, a lock (mutex), a condition variable, a join(), a sleep(), or a message; moves back to READY when the event completes.
  • EXITED / TERMINATED — finished; the thread's resources are reclaimed when joined by another thread; its exit code is readable by the joining thread.

Types of Threads

  • 1 : 1 — one OS thread per application thread (Java 1.1+, .NET, Go): fast and can run on any core, but the OS must track every one. Example: a Python process with 32 background threads → 32 KLTs.
  • M : N — many user-level threads share a small pool of KLTs (Green threads, Erlang on SMP): cheap to switch, but a blocked ULT stalls the whole pool. Example: a JVM with 4,000 Green threads on 4 KLTs.
  • Many-to-Many — M user threads multiplexed onto N kernel threads, with an intermediate scheduler (the modern Windows NPTL and newer Linux models): balance of cheap ULT switches with KLT scheduling. Example: Linux glibc NPTL + C10N model (one KLT per ULT, cheap user-space hand-offs).
  • POSIX threads (pthreads) — the standard KLT API; Java threads (1 : 1 by default since Java 1.1, M : N for Green threads), and kernel threads (the KLTs themselves).

Thread Advantages over Multiple Processes

  • Creation — an order of magnitude faster than fork(); no new address space to copy or map.
  • Context switch — no TLB flush, no page-table reload; the virtual memory is already set up for the process.
  • Shared data — automatic; no pipes, no shared-memory library, no network protocol.
  • Responsiveness — background work (download, index, animation) on one thread while the UI thread keeps the interface live.
  • Scalability — a pool of threads recycles creation; a pool of 8 threads can handle thousands of requests without 8,000 fork() calls.

Cooperating process: a process is called cooperating when its execution is affected by one or more other processes — it shares data with them, communicates via messages, or coordinates with them. Examples: a compiler that produces symbol-table entries that a link editor consumes; a producer and consumer sharing a bounded buffer; a spell-checker that runs on a separate process and reads the text document the editor process is writing.

8
What is the fork() system call? Write a program using fork() to demonstrate the mother-child relationship of processes? What is a co-operating system? What is the purpose of interrupt? What are the differences between trap and interrupt? Can traps be generated intentionally by a user program? If so, for what purpose?

fork()

fork() (POSIX) is the process-creation system call. It creates a new child process that is an identical copy of the calling parent: the child's program counter, registers, code, data, open file descriptors, environment and signal handlers are copied from the parent (with copy-on-write on the memory pages — only actually written pages are duplicated). It returns a long: 0 in the child, the child's PID in the parent (and −1 on failure). The two processes run in parallel from the branch point, and the child typically exec()s a new program in place of the parent's image; the parent typically wait()s for the child to exit.

Demonstration Program

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    int pid = fork();          /* create a child process */
    if (pid < 0) {            /* fork failed */
        perror("fork failed");
        return 1;
    }
    if (pid == 0) {           /* this branch is the CHILD (pid == 0) */
        printf("I am the CHILD process. My PID is %d.\n", getpid());
        printf("My parent PID is %d.\n", getppid());
        exit(0);
    } else {                  /* this branch is the PARENT (pid == child's PID) */
        printf("I am the PARENT process. My PID is %d.\n", getpid());
        printf("My CHILD's PID is %d.\n", pid);
        int status;
        wait(NULL);           /* wait for the child to exit */
        printf("Child %d has terminated.\n", pid);
    }
    return 0;
}

The two processes diverge at the point of fork() — the mother-child relationship is that the parent's pid is the child's PID (so the child knows who created it), and the child's getppid() returns the parent's PID. The child then usually exec()s a new program, or exit()s, while the parent wait()s. This is the C language's standard process creation pattern.

Cooperating System

A cooperating system is an OS model in which a set of independent cooperating processes work together, often communicating explicitly via message passing or shared memory, to complete a task. In a cooperating model, a process blocks (waits) on a message or event that another cooperating process will send (e.g. a producer that has just enqueued a buffer and is now signaling the consumer that data is available). In a non-cooperating model, the kernel mediates all interactions and processes stay unaware of each other's existence. The former is more flexible for distributed systems; the latter is simpler to reason about.

Interrupts — Purpose

An interrupt is a signal from the hardware that tells the CPU to stop its current work and remember where it was so it can return after the interrupt handler finishes. Hardware interrupts are generated by devices (keyboard, disk, timer, network card); traps are generated by software — a syscall, a division-by-zero, an unmapped page, a privileged instruction executed in user mode. The CPU, on a trap, saves its state into the PSW and PC and jumps to the trap handler in the kernel. Interrupts let the kernel pre-empt the running process, service a device, or time-slice processes fairly — they are the core mechanism by which the OS monitors hardware events and reacts to them.

Trap vs Interrupt

AspectTrapInterrupt
SourceSoftware — user program, kernel, CPU.Hardware — a device (disk, keyboard, network).
Intentional?Can be intentional (system calls, brk, breakpoint).Always asynchronous / external — the device does not need the user's consent.
ExampleDivision by zero, illegal instruction, page fault, syscall.Keyboard interrupt, timer interrupt, disk completion.
Mode switchTraps always trap in user mode → kernel mode; a user can never execute a privileged instruction without a trap.Interrupts are delivered to the kernel; the user has no direct control over their timing.
Maskable?Cannot be masked — they are synchronous with the current instruction.Can be masked (temporarily disabled) by the kernel to run critical sections.

Yes — a user program can intentionally generate traps. The two classic uses are: (1) the syscall (or int 0x80 / syscall instruction) is a deliberate trap that the user program fires to ask the kernel for a service — open(), read(), write(), exec(); the user intentionally traps into the kernel. (2) breakpoints / single-step: a debugger uses a breakpoint trap so that execution stops at a particular instruction; a single-step trap fires after each instruction so the debugger can inspect registers and memory. Both are intentional software traps that switch the CPU from user to kernel mode and let the kernel run a handler that the user can specify.

9
What is multi-level feedback scheduling? Make a comparative analysis of the various scheduling algorithms. Discuss about the process of booting. Discuss about orphan, zombie, and daemon processes. What is an aging technique? What is real-time scheduling? What is Rate Monotonic (RM) and Earliest Deadline First (EDF)?

Multi-Level Feedback Queues (MLFQ)

MLFQ is a generalised version of RR: instead of a single FIFO ready queue, the scheduler uses multiple priority queues, and processes move between them. Each queue has its own scheduling policy — the highest-priority queue is a fixed-size quantum RR (for interactive processes), the next queues are SJF, FCFS, etc. The key is that a process starts in the highest-priority queue; if it uses up its time quantum without yielding, it is demoted to the next lower priority queue; if it spends more than X units of time waiting in a queue it is promoted. A process in a higher queue beats one in a lower queue, and within the same queue the algorithm uses RR. The parameters — number of queues, quantum per queue, demotion rule, promotion rule, and priority of a newly-created process — must be tuned; they are the knobs the scheduler turns to balance responsiveness against throughput.

Comparative Analysis of Scheduling Algorithms

AlgorithmPreemptiveKey Trade-off
FCFSNoSimplest; convoy effect — a long job first drags all later short jobs behind it. Worst average waiting time of the three basic algorithms.
SJFNoProvably optimal minimum average waiting time (among non-preemptive) but requires knowing future CPU-burst length — usually approximated by an exponential average of past bursts: τn+1 = α·tn + (1−α)·τn. Long jobs can be starved.
SRTFYesPreemptive SJF — strictly better average waiting time, but the same starvation risk, worse for a long process that is continually preempted by shorter arrivals.
RRYesFair and responsive (response time bounded by the quantum q); too small q → context-switch overhead dominates; too large q → degenerates to FCFS.
PriorityBothAllocates CPU to the highest-priority process; the highest-priority process may starve a low-priority process → fixed with aging. In practice, priorities are often set by the user (interactive process gets a high priority).
MLFQYesAdaptive — responsive interactive processes stay high; CPU-bound processes are demoted. Best average turnaround but has tunable knobs and can be gamed by a process that keeps blocking to appear interactive.

The Booting Process

  1. ROM / firmware: the machine boots from read-only memory (a small bootstrap program — historically on a special disk, now on BIOS or UEFI firmware). The firmware initialises the CPU, loads its configuration, runs POST, and locates the boot device.
  2. Bootstrap loader (MBR / partition bootloader): the firmware reads the Master Boot Record (or a UEFI ESP entry) and transfers control to the primary loader (e.g. GRUB, rEFInd).
  3. Primary loader: loads the OS kernel into RAM and initialises the boot parameters (device addresses, memory size, CPU features).
  4. Kernel: sets up the process scheduler, memory manager, file-system driver, and device drivers; mounts the root file system.
  5. init / systemd: the first user process (init or systemd) runs, launching system services (network, cron, display manager, login). The user logs in and the shell runs.

Orphan, Zombie, and Daemon Processes

Orphan process — a process whose parent has exited; it is adopted by init (or systemd). The kernel re-parents the orphan to the process with PID 1, which will reap it (call wait()) so it does not become a zombie. Example: a daemon that forks and exits, leaving the child orphaned and then the child detaches from the controlling terminal and runs in the background.

Zombie process — a process that has finished executing but whose PCB still exists; it is waiting for its parent to call wait() and reap it. A zombie uses very little memory (only its PCB — a few KB) but it does have a PID, and if the parent exits without calling wait() the zombie is re-parented to init which reaps it. A runaway parent that never waits leaves zombies accumulating until the kernel's zombie limit is reached — then the parent is terminated automatically to free slots.

Daemon process — a background process that is detached from the controlling terminal and has no user attached; it typically forks twice so it has no controlling terminal and is a child of init. Examples: sshd, httpd, crond, syslogd (Linux); Windows services running under the LocalService / NetworkService accounts.

Aging

Aging is a starvation-prevention technique in priority-based scheduling: the priority of a waiting process is gradually increased with the time it has spent waiting, so a process that has not run for a long time eventually gets scheduled. Implementation: a linear increase (+1 every minute), or exponential aging — a priority that doubles for every X time units in the wait queue. Aging is applied in the highest-priority queue in an MLFQ scheme: even a demoted CPU-bound process gradually rises back up so that it eventually runs, while interactive processes that are recently interactive stay at the top.

Real-Time Scheduling

Real-time scheduling is the scheduling of processes with deadlines. Each real-time task has a release time and a deadline; the scheduler must guarantee that every task completes by its deadline. Two kinds: hard (a missed deadline = failure, e.g. a nuclear-reactor controller must react within 1 ms) and soft (a missed deadline degrades quality, e.g. video streaming). Rate Monotonic (RM) and Earliest Deadline First (EDF) are two optimal (for a single CPU) algorithms:

Rate Monotonic (RM)

RM is a static-priority algorithm: a task's priority is inversely proportional to its period — the more frequently a task must run (the shorter its period), the higher its priority. It is computed at design time (before the program runs), so the priorities do not change at run time. It is optimal for a fixed task set on a single CPU: if any fixed-priority algorithm can meet all the deadlines of a task set, RM can. The utilisation bound for n tasks under RM is n(21/n − 1): for n = 1 the bound is 1.0 (100 %), for n = 10 it is ≈ 0.75, and it approaches ln 2 ≈ 0.69 as n → ∞. If the total utilisation U ≤ n(21/n − 1) then RM is guaranteed to schedule the task set; if U > 1 it is guaranteed to fail. Between these two bounds RM may or may not succeed.

Earliest Deadline First (EDF)

EDF is a dynamic-priority algorithm: a task's priority is inversely proportional to its remaining deadline — the closer its deadline, the higher its priority. The scheduler must re-prioritise on every event (task release, completion, new arrival) to find the task with the earliest remaining deadline. EDF is optimal on a single CPU for independent tasks (each task's execution time is at most its deadline): if any scheduler can meet all the deadlines of a task set, EDF can, and it can do so if and only if the total utilisation U ≤ 1. For fixed periodic tasks, EDF's bound is tighter than RM's: it can schedule a task set that RM cannot. The cost is that EDF must update the priority of a task on every release / completion event, so it is more complex to implement than RM; on multiple CPUs it is no longer optimal.

AspectRMEDF
Priority assignmentStatic (at design time).Dynamic (recomputed on each release).
Priority ruleInverse period.Inverse remaining deadline.
OptimalityOptimal for fixed periodic tasks on one CPU.Optimal for independent tasks on one CPU; strictly better than RM on periodic task sets.
Utilisation boundn(21/n − 1) → ln 2 ≈ 0.69.1.0 (100 %) on one CPU.
ComplexityFixed priorities — cheap scheduler.Dynamic priority recomputation — more expensive; must re-sort on every release/completion.
Multi-CPUNot optimal (a global RM or partitioned RM).Not optimal on multi-CPU; requires a global EDF or a partitioned scheme.

Module 3 Questions

1

Describe the two basic operations on a semaphore. Explain whether any integer variable with similar operations can act as a semaphore or not. What is a race condition? Explain Peterson's solution to avoiding a race condition. What are the conditions for a solution to the mutual exclusion problem? Mention the conditions for achieving mutual exclusion.

Semaphore (Dijkstra, 1965): a non-negative integer on which only two atomic operations are defined — the classical names are V() (release) and P() (acquire), modern names signal() and wait().

typedef struct { int value; ... } semaphore;

P(S) / wait(S)        V(S) / signal(S)
-------------------   -------------------
while (S.value <= 0)  S.value++;
  ; /* no-op spin */  /* wake one process blocked in wait, if any */
S.value--;

P (probeit) decrements and, if the value goes negative, blocks the calling process; V (vor) increments and wakes one blocked waiter. The whole test-and-decrement / test-and-increment must be atomic — no interrupt may arrive between the read of value and its update.

Can an ordinary integer work? No. A plain C int implements a non-atomic read-modify-write: with two processes, P1 may read S=1, P2 reads S=1 before P1 writes, both write S=0 — two processes entered the critical section although only one should have. The operation must be indivisible at the hardware level (atomic exchange / test-and-set, or disabling interrupts in kernel mode).

Race condition: the final result depends on the relative, unpredictable timing (interleaving) of concurrently executing processes — a non-deterministic bug, e.g. two threads reading, modifying and writing a shared counter and losing an update.

Peterson's solution (two processes, shared flag array and turn; read-modify-write of one shared variable is atomic on most real hardware — Dijkstra's "atomicity assumption"):

// Process Pi
do {
  flag[i] = true;
  turn = j;                       // let the OTHER process go first
  while (flag[j] && turn == j)    // yield: spin while j wants in AND j's turn
    ;                             // busy wait
  /* critical section */
  flag[i] = false;               // announce exit
  /* remainder section */
} while (true);

Mutual exclusion: if both are at the test and turn = j, Pi spins because turn == j; Pj passes. The invariant "at most one in the CS" holds. Progress (turn-taking): after Pi exits (flag[i]=false), Pj sees it and proceeds; if Pj is in its remainder section while Pi retries, Pi passes since flag[j] is false. A third condition, bounded waiting, also holds: a process waits only one turn. Extension to N processes: two locks sharing a counter (a lock per pair of processes), or a shared entry array scanned before entering.

Conditions for a correct mutual-exclusion solution: (1) Mutual exclusion — never two in the CS; (2) Progress — if no process is in the CS and some wish to enter, only those outside the CS may decide who enters next, and the decision is not postponed forever; (3) Bounded waiting — a bound exists on how long other processes may enter after a request. (A practical fourth: the algorithm must not depend on relative speeds or timing.)

2

What is the critical section problem? What are the requirements that must be met by a solution to the critical section problem? Explain the race condition in the context of process synchronization. What is a mutex? How are semaphores used to solve the critical section problem?

Critical section problem: every process has a code segment that accesses shared data (the critical section, or CS); the problem is to design an algorithm so that whenever several processes execute CS code, at most one is in its CS at any instant. The part after the CS is the remainder section.

Requirements for a solution (three classical, one practical):

  1. Mutual exclusion: no two processes are simultaneously in their critical sections.
  2. Progress: if no process is executing in its CS and one or more wish to enter, only processes outside their CS can take part in deciding which enters next, and that decision cannot be postponed indefinitely.
  3. Bounded waiting: there is a finite upper bound on the number of times other processes can enter their CS after a process has requested to enter and before that request is granted.
  4. (Practical) No timing assumption: correctness must not depend on relative speeds of processors or on absolute timing; and no process may be permanently denied (no starvation).

Race condition in synchronization: the outcome of the program depends on the relative timing of concurrently running processes. Example: counter++ compiled as temp = counter; temp = temp+1; counter = temp; — if P1 and P2 read counter=7 before either writes, the result is 8 instead of 9. Two concurrent executions that share a memory location (a shared variable) "race" to reach the correct write; the fix is a mutual-exclusion protocol around the shared code.

Mutex: a mutual-exclusion lock — a binary semaphore with value in {0, 1}, whose only purpose is to serialize entry to a CS: one process acquires it (P(lock)), the rest block; the holder releases it on exit (V(lock)). It is the canonical primitive of locking.

Semaphores solve the CS problem by pairing a mutex with each shared resource:

semaphore mutex = 1;            // binary, one per resource

void main() {
  P(mutex);
  /* critical section */
  V(mutex);
  /* remainder section */
}

Because P and V are atomic hardware primitives, two processes cannot both pass the P(mutex) when the value is 1: the first decrements it to 0, the second sees 0 and blocks. Mutual exclusion holds; exactly one blocked process is woken on each V; progress and bounded waiting are satisfied by the kernel's wake-up discipline (the scheduler guarantees no process blocks forever — the wake-up queue is FIFO on most kernels, giving bounded waiting).

3

What are the operations on a semaphore? What is a semaphore? What is the problem with these operations if they follow the classical definition? What is the possible remedy to the above problem? Write Peterson's algorithm for the two-process critical section problem.

Semaphore: a synchronization primitive introduced by Dijkstra — an integer variable S ≥ 0 with only two atomic operations:

P(S) / wait(S)          V(S) / signal(S)
-------------------      -------------------
while (S.value <= 0)     S.value++;
  ; /* busy wait */      /* wake one waiting process if any */
S.value--;

P = probe/test ("wait to acquire"), V = release ("signal to release"). Both are indivisible at the hardware level.

Problem with the classical definition: the classical P is written as a busy-wait (spin) loop — while (S.value <= 0) ;. Two serious defects: (i) Wasted CPU time — the blocked process occupies a CPU and burns cycles doing nothing; on a uniprocessor this is fatal, because a preempted spinning process will never get another chance to retest while the process it is waiting for is the one running the CPU. (ii) Priority inversion — a low-priority process spins while a high-priority process it would unblock is starved of the CPU. The classical test-then-decrement is also non-atomic if implemented with ordinary load/store instructions, which is exactly the race condition we are trying to remove.

Remedy: (a) Hardware support for atomicity. Modern CPUs provide an atomic test-and-set (exchange) instruction: TA&S(loc) { temp = *loc; *loc = 1; return temp; } executed as a single instruction; the CS becomes while (TA&S(lock)); followed by *lock = 0;. Or an atomic swap / compare-and-swap instruction. (b) Kernel sleep instead of spin. When P finds S ≤ 0, the kernel blocks the process on the semaphore's waitQ and the CPU is released to other work; V moves one waiting process to the ready queue. This removes the wasted-CPU defect.

Peterson's algorithm — two processes, shared int turn; and bool flag[2]; (initially turn = 0, flag[0] = flag[1] = false; each read-modify-write of a single shared variable is assumed atomic, Dijkstra's assumption):

// Process Pi, with j = 1 - i
do {
  flag[i] = true;
  turn = j;                       // "please go first"
  while (flag[j] && turn == j)
    ; /* yield — busy wait */
  /* critical section */
  flag[i] = false;               // announce departure
  /* remainder section */
} while (true);

Mutual exclusion is proved by contradiction: suppose both are in the CS. Pi can be in it only because when it last tested, flag[j] was false or turn was i. Pj can be in it only by the symmetric condition. But the last write to turn set it to one value; say turn = j. Then Pi passes only if flag[j] was false; Pj, being in the CS, has already set flag[j] = true — contradiction. Progress: the last process to arrive sets turn to the other's index, so the other enters. Bounded waiting: a process waits at most one other's turn. N-process extension: one lock array per pair of processes, entry guarded by the two locks that include process i; or a single shared turn pointer combined with per-process flag bits scanned in order.

4

State the producer-consumer problem. Give a solution to the producer-consumer problem, using a semaphore. Justify that your solution guarantees mutual exclusion. What is message passing? What are event counters?

Producer-consumer (bounded buffer) problem: N producer processes generate data and deposit it into a shared fixed-size buffer; M consumer processes remove data and process it. The buffer cannot overflow (full → producer must wait) or underflow (empty → consumer must wait), and the buffer must be accessed by at most one process at a time.

Semaphore solution (three semaphores: full counts the number of used slots, empty counts the number of free slots, mutex is the buffer lock):

semaphore empty = N;   // N free slots at start
semaphore full  = 0;   // no data in the buffer
semaphore mutex = 1;   // one at a time in the buffer

// Producer
do {
  item = produce();
  P(empty);            // wait for a free slot
  P(mutex);            // exclusive buffer access
  insert(item);
  V(mutex);            // release the buffer
  V(full);             // announce a data item
} while (true);

// Consumer
do {
  P(full);             // wait for a data item
  P(mutex);            // exclusive buffer access
  item = remove();
  V(mutex);
  V(empty);            // announce a free slot
  consume(item);
} while (true);

Why mutual exclusion holds: the pair P(mutex); … V(mutex) is serialized by a binary semaphore; no two processes can both hold mutex. Moreover the invariants full + empty = N always and 0 ≤ full ≤ N hold in every reachable state. Suppose a producer is in the critical region: it holds mutex; the number of free slots it sees is empty, which is at least 1 because it just performed P(empty) successfully. A simultaneous consumer would need full ≥ 1 AND mutex. But while the producer is between V(mutex) and V(full), it holds neither, so the invariant is not broken; the only way to break mutual exclusion would be for both to hold mutex at once, which the binary semaphore forbids. Hence at most one process accesses the buffer at a time.

Message passing: an inter-process communication model in which processes exchange data by send(destination, message) and receive(source, &message) system calls, with no shared memory. The message is a copy; the kernel handles routing and buffering. It contrasts with shared-memory synchronization (semaphores, locks, monitors). Two variants exist: synchronous send blocks until the receiver reads the message; asynchronous send returns immediately and the message is queued. The receiver can specify a source set and/or a message-type predicate to select which messages to match — this is the mechanism by which processes coordinate without sharing memory.

Event counters (Dijkstra): a semaphore specialized to count occurrences of a completed event. The counter starts at 0 and only goes up when the event occurs; a process calls P(e) to wait for the nth occurrence. Unlike a general counting semaphore, an event counter never goes negative because it is incremented exactly once per event and decremented once per wait. In producer-consumer, full and empty are event counters: full counts "an item has been inserted"; empty counts "a slot is free". They are used to order events (consumer must wait for producer to finish inserting before removing), not to exclude simultaneous access to a shared variable, which is what the mutex does.

5

What is the Readers-Writers problem? How to implement a solution to the Readers-Writers problem with the use of semaphores? What is the bounded buffer problem? Explain with the solution. Differentiate between binary and counting semaphore. What is the advantage of using a counting semaphore than a binary semaphore?

Readers-Writers problem: a shared data object (a database file, a table) is accessed by readers (which only read, many can be inside at the same time) and writers (which write, only one can be inside, and no reader may be inside while a writer writes). Three policies: first problem — no starvation, fair between readers and writers; second problem — reader-preferred: no reader waits while any reader is active; third problem — writer-preferred: once a writer requests access, no subsequent reader may enter.

Reader-preferring (second problem) — readers share; writers are exclusive:

semaphore mutex = 1;   // protects counter
int readCount = 0;     // readers currently in the CS
semaphore RWlock = 1;  // exclusive for writers

// Reader
P(mutex);
readCount++;
if (readCount == 1)
  P(RWlock);           // first reader locks the whole object
V(mutex);

/* read the shared object */

P(mutex);
readCount--;
if (readCount == 0)
  V(RWlock);           // last reader releases the lock
V(mutex);

// Writer
P(RWlock);
/* write */
V(RWlock);

This is reader-preferred: readers that arrive after the first reader do not wait (they increment readCount and proceed without touching RWlock). A writer may be starved if readers keep arriving — the second problem accepts that.

Writer-preferred (third problem) — one extra semaphore writeCount:

semaphore RWlock = 1, writeGate = 0, mutex = 1;
int writeCount = 0;   // writers waiting (protected by mutex)
int readCount  = 0;   // readers in the object (protected by mutex)

// Reader
P(mutex);
if (writeCount > 0) { V(mutex); P(writeGate); P(mutex); }
readCount++;
if (readCount == 1) P(RWlock);       // first reader locks the object
V(mutex);
/* read */
P(mutex);
readCount--;
if (readCount == 0) {
  V(RWlock);
  if (writeCount > 0) V(writeGate);  // let the next waiting writer in
}
V(mutex);

// Writer
P(mutex);  writeCount++;  V(mutex);
if (writeCount > 1) P(writeGate);    // queue behind earlier writers
P(RWlock);
/* write */
V(RWlock);
P(mutex);
writeCount--;
if (writeCount > 0) V(writeGate);    // release the next queued writer
V(mutex);

Because a reader blocks on writeGate whenever writeCount > 0, once any writer arrives it gets the object before subsequent readers — writer preference without starving writers, while readers that arrive when no writer is waiting proceed without waiting.

Bounded buffer problem: N producers write items to a fixed-size array of N slots; M consumers read them. A producer must wait when the buffer is full; a consumer must wait when it is empty; only one process accesses the buffer at a time.

Solution (three semaphores):

semaphore empty = N;   // N free slots
semaphore full  = 0;   // no items yet
semaphore mutex = 1;   // exclusive buffer access

// Producer
P(empty);  P(mutex);  insert();  V(mutex);  V(full);
// Consumer
P(full);   P(mutex);  remove();  V(mutex);  V(empty);

Binary vs counting semaphore:

AspectBinary semaphoreCounting semaphore
Value range{0, 1} — a lock0 … N — a counter
PurposeMutual exclusion on a shared resourceLimits concurrent access; counts resources or events
ExampleLock on the shared buffer (mutex)full, empty in bounded buffer; count of free device instances

Advantage of a counting semaphore: a counting semaphore expresses "at most k may be inside at once" in one line — semaphore S = k; with P(S)/V(S) around the shared region. Modeling "at most 5 processes" with five separate binary semaphores and a mutex that assigns one of them requires a table plus a lock; the counting semaphore does it in one primitive. It also carries a quantitative state (the number of waiting processes is the value itself), which a binary semaphore cannot. This makes counting semaphores the natural choice for bounded buffers, device pools, and event counters.

6

What is the Dining Philosophers problem? How can a semaphore be used for the Dining Philosophers problem? How does synchronization and scheduling go hand in hand? What are the problems of busy-wait implementation of a semaphore? Explain how it is solved.

Dining Philosophers problem: five philosophers sit around a circular table with one fork between each pair; to eat, a philosopher must pick up both the left and right fork. The problem is to design an algorithm that prevents deadlock — all five holding one fork each and waiting forever for the other.

Classic 5-fork solution (one semaphore per fork):

semaphore fork[5] = {1,1,1,1,1};  // one per fork

// Philosopher i (forks i and (i+1)%5)
do {
  P(fork[i]);
  P(fork[(i + 1) % 5]);
  /* eat */
  V(fork[i]);
  V(fork[(i + 1) % 5]);
  /* think */
} while (true);

This solution deadlocks if all five simultaneously pick up their left fork: the circular wait is formed (P1 holds fork 1, wants fork 2; … P5 holds fork 5, wants fork 1).

Deadlock-breaking solutions:

  1. Asymmetric pickup: philosopher 4 picks up the right fork first, others the left. At least one philosopher breaks the circular chain — mutual exclusion and progress are preserved by the ordering asymmetry.
  2. Resource hierarchy: number the forks 1–5; every philosopher picks up the lower-numbered fork first. A cycle is impossible because the fork numbers around the loop would have to strictly increase and then decrease — this is the classic Coffman prevention of circular wait.
  3. Waiter semaphore: only 4 of 5 may sit at a time — semaphore in = 4; each does P(in) before the first fork, V(in) after both. With 4 seated, the 5th fork is always free — the circular-wait condition cannot form.

Synchronization and scheduling go hand in hand: synchronization is the protocol that decides which process may use which resource; scheduling is the mechanism by which the OS picks which ready process runs. A process blocked on a semaphore goes to its waitQ and the CPU goes to another ready process; a signal() moves one waiter to the ready queue. The two must stay consistent on what "blocked" and "ready" mean: a fork-holder that is preempted is still a holder, and a woken process that is preempted again must still be counted as waiting.

Problems of busy-wait (spin-wait) semaphores:

  1. CPU waste: a process calling P(S) with S = 0 spins in a tight loop doing no useful work — on a multiprocessor it idles one core; on a uniprocessor it is catastrophic, since the spinner occupies the CPU while the process that must call V(S) is starved of it.
  2. Priority inversion: a low-priority spinner occupies the CPU; a high-priority process that must call V(S) to make progress is starved, because the spinner is not being preempted. The OS must preempt the spinner to let the woken process run — defeating the purpose of the spin.

Solution — kernel sleep (waitQ): when P(S) finds S ≤ 0, the kernel blocks the process on the semaphore's waitQ and gives the CPU to another ready process; when V(S) is called and waitQ is non-empty, the kernel moves one process from waitQ to the ready queue. No CPU cycles are wasted. The cost is a context switch on every P that blocks — expensive for a lock held only briefly — so spin locks are still preferred for very short critical sections on multiprocessors.

7

Explain how the use of monitors guarantee mutual exclusion?

Monitor (Hoare, 1974): a language-level module in which all shared data and the procedures that access it live, and in which the compiler enforces that at most one process is inside the monitor at any time. The monitor is a record with a set of procedures; entry is serialized by the monitor's intrinsic mutual-exclusion protocol — the compiler inserts a lock at the top of every monitor procedure and releases it on exit.

monitor database {
  int read_count = 0, write_count = 0;
  condition can_read, can_write;

  procedure read() {
    read_count++;
    if (write_count > 0)
      wait(can_read);     // a writer is active or waiting — yield
  }

  procedure end_read() {
    read_count--;
    if (read_count == 0 && write_count > 0)
      signal(can_write);  // last reader gone — wake a waiting writer
  }

  procedure write() {
    write_count++;
    if (write_count > 1 || read_count > 0)
      wait(can_write);    // wait for exclusive access
  }

  procedure end_write() {
    write_count--;
    if (write_count == 0)
      signal(can_read);   // no writer left — wake waiting readers
    else
      signal(can_write);  // pass the turn to the next writer
  }
}

How mutual exclusion is guaranteed: (i) Intrinsic lock — the monitor is entered through exactly one procedure; the compiler inserts a binary lock at the entry of each procedure and releases it on every exit path. Two processes cannot both be inside the monitor body at once — this is the guarantee of mutual exclusion. (ii) Condition variables — a condition c has two operations: wait(c) releases the monitor's lock, blocks the calling process on c's queue, and re-acquires the lock when the process is woken; signal(c) moves one waiting process from c's queue to the ready state. Because only the lock-holder may call wait/signal, and because a process inside wait(c) holds no part of the invariant it protects, the monitor's data invariant (here: "at most one writer active, and no writer while read_count > 0") remains true on entry and on every exit — no process can observe or corrupt it mid-step. (iii) No busy-wait — blocking is done by the kernel on the condition's queue, so the CPU is not wasted on spinning, unlike a classical semaphore.

Contrast with semaphores: semaphores are low-level — the programmer must get the P/V ordering right; a misplaced V before a P can corrupt state. Monitors are high-level — the compiler serializes entry and exit, and condition variables replace the waitQ + mutex dance with two clean operations wait(c) and signal(c). The monitor encapsulates the shared data and its synchronization protocol, making it a safe data structure in the language sense. The main cost: a monitor is a language construct, so it must be supported by the compiler and the OS; semaphores are a hardware/kernel primitive, so they are always available.

Module 4 Questions

★ Note: Solve problems on Banker's Algorithm ★
1

What is deadlock? What is starvation? Give the difference between deadlock and starvation. Explain Banker's algorithm. Show how it is helpful to overcome deadlock. "All unsafe states may not lead to deadlock" - why or why not? Describe the necessary and sufficient conditions for the occurrence of deadlock.

Deadlock: a set of processes is deadlocked if each process in the set is waiting for an event that only another process in the same set can cause; none can make progress. The four Coffman conditions must all hold:

  1. Mutual exclusion — at least one resource is non-shareable.
  2. Hold and wait — a process holds at least one resource while waiting for another.
  3. No preemption — a resource can be released only voluntarily by the holder.
  4. Circular wait — a closed chain of processes exists, each waiting for a resource held by the next.

Starvation: a process is indefinitely delayed — it waits forever for a resource that is perpetually granted to others. Starvation needs no closed loop; it is an unfairness in the scheduling/allocation policy.

AspectDeadlockStarvation
StateClosed circular wait among the setNo closed loop; one process is always delayed
CauseResource-allocation cycleScheduling/priority policy (unfairness)
RecoveryTerminate / preempt / roll backChange the priority policy; add a fairness bound

Banker's algorithm (Dijkstra, 1965) is a deadlock-avoidance algorithm. Each process declares its maximum claim per resource type before it starts. A request is granted only if the resulting state is safe — i.e. a safe sequence P1, …, Pn exists such that for each k, Pk's remaining need ≤ (available + resources held by P1 … Pk−1). If no such sequence exists the state is unsafe and the request is refused.

How it helps overcome deadlock: by confining the system to safe states — and since every deadlock is an unsafe state — no deadlock can ever be reached: it is avoidance, checked at every allocation.

Worked example. Five processes, three resource types A(10), B(5), C(7) — 22 instances total. Initial state:

Allocation (A B C)Max (A B C)Need = Max − Alloc (A B C)
P00 1 07 5 37 4 3
P12 0 03 2 21 2 2
P23 0 29 0 26 0 0
P32 1 12 2 20 1 1
P40 0 24 3 34 3 1

Available = (3, 3, 2). Find a safe sequence. P1: need (1,2,2) ≤ avail (3,3,2)? Yes. P1 finishes: avail ← (3,3,2) + (2,0,0) = (5,3,2). P3: need (0,1,1) ≤ (5,3,2)? Yes. avail ← (5,3,2) + (2,1,1) = (7,4,3). P4: need (4,3,1) ≤ (7,4,3)? Yes. avail ← (7,4,3) + (0,0,2) = (7,4,5). P0: need (7,4,3) ≤ (7,4,5)? Yes. avail ← (7,4,5) + (0,1,0) = (7,5,5). P2: need (6,0,0) ≤ (7,5,5)? Yes. Safe sequence ⟨P1, P3, P4, P0, P2⟩ — the state is safe.

Now test an unsafe request. P0 requests (0, 0, 2): P0's need is (7,4,3), so the request is valid (0 ≤ 7, 0 ≤ 4, 2 ≤ 3). Simulate the grant: P0's allocation becomes (0,1,2), and Available ← (3,3,2) − (0,0,2) = (3,3,0). Search for a safe sequence: P1 needs 2 C but 0 available; P3 needs 1 C; P4 needs 1 C and 4 A; P0 needs 4 C; P2 needs 6 A but only 3 available. No process can finish — the state is unsafe, so the request must be refused and P0 must wait until some process releases resources.

"All unsafe states may not lead to deadlock" — why? An unsafe state is one in which no safe sequence exists for the current allocation. But a process may still release resources and exit; a safe state may be reachable by a future release. Deadlock requires that no process in the circular-wait set can ever proceed — an unsafe state is necessary but not sufficient for deadlock. The system may enter an unsafe state and still recover.

Necessary and sufficient condition for deadlock: a deadlock occurs if and only if the resource-allocation graph contains a cycle and every resource type in that cycle is single-instance (at most one instance per type, so no free instance can break the loop). The four Coffman conditions are the necessary ones; the cycle criterion is the sufficient one.

2

Critically comment on the following topic: A cycle in a resource allocation graph does not always imply the occurrence of deadlock. What is the optimistic assumption made in the deadlock detection algorithm? How can this assumption be violated?

Resource Allocation Graph (RAG): a directed graph with two kinds of vertices: processes (circles) and resource types (squares, with one dot per available instance). A request edge P → R means P is waiting for an instance of R; an assignment edge R → P means P currently holds an instance. The key theorem:

Single-instance resource types: if the system has at most one instance per resource type, then a cycle in the RAG is both necessary and sufficient for deadlock. Necessity: deadlock requires circular wait, and circular wait is exactly a cycle in the RAG. Sufficiency: if every resource in the cycle has exactly one instance and each process in the cycle is waiting for the instance held by the next, no process in the cycle can ever be released, so the cycle is a permanent deadlock.

Multi-instance resource types: if a resource type has more than one instance, a cycle is necessary but not sufficient for deadlock. A cycle may exist while a process in the cycle still has access to enough instances of every resource it needs (because it is not the only one waiting for that type). The process can complete and release its resources, breaking the cycle. A cycle in a multi-instance RAG may be resolved; it is not a proof of deadlock. To detect deadlock in a multi-instance system, one must use a deadlock-detection algorithm (e.g. a wait-kill graph or the resource allocation cycle search) that walks the request-and-hold relationships across all instances.

Optimistic assumption in the detection algorithm: the algorithm assumes that the system will eventually reach a safe state — that is, every process will eventually release the resources it holds, so the detection algorithm can find a deadlock-free schedule. In other words, the detection algorithm assumes that no process will hold a resource indefinitely (no indefinite hold, no livelock). This is the optimism of the detection approach: it does not prevent a process from acquiring a resource and then never releasing it; it only detects the deadlock after it has formed.

How the assumption is violated: (i) A bug in the user program: a process may have a coding error that causes it to hold a resource forever without ever releasing it. The detection algorithm sees the cycle and reports deadlock, but the "deadlock" is actually a bug — the process is not waiting for another process; it is simply broken. (ii) Livelock: two or more processes may constantly change state in response to each other, making no progress. A polite-diners example: two people in a narrow hallway each step to the right to let the other pass, but they both step right at the same time, then both step left, and so on, in an endless synchronized cycle. No process is blocked; no process makes progress. A detection algorithm that looks for a cycle in the waiting graph will not find one — the processes are not waiting on each other in a closed loop; they are actively changing state. The livelock is not a deadlock, but it has the same observable effect: no progress. (iii) Priority inversion: a high-priority process may be blocked by a low-priority process that holds a resource; the high-priority process can never run to release its own resources, so the system appears deadlocked. The detection algorithm may flag it as a deadlock, but the root cause is the scheduling policy, not a circular wait.

3

With an example, describe if resources are not properly allocated to the processes it may lead from a safe state to an unsafe state. Prove that linear ordering for denying the "circular wait" condition actually prevents circuits from developing in the Resource Allocation Graph (RAG). What are the methods for handling deadlock?

Safe → unsafe transition: a safe state is one in which a safe sequence exists; the system moves to an unsafe state when a new allocation request is granted. The transition is dangerous because an unsafe state may lead to deadlock (Banker's algorithm refuses exactly such requests).

Example: two resource types A and B, each with 3 instances. Three processes with maximum claims:

ProcessHold AHold BMax AMax BNeed ANeed B
P0203010
P1020301
P2012120

Available: A = 3 − 2 = 1, B = 3 − 3 = 0. Safe sequence: P0 needs (1,0) ≤ avail (1,0) → P0 completes, releasing its 2 A → avail (3,0). P2 needs (2,0) ≤ (3,0) → P2 completes, releasing its 1 B → avail (3,1). P1 needs (0,1) ≤ (3,1) → P1 completes. ⟨P0, P2, P1⟩ — the system is in a safe state.

Now P2 requests 1 instance of A (it already holds 1 B; after the request it holds 1 A + 1 B, still below its max of 2 A). Granting it leaves Available = A: 0, B: 0, and P2's remaining need is (1,0). No process can complete: P0 and P2 each need 1 A but none is available, and P1 needs 1 B while all 3 B are held. The state is unsafe — in fact a deadlock, since P0 waits for the A held by P2, P2 waits for the A held by P0, and P1 waits for B held by P2. The Banker's algorithm, simulating the grant, finds no safe sequence and refuses the request; P2 waits, and the system stays safe. The same request granted without checking takes the system from a safe state to an unsafe one.

Linear ordering prevents circular wait. Assign to every resource type a strict total order R1 < R2 < … < Rn; each process may request resources only in increasing index order, and a request is granted only if the resource's index exceeds the index of every resource the process currently holds.

Proof: suppose a circular wait exists: Pi waits for ri, which Pi+1 holds. By the ordering rule, Pi may request ri only if index(ri) exceeds the index of every resource Pi holds; and Pi+1 may request ri+1 only if index(ri+1) > index(ri) (since Pi+1 holds ri). Going once around the loop gives index(rn) > index(rn−1) > … > index(r1) > index(rn) — a contradiction, since a strict total order cannot cycle. Hence no circuit can form in the RAG; circular wait is broken and deadlock is impossible. ∎

Methods for handling deadlock:

  1. Prevention — break one or more of the four Coffman conditions: make the resource shareable (mutual exclusion); require all resources to be requested and allocated at once (hold-and-wait); allow the OS to forcibly take a resource (no-preemption); impose a linear ordering on resource requests (circular wait).
  2. Avoidance — dynamically check the state before each grant and refuse requests that would make it unsafe (Banker's algorithm); the system stays in the safe region.
  3. Detection and recovery — allow deadlock to occur, periodically find a cycle in the RAG / wait-for graph, then recover by terminating processes, preempting resources, or rolling back to checkpoints.
  4. Ignore the problem (treatment) — the OS takes no action; the application detects deadlock (e.g. by timeouts) and kills the process. This is the approach of most real operating systems (UNIX, Linux, Windows).
4

State four necessary conditions for deadlocks. Explain circular wait for the occurrence of deadlock and how it can be prevented. What is livelock? List down the methods of deadlock detection and deadlock avoidance. Explain how deadlock can be recovered through deadlock.

Four Coffman necessary conditions for deadlock: (1) Mutual exclusion — at least one resource is non-shareable; (2) Hold and wait — a process holds at least one resource and waits for another; (3) No preemption — a resource can only be released by the holder; (4) Circular wait — a closed chain of processes exists such that each waits for a resource held by the next.

Circular wait: the most directly exploitable condition for prevention — a closed loop P1 → P2 → … → Pn → P1 in which Pi waits for a resource held by Pi+1. Prevention methods that break circular wait: (a) Linear ordering — assign a total order to resource types; each process requests resources only in increasing index order, which makes a cycle impossible. (b) All-or-nothing allocation — a process requests all the resources it will need before it starts; the OS allocates them all at once or makes the process wait, breaking hold-and-wait (which in turn destroys circular wait). (c) Resource hierarchy — a process may request only types of lower index than any it holds, the same argument as (a).

Livelock: a set of processes is constantly changing state in response to each other but making no progress. The classic polite-diners example: two people in a narrow hallway each step right to let the other pass, then both step left, endlessly. No process is blocked, but none makes progress. Livelock is not deadlock: in deadlock the processes are blocked (waiting); in livelock they are active (changing state). It is also not starvation: in starvation a single process is indefinitely delayed; in livelock all processes are actively moving, yet no progress is made.

Methods of deadlock detection: (i) RAG cycle detection — for single-instance resources, a cycle in the resource allocation graph is a deadlock; search with DFS. (ii) Wait-for graph — for multi-instance resources, an edge P → Q means P waits for a resource that Q holds; a cycle is a deadlock. (iii) Timeouts — each process sets a timer; if it fires before the resource is acquired, a deadlock is assumed (simple, but a slow process may be falsely flagged). (iv) Wait-kill graph — encodes "P waits for Q, so kill Q"; the algorithm finds a minimal set of processes to kill to break the deadlock.

Methods of deadlock avoidance: (i) Banker's algorithm — the process declares its maximum claim; a request is granted only if the resulting state is safe. (ii) Restricted allocation — the OS restricts how many processes may be active at once (e.g. at most N−1 of N philosophers at the table). (iii) Resource hierarchy / linear ordering — a total ordering of resources; the OS allocates only in increasing order. (iv) Periodic detection with rollback — the OS checks for deadlocks and rolls one process back to its last checkpoint when found.

Deadlock recovery — when a deadlock is detected, the OS must break it:

  1. Process termination — kill one or more of the deadlocked processes. Simplest: kill the whole set; more conservative: kill one process at a time, re-checking the RAG until no cycle remains. Cost: the killed processes lose all their work.
  2. Resource preemption — the OS forcibly takes a resource from one process and gives it to another. Cost: a context switch and potential state corruption (a preempted process mid-transaction may hold inconsistent data).
  3. Rollback (checkpointing) — the OS restores a process to a checkpoint (a saved snapshot) and re-executes from there. The process must periodically save state; cost is re-execution time since the last checkpoint.

The choice depends on the cost of re-execution, the criticality of the work, and the number of deadlocked processes. In practice the OS detects the deadlock with a wait-for graph, rolls one process back to a recent checkpoint, and re-schedules the rest.

Module 5 Questions

★ Note: Numerical on first fit, best fit, worst fit, page replacement problems, problems of TLB ★
1

Difference between logical address and physical address? What is fragmentation and how is it solved? What are first fit, best fit, worst fit? Compare them.

Logical (virtual) vs physical address. A logical address is the address generated by the CPU — it is what appears in a program's instruction and data fields, i.e. the offset inside a process's own address space. It is produced by the MMU relative to the process. A physical (actual) address is the address that finally appears on the address bus, pointing at a real location in main memory. Mapping from logical to physical is done by the memory-management unit (MMU) — typically the base (relocation) register for contiguous allocation (physical = base + offset, checked against the limit register) and the page table for paging (frame number = f(virtual page number); physical address = frame × frame size + offset). Consequence: a program written in logical addresses can be loaded anywhere in memory, enabling relocation and protection.

Fragmentation. Wasted memory that cannot be allocated as a single usable block. Two forms: External fragmentation — free memory exists in total but is scattered in many small gaps between processes, none large enough for the next request; Internal fragmentation — the allocated block is larger than the request, so the unused portion inside it is wasted. Solutions: external fragmentation is attacked by memory compaction (shifting all processes toward one end to create one large free hole — the moving of processes is the expensive part), and by non-contiguous allocation schemes (paging and segmentation), which eliminate the need for a single contiguous block per process. Internal fragmentation is reduced by smaller page sizes (wasting on average half a page) and by variable-size partitioning / segmentation.

The three placement algorithms (all operate on a list of free holes in a fixed-size partitioning scheme): First fit — allocate the first hole large enough, in list order, stopping as soon as it finds one. Fast; tends to leave small useless holes near the start of the list. Best fit — scan the whole list and take the smallest hole that fits. Minimizes leftover waste inside the hole but is slow (full scan) and leaves many tiny unusable crumbs. Worst fit — scan the whole list and take the largest hole, on the idea that the largest leftover is most reusable later; also slow, and the large hole it leaves often gets cut into small pieces by later requests.

Worked numerical — first / best / worst fit. Partitions: 100, 500, 200, 300 MB. Request sequence: 212, 412, 112 MB.

RequestFirst fit (partition, remaining)Best fit (partition, remaining)Worst fit (partition, remaining)
212 MB500 MB (100 too small) → 288 MB left300 MB (smallest that fits) → 88 MB left500 MB (largest) → 288 MB left
412 MB288, 200, 300 all too small → fails500's 88 left too small; 200, 300 too small → fails288, 300, 200, 100 all too small → fails
112 MB500's 288 MB → 176 MB left200 MB (smallest that fits; 300 has only 88) → 88 MB left500's 288 MB (largest) → 176 MB left

So all three fail on the 412 MB request (total free is only enough if it had been placed first — showing placement order matters); best fit still places all three *smaller* requests with the least leftover waste. Note: on this sequence worst fit's placements coincide with first fit because the largest hole is also the first suitable one.

2

Explain Belady's anomaly? How is paging implemented in hardware? What is a TLB and how does it work? Pros/cons of unequal-size partitions in fixed-size partitioning? Why are page sizes a power of 2?

Belady's anomaly: counter-intuitively, for some reference strings the FIFO page-replacement algorithm produces more page faults with a larger number of frames than with a smaller one — adding frames makes performance worse. FIFO is not a "stack algorithm" (its behavior depends on the frame count), so the anomaly is possible; algorithms like OPTIMAL and LRU are stack algorithms and never show it. This is the classic demonstration of why FIFO is considered the least satisfactory replacement algorithm. Worked numerical below.

Hardware implementation of paging. Two pieces of hardware. (1) A page table, one per process, in memory: each entry holds the frame number of the virtual page plus status bits — valid/invalid, reference, modify, and sometimes protection. The page table base (limit) register points to it and holds its length. (2) A page table walker in the MMU: on every access it splits the virtual address into (page number, offset), looks up the entry, checks valid (if invalid → page fault → OS brings the page in), and computes physical address = frame number × frame size + offset. The table needs one cache line per page entry, and a two-stage lookup (TLB → page table → memory) is what the TLB shortens.

TLB (Translation Lookaside Buffer): a small, fast associative (hardware) cache for the most recently used page-table entries, placed between the CPU and the page table. It holds {virtual page number → frame number} with a valid bit. On each access the TLB is probed in parallel with main memory: on a TLB hit the frame number comes directly and only one memory access is needed; on a miss the MMU walks the page table in memory (second access), the TLB is updated (often with an LRU victim). Because of locality, most accesses hit — a 50–90% hit ratio — which is what makes paging fast.

Worked numerical (TLB) — effective access time. Hit ratio h = 0.9, memory access = 200 ns, TLB lookup = 10% of memory = 20 ns. On a hit: TLB + one memory = 20 + 200. On a miss: TLB + two memory accesses (walk page table, then fetch the word) = 20 + 400. So

EAT = h·(TLB + mem) + (1−h)·(TLB + 2·mem)
    = 0.9·(20 + 200) + 0.1·(20 + 400)
    = 0.9·220 + 0.1·420
    = 198 + 42
    = 240 ns

Unequal-size partitions within fixed-size (partitioned) allocation. Pros: (i) small requests no longer waste a whole large block — internal fragmentation shrinks; (ii) utilization improves because each process takes a partition closer to its size; (iii) small processes and large ones can coexist in one memory. Cons: (i) external fragmentation remains and gets worse (a big process may not fit even when enough total free space exists — this is exactly why variable-size free lists and later paging/segmentation were invented); (ii) the OS needs many different-sized free lists; (iii) the number of usable partitions and total partition count fall; (iv) the partition-management table and lookup are more complex; (v) it can encourage placing one process per partition (no sharing) and makes the memory less flexible than paging.

Why page sizes are a power of 2: because a power-of-two size lets the address split be done by pure bit shifting / masking — page number = address >> log2(size), offset = address & (size−1) — no division, no multiplication. The MMU hardware is simpler and faster; it is uniform and scales cleanly; it matches the structure of the binary machine (byte = 2³, kilobyte = 2¹⁰, …); page sizes of 2n bytes align naturally with block and sector sizes, and it simplifies cache, virtual-memory and address-translation design. Practical sizes: 4 KB, 8 KB, 64 KB, …

Worked numerical (Belady's anomaly, FIFO). Use the classic string 1,2,3,4,1,2,5,1,2,5,1,2,3,4,5 (15 refs). Frame-state trace:

Ref #123456789101112131415
Access123412512512345
FIFO, 3 frames — faultsFFFFFFFHHHHHFFH
FIFO, 4 frames — faultsFFFFHHFFFHHHFFF

3 frames → 9 faults; 4 frames → 10 faults. More frames yet more faults — that is Belady's anomaly. The brief's second string (7,0,1,2,0,3,0,4,2,3,1,3,2,1,0,4,2,7,3) actually traces to 2 frames = 16, 3 frames = 15 faults (3 frames does better here — the normal, non-anomalous direction), so it is the first string that demonstrates the anomaly on the 3-vs-4 comparison. The takeaway for the exam: FIFO fault counts are not monotonic in frame count; LRU and OPTIMAL are stack algorithms, so for them more frames ⇒ never more faults (no anomaly).

3

What is thrashing and its cause? What are dynamic loading and dynamic linking, and how are they related? Explain the worst-fit algorithm, its benefits, and drawbacks of compaction. How is thrashing detected?

Thrashing: a state in which a process spends more time paging than computing — the working set of all resident processes exceeds available memory, so every reference is a page fault, the OS swaps one process's page for another's immediately (the "run-for-help" pattern), and total CPU utilization collapses (often to a few percent) with no useful progress. Causes: too many processes admitted relative to memory, or a process whose working set suddenly grows; combined with a page-replacement policy that is not sensitive to the working set. Recovery/detection: monitor page-fault frequency — if it stays above a threshold (mean intervals between faults, or faults per time unit, exceed the target), the OS suspends some process (keeps its pages) and gives its pages to others; equivalently, keep the admitted process count below the point where the sum of working sets fits memory. The working-set model (track WSS per process and admit only when Σ WSS ≤ available frames) is the classic preventive test.

Dynamic loading (run-time loading). Instead of loading a program into memory all at once, only the main control routine is loaded; subroutines (e.g. error handlers) are placed in load units and are loaded on demand — the moment the program needs them. Benefit: less memory (routines that may never run occupy nothing), faster start. Cost: some run-time lookup of units.

Dynamic linking (run-time linking). The program is not linked at build time; each module is a small librarian routine that resolves names to library routines at run time (or lazy binding — deferred until the call is made). Benefit: libraries can be updated or shared without relinking all dependents. Cost: each link is a run-time overhead (slower than static, more library calls, more run-time checks).

How they relate: both are run-time deferrals of work a compiler/linker would otherwise do at load time. Dynamic loading defers reading routines from disk; dynamic linking defers name resolution. Typically they work together — a dynamically linked, dynamically loaded program loads a librarian routine the first time a library call appears. Both save memory and start time at the cost of run-time work, and both require a small run-time component (a load map or a librarian routine) to keep address translation correct.

Worst-fit algorithm: for each allocation request, scan the entire free-partition list and place the request in the largest available partition (or, in paging, take the frame with the largest gap to its next use in some variants). Benefits: leaves behind the largest single leftover, which is more likely to satisfy a future large request than the crumbs best fit leaves; useful when request sizes vary widely. Drawbacks: every request costs a full scan (slow); the large holes it leaves tend to get chopped into many smaller pieces by later requests, eventually producing no useful large hole — and it tends to waste total free space on large, poorly matched assignments.

Drawbacks of compaction. Compaction (shifting all processes to one end to make one big free block) is conceptually simple but expensive — it moves many processes and all their page tables, registers, and MMU base registers; it must be done while the system is stopped (interrupts off, no I/O) for consistency, so it is not suitable for a busy system and adds dead time; it is I/O-bound and slow when many processes must be moved; and it is defeated in virtual-memory systems by external fragmentation in the backing store (swaps), because compaction of physical memory does not compact the swap area. Hence modern systems use paging/segmentation instead of periodic compaction.

4

What is virtual memory and how is it supported/implemented? Why combine segmentation and paging? What are swap-in and swap-out? What is multi-level paging? Merits and demerits of virtual memory.

Virtual memory: the abstraction that lets a process's address space be larger than physically installed RAM by using disk as an extension of memory: a process may keep only its working set resident and the rest in a backing store (swap space / page files). The address space is per-process and independent of physical placement; the OS can over-admit (run more processes than will fit at once) and only pay in I/O when working sets don't co-fit. Implementation: physical RAM is divided into fixed-size frames; a process's logical space is divided into pages of the same size; the page table (one entry per virtual page: frame number + valid/invalid, reference, modify, protection bits) maps only the currently-resident pages; a TLB accelerates the lookup; an invalid (or demand) bit means "page not in memory," and a reference to it triggers a page fault, in which the OS (i) verifies the reference is legal, (ii) finds a free frame (replacing one if needed via LRU/FIFO/OPT/SC), (iii) if the victim page's modify bit is set, writes it back, (iv) reads the wanted page from disk, (v) updates the tables and restarts the instruction.

Why combine segmentation and paging (segmentation with paging): segmentation alone has big drawbacks — external fragmentation (segments of variable size can't pack into frames; a large segment may not find room even when total free space exists), variable length complicates allocation, and inefficient small segments waste memory and complicate management. Paging alone erases this by giving fixed-size units, but it loses the semantic structure (code segment, data segment, stack) that makes segmentation useful for protection (per-segment read/write/execute permissions) and sharing (share a whole library segment across processes). Segmentation with paging keeps both: the user programs in meaningful variable-size segments; internally the OS pages each segment's space into physical frames. The address becomes a three-level tuple (segment number, page number, offset); the page table is per-segment, and protection/sharing is checked at segment granularity while physical placement is at page granularity. This is the scheme used in early Intel and many virtual-memory OSes.

Swap-in / swap-out: Swap-out is writing a process's image (all pages) out of memory to a swap area on disk (or a page file) — done when the process is blocked for I/O, when the system is overcommitted and some process must be evicted, or for disk swap in a system with no virtual memory. Swap-in is the reverse — reading the image back from disk to memory. With virtual memory, demand paging replaces whole-process swapping: only pages actually referenced get swapped in; whole-process swap-in/swap-out is used when memory is too tight or for hierarchical storage to make more room for active processes.

Multi-level (hierarchical) paging: when the address space is large enough that a single flat page table (e.g. 32-bit → 2²² × 4 B = 16 MB) won't fit, store only the present page-table entries in memory and keep the rest on disk; split the table into fixed-size directory blocks, each either resident or on disk. Lookups cascade: top-level block (always in memory) → middle block (on miss, one extra disk I/O) → leaf block. Generalized to N levels; in modern systems (x86-64, 32-bit) 4-level tables are typical. The cost is extra memory hops (TLB miss + two or three additional table lookups), partly hidden by page-table caches (TLBs that hold intermediate blocks).

Merits of virtual memory: (1) a process's address space exceeds physical RAM; (2) over-admission — many processes in memory at once, CPU stays busy; (3) the program is larger than main memory — no memory constraint on program size; (4) simplified allocation — fixed-size frames beat variable-size partitioning; (5) protection — per-page permission bits; (6) address independence — the same binary runs in any physical placement; (7) efficiency — only touched pages occupy memory (demand loading). Demerits: (1) hardware overhead — page tables, TLBs, MMU logic; (2) extra I/O on misses (disk faults are orders of magnitude slower than hits); (3) thrashing risk — over-admission without a working-set check collapses performance; (4) page size fixed — small pages waste table space and TLB; large pages waste memory and increase fault granularity; (5) protection and sharing at page granularity are coarse for fine-grained code; (6) address-translation overhead — a two-stage lookup (TLB + page table) on every reference, amortized by the TLB cache.

5

What is DMA and how does it increase concurrency? What are the types of fragmentation? Advantages/disadvantages of paging and segmentation? Difference between a page and a frame? How does DMA perform, its benefits, and the types of DMA controllers?

DMA (Direct Memory Access): a hardware mechanism (a DMA controller) that moves blocks of data between I/O devices and main memory without the CPU issuing a store/load per byte. The CPU programs the controller with the source, destination, and byte count, then issues a DMA request and is released; the controller does the transfers and raises an interrupt on completion. How it increases concurrency: without DMA, each byte (or word) transfer requires an interrupt, saving/restoring context, and a CPU loop — for a disk block, that can be thousands of interrupts and the CPU is idle waiting for the I/O device. With DMA, the CPU is free to run other processes while the transfer proceeds; only one interrupt is generated for the whole block. This is the core of I/O concurrency: CPU work and I/O work overlap.

Types of fragmentation (memory and disk): Internal fragmentation — waste inside an allocated block (e.g. a 50 KB process in a 64 KB frame leaves 14 KB unused); unavoidable in fixed-size schemes, minimized by small units. External fragmentation — total free space is scattered in many small gaps, none large enough for a request, even though the sum is sufficient; eliminated by compaction or by non-contiguous schemes (paging/segmentation). On disk: external fragmentation of free sizes, internal fragmentation at the last block of a file (partial block).

Paging — advantages: no external fragmentation (frames are fixed and equal); a process's logical space can be larger than RAM (virtual memory); pages can be shared (library pages); demand loading — only touched pages in memory; simple protection at page granularity; processes can be placed in any frame (address independence). Disadvantages: page-table overhead (one entry per page — large in 32-bit, 2²² × 4 B = 16 MB); two memory references per access without a TLB (TLB lookup → page table → data); TLB misses slow down; page size is fixed — small pages over-use tables/TLBs, large pages waste and increase fault granularity; internal fragmentation of half a page per process; address-translation hardware cost.

Segmentation — advantages: natural program structure — the user sees code, data, stack; easy protection (per-segment read/write/execute) and sharing (whole segments shared between processes); growing segments (stacks) supported; logical and addressability are clean. Disadvantages: external fragmentation (variable-size segments can't pack into fixed frames); search is slow — finding a free segment of size S costs a linear scan of the free list; compaction expensive (must move many segments + update all references); the page-table overhead is avoided only at the cost of these management problems; segments are large, so a small change may force a large reallocation; sharing granularity is coarse.

Page vs frame: a page is the unit of logical (virtual) address space — it's a piece of a process. A frame is the unit of physical address space — it's a slot in main memory. Pages are allocated to frames by the page table. They are the same size (typically 4 KB), but conceptually different: the page number is process-relative, the frame number is absolute physical memory. One frame holds exactly one page.

DMA controllers — types: (1) Memory-to-memory — moves a block from one physical address to another (used for swapping and disk buffers). (2) Device-to-memory (input) — moves a block from an I/O device into memory; the controller polls the device's status and, when data is ready, writes to the memory address (typical of disk read). (3) Memory-to-device (output) — the reverse; the controller reads from memory and hands bytes to the device (typical of disk write). (4) Device-to-device (rare; used when two devices can exchange directly, e.g. some graphics pipelines). Two transfer disciplines: cyclic (burst) DMA — the controller takes the bus in chunks and interleaves transfers with CPU; byte-level DMA — every byte alternates between device and CPU (slower); scatter/gather — list of (address, length) pairs so non-contiguous buffers can be moved in one DMA (used by network stacks and disk sector lists). Benefits: one interrupt per block instead of thousands; CPU runs concurrent processes; no memory-bus stalls (in cyclic mode); scalable to high-speed I/O; required for virtual-memory swap and for any block device; and it enables direct device-to-memory paths that cut software overhead to a single setup and a single completion.

6

Internal and external fragmentation? Segmentation with paging? Is segmentation possible without paging? What is swapping and its purpose?

Internal fragmentation: memory waste inside a block that has already been allocated — the allocated block is larger than the request. In paging, a process occupying k full pages plus a partial final page wastes, on average, half a page; in fixed-size partitions it wastes up to one full partition's worth. It is bounded by the unit size, so smaller pages → less internal fragmentation, at the cost of a larger page table and more TLB pressure.

External fragmentation: memory waste between blocks — total free space is enough, but it is broken into many small, non-contiguous holes, none large enough for the next request. It is the classic failure of variable-size contiguous partitioning: after a mix of loads and unloads, the free map has gaps of 10 KB, 20 KB, … and a 30 KB request fails although 40 KB is free in total. Compaction (slide all processes down, merge the free space into one hole) cures it but is expensive; non-contiguous schemes (paging, segmentation) remove the requirement of one contiguous block and so eliminate external fragmentation of physical memory (paging: frames are equal-sized, no external fragmentation at all; segmentation: still possible because segments are variable-size).

Segmentation with paging: the user's address space is divided into variable-size segments (code, data, stack — the program's logical units) for protection and sharing; each segment is then divided internally into fixed-size pages that are placed in physical frames by the page table. The user address is a three-field tuple: (segment number, page number, offset). Each segment has its own page-table base register; the MMU first checks the segment's limit (segmentation protection) and then does the paging translation (frame = f(page), physical = frame × frame size + offset). What each mechanism contributes: segmentation gives semantics, protection granularity, and growth (a stack segment can grow without moving other segments); paging gives fragmentation-free physical placement and demand loading. The two are orthogonal and combined in schemes like segmented paging (the mode this question targets) — segments are logical, pages are physical.

Is segmentation possible without paging? Yes — pure (contiguous) segmentation places each segment in a contiguous, variable-size block of physical memory, with per-segment base and limit registers for relocation and bounds checking. It works but inherits external fragmentation (segments are variable-size; the free map develops unusable gaps) and expensive compaction; it cannot demand-load a piece of a segment. Segmentation with paging is preferred in virtual memory precisely because it keeps the user-visible segmentation (protection, sharing, growth) while the physical level is paged and free of external fragmentation. So: without paging, segmentation is real but suffers the fragmentation and compaction costs above.

Swapping and its purpose: Swapping is moving a whole process image between main memory and a swap area on disk. Swap-out: a resident process is written to disk and its memory freed (its PCB is marked blocked/dormant; its registers are saved). Swap-in: a swapped-out process is read back and re-scheduled. Purposes: (1) Reclaim memory from blocked processes — a process waiting on I/O does not need its pages, so the OS can park it on disk and give its memory to a CPU-ready process (memory reclaim); (2) Over-admission — allow more processes to be defined than can be resident, with the scheduler swapping in the next candidate as memory frees; (3) Hierarchical storage — keep the hottest pages in RAM, the cold ones on disk, extending usable memory (this is whole-process swapping; its page-level refinement is demand paging, which swaps individual pages on fault rather than the whole image). Costs: swap I/O is orders of magnitude slower than memory, so over-swapping (thrashing) collapses the system; modern VM systems swap at page granularity and keep the entire swap space on the backing store.

7

Effective memory access time? Difference between segmentation and paging? What are overlays? Advantages/disadvantages of single contiguous allocation? Purpose of the modify bit? When does a page fault occur and what does the OS do?

Effective (average) memory access time (EMAT): the mean time a CPU reference takes when pages may need to be faulted in. With TLB and no page fault: EAT = h·(TLB + M) + (1−h)·(TLB + 2M) (worked out in q2-5 to 240 ns). With page faults to disk added: EAT = (1 + p)·(TLB + M) + p·D where p is the page-fault rate and D the disk page-fault service time; or, when the TLB cost is ignored on a miss: EAT = (1+p)M + pD. A small fault rate (p ≈ 0.02) with D ≈ 10 ms already makes EAT ≈ 200+20000 ≈ 20 200 ns — showing why the goal is to keep p near zero and why working-set admission controls exist.

Segmentation vs paging. Segmentation: the logical unit is a variable-size segment (code/data/stack) — the unit the user sees; addresses are (segment number, offset); a segment table (one per process) holds base + limit; protection and sharing at segment granularity; a segment is used as a whole; suffers external fragmentation and needs compaction. Paging: the logical unit is a fixed-size page — the unit the OS sees; addresses are (page number, offset); a page table (one per process, indexed by page number) maps to frames; protection/sharing at page granularity; pages may be loaded on demand; no external fragmentation of physical memory (frames are equal); TLB accelerates. In short: segmentation = logical, user-visible, variable-size; paging = physical, fixed-size, demand-loadable.

Overlays: the pre-VM alternative to virtual memory. The program is split into overlay sets — routines that are never active at the same time share the same memory region, and a run-time overlay handler swaps them in and out on call (the programmer declares the overlay tree). It lets a program larger than memory run without virtual memory; its cost is that the programmer must manage overlays explicitly and a wrong declaration is a crash. Virtual memory superseded overlays by doing the same swapping automatically, at page granularity, on a fault.

Single contiguous allocation — advantages: trivially simple — one base register (and limit), no page table, no fragmentation bookkeeping; the fastest possible address translation (one add + bounds check); good locality inside the process. Disadvantages: no inter-process protection (one address space, so a wild pointer destroys others — hence protection hardware); no virtual memory (the program cannot exceed its fixed region); poor utilization and no over-admission (one process's idle blocks waste memory; a blocked process can't be swapped); growth is hard (a contiguous expansion may fail and force a whole-process move, halting others); compaction of the gap between OS and the single process is the only remedy, and it stops the system. These drawbacks are why multiprogramming moved to partitioning, then to paging/segmentation.

Purpose of the modify (dirty) bit: a per-page-table-entry flag set by the hardware on the first write to the page (the MMU checks the write permission and clears the modify bit on that write). The OS uses it at replacement: if the bit is 0 the in-memory copy is identical to the on-disk copy and the frame can be discarded without any write-back I/O; if 1 the page must be written back before its frame is reused. Saving that write is a major part of victim selection — which is exactly what NRU (the "R" half of its 2-bit status) and SC/enhanced-clock exploit. It is set on first write, cleared on page load and after a write-back.

When does a page fault occur, and what does the OS do? A fault is raised when the CPU references a virtual page whose valid bit is clear (page not resident), or a protection violation (e.g. write to a read-only page — handled by a protection fault, not a load). The OS page-fault handler does: (1) Verify the reference is inside the process's address space (page-table entry exists; segment limit ok) — if not, an illegal-instruction trap. (2) Find a free frame: use one from the free list, or choose a victim by the replacement policy (FIFO / LRU / OPT / SC / NRU), consulting the modify bit. (3) If the victim is dirty, write it to disk. (4) Read the wanted page from disk into the frame. (5) Update the page table (frame number, valid = 1, modify = 0, reference = 1) and the process's PCB/working-set data. (6) Restart the faulting instruction — the page is now resident. The cost is one disk transfer (plus a write if dirty) — which is why the admission control that avoids thrashing (keep Σ working sets ≤ free frames, check fault frequency) matters more than any single algorithm.

8

Disadvantages of segmentation and how segmentation-with-paging avoids them? What is a page reference string and its physical significance? What is bumping?

Disadvantages of (pure) segmentation — and how segmentation with paging avoids each.

  1. External fragmentation. Variable-size segments leave gaps that no new segment can fill; total free can exceed a request while no single hole fits. Avoided: paging splits every segment into equal frames, so physical memory has no external fragmentation — any free frame serves any page of any segment.
  2. Expensive compaction. Merging free space requires moving segments and rewriting cross-segment references, with the system stopped. Avoided: frames are interchangeable, so no physical compaction is ever needed.
  3. Hard-to-grow segments. A growing stack may find no contiguous room and force a whole-segment move (or fail). Avoided: a segment grows by allocating new frames at the end of its page list; no existing page moves.
  4. Slow free-space search. Finding a free segment of size S is a linear scan of the free list. Avoided: the free-frame list is uniform (any free frame will do), allocation is O(1).
  5. Coarse waste. A segment that needs 500 KB may only find a 1 KB gap, or a 1 KB segment may squat in a 500 KB hole. Avoided: page granularity (1 KB–64 KB) matches actual demand, and demand loading means a segment occupies only the pages it touches.
  6. Coarse protection/sharing. Only per-segment read/write/execute. Avoided: per-page protection bits and per-page sharing give finer granularity; shared library pages are a standard use.

What stays after adding paging: the user-visible segments (protection, sharing, growth semantics) and the segment table; the physical level is paged. That split — logical segmentation over physical paging — is why segmentation with paging is the workhorse of many virtual-memory systems.

Page reference string: the sequence of page numbers a process references during execution, in time order — e.g. 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, …. Its physical significance: it is the observable fault behavior of a real run, and the input to simulation of a replacement policy (FIFO/LRU/OPT/SC) — simulating the string gives the exact fault count and working-set behavior of that execution. It is also what Belady's-anomaly analysis (q2-5) and working-set estimation run on: the working set at instant t is the set of pages referenced in the last Δ references of the string; the sum of working sets over all processes is the memory needed to run without thrashing. In practice the string is obtained by running the program (a trace), because it depends on input data and timing, not just the program text.

Bumping: in variable-partition (fixed-size partitioning) allocation, best-fit's greedy choice can displace an already-placed request — the new request's hole is cut from one that a smaller, older request was using, forcing the older one to move ("bumped") — or, in paging replacement, a policy evicts a hot page (one that will be re-referenced immediately) and the very next reference faults again: the page was "bumped" out under a live process. The symptom is thrashing of the allocator — constant movement, no steady state. The cure is reference-informed policies: second-chance / clock / NRU use the use bit so a recently-used page gets a "second chance" instead of being bumped; the working-set model steers admission so no live set is ever displaced. Bumping is the concrete failure mode that makes FIFO and best-fit undesirable in practice and that SC / NRU / LRU are designed to prevent.

9

Hierarchical page tables? Disadvantages of paging? What is the dirty bit? The SC (Second Chance) algorithm? Short notes on NRU and LRU.

Hierarchical page tables: a flat page table (32-bit space: 2²⁰ × 4 B = 4 MB; larger on wider addresses) is too big to keep fully resident. The table is therefore paged in levels: the top (first-level) directory always resides in memory and points to second-level tables, which in turn point to third-level leaf entries holding the frame numbers; only the active portions are resident, the rest live on disk. A lookup cascades: TLB → top directory (resident) → middle table (on miss: one extra memory access, or a disk I/O if that table block was paged out) → leaf entry. x86-64 uses four levels (PML4 → PDPT → PD → PT); x86-32 typically three. The payoff: a program that touches a small fraction of its 4 GB address space pays only for the table blocks it uses, not the whole 4 MB. The cost: one extra reference per level on a TLB miss — mitigated by page-table caches (PTCs) that hold intermediate blocks, and by larger intermediate blocks (each middle table covers a large address range).

Disadvantages of paging: (1) Page-table overhead — one entry per virtual page; for a full 32-bit space that is 4 MB of RAM, most of it unused, plus the table's own caching. (2) Two-stage translation — a TLB miss forces two memory references (page table, then data), roughly doubling per-access cost on misses; TLBs are small, so miss rate is non-zero. (3) Fixed page size — small pages (4 KB) waste TLB and table space for large working sets; large pages (4 MB) waste internal fragmentation (up to a page's worth per process) and coarsen fault granularity. (4) TLB shootdowns — changing a shared page's protection or mapping forces every CPU to invalidate its TLB entries, an expensive cross-processor operation. (5) Page faults — a disk I/O on every cold reference; a fault storm (thrashing) collapses system-wide performance. (6) Loss of logical structure — pages are address-unit only; the user's code/data/stack structure is invisible to the allocator, so segmentation (or segmented paging) is needed on top for user-level protection and sharing. (7) Contiguity of virtual ranges — a program wanting one large contiguous virtual region must reserve adjacent pages up front or span many, unlike a segment that can grow in place.

Dirty (modify) bit: one bit per page-table entry, set by the MMU on the first write to the page (the hardware clears it on that write). It tells the replacement policy whether the in-memory copy differs from the on-disk copy: dirty = 1 → a write-back I/O is required before the frame is reused; dirty = 0 (clean) → the frame can be discarded with no I/O. It is set on first write, cleared on page load and after a write-back; FIFO ignores it, while NRU (the M bit of its (R,M) status) and enhanced clock / SC use it to prefer evicting clean pages.

SC (Second Chance) / clock: a practical approximation to LRU that avoids scanning the whole frame list. Keep frames in a ring (FIFO order), each with a use (reference) bit set on every access and a pointer (clock hand). On a fault: examine the frame under the hand; if use bit = 1, clear it and advance the hand (the page gets a "second chance"); if use bit = 0, it is the victim — replace it, leave the hand. The enhanced clock (SC+) stores a 2-bit (use, modify) pair and evicts in order (0,0) → (0,1) → (1,0) → (1,1), so a clean, unused page goes first and a dirty, hot page last. Cost is O(1) per fault (amortized) versus O(n) for true LRU; it tracks recent use with no full scan.

NRU (Not Recently Used): coarse, quantized replacement. Each frame carries a 2-bit (R, M) status — R: referenced in the last interval, M: modified since load (the modify bit). On a fault the OS scans the frames once, classifies them into four groups — (0,0) best victim (clean, not referenced), then (0,1) (clean, referenced), (1,0) (dirty, not referenced), (1,1) (dirty, referenced) — evicts from the lowest non-empty group (random within the group), then clears all R bits and starts a new interval. Cost: O(n) per scan; the interval length is the quantization trade-off (shorter interval → better approximation of LRU, more frequent scans). NRU is the base on which clock/SC builds its per-page, O(1) version.

LRU (Least Recently Used): evict the frame that has gone the longest without a reference. Exact LRU needs per-frame reference timestamps (or a hardware stack of all frames, the ideal "stack algorithm" hardware) and an update on every access — O(n) to find the victim in software, O(1) with hardware counters. LRU is a stack algorithm, so its fault count is monotone non-increasing in frame count (no Belady anomaly), but its exact implementation is costly; SC, NRU and the various clock variants are all practical approximations to LRU that trade precision for per-fault cost.

Worked numerical (page replacement, 3 frames). Reference string 1, 2, 3, 4, 1, 2, 5, 1, 2, 5, 3, 4, 5. Frame-state trace (F = fault, H = hit) and the frames held after each reference:

Ref #12345678910111213
Access1234125125345
FIFO frames{1}{1,2}{1,2,3}{2,3,4}{3,4,1}{4,1,2}{1,2,5}{2,5,1}{5,1,2}{1,2,5}{2,5,3}{5,3,4}{3,4,5}
FIFO faultsFFFFFFFHHHFFH
LRU frames{1}{1,2}{1,2,3}{2,3,4}{3,4,1}{4,1,2}{1,2,5}{2,5,1}{5,1,2}{1,2,5}{2,5,3}{5,3,4}{3,4,5}
LRU faultsFFFFFFFHHHFFH
OPTevict the page whose next use is farthest (never used again = farthest)frame state: {1,2,3} → {4,1,2} → {5,1,2} → {5,2,3} → {5,3,4}
OPT faultsFFFFHHFHHHFFH

Fault counts: FIFO = 9, LRU = 9, OPTIMAL = 7. OPT's trace: after the first three fills give {1,2,3}, ref 4 faults — OPT looks ahead and evicts the page whose next use is farthest: 3's next use is ref 11, 1's ref 5, 2's ref 6, so evict 3 → {4,1,2}. Refs 5, 6 hit. Ref 7 (page 5) faults: next uses are 4 → ref 12, 1 → ref 8, 2 → ref 9; the farthest is 4, so evict 4 → {5,1,2}. Refs 8, 9, 10 hit. Ref 11 (page 3) faults: next uses 5 → ref 13, 1 → never, 2 → never; evict 1 (never used again) → {5,2,3}. Ref 12 (page 4) faults: 5 → ref 13, 2 → never, 3 → never; evict 2 → {5,3,4}. Ref 13 (page 5) hits. Faults at refs 1, 2, 3, 4, 7, 11, 12 = 7 — the optimal minimum, no policy can beat it. FIFO and LRU tie at 9 on this particular string because the access order happens to rotate evenly; they diverge (and the anomaly appears) on the Belady string in q2-5.

Module 6 Questions

★ Note: Numerical on the file allocation table and numerical of disk scheduling (SSTF, C-SCAN, SCAN) ★
1

Blocking vs non-blocking I/O. Why does an OS require dual-mode operation?

Blocking I/O: a process that initiates an I/O request is suspended by the OS (placed in a blocked state) until the I/O completes; it cannot run on any CPU. The I/O device runs independently (CPU and I/O overlap), and a completion interrupt wakes the process (or a dedicated I/O thread) to finish the transfer. Blocking I/O is the default model: simple to program ("read until it's done"), and on modern systems cheap in memory because only a few processes block on I/O at a time. A fully blocking system wastes CPU time on process switching when many processes block — which motivated multi-threading.

Non-blocking I/O: the request returns immediately with a "pending" (or "retry") status; the caller checks a poll status variable (a busy-wait or spin) or registers a completion callback that the kernel invokes when the I/O finishes. The calling thread is never suspended for the duration of the I/O — it keeps running and does other work or polls. Advantages: a thread never wastes its own context while waiting; a single thread can manage many I/O channels (e.g. a network server) without blocking; lower per-thread memory. Disadvantages: busy-waiting burns CPU (or spin wastes cache); the programming model is harder (asynchronous, callbacks or event loops); a thread that spins and blocks is the worst of both. In modern OSes, non-blocking is the basis of event-driven I/O (epoll, kqueue, IOCP).

Comparison (blocking vs non-blocking):

AspectBlocking I/ONon-blocking I/O
Caller stateSuspended until I/O doneReturns immediately; caller decides to poll/callback
CPU wasteProcess switch on completionBusy-wait burns cycles; callback avoids it
ConcurrencyOne thread per I/O channel (or one blocked)One thread can manage many I/O channels
Programming modelSynchronous, simpleAsynchronous, harder (event-driven)
Memory costLow (blocked process is cheap)Low (caller not suspended)
Typical useFile reads, simple serversNetwork servers, game loops, UIs

Why an OS requires dual-mode operation: modern CPUs support two modes — user (monitor) mode and kernel (privileged) mode — distinguished by a mode bit in the CPU status register (the PSW). Kernel mode allows all instructions, access to all memory, and control of privileged hardware (timers, DMA, I/O registers, interrupt control, memory-management unit). User mode restricts the process to non-privileged instructions; any attempt to execute a privileged instruction (page-table write, disable interrupts, read a timer, access I/O port) traps to the OS. The OS is the only entity that runs in kernel mode, and it is the only entity that can switch the mode bit (or return from a trap). This is the protection mechanism: a user process cannot bypass its own constraints, cannot modify another process's page table, cannot disable interrupts, and cannot access I/O registers directly — it must go through the OS, which enforces mutual exclusion and protection. A dual-mode OS is also the foundation of virtual memory (user-mode processes get a virtual address space; the MMU translates it and checks protection bits), interrupt handling (traps always go to kernel mode), and system calls (a user process requests service by executing a software interrupt — a trap — that switches to kernel mode and dispatches the request). Without dual-mode, a rogue process could disable interrupts and take over the machine; with it, the OS is the sole authority over privileged resources, and protection is enforced by hardware (the mode bit is checked on every instruction), not by the OS's trust in user code.

2

Short note on data-transfer methods of I/O devices. Explain different file-management methods with a diagram (text diagram in <pre><code>). Describe FAT structure. Indexed allocation. Advantages/disadvantages of contiguous allocation.

Data-transfer methods of I/O devices. Three classical mechanisms, in increasing order of CPU involvement. (1) Programmed I/O (PIO): the CPU itself reads/writes each byte from the I/O port, checking a device-status register in a loop (busy-wait); each byte requires a port read + a check, and the CPU is tied to the I/O device for the duration of the transfer. Pros: simple. Cons: very slow for large transfers; a CPU cycle is wasted on every byte; the processor does the data movement, not the device. (2) Interrupt-driven I/O: the CPU starts the transfer and does other work; on completion (or every block boundary), the device raises an interrupt and the CPU's interrupt handler reads the data from the device's buffer into memory. Pros: CPU is free during the transfer; Cons: an interrupt is still generated per block (or per word); on a slow device (tape) the interrupt overhead dominates the transfer time. (3) DMA (Direct Memory Access): a DMA controller moves blocks of data from the device to memory without CPU intervention — the CPU programs the controller with source, destination, and byte count, then does other work; the controller issues a single interrupt on completion (one DMA transfer). Pros: high-speed burst transfers; the CPU is free for the entire block; scalable to high-speed I/O (disks, network). Cons: requires a DMA controller in hardware; more complex; the device takes over the memory bus for the transfer (in cyclic mode it interleaves with the CPU). This hierarchy — PIO → interrupt → DMA — is the classical I/O-transfer model taught in the exam.

File-management methods (the four allocation schemes). How a file (a sequence of logical records, each of L bytes) is placed in physical blocks on disk. (a) Contiguous allocation: the file is placed in one contiguous run of blocks; the file table (FCB — file control block) stores starting block + length. (b) Linked allocation: each block has a next-block pointer; the FCB stores first-block + last-block (or last-block = 0). No contiguous run needed; files can grow. (c) Indexed allocation: a single block (the index) holds a list of pointers to every block of the file; the FCB points to the index. (d) FAT (File Allocation Table): the OS maintains a linked-list-in-array (the FAT) where each entry is the next block of the corresponding block — a global linked list stored in a table, not in the blocks. The text diagram:

CONTIGUOUS          LINKED                  INDEXED
|F|F|F|F|F|         [blk1]->[blk2]->[blk3]->NULL
FCB: start, len      FCB: first, last      FCB: -> index block
                                        [ p1 | p2 | p3 | ... ] -> each p is a block
                                        (one index block per file)

FAT (global table)  [FAT[0]=blk1] [FAT[blk1]=blk2] [FAT[blk2]=blk3] [FAT[blk3]=END]
                                        (array of next-block pointers, one entry per disk block)

FAT structure. A global array (one per partition) where FAT[b] = the next block of the file that owns block b (or END / 0xFFFF if b is the last block of a file). A file is thus a linked list of blocks where the links are stored outside the blocks (in the FAT array), not inside them. The FCB of a file stores only the first block of the file. The OS follows the chain: first → FAT[first] → FAT[FAT[first]] → … until END. Because the FAT is global and stored as a table (not in the data blocks), it doubles as a free-block list (the free-space bitmap is a separate table). Advantages: no contiguous requirement; files grow anywhere; fast random access (one table lookup per seek, but no pointer chasing through blocks — all links are in RAM); no internal fragmentation within a file (each block is full except the last). Disadvantages: one FAT table per partition; the table itself occupies 100% of the disk blocks as pointers (a 16-bit FAT on a 500 MB disk wastes ~500 MB / 2 B per entry — the table is huge and in RAM); no protection at the file level; chain traversal on a seek is a random-access pattern; a corrupted FAT entry breaks the chain; maximum file size is bounded by the number of entries (16-bit: 65,536 × 512 B = 32 MB).

Indexed allocation. A single block per file holds a list of pointers to every data block of the file. Advantages: random access in two seeks (index + data) vs linked's linear; files can grow anywhere (just add a pointer to the index); no internal fragmentation; the index can be paged (multi-level indexing) for very large files. Disadvantages: one index block is wasted per file (a 512 B index on a 1 KB block wastes 50% of the index block for small files); index overhead grows with file size; the index must be in RAM for fast access; a corrupted index block is unrecoverable without a backup.

Contiguous allocation — advantages/disadvantages. Advantages: sequential access is fast (one seek + read); random access is direct (block n is at start + n, no pointer chasing); no internal fragmentation within a block; no index block wasted; simple FCB (start + length); best for sequential files (video, audio). Disadvantages: external fragmentation — a new file of length L may not fit in any single free run; growing a file is expensive (must move the whole file if no adjacent free space); small files waste large blocks; the FCB stores start + length only, so no random access to a sub-block; corruption of the FCB loses the whole file; the file table must be updated on every grow/shrink, which is a lock on the FCB.

3

Free-space management techniques. Advantages/disadvantages of linked file allocation. How indexed allocation overcomes them.

Free-space management: the problem is to keep track of which blocks on disk are free. The three classical techniques, in increasing order of space and access cost:

(1) List of free blocks: the OS maintains a linked list of all free block numbers (in RAM). Pros: one pointer per free block (4 B); allocation is O(1) (pop the head); deallocation is O(1) (push). Cons: the list itself is in RAM (must be persisted to disk); a corruption of the list loses all free-space info; slow to build the list on a large disk (scan the whole disk); pointer-chasing through the list is random (cache-unfriendly); not usable for contiguous allocation (no gap info). It is the simplest scheme and is used by ext2.

(2) Bit map (free-block bitmap): a bit per disk block: 0 = free, 1 = allocated. The bitmap is in RAM (or on a special block). Pros: compact — one 512 B block holds a bit map of 4096 blocks (512 × 8 = 4096); allocation is O(1) (find the first 0-bit); fast for contiguous allocation (scan the bitmap for the first run of L 0-bits); the bitmap can be written to disk (on a boot block or a special reserved block). Cons: finding a contiguous run of L blocks is O(L) (scan the bitmap); the bitmap must be in RAM for speed; a large disk needs a large bitmap (a 100 GB disk at 512 B blocks = 200 M bits = 25 MB of bitmap); corruption of the bitmap is catastrophic. It is used by ext2/3 (with grouping into block groups).

(3) Grouping (free-space grouping): the last free block stores the next K free block numbers (a chain of K-size groups); the first free block is the head of the chain. Pros: no separate table needed — the free blocks themselves store the list; the entire free-space info is on disk (no RAM copy needed); allocation is O(1) (the head block is in RAM); robust — a corrupted group is repaired by scanning. Cons: the head must be in RAM; a large K wastes block space on pointers (each group block holds K pointers = K × 4 B, for K = 128 that's 512 B — one whole block of pointers per group); random access to a non-head group is O(1) only if it's in RAM (otherwise a disk read); the grouping scheme is not suited to contiguous allocation. It is used by UNIX (the grouping scheme).

Linked file allocation — advantages/disadvantages. Advantages: no contiguous requirement — a file can be scattered over the entire disk; no internal fragmentation within a block (each block is full except the last); growing a file is O(1) (append a block); no separate index or table needed (the links are in the blocks themselves); simple — the FCB stores only first and last block. Disadvantages: random access to the n-th record is O(n) (pointer-chasing through n blocks); pointer overhead — each block carries a 4-byte pointer (a 512 B block wastes ~0.8% to pointers); corruption of a pointer breaks the chain (a lost pointer = a lost block); sequential access is slower than contiguous (random seeks); the last block's pointer is NULL (or 0), which is a convention that must be checked on every traversal; a large file has many pointers (1 GB / 512 B = 2 M pointers).

How indexed allocation overcomes them. The indexed scheme stores a single block (the index) that holds a list of pointers to every data block of the file. It overcomes linked's key weaknesses: (1) Random access is O(1) — the index block is in RAM, and index[n] gives the n-th block directly (one seek to the index + one seek to the data block); (2) Pointer overhead is centralized — the 4-byte pointers are in one block (the index), not scattered across every data block; (3) Corruption is contained — a corrupted data block's pointer is still in the index (recoverable from a backup of the index); a corrupted index block is fatal but rare (the index is a single block, not a chain); (4) Growing a file is O(1) — add a pointer to the index block; (5) Multi-level indexing (a table of pointers to index blocks) handles very large files (ext2 uses a 2-level index for huge files). The cost is one index block per file (a 512 B index on a 1 KB block wastes 50% of the index for small files) and a second seek (to the index) that contiguous allocation avoids.

4

What is a record in a file? Indexing strategies for multi-record files. File structure vs directory structure. Directory-implementation techniques. File-allocation methods. What are files and directories? Explain linked allocation and i-nodes with a text diagram.

Record in a file: a fixed-size (or variable-size) logical unit of data within a file — the unit the application (not the OS) reads and writes. A record is not a disk block; a record may span multiple blocks (variable-length records) or occupy a fraction of a block (fixed-length records with internal fragmentation). A multi-record file is a sequence of records, each of L bytes (fixed) or Li bytes (variable). The file is the logical unit; the block is the physical unit; the record is the application unit. The OS allocates blocks to files; the application allocates records to files (via read/write calls).

Indexing strategies for multi-record files: three classical approaches, each a trade-off between space and time. (1) Direct (linear) indexing: a separate array of pointers, one per record (or per block); the index is in RAM; random access to record n is O(1). Cost: a huge index (a 1 GB file of 512 B records = 2 M pointers = 8 MB of index); not practical for large files. (2) Single-level (one index block): the index is a single disk block; random access is O(1) (one seek to the index + one seek to the data block). Cost: the index block is limited (512 B / 4 B = 128 pointers = 128 × 512 B = 64 KB max); a file larger than 64 KB needs a multi-level index. (3) Multi-level (hierarchical) indexing: a table of pointers to index blocks; each index block points to data blocks; the top level is a single block. Random access is O(k) for a k-level index (k seeks). ext2 uses a 3-level index (a top block with 12 direct + 2 indirect + 1 doubly-indirect pointers); Linux uses a 2-level index for large files. The trade-off: more levels → faster growth (a file can grow to terabytes) but slower random access (more seeks).

File structure vs directory structure. A file is a logical sequence of bytes with a name; it is the unit of data. A directory is a special file that holds a list of file names and their pointers (or inodes); it is the unit of organization. The difference: a file stores data; a directory stores metadata (names → inodes). A directory is a tree (a hierarchy of directories); a file is a leaf in the tree. The OS treats a directory as a special file (the same read/write calls apply, but the content is a list of entries, not data). The root directory is the top of the tree; every file has a path from the root to it.

Directory-implementation techniques: three classical schemes. (1) Linear (list) directory: the directory is a flat list of file names + pointers; lookup is O(n) (scan the list); creation is O(1) (append). Cons: slow lookup on a large directory; no hierarchy. (2) Hashed directory: the directory is a hash table of names → inodes; lookup is O(1) (hash the name); creation is O(1) (insert into the hash). Cons: a corrupted hash table is fatal; a hash collision requires a chain; the table must be in RAM. (3) Tree (hierarchical) directory: the directory is a tree of directories; a file is a leaf; a path is a sequence of directory names from the root to the file. Lookup is O(k) for a path of k directories (each step is a hash or linear lookup). Pros: no flat list of 100,000 names; easy organization; easy search (by path). Cons: a long path is slow (k hash lookups); a corrupted directory node is fatal; the tree must be persisted to disk. ext2 uses a tree with hashed directory nodes.

File-allocation methods: the three classical schemes (from q2-6): contiguous (one run of blocks; FCB = start + length), linked (each block carries a next pointer; FCB = first + last), indexed (a single index block; FCB → index). A fourth scheme is the FAT (a global linked list in a table). Each has a trade-off: contiguous = fast sequential + no pointer overhead + external fragmentation; linked = no fragmentation + O(1) growth + slow random access; indexed = fast random + no fragmentation + one index block wasted.

Files and directories: a file is a named collection of bytes with metadata (an inode: type, size, permissions, owner, pointers to data blocks); a directory is a special file that holds a list of name → inode entries. The inode is the core of the Unix file system: it is a fixed-size block on disk that holds all the metadata of a file (or directory) and the pointers to its data blocks. Linked allocation with i-nodes: each data block carries a next-block pointer; the inode stores the first block and the last block (or 0 if the file is empty). The text diagram:

INODE (one per file/directory)
+---+---+---+---+---+---+---+---+
|mode|size|nlinks|owner|ctime|mtime|
+---+---+---+---+---+---+---+---+
|ptr1|ptr2|ptr3|ptr4|...|ptr12|  (direct pointers, up to 12)
+---+---+---+---+---+---+---+---+
|sinde|dinde|tinde|      |       |  (single/double/triple indirect)
+---+---+---+---+---+---+---+---+

LINKED ALLOCATION:
[blk1] -> [blk2] -> [blk3] -> NULL
  (each block has a 4-byte next-pointer; inode stores blk1, blkN)

INDEXED (with i-node):
inode -> [index block] -> [data blk1] [data blk2] [data blk3] ...

The inode is the bridge between the directory (a name → inode number) and the file (an inode → data blocks). A hard link is a second directory entry that points to the same inode; a symbolic link is a file whose content is a path (a string, not an inode).

5

Free-space management of disk. Seek time? Rotational latency? Advantages of SCAN over C-SCAN.

Free-space management of disk (the three schemes, detailed in q3-6): list of free blocks (a linked list in RAM; O(1) alloc/dealloc; corruption loses all info), bit map (one bit per block; compact; O(1) alloc; O(L) contiguous search), grouping (a chain of K-pointer groups; no separate table; robust). The OS must persist the free-space info to disk (on a boot block or a reserved block) so that a crash does not lose the map. A bitmap is the most common (used by ext2/3); a grouping scheme is used by UNIX.

Seek time: the time it takes the disk arm to move from the current cylinder to the target cylinder. A seek is the dominant cost in disk I/O (millions of ns, vs microseconds for memory). Rotational latency: the time the disk platter takes to rotate the target sector under the read/write head. For a 7200 RPM disk: one rotation = 60 / 7200 s = 8.33 ms; average rotational latency = 8.33 / 2 = 4.17 ms. For a 10,000 RPM disk: 60 / 10,000 = 6 ms; average = 3 ms. Transfer time: the time to read/write the actual data (bytes / data rate). The total disk access time = seek + rotational latency + transfer = 4.17 ms + 0.36 ms + 0.10 ms ≈ 4.63 ms (a typical 7200 RPM disk). The key insight: seek + rotational latency dominate; transfer is negligible. This is why disk scheduling (SCAN, C-SCAN, SSTF) matters — it reduces seek time by grouping requests in cylinders.

Advantages of SCAN over C-SCAN: SCAN (the elevator algorithm) moves the head in one direction (say right) to the end of the track, then reverses to the other end, and so on. C-SCAN (circular SCAN) moves the head in one direction (say right) to the end of the track, then jumps back to the start (no reverse pass). SCAN's advantage over C-SCAN: fairness — a request at the start of the track that arrives while the head is at the end gets service on the reverse pass (SCAN); in C-SCAN, it must wait for the head to complete the full circular pass (a long wait). C-SCAN's advantage over SCAN: predictable latency — a request at any cylinder gets service within one full rotation (a bounded wait); SCAN's wait can be two full passes (a request at the opposite end arrives just after the head reversed → two passes). So C-SCAN is fairer (a bounded latency); SCAN is faster on average (a reverse pass handles requests in the opposite direction without jumping to the start). The exam answer: C-SCAN avoids the unfairness of SCAN (a request at the start waits a full circular pass); SCAN is faster on average (a reverse pass handles requests in the opposite direction). Worked numerical in q7-6 (SSTF / SCAN / C-SCAN on the given queue).

6

SSTF working, advantages/disadvantages. Essential goals of disk scheduling and why each matters. Physical and logical formatting of a disk.

SSTF (Shortest Seek Time First): the head moves to the request with the shortest seek (the closest cylinder) next, regardless of direction. It is a greedy algorithm: at every step, pick the nearest pending request. Working: maintain a priority queue of pending requests keyed by distance from the current cylinder; on each request, pop the closest cylinder and service it. Advantages: the lowest average seek time of all scheduling algorithms (greedy = optimal for minimizing total seek time); simple to implement; no direction state (a head can move in either direction). Disadvantages: starvation — a request at the far end of the track may never be served (a closer request always wins; the far request wait is unbounded); head moves back and forth (a request at cylinder 10, then 200, then 10 again — the head oscillates; a request at cylinder 100 is starved); no fairness guarantee (a request at the far end waits indefinitely). The fix is SCAN/C-SCAN (a direction state that prevents starvation).

Essential goals of disk scheduling — and why each matters. (1) Disk-schedule fairness: every request should get service within a bounded time; a request should not wait indefinitely. Why: starvation (a request at the far end waits forever) is worse than a long average wait; a user who issues a request and waits for minutes is unfair. (2) High throughput: the disk should service many requests per unit time; batch requests in the same cylinder (grouping) to amortize the seek cost. Why: the seek cost dominates; a scheduler that groups requests in adjacent cylinders (SCAN, C-SCAN) reduces the total seek time. (3) Uniform response time: the average wait time should be even across all requests; no request should wait much longer than another. Why: fairness across users and processes (a request from a background process should not wait longer than a request from a foreground process). The SSTF algorithm is fast on average (minimizes total seek time) but fails goal 1 (starvation); SCAN satisfies goals 1 and 3 (fairness + uniform response) at the cost of a slightly higher average seek; C-SCAN improves goal 3 (a bounded wait = one full rotation) at the cost of a jump to the start of the track.

Physical formatting of a disk: the low-level formatting of the platter — the division of the platter into tracks (concentric rings) and sectors (the smallest unit of storage on a track). A track has fixed number of sectors; a sector has a fixed size (usually 512 B); a cylinder is a stack of tracks at the same radius (one per platter surface). The physical format is done at the factory (the disk manufacturer writes the sector boundaries and sync marks). It is independent of the file system; a disk can be reformatted at the logical level (a new file system) without re-doing the physical format. The physical format determines the sector size, the number of sectors per track, and the number of tracks per surface — the physical capacity of the disk. A bad sector (a physical defect) is detected by the disk controller and remapped (a spare sector is used in its place).

Logical formatting of a disk: the high-level formatting — the division of the disk into file-system structures: a boot sector (a boot loader), a partition table (a table of partitions, each with a start cylinder, end cylinder, type), and a file-system structure (a superblock, inode table, data blocks). The logical format is done by the user (or the OS) at install time; it is independent of the physical format (a disk can be reformatted with a new file system — ext2 → ext4 → XFS — without re-doing the physical format). The logical format determines the block size (a 4 KB block on ext4), the inode size, the file-system metadata layout, and the partition boundaries. The difference: physical format = sectors on the platter (fixed at the factory); logical format = blocks and files on the file system (chosen by the user). The logical block size is a multiple of the physical sector size (a 4 KB block = 8 × 512 B sectors).

7

Compare SSTF and C-SCAN. What are a boot block and a bad block? Describe SCAN and C-SCAN.

Comparison of SSTF and C-SCAN.

AspectSSTFC-SCAN
AlgorithmMove to the closest pending request (greedy, no direction)Move in one direction to the end of the track, then jump to the start and continue (circular)
StateNone (distance to closest)Direction (one) + current cylinder
StarvationYes — a request at the far end may never be servedNo — every request is served within one full rotation
Average seekMinimum (greedy is optimal for total seek)Slightly higher than SCAN (the jump to the start costs a full-track seek)
FairnessPoor (distance only; no direction)Good (bounded wait = one rotation; uniform response)
Head motionBack and forth (oscillates)One direction only (circular)
Typical useSmall request queues; latency-sensitive workloadsGeneral-purpose; fairness-critical systems

Boot block vs bad block. A boot block is the first block (or a reserved block) of a partition that holds the boot loader (the operating-system bootstrap code that the CPU executes at start-up). It is not part of the file-system data; it is a special block that the firmware (the BIOS / UEFI) reads and jumps to on boot. A bad block is a physical sector (or a logical block) that the disk controller has detected as defective (a surface defect, a media error, or a wear-out sector); it is remapped to a spare sector and excluded from the file-system's allocation. A boot block is a special logical block (a boot loader); a bad block is a defective physical sector that is excluded from use.

SCAN (elevator algorithm): the head moves in one direction (say right, toward cylinder 199) servicing every pending request it encounters; on reaching the end of the track, it reverses and moves left, servicing requests in the opposite direction; it oscillates back and forth. Advantages: fair (a request at the far end is served on the reverse pass — a bounded wait = two full passes); uniform response (the average wait is even across all requests); no starvation; good throughput (a pass handles all requests in the direction of motion). Disadvantage: a request at the opposite end that arrives just after the head reversed must wait for two full passes (the worst-case wait is longer than C-SCAN's one rotation).

C-SCAN (circular SCAN): the head moves in one direction (say right) to the end of the track, then jumps instantly to the start of the track and continues right (no reverse pass). Advantages: a request at any cylinder gets service within one full circular pass (bounded wait = one rotation); uniform response (the jump to the start is free — the head does not move during the jump, it repositions); no starvation; predictable latency (every request waits at most one rotation). Disadvantage: the jump from the end to the start costs a full-track seek (the head moves from cylinder 199 to cylinder 0, 199 cylinders), which is wasted seek time; a request just past the end (a request at cylinder 5 that arrives while the head is at cylinder 190) must wait for the jump + the full pass to cylinder 5 — a longer wait than SCAN (which reverses and serves it on the reverse pass).

Worked numerical (disk scheduling). Disk: cylinders 0–199. Head at 53. Request queue: 98, 37, 18, 122.

(a) SSTF. From 53, compute the distance to each request:

distances from 53:  37 → 16,  18 → 35,  98 → 45,  122 → 69
SSTF stop sequence:  53 → 37 → 18 → 98 → 122
movement:            16 + 19 + 80 + 24  =  139 cylinders

(b) SCAN (assumption: the head is sweeping RIGHT, toward 199). Service all requests in the right direction first, then the remaining left-side requests on the reverse pass.

SCAN stop sequence (right sweep):  53 → 98 → 122  (all right-side requests)
then left sweep:                   122 → 37 → 18
movement (stop after last request): 45 + 24 + 85 + 19  =  173 cylinders

With the standard convention of sweeping to the end cylinder before reversing: 53 → 199 = 146, then 199 → 122 = 77, 122 → 98 = 24, 98 → 37 = 61, 37 → 18 = 19; total = 146 + 77 + 24 + 61 + 19 = 327 cylinders.

(c) C-SCAN (assumption: sweep RIGHT; after reaching the end, jump to 0 and continue). C-SCAN services right-side requests first, then jumps to cylinder 0, then services the left-side requests in increasing order:

C-SCAN stop sequence:  53 → 98 → 122 → 199 (end) → 0 (jump) → 18 → 37
movement:
  53 → 98        =  45
  98 → 122       =  24
  122 → 199      =  77    (continue the sweep to the end)
  199 → 0        = 199    (jump to start; head repositioning)
  0 → 18         =  18
  18 → 37        =  19
total            = 45 + 24 + 77 + 199 + 18 + 19 = 382 cylinders

Summary table:

AlgorithmStop sequenceTotal head movement
SSTF53 → 37 → 18 → 98 → 122139
SCAN (stop at last request)53 → 98 → 122 → 37 → 18173
SCAN (sweep to 199, standard)53 → 199 → 122 → 98 → 37 → 18327
C-SCAN (RIGHT, stop at 37)53 → 98 → 122 → 199 → 0 → 18 → 37382

Note: SSTF always has the lowest total movement (it is the greedy optimum); SCAN and C-SCAN trade total seek time for fairness (no starvation). The sweep-direction assumption for SCAN and C-SCAN is stated explicitly — a LEFT sweep gives different sequences but the same total-movement formula.

Worked numerical (FAT). 400 MB disk, 512 KB FAT block, 16-bit FAT entries. Records per FAT block, maximum addressable space, FAT overhead, usable space — every step shown.

GIVEN:  disk = 400 MB,  FAT block = 512 KB,  entry = 16 bits = 2 bytes

(1) Records per FAT block:
    512 KB  =  512 × 1024 B  =  524,288 B
    records per block  =  524,288 B / 2 B  =  262,144 records

(2) Total entries in the FAT:
    16-bit  =  2^16  =  65,536 entries (FAT[0] … FAT[65535])
    Total FAT size  =  65,536 × 2 B  =  131,072 B  =  128 KB

(3) How many FAT blocks are needed:
    262,144 records per block  ≥  65,536 entries  →  1 block suffices
    (one 512 KB FAT block holds the entire 65,536-entry table)

(4) Maximum addressable space:
    each FAT entry points to one 512 B data block
    max records  =  65,536
    max data space  =  65,536 × 512 B  =  33,554,432 B  =  32 MB
    → a 16-bit FAT can address at most 32 MB of data

(5) FAT overhead:
    the entire FAT table  =  131,072 B  =  128 KB
    (it occupies 128 KB of the 512 KB block; the block itself is 512 KB reserved)

(6) Usable space (400 MB total, binary 1 MB = 1,048,576 B):
    400 MB  =  400 × 1,048,576 B  =  419,430,400 B
    subtract the FAT block (the reserved 512 KB):  419,430,400 − 524,288  =  418,906,112 B
    usable data space  =  418,906,112 B  ≈  399.5 MB
    BUT: only the first 32 MB is addressable by a 16-bit FAT
         (the remaining 367.5 MB is unusable to the FAT scheme)

(7) Overhead percentage (of the FAT block):
    128 KB used out of 512 KB reserved  =  25%
    FAT overhead as fraction of total:  524,288 / 419,430,400  ≈  0.125%