Learning Guide · Assignment Solutions

Operating Systems — Complete Study Companion

Every question from Assignments 1–5 (Chapters 1–9) answered in exam-ready form: definitions, comparison tables, diagrams, pseudo code, and fully worked numerical problems with verified Gantt charts, Banker's algorithm traces and page-replacement tables.

Ch 1–2 · Intro & Scheduling Ch 3–4 · Processes & Sync Ch 5 · Deadlocks Ch 6–7 · Memory & VM Ch 8 · File Systems Ch 9 · I/O Bonus · Disk & RAID
Study progress0 / 56 done
💡 How to use: read a question, try recalling the answer before scrolling, then check yourself. Tick studied on each card — your progress is saved in this browser. Use the search box to jump to any topic.

Visual Overview — The Whole Subject on One Page

Scroll horizontally to explore the full map · also saved separately as OS-Visual-Map.png for printing

Operating Systems — One-Page Visual Map Operating Systems — One-Page Visual Map BIT 2nd Semester · Chapters 1–9 (Assignments 1–5) + bonus · every number verified by simulation CH 1–9 · VISUAL OVERVIEW CH 1 · INTRODUCTION User applications system calls OPERATING SYSTEM kernel · drivers · services Hardware (CPU · RAM · I/O) System call = trap: user mode → kernel mode Types: batch · time-sharing · real-time · distributed · parallel (SMP) Dual role: resource manager + extended machine Services: execution · I/O · files · communication · error detection · protection · accounting CH 2 · CPU SCHEDULING P1 P2 P3 P4 P5 01011131419 FCFS Gantt (all arrive at time 0) · TAT = finish − arrival · WT = TAT − burst avg WT: SJF 3.2 < RR 5.4 < Pri 8.2 < FCFS 9.6 (ms) Preemptive: SRTF · Round Robin · preemptive priority Non-preemptive: FCFS · SJF · priority RR (q=1) cycles the queue → low waiting, fair Priority: smaller number = higher priority Convoy effect (FCFS) · starvation (priority) SJF is provably optimal when all arrive at t = 0 ★ ANSWER: SJF gives the minimum average waiting time = 3.2 ms CH 3–4 · PROCESSES & SYNC Ready Running Blocked dispatch timeout / interrupt event wait event done Race condition: result depends on timing → guard the critical section with mutual exclusion · progress · bounded waiting Tools: Peterson · TSL · mutex · semaphore (P/V) Classics: producer–consumer · dining philosophers · sleeping barber Thread: shares process memory, own stack/PC; user threads (library) vs kernel threads (OS) IPC: shared memory or message passing CH 5 · DEADLOCKS P1 R1 P2 R2 circular wait ⇒ DEADLOCK red = request edge · grey = assignment edge 4 conditions: mutual exclusion · hold & wait · no preemption · circular wait (all needed) Prevention: break one · Avoidance: Banker's Recovery: kill processes / preempt + rollback safe seq <P1,P3,P4,P0,P2> · P1 req (1,0,2) → granted CH 6–7 · MEMORY & VIRTUAL MEMORY P0 P1 P2 (p,d) 0 → 5 1 → 9 2 → 1 frame 5 · page 0 frame 9 · page 1 frame 1 · page 2 page table maps pages → scattered frames (+TLB cache) Logical address (CPU) → MMU → physical (RAM) Paging: fixed pages/frames → no external frag. Segmentation: logical units, base + limit VM = demand paging + page replacement FIFO · LRU · Optimal · second chance (clock) Swapping moves whole processes to disk Belady's anomaly: FIFO only · thrashing = too few frames · coalescing/compaction fix holes faults 3f: OPT 9 < LRU 12 < FIFO 15 · 4f: 8 / 8 / 10 CH 8 · FILE SYSTEMS root etc/ home/ passwd hosts bikash notes File = named data + attributes; directory maps name → FCB; tree + acyclic graph allow sharing FCB / inode: owner · size · dates · block pointers Boot control block: boots OS from the volume Allocation: contiguous · linked (FAT) · indexed Free space: bitmap · linked list · grouping · counting Access: sequential · direct · indexed; dir impl: linear list O(n) vs hash table ≈ O(1) CH 9 · I/O MANAGEMENT CPU driver device controller device main memory (DMA) OS role: drivers · buffering · caching · spooling · scheduling · error handling · protection Polling: CPU busy-waits on the status register Interrupt: device signals CPU — efficient, event-driven, supports priorities DMA: block transfer straight to memory, one interrupt per block → CPU stays free Device classes: human-readable · machine- readable · communication; block vs character BONUS · DISK SCHEDULING & RAID head 53 queue: 98 183 37 122 14 124 65 67 · minimise seek Algorithms: FCFS · SSTF · SCAN · C-SCAN · LOOK · C-LOOK (SCAN = elevator) Classic example: FCFS 640 → SSTF 236 cylinders Bad blocks → spare sectors; RAID 0 striping · 1 mirror · 5 parity · 6 double parity · 10 mirrors Formatting · cylinder skew · interleaving · error handling (from Ch 10 slides) RAID quick table RAID 0 · 1 · 5 · 6 · 10 speed · copy · parity(n−1) · 2-disk fault · best of both min disks: 2 · 2 · 3 · 4 · 4 KEY NUMBERS TO REMEMBER SJF → min avg WT 3.2 ms safe seq <P1,P3,P4,P0,P2> · P1 (1,0,2) granted faults 3f: 9/12/15 · 4f: 8/8/10 (OPT/LRU/FIFO) best-fit wins the 12/13/5 K fit problem RR q=1 avg WT 5.4 ms · avg TAT 9.2 ms SSTF 236 vs FCFS 640 cylinders

Chapter 1 — Introduction to Operating Systems

Assignment 1 · Q1 – Q7

Q1

What is an operating system? Why is an operating system required?

Definition

An operating system (OS) is a system software that acts as an intermediary between the user and the computer hardware. It is a program that manages all the resources of a computer system — CPU, memory, storage, and I/O devices — and provides an environment in which user programs can execute conveniently and efficiently.

Famous definitions: “An OS is a program that controls the execution of application programs and acts as an interface between the user and the computer hardware” and Tanenbaum's view — “the OS is the government: it provides an environment in which other programs can do useful work.”

Why is an OS required?

  • Convenience — hardware is low-level and hard to use directly; the OS offers simple abstractions (files, folders, windows, processes) through a user interface (CLI/GUI).
  • Process management — creates, schedules, and terminates processes; allows multiprogramming so the CPU is never idle.
  • Memory management — allocates and frees main memory among programs, protecting them from each other.
  • Resource allocation & sharing — fairly distributes CPU time, memory, devices and files among competing users/programs.
  • File management — organises data into files and directories on storage devices and controls access to them.
  • I/O handling — hides the complexity of device controllers and drivers behind uniform system calls.
  • Protection & security — isolates users and processes, prevents unauthorised access to data and resources.
  • Error detection & handling — constantly monitors the system for errors (CPU, memory, devices) and takes corrective action.
  • Accounting & performance — keeps statistics on resource usage for billing, tuning and planning.
Exam tip: open the answer with the definition + interface diagram, then list 5–6 reasons. Close with one line: “Without an OS, every program would have to implement its own device drivers, memory protection and scheduling — an impossible task.”
Q2

Define system call. Explain different categories of system calls with example.

Definition

A system call is the programmatic interface through which a user program requests a service from the operating system kernel. When a program needs something only the kernel may do (I/O, memory, creating a process), it invokes a system call, which raises a trap / software interrupt, switching the CPU from user mode to kernel mode; the kernel executes the request and returns the result to the program.

Categories of system calls

CategoryPurposeWindows examplesUNIX / Linux examples
Process controlCreate, terminate, load, execute and wait for processes.CreateProcess(), ExitProcess(), WaitForSingleObject()fork(), exec(), exit(), wait()
File managementCreate/delete files, open/close, read, write, reposition, get/set file attributes.CreateFile(), ReadFile(), WriteFile(), CloseHandle()open(), read(), write(), close(), lseek(), stat()
Device managementRequest, release, read/write and configure I/O devices.SetConsoleMode(), ReadConsole(), WriteConsole()ioctl(), open(), read(), write() on device files
Information maintenanceGet/set time, date, process IDs and other system data; also used for debugging.GetSystemTime(), GetCurrentProcessID(), SetTimer()getpid(), alarm(), sleep(), time()
CommunicationSet up a connection, send/receive messages between processes on the same or different machines.CreatePipe(), CreateFileMapping(), socket APIspipe(), socket(), send(), recv(), shmget()
ProtectionGet/set permissions and ownership of resources so they cannot be misused.SetFileSecurity(), AdjustTokenPrivileges()chmod(), chown(), umask()
Example flow: a C statement like count = read(file, buffer, bytes) triggers a system call: the library pushes parameters, executes trap, the kernel verifies parameters, performs the disk I/O, and returns status in a register.
Q3

Define the properties of the following operating systems: batch, real-time, time-sharing, distributed, parallel.

1. Batch Operating System

Jobs with similar needs are batched together and executed as a group by an operator; there is no direct user interaction. Early systems (IBM mainframes) worked this way.

  • Users submit jobs on cards/tape; the OS processes them one after another in a batch.
  • Jobs share the same nature/requirements, so the operator groups them to reduce setup time.
  • High throughput, but no interactivity — turnaround time can be long, and debugging is hard.
  • Modern usage: payroll processing, bank statement generation, report printing.

2. Real-Time Operating System (RTOS)

Guarantees that results are produced within a fixed, bounded deadline; correctness depends not only on the result but also on when it is delivered.

  • Hard real-time: deadlines must never be missed — critical physical tasks (missile guidance, airbags, pacemakers).
  • Soft real-time: missing a deadline only degrades quality (video streaming, online games, multimedia).
  • Event-driven, minimal jitter, priority-based scheduling, small kernels; used in embedded/industrial control systems.

3. Time-Sharing Operating System

The CPU is switched rapidly among multiple users/programs (multiprogramming with a time quantum) so each gets the illusion of having its own machine — also called multitasking.

  • Many users share the system simultaneously via terminals — interactive processing.
  • Each user gets a small time slice; response time is short (typically < 1 second).
  • Uses CPU scheduling, swapping/virtual memory and spooling; improves CPU utilisation and gives faster response.
  • Examples: UNIX, Linux, Windows multi-user servers.

4. Distributed Operating System

Multiple independent, networked computers appear to users as a single coherent system; the OS coordinates them via message passing.

  • Each node has its own memory and CPU; no shared physical clock or memory.
  • Resource sharing, load balancing, computation speedup, and high availability (graceful degradation if a node fails).
  • Communication takes place over a network using messages/RPC — slower than shared memory.
  • Examples: LOCUS, Amoeba, cluster and cloud systems.

5. Parallel Operating System (Multiprocessor / Multicore)

Runs on systems with two or more processors in close communication sharing the bus, clock, memory and peripherals, executing multiple tasks truly simultaneously.

  • Increased throughput — more work per unit time; economical — resources are shared.
  • Increased reliability — graceful degradation / fault tolerance if one processor fails.
  • Symmetric multiprocessing (SMP): all processors are peers running one OS copy; asymmetric: a master controls slaves.
  • Key issue: cache coherence and synchronisation among processors.
Also in the syllabus — Multiprogrammed OS: keeps several jobs in main memory at once, so when the running job waits for I/O the CPU immediately switches to another — the CPU is never idle. It is the foundation of time-sharing (which adds a time quantum), and its multiprogramming degree = number of jobs resident in memory.
Q4

Describe various services provided by operating system.

An OS provides services both to users (making the system convenient) and to programs (making execution efficient):

  • Program execution — loads a program into memory and runs it; handles scheduling and normal/abnormal termination.
  • I/O operations — every program needs input/output; the OS performs them on behalf of the user via device drivers (file or device read/write).
  • File-system manipulation — create/delete files and directories, read/write/search, list, and control permissions (read/write/execute).
  • Communication — allows processes to exchange information via shared memory or message passing, on the same machine or across a network.
  • Error detection — continuously checks CPU, memory, I/O devices and programs for errors; reports and recovers to keep the system consistent.
  • Resource allocation — allocates CPU cycles, memory, files, storage and devices to multiple users/jobs running at the same time (using schedulers, partitioning, queues).
  • Accounting — records which resources, how much, and for whom — for billing, usage statistics and performance tuning.
  • Protection & security — controls access to system resources (mode bits, permissions) and authenticates users so one user/process cannot harm another.
  • User interface — CLI (command interpreter / shell), GUI (windows, icons, menus, pointer), or touch/voice interfaces.
A good answer draws the two service groups: services for the user (UI, program execution, I/O, file manipulation, communication, error detection) and services for efficient operation (resource allocation, accounting, protection & security).
Q5

Can OS be called as a resource manager and an extended machine? Justify.

Yes. Both views (Tanenbaum's) describe the OS completely — one looks upward (service provider), the other downward (manager).

1. OS as an Extended Machine (Top-down view)

The bare machine's hardware is complicated: disk drives, timers, GPUs each expose messy, low-level interfaces. The OS hides the hardware details and presents the user with a cleaner, easier, more abstract “virtual machine” — files instead of disk blocks, processes instead of CPU registers, virtual memory instead of physical RAM addresses.

  • Users see abstractions: processes, files, directories, sockets, pipes, virtual memory.
  • The abstraction is simpler to use and portable across different hardware.
  • Hence the OS extends the machine: hardware + OS = a more powerful virtual machine.

2. OS as a Resource Manager (Bottom-up view)

A computer has limited resources — CPU time, memory, disk space, devices — demanded by many competing programs. The OS allocates, schedules, shares and protects these resources among processes fairly and efficiently.

  • Multiplexing in time — different programs take turns using the CPU (scheduling).
  • Multiplexing in space — memory and disk are divided among programs (allocation).
  • Also ensures protection (no process steals another's resources), accounting, and resolves conflicts between users.
Conclusion: The extended-machine view justifies convenience and the resource-manager view justifies efficiency — the two classic goals of an OS — so the OS is legitimately both.
Q6

Differentiate between batch system and time-sharing system.

BasisBatch SystemTime-Sharing System
Basic ideaSimilar jobs are grouped into batches and executed one after another.CPU time is divided into small slices and switched rapidly among many users/tasks.
User interactionNo interaction — jobs are submitted and collected later.Interactive — user communicates with the system during execution.
UsersEffectively single user / single job at a time.Many users share the system simultaneously via terminals.
Response / turnaroundHigh turnaround time; response delayed till batch completes.Short response time (usually < 1 s); results seen immediately.
CPU utilisationModerate — CPU may idle waiting for I/O of the current job.High — while one process waits for I/O, another uses the CPU.
SchedulingJobs run to completion in sequence (FCFS-like).Preemptive round-robin / time-quantum based scheduling is essential.
MemoryOne job resident at a time (simple partitioning).Needs swapping / virtual memory to hold many processes.
Design goalMaximise throughput; minimise operator setup.Minimise response time; fairness among users.
ExamplePayroll system, bank statement printing (old IBM batch).UNIX / Linux multi-user time-sharing, online transaction systems.
Q7

Define operating system structure. Explain simple, layered and virtual machine structure with suitable diagram.

OS structure refers to how the components of the operating system are organised and how they interact with the hardware and user programs — i.e., the internal architecture of the OS. Three classic structures:

1. Simple / Monolithic Structure (MS-DOS)

The OS is written as one big program with no clear separation between layers — applications and the OS can call almost anything. It is simple to build and fast, but poorly structured and fragile: any bug can crash the whole system, and it is hard to extend or port.

Application programs Resident system program MS-DOS device drivers (ROM BIOS)
Simple (MS-DOS) structure — users can reach drivers and BIOS almost directly; boundaries are weak.

2. Layered Structure (THE Operating System)

The OS is divided into N levels (layers): layer 0 is the hardware and layer N is the user interface. Each layer only uses the services of the layer directly below it.

  • Advantages: modular design — easier to debug and verify (errors are localised to one layer), easy to replace/extend a layer, information hiding.
  • Disadvantages: hard to define layers properly (each must use only lower layers), performance cost of crossing many layers; less efficient than monolithic.
  • Examples: THE system (Dijkstra, 6 layers), Multics (8 layers), MULTICS ring model.
Layer 5 · User programs Layer 4 · Buffering for I/O devices Layer 3 · Operator–console device driver Layer 2 · Memory management Layer 1 · CPU scheduling Layer 0 · Hardware
Layered (THE) structure — each layer uses only the services of the lower adjacent layer.

3. Virtual Machine Structure

A virtual machine treats the hardware + host OS as if it were bare hardware: the VM monitor creates the illusion that each process/user has its own dedicated processor with its own (virtual) memory and devices. Each guest can run its own complete OS on top of the host.

  • Implemented by a Virtual Machine Monitor (hypervisor) — e.g., VMware, VirtualBox, Hyper-V, JVM (for Java bytecode), IBM CP/CMS.
  • Advantages: complete protection & isolation of VMs; different OSes on one physical machine; easy research, development and testing; snapshots, live migration and cloud computing are possible.
  • Disadvantages: implementing the virtual CPU/devices is difficult; exact simulation of hardware introduces overhead (virtualisation cost).
VM #1Guest OS + apps VM #2Guest OS + apps VM #nGuest OS + apps Virtual Machine Monitor / Host OS (Hypervisor) Physical hardware (CPU · Memory · Disk · Network) Each VM believes it owns the entire machine
Virtual machine structure — a hypervisor multiplexes the physical machine into several virtual machines.

Chapter 2 — Process Scheduling Algorithms

Assignment 2 · Theory + fully worked numerical (all values verified by simulation)

Q

Differentiate preemptive and non-preemptive scheduling algorithms.

Preemptive scheduling: the CPU can be taken away from a running process before it finishes (on timeout, or when a higher-priority process arrives). Non-preemptive (cooperative): once a process gets the CPU it keeps it until it terminates or voluntarily switches to waiting state.

BasisPreemptive SchedulingNon-Preemptive Scheduling
CPU controlOS can forcibly take the CPU from a running process.Process holds the CPU until it terminates or blocks for I/O.
InterruptUses a timer interrupt / higher-priority arrival to pre-empt.No forced interruption; relies on the process's cooperation.
Cost / overheadHigher — frequent context switches.Lower — fewer context switches.
Response timeShort — good for interactive / real-time systems.Longer — an unlucky process may starve response.
StarvationLow priority processes may starve (needs ageing).A long job delays short jobs behind it (convoy effect).
Data consistencyRace conditions possible; needs synchronisation.Simpler, safer for shared data.
Flexible?Flexible — supports priorities and fair sharing.Rigid — scheduling decisions only at job switch points.
ExamplesSRTF, Round Robin, (preemptive) Priority.FCFS, SJF, (non-preemptive) Priority.
Scheduling decisions may be needed when a process: (1) switches running → waiting, (2) switches running → ready (preemption), (3) switches waiting → ready (preemption), (4) terminates. Options 1 & 4 alone ⇒ non-preemptive; with 2 & 3 ⇒ preemptive.
Q

Given P1(10, pri 3), P2(1, pri 1), P3(2, pri 3), P4(1, pri 4), P5(5, pri 2) — all arriving at time 0 in order P1…P5: (i) draw Gantt charts for FCFS, SJF, non-preemptive priority and RR (q = 1); (ii) waiting times; (iii) turnaround times; (iv) which algorithm gives minimum average waiting time?

ProcessBurst Time (ms)Priority (1 = highest)
P1103
P211
P323
P414
P552

(i) Gantt Charts

1 · FCFS — jobs run in arrival order P1, P2, P3, P4, P5
P1
P2
P3
P4
P5
0
10
11
13
14
19
2 · SJF (non-preemptive) — shortest job first: P2(1) → P4(1) → P3(2) → P5(5) → P1(10)
P2
P4
P3
P5
P1
0
1
2
4
9
19
3 · Non-preemptive Priority — smaller number = higher priority: P2(1) → P5(2) → P1(3) → P3(3) → P4(4)
P2
P5
P1
P3
P4
0
1
6
16
18
19
4 · Round Robin (quantum = 1) — queue cycles P1 P2 P3 P4 P5, re-queued after each quantum
P1
P2
P3
P4
P5
P1
P3
P5
P1
P5
P1
P5
P1
P5
P1
P1
P1
P1
P1
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
P1P2P3P4P5

(ii) Waiting Time (WT = Start-time in CPU total − Burst… i.e. time spent in ready queue)

AlgorithmP1P2P3P4P5Average WT
FCFS01011131448 / 5 = 9.6 ms
SJF9021416 / 5 = 3.2 ms
Priority (non-preemptive)601618141 / 5 = 8.2 ms
RR (q = 1)9153927 / 5 = 5.4 ms

WT = Turnaround − Burst. RR e.g. P5 runs at 4,7,9,11,13 and finishes at 14 ⇒ WT = 14 − 5 = 9.

(iii) Turnaround Time (TAT = Completion − Arrival, arrival = 0)

AlgorithmP1P2P3P4P5Average TAT
FCFS101113141967 / 5 = 13.4 ms
SJF19142935 / 5 = 7.0 ms
Priority (non-preemptive)1611819660 / 5 = 12.0 ms
RR (q = 1)192741446 / 5 = 9.2 ms

(iv) Conclusion

SJF results in the minimum average waiting time (3.2 ms) — and also the minimum average turnaround time (7.0 ms). This is expected: SJF is provably optimal for a given set of processes when all arrive at once. Ranking (avg WT): SJF 3.2 < RR 5.4 < Priority 8.2 < FCFS 9.6.

Chapters 3 & 4 — Processes, Threads, Synchronization & IPC

Assignment 3 · Q1 – Q10

Q1

Why is inter-process communication required? Explain. Differentiate between user and kernel thread. Draw figures to illustrate.

Why IPC is required

Each process has its own isolated address space, so cooperating processes cannot simply share variables. Inter-process communication (IPC) — provided by the OS via shared memory or message passing — is needed because:

  • Information sharing — several processes (e.g., a web server and its helpers) must access the same data.
  • Computation speedup — a big task can be split among processes/cores running in parallel.
  • Modularity — a system is designed as separate cooperating modules (compiler, editor, shell) that need to talk.
  • Convenience — a user may work on many tasks at once (edit, compile, browse) which exchange data.
  • Synchronization & coordination — processes must signal events (producer tells consumer that data is ready).

User thread vs Kernel thread

BasisUser-Level Thread (ULT)Kernel-Level Thread (KLT)
Managed byA user-space library (e.g., POSIX Pthreads, Java threads) — the OS does not know about them.The OS kernel itself — thread table kept in kernel space.
Creation / switchingFast — no kernel intervention / mode switch needed.Slower — requires system calls and mode switching.
Blocking callIf one thread blocks (e.g., on I/O), the entire process blocks.Only that thread blocks; kernel schedules another thread of the process.
MultiprocessingCannot run on different CPUs in parallel (kernel schedules the whole process).Different threads may run truly in parallel on multiple CPUs.
Kernel awarenessKernel treats the process as single-threaded.Kernel schedules each thread individually.
Portability / implementationEasy, portable — only a library is required.Complex — kernel must be modified to support threads.
ExamplePOSIX threads (user mode), GNU Portable Threads.Windows threads, Linux threads (pthreads mapped to kernel tasks).

The two levels are combined by multithreading models:

Many-to-One User thread U1 User thread U2 User thread U3 Kernel thread K1 fast, but one block = all block; no true parallelism One-to-One User thread U1 User thread U2 User thread U3 K1 K2 K3 true parallelism; overhead of creating kernel threads (Linux, Windows) Many-to-Many U1 U2 U3 (user level) K1 K2 K3 multiplexes m user threads onto n kernel threads — best of both
Fig: Multithreading models linking user threads (top, library-managed) to kernel threads (bottom, OS-managed).
Q2

Define race conditions. What are the different techniques for avoiding race condition? Explain each of them in brief.

Definition

A race condition is a situation where several processes access and manipulate shared data concurrently, and the final result depends on the particular order (timing) in which their accesses are interleaved. To avoid it, the shared-data accesses must be made mutually exclusive — execution must not be interleaved inside the region that touches shared data.

Classic example: two processes execute counter++ (registers: load → increment → store). If both read counter = 5 and interleave their stores, the final value becomes 5 instead of 7 — one update is lost.

Techniques for avoiding race conditions

  1. Disabling interrupts (hardware approach) — a process entering the critical section turns interrupts off, so no timer preemption can interleave another process. Simple for a single CPU, but dangerous to give user programs this power and does not scale to multiprocessors.
  2. Lock variables (software busy-wait) — a shared boolean; test-and-set it before entering. A naive single lock variable itself suffers a race — safe only when done with atomic instructions.
  3. Strict alternation — an integer turn alternates entry rights between the two processes (0, 1, 0, 1…). It gives mutual exclusion, but violates progress: a process must wait even when the other is not interested in entering.
  4. Peterson's solution (pure software) — two-process protocol using a flag[] array and turn variable; guarantees mutual exclusion, progress and bounded waiting.
  5. Atomic hardware instructions — TSL / Test-and-Set, swap — the instruction reads and writes a lock atomically, used to build spinlocks that work even on multiprocessors.
  6. Sleep & wakeup primitives — instead of busy-waiting, a blocked process goes to sleep and the process whose action unblocks it issues a wakeup (the basis of the sleeping implementations in producer–consumer; the classic risk is a lost wakeup if signals are not remembered — solved by semaphores).
  7. Mutex locks — an OS-provided lock: acquire() before the critical section, release() after; blocks (sleeps) instead of busy-waiting; has ownership.
  8. Semaphores — an integer counter manipulated atomically by wait() / signal(); enforces mutual exclusion (binary semaphore) and ordering/resource counting (counting semaphore); waiters are put to sleep, so no busy waiting.
  9. Monitors — a high-level language construct: shared data + procedures inside one object where only one process may be active at a time; condition variables handle waiting (e.g., Java synchronized).
Q3

Describe Peterson's solution. Define and explain the purposes of TSL, mutex & semaphore.

Peterson's Solution

A classic software-based solution to the critical-section problem for two processes P0 and P1. It uses two shared variables: int turn (whose turn it is to enter) and boolean flag[2] (is a process ready to enter?).

// shared:  int turn;  boolean flag[2] = {false, false};
// code for process P[i]  (j = other process)
do {
    flag[i] = true;      // I want to enter
    turn    = j;          // but let the other go first
    while (flag[j] && turn == j) ;  // busy wait

        critical section

    flag[i] = false;      // I am done
        remainder section
} while (true);
  • Mutual exclusion: Pi and Pj cannot both be inside — only the one whose flag is true and whose turn it is enters.
  • Progress: if the other process is not interested (flag[j] = false), Pi enters immediately.
  • Bounded waiting: turn = j ensures Pj enters after at most one entry by Pi.
  • Caveat: on modern out-of-order CPUs it may fail without memory barriers — it is of historical/conceptual value.

TSL (Test-and-Set Lock instruction)

Definition: an atomic hardware instruction: TSL lock, R1 reads the old value of lock into R1 and writes TRUE to lock in one indivisible step (memory is locked on the bus during it).

Purpose: to build mutual exclusion that cannot race — whoever executes TSL first gets the lock; others spin. It fixes the weakness of pure software locks and works on multiprocessors; used to implement spinlocks.

enter_region:
    TSL REGISTER, LOCK      // atomically copy & set lock
    CMP REGISTER, #0        // was lock free?
    JNE enter_region        // no – keep trying (spin)
    RET                     // yes – critical section entered
leave_region:
    MOVE LOCK, #0           // release
    RET

Mutex (Mutual Exclusion lock)

Definition: an OS-level locking variable with ownership: only the thread that locked a mutex may unlock it. Calls: acquire()/lock() before and release()/unlock() after the critical section.

Purpose: protect a shared resource from concurrent access with no busy waiting — if the lock is taken, the thread is put to sleep (block) and woken when released. Simplest tool when a resource is used by one thread at a time.

Semaphore

Definition: an integer variable S accessed only through two atomic operations: wait(S) / P (decrement, block if S < 0) and signal(S) / V (increment, wake a waiter).

wait(S){ while(S <= 0); S--; }   signal(S){ S++; }  // spin version; OS version sleeps

Purpose: a general-purpose synchronisation tool — binary semaphore (0/1) gives mutual exclusion like a mutex but without ownership; counting semaphore manages N identical resources or counts events; can also enforce execution ordering (P2 waits on a semaphore P1 signals). Semaphores avoid busy waiting when implemented with blocked queues.

One-line comparison: TSL = atomic hardware instruction for spinlocks; mutex = OS lock with ownership, sleeping waiter; semaphore = generalised counter for both exclusion and signalling, no ownership.
Q4

Explain the dining-philosophers problem as a classic synchronization problem with pseudo code.

Problem: 5 philosophers sit around a circular table, alternating between thinking and eating. Between every two adjacent plates lies one chopstick (5 total). A philosopher must pick up both the left and the right chopstick to eat, and put both down when finished. The problem models the allocation of multiple exclusive resources among competing processes and shows how naive resource allocation leads to deadlock and starvation.

P0 P1 P2 P3 P4 c[0] c[1] c[2] c[3] c[4] philosopher i needs c[i] and c[(i+1)%5]
Fig: 5 philosophers, 5 chopsticks — philosopher i needs chopstick[i] (right) and chopstick[(i+1) % 5] (left).

Naive (deadlock-prone) solution with semaphores

// chopstick[0..4] : semaphores, all initialised to 1
philosopher(i):
    while(true){
        think();                    // non-critical work
        wait(chopstick[i]);          // pick up RIGHT chopstick
        wait(chopstick[(i+1)%5]);    // pick up LEFT chopstick
        eat();
        signal(chopstick[i]);
        signal(chopstick[(i+1)%5]);
    }

Why it fails: if every philosopher picks up the right chopstick simultaneously, each waits forever for the left one — circular wait ⇒ deadlock.

Correct solutions

  1. Allow at most 4 philosophers at the table — add wait(room) with room = 4; someone always gets both sticks.
  2. Pick up both chopsticks atomically (a monitor/mutex region: take them together or not at all).
  3. Asymmetric (odd–even) rule — odd philosophers pick the left stick first, even ones the right first; the circular wait chain is broken.
// fix (c): asymmetric pick-up — breaks circular wait
if (i % 2 == 0) { wait(c[i]);      wait(c[(i+1)%5]); }
else           { wait(c[(i+1)%5]); wait(c[i]); }
Q5

Explain the producer–consumer problem as a classic synchronization problem with pseudo code.

Problem (bounded buffer): a producer process generates items and puts them into a fixed-size circular buffer of size N; a consumer removes and uses them. The two share the buffer, so three conditions must be enforced: the producer must not insert when the buffer is full, the consumer must not remove when it is empty, and insertions/removals (shared counter/indices) must be mutually exclusive.

PRODUCER produces item ▪ ▪ ▪ bounded buffer of size N CONSUMER consumes item
Fig: Producer–consumer with a bounded buffer — semaphores count empty and full slots; a mutex guards the buffer.

Semaphore solution

// shared:
#define N 10
semaphore mutex = 1;   // binary — protects buffer & counter
semaphore empty = N;   // counting — free slots
semaphore full  = 0;   // counting — filled slots

Producer:                       Consumer:
while(true){                    while(true){
  item = produce_item();          wait(full);   // any item?
  wait(empty);  // free slot?      wait(mutex);
  wait(mutex);                    item  = remove_item();
  insert_item(item);              signal(mutex);
  signal(mutex);                  signal(empty); // +1 free slot
  signal(full); // +1 full slot     consume_item(item);
}                               }
Key exam point: the order matters — producer must wait(empty) before wait(mutex). Swapping them lets the producer hold the mutex while waiting for a free slot; the consumer can then never enter ⇒ deadlock.
Q6

Explain the sleeping-barber problem as a classic synchronization problem with pseudo code.

Problem: A barbershop has one barber, one barber chair, and a waiting room with N chairs. The barber sleeps when there are no customers. A customer who arrives and finds a free waiting chair sits down and wakes the barber; if the shop is full the customer leaves. The barber cuts one customer's hair, then checks the waiting room. It models resource allocation with a limited service provider and bounded queue (a generalisation of producer–consumer with a finite waiting room).

  • Shared state: number of waiting customers, protected by a mutex.
  • Signals: customers — barber waits on it (sleeps when 0); barber — customer waits on it for his turn.
// shared:
#define N 5                          // waiting-room chairs
semaphore customers = 0;              // waiting customers (barber sleeps if 0)
semaphore barber    = 0;              // barber ready signal
semaphore mutex     = 1;              // guards 'waiting' counter
int waiting = 0;                      // customers in waiting room

Barber:                               Customer:
while(true){                          wait(mutex);
  wait(customers);  // sleep if none  if (waiting < N){
  wait(mutex);                            waiting++;
  waiting--;                              signal(customers);
  signal(barber);   // invite one        signal(mutex);
  signal(mutex);                          wait(barber); // wait for turn
  cut_hair();                             get_haircut();
}                                     }
                                          else signal(mutex); // shop full → leave

How it works

  1. Barber starts: wait(customers) blocks — he sleeps.
  2. A customer increments waiting, signals customers → barber wakes and decrements the count.
  3. Barber signals barber — exactly one waiting customer takes the chair; others keep waiting.
  4. If waiting == N on arrival, the customer releases the mutex and leaves (no deadlock, no lost wake-ups).
Q7

How is a thread different from a process? Describe in detail the different state transition models of a process.

Process vs Thread

A process is a program in execution with its own address space, file descriptors, registers and PCB. A thread is the basic unit of CPU execution inside a process — it shares the process's address space and resources with sibling threads but has its own program counter, register set, stack and state (TCB).

BasisProcessThread
DefinitionA program in execution; heavyweight unit of work.A lightweight sub-unit of a process; unit of CPU scheduling.
Address spaceOwn separate address space.Shares the address space of its process.
OwnsCode, data, heap, stack, open files, PCB.Only its own stack, registers, program counter, TCB.
Creation / terminationExpensive (memory map, PCB, page tables).Cheap — no new address space needed.
Context switchSlow (flush TLB, switch page tables).Fast (same address space retained).
CommunicationNeeds IPC (pipes, messages, shared memory).Direct — shared variables (needs synchronisation).
Isolation / safetyStrong — one process cannot corrupt another.Weak — one thread can crash the whole process.
DependenceIndependent of other processes.Sibling threads die if the process dies.

Process State Transition Model (5-state)

As a process executes, it moves through states. Transitions:

  • Admitted — job submitted; PCB created; moves New → Ready.
  • Dispatch — scheduler selects it; Ready → Running.
  • Interrupt / time-out — higher priority arrives or quantum expires; Running → Ready.
  • Event wait (I/O request) — Running → Blocked/Waiting.
  • Event completion — the awaited I/O finishes; Blocked → Ready.
  • Exit — Running → Terminated; OS reclaims resources.
New Ready Running Blocked / Waiting Terminated admitted dispatch time-out / interrupt event wait (I/O) eventcompleted exit
Fig: Five-state process transition model (New, Ready, Running, Blocked, Terminated).

Extended (7-state) model adds Ready-suspend and Blocked-suspend states, when the OS swaps blocked processes out to disk to free memory.

Q8

What is a critical section? What are the minimum requirements that should be satisfied by a solution to the critical-section problem? Explain the software solution.

Definition

Each process has a segment of code, the critical section (CS), in which it accesses shared data / resources (variables, files, tables). When one process is executing in its critical section, no other process may enter its own critical section that touches the same shared data — otherwise race conditions corrupt the data.

do {
   entry section        // request permission (acquire lock)
      CRITICAL SECTION  // touch shared data
   exit section         // release lock
   remainder section    // other code
} while(true);

Minimum requirements of any CS solution

  1. Mutual exclusion — at most one process may execute inside its critical section at a time.
  2. Progress — if the CS is free and some processes wish to enter, only those processes participate in choosing who enters next, and the choice cannot be postponed indefinitely.
  3. Bounded waiting — there is a limit on how long a process waits to enter after requesting (no starvation).

Software solution — Peterson's algorithm

The best-known two-process software solution (full code in Q3 above): it combines a flag[] array (interest in entering) with the turn variable (permission when both are interested).

// Process Pi  (Pj = the other)   — satisfies all 3 requirements
flag[i] = true;      // entry section: express interest
turn    = j;         // politely yield turn
while (flag[j] && turn == j);   // wait while other interested & has turn
   CRITICAL SECTION
flag[i] = false;     // exit section

Why it works: Pi can enter only if flag[j] == false (Pj not interested ⇒ no conflict) or turn == i (it is Pi's turn). Both conditions can hold for both processes only if both set turn = j and turn = i simultaneously — impossible; hence mutual exclusion. turn alternates, giving bounded waiting.

Limitations: busy waiting wastes CPU, works for 2 processes only, and needs memory barriers on modern hardware. For general use we use atomic hardware instructions (TSL), mutexes and semaphores.
Q9

What is mutual exclusion? Show how mutual exclusion can be achieved using Peterson's solution.

Mutual exclusion

Mutual exclusion is the guarantee that when one process is executing in its critical section, no other process can execute in its critical section (for the same shared resource) — i.e., the shared accesses are serialised so the result never depends on interleaving.

Achieving it with Peterson's solution

// Shared variables
int turn;
boolean flag[2] = {false, false};

// Structure of process Pi (i = 0 or 1, j = 1 - i)
do {
   flag[i] = true;          // 1. I want to enter
   turn    = j;             // 2. you may go first
   while (flag[j] && turn == j) ;  // 3. busy-wait (entry)

      /* ---- CRITICAL SECTION ---- */

   flag[i] = false;         // 4. exit: I am out
      /* remainder section */
} while (true);

Proof of mutual exclusion

Pi enters the CS only when flag[j] == false or turn == i. Suppose both P0 and P1 were inside: then flag[0] == flag[1] == true. Each set turn last to the other's number, so turn can hold only one value (say 1). Then P0's entry condition flag[1] && turn == 1 is true — so P0 must still be waiting — a contradiction. Hence at most one process is ever in the CS ⇒ mutual exclusion holds. (Progress: a waiting process is blocked only while the other is genuinely interested; Bounded waiting: turn alternates, so Pj waits at most one CS execution of Pi.)

Q10

What is IPC? What are the different methods used for logical implementations of message-passing systems?

Definition

IPC (Inter-Process Communication) is the mechanism provided by the OS that allows cooperating processes to exchange data and synchronise their actions. It has two fundamental models: shared memory (fast; processes read/write a common region; user-managed synchronisation) and message passing (slower; kernel transmits send()/receive() messages; good for distributed systems).

Logical implementation methods of message passing

  1. Naming — direct vs indirect
    Direct: processes address each other explicitly (send(P, msg), receive(Q, msg)) — one link per pair, automatic bidirectional.
    Indirect: messages go to mailboxes/ports (send(A, msg)) — a link exists only if both share a mailbox; a mailbox can be owned by a process or by the OS; supports many-to-many communication.
  2. Synchronisation — blocking vs non-blocking
    Blocking (synchronous): sender waits until the message is received; receiver waits until a message arrives — tight synchronisation (rendezvous).
    Non-blocking (asynchronous): sender continues immediately; receiver polls or is signalled later.
  3. Buffering — capacity of the queue on the link
    Zero capacity: no queue — sender must block until receiver ready (message systems become rendezvous).
    Bounded capacity: finite queue of n messages — sender blocks only when the queue is full.
    Unbounded capacity: infinite queue — sender never waits.
  4. Message format & addressing — fixed-size messages (simple, low overhead, used in OS kernels) vs variable-size (flexible, used in distributed systems); send by copy vs send by reference.
  5. Queueing discipline — FIFO ordering of messages, or priority queues for urgent messages.
  6. Exceptions / extra: mailbox ownership, message acknowledgement, timeouts and failure handling in distributed settings.

Chapter 5 — Deadlocks

Assignment 4 · Q1 – Q7 (numerical verified by simulation)

Q1

What is deadlock? What are preemptable and non-preemptable resources? Describe.

Deadlock

A deadlock is a situation in which a set of processes is blocked because each process holds a resource and waits for a resource held by another process in the set. Since nobody releases what the others need, none can ever proceed — they wait forever.

Example: P1 holds printer, requests tape drive; P2 holds the tape drive and requests the printer. Both block permanently.

Preemptable vs Non-preemptable resources

BasisPreemptable ResourceNon-Preemptable Resource
MeaningCan be taken away from the holding process without harm; its state can be saved and restored later.Cannot be snatched away; taking it causes failure or loss of work — it must be released voluntarily.
ExamplesCPU, main memory (swapping), buffer space, printer queue entries.Printer/tape drive mid-job, file locks, database records, CD burner, semaphore-held devices.
Deadlock roleRarely cause deadlock — preemption breaks waits.The usual cause of deadlock — a cycle of waits on these is fatal.
How handledOS simply re-allocates (schedules) it to another process.Handled by request/release protocols, ordering, avoidance.
Deadlocks involve only non-preemptable (serially reusable) resources — for preemptable ones the OS simply steals the resource back.
Q2

What is resource allocation graph? Describe.

A Resource Allocation Graph (RAG) is a directed graph that describes the state of resource allocation in the system — who holds what and who is waiting for what.

  • Vertices: circles = processes Pi; rectangles = resource types Rj (dots inside a rectangle = number of instances of that resource).
  • Request edge Pi → Rj (process waiting for a resource).
  • Assignment edge Rj → Pi (an instance is held by the process).
R1 (3 instances) R2 (1 instance) P1 P2 P3 R1 → P1 (assigned) R1 → P3 (assigned) P2 requests R1 R2 → P1 (assigned) P3 requests R2 red = request edge · gray = assignment edge
Fig: Resource allocation graph — P2 waits for R1, P3 waits for R2; no cycle ⇒ no deadlock.

Interpretation rules

  • No cycle in the graph ⇒ no deadlock (safe).
  • Cycle + only single instances of each resource in the cycle ⇒ deadlock exists (cycle is necessary and sufficient).
  • Cycle with multiple instances ⇒ cycle is only necessary; deadlock may exist (need the detection algorithm to decide).
Q3

What are the four necessary conditions for deadlock to occur? Describe.

A deadlock can arise if and only if all four of the following conditions hold simultaneously:

  1. Mutual exclusion — at least one resource is non-sharable: only one process can use it at a time; any other requesting process must wait (e.g., a printer, a locked record).
  2. Hold and wait — a process is holding at least one resource while waiting to acquire additional resources held by others.
  3. No preemption — resources cannot be forcibly taken from a process; they are released only voluntarily when the process finishes using them.
  4. Circular wait — there exists a circular chain of processes {P0, P1, …, Pn} such that Pi waits for a resource held by P(i+1) mod n; each process waits for the next one's resource, forming a cycle.
Usefulness: deadlock prevention works by attacking (negating) one of these four conditions. If any one condition is absent, deadlock cannot occur.
Q4

List and describe the techniques for deadlock recovery.

Before recovery: deadlock detection

  • Single instance per resource type: build the wait-for graph (collapse resource nodes out of the RAG) — a cycle in it means deadlock; run the check periodically or on every request.
  • Multiple instances: use a detection algorithm identical in shape to Banker's safety test: Work = Available, Finish[i] = false (or Allocationi = 0); repeatedly pick a process with Requesti ≤ Work and add its Allocation into Work. If some Finish stays false, those processes are deadlocked.

When detection finds a deadlock, the system must break the circular wait. Recovery techniques:

  1. Process termination
    a) Abort all deadlocked processes — certain but very costly (all their work is lost).
    b) Abort one process at a time until the cycle breaks — after each kill, re-run the detection algorithm; choose the victim by cost (CPU time used, resources held, priority, how long to completion).
  2. Resource preemption — forcibly take resources from some processes and give them to others until the cycle is broken. Requires three issues to be handled:
    • Selecting a victim — minimise cost (resources held, time consumed).
    • Rollback — the robbed process cannot continue normally; return it to some safe state (checkpoint) and restart it later. Since a safe state is hard to determine, total restart is often used.
    • Starvation — the same victim may always be picked; include the number of rollbacks in the cost to guarantee finite progress.
  3. Manual / operator intervention — kill processes by hand (e.g., task manager), used in practice on interactive systems.
Q5

How can deadlock be prevented? Describe briefly.

Prevention ensures the system never enters a deadlocked state by breaking at least one of the four necessary conditions by design:

  1. Attack mutual exclusion — make resources sharable where possible (read-only files, spooling: a printer daemon accepts jobs so no process holds the printer directly). Limitation: some resources are inherently non-sharable.
  2. Attack hold-and-wait — require every process to request all its resources at once and block until all are available; or allow a request only when the process holds nothing. Drawbacks: low resource utilisation and possible starvation.
  3. Attack no-preemption — if a process holding some resources requests another that cannot be granted immediately, preempt (take back) all resources it holds and it must re-request them later; or preempt resources from waiting processes. Works for state-saveable resources (CPU, memory) but not for printers mid-job.
  4. Attack circular wait — impose a total ordering on resource types (numbered 1…n) and force every process to request resources in strictly increasing order (and release in decreasing order). No cycle can form, hence no deadlock. Most practical method (e.g., always lock A before B).
Related (from the course deck): the Ostrich algorithm — simply ignore the problem, since deadlocks are rare and handling them is expensive; UNIX/Windows take this approach for general resources.
Q6

Describe Banker's algorithm.

The Banker's algorithm (Dijkstra) is a deadlock avoidance technique for multiple instances of resources. Named because it works like a banker never granting loans that could leave him unable to satisfy all customers: the OS never grants a request if granting could lead to an unsafe state (one from which deadlock is possible).

Data structures (n processes, m resource types)

  • Available[m] — instances of each resource currently free.
  • Max[n][m] — maximum demand of each process.
  • Allocation[n][m] — resources currently held by each process.
  • Need[n][m] = Max − Allocation — resources still needed.

Safety algorithm (is the state safe?)

  1. Let Work = Available and Finish[i] = false for all i.
  2. Find an i with Finish[i] = false and Need[i] ≤ Work. If none exists, go to step 4.
  3. Process Pi can finish: Work = Work + Allocation[i], set Finish[i] = true; go to step 2.
  4. If all Finish[i] = true, the system is in a safe state; the order of completion is a safe sequence. Otherwise the state is unsafe.

Request-resource algorithm (when Pi requests Requesti)

  1. If Requesti ≤ Needi, go to 2; else error (exceeded declared maximum).
  2. If Requesti ≤ Available, go to 3; else the process must wait (resources not free).
  3. Pretend to allocate: Available −= Requesti; Allocationi += Requesti; Needi −= Requesti. Run the safety algorithm — if the resulting state is safe, grant the request; otherwise roll back and let Pi wait.
Drawbacks (asked in the deck): processes must declare maximum needs in advance; the number of processes/resources is fixed; a check on every request costs O(n²·m); low resource utilisation because allocations are kept conservative.
Q7

System snapshot — 10 instances of A, 5 of B, 7 of C; Available = (3,3,2): (i) is the system safe (find the safe sequence)? (ii) if P1 requests (1,0,2), can it be granted immediately?

Applying the Banker's algorithm to the given snapshot (10 instances of A, 5 of B, 7 of C):

ProcessAllocationMaxNeed = Max − Alloc
ABCABCABC
P0010753743
P1200322122
P2302902600
P3211222011
P4002433431

(i) Safety algorithm — Work starts at Available = (3, 3, 2)

StepProcess runNeed ≤ Work?Work beforeWork after (Work + Allocation)
1P1(1,2,2) ≤ (3,3,2) ✓3 3 23+2, 3+0, 2+0 = 5 3 2
2P3(0,1,1) ≤ (5,3,2) ✓5 3 25+2, 3+1, 2+1 = 7 4 3
3P4(4,3,1) ≤ (7,4,3) ✓7 4 37+0, 4+0, 3+2 = 7 4 5
4P0(7,4,3) ≤ (7,4,5) ✓7 4 57+0, 4+1, 5+0 = 7 5 5
5P2(6,0,0) ≤ (7,5,5) ✓7 5 57+3, 5+0, 5+2 = 10 5 7
All processes finish ⇒ the system is in a SAFE state. Safe sequence: <P1, P3, P4, P0, P2> (equally, <P1, P3, P4, P2, P0> works — any sequence found by the algorithm is a valid answer).

(ii) Request from P1 = (1, 0, 2)

Step 1 — Request ≤ NeedP1: (1,0,2) ≤ (1,2,2) ✓   Step 2 — Request ≤ Available: (1,0,2) ≤ (3,3,2) ✓

Step 3 — pretend allocation: Available = (3,3,2) − (1,0,2) = (2,3,0); AllocationP1 = (3,0,2); NeedP1 = (0,2,0).

StepProcess runNeed ≤ Work?Work beforeWork after
1P1(0,2,0) ≤ (2,3,0) ✓2 3 02+3, 3+0, 0+2 = 5 3 2
2P3(0,1,1) ≤ (5,3,2) ✓5 3 27 4 3
3P4(4,3,1) ≤ (7,4,3) ✓7 4 37 4 5
4P0(7,4,3) ≤ (7,4,5) ✓7 4 57 5 5
5P2(6,0,0) ≤ (7,5,5) ✓7 5 510 5 7
A safe sequence <P1, P3, P4, P0, P2> still exists ⇒ the state after granting is safe ⇒ yes, the request (1,0,2) from P1 can be granted immediately.

Chapters 6 & 7 — Memory Management & Virtual Memory

Assignment 5 · Q1 – Q17 (numerical problems fully worked and verified)

Q1

What is memory management? Describe.

Memory management is the OS function that controls and coordinates the use of main memory: it keeps track of every memory location (free or allocated), allocates memory to processes when they need it and reclaims it when they finish, and translates logical addresses to physical addresses.

Main functions

  • Keeping track of which parts of memory are in use, by whom, and which are free.
  • Allocation & deallocation of memory to processes (contiguous or paged) as needed.
  • Address translation (MMU) — mapping logical/virtual addresses generated by the CPU onto physical addresses in RAM.
  • Protection & sharing — a process may not touch memory outside its space; controlled sharing is possible (base + limit registers).
  • Multiprogramming support — bringing more processes into memory to raise CPU utilisation: swapping, paging, segmentation, virtual memory.

Goal: maximise memory utilisation and multiprogramming degree while keeping translation fast and protecting processes from each other.

Q2

What are pages and frames? Describe.

Paging splits memory into equal-sized blocks so that physical memory can be allocated non-contiguously:

  • Frame (page frame): a fixed-size block of physical memory (RAM). Physical memory is divided into frames — the containers.
  • Page: a block of the same fixed size in logical (virtual) memory of a process — the contents that get loaded into frames.
  • Common sizes: 4 KB; always a power of 2 (256 B – 1 GB). Page size = frame size, so any page can go into any free frame.
  • The OS keeps a page table per process recording which frame holds each page — logical address = (page number p, offset d) → physical address = (frame number f, offset d), with d unchanged.
  • Consequences: no external fragmentation (all frames equal), but possible small internal fragmentation in a process's last page.
Q3

What is meant by logical address space and physical address space? Write any two differences between them.

Logical (virtual) address: the address generated by the CPU while a program runs — what the program "sees". The set of all logical addresses forms the logical address space (0 … 2n−1).

Physical address: the actual location in main memory (what the memory unit sees, loaded into the address register). The set of all physical addresses forms the physical address space, corresponding to the real RAM frames.

The MMU (memory management unit) hardware converts logical → physical at run time using the relocation/base register and page table.

BasisLogical Address SpacePhysical Address Space
Generated by / seen byGenerated by the CPU; visible to the user program.Located in RAM; visible only to the memory unit / OS.
Reality & accessVirtual — may exceed physical RAM; accessed via MMU translation.Real — directly addresses memory chips; user code can never reference it directly.
Q4

What is swapping? Illustrate with a suitable diagram.

Swapping is temporarily moving a process (or part of it) from main memory to a backing store (swap area on disk) and later bringing it back for continued execution. It lets the total memory committed to processes exceed physical RAM, increasing the degree of multiprogramming.

  • Swap out: an idle/blocked process is copied to the backing store to free RAM for others.
  • Swap in: when memory frees or the process becomes runnable, it is brought back (possibly into a different location — dynamic relocation needed).
  • Cost: swap time dominates — transfer of the whole process image on the disk bus; decided by the medium-term scheduler.
Main memory (RAM) Operating system Process P1 Process P2 free (P3 swapped out) Backing store (swap area on disk) P3 (swapped out) … other swap images swap out swap in A blocked/idle process is rolled out to disk; another is rolled in to use its memory.
Fig: Swapping — the medium-term scheduler swaps P3 out to the backing store and swaps another process in.
Q5

What are the memory allocation techniques? Differentiate between contiguous and non-contiguous memory allocation.

Allocation techniques

  • Fixed (static) partitioning — memory pre-divided into fixed regions (equal or unequal); one process per partition → internal fragmentation.
  • Dynamic partitioning — a partition exactly as big as the process is created on demand → external fragmentation, solved by compaction.
  • Placement strategies for a free hole: First-fit — first hole big enough (fastest); Best-fit — smallest sufficient hole (least leftover, but tiny useless fragments); Worst-fit — largest hole (leaves large usable leftovers).
    (Next-fit = first-fit restarting from the last allocated point.)
  • Non-contiguous schemes — paging (fixed-size pages/frames) and segmentation (variable-size logical segments).
BasisContiguous AllocationNon-Contiguous Allocation
PlacementProcess occupies one single block of consecutive addresses.Process is spread over many separate blocks anywhere in memory.
TechniquesFixed & dynamic partitioning (first/best/worst fit).Paging, segmentation, segmentation-with-paging.
Address translationSimple — base (relocation) + limit registers only.Needs page table / segment table lookup (TLB speeds it up).
FragmentationBoth types: internal (fixed) and external (dynamic) — may need compaction.No external fragmentation (paging); only small internal (last page) or per-segment overhead.
Flexibility / sharingRigid; no sharing, process must wait for one big hole.Flexible; pages can be shared (e.g., code), supports virtual memory.
OverheadVery low.Extra memory for tables and time for translation.
Q6

What is paging? Why is paging required? Describe with a suitable diagram.

Paging is a memory-management scheme that breaks the logical address space of a process into fixed-size pages and physical memory into same-size frames, and loads any page into any free frame — physical memory allocation becomes non-contiguous. A per-process page table maps page numbers to frame numbers.

Address: logical address = (p, d) — page number p indexes the page table to get frame f; offset d stays unchanged; physical address = f × page-size + d. Example: page size 4 KB ⇒ a 32-bit address has p = upper 20 bits, d = lower 12 bits.

Why paging is required

  • No external fragmentation — all holes are the same size, so any free frame is usable.
  • A process need not sit in one contiguous block ⇒ no compaction, higher memory utilisation, more multiprogramming.
  • Simple allocation — keep a list of free frames; grab any.
  • Foundation of virtual memory — pages can be brought in on demand (demand paging), shared (common code), and protected per page (read/write bits).
Logical memory (pages of process) Page 0 Page 1 Page 2 Page 3 CPU generates (p, d) Page table p0 → f5 p1 → f9 p2 → f1 p3 → f2 Physical memory (frames) Frame 0 — OS Frame 1 — Page 2 Frame 2 — Page 3 Frame 3 — P4 Frame 4 — free Frame 5 — Page 0 Frame 6 — P7 Frame 7 — free Pages are scattered across non-adjacent frames — frames 1, 2, 5 hold the process.
Fig: Paging — the page table maps each logical page to any free physical frame.
Q7

What is segmentation? Why is segmentation required? Describe with a suitable diagram.

Segmentation is a memory-management scheme that supports the user/programmer view of memory: a program is a collection of variable-size logical units — main program, functions, objects, stack, arrays, global variables — called segments. Each segment is allocated contiguously, but different segments need not be adjacent.

Address: logical address = (segment number s, offset d). The segment table stores per segment a base (start physical address) and limit (length): hardware checks d < limit (else trap — protection), then physical = base + d.

Why segmentation is required

  • Matches the programmer's logical view — code vs data vs stack treated separately, unlike paging's meaningless one-dimensional memory.
  • Protection per logical unit — e.g., mark the code segment execute-only, shared library segments read-only; limit check catches invalid access.
  • Sharing — a single segment (library, text editor) can be shared by many processes by pointing at the same base.
  • Grows naturally — a stack segment can grow independently of the data segment.
  • Drawback: variable sizes ⇒ external fragmentation (needs compaction / best-fit placement).
Logical address space segment 0 · main() seg 1 · stack seg 2 · sqrt() seg 3 · symbol table Segment table (base, limit) s0: 1400, 1000 s1: 6300, 400 s2: 4300, 680 s3: 3200, 400 Physical memory segment 0 (base 1400) segment 2 (base 4300) other process segment 3 (base 3200) segment 0 contd… segment 1 (base 6300) Each segment is contiguous internally; segments lie anywhere in memory. Access check: d < limit.
Fig: Segmentation — variable-size logical segments with (base, limit) pairs in the segment table.
Q8

Write any 5 differences between paging and segmentation.

#PagingSegmentation
1Memory is divided into fixed-size pages/frames (decided by hardware).Memory is divided into variable-size segments (decided by the programmer/compiler).
2Visible only to the OS/hardware — user sees one linear address space.Visible to the user — matches the logical structure of a program.
3Address = (page number, offset); only page number is translated, offset unchanged.Address = (segment number, offset); needs a base and limit (translation + bounds check).
4Page table holds only frame numbers (+ status bits).Segment table holds base and limit of every segment.
5Suffers internal fragmentation (last page), but no external fragmentation.Suffers external fragmentation (unequal holes); no internal fragmentation within a segment.

Extra points: paging is faster/simpler to allocate (any free frame); segmentation gives finer per-logical-unit protection & sharing; modern systems combine both (segmentation with paging).

Q9

What do you mean by internal and external fragmentation? How do they occur?

Fragmentation is wasted memory that cannot be used effectively. It occurs in two forms:

Internal fragmentation

  • What: unused space inside an allocated block/partition — the waste is internal to the allocated region.
  • How it occurs: when memory is handed out in fixed-size units. A process needing, say, 18 KB in 4 KB pages gets 5 pages = 20 KB, but the last page is only ¾ used — 2 KB inside it can never be used by anyone else.
  • Seen in: fixed partitioning, paging (last page of a process), filesystem blocks.

External fragmentation

  • What: free memory exists in scattered small holes between allocations — total free space is enough for a request, but no single contiguous hole is big enough.
  • How it occurs: processes of different sizes are repeatedly loaded and removed from variable-size (dynamic) partitions, chopping memory into non-contiguous pieces.
  • Seen in: dynamic partitioning, segmentation. Solved by compaction or by switching to paging.
Internal fragmentation P1: needs 18KB last 4KB page:2KB used ← 2KB wasted inside External fragmentation P1 6K P2 10K P3 14K P4 8K P5 38K free in total — but a 20K request cannot fit in any single hole
Fig: Internal = waste inside an allocated block; external = usable total space scattered in non-contiguous holes.
Q10

Write any 3 differences between internal fragmentation and external fragmentation.

#Internal FragmentationExternal Fragmentation
1Wasted space is inside the allocated partition/page of a process.Wasted space lies outside/between allocations, in free holes.
2Occurs when memory is allocated in fixed-size blocks (fixed partitions, paging).Occurs with variable-size allocations (dynamic partitions, segmentation) after repeated load/remove.
3The wasted memory belongs to a process and cannot be reclaimed (only by smaller page sizes).Total free memory may be enough for a request but is non-contiguous; recoverable by compaction or by paging.
Q11

What is virtual memory? Why is virtual memory required? Describe.

Virtual memory is a technique that allows the execution of processes that are not completely in main memory. The programmer sees a very large, uniform logical address space; the OS + hardware keep only the active parts of each process in RAM and the rest on disk, transparently moving data as needed (paging/segmentation on demand).

Why it is required

  • Run programs larger than physical RAM — user is freed from the memory-size limit.
  • Higher CPU utilisation / multiprogramming — more processes fit in RAM at once, so the CPU rarely idles.
  • Less I/O for load/swap — only the needed pages are loaded, so processes start faster.
  • Efficient process creation — copy-on-write (fork shares pages until written) and memory-mapped files become possible.
  • Programs need not worry about memory size — no manual overlays; the same program runs on machines with different RAM.
  • Enables page sharing and per-page protection between processes.

Implemented with demand paging + page replacement; governed by locality of reference, bounded below by thrashing if over-committed.

Q12

What is demand paging? Describe.

Demand paging is the implementation of virtual memory in which a page is brought into memory only when it is actually referenced (demanded) during execution — a "lazy swapper" (pager) loads pages, instead of swapping the whole process in at start.

  • Pages needed at startup are loaded; others are marked invalid in the page table ("not in memory").
  • Page fault: reference to an invalid page traps to the OS → the pager locates the page on disk → finds/replaces a free frame → reads the page in → updates the page table (valid) → restarts the faulting instruction; the process continues as if nothing happened.
  • Hardware support: page table with valid/invalid bit, backing store, and (optionally) a reference/dirty bit.
  • Effective access time = (1 − p) × memory-access + p × page-fault-time, where p = page-fault rate — performance depends critically on locality keeping p tiny.

Pure demand paging: start with zero pages and fault everything in. Advantages: less I/O, less memory used, faster response, more users.

Q13

What is page replacement? Why is the page replacement technique required?

Page replacement is the mechanism used when a page fault occurs and no free frame exists: the OS chooses a victim page currently in memory, writes it back to disk (if modified), and loads the requested page into the freed frame.

Why it is required

  • With demand paging, total pages needed by all processes exceed physical frames — someone must give up a frame when memory is full.
  • The choice of victim decides performance: replacing a page that will be used again soon causes more faults (and more disk I/O, which costs ~105× a memory access).
  • Good algorithms (LRU/Optimal approximations) minimise the fault rate by exploiting locality of reference, keeping the working set of each process resident and avoiding thrashing.

Overhead to minimise: two page transfers per replacement (out + in) — reduced with a modify (dirty) bit: clean victims need no write-back.

Allocation of frames (syllabus point): frames are divided among processes as fixed / equal, proportional to process size, or by priority. With global replacement a fault may evict a page belonging to any process (higher throughput, less predictable); with local replacement only the faulting process's own pages can be victims (predictable, protects others).
Q14

Describe briefly FIFO, Optimal, LRU and second-chance page replacement techniques.

  • FIFO: replace the page that has been in memory the longest (oldest arrival) — implemented with a simple queue. Easy, but ignores usage; suffers Belady's anomaly (more frames can cause more faults, e.g., string 1,2,3,4,1,2,5,1,2,3,4,5 gives 9 faults with 3 frames but 10 with 4).
  • Optimal (OPT/MIN): replace the page that will not be used for the longest time in the future. Provably the lowest possible fault rate, but needs future knowledge — used only as a benchmark; practical algorithms approximate it.
  • LRU (Least Recently Used): replace the page that has not been used for the longest time in the past — the past is a good predictor of the future (locality). Optimal in practice; needs hardware help: counters/time-stamps or a stack of references (expensive to implement exactly).
  • Second chance (clock): FIFO plus a reference bit. When a page is chosen as victim, if its reference bit = 1, clear the bit and give it a "second chance" (move to the tail); if 0, replace it. Pages used recently survive; approximates LRU with cheap queue bookkeeping.
  • LFU (Least Frequently Used): replace the page with the smallest reference count. Cheap counters, but a page that was heavily used in the past keeps a high count even when no longer needed (fix: shift/right-decay the counters periodically). It is the mirror image of MFU, which argues the least-used page was probably just loaded.
Q15

Memory partitions of 10K, 4K, 15K, 17K and 15K (in order). How would first-fit, best-fit and worst-fit place processes of 12K, 13K and 5K (in order)? Which algorithm makes the best use of memory?

Algorithm12K process13K process5K processLeftover free blocks
First-fit (first hole that fits, scanning from start)10K ✗, 4K ✗ → 15K ✓ (3K left)10K ✗, 4K ✗, 15K(full) ✗ → 17K ✓ (4K left)→ 10K ✓ (5K left)5K, 4K, 3K, 4K, 15K
Best-fit (smallest hole that fits)smallest of {15,17,15} → 15K ✓ (3K left)smallest of {17, 15} → 15K ✓ (2K left)smallest of {10, 17} → 10K ✓ (5K left)5K, 4K, 3K, 17K, 2K
Worst-fit (largest hole)largest = 17K ✓ (5K left)largest = 15K ✓ (2K left)largest = 15K ✓ (10K left)10K, 4K, 2K, 5K, 10K

All three algorithms succeed in placing all three processes (30K used of 61K total).

Best-fit makes the best use of memory. It produces the tightest packing (leftovers of only 3K, 2K and 5K inside the partitions it uses) and leaves one whole 17K block untouched — the largest contiguous free region of the three algorithms (first-fit leaves at most 15K, worst-fit only 10K), which keeps memory ready for future large requests.
Q16

Page reference string 7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1 — how many page faults occur for LRU, FIFO and Optimal with 3 and with 4 frames? Which algorithm performs better in each case?

With 3 frames

FIFO
3 frames
70120304230321201701
Frame 177722224440000000777
Frame 2·0000333222221111100
Frame 3··111100033333222221
Fault?FFFFHFFFFFFHHFFHHFFF

15 page faults, 5 hits → fault rate 75%

LRU
3 frames
70120304230321201701
Frame 177722224440001111111
Frame 2·0000000033333300000
Frame 3··111333222222222777
Fault?FFFFHFHFFFFHHFHFHFHH

12 page faults, 8 hits → fault rate 60%

Optimal
3 frames
70120304230321201701
Frame 177722222222222222777
Frame 2·0000004440000000000
Frame 3··111333333331111111
Fault?FFFFHFHFHHFHHFHHHFHH

9 page faults, 11 hits → fault rate 45%

With 4 frames

FIFO
4 frames
70120304230321201701
Frame 177777333333333222222
Frame 2·0000004444444444777
Frame 3··111111110000000000
Frame 4···22222222221111111
Fault?FFFFHFHFHHFHHFFHHFHH

10 page faults, 10 hits → fault rate 50%

LRU
4 frames
70120304230321201701
Frame 177777333333333333777
Frame 2·0000000000000000000
Frame 3··111114444441111111
Frame 4···22222222222222222
Fault?FFFFHFHFHHHHHFHHHFHH

8 page faults, 12 hits → fault rate 40%

Optimal
4 frames
70120304230321201701
Frame 177777333333331111111
Frame 2·0000000000000000000
Frame 3··111114444444444777
Frame 4···22222222222222222
Fault?FFFFHFHFHHHHHFHHHFHH

8 page faults, 12 hits → fault rate 40%

Summary & conclusion

Algorithm3 frames4 frames
FIFO15 faults10 faults
LRU12 faults8 faults
Optimal9 faults8 faults
  • 3 frames: Optimal performs best (9 < LRU 12 < FIFO 15).
  • 4 frames: LRU and Optimal tie at 8 faults, both better than FIFO (10).
  • Overall: Optimal is the theoretical best; LRU is the best practical algorithm; FIFO is the worst — it is the only one that can suffer Belady's anomaly.
Q17

Explain coalescing and compaction. How does paging hardware with TLB improve the performance during memory mapping?

Coalescing

The act of merging physically adjacent free blocks (holes) into one larger hole. When a block is freed, the allocator checks whether its left and/or right neighbours are free; if so, they are combined into a single bigger free block instead of remaining as tiny useless fragments. It reduces external fragmentation without moving any data (used in dynamic partitioning and malloc-style allocators).

Compaction

The act of shuffling all allocated processes to one end of memory so that all free space is collected into one large contiguous block. It requires dynamic relocation (addresses bound at execution time) and is expensive — large data movement and CPU time — but completely removes external fragmentation. Best when coalescing is not enough; impossible with static binding. (Coalescing = merge adjacent holes in place; compaction = physically move processes.)

Paging hardware with TLB

Every memory access needs a page-table lookup: without help, one logical access = two memory accesses (page table + data) — doubling effective time. The Translation Look-aside Buffer (TLB) is a small, fast associative cache of recent page→frame entries:

  1. CPU issues (p, d) → the page number is searched in the TLB in parallel.
  2. TLB hit: frame number is available immediately — the page-table walk is skipped; physical address formed in one memory access.
  3. TLB miss: the page table in RAM is consulted, the translation is loaded into the TLB (replacing an old entry — LRU/round-robin), then the access proceeds.

Effective access time = h·(TLB-time + memory) + (1−h)·(TLB-time + memory + page-table-access). With hit ratio h = 0.90–0.99 (thanks to locality), EAT ≈ 1.1–1.2 memory accesses instead of 2 — a huge gain. Some TLBs also cache the ASID (address-space identifier) to avoid flushing on context switch.

CPU TLB(p → f cache) Page table(in main memory) Physical memory page no. p HIT — f known instantly MISS → walk table load entry into TLB offset d passes through unchanged; physical = f × page-size + d
Fig: Paging hardware with TLB — a TLB hit yields the frame without a page-table walk.

Chapter 8 — File System Interface & Implementation

Assignment 6 · Q1 – Q8

Q1

What is a file? What are the attributes of a file?

A file is a named collection of related information recorded on secondary storage — the smallest unit of logical storage; anything can be put in one (program, document, image, data). Files are mapped by the OS onto physical devices and are managed in directories.

File attributes

  • Name — the symbolic name kept in the directory (human-readable).
  • Identifier (inode number) — unique internal tag that names the file within the file system.
  • Type — text, binary, executable, etc. (needed by systems that support different file types).
  • Location — pointer(s) to the device and to the disk blocks where the file's data resides.
  • Size — current size of the file (bytes/words/blocks); may also include a maximum allowed size.
  • Protection — access-control information: who (owner, group, others) may read / write / execute.
  • Time, date & user identification — creation, last modification and last use times; owner/user id — used for protection, security and monitoring.

All these attributes (except the name, which lives in the directory) are kept in the file control block / inode.

Q2

What are the different file access methods? Explain in brief.

  1. Sequential access — information is processed in order, record by record (read-next / write-next, with a reset-to-start option); a file pointer moves automatically. Simplest, matches tape/line-printer model; used by editors and compilers reading source files.
  2. Direct (relative / random) access — a file is a numbered sequence of blocks; the program may read/write block n directly (seek(n) then read) with no ordering. Ideal for databases and immediate access to large amounts of information.
  3. Indexed access — built on top of direct access: an index (like a card catalogue) holds pointers to blocks containing records keyed by an attribute. Search the small index first, then access the block directly; multi-level indexes handle very large files (e.g., ISAM).
  4. Memory-mapped access — the file is mapped into a process's virtual address space; ordinary memory instructions read/write it (modern convenience method).
Q3

What is Boot Control Block and File Control Block? Explain in brief.

Boot Control Block (per volume)

Contains everything needed to boot an operating system from that volume. If the volume holds a bootable OS, it holds the bootstrap loader's location — in UNIX it is the boot block; in NTFS it is the boot sector. At power-on, firmware loads the code from here, which then loads the full OS.

File Control Block — FCB (per file)

Contains all the metadata of a single file: permissions, ownership, file size, dates of creation/modification/access, and the locations of the file's data blocks on disk. The directory entry typically holds only name + FCB number. In UNIX it is the inode (index node); in NTFS it is stored inside the master file table (MFT).

Also on each volume: the volume control block (per file system: block count, block size, free-block count, free-block pointers) and the per-process open-file table (each entry points to the system-wide open-file table entry, which points to the FCB).
Q4

How are disk blocks allocated for files? Explain in brief.

  1. Contiguous allocation — each file occupies consecutive disk blocks; the directory stores (start block, length). + Excellent sequential & direct access, few seeks. − External fragmentation, hard to grow a file, must declare size in advance.
  2. Linked allocation — each block holds data + a pointer to the next block; directory stores first & last block. + No external fragmentation, file grows freely. − Direct access is slow (must chase pointers), pointers consume space, one lost pointer breaks the chain. Variant: FAT (File Allocation Table) — all next-pointers collected into one table at volume start, cached in memory.
  3. Indexed allocation — all of a file's block pointers are gathered in one index block; the directory points to the index block. + Direct access without external fragmentation. − Index block overhead; large files need linked/multilevel indexes (UNIX inode: 12 direct pointers + single, double and triple indirect blocks).
Q5

What is free-space management? Explain different techniques related to it.

Free-space management is how the file system keeps track of which disk blocks are free so they can be granted to new files and reclaimed on deletion.

  1. Bit vector (bitmap) — one bit per block: 1 = free (or vice-versa). Easy to find contiguous runs (count zero-bits); but for a 1 TB disk with 4 KB blocks the bitmap itself is ~32 MB and must be kept partly in memory. Optimisations: bit volumes, grouping free regions with start/count pairs.
  2. Linked list — a chain through all free blocks: each free block stores the number of the next free one. No space waste, but traversal is I/O-costly and finding contiguous runs is hard.
  3. Grouping — the first free block holds the addresses of n other free blocks (the last of which also holds more addresses) — addresses become reachable quickly.
  4. Counting — exploits contiguity: keep (first-free-block, count-of-contiguous-free-blocks) triples in a list; ideal after contiguous allocation.
  5. Space maps / FAT-as-free-list — modern file systems (ZFS) store per-metasmide free/run info; FAT doubles as allocation and free-space structure.
Q6

What is meant by directory structure? Why is it required?

A directory is a special file containing symbolic name → file metadata (FCB) mappings. The directory structure is the way directories and files are organised and related across the volume (single-level, two-level, tree, acyclic graph).

Why required:

  • Organisation & fast search — thousands of files must be found by name efficiently; grouping related files (per project/user/topic) makes lookup, listing and management easy.
  • Unique naming — lets different users use the same file name without conflict (two-level and beyond).
  • Grouping & sharing — related files can be shared, moved or protected as one unit (subdirectories, links, per-directory permissions).
  • Provides the basis of path names (absolute/relative) used by every command and open() call.
Q7

Explain: single-level, two-level, tree-structured and acyclic-graph directory.

Single-level directory directory cat bo list hex one master directory for ALL files name clashes, no grouping Two-level directory MFD UFD · user1 UFD · user2 test data test mail MFD → one UFD per user; both users may keep 'test'
Fig: Single-level (one flat directory) vs two-level (MFD + per-user UFDs) directory structures.
  1. Single-level directory — one directory holds all files of all users. Simple, but name conflicts between users and no grouping — searching gets harder as files grow.
  2. Two-level directory — a Master File Directory (MFD) points to one User File Directory (UFD) per user; each UFD lists only that user's files. Solves name clashes (same name in different UFDs) and speeds search; but still no grouping within a user's files, and sharing is awkward.
  3. Tree-structured directory — directories may contain subdirectories recursively, forming a tree with a root. Supports absolute and relative path names, a current working directory, and natural grouping; files may not be shared across branches. Deletion: files = free space; empty dirs removed; recursive removal for non-empty ones.
  4. Acyclic-graph directory — allows shared subdirectories/files while forbidding cycles: the same file/subdirectory appears in two places via a link. Sharing is cheap and natural; but deletion becomes tricky (dangling links) — solved with reference counts (UNIX: hard links + inode count) or by deleting only the link (symbolic links point by path).
Tree-structured root spell/ mail/ prog/ list all copy hex /spell/list — absolute path, one parent each Acyclic graph (shared file) root dict/ spell/ words (shared) words/ reachable from two directories via links
Fig: Tree-structured directory vs acyclic graph with a shared file.
Q8

What is meant by directory implementation? What are the differences between linear and hash-table directory implementations?

Directory implementation is the choice of data structure used to store the directory entries (name → FCB mappings) in memory and on disk — it directly decides how fast files can be located, created and deleted.

BasisLinear List (Linear / Simple table)Hash Table
StructureA simple list (array or linked list) of entries: file name + FCB pointer.A hash table: the file name is hashed to an index of a bucket holding the entry.
Search timeLinear — O(n): every create/delete/lookup may scan the whole list; slow for large directories.≈ O(1): direct bucket access; fast regardless of directory size.
Programming effortSimplest to implement; small directories perform fine.More complex: must choose a hash function, handle collisions (chaining) and keep table size sensible.
Ordering / listingEntries can be kept sorted for ordered listings (binary search possible but re-sorting costs).No ordering — hash destroys sequence; sorted listing needs an extra pass.
Used bySmall file systems, early UNIX directories.Modern systems / bigger directories (often hybrid: linear + hash cache).

A common compromise: a sorted linear list for correctness/ordering, with a hash table maintained as an index for fast lookup.

Chapter 9 — I/O Management

Assignment 7 · Q1 – Q6

Q1

What is I/O management? Why is I/O management required?

I/O management is the part of the operating system that controls and coordinates all input/output operations between the computer and its external devices (keyboard, mouse, monitor, disks, SSDs, network cards, printers, USB devices). It hides device-specific details behind a uniform interface: user program → system call → device driver → device controller → device.

Why is it required?

  • Device diversity — hundreds of very different devices need a common, portable interface for programs.
  • Preventing conflicts — without coordination, programs would clash while accessing the same devices.
  • Speed mismatch — devices are far slower than CPU/RAM; buffering, caching and spooling are needed so the CPU is not wasted waiting.
  • Efficiency & sharing — devices must be allocated fairly, shared among processes and kept busy (else devices stay idle and transfers become slow).
  • Error handling & protection — device faults must be detected, reported and isolated from user programs; user programs must not bypass the OS to touch hardware.
Q2

What is the role of the operating system in I/O management? List and describe.

  1. Device control via drivers — device-driver modules encapsulate device-specific code; the OS issues commands to device controllers (via registers) and interprets status.
  2. Device sharing & allocation — grants devices to processes, queues competing requests, and makes exclusive devices (printer) shareable via spooling.
  3. Buffering — holds data temporarily in memory between transfers to smooth speed differences and size mismatches (single/double/circular buffer).
  4. Caching — keeps copies of frequently used blocks (disk cache) so repeated accesses avoid device I/O.
  5. Scheduling I/O requests — orders the queue of pending requests for fairness and throughput (e.g., disk scheduling: SSTF, SCAN).
  6. Error handling — detects, retries and reports device errors to applications in a consistent way.
  7. Interrupt handling & polling — manages the two ways devices signal completion; services interrupt handlers quickly.
  8. Protection & abstraction — user processes cannot command devices directly (mode bit); the OS exposes only named files/sockets via system calls (device independence).
Q3

What are the components of I/O hardware? Illustrate with a diagram.

I/O hardware consists of the physical devices plus the pieces that connect them to the CPU:

  • Devices — the actual hardware: keyboard, monitor, printer, SSD, network card…
  • Device controllers (adapters) — electronic modules between device and system: each has registers (data-in, data-out, status, control) and possibly its own processor/memory; they translate serial device signals into the computer's bus protocol. (The software module that operates it is the device driver.)
  • I/O ports & buses — connection points and shared communication channels (PCIe, USB, SATA, SCSI) that carry address, data and control lines.
  • CPU + memory bus — executes drivers, processes interrupts; the DMA module also sits here for block transfers.
CPUruns drivers Main memorybuffers DMA controllerblock transfers System / memory bus (address · data · control lines) graphics controller USB controller disk (SATA/SCSI) keyboard/mouse port Each controller has device registers the driver reads/writes; DMA moves data straight to memory.
Fig: Components of I/O hardware — CPU, memory bus, device controllers, ports and the DMA module.
Q4

What are I/O devices? List and describe the categories of I/O devices.

I/O devices are the pieces of hardware used by humans or other systems to communicate with a computer — input (keyboard, mouse), output (monitor, printer) or both (modem, network card, touch screen).

Categories

  1. Human-readable devices — communicate with the user: keyboards, mouse, monitors, printers, touchscreens.
  2. Machine-readable devices — communicate with electronic equipment: disk drives, tape drives, sensors, controllers, actuators, robotics devices.
  3. Communication devices — communicate with remote devices: network interface cards (NICs), modems, routers, serial lines.

By data transfer behaviour:

  • Block devices — store information in fixed-size, individually addressable blocks (disk, SSD, USB drive); support seeking; typically use DMA.
  • Character (stream) devices — deliver/receive a byte stream with no block structure (keyboard, serial port, printer, network).
  • Network devices — have their own interface family: sockets with select/read/write, packet-based rather than block/character.
  • Clocks & timers — special devices the OS uses to measure time: the interval timer drives time-sharing quantum expiry, and sleep()/alarm() are implemented on them.
  • Blocking vs non-blocking interface — a blocking call (read() with no data) suspends the process until data arrives; a non-blocking call returns immediately (e.g., "no data yet"), useful for polling-style apps; asynchronous I/O notifies completion later via signal/callback.
  • Others: input vs output vs storage; synchronous vs asynchronous; speed classes from human-speed to network speed.
Q5

What do you mean by polling and interrupts in I/O? What are the differences between them?

Polling: the CPU periodically reads the device's status register in a loop (busy-waiting) until the controller reports "ready/done" — the simplest way to detect I/O completion.

Interrupts: the device controller signals the CPU (hardware interrupt) when it needs attention; the CPU finishes the current instruction, saves state, jumps to the interrupt handler (via the interrupt vector), processes the I/O result and resumes. The CPU does no waiting in between.

BasisPollingInterrupt-driven I/O
InitiationCPU actively checks device status again and again.Device informs the CPU when ready (event-driven).
CPU timeWasted in busy-wait loops even when nothing happens.Efficient — CPU runs other programs while I/O proceeds.
Response / latencyDevice must wait to be interrogated; latency depends on poll frequency.Fast, almost immediate service on the event; priorities supported.
ComplexityVery simple hardware/software; good for tiny or dedicated systems.Needs interrupt controller, vector table and handler logic.
OverheadNone per event, but huge when devices are slow/rare.Context-switch overhead per interrupt; costly for very high rates.
SuitabilitySmall embedded systems; fast devices; low load.General-purpose multitasking systems; slow/infrequent events.
Hybrid: an interrupt may be serviced with a short poll loop; and DMA finishes with a single interrupt per block instead of per byte.
Q6

What is DMA? Why is it required?

DMA (Direct Memory Access) is a technique in which a dedicated DMA controller transfers a whole block of data directly between a device and main memory, without the CPU copying every word. The CPU only sets up the transfer (device address, memory address, count, direction) and is interrupted once, when the entire block finishes.

How it works

  1. CPU programs the DMA controller (source, destination, byte count).
  2. DMA controller takes the system bus and streams data device ↔ memory, "stealing" bus cycles (cycle stealing).
  3. On completion it raises one interrupt; the CPU resumes, never having touched the data.

Why it is required

  • Without DMA the CPU would execute one interrupt/copy per byte or word — for a disk block of thousands of bytes this drowns the CPU in I/O work.
  • Frees the CPU to run other processes during the whole transfer → better throughput and multitasking.
  • Fast, bulk transfers for disks, SSDs, network and graphics controllers at device speed.
  • Lower interrupt overhead — one interrupt per block instead of thousands.

Bonus — Extras from your course material

Chapters 9–10 attachments: Disk scheduling (PDF) & RAID levels (slides)

+

Disk scheduling algorithms — FCFS, SSTF, SCAN, C-SCAN, LOOK, C-LOOK (Chapter 10)

Disk scheduling decides the order in which pending disk requests are serviced to minimise seek time (head movement) and maximise throughput.

AlgorithmHow it worksKey trait
FCFSService requests in arrival order.Fair and simple; wild head swings, worst seek distance.
SSTFAlways serve the request closest to the current head.Much less head movement; can starve far-away requests.
SCAN (elevator)Head moves in one direction servicing all requests, reaches the disk end, then reverses.Uniform wait; no starvation; end-tracks over-served.
C-SCANLike SCAN but on reaching the end it jumps straight back to track 0 and scans again.Most uniform wait times (circular service).
LOOK / C-LOOKSCAN / C-SCAN but the head only goes as far as the last request ("looks"), not to the physical end.Same fairness, slightly less travel than SCAN/C-SCAN.
Standard worked example: queue 98, 183, 37, 122, 14, 124, 65, 67; head at 53, 200 cylinders (0–199).
FCFS: order 98→183→37→122→14→124→65→67, total movement = 640 cylinders.
SSTF: 53→65→67→37→14→98→122→124→183 = 236 cylinders.
SCAN (toward 0): 53→37→14→0→65→67→98→122→124→183 = 53 + 183 = 236 cylinders.
+

RAID levels — redundancy & performance summary (RAID slides)

RAID (Redundant Array of Independent Disks) combines several physical disks into one logical unit to gain reliability (redundancy) and/or performance (parallel access).

Also in the syllabus — reliability & formatting: low-level formatting lays down sectors (with cylinder skew and interleaving so the head can keep up); boot block holds the bootstrap (Ch 8 Q3); bad blocks are detected by formatting and handled by the controller or OS using sector sparing (swap in a spare) or sector forwarding (remap, let the controller skip to the spare).
LevelTechniqueMin. disksCapacity useFault toleranceTypical use
RAID 0Striping, no redundancy2100%None (1 disk fails → all lost)Scratch / speed-only
RAID 1Mirroring250%Survives 1 diskOS drives, critical small disks
RAID 2Bit-level striping + Hamming ECC3+LowMultipleObsolete (memory ECC does it)
RAID 3Byte striping + dedicated parity disk3n−1Survives 1 diskLegacy streaming
RAID 4Block striping + dedicated parity disk3n−1Survives 1 diskRare (parity-disk bottleneck)
RAID 5Block striping + distributed parity3n−1Survives 1 diskGeneral-purpose servers
RAID 6Striping + double distributed parity (P, Q)4n−2Survives 2 disksLarge-capacity arrays
RAID 10 (1+0)Stripe of mirrors450%1 per mirror setDatabases, high perf + safety
+

Protection & Security — protection goals, domains, security problems, authentication, one-time passwords, threats, threat monitoring, encryption (Unit 8)

Protection — goals and domains

  • Protection is the mechanism for controlling which processes may access which resources (objects) and in what ways. Goal: enforce the access policy — ensure objects (files, memory, devices, CPU) are used only as intended, and follow the principle of least privilege (a process gets no more rights than it needs).
  • Protection domain — the set of (object, rights) pairs a process may use. Domains are modelled by the access matrix: rows = domains, columns = objects, cells = rights (read / write / execute). A domain switch lets a process change its rights (e.g., user mode → kernel mode).
  • Implementation of the matrix: per-object Access Control Lists (ACLs) or per-domain capability lists; UNIX realises domains with user/group IDs — the same file checked against rwx for owner/group/others.

Security problems

  • Program threats: Trojan horse (useful-looking program hiding malicious code), virus (attaches to files/programs, replicates on execution), worm (self-replicating over the network), logic/time bomb (fires on a condition/date), buffer overflow (overwriting memory to hijack execution).
  • System & network threats: denial of service (DoS) — exhaust a resource so legitimate users are blocked; port scanning, eavesdropping, man-in-the-middle, spoofing.

Authentication & one-time passwords

  • Authentication = verifying a user's identity via something you know (password/PIN), something you have (smart card, token), or something you are (biometrics — fingerprint, face, iris).
  • Passwords must be stored hashed and salted — never in plain text; long passphrases beat short complex ones.
  • One-time passwords (OTP): a password valid for a single login or a few seconds, so a stolen one is useless. Types: counter-based tokens, time-synchronised codes (TOTP apps like Google Authenticator), challenge–response grid cards. They defeat replay attacks.

Threats & threat monitoring

  • Threat monitoring: keep audit logs and continuously scan system activity for suspicious behaviour using intrusion detection systems (IDS): anomaly detection (flag deviation from the user's normal profile) and signature/misuse detection (match known attack patterns) — plus antivirus scanners and firewalls filtering traffic between networks.

Encryption

BasisSymmetric (secret-key) — AES, DESAsymmetric (public-key) — RSA, ECC
KeysOne shared secret key for both encryption and decryption.Key pair: public key encrypts, private key decrypts (and vice-versa for digital signatures).
Speed / useVery fast — bulk data (disk, TLS session data).~1000× slower — key exchange, signatures, small data.
Main problemHow to distribute the secret key securely.Slower, but solves distribution — public key can be published.

Real systems combine them: TLS/HTTPS uses asymmetric crypto to agree a session key, then symmetric crypto for the traffic; hash functions (SHA-256) add integrity checks/digital signatures. Ciphertext should look random — security rests on the key, never on the secrecy of the algorithm (Kerckhoffs's principle).