Theme
Operating Systems: Complete MCQ Revision Notes β
Legend: β = asked very often Β· β οΈ = trap Β· All numerical examples were checked by running code.
Contents
- OS basics (types, kernels, dual mode, system calls, interrupts, booting)
- Processes (states, PCB, schedulers, fork/exec, zombie/orphan, IPC)
- Threads
- CPU scheduling (formulas + worked examples)
- Process synchronization
- Deadlocks (Banker's + resource formula)
- Memory management (paging, TLB, segmentation)
- Virtual memory (page faults, replacement, thrashing)
- File systems
- I/O and disk scheduling
- Protection and security
- Virtualization and Linux facts
- Rapid-fire trap list
1. OS Basics β
- OS = intermediary between user and hardware; resource allocator + control program. The kernel is the part that is always running.
- Goals: convenience (user view) and efficient use of hardware (system view).
- Functions: process, memory, storage/file and I/O management; protection and security; networking; user interface (CLI, GUI, batch).
1.1 Types of OS ββ β
| Type | Key idea | Note |
|---|---|---|
| Batch | Similar jobs grouped and run without interaction | Long turnaround |
| Multiprogramming | Several jobs in memory; CPU switches when one waits for I/O | Goal: maximize CPU utilization |
| Time-sharing / multitasking | Rapid switching (time slices) between interactive users/processes | Goal: minimize response time; needs CPU scheduling + virtual memory |
| Multiprocessing | β₯ 2 CPUs sharing memory and bus | SMP (all CPUs peers) vs AMP (masterβslave); more throughput, economy of scale, reliability (graceful degradation) |
| Distributed | Loosely coupled networked machines | Resource sharing, reliability |
| Real-time | Strict timing constraints | Hard RT (deadline must be met: airbag, pacemaker) vs soft RT (best effort: streaming, VoIP). Examples: VxWorks, QNX, FreeRTOS, RTLinux |
| Embedded / mobile / network OS | Android (Linux kernel), iOS (XNU) |
Degree of multiprogramming = number of processes in memory.
1.2 Kernel structures β β
| Structure | Idea | Examples |
|---|---|---|
| Simple (unstructured) | Little separation | MS-DOS |
| Monolithic | All services in kernel space, one address space; fast, less isolation | Traditional UNIX, Linux (with loadable modules) |
| Layered | Layer i uses only layer iβ1 | THE (Dijkstra) |
| Microkernel | Minimal kernel (IPC, basic scheduling, memory); other services in user space via message passing. More reliable/secure, slower (IPC overhead) | Mach, QNX, MINIX 3, L4 |
| Modular | Core + loadable kernel modules | Linux, Solaris |
| Hybrid | Mix of the above | Windows NT, macOS/iOS (XNU = Mach + BSD) |
| Exokernel | Securely multiplexes raw hardware; apps build abstractions | MIT research |
1.3 Dual-mode operation ββ β
- Mode bit: 0 = kernel (supervisor/privileged/system/monitor) mode, 1 = user mode (Galvin).
- Privileged instructions run only in kernel mode; trying one in user mode traps to the OS.
- Privileged: set the timer, clear memory, disable/turn off interrupts, modify the device-status table, direct I/O access, load base/limit registers, halt, set the mode bit to user.
- Not privileged: read the clock, issue a trap / system call. (Switching from user to kernel mode happens through a trap, which user code may issue.)
- The timer stops a user program from hogging the CPU (infinite loop).
- x86 protection rings: ring 0 = kernel, ring 3 = user.
1.4 System calls ββ β
- The interface between a running program and the OS, entered through a trap (software interrupt). Usually used via an API (POSIX, Windows API, Java API) and libraries (libc's printf() calls write()).
- Parameter passing: registers; a block/table in memory whose address is in a register (Linux, Solaris); the stack.
| Category | UNIX examples |
|---|---|
| Process control | fork, exec, exit, wait, kill |
| File management | open, read, write, close, lseek |
| Device management | ioctl, read, write |
| Information maintenance | getpid, alarm, sleep, time |
| Communication | pipe, shmget, mmap, socket |
| Protection | chmod, umask, chown |
1.5 Interrupts and I/O methods β
- Hardware interrupt (device signals the CPU) vs software interrupt / trap (exception such as divide-by-zero or invalid memory access, or a system call). The interrupt vector table holds ISR addresses. Maskable vs non-maskable (NMI, for unrecoverable errors).
- I/O methods β: programmed I/O (polling, busy-wait) β interrupt-driven I/O β DMA (device moves a whole block to/from memory directly; the CPU is interrupted once per block; cycle stealing).
1.6 Booting β β
Power on β firmware (BIOS/UEFI in ROM/EEPROM/flash) runs POST β bootstrap loader finds the boot block (MBR = first 512-byte sector on legacy systems, or the EFI system partition) β boot loader (GRUB, Windows Boot Manager) β loads the kernel β kernel initializes β starts init/systemd (PID 1) β services and login.
- MBR: 4 primary partitions, 2 TB disk limit. GPT (with UEFI): up to 128 partitions in Windows, huge disks.
- The bootstrap program lives in ROM/firmware because RAM is volatile.
1.7 Misc basics β
- The shell (command interpreter) is a user program, not part of the kernel.
- UNIX: Bell Labs, 1969 (Ken Thompson, Dennis Ritchie; rewritten in C). Linux: Linus Torvalds, 1991 (the kernel).
- Spooling (Simultaneous Peripheral Operations On-Line): disk used as a buffer for slow devices such as printers (queue of jobs). Buffering: memory area holding data in transit (single, double, circular). Caching: keeping a copy for faster access.
- Memory hierarchy: registers β cache (L1/L2/L3) β main memory β SSD β HDD β optical β tape. Locality of reference: temporal (same item again soon) and spatial (nearby items). Cache write-through vs write-back; cache coherence on multiprocessors.
2. Processes β
2.1 Process basics ββ β
- Process = program in execution (active). Program = passive file on disk. One program can become many processes.
- Memory layout (low β high addresses): Text (code) | Data (initialized globals/statics) | BSS (uninitialized globals) | Heap (grows up) | β¦ | Stack (function frames, locals, return addresses; grows down).
- PCB (process control block; task_struct in Linux): PID, process state, program counter, CPU registers, CPU-scheduling info (priority, queue pointers), memory-management info (base/limit, page/segment tables), accounting info (CPU time used, limits), I/O status (open files, devices).
2.2 Process states βββ β
- New β (admitted) β Ready β (dispatch) β Running β (exit) β Terminated
- Running β Ready (interrupt, quantum expiry, preemption)
- Running β Waiting/Blocked (I/O request or event wait) β Ready (I/O or event done)
- β οΈ Not possible: Waiting β Running (must go via Ready), Ready β Waiting, New β Running.
- One Running process per CPU at a time; many can be Ready or Waiting.
- 7-state model adds Ready-Suspended and Blocked-Suspended (swapped out by the medium-term scheduler).
2.3 Schedulers βββ β
| Scheduler | Moves processes | Runs | Controls |
|---|---|---|---|
| Long-term (job) | Job pool on disk β ready queue in memory | Infrequently (seconds/minutes) | Degree of multiprogramming; good mix of I/O-bound and CPU-bound jobs |
| Short-term (CPU) | Ready queue β CPU | Very often (milliseconds) | Must be very fast |
| Medium-term | Swaps out/in (suspend/resume) | Occasionally | Reduces the degree of multiprogramming |
- Time-sharing systems (UNIX, Windows) often have no long-term scheduler.
- Dispatcher: gives the CPU to the chosen process: context switch, switch to user mode, jump to the right location. Dispatch latency = time to stop one process and start another.
- Context switch: save state into the old PCB, load the new PCB. Pure overhead; its cost depends on hardware (e.g., multiple register sets).
- Queues: job queue, ready queue (linked list of PCBs), device (I/O) queues.
- I/O-bound processes have many short CPU bursts; CPU-bound processes have few long ones.
2.4 Creation, termination, fork puzzles βββ β
- fork() creates a child with a copy of the parent's address space (copy-on-write in modern systems). Returns 0 in the child, the child's PID (> 0) in the parent, β1 on failure.
- exec() family replaces the process image with a new program; it does not return on success.
- wait()/waitpid(): parent waits for a child to finish and collects its exit status. exit() terminates.
- n consecutive fork() calls β 2^n processes in total (2^n β 1 new children); a print after them runs 2^n times.
- Short-circuit puzzles (checked by running them):
if (fork() && fork()) fork();β 4 processesif (fork() || fork()) fork();β 5 processesfork() && fork() || fork();β 5 processesfor (i = 0; i < n; i++) fork();β 2^n processes
- β οΈ printf buffering:
printf("A"); fork(); printf("B\n");prints "AB" twice, because the unflushed "A" is copied into the child. Withprintf("A\n")on a terminal (line-buffered) A prints once and B twice. If output is redirected to a file or pipe (fully buffered), even "A\n" prints twice. - Zombie: child has terminated but the parent hasn't called wait(), so its process-table entry (exit status) remains. Orphan: parent ended first; the child is adopted by init/systemd (PID 1), which reaps it. Some OSes do cascading termination (children killed with the parent).
- Daemon: background service process (sshd, crond). Linux: PID 0 = idle/swapper, PID 1 = init/systemd.
2.5 Inter-process communication ββ β
| Shared memory | Message passing |
|---|---|
| A memory region shared by processes; fastest (no kernel involvement after setup) | send()/receive() through the kernel; slower (system calls) |
| Processes must synchronize themselves | Easier; good for small data and distributed systems |
- Message passing choices: direct (name the process) vs indirect (mailboxes/ports); blocking (synchronous) vs non-blocking (asynchronous) send/receive (both blocking = rendezvous); buffering: zero capacity (sender waits), bounded, unbounded.
- Ordinary (anonymous) pipes: unidirectional; need a parentβchild relationship; exist only while the processes run (
pipe(fd): fd[0] = read end, fd[1] = write end). Named pipes (FIFOs): live in the file system, usable by unrelated processes, bidirectional (half-duplex on UNIX). - Others: message queues, signals, sockets (IP + port), RPC, shared memory (shmget/shmat, mmap).
- β οΈ Galvin's bounded buffer with in/out indices (no counter) holds at most BUFFER_SIZE β 1 items.
3. Threads ββ β
- Thread = basic unit of CPU use ("lightweight process"). Own: thread ID, program counter, register set, stack. Shared with the other threads of the process: code, data (globals), heap, open files, signals.
- Benefits: responsiveness, resource sharing, economy (cheaper to create/switch than processes), scalability on multicore.
- Concurrency (several tasks make progress, possibly interleaved on one core) vs parallelism (tasks run at the same time on several cores).
- Amdahl's law: speedup β€ 1 / (S + (1 β S)/N), S = serial fraction, N = cores. As N β β, speedup β 1/S. Example: S = 0.25 β N = 2: 1.6Γ, N = 4: 2.29Γ, maximum 4Γ.
| User-level threads (ULT) | Kernel-level threads (KLT) |
|---|---|
| Managed by a user library; kernel unaware | Managed by the kernel |
| Fast to create and switch (no mode switch) | Slower (system calls) |
| One blocking system call blocks the whole process (many-to-one) | Other threads keep running |
| No true parallelism on multiple CPUs (many-to-one) | True parallelism |
- Models: many-to-one (green threads; one blocking call blocks all), one-to-one (Linux, Windows; more concurrency, limit on thread count), many-to-many (many ULTs multiplexed onto β€ KLTs), two-level (many-to-many plus optional 1:1 binding). LWPs and scheduler activations sit between ULTs and KLTs.
- Libraries: POSIX Pthreads (pthread_create, pthread_join), Windows threads, Java threads (extend Thread / implement Runnable). Thread pools, fork-join, OpenMP.
- Thread cancellation: asynchronous (immediate) vs deferred (target checks periodically; safer).
- Hyper-threading / SMT: several hardware threads per core.
| Process | Thread |
|---|---|
| Heavyweight; own address space | Lightweight; shares the address space |
| Costly context switch | Cheaper switch |
| Needs IPC to communicate | Communicates through shared memory directly |
| A crash is isolated | One thread crashing can kill the whole process |
4. CPU Scheduling βββ β
- CPUβI/O burst cycle. Scheduling decisions happen when a process (1) goes running β waiting, (2) running β ready, (3) waiting β ready, (4) terminates. Only (1) and (4) β non-preemptive (cooperative); also (2) and (3) β preemptive.
- Criteria: maximize CPU utilization and throughput; minimize turnaround, waiting and response time.
4.1 Formulas βββ β
- Turnaround time (TAT) = Completion time (CT) β Arrival time (AT)
- Waiting time (WT) = TAT β Burst time (BT) (when there is no I/O)
- Response time = time of first CPU allocation β AT
- Throughput = processes completed per unit time; CPU utilization = busy time / total time.
- Little's law: n = Ξ» Γ W (average queue length = arrival rate Γ average wait).
- Context-switch overhead: with quantum q and switch time s, CPU efficiency = q / (q + s).
4.2 Algorithms βββ β
| Algorithm | Preemptive? | Starvation? | Key facts |
|---|---|---|---|
| FCFS | No | No | Simple; convoy effect (short jobs stuck behind a long one) |
| SJF | No (by default) | Yes | Optimal (minimum average WT) for a given set of processes; needs burst prediction |
| SRTF (preemptive SJF) | Yes | Yes | Optimal average WT when arrivals differ |
| Priority | Either | Yes (indefinite blocking) | Fix: aging. SJF = priority with priority = 1/(predicted burst) |
| Round Robin | Yes (quantum q) | No | For time-sharing; each process waits β€ (n β 1)Β·q for its next turn; q β β β FCFS; q too small β context-switch overhead; rule of thumb: ~80% of bursts < q |
| Multilevel queue | Yes (between queues) | Yes (fixed priority) | Processes permanently assigned to a queue (foreground RR, background FCFS); fixed priority or time-slicing between queues |
| Multilevel feedback queue | Yes | Avoidable by aging (moving up) | Processes move between queues; most general and most complex; favors short and I/O-bound jobs |
| HRRN | No | No | Response ratio = (W + S) / S (W = time waited, S = burst); favors short jobs but ages long ones |
| LJF / LRTF | No / Yes | Yes | Appear only in numericals |
| Linux CFS | Red-black tree keyed by vruntime (kernel 2.6.23+); replaced by EEVDF in kernel 6.6 |
- Burst prediction by exponential averaging: Ο(n+1) = Ξ±Β·t(n) + (1 β Ξ±)Β·Ο(n), 0 β€ Ξ± β€ 1 (Ξ± = 0: ignore the last burst; Ξ± = 1: only the last burst counts; Ξ± = Β½ is common).
- Larger q β fewer context switches; average TAT does not necessarily improve as q grows.
- SJF is a special case of priority scheduling; RR is preemptive FCFS.
- Real-time: Rate-Monotonic (static: shorter period = higher priority; guaranteed if U = Ξ£ Cα΅’/Tα΅’ β€ n(2^(1/n) β 1): n = 1 β 100%, 2 β 82.8%, 3 β 78%, β β 69.3%). EDF (dynamic: earliest deadline first; schedulable iff U β€ 1).
- Multiprocessor: asymmetric vs symmetric (SMP); processor affinity (soft/hard); load balancing (push/pull migration).
- Evaluating algorithms: deterministic modeling, queueing models (Little's law), simulation, implementation.
4.3 Worked examples (all checked) βββ β
- FCFS convoy: P1 = 24, P2 = 3, P3 = 3, all at t = 0. Order P1, P2, P3 β avg WT = (0 + 24 + 27)/3 = 17. Order P2, P3, P1 β (6 + 0 + 3)/3 = 3.
- SJF: P1 = 6, P2 = 8, P3 = 7, P4 = 3 (all at 0) β run P4, P1, P3, P2 β WT 3, 16, 9, 0 β avg 7 (FCFS would give 10.25).
- SRTF: P1 (AT 0, BT 8), P2 (1, 4), P3 (2, 9), P4 (3, 5) β Gantt P1 0β1 | P2 1β5 | P4 5β10 | P1 10β17 | P3 17β26 β avg WT = (9 + 0 + 15 + 2)/4 = 6.5 (non-preemptive SJF gives 7.75).
- RR, q = 4: P1 = 24, P2 = 3, P3 = 3 (all at 0) β P1 0β4 | P2 4β7 | P3 7β10 | P1 10β30 β avg WT = (6 + 4 + 7)/3 = 5.67.
- Priority (non-preemptive, smaller number = higher priority): P1 (BT 10, pri 3), P2 (1, 1), P3 (2, 4), P4 (1, 5), P5 (5, 2) β order P2, P5, P1, P3, P4 β avg WT = 8.2.
Tips: always draw the Gantt chart. For RR, check the tie rule; the usual convention is that a newly arrived process joins the ready queue before the process whose quantum just expired. CPU idle gaps count in completion time, not as waiting time for processes that hadn't arrived yet.
5. Process Synchronization βββ β
- Race condition: the result depends on the order of access to shared data. Critical section (CS): code that touches shared resources. Structure: entry section β CS β exit section β remainder section.
- Requirements for a CS solution βββ:
- Mutual exclusion: at most one process in the CS.
- Progress: if the CS is free, only processes not in their remainder section take part in choosing who enters next, and the choice can't be postponed forever.
- Bounded waiting: there is a limit on how many times others can enter after a process has requested entry (no starvation).
- No assumptions about relative speeds or the number of CPUs.
5.1 Software solutions (two processes) ββ β
| Solution | Mutual exclusion | Progress | Bounded waiting |
|---|---|---|---|
Strict alternation (turn only) | β | β (a process must wait for its turn even if the other doesn't want the CS) | β |
Flags only (flag[i] = true; while (flag[j]);) | β | β (both set flags β deadlock) | β |
| Peterson (flag[] + turn) | β | β | β |
| Dekker | β | β | β (first correct software solution) |
| Bakery (Lamport), n processes | β | β | β |
c
// Peterson, process i (j = the other process)
flag[i] = true; turn = j;
while (flag[j] && turn == j); // busy wait
/* critical section */
flag[i] = false;β οΈ Peterson can fail on modern CPUs (instruction reordering) without memory barriers. All of these solutions busy-wait.
5.2 Hardware support β
- Disabling interrupts: works only on a uniprocessor; unsafe for user code; inefficient on multiprocessors.
- Atomic test_and_set() and compare_and_swap(). β οΈ A simple TSL/CAS lock gives mutual exclusion and progress but not bounded waiting (fixed by the waiting[] array algorithm).
- Memory barriers (fences); atomic variables.
- Mutex / spinlock: acquire()/release() must be atomic. A spinlock busy-waits: no context switch, so it suits short critical sections on multiprocessors and wastes CPU on a single core.
5.3 Semaphores (Dijkstra) βββ β
- Integer S changed only by atomic wait() = P() = down() and signal() = V() = up().
c
wait(S) { while (S <= 0); S--; } // busy-waiting definition
signal(S) { S++; }- Blocking implementation: wait: S--; if S < 0, block on S's queue. signal: S++; if S β€ 0, wake one process. A negative value βk means k processes are blocked.
- Counting semaphore (any value; manages n instances) vs binary semaphore (0/1; similar to a mutex).
- Final value = initial β (number of P) + (number of V). Examples: S = 10, 6 P and 4 V β 8. S = 7, 20 P and 15 V β 2.
- Mutex vs binary semaphore: a mutex has ownership (only the locker unlocks it); a semaphore is a signaling tool (anyone may signal).
- Misuse: signal before wait (breaks mutual exclusion), wait twice (deadlock), leaving one out.
- Ordering: to run S2 only after S1, use synch = 0. P1: S1; signal(synch). P2: wait(synch); S2.
- Priority inversion β: high-priority H waits for a lock held by low-priority L, while medium-priority M preempts L, so H effectively waits for M. Fixes: priority inheritance (L temporarily gets H's priority) or priority ceiling. (Mars Pathfinder, 1997.)
5.4 Monitors β β
- High-level abstract data type: shared data + procedures; only one process can be active inside the monitor at a time (mutual exclusion is automatic).
- Condition variables: x.wait() suspends the caller; x.signal() resumes exactly one waiting process. β οΈ If no process is waiting, signal() has no effect (a semaphore's signal always increments).
- Signal-and-wait (Hoare) vs signal-and-continue (Mesa, Java). Java: synchronized, wait(), notify(), notifyAll().
5.5 Classic problems βββ β
Bounded buffer (producerβconsumer): mutex = 1, empty = n, full = 0.
c
// Producer // Consumer
wait(empty); wait(full);
wait(mutex); wait(mutex);
/* add item */ /* remove item */
signal(mutex); signal(mutex);
signal(full); signal(empty);β οΈ Swapping wait(empty) and wait(mutex) in the producer can deadlock (it holds mutex while waiting for an empty slot).
Readersβwriters: rw_mutex = 1, mutex = 1, read_count = 0. The first reader locks rw_mutex; the last reader unlocks it. First variant (readers' preference) β writers may starve. Second variant (writers' preference) β readers may starve.
Dining philosophers (5 philosophers, 5 chopsticks): each picks up the left then the right chopstick using semaphores β deadlock possible (everyone holds a left chopstick). Remedies: allow at most 4 at the table; pick up both only if both are free (inside a CS or monitor); asymmetric order (odd: left first, even: right first). The monitor solution is deadlock-free but starvation is still possible.
Also: sleeping barber, cigarette smokers.
- Deadlock (all blocked forever) vs livelock (processes keep changing state but make no progress) vs starvation (one process waits indefinitely while others proceed).
6. Deadlocks βββ β
- Deadlock: every process in a set waits for an event (a resource release) that only another process in the set can cause.
- Four necessary conditions (Coffman), all at the same time βββ: (1) Mutual exclusion (2) Hold and wait (3) No preemption (4) Circular wait. (Circular wait implies hold-and-wait, so the four aren't fully independent.)
- Resource allocation graph (RAG): request edge Pi β Rj, assignment edge Rj β Pi.
- No cycle β no deadlock.
- Cycle + one instance per resource type β deadlock.
- Cycle + multiple instances β deadlock possible (a cycle is necessary, not sufficient) β οΈ.
- Wait-for graph (resource nodes collapsed) for single-instance resources: cycle β deadlock.
6.1 Handling methods β
- Prevention: make sure at least one condition can never hold.
- Mutual exclusion: can't be denied for inherently non-sharable resources (printer, mutex); read-only files are sharable; spooling helps printers.
- Hold and wait: request everything at the start, or request only when holding nothing β low utilization, starvation.
- No preemption: take resources from a waiting process (fine for CPU registers and memory, not for printers or mutexes).
- Circular wait: number the resource types and request only in increasing order β (the most practical).
- Avoidance: use advance knowledge (maximum claims) to stay in safe states.
- Safe state: some safe sequence <P1 β¦ Pn> exists in which each Pi's remaining need β€ available + resources held by all earlier Pj.
- Safe β no deadlock. Unsafe β deadlock possible, not certain β οΈ. Deadlocked states β unsafe states.
- Single instance per type: RAG with claim edges (dashed); grant a request only if no cycle forms.
- Multiple instances: Banker's algorithm (Dijkstra). Data: Available[m], Max[n][m], Allocation[n][m], Need = Max β Allocation. The safety algorithm is O(mΒ·nΒ²). Resource request: if Request β€ Need and Request β€ Available, pretend to allocate and run the safety check; grant only if the state is safe.
- Detection and recovery: let deadlocks happen, detect them (wait-for graph, or a Banker-like algorithm using a Request matrix, O(mΒ·nΒ²)), then recover: kill all deadlocked processes, or one at a time until the cycle breaks; or preempt resources (choose a victim, roll back, count rollbacks in the cost to avoid starvation).
- Ignore it (Ostrich algorithm): what most OSes do (UNIX, Linux, Windows).
6.2 Banker's worked example (Galvin, checked) ββ β
Totals A = 10, B = 5, C = 7. Available = (3, 3, 2).
| Allocation | Max | Need | |
|---|---|---|---|
| P0 | 0 1 0 | 7 5 3 | 7 4 3 |
| P1 | 2 0 0 | 3 2 2 | 1 2 2 |
| P2 | 3 0 2 | 9 0 2 | 6 0 0 |
| P3 | 2 1 1 | 2 2 2 | 0 1 1 |
| P4 | 0 0 2 | 4 3 3 | 4 3 1 |
- Safe sequence: <P1, P3, P4, P2, P0> (others exist too).
- P1 requests (1, 0, 2) β granted (state stays safe; e.g., <P1, P3, P4, P0, P2>).
- Then P4 requests (3, 3, 0) β must wait (not available). P0 requests (0, 2, 0) β available, but the new state would be unsafe β denied.
6.3 Resource-count formula βββ β
- n processes, each needs at most k instances: deadlock is impossible iff R β₯ n(k β 1) + 1. (Worst case: every process holds k β 1; one extra unit lets someone finish.)
- Different maximum needs kα΅’: R β₯ Ξ£(kα΅’ β 1) + 1.
- Maximum processes for R units: n β€ (R β 1)/(k β 1).
- Examples: 3 processes Γ 2 units β 4. 4 processes Γ 3 units β 9. Needs 3, 4, 5 β 2 + 3 + 4 + 1 = 10. 6 tape drives, 2 per process β at most 5 processes.
7. Memory Management βββ β
7.1 Address binding and loading β
- Binding at compile time (absolute code; must know where it loads), load time (relocatable code), execution time (needs MMU hardware; the process can move while running; used by most OSes).
- Logical (virtual) address = generated by the CPU. Physical address = seen by the memory unit. They are the same under compile/load-time binding and differ under execution-time binding.
- MMU: adds the relocation (base) register to every logical address; the limit register gives protection (logical address must be < limit, else trap).
- Dynamic loading: a routine is loaded only when called (no special OS support needed). Dynamic linking: linking postponed to run time (shared libraries, DLLs, .so files, via a stub); needs OS support. Static linking copies libraries into the binary.
- Overlays: keep only the needed code/data in memory (old, programmer-managed).
- Swapping: move a process to the backing store and back (roll out / roll in). Slow because of transfer time.
7.2 Contiguous allocation and fragmentation βββ β
- Fixed partitions β internal fragmentation (unused space inside an allocated partition).
- Variable partitions β external fragmentation (enough total free memory, but not contiguous).
- Placement: first fit (first hole big enough; fastest), best fit (smallest adequate hole; searches the whole list unless sorted; leaves tiny holes), worst fit (largest hole), next fit. Simulations: first fit and best fit beat worst fit in time and utilization; first fit is generally faster.
- 50-percent rule: with first fit, N allocated blocks lose about 0.5N blocks to fragmentation, i.e., one-third of memory may be unusable.
- Fixes for external fragmentation: compaction (only possible with execution-time binding; expensive), paging, segmentation.
Example (checked) β: holes 100, 500, 200, 300, 600 KB (in order); processes 212, 417, 112, 426 KB (in order).
| Strategy | 212 | 417 | 112 | 426 |
|---|---|---|---|---|
| First fit | 500 hole (leaves 288) | 600 (leaves 183) | 288 hole (leaves 176) | must wait |
| Best fit | 300 | 500 | 200 | 600 β (all placed) |
| Worst fit | 600 (leaves 388) | 500 (leaves 83) | 388 hole (leaves 276) | must wait |
7.3 Paging βββ β
- Physical memory is divided into frames, logical memory into pages of the same size (a power of 2, typically 4 KB). No external fragmentation; internal fragmentation in the last page (half a page per process on average).
- Logical address = page number p | offset d. Logical space 2^m, page size 2^n β p has m β n bits, d has n bits. Frames = physical memory / page size. Physical address = frame number | d.
- Page table: one entry per page, per process. A PTE holds the frame number plus valid/invalid, protection (R/W/X), dirty (modified) and reference (accessed) bits. PTBR points to the page table; PTLR holds its length.
- Page table size = number of pages Γ PTE size. Example: 32-bit logical address, 4 KB pages, 4-byte PTEs β 2^20 entries Γ 4 B = 4 MB per process.
- Without a TLB every memory reference needs 2 memory accesses (page table + data).
- TLB (translation look-aside buffer): small, fast associative cache of PTEs (64β1,024 entries), hit ratio h.
- EAT = hΒ·(t_TLB + t_mem) + (1 β h)Β·(t_TLB + 2Β·t_mem) for a single-level table. With k-level paging a miss costs k + 1 memory accesses.
- Example: h = 0.8, TLB = 20 ns, memory = 100 ns β 0.8 Γ 120 + 0.2 Γ 220 = 140 ns. (Newer Galvin edition ignores TLB time: h = 0.8, memory = 10 ns β 12 ns.)
- ASIDs in TLB entries avoid flushing the TLB on every context switch. TLB reach = number of entries Γ page size.
- Shared pages: reentrant (pure, non-self-modifying) code can be shared (one copy of libc for many processes).
- Page-table structures for large address spaces:
- Hierarchical (multilevel): two-level for 32-bit (10 | 10 | 12 bits); x86-64 uses 4-level paging for 48-bit virtual addresses (9|9|9|9|12), 5-level for 57-bit.
- Hashed page tables (> 32-bit; chained entries of virtual page, frame, next); clustered page tables.
- Inverted page table: one entry per physical frame (process ID + page number) β. One table for the whole system, less memory, slower lookup (search/hash), hard to share memory. (PowerPC, IA-64, UltraSPARC.)
- Page-size trade-off: smaller pages β less internal fragmentation, better locality, but bigger page tables and more TLB pressure. Larger pages β smaller tables, fewer faults, more efficient I/O and better TLB reach, but more internal fragmentation. Optimal page size β β(2Β·sΒ·e) (s = average process size, e = PTE size). Huge pages: 2 MB / 1 GB.
- Galvin example: page size 2,048 B, process of 72,766 B β 35 pages + 1,086 B β 36 frames, internal fragmentation = 2,048 β 1,086 = 962 B.
7.4 Segmentation ββ β
- Memory seen as variable-size logical segments (main program, functions, stack, symbol table, arrays). Logical address = <segment number s, offset d>.
- Segment table: base + limit per segment. If d β₯ limit β trap (addressing error); otherwise physical address = base + d.
- No internal fragmentation; external fragmentation; natural per-segment protection and sharing.
- Segmentation with paging: Intel IA-32 (segmentation β linear address β paging), Multics.
| Paging | Segmentation |
|---|---|
| Fixed-size pages | Variable-size segments |
| Invisible to the programmer | Matches the programmer's view |
| Internal fragmentation | External fragmentation |
| Page table holds frame numbers | Segment table holds base + limit |
7.5 Kernel memory allocation β
- Buddy system: blocks in powers of 2; quick splitting and coalescing of buddies; internal fragmentation (a 33 KB request gets 64 KB).
- Slab allocation: caches of pre-built kernel objects; no fragmentation, fast (Linux SLAB/SLUB).
8. Virtual Memory βββ β
- Separates logical from physical memory: programs larger than RAM, more multiprogramming, less I/O to load/swap, sharing (libraries, fork with copy-on-write), memory-mapped files.
- Demand paging: bring a page in only when it is referenced (lazy swapper = pager). Pure demand paging: start with no pages in memory. The validβinvalid bit marks pages that are in memory.
- Page-fault handling ββ: (1) reference hits an invalid entry β trap to the OS; (2) OS checks: invalid reference β abort; valid but not in memory β continue; (3) find a free frame (or replace one); (4) schedule the disk read; (5) update the page table (valid bit); (6) restart the faulting instruction.
- EAT = (1 β p)Β·ma + pΒ·(page-fault service time). Example: ma = 200 ns, service time = 8 ms β EAT = 200 + 7,999,800Β·p ns. With p = 1/1,000 β 8.2 Β΅s (about 40Γ slower). For less than 10% slowdown, p < 2.5 Γ 10β»βΆ (fewer than 1 fault in ~400,000 accesses).
- Copy-on-write: after fork(), parent and child share pages until one writes, and only that page is copied. vfork(): the child uses the parent's address space directly (parent suspended), with no copying.
- Major vs minor page faults (minor = page already in memory, just not mapped).
8.1 Page replacement βββ β
Needed when there is no free frame. The dirty (modify) bit lets the OS skip writing back unmodified victims (halves the I/O).
| Algorithm | Rule | Notes |
|---|---|---|
| FIFO | Replace the oldest page | Simple; suffers Belady's anomaly |
| Optimal (OPT/MIN) | Replace the page not used for the longest time in the future | Fewest possible faults; not implementable (needs the future); used as a benchmark; no Belady |
| LRU | Replace the least recently used page | Good approximation of OPT; needs hardware (counters or a stack); stack algorithm β no Belady |
| LRU approximations | Reference bit; additional-reference-bits (shift register); second chance / clock (FIFO + reference bit: if 1, clear it and skip); enhanced second chance using (reference, modify): best victim (0,0), then (0,1), (1,0), (1,1) | Second chance becomes FIFO if all bits are set |
| LFU / MFU | Counting-based | Rarely used; poor approximations of OPT |
- Belady's anomaly ββ: more frames β more page faults. Possible with FIFO. Reference string 1,2,3,4,1,2,5,1,2,3,4,5: FIFO with 3 frames = 9 faults, with 4 frames = 10. (LRU on the same string: 10 then 8, no anomaly.) Stack algorithms (OPT, LRU) never show it, because the pages kept with n frames are always a subset of those kept with n + 1.
- Galvin's string 7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1 with 3 frames: FIFO = 15, LRU = 12, OPT = 9 faults β (checked).
- Page buffering: keep a pool of free frames.
8.2 Frame allocation β
- Minimum frames per process is set by the architecture (the most pages one instruction can touch); the maximum by physical memory.
- Equal allocation (m/n each), proportional (aα΅’ = (sα΅’ / S)Β·m), priority-based.
- Global replacement (victim from any process; better throughput, a process can't control its own fault rate) vs local (only from its own frames).
8.3 Thrashing βββ β
- A process spends more time paging than executing, because it doesn't have enough frames for its working set (degree of multiprogramming too high).
- Vicious cycle: CPU utilization drops β long-term scheduler admits more processes β more faults β utilization drops further.
- Locality model: a process moves between localities; thrashing happens when Ξ£(locality sizes) > total frames.
- Working-set model: WS(t, Ξ) = pages referenced in the last Ξ references; WSSα΅’ = its size; D = Ξ£ WSSα΅’. If D > m (frames available) β thrashing β suspend a process. Ξ too small misses the locality; too large covers several localities.
- Page-fault frequency (PFF): set upper and lower bounds on the fault rate; above the upper bound give the process frames, below the lower bound take frames away.
- Remedies: local/priority replacement, working set, PFF, lower multiprogramming, more RAM.
- Other: prepaging, TLB reach, program structure (row-major traversal of C arrays causes fewer faults), I/O interlock (lock pages used for I/O), memory-mapped files (mmap).
9. File Systems ββ β
- File attributes: name, identifier, type, location, size, protection, timestamps, owner. Operations: create, open, read, write, reposition (seek), delete, truncate, append, rename.
- Open-file tables: per-process (file pointer, access rights) + system-wide (disk location, size, open count). File locks: shared/exclusive; mandatory (Windows) vs advisory (UNIX).
- FCB (file control block) = inode in UNIX: permissions, owner, size, timestamps, block pointers. β οΈ The inode does not store the file name; the name lives in the directory entry.
- Access methods: sequential (tape model: read next, write next, rewind), direct/relative (fixed-length records, read block n), indexed (index of keys β blocks; ISAM).
- Directory structures β: single-level (naming conflicts), two-level (MFD β one UFD per user), tree-structured (absolute/relative paths, current directory), acyclic graph (sharing via links; dangling pointers and deletion issues; reference counts), general graph (cycles allowed β garbage collection and cycle checks needed).
| Hard link | Soft (symbolic) link |
|---|---|
| Another directory entry for the same inode | A separate file (own inode) that stores a path |
| Same inode number; link count increases | Different inode |
| Data deleted only when the link count reaches 0 | Dangles if the target is removed |
| Can't cross file systems; usually not allowed for directories | Can cross file systems and point to directories |
- Mounting attaches a file system at a mount point. The VFS (virtual file system) layer hides different FS types behind one interface.
- Protection: access control lists; UNIX owner/group/others Γ rwx. Octal r = 4, w = 2, x = 1: 755 = rwxr-xr-x, 644 = rw-r--r--, 777 = rwxrwxrwx, 700 = rwx------. umask 022 β new files 644 (666 β 022), new directories 755 (777 β 022). Special bits: setuid (4), setgid (2), sticky (1, as on /tmp).
9.1 Allocation methods βββ β
| Method | Pros | Cons |
|---|---|---|
| Contiguous | Simple; fast sequential and direct access; few seeks | External fragmentation; hard to grow files; size needed upfront (CD-ROM / ISO 9660; extents in modern FS) |
| Linked | No external fragmentation; files grow easily | Efficient only for sequential access; pointer overhead; a lost pointer breaks the chain. FAT = linked allocation with the pointers kept in a table at the start of the volume (MS-DOS, FAT32) |
| Indexed | Direct access; no external fragmentation | Index-block overhead (wasteful for tiny files); large files need linked, multilevel or combined index blocks |
UNIX inode (combined scheme) ββ: typically 12 direct + 1 single-indirect + 1 double-indirect + 1 triple-indirect pointer (15 in total). Older UNIX used 10 direct (13 total), so always read the question.
- Max file size = (D + N + NΒ² + NΒ³) Γ B, where B = block size, N = B / pointer size, D = number of direct pointers.
- B = 4 KB, 4-byte pointers β N = 1,024 β 48 KB + 4 MB + 4 GB + 4 TB β 4 TB.
- B = 1 KB, 4-byte pointers, 10 direct β N = 256 β (10 + 256 + 65,536 + 16,777,216) KB β 16 GB.
Free-space management: bit vector/bitmap (Galvin: 1 = free, 0 = allocated; size = one bit per block, so a 1 TB disk with 4 KB blocks needs 2^28 bits = 32 MB), linked free list, grouping (first free block stores the addresses of n free blocks), counting (start address + run length), space maps (ZFS).
Directory implementation: linear list (simple, O(n) search) vs hash table (fast; collisions; fixed size).
Consistency and recovery: fsck/chkdsk; journaling (log metadata changes first: ext3/ext4, NTFS, XFS, JFS); log-structured FS; copy-on-write FS (ZFS, Btrfs, APFS); backups (full/incremental).
Common file systems: FAT32 (max file size 4 GB β 1 byte; no permissions or journaling), exFAT (flash drives), NTFS (Windows; journaling, ACLs, MFT, compression, encryption), ext4 (Linux; extents, journaling; max file 16 TB with 4 KB blocks), XFS, Btrfs, ZFS, APFS, HFS+. NFS: v3 stateless, v4 stateful.
10. I/O and Disk Management ββ β
- I/O hardware: ports, buses (PCIe), controllers; device drivers are the OS's hardware-specific code. Memory-mapped I/O (device registers appear in the address space) vs port-mapped / isolated I/O (special IN/OUT instructions).
- Device types: block (disk: read/write/seek), character (keyboard, serial: get/put), network (socket interface).
- Blocking I/O (process suspended) vs non-blocking (returns at once with whatever is available) vs asynchronous (returns at once; completion signaled later).
- Kernel I/O subsystem: I/O scheduling, buffering (handles speed and transfer-size mismatches; double buffering), caching, spooling (printer queue), error handling, protection (I/O instructions are privileged).
10.1 Disk structure and timing ββ β
- Platters β surfaces β tracks β sectors (512 B or 4 KB). A cylinder = the same track on all surfaces. Capacity = surfaces Γ tracks per surface Γ sectors per track Γ bytes per sector.
- Access time = seek time + rotational latency + transfer time (+ controller overhead). Average rotational latency = Β½ rotation = 30/RPM seconds (7,200 RPM β 4.17 ms; 15,000 RPM β 2 ms). Transfer rate = bytes per track Γ rotations per second.
- Low-level (physical) formatting β partitioning β logical formatting (creating the file system). Boot block; bad blocks (sector sparing/forwarding, sector slipping).
- SSDs: no seek or rotation, so FCFS/NOOP-style scheduling; wear leveling, TRIM, write amplification. Current Linux I/O schedulers: mq-deadline, BFQ, Kyber, none.
10.2 Disk scheduling βββ β
| Algorithm | Behavior | Notes |
|---|---|---|
| FCFS | Serve in arrival order | Fair, no starvation, lots of head movement |
| SSTF | Nearest request next | Like SJF; can starve far requests; not optimal |
| SCAN (elevator) | Sweep to the end of the disk, then reverse | Middle cylinders get better service |
| C-SCAN | Sweep to the end, jump back to cylinder 0 without serving, sweep again | More uniform wait times |
| LOOK | Like SCAN but reverse at the last request | |
| C-LOOK | Like C-SCAN but go only to the last request, then jump to the lowest pending request |
Worked example (Galvin, checked) ββ: cylinders 0β199, head at 53, queue 98, 183, 37, 122, 14, 124, 65, 67.
| Algorithm | Total head movement |
|---|---|
| FCFS | 640 |
| SSTF (53β65β67β37β14β98β122β124β183) | 236 |
| SCAN toward 0 (53β37β14β0β65ββ¦β183) | 236 |
| LOOK toward 0 (53β37β14β65ββ¦β183) | 208 |
| SCAN toward 199 (53ββ¦β183β199β37β14) | 331 |
| LOOK toward 199 (53ββ¦β183β37β14) | 299 |
| C-SCAN toward 199 (β¦183β199, jump to 0, β14β37) | 382 counting the return jump, 183 without |
| C-LOOK toward 199 (β¦183, jump to 14, β37) | 322 counting the jump, 153 without |
β οΈ Read the direction of head movement, and whether the return jump counts in C-SCAN/C-LOOK.
RAID: see the DBMS notes (0 striping, 1 mirroring, 5 distributed parity, 6 double parity, 10 mirror + stripe).
11. Protection and Security (OS) β
- Protection = internal mechanism controlling how processes/users access resources. Security = defense against internal and external attacks.
- Principle of least privilege; need-to-know; domain of protection = set of <object, rights> pairs.
- Access matrix (rows = domains, columns = objects). Implementations: global table; access control lists (per object = a column; file ACLs); capability lists (per domain = a row; like tickets); lockβkey.
- Threats: Trojan horse, trap door/backdoor, logic bomb, stack/buffer overflow, virus, worm (Morris worm, 1988), port scanning, denial of service. Defenses: authentication, ASLR, DEP/NX bit, stack canaries, sandboxing.
12. Virtualization and Linux Facts β
- Type 1 hypervisor (bare metal): VMware ESXi, Microsoft Hyper-V, Xen, KVM. Type 2 (hosted on an OS): VirtualBox, VMware Workstation, Parallels. Paravirtualization: the guest OS is modified (Xen).
- Containers (Docker) = OS-level virtualization: they share the host kernel (namespaces + cgroups), so they are lighter than VMs.
- Linux signals: SIGHUP (1), SIGINT (2, Ctrl+C), SIGKILL (9, can't be caught or ignored), SIGSEGV (11), SIGALRM (14), SIGTERM (15, default for kill), SIGSTOP (can't be caught or ignored), SIGTSTP (Ctrl+Z), SIGCHLD (sent to the parent when a child ends).
- nice values: β20 (highest priority) to 19 (lowest), default 0; only root can lower the nice value.
- Commands: ps, top/htop, kill, nice/renice, chmod/chown, ls -l, df (disk free), du (disk usage), free (memory), vmstat, lsof, strace (trace system calls).
13. Rapid-fire trap list βββ β
- Multiprogramming β CPU utilization; time-sharing β response time.
- Mode bit 0 = kernel, 1 = user.
- Reading the clock and issuing a trap are non-privileged; setting the timer, disabling interrupts and I/O are privileged.
- fork() returns 0 to the child and the child's PID to the parent; n forks β 2^n processes.
- Waiting β Running is impossible (goes through Ready).
- Long-term scheduler controls the degree of multiprogramming; medium-term swaps.
- Threads share code, data, heap, files; not stack, registers or PC.
- A blocking call in a user-level thread blocks the whole process (many-to-one).
- SJF gives the minimum average waiting time; SRTF is its preemptive optimum.
- RR: q too large β FCFS; too small β overhead.
- Starvation: SJF, SRTF, priority (fix: aging). No starvation: FCFS, RR, HRRN.
- Peterson: mutual exclusion + progress + bounded waiting. Strict alternation fails progress.
- A simple TSL lock lacks bounded waiting.
- Semaphore final value = initial β P + V.
- A monitor signal with no waiter is lost.
- Deadlock needs all four Coffman conditions.
- A RAG cycle means deadlock only with single-instance resources.
- Unsafe β deadlocked.
- R β₯ n(k β 1) + 1 guarantees no deadlock.
- Belady's anomaly β FIFO (stack algorithms are immune).
- OPT gives the fewest faults but can't be implemented.
- Paging β internal fragmentation; segmentation β external.
- Inverted page table: one entry per physical frame.
- A TLB miss costs extra memory access(es).
- Thrashing: too many processes, too few frames β working set / PFF.
- Compaction requires execution-time binding.
- Best fit leaves the smallest holes, worst fit the largest; first fit is fastest.
- Hard link shares the inode; soft link has its own inode and can dangle.
- SCAN goes to the disk end; LOOK stops at the last request.
- SSTF can starve requests; FCFS can't.