PrepStack › CS Fundamentals › Operating Systems
Operating Systems interview cheat sheet
Processes, threads, scheduling, sync, deadlock, memory, files and I/O
OS rounds check that you understand what really happens below your code: how processes and threads are created and scheduled, why shared data needs locks, how deadlock happens, how virtual memory and paging work, and how files and I/O reach the disk. Expect numeric questions too (waiting times, page faults, Banker's algorithm, address translation). The simulations below are runnable, so use them to check your hand calculations. Read the 15-minute revision first, then switch to Quiz mode and answer out loud.
15-minute revision
- The OS is a resource manager and a set of abstractions: processes (CPU), virtual memory (RAM), files (disk) and sockets (network). The kernel is the part that runs in privileged mode.
- Monolithic kernel (Linux): all services in kernel space, fast but a bug can crash everything. Microkernel (seL4, QNX, MINIX 3): only IPC, scheduling and basic memory in the kernel. Hybrid: Windows NT, macOS XNU.
- User mode cannot touch hardware. A system call is a controlled trap into kernel mode (
syscallon x86-64). Interrupts are asynchronous (from devices), traps and exceptions are synchronous (from the running instruction). - Process = program in execution with its own address space. Thread = unit of scheduling inside a process; threads share heap, code and open files but each has its own stack, registers and PC.
- The PCB stores PID, state, saved registers, PC, scheduling info, page-table pointer and open files. A context switch saves one PCB and loads another; it is pure overhead.
- States: new → ready → running → waiting (blocked) → ready … → terminated. Only ready processes compete for the CPU.
fork()returns 0 in the child and the child PID in the parent.exec()replaces the program image and keeps the PID. Zombie = exited but not yet reaped bywait(); orphan = parent died, adopted by init.- Scheduling metrics: waiting time = turnaround − burst, turnaround = completion − arrival, response = first run − arrival. SJF/SRTF minimise average waiting time; RR gives good response time.
- Linux used CFS (red-black tree ordered by virtual runtime) from 2.6.23; since 6.6 the fair class moved to EEVDF (earliest eligible virtual deadline first).
- A race condition happens when the result depends on thread timing. A critical section needs mutual exclusion, progress and bounded waiting.
- Mutex = lock with an owner. Semaphore = counter with wait/signal, no owner. Monitor = lock + condition variables bundled with the data. Always wait on a condition in a
whileloop. - Deadlock needs all four Coffman conditions: mutual exclusion, hold and wait, no preemption, circular wait. Break any one to prevent it; Banker's algorithm avoids it by refusing unsafe states.
- Paging splits memory into fixed pages and frames, so there is no external fragmentation. Address = page number + offset. The TLB caches recent translations.
- A page fault loads a missing page from disk. FIFO can show Belady's anomaly (more frames, more faults); LRU and Optimal cannot. Too little memory for the working set causes thrashing.
fork()uses copy-on-write: parent and child share pages read-only until one writes, then only that page is copied.- An inode holds file metadata and block pointers but not the name. Journaling writes intent to a log first so a crash cannot leave the file system inconsistent. DMA lets devices copy data to RAM without the CPU.
OS foundations
What an OS does & kernel types
The OS shares hardware safely between programs; the kernel design decides how much code runs with full privilege.
- Two views of an OS: a resource manager (CPU time, memory, disk, devices) and an extended machine that hides hardware behind clean abstractions such as processes, files and sockets.
- Core jobs: process and thread management, CPU scheduling, memory management, file systems, device drivers and I/O, protection and security, networking.
- The kernel is the always-resident core that runs in privileged mode. Shells, compilers and system utilities are user programs, not part of the kernel.
- Monolithic kernels put drivers, file systems and networking in one kernel address space. Calls are plain function calls, so they are fast, but one buggy driver can crash the machine. Linux is monolithic but supports loadable kernel modules.
- Microkernels keep only IPC, basic scheduling and address-space management in kernel mode. Drivers and file systems run as user-space servers, which isolates faults but costs extra IPC and context switches.
- Hybrid kernels mix both: Windows NT and macOS XNU (Mach + BSD) are structured like microkernels but run most services in kernel space for speed.
Interview questions
- What is an operating system and what does it do?
- Difference between a monolithic kernel and a microkernel?
- What is multiprogramming vs multitasking vs multiprocessing?
User vs kernel mode, system calls & interrupts
The CPU has a privileged mode for the kernel; programs enter it only through system calls, interrupts and exceptions.
- A mode bit in the CPU decides what is allowed. In kernel mode any instruction and any memory is allowed. In user mode, privileged instructions (I/O, changing page tables, disabling interrupts) cause a fault.
- x86 has rings 0 to 3; Linux and Windows use only ring 0 (kernel) and ring 3 (user). ARM uses exception levels EL0 (user) and EL1 (kernel).
- A system call is the official door into the kernel. Library wrappers like
read()put the syscall number and arguments in registers and run a trap instruction (syscallon x86-64,svcon ARM64). - Categories of system calls: process control (
fork,exit,wait), file (open,read,write), device (ioctl), information (getpid), communication (pipe,socket,mmap). - Interrupts are asynchronous signals from hardware (timer, NIC, disk). Traps/exceptions are synchronous and caused by the current instruction (syscall, page fault, divide by zero).
- The CPU uses an interrupt vector table (IDT on x86) to jump to the right handler. Linux splits handling into a fast top half and deferred bottom halves (softirqs, tasklets, workqueues).
Interview questions
- Why do we need user mode and kernel mode?
- What happens during a system call?
- Difference between an interrupt and a trap?
Processes & threads
Process vs thread & the PCB
A process owns resources; a thread is a path of execution inside it. The kernel tracks each one in a control block.
- A process is a program in execution: code, data, heap, stack, open files and its own virtual address space. Processes are isolated from each other.
- A thread is the unit the scheduler runs. Threads of one process share code, heap, globals and file descriptors, but each has its own stack, registers, program counter and thread-local storage.
- The Process Control Block (PCB) holds: PID and parent PID, state, saved registers and PC, scheduling info (priority, time used), memory info (page-table pointer), open file table, signal info and accounting.
- Linux uses one structure,
task_struct, for both. A thread is just a task created withclone()that shares the address space and file table with its parent. - Threads are cheaper to create and switch between because there is no address-space change. The price is less isolation: one thread's bad write or crash can kill the whole process.
Interview questions
- What is the difference between a process and a thread?
- What is a PCB and what does it contain?
- When would you choose multiple processes over multiple threads?
Process states & context switching
A process moves between ready, running and waiting; the kernel switches between them by saving and restoring CPU state.
- New: being created. Ready: waiting for a CPU. Running: on a CPU. Waiting/Blocked: waiting for an event such as I/O. Terminated: finished, waiting for the parent to collect its status.
- Running → ready happens on preemption (time slice over, higher-priority task woke up). Running → waiting happens when the process blocks on I/O, a lock or
sleep. - Waiting never goes straight to running. When the event happens the process becomes ready and waits for the scheduler.
- Some textbooks add suspended ready and suspended blocked for processes swapped out to disk.
- A context switch saves registers, PC and stack pointer of the old task into its PCB, picks the next task, switches the page tables if the process differs, and restores its registers.
- Direct cost is a few microseconds. The bigger hidden cost is cold caches and TLB. Tagged TLBs (PCID on x86, ASID on ARM) avoid a full TLB flush.
Interview questions
- Explain the process state diagram.
- What is a context switch and why is it expensive?
- Difference between a context switch and a mode switch?
fork, exec, wait & copy-on-write
Unix creates processes in two steps: fork() clones the caller cheaply with copy-on-write, and exec() loads a new program.
fork()creates a child that is a copy of the parent. It returns 0 in the child, the child's PID in the parent, and -1 on failure.exec()family (execve,execvp, …) replaces the current program image with a new one. The PID stays the same, and open file descriptors stay open unless marked close-on-exec. It returns only on error.wait()/waitpid()lets the parent block until a child exits and read its exit status. This also frees the child's last kernel entry.- Zombie: a child that has exited but whose parent has not called
wait()yet; it keeps a process-table slot. Orphan: a child whose parent died; it is adopted byinit(PID 1) or a subreaper, which reaps it. - Copy-on-write (COW): after
fork()both processes map the same physical pages marked read-only. The first write to a page causes a fault, and the kernel copies only that page. Sofork()+exec()copies almost nothing. posix_spawn()andvfork()are cheaper alternatives when you only want to start a new program.
Interview questions
- What does
fork()return and why? - Difference between
fork()andexec()? - What are zombie and orphan processes?
- How does copy-on-write make
fork()fast?
Inter-process communication (IPC)
Processes are isolated, so the kernel provides pipes, shared memory, message queues, sockets and signals to let them talk.
- Pipe: one-way byte stream between related processes (
ls | wc). Created withpipe()beforefork(). A named pipe (FIFO) lives in the file system so unrelated processes can use it. - Shared memory (
shm_open+mmap, or System Vshmget): the fastest IPC because data is not copied through the kernel, but you must synchronise access yourself (semaphores, mutexes). - Message queues (POSIX
mq_open, System Vmsgget): the kernel keeps discrete messages with optional priorities; easier than shared memory, slower than it. - Sockets: bidirectional, work across machines (TCP/UDP) or locally (Unix domain sockets, used by Docker and databases). Unix sockets can also pass file descriptors.
- Signals: tiny asynchronous notifications (
SIGINT,SIGTERM,SIGCHLD).SIGKILLandSIGSTOPcannot be caught or ignored. - Two models: shared memory (fast, manual sync) vs message passing (simpler, kernel copies the data, works across machines).
Interview questions
- What IPC mechanisms do you know and when would you use each?
- Why is shared memory the fastest IPC?
- Difference between
SIGTERMandSIGKILL?
User vs kernel threads & threading models
Threads can be managed by a user-space library, by the kernel, or a mix; the mapping decides blocking and parallelism.
- Kernel threads are known to and scheduled by the OS. They can run on different cores in parallel and one blocking does not block the others.
- User threads (green threads) are managed by a runtime library in user space. Creating and switching them is very cheap, but the kernel sees only the underlying kernel thread.
- Many-to-one (M:1): many user threads on one kernel thread. No parallelism, and one blocking syscall blocks all of them. Old green threads worked like this.
- One-to-one (1:1): each user thread is a kernel thread. Used by Linux NPTL pthreads, Windows and Java platform threads. Real parallelism, but each thread costs kernel memory and scheduling.
- Many-to-many (M:N): many user threads multiplexed over a pool of kernel threads. Go goroutines and Java 21 virtual threads use this; the runtime parks a user thread on blocking I/O and runs another one.
- Separately, kernel threads in the Linux sense (
kthreadd,kworker) are tasks that run only in kernel mode with no user address space.
Interview questions
- Difference between user-level and kernel-level threads?
- Which threading model does Linux use?
- Why can a server handle a million goroutines but not a million OS threads?
CPU scheduling
Scheduling algorithms: FCFS, SJF, SRTF, priority, RR
The scheduler picks which ready task runs next; each algorithm trades throughput, waiting time, response time and fairness.
- Non-preemptive: a task keeps the CPU until it blocks or finishes. Preemptive: the OS can take the CPU away (timer, higher-priority arrival).
- Metrics: turnaround = completion − arrival, waiting = turnaround − burst, response = first run − arrival. Also CPU utilisation and throughput (jobs per unit time).
- FCFS: simple queue. Suffers the convoy effect: short jobs wait behind one long job.
- SJF (non-preemptive) and SRTF (preemptive, shortest remaining time first) are provably optimal for average waiting time, but need burst lengths, which are usually estimated with an exponential average of past bursts. Long jobs can starve.
- Priority scheduling runs the highest priority first. Low-priority tasks can starve; fix with aging (raise priority over time).
- Round Robin (RR): FCFS with a time quantum. Great response time for interactive work. A huge quantum turns it into FCFS; a tiny one wastes time on context switches.
Interview questions
- Difference between preemptive and non-preemptive scheduling?
- Why is SJF optimal, and why is it not used directly?
- What is the convoy effect?
- How do you choose the time quantum in Round Robin?
MLFQ, Linux CFS/EEVDF & multicore scheduling
Real schedulers learn task behaviour (MLFQ) or share CPU fairly by virtual runtime (Linux CFS, now EEVDF), across many cores.
- Multilevel queue: separate queues (system, interactive, batch) with fixed priorities. Multilevel feedback queue (MLFQ) lets tasks move between queues based on behaviour.
- MLFQ rules (OSTEP): new jobs start at the top; a job that uses its full slice moves down; a job that gives up the CPU early (I/O) keeps its level; periodically boost all jobs to the top to stop starvation; account total time used at a level so jobs cannot game it by yielding just before the slice ends.
- Linux CFS (2.6.23 to 6.5) tracks each task's vruntime (CPU time scaled by weight from its nice value) and always runs the task with the smallest vruntime, kept in a red-black tree.
- EEVDF became the fair scheduler starting in Linux 6.6. It still tracks virtual runtime but computes lag (how much CPU a task is owed). Among eligible tasks (lag ≥ 0) it runs the one with the earliest virtual deadline, so tasks asking for shorter slices get lower latency.
- Linux also has real-time classes
SCHED_FIFOandSCHED_RR(static priorities 1–99) andSCHED_DEADLINE(EDF), which all run before normal tasks. - Multicore: per-CPU run queues, load balancing between them, and processor affinity to keep a task on a core with warm caches. NUMA-aware placement keeps tasks near their memory.
Interview questions
- How does a multilevel feedback queue work?
- How does Linux CFS decide which task to run?
- What is EEVDF and why did Linux switch to it?
Synchronisation & deadlock
Race conditions, critical sections & Peterson
When threads update shared data without coordination, results depend on timing; a critical-section protocol makes the update atomic.
- A race condition occurs when two or more threads access shared data, at least one writes, and the result depends on the interleaving.
count++is really load, add, store, so two threads can lose an update. - A critical section is the code that touches shared state. A correct solution needs mutual exclusion (one at a time), progress (if nobody is inside, someone waiting can enter) and bounded waiting (no one waits forever).
- Peterson's solution for two threads uses
flag[i](I want to enter) andturn(who yields). It is a classic software solution but needs memory barriers on modern CPUs, which reorder loads and stores. - Hardware gives atomic instructions: test-and-set, compare-and-swap (CAS), fetch-and-add. Locks and lock-free structures are built on them.
- Disabling interrupts works only on a single CPU and only in the kernel; it does not stop other cores.
Interview questions
- What is a race condition? Give an example.
- What are the requirements for a solution to the critical-section problem?
- How does Peterson's algorithm work, and does it work on modern hardware?
Mutex vs semaphore vs monitor, spinlocks & condition variables
Mutexes give exclusive ownership, semaphores count permits, monitors bundle a lock with condition variables, and spinlocks busy-wait.
- Mutex: a lock with an owner. Only the thread that locked it should unlock it. Blocking mutexes put waiters to sleep; on Linux they are built on futex, which avoids a syscall when there is no contention.
- Semaphore (Dijkstra): an integer with
wait()/P (decrement, block if it would go below zero) andsignal()/V (increment, wake a waiter). A counting semaphore limits access to N resources; a binary semaphore has values 0 and 1 but no owner. - Spinlock: waits by looping on an atomic flag. Good only when the lock is held for a very short time on multicore systems, shorter than a context switch. Used heavily inside kernels, for example where sleeping is not allowed.
- Condition variable: lets a thread sleep until some condition about shared state becomes true. Always used with a mutex:
lock; while (!cond) wait(cv, m); … unlock. - Monitor: a language-level construct where the data, a lock and condition variables are bundled; only one thread runs inside at a time. Java
synchronized+wait/notifyis a monitor. - Read-write lock: many readers or one writer. Helps read-heavy data; can starve writers depending on policy.
Interview questions
- Difference between a mutex and a semaphore?
- When would you use a spinlock instead of a mutex?
- Why must a condition variable wait be in a while loop?
Classic problems: producer-consumer, readers-writers, dining philosophers
Three standard puzzles test whether you can combine locks and semaphores without races, deadlock or starvation.
- Producer-consumer (bounded buffer): semaphores
empty = N,full = 0,mutex = 1. Producer: wait(empty), wait(mutex), add, signal(mutex), signal(full). Consumer is the mirror image. - Order matters: if the producer takes
mutexbeforeemptyand the buffer is full, it sleeps holding the mutex and the consumer can never get in. Deadlock. - Readers-writers: many readers may read together, writers need exclusive access. The first variant favours readers (writers can starve); the second favours writers (readers can starve). Fair versions queue both.
- Dining philosophers: five philosophers, five forks, each needs both neighbours' forks. If all pick up the left fork at once, everyone waits forever (circular wait).
- Dining fixes: resource ordering (always pick the lower-numbered fork first), allow at most four at the table (a semaphore of 4), pick up both forks atomically, or an asymmetric rule (odd philosophers take left first, even take right first).
Interview questions
- Solve producer-consumer with semaphores.
- What goes wrong if you swap
wait(empty)andwait(mutex)in the producer? - How do you prevent deadlock in the dining philosophers problem?
- Explain the readers-writers problem and its variants.
Deadlock: conditions, prevention, Banker's, detection, recovery
Deadlock is a cycle of tasks each waiting for a resource held by the next; you prevent, avoid, or detect and recover.
- Coffman conditions, all four must hold: mutual exclusion (resource is non-shareable), hold and wait (hold one, wait for another), no preemption (cannot take a resource away), circular wait (a cycle in the wait-for graph).
- Resource-allocation graph: edges from process to requested resource and from resource to holder. With single-instance resources, a cycle means deadlock; with multiple instances a cycle means only possible deadlock.
- Prevention breaks a condition by design: request all resources at once (no hold-and-wait), allow preemption, or use a global lock order (no circular wait, the most practical one).
- Avoidance checks each request at run time. Banker's algorithm grants a request only if the system stays in a safe state, one where some order lets every process finish. Needs each process's maximum demand in advance.
- Detection lets deadlocks happen, periodically looks for cycles (or runs a Banker-like detection algorithm), then recovers: kill processes, roll back to a checkpoint, or preempt resources. Databases do this and abort one transaction.
- Ignore it (ostrich algorithm): most general-purpose OSes do not prevent application deadlocks; developers avoid them.
Interview questions
- What are the four necessary conditions for deadlock?
- Difference between deadlock prevention and deadlock avoidance?
- Explain Banker's algorithm.
- How would you detect and recover from a deadlock?
- You see two services hang under load. How do you check for a deadlock?
Starvation, livelock & priority inversion
Besides deadlock, tasks can wait forever because others are always chosen, keep reacting without progress, or be blocked by lower priorities.
- Starvation: a task is ready but never gets the resource because others are always preferred (low priority, long jobs in SJF, writers in readers-preference locks). Fix with aging or fair (FIFO) queues.
- Livelock: tasks are not blocked but keep changing state in response to each other without progress, like two people stepping aside in a corridor in sync. Fix with randomised back-off.
- Priority inversion: a high-priority task H waits for a lock held by low-priority L, and a medium task M preempts L, so H effectively waits for M.
- Priority inheritance: L temporarily inherits H's priority while holding the lock, so M cannot preempt it. Priority ceiling: a lock carries the priority of its highest possible user, and the holder runs at that priority.
- Famous case: the Mars Pathfinder (1997) kept resetting due to priority inversion in VxWorks; it was fixed by enabling priority inheritance on the mutex remotely.
Interview questions
- What is priority inversion and how is it solved?
- Difference between deadlock and starvation?
- What is a livelock? Give an example.
Memory management
Address spaces, MMU, contiguous allocation & fragmentation
Programs use logical addresses; the MMU maps them to physical memory, and the allocation scheme decides how memory fragments.
- A logical (virtual) address is generated by the CPU for a program. A physical address is the real location in RAM. The MMU (memory management unit) translates one to the other on every access.
- Address binding can happen at compile time, load time or execution time. Execution-time binding, done by the MMU, lets the OS move processes around.
- Simplest MMU: base (relocation) and limit registers. Physical = base + logical, and any logical address ≥ limit traps. This gives protection between processes.
- Contiguous allocation gives each process one block. Placement strategies: first fit (fast), best fit (smallest hole that fits, leaves tiny holes), worst fit (largest hole).
- External fragmentation: enough total free memory exists but not in one contiguous piece. Fixed by compaction or by paging.
- Internal fragmentation: space wasted inside an allocated block, for example the unused end of the last page or a fixed partition larger than needed.
Interview questions
- Difference between logical and physical address?
- Difference between internal and external fragmentation?
- Compare first fit, best fit and worst fit.
Paging, page tables, TLB & segmentation
Paging maps fixed-size virtual pages to physical frames through page tables, and the TLB makes that fast.
- Virtual memory is split into pages, physical memory into frames of the same size (usually 4 KiB). Any page can go in any frame, so there is no external fragmentation.
- An address splits into page number (index into the page table) and offset (position inside the page). With 4 KiB pages the low 12 bits are the offset.
- A page table entry (PTE) holds the frame number plus bits: present/valid, read/write, user/supervisor, accessed (reference), dirty, and no-execute.
- A flat table for a 32-bit space with 4 KiB pages has 2^20 entries (4 MiB per process). Multi-level page tables only allocate the parts in use. x86-64 uses 4 levels for 48-bit addresses (5 levels for 57-bit with LA57).
- The TLB is a small, fast cache of recent translations. A hit avoids walking the page table; a miss costs several memory accesses. Huge pages (2 MiB, 1 GiB) cover more memory per TLB entry.
- Segmentation splits the address space into variable-size logical units (code, data, stack) with base and limit each. It matches the programmer's view but causes external fragmentation. x86-64 mostly disables it in favour of paging.
Interview questions
- How does paging translate a virtual address?
- Why use multi-level page tables?
- What is a TLB and what happens on a TLB miss?
- Calculate: 32-bit addresses, 4 KiB pages, 4-byte PTEs. How big is a single-level page table?
Virtual memory: demand paging, page replacement & thrashing
Only the pages a process touches are kept in RAM; on a page fault the OS loads the page and may evict another one.
- Virtual memory lets a process use more address space than physical RAM and gives each process an isolated view. Pages live in RAM or on disk (swap or the file they map).
- Demand paging: a page is loaded only when first accessed. Pure demand paging starts a process with zero pages in memory.
- Page fault steps: trap to the kernel; check the address is valid (else
SIGSEGV); find a free frame or evict one; read the page from disk; update the PTE; restart the instruction. - Minor fault: the page is already in RAM (page cache, COW), only the mapping is missing. Major fault: disk I/O is needed, millions of times slower than a memory access.
- Replacement algorithms: FIFO (oldest), Optimal/OPT (page used farthest in future, a benchmark only), LRU (least recently used), Clock/second chance (LRU approximation using the reference bit), LFU/MFU.
- Thrashing: the total working sets exceed RAM, so processes fault constantly and the CPU sits idle waiting for disk. Fix by reducing the degree of multiprogramming, using the working-set model or page-fault frequency control, or adding RAM.
Interview questions
- What is virtual memory and why is it useful?
- What happens on a page fault?
- What is Belady's anomaly?
- What is thrashing and how do you fix it?
Storage & I/O
File systems: inodes, allocation methods & journaling
A file system maps names to inodes and inodes to disk blocks, and journaling keeps that mapping consistent after a crash.
- An inode stores a file's metadata: type, permissions, owner, size, timestamps, link count and pointers to data blocks. It does not store the file name.
- A directory is a special file mapping names to inode numbers. So a hard link is just another name for the same inode; a symbolic link is a separate file whose content is a path.
- Allocation methods: contiguous (fast, external fragmentation, hard to grow), linked (no fragmentation, slow random access; FAT keeps the links in a table), indexed (an index block lists all blocks; Unix inodes use direct + single/double/triple indirect pointers). ext4 uses extents (start block + length).
- Free space is tracked with bitmaps, free lists or extent trees.
- Journaling: before changing metadata, the file system writes the planned changes to a journal; after a crash it replays or discards incomplete transactions instead of running a full
fsck. ext4's default is ordered mode (metadata journaled, data written before its metadata commits). - Copy-on-write file systems (ZFS, Btrfs, APFS) never overwrite live blocks; they write new blocks and switch a pointer atomically, which also makes snapshots cheap.
Interview questions
- What is an inode?
- Compare contiguous, linked and indexed allocation.
- What is journaling and why is it needed?
- Difference between a hard link and a soft link?
Disk scheduling: FCFS, SSTF, SCAN, C-SCAN, LOOK
On spinning disks, seek time dominates, so the OS reorders requests to reduce head movement without starving anyone.
- HDD access time = seek time (move the arm) + rotational latency (wait for the sector) + transfer time. Scheduling mainly reduces seek distance.
- FCFS: fair, no reordering, lots of back-and-forth movement.
- SSTF (shortest seek time first): serve the closest request. Much less movement but can starve far requests, like SJF.
- SCAN (elevator): move in one direction to the end of the disk serving requests, then reverse. LOOK reverses at the last request instead of the edge.
- C-SCAN: serve in one direction only, then jump back to the start without serving. Gives more uniform wait times. C-LOOK jumps back only as far as the lowest request.
- SSDs have no seek, so heavy reordering is pointless. Linux block layer (blk-mq) offers
mq-deadline,bfq,kyberandnone; NVMe drives often usenone.
Interview questions
- Difference between SCAN and C-SCAN?
- Why can SSTF cause starvation?
- Does disk scheduling matter for SSDs?
I/O: polling, interrupts, DMA, buffering & caching
The CPU can wait for devices by polling or interrupts, let DMA move the data, and smooth speed gaps with buffers and caches.
- Polling (programmed I/O): the CPU repeatedly checks a device status register. Wasteful for slow devices, but the lowest latency for very fast ones (NVMe and network busy-polling).
- Interrupt-driven I/O: the device raises an interrupt when ready, so the CPU does other work meanwhile. Too many interrupts (an interrupt storm) hurt, so NICs use coalescing or switch to polling (Linux NAPI).
- DMA (direct memory access): the CPU programs a DMA controller with source, destination and length; the device copies the whole block to RAM itself and interrupts once at the end. Essential for disks and NICs. An IOMMU restricts what memory a device may touch.
- Buffering holds data in memory while moving between producer and consumer of different speeds or sizes: single, double (one fills while the other drains) and circular buffers.
- Caching keeps a copy of data in faster storage for reuse. Linux keeps file data in the page cache, so repeated reads hit RAM and writes are write-back (flushed later, or on
fsync). - Spooling queues output for a device that can serve one job at a time, like a printer.
Interview questions
- Difference between polling and interrupts?
- What is DMA and why is it useful?
- Why might
write()return before data is on disk, and how do you make it durable?