Notes
All notes

Operating System Fundamentals (OS Core #1)

An operating system is the program that owns the hardware and lends it to everyone else. Every question in this series — processes, scheduling, memory, files, locks — is a consequence of that arrangement: the kernel has the privilege, and your code does not.

What an operating system does

Two verbs cover it.

Multiplex. One CPU with eight cores runs three hundred threads. 16 GB of RAM holds programs that want 40 GB. One disk serves fifty readers. The OS decides who gets what, for how long, and in what order.

Abstract. You do not program the disk controller; you call read() on a file. You do not program the MMU; you use a pointer. The abstraction is the contract, and the kernel can change the implementation underneath without breaking your program.

The services that follow from those verbs:

Service What the OS provides
Process management create, schedule, suspend, kill
Memory management address spaces, allocation, protection, paging
File systems names, directories, persistent bytes
Device I/O drivers, buffering, interrupts
Protection isolation between users and processes
Accounting CPU time, memory, I/O per process

If the OS disappeared, every program would need its own disk driver, its own allocator, and its own convention for sharing the CPU. That is the situation on a microcontroller, and it is why embedded code is written differently.

QQuestionWhy is “the OS is a program” a useful way to think about it?
ASolution

Because it is scheduled, has memory, and runs on the CPU like any other program. The difference is the privilege level it runs at and the hardware it controls.

Kernel space and user space

The CPU has at least two privilege levels. On x86-64 these are ring 0 (kernel) and ring 3 (user); ARM calls them EL0 and EL1. The current level is a bit in a CPU register, not a software convention.

The address space is split too. On 64-bit Linux, user space occupies the lower half of the virtual address range and the kernel maps itself into the upper half. The kernel’s pages are marked so that user code cannot read them, even though they are in the same page table.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  r/.style={draw, thick, minimum width=4.6cm, minimum height=1.0cm, font=\scriptsize, align=center}]
  \node[r, fill=blue!10] (u) at (0,0) {user space: your code, heap, stack, libraries\\ring 3};
  \node[r, fill=orange!18] (k) at (0,1.2) {kernel space: scheduler, page tables, drivers\\ring 0};
  \draw[thick, red!65] (-2.4,0.6) -- (2.4,0.6) node[midway, above, font=\tiny, text=red!65] {privilege boundary};
  \node[font=\scriptsize, anchor=west] at (2.6,0.6) {system call entry};
  \node[font=\scriptsize, anchor=west] at (2.6,0) {no direct access to kernel memory};
\end{tikzpicture}

The boundary is enforced by the MMU and the mode bit, not by the compiler. A bug in user code can corrupt its own address space; it cannot write kernel memory without a kernel bug or a vulnerability.

QQuestionIs a device driver “part of the OS” if it is loaded later?
ASolution

Yes. A loadable kernel module runs in kernel mode with full privilege. Loading one is equivalent to installing kernel code.

System calls

A system call is the only supported way for user code to ask the kernel for something. The mechanism is a deliberate trap:

  1. Put the syscall number in a register (rax on x86-64).
  2. Put the arguments in the specified registers (rdi, rsi, rdx, r10, r8, r9).
  3. Execute the syscall instruction.
  4. The CPU switches to kernel mode and jumps to the kernel’s entry point.
  5. The kernel validates, does the work, puts the result in rax, and returns with sysret.

The C library wraps this so you can call read(fd, buf, n) instead of writing registers. The wrapper also converts a negative return value into -1 and sets errno.

#include <unistd.h>
#include <sys/syscall.h>
#include <cerrno>
#include <cstdio>

int main() {
    long pid = syscall(SYS_getpid);      // bypasses the libc wrapper
    std::printf("pid = %ld\n", pid);

    char buf[16];
    long n = syscall(SYS_read, 0, buf, sizeof buf);
    if (n < 0) std::perror("read");      // errno is set by the wrapper
}

Raw syscalls are rarely needed, but seeing them explains the cost. A syscall is not a function call: it changes privilege, switches stacks, and may touch cold kernel data. A simple one costs roughly 50–300 ns; a syscall that blocks costs whatever the I/O costs.

$ strace -e trace=read,write ./hello
write(1, "hello\n", 6)                  = 6
read(0, 0x7ffd..., 16)                  = -1 EAGAIN

strace is the practical way to see which syscalls a program makes. If a program is slow for no obvious reason, the answer is often “too many small syscalls”.

QQuestionWhy does printf not call write once per character?
ASolution

Because every write is a syscall. printf buffers output in user space and flushes in large chunks; the buffer is why output can be lost if the process crashes before flushing.

Interrupts, traps, and exceptions

All three transfer control to the kernel, but for different reasons and at different times.

Event Source Timing Examples
Interrupt external hardware asynchronous timer tick, disk completion, network packet
Trap the program itself synchronous syscall, breakpoint (int3)
Exception CPU detects a fault synchronous page fault, divide by zero, invalid opcode

The CPU looks up a handler through the interrupt descriptor table (IDT), which maps each vector to an entry point. The kernel saves the interrupted context, handles the event, and returns with iretq.

Two details matter in practice:

The timer interrupt is what makes preemption possible. Without it, a CPU-bound process that never makes a syscall would keep the CPU until it exits.

QQuestionIs a system call a trap or an interrupt?
ASolution

A trap: it is synchronous, caused deliberately by the executing instruction, and the return address is the instruction after syscall.

User mode to kernel mode

The transition has a fixed shape:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=2.0cm, minimum height=0.6cm, font=\scriptsize, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (u) at (0,0) {user code};
  \node[b, fill=orange!15] (e) at (3.0,0) {entry stub\\save registers};
  \node[b, fill=orange!15] (s) at (6.0,0) {syscall table\\handler};
  \node[b, fill=green!18] (r) at (9.0,0) {return\\restore, sysret};
  \draw[a] (u) -- node[above, font=\tiny] {syscall} (e);
  \draw[a] (e) -- (s);
  \draw[a] (s) -- (r);
  \draw[a, dashed] (r) -- (u);
  \node[font=\scriptsize, anchor=north] at (4.5,-0.55) {kernel mode throughout};
\end{tikzpicture}

The cost of the transition is the register save/restore, the stack switch, and the cache pollution from touching kernel data. It is small but not free, which is why batching syscalls matters: one read of 64 KB beats 64 reads of 1 KB.

A mode switch is not the same as a context switch. A syscall switches mode and back, staying in the same process. A context switch saves one thread’s registers and switches to a different thread, which costs more (Ch. 2).

QQuestionWhat is saved on the kernel stack when a syscall runs?
ASolution

The user registers needed to resume, the instruction pointer, the flags, and the syscall arguments. The kernel then runs on its own stack, not the user stack.

Monolithic kernels and microkernels

Kernel design is a trade-off between performance and isolation.

Design Structure Pros Cons Examples
Monolithic all services in one address space fast calls, shared caches one bug can crash everything Linux, FreeBSD
Microkernel minimal kernel; servers in user space isolation, small trusted core IPC overhead for every service seL4, QNX, Minix
Hybrid microkernel-ish with kernel components pragmatic balance complexity Windows NT, macOS XNU

Linux is monolithic but modular: drivers and filesystems can be loaded as modules, yet they still run in kernel mode with full privilege. seL4 is a few thousand lines of code that can be formally verified; its filesystem and network drivers are user processes that talk to the kernel through IPC.

The performance argument for monolithic kernels is concrete: a function call between kernel subsystems costs nanoseconds, while IPC between user-space servers costs microseconds. The safety argument for microkernels is equally concrete: a driver crash is a process crash, not a kernel panic.

QQuestionWhy does a microkernel need a fast IPC mechanism?
ASolution

Every service request crosses a protection boundary. If IPC costs more than the work being requested, the design is unusable, so microkernels invest heavily in fast message passing.

OS services and resource management

Resource management is the day-to-day work:

Accounting is part of it too: /proc/<pid>/stat, getrusage, cgroups. That is how the OS enforces quotas and how top knows which process is using the CPU.

#include <sys/resource.h>
rlimit lim{};
getrlimit(RLIMIT_NOFILE, &lim);
std::printf("open files: soft=%llu hard=%llu\n",
            (unsigned long long)lim.rlim_cur,
            (unsigned long long)lim.rlim_max);

Resource limits are per-process and inherited across fork and exec. They are the simplest form of resource management: a hard ceiling the kernel enforces.

QQuestionWhy is protection listed as a service rather than a feature?
ASolution

Because every other service needs it. Sharing the CPU or memory only works if a process cannot read or corrupt another’s data, so checks happen on every privileged operation.

Bugs and edge cases

QQuestionwrite(fd, buf, 4096) returns 1024. Is that an error?
ASolution

No. It is a short write: 1024 bytes were accepted. The correct code loops, advancing the buffer and subtracting the count, until everything is written or a real error occurs.

Next: Processes and Threads (OS Core #2) — what a process owns, what a thread shares, and what a context switch actually saves.