Previous: Parallel Programming Reading map Next: Programming Paradigms
Volume II: Systems Programming (Chapter 8)Code & tests Chapter diagrams Download editable SVGs
The kernel manages processor time, protected memory, and hardware operations.
Chapter Map
what happens inside the kernel
it is too difficult to actually write something useful for the kernel
it is useful to at least have a high-level understanding of kernel
| Mode | What runs there |
|---|---|
| User | Application code; only permitted memory and operations |
| Kernel | Trusted handlers; memory protection, scheduling, and devices |
kernel starts earlier than other processes and works in privileged mode; it launches other programs in limited mode kernel mode configures special handlers for: interrupts exceptions syscalls in which cases program continues in kernel mode limited mode can only modify memory allocated to it; everything else requires access to kernel
no user code could ever be executed in privileged mode; only kernel code could be executed in privileged mode within a process as a
scheduling unit while preserving MMU configuration this happens upon:
exceptions syscalls return to process
kernel has 2 main purposes: manage processes: launching, stopping scheduling memory management process interactions process permissions manage devices abstractions coordination
kernel does not have to be monolithic some parts could be processes only in user mode in kernel mode
Syscalls, exceptions, and interrupts enter predefined kernel handlers. Longer work can be deferred to an appropriate context:
| Context | Typical work | May sleep? |
|---|---|---|
| Hard interrupt | Save urgent state and acknowledge the device | No |
| Softirq / tasklet | Deferred work in atomic context | No |
| Kernel thread | Scheduled work, including threaded workqueues | Where permitted |
after launching, kernel does not do anything "from it's own will"; it only responds to user requests if there are no user tasks it can become idle if there are no tasks in the system it can even turn off
userspace tasks often need something from kernel; in this case kernel responds to requests same for interrupts that might not happen immediately but kernel still responds to actions here not initiates them
in all of these cases interrupts exceptions syscalls control passes over to kernel code in privileged mode via predefined addresses of procedures-handlers
during exceptions and syscalls the process continues in privileged mode as process from scheduler's perspective
interrupt happen asynchronously, so there might not even be another process
interrupt handlers have limited capability of blocking other interrupts until the information about the original interrupt is saved properly and the interrupts are unblocked
sometimes there is no need for unblocking because the interrupt handler finishes extremely fast i.e. timer interrupts without scheduler and the unblocking happens automatically when the process continues
it gets more complicated in case interrupt handler does not finish that fast
because of multicore processors and no ability of being blocked (interrupt handlers are not scheduling units) we need to use active waiting to handle critical sections
kernel implements more than 10 techniques for mutual exclusions. programmer should not use mutexes designed for interrupts in processes and vice verse.
sometimes as result of interrupt, we need to switch process kernel saves context of the current process, then restores context of another process
sometimes interrupt handlers are complex enough that need to be executed as scheduling unit, but could not be related to the context of any of the processes
top half: interrupt handler executed during interrupt block bottom half: longer processes
bottom half: tasklets and workqueues tasklets: no interrupt blocking, not scheduling unit, on the same processor, executed immediately or on the next time interval workqueue: scheduling unit with pid, can be delayed more than tasklet
init process with id 1 is being executed during the whole lifecycle of operating system. it becomes parent for orphan child processes
init is the last stage of operating system launching
when init process is stopped the whole system stops
Clarification. An idle CPU waits for events; lack of runnable tasks does not normally shut down the OS. Kernel threads can initiate deferred or periodic work. Tasklets cannot sleep; threaded workqueues run work in worker threads, while BH workqueues remain in atomic context.
SIGTERM), then forces
remaining tasks to exit (SIGKILL) before finishing storage
cleanup.ROM (read-only memory) is similar to RAM but its data can only be read and the data is not erased upon power off. It is used to boot system.
ROM was built as PROM (programmable ... ) -> EPROM (erasable ... ) -> EEPROM (electrically ... )
system boots from a program stored in ROM (address 0xFFFFFFF0 on i386 in real 16-bit mode no memory protection and [non-]privilege modes,; it is switched into protected mode later by kernel (in the case of BIOS) by advanced loader (UEFI))
BIOS (basic input-output system) UEFI (unified extensible firmware interface) ROW saves configuration of how to load BIOS or UEFI program in ROM determines the boot device BIOS: passes control to boot sector UEFI: finds special sector with particular executable and loads it, it can also boot in the same way as BIOS
BIOS: boot sector is only 512 bytes, thus its purpose is to load more complicated program (bootloader of operating system) UEFI: directly loads bootloader
bootloader boots the kernel, which: loads its subsystems including drivers mounts root file system in read-only mode launches process 0, which forks process 1 and terminates process 1 launches init with execve
init: checking disks remounts root file system with read/write and
mount other file systems launching other OS subsystems including:
network interfaces launches system daemons launches getty, which:
creates a session performs login launches command line interpreter
because init is quite complicated, most functionality is performed via scripts: /etc
restart or poweroff is also performed through init via scripts: SIGTERM SIGKILL unmount all file systems apart from the root one sync buffers remount root as read-only
Clarification. Boot order depends on the platform. UEFI loads an executable from a filesystem, not a special boot sector. The kernel starts PID 1; the process-0/fork/exit sequence is not a portable Unix rule.
firmware -> boot loader -> kernel -> root filesystem -> PID 1 -> services / login
shutdown -> stop tasks -> flush buffers -> unmount -> power off
| Subsystem | Builds on |
|---|---|
| Processes | Interrupts, scheduler, synchronization |
| Memory | MMU, frames, mappings, reclamation |
| Storage | Drivers, block requests, filesystems |
| Networking | Interface drivers, protocols, sockets |
Kernel is designed as separate layers distinguished by proximity to hardware. The further away from the hardware, the higher the abstraction.
The lowest layer includes: drivers interrupt handler others hardware-specific components Some part of it is usually written in assembly.
Memory subsystem consists of: hardware layer interacting with MMU of particular CPU tracking, allocation and freeing of physical memory frames abstraction of physical memory allocation for kernel and processes disk storage mapping (mmap) Both virtual memory management and virtual file systems need other lower-level systems: virtual memory needs swapping virtual file systems needs disks, sometimes networking
Storage: disk controllers and interrupt handlers abstraction of block device, planning of disk operations virtual file system and swapping subsystem Virtual file system also needs implementation of actual file systems
Networking: network card drivers and interrupt handlers abstraction of network interface implementations of network protocols family of protocols sockets Scheduler: programming of interrupt handlers and interrupt handlers themselves including timer scheduler of kernel threads blocking of critical sections including mutexes userspace threads management of processes: fork, execve, wait, _exit
Main kernel subsystems: hardware level including drivers and interrupt handlers process management and scheduler memory storage networking
| Mechanism | Main idea |
|---|---|
| Virtual machine | Guest kernel runs under a hypervisor |
| Emulation | Simulate a machine, possibly a different instruction set |
| API / ABI compatibility | Implement another system's application interface, as Wine does |
| Container | Isolate processes while sharing the host kernel |
we can emulate a computer by running guest code in a restricted mode, intercepting privileged instructions and protected memory, and simulating their effects.
hypervisor (Xen, KVM (Kernel Virtual Machine) for Linux) can load operating systems as its processes, or; it can be part of a host operating system that loads its guest operating systems
trap and emulate technique did not work originally on i386: POPF behaved differently in privileged and limited modes and did not raise exceptions i386 could understand that it is in limited mode from segment registers
MMU configuration is done by modifying memory in privileged mode, but when emulated system tries to do that it just modified its process memory. That can be fixed my slightly modifying machine code of the guest kernel
In 2006 both amd and intel added support for virtualization at hardware level.
systems can also be emulated via interpretation (DOSBox, Atari, Commodore-64) of machine code, this way no need from the operating system, but it is much slower
WINE is something in between virtualization and interpretation, calls to WinAPI is replaced by function that refer to UNIX syscalls Executing .exe in WINE is achieved via modification of binary code
QEMU uses both virtualization and interpretation so that it can emulate different platforms and get speed benefits when possible
Paravirtualization is achieved by modifying the kernel of guest operating systems or installing special drivers to efficiently interact with hypervisor on the host operating system
Containers (OpenVZ, LXC) work inside host operating system without its own kernel. Host operating system can see process inside containers and its file tree, but the containers cannot see host processes and file tree.
VPS can be created with virtualization or containers. Containers improve efficiency of resource usage, because they don't need separate kernel.
Clarification. These are historical examples. Wine implements Windows APIs/ABIs; it is not a halfway form of hardware virtualization and does not generally require rewriting the application binary. Hardware-assisted x86 virtualization appeared in the mid-2000s.
Program view: code, data, heap, and stack.
Kernel view: memory mappings, permissions, descriptors, saved registers, and scheduling state.
execve replaces the program; the scheduler decides
when the task runs.
Threads share process resources but have separate execution contexts.
From a programmer perspective a process is: program code global data including heap and stack
From a kernel perspective a process is: allocated memory permissions table with file descriptors registers (execution context) when process is not being executed
To start a process (or replace with execve), an operating system has to allocate enough memory for: code, data, stack initialize code and data create execution context with initial values in registers _start address in instruction pointer initial value of stack pointer command line arguments and pointer to them other important registers
For each new process kernel has to: allocate and initialize memory configure MMU Then the process is ready to be executed and is included in the schedule Finally the scheduler decides when the process starts
Process can have 3 states: execution blocked ready The transition between states could look like: execution <-(scheduler)-> ready execution -(syscall)-> blocked execution -(swapping)-> blocked blocked -(interrupt handler)-> ready
Process is executed in kernel mode: on syscall on exceptions before returning back to user mode
Process can change state from execution to read without syscall, but vice verse is not true
If a process is blocked waiting for a syscall, required memory pages will not be swapped back in before the process becomes unblocked by the original syscall
Threads work in parallel within a process with the same shared memory From the scheduler perspective though, threads are almost like individual processes each with its own execution context
Clarification. A ready task resumes when the scheduler selects it, without making a new syscall. Page residency and I/O blocking are separate; modern kernels manage memory page by page. An interrupt need not resume the task it interrupted.
load program -> prepare memory and mappings -> set entry/stack/arguments -> ready
Context switch: save registers -> select task/address space -> restore registers.
| State | Meaning |
|---|---|
| Running | Executing on a CPU |
| Runnable | Ready, waiting for CPU time |
| Blocked | Waiting for an event; receives no time slice |
| Zombie | Exited; termination status awaits collection |
| Level | Decision |
|---|---|
| Long-term | Which jobs to admit; balance CPU- and I/O-bound work |
| Medium-term | Which memory or tasks to reclaim or suspend |
| Short-term | Which runnable task executes next |
SCHED_FIFO / SCHED_RR).In historical CFS, a red-black tree makes selection efficient; new and waking tasks are placed relative to the queue's current vruntime.
Scheduling policies can be compared directly. Each child process
selects a policy with sched_setscheduler and times the same
computation:
static void launch_processes(int num_processes, long lim)
{
int i, pid, policy, ret, actual;
long duration;
char *name;
struct sched_param param;
struct timespec start, end;
param.sched_priority = 0;
for (i = 0; i < num_processes; i++) {
pid = fork();
if (pid == -1)
err(1, "fork");
if (pid == 0) {
pid = getpid();
select_policy(i, &policy, &name, ¶m);
ret = sched_setscheduler(pid, policy, ¶m);
if (ret == -1)
err(1, "sched_setscheduler %d\n", i);
actual = sched_getscheduler(0);
printf("PID %d requested %d, actual %d\n", pid, policy, actual);
clock_gettime(CLOCK_MONOTONIC, &start);
some_random_computation(lim, 100);
clock_gettime(CLOCK_MONOTONIC, &end);
duration = (end.tv_sec - start.tv_sec) * 1000000000 +
(end.tv_nsec - start.tv_nsec);
printf("(PID %d) (i %d ) (policy %15s) (duration %ld)\n",
pid, i, name, duration);
exit(0);
}
}
}
Run on a single CPU, so that the processes compete for it. The
durations are wall-clock times: other and
batch share the CPU, while idle runs only when
nothing else wants it and finishes last. fifo and
round robin (processes 3 and 4) need root privileges.
$ taskset -c 0 ./sched 3 300000
PID 285919 requested 0, actual 0
PID 285920 requested 3, actual 3
PID 285921 requested 5, actual 5
(PID 285919) (i 0 ) (policy other) (duration 521352394)
(PID 285920) (i 1 ) (policy batch) (duration 520086020)
(PID 285921) (i 2 ) (policy idle) (duration 772161650)
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <sched.h>
#include <unistd.h>
#include <time.h>
#include <sys/wait.h>
static void select_policy(int i, int *policy, char **name,
struct sched_param *param)
{
switch (i) {
case 0:
*policy = SCHED_OTHER;
*name = "other";
break;
case 1:
*policy = SCHED_BATCH;
*name = "batch";
break;
case 2:
*policy = SCHED_IDLE;
*name = "idle";
break;
case 3:
*policy = SCHED_FIFO;
*name = "fifo";
param->sched_priority = 1;
break;
case 4:
*policy = SCHED_RR;
*name = "round robin";
param->sched_priority = 1;
break;
}
}
static void some_random_computation(int lim_i, int lim_j)
{
int i, j;
long x;
x = 11;
for (i = 0; i < lim_i; i++) {
for (j = 0; j < lim_j; j++) {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x *= 0x9E3779B97F4A7C15ULL;
x += 0xBF58476D1CE4E5B9ULL;
x ^= x >> 29;
}
}
}
static void launch_processes(int num_processes, long lim)
{
int i, pid, policy, ret, actual;
long duration;
char *name;
struct sched_param param;
struct timespec start, end;
param.sched_priority = 0;
for (i = 0; i < num_processes; i++) {
pid = fork();
if (pid == -1)
err(1, "fork");
if (pid == 0) {
pid = getpid();
select_policy(i, &policy, &name, ¶m);
ret = sched_setscheduler(pid, policy, ¶m);
if (ret == -1)
err(1, "sched_setscheduler %d\n", i);
actual = sched_getscheduler(0);
printf("PID %d requested %d, actual %d\n", pid, policy, actual);
clock_gettime(CLOCK_MONOTONIC, &start);
some_random_computation(lim, 100);
clock_gettime(CLOCK_MONOTONIC, &end);
duration = (end.tv_sec - start.tv_sec) * 1000000000 +
(end.tv_nsec - start.tv_nsec);
printf("(PID %d) (i %d ) (policy %15s) (duration %ld)\n",
pid, i, name, duration);
exit(0);
}
}
}
int main(int argc, char **argv)
{
int i, num_processes;
long lim;
if (argc < 3) {
fprintf(stderr, "Usage: %s <num processes> <max num iterations>\n",
argv[0]);
return 1;
}
num_processes = atoi(argv[1]);
lim = atoi(argv[2]);
launch_processes(num_processes, lim);
for (i = 0; i < num_processes; i++)
wait(NULL);
return 0;
}
3 levels of scheduling: long-term: decides when to execute a process mid-term: decides what memory to swap out this can block a process short-term: decides which processes shall be paused and resumed The following systems mainly use: Batch OS: mainly long-term scheduling Time-sharing OS: mainly short-term use mid-term scheduling indicates that system is working at its capacity
Tasks could be bound by: CPU I/O Good short-term scheduler should prioritize I/O bound tasks This will increase responsiveness of a system. Good long-term scheduler should have a balanced mix of CPU- and I/O-bound tasks.
Primitive short-term schedules without priorities include: round-robin:
cycles through ready each task and start the ready ones with equal time slices FIFO: ready tasks are in line, the first one gets executed first and then is placed last blocked tasks could be places first or last
Task priority is determined from static: defined by user dynamic:
increases while task is waiting from 0 to max when task is finally executed dynamic priority is 0 and priority of all other tasks increases by 1 Scheduler selects a task with the highest static+dynamic priority but it has to be extremely efficient because it is executed ~1000 times per second within a critical section without block with blocked interrupts
we can set scheduling policy for a process using sched_setscheduler:
SCHED_OTHER: default SCHED_RR and SCHED_FIFO: real-time higher priority than SCHED_OTHER you can set static priority no dynamic priority
SCHED_BATCH: batch mode, lower priority than SCHED_OTHER SCHED_IDLE:
lowest priority, executed only when there are no other processes
Modern systems use efficient algorithms such as CFS (Completely Fair Scheduler): performs calculation only when starting, resuming or stopping a task remember how long each process has been executing selects a process with the lowest time
Let's assume all processes start at the same time For each process we will have a variable (vruntime) that stores how long (nanoseconds) it has been executing. Since, we assumed all processes started at the same time, initially it is zero. Scheduler selects a process with the lowest vruntime and assigns a time slice based on processes priority (nice value) After the time slice has passed, the processes is replaced with another one with the lowest vruntime, while the current one's vruntime is increased by the time slice
Since time-slices are based on priorities there could be processes with vastly different vruntime, so it is important to efficiently find those with the lowest vruntime, for which scheduler uses red-and-black trees.
Processes with the lowest vruntime are on the left, after they are selected and replaced they usually move on the right and with this progression every process will be executed at some point.
To eliminate our assumption that all programs were started simultaneously we just have to replace 0 in vruntime upon program start with minimum current vruntime. Thus it is not really a time a program has been executing, but some constant + time a program has been executing.
For blocking processes if the current time is lower than min vruntime, then min vruntime is assigned, otherwise the current vruntime is being unchanged.
Clarification. CFS is the historical example here. Its vruntime accounts for priority-weighted CPU service, not simply elapsed runtime. Linux policies do not all use a static-plus-dynamic priority sum; SCHED_BATCH is a normal scheduling policy, and SCHED_IDLE is a very low-priority policy rather than a promise that every other task must be absent.
historical CFS: account priority-weighted vruntime -> choose least-served runnable task
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <sched.h>
#include <unistd.h>
#include <time.h>
#include <sys/wait.h>
static void select_policy(int i, int *policy, char **name,
struct sched_param *param)
{
switch (i) {
case 0:
*policy = SCHED_OTHER;
*name = "other";
break;
case 1:
*policy = SCHED_BATCH;
*name = "batch";
break;
case 2:
*policy = SCHED_IDLE;
*name = "idle";
break;
case 3:
*policy = SCHED_FIFO;
*name = "fifo";
param->sched_priority = 1;
break;
case 4:
*policy = SCHED_RR;
*name = "round robin";
param->sched_priority = 1;
break;
}
}
static void some_random_computation(int lim_i, int lim_j)
{
int i, j;
long x;
x = 11;
for (i = 0; i < lim_i; i++) {
for (j = 0; j < lim_j; j++) {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x *= 0x9E3779B97F4A7C15ULL;
x += 0xBF58476D1CE4E5B9ULL;
x ^= x >> 29;
}
}
}
static void launch_processes(int num_processes, long lim)
{
int i, pid, policy, ret, actual;
long duration;
char *name;
struct sched_param param;
struct timespec start, end;
param.sched_priority = 0;
for (i = 0; i < num_processes; i++) {
pid = fork();
if (pid == -1)
err(1, "fork");
if (pid == 0) {
pid = getpid();
select_policy(i, &policy, &name, ¶m);
ret = sched_setscheduler(pid, policy, ¶m);
if (ret == -1)
err(1, "sched_setscheduler %d\n", i);
actual = sched_getscheduler(0);
printf("PID %d requested %d, actual %d\n", pid, policy, actual);
clock_gettime(CLOCK_MONOTONIC, &start);
some_random_computation(lim, 100);
clock_gettime(CLOCK_MONOTONIC, &end);
duration = (end.tv_sec - start.tv_sec) * 1000000000 +
(end.tv_nsec - start.tv_nsec);
printf("(PID %d) (i %d ) (policy %15s) (duration %ld)\n",
pid, i, name, duration);
exit(0);
}
}
}
int main(int argc, char **argv)
{
int i, num_processes;
long lim;
if (argc < 3) {
fprintf(stderr, "Usage: %s <num processes> <max num iterations>\n",
argv[0]);
return 1;
}
num_processes = atoi(argv[1]);
lim = atoi(argv[2]);
launch_processes(num_processes, lim);
for (i = 0; i < num_processes; i++)
wait(NULL);
return 0;
}
EINTR or restart.setjmp saves a return context; longjmp
returns there while its calling function is still active. It does not
undo side effects or release resources.sigsetjmp / siglongjmp can also
save/restore the signal mask. Jumping out of a handler cannot repair
interrupted library state.Processes do not know when a signal handler could be called, on the contrary to kernel.
If a process got a signal, the signal handler gets called when the process switches from kernel to user modes, which happens when process returns from ready state to execution syscall interrupt
When switching from kernel to user mode and there is a signal: the kernel modified the stack frame of the process with the signal handler at the top with return address of machine code that just calls sigreturn, which: restores original state of the stack restores signal masks other cleanups
It just modifies instruction pointer to point to the address of signal handler, which when done eventually returns to sigreturn. Kernel then again checks for new signals when returns from sigreturn.
Signal arrival is noticed by raising the relevant flag, which is reset to zero upon calling signal handler. However, if the flag is already raised, all the arrived signals will be ignored until the flag is reset (returning from kernel to userspace).
This also explains why blocking syscalls are interrupted by signals: to handle a signal we have to return from kernel to userspace, thus interrupting the blocking syscall
c int setjmp(jmp_buf env); void longjmp(jmp_buf env, int val); setjmp:
macro that saves EIP and ESP; returns 0 jmp_buf: array; that is why there is no need for the address-of operator env: is valid until returning from the function where it has been called, thus we can use it in longjmp from any subfunction longjmp: uses env saved in setjmp and some non-zero number in val to return to the location of setjmp while returning val. It restores EIP and ESP, but modifications to global variables and other side effects are not undone.
the functions are implements by: setjmp: 0 -> EAX ESP and EIP -> env longjmp: val -> EAX ESP and EIP <- env returns from setjmp with val in EAX instead of 0
for long jumps from inside the signal handler, there are similar functions: int sigsetjmp(sigjmp_buf env, int savesigs); int siglongjmp(sigjmp_buf env, int val); savesigs: non-zero value saves current signal mask then siglongjmp with restore signal mask before jumping siglongjmp: no call to sigreturn in this case
readline library specifies that we can use siglongjmp to process Ctrl-C (jumping out of the library functions)
Clarification. Ordinary signals may coalesce; queued signals differ. A syscall can restart instead of returning EINTR. setjmp saves the context needed for a non-local return, not just two registers; siglongjmp returns void. A jump cannot repair interrupted library state or release resources automatically.
return toward user mode -> check pending signals, mask, and disposition
caught signal -> prepare user stack/IP -> handler -> sigreturn restores context/mask
The MMU translates addresses; the kernel configures and manages the mappings.
UNIX kernel has memory management subsystem to manage memory of multiple processes in a system. Hardware running multitasking OS should have memory protection. Usually CPU has MMU (memory management unit) so that programs can work with virtual addresses instead of the physical ones. Memory protection and configuration of MMU is kernel's job.
| Problem | Main mechanism |
|---|---|
| Protection | Per-process permissions |
| Relocation | Virtual-to-physical translation |
| Duplication | Shared mappings |
| Limited RAM | Demand paging, reclamation, swapping |
| Fragmentation | Place virtual pages in separate physical frames |
memory protection: process-process, kernel-process not enough memory:
swapping, can slow down processes data duplication: starting copies of the same program code portability: hard-coded absolute physical memory addresses can create problems when that specific physical memory is taken, that is why we need MMU fragmentation: there could be enough memory for a new process but it is spread out through different areas within RAM, also running task might need more memory, but the adjacent memory is already taken by another process
Most of these problems appear only in multitasking operating systems:
there is only 1 process: memory protection, data duplication we can use the same physical memory: code portability, fragmentation not enough memory: we can use overlays, load into memory only parts of program we need at the moment
The kernel configures the MMU per address space. Virtual addresses stay stable when physical placement changes.
| Access without a resident mapping | Kernel response |
|---|---|
| Invalid address | Report an error, commonly SIGSEGV |
| Permitted stack growth | Allocate within the mapping and its limits |
| Swapped-out data | Block, load contents, update mapping, resume |
Virtual memory includes protection and relocation; swapping is only one use.
MMU is not required, but it: solves code portability when flexible enough simplifies: data duplication fragmentation protection Kernel configures MMU for each process You can even transfer part of a process into a different physical memory while modifying MMU Without MMU we can only swap out an entire process
Some virtual pages may not correspond to physical ones Access to such pages causes an exception initiated by MMU Kernel handles it depending on the situation: process never had such memory -> error: SIGSEGV, segmentation fault write access next to stack in stack-growing direction -> increase stack swapped-out memory: block process swap it back in resume process
Clarification. Virtual memory is broader than swapping. Stack growth is allowed only within valid mappings and limits. Relocation without an MMU can also be implemented in software; the whole-process rule describes the simple model used here.
if virtual_address >= region_size:
raise protection fault
else:
physical_address = base + virtual_address
base;
virtual addresses stay fixed. A task switch restores the selected task's
base, limit, and registers.CPU uses 2 registers: base limit for every memory access: physical address = virtual address + base if virtual address > limit: exception
base: start of process memory in physical RAM -> virtual memory addresses limit: size of memory available to the process -> process can only access its own memory area memory protection
process can be moved to another part of physical memory copy its data to the new location change base virtual addresses stay the same portability switching to another task: interrupt / exception / syscall kernel gets control changes base / limit restores EIP and other process state new task continues in user mode
limitations: not enough physical memory whole process may have to be swapped the problem of single task exceeds memory size is not solved fragmentation expensive copying of large segments duplication
Clarification. When limit is a region size, valid offsets satisfy address < limit: equality must fault. An inclusive upper-bound limit uses a different comparison.
several segments placed independently in physical memory -> (base, limit) pairs
address must specify: segment offset inside that segment x86 uses segment registers: CS, DS, ES, SS, FS, GS
segment descriptor contains information about a segment: base limit attributes address translation: segment selector -> find segment descriptor -> get segment base physical address = segment base + offset if offset > segment limit: exception
duplication common segments for different tasks not significant implication: +/- swapping: individual segments can be swapped separately +/- fragmentation: segments do not have to be next to each other -> easier to use fragmented free memory
in flat model if a large data structure grows -> the whole data structure next to it has to be moved this is solved in segment model
caching of segment descriptors to avoid excessive memory access saved in "hidden part of" CS, DS, ES, SS, FS, GS
Clarification. Segment limits may be inclusive, as on x86; the base-and-size model uses an exclusive upper bound. Variable-size segments still suffer external fragmentation.
segment selector -> descriptor (base, limit, permissions)
check offset and access -> translated address = base + offset
| Term | Meaning |
|---|---|
| Page | Fixed-size virtual-memory block |
| Frame | Equal-size physical-memory block |
| Page table | Page-to-frame mapping, permissions, and status |
| TLB | Cache of recent translations; avoids repeated table walks |
each process has: virtual address space tables for translation into physical addresses
frame: block in physical memory page : block in virtual memory page size = frame size lowest 12 bits in address are offset within page/frame highest are page/frame numbers
virtual pages can be placed in any free physical frames: -> do not have to be next to each other each process has its own translation table virtual page number -> page table -> physical frame and attributes, one of which says if the virtual page has corresponding physical frame in memory at the moment
page size selection: large pages: more unused space inside partially used pages small pages: more pages -> larger page tables 4 KB (2^12) is the most popular 2^20 > 10^6 number of pages with each row 4 bytes -> 4MB of page table for EVERY process this problem is solved via multilevel (2-3) pages: 2 10-bit groups specify location in tables of respective layers
fragmentation: any free physical frame can hold a page of any process limited physical memory capacity: individual pages can be swapped a
process can use more virtual memory than available physical RAM limit:
size of virtual address space available disk / swap space
drawbacks: unused space can remain in the last page / frame every memory access requires: access page directory access page table access actual memory = 2 additional memory accesses for address translation solved by TLB (Translation Lookaside Buffer) TLB: caches recently used translations: virtual page number -> physical frame number + attributes uses associative / parallel lookup
if translation is not found in TLB: get it from page tables cache it in TLB if TLB has no free entry: -> replace / erase one existing entry TLB usually contains from tens to thousands of entries -> enough to greatly reduce page-table accesses
when switching tasks: address space changes TLB entries from previous task may no longer be valid TLB is flushed / replaced
software-managed TLB: OS takes care of page-table data structures (vs CPU) flexibility TLB miss causes an exception OS handles the miss and updates the TLB TLB miss is more expensive
Clarification. The 4 KiB, 32-bit, two-level layout is the classic i386 example. A TLB miss is distinct from a page fault, and address-space tags can preserve translations across task switches.
classic i386, 4 KiB pages: 10 directory bits + 10 table bits + 12 offset bits
virtual page + offset -> page tables -> physical frame + unchanged offset
| Fault | Response |
|---|---|
| Invalid or forbidden address | Report an error, commonly SIGSEGV |
| Valid but absent page | Allocate or load a frame, update mapping, retry |
| Copy-on-write | Make a private writable copy |
fork can share unchanged pages until a write requires a
copy.| Smaller pages | Larger pages |
|---|---|
| Less waste; finer protection and reclamation | Fewer entries; more coverage per TLB entry |
| More translation and bookkeeping overhead | More internal fragmentation; coarser page movement |
A flat i386 setup uses base-zero code/data segments and relies mainly on paging.
segmentation: multidimensional address space segment-paging model:
double address conversion: segment part of address via segment descriptor -> flat virtual flat virtual address via page table -> physical frame / address each process has its own paged virtual address space segments can be organized inside it
disadvantages: tied to i386 / x86 architecture complicated not portable to other CPUs on i386, segmentation is usually flat: segment base = 0 segment limit = full address space segment registers do not need to be changed
Clarification. This is the conventional flat i386 model. Some segment registers still have specialized uses; segmentation details vary across x86 modes.
logical address -> segment translation -> linear address -> paging -> physical address
read / write; signals and shared memory are
traditionally treated separately.| Operation | Kernel path | Hardware I/O? |
|---|---|---|
./hello > file1 |
Filesystem and cache | Later, for a disk file |
./hello | ./prog2 |
Pipe buffer | Can remain in RAM |
hardware perspective: CPU + RAM are treated as one unit I/O = exchange of information between: CPU + RAM <-> external devices CPU <-> RAM communication is not considered I/O
the same program may or may not cause hardware I/O: ./hello > file1 output is written to disk hardware I/O occurs ./hello | ./prog2 output of hello is passed to prog2 interaction may stay entirely in CPU + RAM no hardware I/O
programmer's perspective: I/O = exchange of information through I/O streams typically using: read / write actual access to an external device is not required
not every exchange of information with a process is considered I/O:
signals, shared memory are traditionally not considered I/O
Clarification. The redirected file example assumes a disk filesystem. Buffering can delay its physical write; a pipe can remain entirely in RAM.
| Component | Role |
|---|---|
| Driver | CPU-executed software implementing controller commands |
| Controller | Hardware exposing registers and possibly a device-local buffer |
| Port I/O | Separate address space; x86 IN / OUT |
| Memory-mapped I/O | Device regions accessed through the physical memory address space |
CPU communicates with external devices through controllers: CPU <-> bus
<-> controller <-> device controllers provide a uniform bus interface:
hide device-specific details from CPU from CPU's perspective, devices differ only by port addresses devices created after the CPU can still be connected provided their controllers are compatible with the bus
controller has two sides: CPU side: connects to the common bus exchanges numerical values with CPU device side: connects directly to the device it was designed for generates the electrical signals needed to control it driver: software executed by CPU specifies how to interact with a particular controller CPU does not need built-in knowledge of each device
many controllers can be connected to the bus at once CPU needs to identify which controller to communicate with I/O ports: each port has an address representable on the bus each controller has one or more ports ports can be read-only, write-only or both
I/O ports resemble memory locations: CPU accesses them through read / write operations on some architectures, they share RAM's physical address space then the same instructions can access both ports and RAM but their meaning differs from ordinary memory access: write: can send a command specifying what the device should do read: can return information about the device's current state reading a port need not return the value previously written
some controllers also have I/O buffers: RAM built into the controller used to exchange blocks of data between CPU and controller writing to disk: copy data into the controller's buffer send a write command through an I/O port controller writes the buffered data to disk reading from disk: controller places data from disk into its buffer copy data from the buffer into main RAM video memory (VRAM): another example of an I/O buffer stores the image shown on the display
separate address spaces: I/O ports have their own address space, separate from RAM port addresses usually use fewer bits than memory addresses separate CPU instructions, for example: IN / OUT for I/O ports MOV for memory
shared address space: I/O ports share the same physical address space
as RAM ordinary memory-access instructions for both, e.g. MOV example:
PDP-11 advantages: I/O regions can be mapped into a process's virtual address space direct device access without a syscall for every operation makes it easier to implement drivers in userspace drivers can use high-level languages supporting pointers no assembly inserts needed for port access disadvantages: I/O ports occupy part of the limited memory address space address regions for ports / buffers must be explicitly excluded from caching using one common bus for RAM and controllers can be difficult their optimal data-bus widths can differ using two separate buses with one shared address space requires a decision about which bus handles each address
combined approach: i386 example: I/O ports are in a separate address space I/O buffers share the physical address space with RAM
Clarification. A uniform bus interface does not mean controllers differ only by address: their protocols and ordering rules differ too. Memory-mapped registers require appropriate cache attributes and kernel I/O primitives.
CPU <-> bus <-> controller <-> device
/* The kernel dispatches common operations through driver function pointers. */
struct device_ops {
int (*read)(struct device *dev, void *dst, int count);
int (*write)(struct device *dev, const void *src, int count);
};
driver: software component for controlling a hardware device provides abstraction provides operations that allow device control without knowing hardware-specific details
driver is usually a collection of functions, not a standalone program mainly called by other parts of the kernel resembles a library in structure kernel is the program that works with hardware devices via drivers drivers usually become part of the kernel when loaded
device-specific details are hidden inside the driver other kernel subsystems call its operations / entry points: externally accessible driver functions same interface for drivers of the same category example: HDD and USB flash drive request from the rest of the kernel can look the same actual hardware operations can be completely different -> abstraction
drivers usually run in kernel mode privileged operations may be needed to access device controllers user-space alternative: driver runs as a regular process requests hardware access through syscalls kernel performs required operations and returns results extra context switches reduce efficiency
3 ways drivers can be included / loaded: built-in driver: compiled directly into kernel adding / removing it requires kernel rebuild + reboot requires kernel source code or object modules + corresponding interface files traditional Unix approach module loaded at boot: driver is stored as a separate kernel module system configuration determines which modules are loaded kernel loads them during boot no kernel rebuild required traditionally used by Windows / MS-DOS loadable kernel module (LKM): can be loaded into an already running kernel no reboot required module file must follow required kernel conventions loaded through kernel module-loading mechanism becomes part of kernel unused modules can usually be unloaded flexibility Drawback: security risk privileged user can load arbitrary kernel code
driver interface: set of operations / entry points provided by driver drivers for different devices can implement the same interface -> abstraction kernel calls these operations through function pointers driver usually registers an operations structure: sometimes an array of function pointers usually structure containing function pointers
one interface cannot cover all device types OS supports several device classes: each class defines a fixed set of operations corresponding drivers must implement those operations
virtual devices: implement the required device interface no corresponding physical hardware functionality is implemented in software example: RAM disk driver allocates RAM emulates disk sectors in this RAM write: copies data into RAM read: copies data from RAM can be read, written, formatted and mounted like a real disk
logical devices: abstraction layer built on top of physical devices and their drivers represent underlying devices in a different logical form example: disk partitions one physical disk can be divided into several partitions each partition appears as a separate logical block device physical disk itself remains the same
RAID (Redundant Array of Independent Disks): one logical block device can be built on top of multiple physical disks loop device: ordinary file presented as a logical block device useful for accessing files inside a disk image no need to write image to CD / DVD / USB drive
all devices accessible to user programs through syscalls are logical devices even when logical representation matches physical device almost exactly
"driver" can refer to: driver controlling a physical device kernel component implementing a logical device both provide operations called by other kernel subsystems set of operations = driver interface classic Unix device types: character devices block devices each type has a different driver interface: fixed set of operations required for that type drivers of the same type implement the same interface Linux also supports network interfaces: not represented as ordinary device files use a different driver interface
FreeBSD: no separate block-device category block-device writes may be buffered in kernel memory data may remain there before reaching physical disk program does not directly control when buffered data reaches disk some character-device drivers support lseek positioning is possible without a separate block-device interface Linux: O_DIRECT can bypass the page cache
Virtual File System (VFS): allows mounting filesystems without an
underlying device physical virtual logical filesystem implementation:
fixed set of operations similar to driver entry points ordinary filesystems implement them using data structures on disk the same interface can be implemented in other ways
physical and virtual devices occupy the same architectural level virtual devices imitate physical devices logical devices / abstractions can be built on top of either
pseudo-devices: /dev/null, /dev/zero, /dev/full, /dev/random character devices no corresponding physical hardware could be called logical (more appropriate) / virtual devices
Clarification. The physical/virtual/logical labels describe layers, and their use varies by OS. Direct I/O can bypass a page cache without guaranteeing durable storage.
Computing system: computer + all programs running on it. Each layer translates requests into terms of the next lower layer: text user | prog > f1.txt program | printf("Hello, world"); system library syscall interface | write(1, "Hello, world", 12); virtual file system (OS) | sde1, sector 127563 logical-device level (OS) | SCSI/5:1:0, cylinder 125, head 8, sector 20 physical-device driver (OS) | control codes hardware / controller Moving toward the user: more abstraction, simpler descriptions. VFS handles write using the open-file object referenced by the descriptor.
disk geometry visible to OS can differ from physical geometry physical geometry: inner tracks contain fewer sectors than outer tracks keeps
recording density approximately constant OS-visible / virtual geometry:
fixed numbers of heads, cylinders and sectors per track controller translates between virtual and physical geometry hardware itself can contain several abstraction layers
controller connected to the computer bus may communicate with the disk through another hardware interface / bus: another controller (SATA) can be located directly on the disk connection: computer bus <-> host-side controller <-> disk interface / bus
Clarification. CHS is historical. Modern storage interfaces usually expose logical block addresses (LBA), while the controller handles physical placement.
printf("Hello, world") -> write(1, ..., 12)
-> VFS/filesystem -> logical device block -> driver commands -> controller
| Waiting method | Trade-off |
|---|---|
| Polling | Repeatedly check status; useful for very short waits |
| Interrupt | Let other work run; handle completion when notified |
Interrupt handlers work with the driver; they can report completion or device availability. The scheduler decides when a ready task actually runs.
after driver starts an I/O operation by writing to controller ports:
operation takes some time 2 ways to wait: active waiting: driver repeatedly reads controller port / status CPU does no useful work until operation finishes interrupt-driven I/O: driver sets up / uses an interrupt handler and returns requesting process can be blocked CPU runs another process or becomes idle when device finishes -> controller sends interrupt request interrupt handler gives control back to driver
driver completes operation / gets results waiting process may change:
blocked -> ready active waiting can be better when response is extremely fast polling can cost less CPU time than setting up and processing an interrupt e.g. checking whether a network cable is connected
I/O organization levels: text user software | device-independent OS components (OS) | physical-device drivers (OS) | interrupt handlers (OS) | hardware Physical-device driver: directly starts operations through I/O ports and reads results from the controller. Interrupt handlers: Not really a completely independent layer. Tell the driver when operation results are ready. Can also report that a device became available, allowing the next operation to start.
blocking I/O: submit -> task blocks; CPU runs other work or idles
completion: interrupt -> driver handles result -> waiting task becomes ready
| Mechanism | Benefit |
|---|---|
| Kernel I/O buffer | Keep transfer data available independently of process memory residency |
| Queued output | Reorder nearby disk requests without involving the CPU scheduler |
| Cache / merged updates | Reuse reads and combine writes to reduce physical I/O |
| Character-device buffers | Accumulate input; let output and program execution overlap |
fsync, fdatasync, msync, and
sync request propagation of buffered data. Durability also
depends on device caches and their guarantees; shutdown flushes buffers
before power-off.several processes may request I/O on the same device process A starts a disk write and becomes blocked CPU runs process B B requests a write to the same disk controller is still processing A's request -> B's operation cannot start immediately simple approach: block B until controller becomes available then start B's operation
processing requests in arrival order can cause unnecessary head
movement A: write to last cylinders B: write to first cylinders C:
write to last cylinders head movement: last cylinders -> first cylinders -> last cylinders repeated back-and-forth movement reduces performance
processing C before B could reduce head movement waking C before B would require CPU scheduler to know how to optimize requests for this device device-specific knowledge should remain inside drivers -> CPU scheduler should not depend on these details
reading directly into process memory can create a circular dependency:
process A is blocked waiting for a disk read requested data becomes available in controller buffer destination pages in A's memory may be swapped out swap area may be on the same disk problem: to empty controller buffer into A's memory, its pages must be loaded to load those pages, the same controller must first become available -> circular dependency solution: copy data into a kernel I/O buffer temporary storage in main RAM separate from the controller's own buffer
buffered output: upper kernel layer copies data into a buffer driver retrieves it later and writes it to disk driver determines the order of physical writes buffers for adjacent disk regions can be processed together regardless of request arrival order
buffering can reduce the number of physical I/O operations example:
process A requests a write -> data stored in buffer process B reads the same data -> supplied from buffer no physical disk read needed B modifies the data and requests a write -> same buffer updated if A's data has not yet been written to disk: driver writes only the latest version -> one physical write instead of two fewer physical operations improved performance, especially for frequent updates to filesystem metadata / global filesystem parameters
I/O buffering for character devices: input: accumulates incoming data before passing it to process delivers accumulated data in one syscall fewer syscalls than reading many small portions separately retains data
when process is not ready to read or its memory is swapped out output:
process can continue without waiting for physical output
kernel I/O buffers: stored in kernel memory that cannot be swapped out
consume physical RAM -> total buffer capacity is limited disk buffers:
can be discarded to free up memory cannot be discarded while holding data not yet written to disk when output buffers are full: write may block until buffered data is written and buffer space becomes available input buffer overflow: incoming data accumulates faster than process reads it data may be lost connection may be interrupted
I/O buffer management: traditionally handled by logical-device drivers character-device buffers are usually still managed this way Linux page cache: originally used to track physical pages and their use by processes tracks file-backed pages mapped through mmap changes to these pages must eventually be written to disk combines physical-memory management, disk I/O buffering and swapping uses free physical pages to cache disk data releases cached pages when memory is needed elsewhere
is handled by VFS
output modes: synchronous: process waits until the physical write finishes write errors can be reported before returning to the process more reliable asynchronous: process continues after data is copied into a kernel buffer physical write happens later more efficient: process does not wait for physical output process may finish before a write error becomes known Unix filesystems: synchronous / asynchronous operation can be selected through mount options shutdown: buffered data must be written before power is switched off unexpected power loss can cause data loss / filesystem corruption logical damage, even if physical hardware remains intact forced synchronization: requests that buffered data be written to disk fsync / fdatasync / sync msync for memory mappings created with mmap hardware limitation: disk controller may have its own cache outside software control synchronization cannot provide an unconditional guarantee that data has physically reached the disk
Clarification. Here "asynchronous" describes delayed writeback, which differs from an asynchronous I/O API. Active transfer buffers must remain available; clean cached pages can be reclaimed. Durability depends on the requested synchronization and the device contract.
| Policy | Selection rule | Main trade-off |
|---|---|---|
| FIFO / FCFS | Arrival order | Simple; may cause long seeks |
| SSTF | Nearest request | Efficient; distant requests may starve |
| LOOK / elevator | Sweep in both directions | Prevents indefinite postponement in the model; waits vary |
| Circular elevator | Serve in one direction, then return | More even waits; return travel costs time |
| Hybrid / anticipatory | Mix policies or briefly wait for a nearby request | Balance throughput and waiting time |
| Historical CFQ | Give processes I/O time slices | Favor synchronous requests and share service time |
system needs disk I/O when: a user process requests a read / write a process accesses a page that must be brought back from swap if controller is available: operation can start immediately if controller is busy: request is placed in a queue several requests may accumulate before controller becomes available
simplest strategy: FIFO / FCFS (First Come, First Served) process requests in arrival order USB flash drives, SSDs, network disks
HDD requests can be reordered to reduce head movement consecutive requests in a FIFO queue may target distant disk regions serving a nearby request first can avoid unnecessary backtracking -> improved performance
scheduling strategy: rule for selecting the next queued request shortest seek time first (SSTF): select request requiring the least head movement time greedy strategy: choose the best immediate option efficient, but can cause starvation nearby requests keep being selected requests for distant tracks may wait indefinitely elevator algorithm (LOOK): move head in one direction, serving requests along the way reverse direction after the last requested track in that direction repeat in the opposite direction avoids starvation waiting times can vary considerably request just behind the head must wait for its return sequential requests toward higher track numbers can wait longer while
head is moving toward lower track numbers circular elevator algorithm:
serve requests only from lower to higher track numbers after the highest requested track, return to the beginning start another sweep toward higher track numbers more evenly distributed waiting times the return to the beginning is usually very fast
modified scheduling strategies: use greedy strategy (SSTF) for at most N requests then select the next request using the elevator algorithm
efficiency close to SSTF, without starvation anticipatory scheduling:
pause briefly before a large head movement another request may arrive for the same or next track -> large head movement may be avoided
Completely Fair Queuing (CFQ): historical Linux I/O scheduler separates synchronous and asynchronous requests prioritizes synchronous requests, e.g. reads requesting process cannot continue until operation finishes each process receives a time slice for servicing its disk requests other processes' requests wait during that interval
disk scheduler works with the virtual geometry presented by controller does not know the actual physical geometry cannot determine exact physical head-movement distances limits how accurately scheduling can optimize physical head movement
Clarification. The head-movement policies describe rotating disks. FIFO is a simple strategy, not a requirement for SSDs or network storage. The circular return still takes time; starvation claims assume requests finish and the device keeps making progress. CFQ is a historical Linux scheduler.
| Filesystem example | What files represent |
|---|---|
| Disk filesystem | Persistently stored names, metadata, and contents |
tmpfs |
Temporary data in memory, with optional swap and size limits |
procfs / sysfs |
Process, device, and kernel information or controls |
Device filesystems / devpts |
Device nodes and pseudo-terminals |
| NFS / SMB | Files stored on another computer |
VFS: kernel subsystem supporting files as abstract objects file operations: open, read, write, close mmap / lseek where supported file properties: owner, group, access permissions timestamps number of hard links inode: stores file metadata, except the filename some file types require no disk storage beyond the inode filenames: stored in directories one file can have several names / hard links Unix file types: regular files directories symbolic links named pipes / FIFOs sockets character-device files block-device files
"filesystem" can mean: data structures organizing information on disk software functions that work with those structures Unix systems support different filesystem implementations different on-disk formats common file concepts and operations
root filesystem: its root directory corresponds to the system-wide / other filesystems: mounted at existing directories called mount points become part of the common directory tree mount points are usually empty directories existing contents are hidden while another filesystem is mounted there reappear after unmounting common directory tree can contain different filesystem types filesystems from other operating systems: do not use the same inode-based organization as Unix filesystems permissions may be absent or organized differently
filesystems without an underlying disk: different from a filesystem placed on a virtual / RAM disk implement file operations without disk data structures tmpfs: stores temporary files in memory no fixed disk size needs to be defined beforehand limited by available virtual memory: physical RAM + swap deleting files releases memory pseudo / synthetic filesystems: expose kernel information through files and directories interface for inspecting / controlling kernel subsystems read: obtain information write: change settings procfs: usually mounted
at /proc /proc/<pid>/ contains information about a process: exe:
symlink to executable cwd: symlink to current working directory fd:
symlinks for open file descriptors cmdline: command-line arguments maps: virtual-memory mappings Linux ps obtains process information from /proc can also expose kernel settings: echo "1" >
/proc/sys/net/ipv4/ip_forward -> enables IPv4 packet forwarding sysfs:
usually mounted at /sys information about connected devices and loaded kernel modules devfs: mounted at /dev provides device files for devices supported by kernel alternative: tmpfs at /dev, populated by udev device files are created by a user-space daemon devpts: mounted at /dev/pts provides pseudo-terminal device files network filesystems: NFS / smbfs present remote files as part of the local directory tree actual data is stored on another computer
Unix filesystem formats share common concepts: inodes superblocks directories other filesystem formats: e.g. vfat, NTFS, smbfs emulate the file abstractions expected by Unix pseudo filesystems: implement these abstractions without corresponding disk structures filesystem module: handles the specifics of its filesystem provides a fixed set of operations / entry points similar to a device driver
VFS coordinates filesystem implementations: mounts / unmounts filesystems maintains the common directory tree selects the appropriate filesystem module translates syscalls into calls to filesystem entry points handles file I/O syscalls creates and maintains I/O streams as kernel objects
Clarification. tmpfs has configurable
byte and inode limits; available RAM and swap are not its only limits.
Swap can also be disabled for a mount. See the Linux
tmpfs documentation. The device-filesystem examples in the notes
reflect different Unix systems and historical arrangements.
open: resolve path and mounts -> check permissions -> filesystem operations -> descriptor
| Structure | Stores |
|---|---|
| Superblock and its backups | Global filesystem information |
| Block group / free-block bitmap | Allocation region; one bit records whether a block is occupied |
| Inode table | Numbered file metadata and data-block mappings |
| Directory | Names mapped to inodes; multiple names allow hard links |
| Data / indirect blocks | File contents / pointers to other blocks |
on-disk data structures can differ considerably even between Unix-style filesystems some common principles still apply
physical sectors are grouped into filesystem blocks sector size:
usually 512 bytes block size: e.g. 4 KB, but can differ depends on filesystem; may be selected during formatting each block has its own number superblock: stores global information about the filesystem copies are stored in different disk locations
some blocks are reserved for inode tables filesystem may contain tens to thousands of inode areas each block in these areas contains several inodes inodes are numbered across the whole filesystem block groups, e.g. ext2-ext4: group of filesystem blocks superblock copy inode table free-block bitmap: each bit represents one block in the group 0: free 1: occupied
inode (index descriptor): typically 256 bytes; size depends on filesystem stores file metadata, not filename or contents filenames are stored in directories file contents are stored in data blocks inode records the numbers of blocks containing file data block-pointer layout: first entries point directly to data blocks final 3 entries point to indirect blocks: single indirect: contains data-block numbers double indirect: contains single-indirect block numbers triple indirect: contains double-indirect block numbers indirect blocks: store block numbers rather than file contents provide additional levels for locating a file's data blocks
example: ext2 with 4 KB (4096-byte) blocks inode contains 15 block pointers: 12 direct pointers 1 single-indirect pointer 1 double-indirect pointer 1 triple-indirect pointer each block number occupies 4 bytes one indirect block holds 4096 / 4 = 1024 block numbers direct blocks only: 12 * 4 KB = 48 KB files up to 48 KB need no indirect blocks with single indirect: 12 + 1024 = 1036 data blocks 1036
data blocks 1049612 * 4 KB > 4 GB with triple indirect: 12 + 1024 + 1024^2 + 1024^3 data blocks (12 + 1024 + 1024^2 + 1024^3) * 4 KB > 4 TB additional ext2 limit: inode contains a 32-bit number of 512-byte sectors 2^32 * 512 = 2^41 bytes -> file-size limit is about 2 TB
Clarification. The sizes and pointer layout are an ext2-style example, not universal filesystem rules. Here KB, GB, and TB in the source calculations mean KiB, GiB, and TiB. The pointer calculations count data capacity; metadata needs additional blocks. Superblock backups may exist only in selected block groups, and inode sizes vary. The diagram is schematic, not a literal block layout. See the Linux ext2 documentation.
directory entry -> inode -> direct blocks / indirect blocks -> file contents
Accessing RAM takes time. Caches reduce how often the CPU needs those transfers; DMA lets hardware move I/O data without a CPU copy loop.
| Mechanism | Role |
|---|---|
| Bus | Carries transfers; distance and response time contribute to latency |
| CPU cache | Keeps copies of memory blocks close to the CPU, often in several levels |
| DMA | Transfers data between memory and devices after the driver sets up the operation |
Cache policies determine what is kept and when writes propagate. DMA also needs suitable memory addresses and buffers; contiguous virtual memory can occupy scattered physical pages.
signal travel time depends on physical distance CPU chip is small; motherboard bus traces are much longer longer path -> longer signal propagation time bus frequency therefore cannot grow as easily as CPU frequency
example: bus length: about 25 cm request + response travel about 0.5 m even at speed of light -> theoretical limit about 600 MHz real bus must also allow time for components to respond -> actual frequency is lower if CPU had to access RAM constantly: much of its time would be spent waiting
cache: fast memory placed close to CPU reduces need to access slower RAM through shared bus 80286 could insert wait states while waiting for memory with larger CPU / RAM speed gap, many cycles could be wasted
how cache works: physical RAM is divided into equal-size blocks cache stores copies of some RAM blocks each cached block has a tag identifying its RAM block if required block is already cached -> use it if not: load whole block into cache possibly replace an existing block block transfers allow several bytes to be moved efficiently at once
cache writes: write-back: modify cache only mark block as dirty write it to RAM when block is removed write-through: update cache and RAM immediately
direct-mapped cache: RAM block n maps to cache block: n mod M where M = number of cache blocks if M = 2^k: index = lowest k bits of block number simple and fast disadvantage: different RAM blocks can map to same cache block they may repeatedly replace each other
multi-level cache: L1: smallest, fastest, closest to CPU core usually
private to each core often separate instruction + data caches L2:
larger and slower than L1 usually private to each core usually unified for instructions + data L3: much larger and slower usually shared
between cores example: L1: 32 KB instructions + 32 KB data per core L2:
256 KB per core L3: 8 MB shared
cache means CPU uses shared bus less often free bus time can be used for transfers between RAM and device controllers without DMA: driver starts I/O device works while CPU can run another task after interrupt, CPU still has to copy data between controller buffer and RAM
DMA (Direct Memory Access): lets hardware transfer data between RAM and device without CPU copying every byte was also useful in early computers because CPU could be slower than bus / memory IBM PC: used Intel 8237 DMA controller connected to shared bus had I/O ports for configuring transfers
without DMA: RAM -> CPU -> device port MOV: read byte from RAM OUT:
write byte to device port increment address decrement counter repeat with DMA: driver gives DMA controller: start RAM address amount of data transfer direction starts operation CPU does not copy every byte itself
ISA DMA channels: each channel has 2 control lines: DRQ: DMA request DACK: DMA acknowledgement fly-by mode: device sends DRQ when ready DMA controller responds with DACK DMA controller supplies RAM address + read / write signals actual data moves directly: device port <-> RAM DMA controller: increments RAM address counts remaining data stops when transfer is complete one data portion can be transferred in one bus cycle data does not pass through DMA controller itself
PCI changed the DMA model: central DMA controller was replaced by bus arbitration bus arbiter: does not transfer data decides which component may control the bus component currently controlling bus = bus master device controllers can perform DMA themselves example: disk read driver tells disk controller where in RAM to place data disk controller requests bus arbiter grants bus disk controller becomes bus master disk controller writes data directly into RAM
DMA and virtual memory: device controllers work with physical addresses virtual contiguous memory can correspond to scattered physical pages simple DMA transfer needs a physically contiguous RAM region example: 1 MB = 256 pages of 4 KB OS may have 256 free pages, but not 256 consecutive physical pages -> cannot use them as one contiguous DMA area physical-memory fragmentation therefore limits DMA OS tries to avoid excessive physical-memory fragmentation
Clarification. The bus timing, cache sizes, and ISA/PCI descriptions are illustrative or historical examples. The 600 MHz figure comes from the simple round-trip model in the notes. Cache organization varies by CPU, and writes in a cache hierarchy propagate to the next level before eventually reaching RAM.
DMA addresses are device-visible bus addresses and need not equal CPU physical addresses. An IOMMU can translate them, and scatter-gather transfers can use several memory regions. Physical contiguity is a constraint of the simple transfer model, not every DMA operation. The driver must keep buffers valid and handle the required cache synchronization until completion. See the Linux DMA mapping guide.
Previous: Parallel Programming Reading map Next: Programming Paradigms
Comments