electronics engineering
Course handbook · Fifth year
Operating Systems
Operating systems: processes, scheduling, memory management, file systems and Linux and Windows in practice.
- 8Topics
- 0Solved exercises
- 5Formula sheet
Free handbook generated from the lessons of the site and updated often, every time a lesson or an exercise changes: the latest version is always at www.electronics-engineering.com/handbook/operative-systems. Links work in the PDF too.
1Processes and threads
An operating system does two jobs: it offers programs a convenient abstraction of the machine (files instead of disk sectors, processes instead of processor registers) and it manages its resources so that many programs can coexist without harming each other. The central concept is the process, a program in execution. In this lesson we look at protected mode and system calls, the structure of a process and its states, context switching, process creation in Unix with the proof of how many processes arise from a sequence of forks, threads and inter-process communication.
User mode and kernel mode
The processor has at least two privilege levels (Computer Systems lesson on input and output). In kernel mode all instructions can be executed and all memory and devices accessed; in user mode privileged instructions cause an exception. Programs run in user mode; when they need a service (reading a file, creating a process, allocating memory) they execute a system call: a special instruction (trap) passes control to the kernel at a fixed point, the kernel checks the parameters, performs the service and returns the result, going back to user mode.
The transition costs from tens to hundreds of nanoseconds, much more than a function call: this is why libraries batch operations (for example the C printf function accumulates characters in a buffer and calls the kernel only once).
The process
A process consists of:
- a private address space: code, global data, heap (dynamically allocated memory) and stack (Computer Science Foundations lesson on dynamic memory);
- the processor state: program counter, registers, stack pointer;
- system resources: open files, permissions, identifier (PID), parent process.
The kernel keeps all this in a process descriptor (PCB, process control block). During its life a process goes through several states.

On a CPU only one process runs at a time; the other ready ones wait in a queue, and those waiting wait for an event (the end of a disk read, a packet from the network, a key press). Choosing who runs is the job of the scheduler (lesson on scheduling).
Context switching
To move from one process to another the kernel saves the registers of the first in its PCB, loads those of the second and changes the address space (the page table, lesson on virtual memory). The switch takes a few microseconds, but the real cost is indirect: caches and the TLB contain data of the previous process and refill, slowly. A scheduler that switches too often wastes the machine.
Creating processes in Unix
In Unix a process is born by cloning another one with the fork call: the child is a copy of the parent (same memory, same open files), and fork returns 0 in the child and the child’s PID in the parent. To run another program the child calls exec, which replaces its code. The parent can wait for the child to finish with wait.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid = fork();
if (pid == 0) { /* child */
execlp("ls", "ls", "-l", NULL); /* becomes the ls program */
perror("exec"); /* reached only if exec fails */
return 1;
}
waitpid(pid, NULL, 0); /* the parent waits for the child */
printf("child %d finished\n", pid);
return 0;
}Copying all the memory would be slow; modern systems use copy-on-write: parent and child share the pages, marked read-only, and a page is duplicated only when one of the two modifies it.
Theorem. A program that executes
fork calls in sequence, without checking their result, produces
processes in total.
Proof. By induction on
. With
there is only the initial process,
. Suppose that after
forks there are
processes; each continues from where it is and executes the next fork, creating a child. The processes become
. ∎
With
we get 1024 processes: this is the principle of the “fork bomb”, defended against by limiting the number of processes per user.
Threads
A thread is a flow of execution inside a process: it has its own registers and stack, but shares memory and files with the other threads of the same process. Creating one and switching between threads costs less than between processes, and communication is immediate through shared memory. The price is that every shared access must be synchronised (lesson on synchronisation), and a bug in one thread can corrupt the whole process. Threads are used to exploit several cores (lesson on multicore systems) and to avoid blocking an interactive program while it waits for the disk or the network.
Inter-process communication
Separate processes communicate through the kernel:
- pipes: a one-way byte channel between two processes; the shell uses them to connect commands, as in ls | grep txt, where the output of the first becomes the input of the second;
- shared memory: an area mapped into the address spaces of several processes, very fast but needing synchronisation;
- message queues and sockets, which also work between different machines (Telecommunication Networks lesson on layered architecture);
- signals: asynchronous notifications, such as interruption with Ctrl-C.
Unix filters, small programs that read a text stream and transform it, such as sed, grep and sort, are composed with pipes into powerful chains: this is the “do one thing and do it well” philosophy.
2CPU scheduling
When several processes are ready, the scheduler decides who uses the CPU and for how long. The possible choices favour different goals: finishing many jobs, responding quickly to the user, being fair, meeting deadlines. In this lesson we look at performance measures, the classic algorithms with the proof that “shortest first” minimises average waiting, duration estimation, round robin with its bound on response time, priorities and the Linux scheduler.
The measures
For each process we measure:
- the turnaround time: from arrival to completion;
- the waiting time: the time spent ready in the queue, without running;
- the response time: from arrival to first execution, important for interactive programs.
For the system what counts is throughput, the number of jobs completed per unit time, and CPU utilisation. Processes alternate bursts of computation (CPU bursts) and input/output waits: interactive processes have short bursts, compute-bound ones long bursts.
FCFS and SJF
FCFS (first come, first served) runs processes in order of arrival. It is simple but suffers from the convoy effect: one long job in front makes all the short ones behind it wait. SJF (shortest job first) runs the job with the shortest burst first.

Example. With FCFS the waiting times are 0, 5, 14, 20, average 9.75; with SJF they are 0 (P4), 2 (P1), 7 (P3), 13 (P2), average 5.5.
Theorem. Among all non-preemptive orderings of
jobs available at time 0, SJF minimises the average waiting time.
Proof (exchange). Consider an ordering in which two consecutive jobs
and
have durations
, with
before
. Swapping them, the waiting time of the earlier and later jobs does not change (the later ones wait
for the two anyway). The waiting time of
decreases by
and that of
increases by
: the sum decreases by
. So every ordering with a consecutive “long before short” pair can be improved, and the optimum has none: it is the ordering by increasing duration, i.e. SJF. ∎
The same exchange argument proves many optimality results in scheduling (Business Management lesson on production scheduling).
Estimating the future
SJF requires knowing the duration of the next burst, which is unknown. It is estimated with an exponential average of past bursts:
![]()
where
is the measured duration of the last burst and
the weight of recent history. It is a first-order low-pass filter (lesson on discrete-time systems). The preemptive version, SRTF (shortest remaining time first), interrupts the running process if one arrives with a burst shorter than its remaining time. The risk of both is starvation of long jobs, if short jobs keep arriving.
Round robin
Round robin gives every ready process, in turn, a time quantum
; when it expires the process goes back to the end of the queue (the transition from running to ready in the state diagram, lesson on processes).
Theorem. With
ready processes and quantum
, no process waits more than
before its turn.
Proof. In front of a process in the queue there are at most
processes, and each uses the CPU for at most
before being put back at the end. ∎
The quantum is a trade-off. If
is large, round robin becomes FCFS; if it is small, response is fast but the context switch, lasting
, weighs: the useful fraction of time is
. With
µs and
ms the cost is 0.1 %; with
µs it would be almost 10 %. Usually the quantum is chosen longer than the typical burst of interactive processes, which thus finish before it expires.
Priorities and multiple queues
Real schedulers assign priorities: interactive or system processes before compute-bound ones. To avoid starvation of low-priority processes aging is used: priority grows with the time spent waiting.
The multilevel feedback queue (MLFQ) learns the nature of processes without knowing it in advance: a new process enters the highest-priority queue with a short quantum; if it uses its whole quantum it moves down a level, if it blocks earlier it stays up. Interactive processes thus stay at the top, compute-bound ones move down to queues with longer quanta.
The Linux scheduler
The Linux scheduler for ordinary processes, CFS (completely fair scheduler, replaced from version 6.6 by its evolution EEVDF with the same principle), tries to give each process a fair share of the CPU. It keeps for each process a virtual runtime, which grows while the process runs, more slowly for more important processes; it always runs the process with the minimum virtual runtime, keeping processes in a balanced binary tree. A process that sleeps a lot (interactive) accumulates little virtual runtime and, when it wakes up, runs immediately. Importance is set with the “nice” value: each step changes the weight by about 25 %.
On multiprocessor systems the scheduler must also balance the load across cores and, on the contrary, keep a process on the same core (affinity) to exploit the caches already filled with its data. Real-time processes need different rules, with guaranteed deadlines (lesson on real-time systems).
3Synchronisation
When several threads or processes access the same data, the result can depend on the unpredictable order in which their instructions interleave. These are the hardest bugs to find: they appear once in a million runs and disappear when a debug print is added. In this lesson we look at race conditions, the requirements of a critical section, Peterson’s algorithm with the proof of mutual exclusion, atomic instructions, semaphores with the producer-consumer problem, and monitors.
The race condition
The C statement counter++ looks indivisible, but the processor executes it in three steps: it reads the value from memory into a register, increments it, writes it back. If two threads execute it together starting from 5:
| Thread A | Thread B | counter |
|---|---|---|
| reads 5 | 5 | |
| reads 5 | 5 | |
| writes 6 | 6 | |
| writes 6 | 6 |
Two increments, but the counter is 6: one has been lost. This is a race condition. Two threads each performing a million increments on a multicore almost always end with less than two million, and with a different value on every run.
The critical section
The code that accesses shared data is a critical section. A correct solution must guarantee:
- mutual exclusion: at most one thread at a time in the critical section;
- progress: if nobody is in the critical section and someone wants to enter, the decision cannot be postponed forever;
- bounded waiting: a thread asking to enter succeeds after a bounded number of entries by the others.
Peterson’s algorithm
For two threads, 0 and 1, two shared variables suffice: flag[i] is true when thread i wants to enter, turn indicates who must give way.
/* code of thread i; j = 1 - i is the other */
flag[i] = true; /* I want to enter */
turn = j; /* but I give way to the other */
while (flag[j] && turn == j)
; /* wait */
/* critical section */
flag[i] = false; /* leave */Theorem. Peterson’s algorithm guarantees mutual exclusion.
Proof. Suppose, for contradiction, that both threads are in the critical section. Then flag[0] and flag[1] are both true, because each set it to true before entering and resets it to false only on leaving. Consider the last thread that wrote turn, for example thread 1, which wrote turn = 0. From that moment turn is 0 and flag[0] is true, so the loop condition of thread 1, flag[0] && turn == 0, is true: thread 1 cannot have passed the loop after its write. But the loop comes after the write in its code: contradiction. The same holds with the roles swapped. ∎
Progress and bounded waiting can also be proved. On modern processors, however, the algorithm works only with memory barriers, because the processor and the compiler may reorder reads and writes to different addresses (lesson on multicore systems): it is a teaching idea, not a practical tool.
Atomic instructions
Processors offer instructions that read and modify a memory word indivisibly:
- test-and-set: writes true and returns the previous value;
- compare-and-swap (CAS): writes a new value only if the current one equals an expected value, and reports whether it succeeded.
With these a spinlock is built: a thread repeats test-and-set until it gets the value false. It is fine for very short critical sections on multicore; otherwise it wastes CPU, and it is better for the thread to block and yield the processor.
Semaphores
A semaphore (Dijkstra, 1965) is an integer with two atomic operations:
- wait (or P): if the value is positive it decrements it, otherwise it blocks the thread until it becomes positive;
- signal (or V): increments the value and wakes a waiting thread, if any.
A semaphore initialised to 1 is a mutex: wait before the critical section, signal after. A semaphore initialised to
counts available resources.
Producer and consumer. A producer puts items into a circular buffer of
slots, a consumer takes them out. Three semaphores are needed: e counts empty slots (initially
), f full slots (initially 0), m protects the indices (initially 1).

/* producer */ /* consumer */
wait(e); wait(f);
wait(m); wait(m);
buf[i] = x; i = (i+1) % N; y = buf[j]; j = (j+1) % N;
signal(m); signal(m);
signal(f); signal(e);The producer blocks on e when the buffer is full, the consumer on f when it is empty. The order of the waits matters: if the producer did wait(m) before wait(e) and found the buffer full, it would block while holding m, and the consumer could no longer enter to free a slot. This is a deadlock (lesson on deadlock).
Monitors
Semaphores are powerful but easy to get wrong: a forgotten or swapped wait breaks everything. Modern languages offer higher-level constructs. A monitor groups shared data and procedures, with the guarantee that only one thread at a time executes a procedure; to wait for a condition inside the monitor, condition variables are used, with the operations wait (which releases the monitor while waiting) and signal. In Java every object is a monitor (synchronized, wait, notify); in C and C++ the mutexes and condition variables of the thread library are used.
An alternative is to avoid sharing: lock-free data structures based on compare-and-swap, or threads that share nothing and communicate only by messages, as in the Go and Erlang languages.
4Deadlock
A deadlock is a situation in which a group of processes stays blocked forever, because each is waiting for a resource held by another in the group. It is the crossroads with four stopped cars, each waiting for the one on its right to go. In this lesson we look at the four necessary conditions, the resource allocation graph with the cycle criterion, prevention by ordering resources and its proof, the banker’s algorithm with an example, detection and the dining philosophers problem.
The four conditions
Coffman (1971) showed that a deadlock can occur only if four conditions hold simultaneously:
- mutual exclusion: resources are not shareable (a printer, a lock);
- hold and wait: a process holds resources while waiting for others;
- no preemption: resources cannot be taken away by force, only released voluntarily;
- circular wait: there is a chain of processes in which each waits for a resource of the next, and the last for one of the first.
Preventing any one of them makes deadlock impossible.
The allocation graph
The relations between processes and resources are represented by a graph: an edge from a resource to a process means the resource is assigned to that process; an edge from a process to a resource means a pending request.

Theorem. If every resource has a single instance, the system is deadlocked if and only if the allocation graph contains a cycle.
Proof. If there is a cycle, each process in the cycle waits for a resource, which has a single instance and is assigned to the next process of the cycle, also waiting: nobody can proceed or release, so they are deadlocked. Conversely, if there is a deadlock, start from a blocked process: it waits for a resource, assigned to another process, which is in turn blocked (otherwise it would finish and release it); following the chain in the finite graph we must sooner or later return to an already visited process, closing a cycle. ∎
With multi-instance resources a cycle is necessary but not sufficient: another instance may be freed and break the wait.
Prevention
One of the four conditions is denied. The most practical is circular wait.
Theorem. If resources are numbered and every process requests them only in increasing order of number, circular wait cannot occur.
Proof. Suppose, for contradiction, a cycle
, where
holds resource
and waits for
, held by
(and
waits for
). Since
holds
and requests
, by the rule
. Along the cycle we get
, impossible. ∎
This is the rule used in kernels: locks have a documented order, and in Linux a checking tool (lockdep) reports at run time every violation of the order, even if the deadlock has not yet occurred. The other conditions are denied by requesting all resources together at the start (against hold and wait, but it wastes resources) or by allowing preemption for resources whose state can be saved, such as the CPU and memory.
The banker’s algorithm
Avoidance grants a request only if the resulting state is safe: there is an order in which all processes can obtain their declared maximum and terminate. The banker’s algorithm (Dijkstra) performs this check.
Example. One resource with 14 instances and three processes:
| Process | Maximum | Allocated | Remaining need |
|---|---|---|---|
| P1 | 10 | 6 | 4 |
| P2 | 5 | 3 | 2 |
| P3 | 8 | 2 | 6 |
instances are available. The state is safe: P2 (need 2) can finish and return 3, available 6; then P1 (4), available 12; then P3. If now P3 requests 2 instances and they are granted, 1 remains available and P3’s need becomes 4: no process can be sure to finish any more (P2 needs 2, P1 4, P3 4). The state would not be safe, and the request is postponed, even though it would not necessarily cause a deadlock.
The algorithm requires knowing each process’s maximum in advance and costs
per request, with
resource types: it is used in specialised systems, not in general-purpose operating systems.
Detection and recovery
Many systems let deadlock happen, detect it by looking for cycles in the wait-for graph and then recover: they terminate one of the processes or take a resource away from it and roll it back to an earlier point. This is the strategy of databases, which abort a transaction and re-run it (Information Systems lesson on transactions). General-purpose operating systems, for application locks, often do nothing: they ignore the problem, leaving applications the task of avoiding it.
The dining philosophers
Five philosophers sit at a round table with a fork between each pair; two are needed to eat. If all simultaneously take the fork on their left, each waits forever for the one on the right: a circular wait. The ordering solution: number the forks and always take the lower-numbered one first. Then one philosopher, the one between fork 5 and fork 1, takes the right one first, and the cycle is broken.
5Memory management
Virtual memory (Computer Systems lesson on virtual memory) gives each process a private address space, divided into pages that the operating system loads into memory only when needed. When physical memory is full and a new page is needed, one must be chosen for removal: this is the page replacement problem, and the choice matters enormously, because a page fault costs millions of times a normal access. In this lesson we look at the cost of page faults with an example, the FIFO, optimal and LRU algorithms, Belady’s anomaly with the proof that LRU does not suffer from it, the clock algorithm, the working set and thrashing.
The cost of a page fault
If the requested page is not in memory, the processor raises a page fault: the operating system finds a free frame (or frees one), reads the page from disk, updates the page table and makes the instruction repeat. With fault probability
, memory access time
and fault service time
, the effective access time is
![]()
Example. With
ns and
ms (a magnetic disk), to slow down by no more than 10 % we need
ns, i.e.
ns roughly,
: less than one fault every 800,000 accesses. With an SSD (
µs) the limit relaxes eighty-fold, but remains strict.
Replacement algorithms
- FIFO: remove the page loaded longest ago. Simple, but it also removes heavily used pages, such as those of the main code.
- Optimal (OPT, Belady): remove the page that will be used furthest in the future. It is the best possible, but requires knowing the future; it serves as a benchmark in simulations.
- LRU (least recently used): remove the page unused for the longest time. It uses the recent past as a prediction of the near future, exploiting locality (lesson on cache memory).
Belady’s anomaly
One would expect faults always to decrease with more frames. With FIFO this is not so.

With the string 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5, FIFO makes 9 faults with 3 frames and 10 with 4: adding memory makes things worse. LRU and OPT do not have this anomaly, because of a structural property.
Theorem. With LRU, at every instant, the set of pages in memory with
frames is contained in the set of pages in memory with
frames. Consequently the number of faults with
frames does not exceed that with
frames.
Proof. With LRU, after the initial warm-up, memory with
frames contains exactly the
distinct pages used most recently; before that, it contains all those used so far. In both cases it is the set of the “first
” pages in order of recent use, and the first
are contained in the first
. Every reference that is a hit with
frames (page present) is also a hit with
, so the faults with
frames are at most those with
. ∎
Algorithms with this property are called stack algorithms. FIFO is not one: the set in memory depends on the loading order, not only on recent use.
The clock algorithm
Exact LRU would require recording the time of every memory access, which is too expensive. The hardware offers a reference bit per page, which the processor sets to 1 on every access. The clock (second chance) algorithm arranges the frames in a circle with a hand: when a frame is needed, it looks at the page the hand points to; if the bit is 1 it clears it and moves on (giving it a second chance), if it is 0 it chooses it. Recently used pages survive one sweep of the hand. It is an approximation of LRU used, with variants, in real systems. Clean (unmodified) pages are also preferred for removal, since they need not be written back to disk.
Working set and thrashing
The working set of a process is the set of pages used in the last window of
references: it represents its current locality. If the sum of the working sets of all processes exceeds physical memory, each process removes pages needed by the others, faults multiply and the CPU spends its time waiting for the disk. This is thrashing: adding processes makes throughput collapse instead of increasing it. The cure is to reduce the number of active processes (suspending some) until the working sets fit in memory, or to add memory.
Other uses of virtual memory
- Copy-on-write after a fork (lesson on processes).
- Memory-mapped files: a file becomes an area of the address space, and reading it means accessing memory; the system loads pages on demand.
- Shared libraries: the code of a library used by a hundred processes is in memory only once, mapped into all of them.
- Huge pages (2 MB or 1 GB instead of 4 KB) for programs using a lot of memory, which reduce TLB misses.
6File systems
The file system turns a disk, which is just a long row of numbered blocks, into a hierarchy of folders and files with names, permissions and dates. It must do so efficiently for both tiny and huge files, and stay consistent even if power fails in the middle of an operation. In this lesson we look at block allocation methods, the Unix inode with the calculation of the maximum file size, directories and links, permissions, journaling with the reasoning that guarantees its consistency, and the peculiarities of solid-state drives.
Block allocation
The disk is divided into blocks, typically 4 KiB. A file occupies a number of blocks, and the file system must remember which:
- contiguous allocation: the blocks are consecutive; it is enough to remember the first and the count. Very fast reading and easy direct access, but the disk becomes fragmented and a file cannot grow if the next block is taken;
- linked allocation: each block contains the number of the next. No fragmentation, but to reach block 1000 the 999 before it must be read. The FAT of old Windows systems and memory cards keeps the chain in a separate table, read into memory;
- indexed allocation: an index block contains the list of the file’s blocks. Direct access and no external fragmentation; it remains to decide how to handle files with many blocks.
The inode
In Unix every file is described by an inode, which contains everything except the name: size, owner, permissions, dates and the pointers to the blocks. To handle both small and huge files, the pointers are of four kinds.

- 12 direct pointers to data blocks;
- one single indirect pointer to a block containing
pointers to data blocks; - one double indirect to a block of
pointers to single indirect blocks; - one triple indirect, with one more level.
Theorem. With blocks of
bytes and pointers of
bytes, i.e.
pointers per block, the maximum file size is
![]()
Proof. The direct pointers address 12 blocks. The single indirect block contains
pointers to data:
blocks. The double indirect contains
pointers, each to a block of
pointers to data:
blocks. The triple, with one more level,
. Adding up and multiplying by the block size gives the formula. ∎
Example. With
KiB and 4-byte pointers,
:
blocks, for a maximum of about 4 TiB. A small file, up to 48 KiB, uses only the direct pointers and is read without additional index blocks: the structure is optimised for the common case, because most files are small. Modern file systems such as ext4 replace the pointers with extents, pairs (first block, length) describing whole contiguous runs with a single entry.
Directories, names and links
A directory is a special file containing pairs (name, inode number). Opening /home/anna/thesis.txt means reading the root directory, finding home in it, reading its inode and directory, and so on. Since the name is in the directory and not in the inode, the same file can have several names: a hard link is another entry pointing to the same inode, which keeps a link count and is freed when it reaches zero. A symbolic link is instead a small file containing a path.
Unix permissions assign read, write and execute (r, w, x) to three categories: owner, group, others. The kernel checks them at every file open, in kernel mode, and a user process cannot bypass them (lesson on virtualisation and security).
Consistency after a failure
Creating a file requires modifying several structures: the free-block map, the inode, the directory. If power fails half way, the disk is left in an inconsistent state: a block marked as used but belonging to no file, or worse, a directory pointing to an uninitialised inode. In the past, at every reboot, a checking program (fsck) examined the whole disk, taking hours on large disks.
Journaling solves this with the write-ahead log technique, the same as databases:
- the changes of an operation are first written to a sequential area, the journal, followed by a commit record;
- only then are they applied to the final structures (checkpoint);
- once the operation is complete, the journal entry can be erased.
After a failure: if the journal contains a committed operation, it is reapplied from the start; if the commit is missing, it is ignored. Reapplying is safe because writing the logged blocks is idempotent: writing the same content twice to the same block gives the same result. Each operation is therefore either fully applied or not at all: this is the atomicity of transactions (Information Systems lesson on transactions). Recovery only requires reading the journal, a few seconds. To save writes, the journal usually contains only metadata, not file data.
Solid-state drives
Flash memories (Digital Systems Electronics lesson on semiconductor memories) have different rules from disks: they are written by pages, but erased only by large blocks, and each block endures a limited number of erasures. A translation layer in the controller (FTL) always writes to new pages, keeps the mapping between logical and physical addresses, spreads wear over all blocks (wear leveling) and reclaims the space of obsolete pages in the background. The TRIM command lets the operating system tell the SSD which blocks are no longer needed, so reclamation need not copy them uselessly. There is no longer any head seek time: the algorithms that ordered disk requests to reduce arm movements lose importance, and what counts instead is keeping many requests in flight in parallel.
7Real-time systems
In a real-time system a correct but late result is wrong: a car’s brake command, a motor controller, a pacemaker must respond within a deadline. What counts is not average speed, but the worst-case guarantee. In this lesson we look at the periodic task model, EDF scheduling with the proof of the necessary condition, rate monotonic priority with its bound and exact response time analysis worked through an example, priority inversion and real-time operating systems.
The periodic task model
We distinguish hard systems, where missing a deadline is a failure (flight control, airbags), and soft ones, where only quality degrades (video playback). Many control tasks are periodic (Digital Control lesson on implementation): task
is released every
, requires at most
of computation (the worst-case execution time) and must finish before the next release. Its utilisation factor is
, and the total utilisation
.
Earliest deadline first
The EDF (earliest deadline first) algorithm runs at each instant the ready task with the nearest deadline, with preemption.
Theorem. On one processor, a set of periodic tasks with deadline equal to period is schedulable by any algorithm only if
; with EDF the condition is also sufficient.
Proof of necessity. Consider the interval
, where
is the least common multiple of the periods. Task
is released
times and requires in all
of computation, which must be done within
. The total demand is
, and the processor offers at most
: we need
, i.e.
. ∎
Sufficiency for EDF (Liu and Layland, 1973) is proved by showing that, if a deadline were missed, in the preceding interval the processor would always have been busy with tasks with no later deadlines, and their demand would exceed the length of the interval, i.e.
. EDF is therefore optimal: it uses the processor up to 100 %.
Rate monotonic priority and response time
Many systems use fixed priorities instead, simpler and more predictable under overload: with the rate monotonic rule (RMS) the task with the shortest period has the highest priority. Liu and Layland proved that RMS guarantees the deadlines if
![]()
where
is the number of tasks: 0.83 for two, 0.78 for three, tending to
. The condition is only sufficient; for an exact answer the worst-case response time is computed, which occurs when all tasks are released together. For task
, with higher-priority tasks
:
![Rendered by QuickLaTeX.com \[ R_i = C_i + \sum_{j}\left\lceil\frac{R_i}{T_j}\right\rceil C_j \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-5bca40fbeedd58f9e9bb0696127bdf0a_l3.png)
because during
each higher-priority task is released
times and each time interrupts it for
. The equation is solved by iteration starting from
, until the value stops changing; the task meets its deadline if
.

Example. Three tasks
:
,
,
, with
, above the 0.78 bound: the sufficient test is inconclusive. Response time of
: start from
; then
; then
; then
; then
; then
, stable.
: the set is schedulable, as the figure shows.
Priority inversion
A high-priority task H waits for a lock held by a low-priority task L. If meanwhile a medium-priority task M is released, which does not use the lock, M preempts L, and H stays blocked for the whole duration of M: a less important task indirectly delays the most important one, for an unbounded time if there are many medium tasks. This is priority inversion. In 1997 the Mars Pathfinder probe kept resetting for this reason, until the priority inheritance option was enabled from Earth: while L holds a lock requested by H, L temporarily inherits H’s priority, M cannot preempt it, and H’s blocking lasts at most as long as L’s critical section. The priority ceiling protocol does more, and also prevents deadlocks between locks.
Real-time operating systems
A real-time operating system (RTOS) offers preemptive priority schedulers, small and above all bounded interrupt latencies, synchronisation tools with priority inheritance and predictable memory allocation. On microcontrollers very small kernels such as FreeRTOS or Zephyr are used, a few kilobytes in size; in larger systems Linux with the PREEMPT_RT extensions, which make almost the whole kernel preemptible and bring worst-case latencies down to tens of microseconds. The worst-case execution time
must be measured or computed with analysis tools, taking caches and interrupts into account: it is often the hardest part of the design.
8Virtualisation and security
A modern data centre does not run one operating system per machine: it runs dozens, each in a virtual machine, or thousands of applications isolated in containers. Virtualisation made the cloud possible, and it rests on the same protection mechanisms that separate processes. In this lesson we look at hardware protection, the Popek and Goldberg theorem on virtualisability with its justification, the hypervisor and hardware support with the calculation of the cost of two-level address translation, containers and some security principles.
Protection
Isolation between processes rests on three hardware mechanisms, controlled by the kernel:
- privileged mode (lesson on processes): only the kernel executes the instructions that configure the system;
- address translation: each process sees only the pages its table maps, with read, write and execute permissions per page (lesson on memory);
- timer interrupts: the kernel regains control periodically, even from a process that never calls the system.
When a machine can be virtualised
A hypervisor (or virtual machine monitor) runs several guest operating systems, making each believe it has the machine to itself. The natural method is trap-and-emulate: the guest kernel runs in user mode; when it executes a privileged instruction, the processor raises an exception, the hypervisor intercepts it and emulates the effect on the virtual machine.
Popek and Goldberg (1974) distinguished sensitive instructions, which read or modify the machine’s configuration state (mode, page tables, interrupts), and privileged ones, which cause an exception in user mode.
Theorem (Popek and Goldberg). An efficient hypervisor can be built with the trap-and-emulate method if the set of sensitive instructions is contained in the set of privileged instructions.
Justification. If every sensitive instruction is privileged, every attempt by the guest to touch the configuration causes an exception and reaches the hypervisor, which emulates it on the virtual state: the hypervisor keeps control. All the other instructions do not touch the configuration and can run directly on the processor, at full speed. If instead a sensitive instruction were not privileged, the guest in user mode would execute it without an exception, with an effect different from the one expected in kernel mode, and the hypervisor would not notice. ∎
The original x86 architecture violated the condition: some instructions, such as the one restoring the processor flags, behaved differently in user mode without raising exceptions. The first solutions were binary translation (VMware rewrote the guest kernel’s code on the fly) and paravirtualisation (Xen modified the guest kernel so that it called the hypervisor). Since 2005-2006 processors have dedicated extensions (Intel VT-x, AMD-V) with a new mode for the hypervisor, which make the machine virtualisable according to the theorem.
Hypervisors and memory
A type 1 hypervisor runs directly on the hardware (ESXi, Xen, Hyper-V, KVM built into the Linux kernel); a type 2 one runs as an application on a host operating system (VirtualBox).

Memory requires a two-level translation: the guest translates virtual addresses into “guest physical” addresses, and the hypervisor translates these into real physical addresses. Modern processors do both in hardware with nested page tables (EPT, NPT).
Theorem. With
-level tables in the guest and
-level tables in the hypervisor, a TLB miss can require up to
memory accesses.
Proof. The guest translation reads
table entries, and then there is the final data address:
guest physical addresses in all, each to be translated with the hypervisor’s table, which requires
reads. Add the
reads of the guest entries themselves (the final data access is not counted, since it is there even without virtualisation). Total
. ∎
Example. With four levels in both,
accesses instead of 4: this is why the TLB and page-table entry caches are even more important in virtual machines, and why huge pages pay off.
Containers
A container does not virtualise the hardware but the operating system: applications share a single kernel, which gives each group of processes a separate view of resources with namespaces (processes, network, file system, users) and limits their consumption with control groups (cgroups: CPU, memory, input and output). A container starts in fractions of a second and occupies only the application’s memory; an image (Docker, Podman) packages the application with all its libraries and runs the same everywhere. The price is weaker isolation: a flaw in the shared kernel exposes all containers, whereas a virtual machine has its own kernel. This is why in public cloud services the containers of different customers often run inside lightweight virtual machines.
Security principles
- Least privilege: every program has only the permissions it needs; a network service does not run as administrator.
- Defence in depth: several independent barriers, because each can have flaws.
- Protection against exploitation of memory errors: non-executable data pages (NX bit), address space layout randomisation (ASLR), which makes addresses unpredictable to anyone trying to hijack the program, canary values on the stack.
- Updates: most successful attacks exploit vulnerabilities that are already known and fixed, but not installed.
∑Formula sheet
CPU scheduling
Estimating the future
![]()
Memory management
The cost of a page fault
![]()
File systems
The inode
![]()
Real-time systems
Rate monotonic priority and response time
![]()
![Rendered by QuickLaTeX.com \[ R_i = C_i + \sum_{j}\left\lceil\frac{R_i}{T_j}\right\rceil C_j \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-5bca40fbeedd58f9e9bb0696127bdf0a_l3.png)