TL;DR
A system call is the controlled way a program asks the Operating System to do something it is not allowed to do itself, such as reading a file, opening a network connection or starting a new process. The processor switches into a privileged mode, the operating system checks the request, does the work and returns the result. Every program that touches the outside world does so through this door.
Builds on: Operating System, Virtual Memory · Leads to: File System, Linux Containers, Virtual Machine
Where it's used
Reading and writing files. When a text editor saves your document, the editor does not write to the disk itself. It asks the operating system to write the bytes to a file, and the operating system decides where on the disk they go. Every save, open and read is a system call.
Starting programs. When you type a command in a terminal, the shell asks the operating system to create a new Process (Running Program) and then to load the program into it. Both steps are system calls. A shell that could not make these requests could not run anything.
Containers and virtual machines. A Linux container is an ordinary process whose access to the kernel is limited, and every resource it asks for still passes through a system call that the kernel checks. A Virtual Machine goes further: a hypervisor, the software that runs several guest operating systems on one machine, handles the privileged requests of each guest operating system, so one guest cannot reach the hardware of another.
How it works
Take one small job: a program has a file open and wants to write four bytes, the letters "milk", to it. In this toy setup, "file 3" is the number the operating system gave the program when it opened the file, and call number 7 means "write". Both are made up for the example; real systems use their own tables.
- The program puts the request in registers. It stores the call number 7, the file number 3, the address of the bytes (a Pointer) and the length 4 in the processor's registers, which are small storage slots inside the processor. Check: nothing has been written yet. The program has only prepared a request.
- The program executes a trap. A trap is a special instruction that deliberately stops the normal flow of the program and transfers control to a fixed place chosen by the operating system. The processor switches from user mode, where programs run with limits, into privileged mode, in which the kernel (the core of the operating system) runs. Check: the program cannot choose where control lands; the fixed entry point decides.
- The operating system saves the program's state. It stores the registers and the program counter (the address of the next instruction to run), just as in a Context Switch, so the program can resume later. Check: the program's values are safe while the operating system works.
- The operating system looks up call 7. Its table maps the number 7 to the code that handles writes. Check: an unknown call number is refused here, with an error.
- The handler checks the request. It confirms that file 3 is open for this program, that the four bytes lie inside the program's own memory (the address translation of Virtual Memory does this), and that the length is sensible. If any check fails, the call returns an error and nothing is written. Check: all three pass for "milk".
- The handler does the work. It copies the four bytes into the file's data, and the File System decides which disk blocks hold them. Check: the file has grown by 4 bytes.
- The operating system returns. It places the value 4, the number of bytes written, in a register, switches back to user mode and resumes the program right after the trap. Check: the program sees 4 and continues.
sequenceDiagram participant P as Program (user mode) participant CPU as Processor participant OS as Kernel (privileged mode) P->>CPU: put call 7 and arguments in registers, execute trap CPU->>OS: switch to privileged mode, jump to fixed entry point OS->>OS: save program's registers OS->>OS: look up call 7 in the table OS->>OS: check file, memory range and length OS->>OS: copy 4 bytes into the file OS->>CPU: return 4, switch back to user mode CPU->>P: resume after the call
The key idea is that the program never gets the power to write the disk. It can only ask, and the operating system decides.
The math
The cost of a system call has two parts: a fixed cost to cross the boundary, and the work done inside. Let be the fixed cost of one trap and its return, and let be the work per item of data. Let be the total number of items. A program that moves them with one call per item pays for each item.
If the program groups items into each call, it makes calls. The total time is The first term shrinks as grows, and the second term does not.
Step 2 in symbols: the trap cost
Each trap pays the fixed cost once, whatever the call does. Sending each of the items in its own call, which is , gives . This is the naive version, and it is the one to avoid when is large.
Step 6 in symbols: the work
Copying the data costs per item, so items cost however they are grouped. Batching cannot remove this part of the cost.
Batching: many items per call
Grouping items divides the trap cost by . Each call still does its work for all items, so the work term stays . As grows without limit, approaches , the cost of the work alone.
Worked examples
A program has three items to write. A trap costs microseconds and each item's work costs microsecond.
- One call per item: 3 calls, each costing microseconds. Total: microseconds.
- One call for all three items: 1 trap costing 2 microseconds, plus 3 items of work costing microseconds. Total: microseconds.
- Check with the formula: and .
Interpretation: the work is the same in both cases. Only the number of trips across the boundary changed, and that alone cut the time from 9 to 5 microseconds.
A program has items. The trap costs microseconds and the work per item is microsecond.
- With : microseconds.
- With : there are calls, so microseconds.
- With : there are calls, so microseconds.
- The time falls from 3000 to 1200 to 1020 microseconds. The last step saves only 180 microseconds, because the trap cost was already small compared with the work.
Interpretation: batching helps most when the trap is expensive relative to the work per item. Past a point, a bigger batch changes little.
A logging program writes 50,000 records of 100 bytes each. Treat the costs as illustrative: a trap of microseconds and a copy cost of microsecond per record.
- One call per record: 50,000 calls, so microseconds, which is 0.15 seconds.
- Buffer the records in a 4000-byte block. Each block holds records, so there are calls.
- Buffered total: microseconds, which is 0.0525 seconds.
- The saving is , so about 65 percent less time.
Interpretation: this is why libraries collect small writes into larger blocks before calling the operating system. The program looks the same, but it crosses the boundary about forty times less often.
Try it: the same 50,000 records, buffered in 8000-byte blocks of 80 records each, with the same costs. How many calls, and what total time? Answer: there are calls, so microseconds, which is 0.05125 seconds.
Common mistakes and tradeoffs
It is tempting to think a system call is just a function call into another library. In fact it changes the processor's mode and the set of memory and devices the code may touch. That change is the point: it is what lets the operating system protect everything else.
It is tempting to think a careful program can skip the operating system and drive the hardware directly. In fact the processor refuses privileged instructions and device access in user mode, so the attempt stops with a fault and the operating system takes over.
It is tempting to think system calls are cheap because they look like function calls. In fact each one pays for the trap, the checks, and the cache effects (the processor's fast memory is left holding other data) that a Context Switch also causes. A program that makes one call per byte pays this cost a million times for a megabyte.
When to use one: whenever the program needs a resource the operating system owns, such as a file, a network socket or a new process.
When not to use one: for pure computation on data already in memory. A loop that adds numbers needs no system call at all.
Alternatives: buffering small writes into large blocks, as in the logger example. Memory mapping, which asks the operating system once to map a file into memory and then reads it with ordinary memory accesses, also avoids repeated calls, at the cost of more complex code.
Tradeoff: the boundary costs time, but it is what keeps one program from damaging another. Faster designs move some work out of the kernel, and then they must give up some of that protection.
History
Early computers gave a program full control of the hardware, and a program that failed could bring down the whole machine. A small supervisor program then began to take over the input and output for each job, which is the ancestor of the operating system.
Protection followed. Systems of the 1960s, such as Multics, used hardware rings (levels of privilege that the processor enforces) to separate privileged code from ordinary programs, so that a call into the system had to pass through a controlled entry point. Unix, developed at Bell Labs in the late 1960s and early 1970s, gave programs a small and uniform set of system calls for files and processes. That design shaped later systems, and the POSIX family of standards later described a common interface for such calls. The idea caught on because it made the boundary explicit. Programs could be written against a stable set of requests, and the operating system could change its internals without breaking them.
Recap
- A system call is the controlled door through which a program asks the operating system for a resource it may not touch directly.
- The processor switches into privileged mode through a trap, and jumps to a fixed entry point that the program cannot choose.
- The operating system saves state, looks up the call, checks the arguments, does the work and returns the result.
- Each crossing of the boundary costs a fixed amount, so batching many items into one call saves time, with .
- Next, read about File System for how the operating system organises the data a write reaches, and Linux Containers and Virtual Machine for how the boundary is used to isolate whole programs and systems.
Check yourself
QuestionRecall: what are the two modes a processor runs in during a system call, and which one does the program's own code run in?Show answer
QuestionComputation: a program makes 1000 calls, each with a trap of 2 microseconds and work of 1 microsecond. If it batches 20 items per call, what is the total time?Show answer
QuestionWhy: why can a program not write to the disk itself, even though it could in principle issue the same commands?Show answer
QuestionApplied: a program reads a 1 MB file with one system call per byte. Using only what this lesson says, how would you improve it, and roughly how many calls would the improved version make?Show answer
Sources
- System call (Wikipedia)
- Operating system (Wikipedia)
- Arpaci-Dusseau and Arpaci-Dusseau, Operating Systems: Three Easy Pieces