Skip to content
systemcoding.dev
Kernels

What Is a System Call and How Does It Reach the Kernel

A system call is the controlled jump from a user program into the kernel. See how write() becomes a syscall instruction, a number in rax and a return value.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and FreeBSD logos.

Your program cannot read a file, open a socket or allocate a page of memory by itself. Those jobs belong to the operating system kernel, and the CPU is configured so that ordinary programs are not allowed to do them directly. A system call is the one sanctioned doorway: a way for a program to ask the kernel to do something on its behalf and get an answer back. Every printf, every open, every malloc that needs more memory ends up going through it. This post follows one call, write(), from your C code to the kernel and back, on x86-64 Linux with a 6.12 kernel and glibc 2.40.

Why programs need a doorway at all

A modern CPU has at least two privilege levels. On x86-64 they are called rings; the kernel runs in ring 0 and ordinary programs run in ring 3. Code in ring 3 cannot execute certain instructions, cannot touch the memory the kernel uses, and cannot talk to devices. If a program tried, the CPU would raise a fault and the kernel would normally terminate the process.

That split is deliberate. It means one buggy or hostile program cannot overwrite another program's memory or lock up the disk controller. But programs still need disks, networks and memory, so the CPU provides one instruction whose job is to switch from ring 3 to ring 0 at a place the kernel chose in advance. On x86-64 that instruction is syscall. The program does not pick the destination address; the kernel set it earlier, in a register called LSTAR. This is what makes the doorway safe: you can knock, but you cannot choose which room you walk into.

What a program has to say

When the kernel takes over, it needs to know two things: which service the program wants, and what to do it with. Linux answers with a fixed convention, called the system call ABI. On x86-64:

RegisterMeaning
raxSystem call number (on return: the result)
rdiFirst argument
rsiSecond argument
rdxThird argument
r10Fourth argument
r8Fifth argument
r9Sixth argument

Every kernel service has a number. write is number 1 on x86-64, read is 0, exit is 60, and there are a few hundred more. The numbers are listed in arch/x86/entry/syscalls/syscall_64.tbl in the kernel source. The arguments go in registers, not on the stack, which is why a system call is cheaper to set up than an ordinary function call that spills values to memory. Different CPU architectures use different registers and different numbers, which is the subject of a later post in this series.

One call, three layers

Here is the smallest useful program. It writes six bytes to standard output:

hello.cc
#include <unistd.h>

int main(void)
{
	ssize_t n = write(1, "hello\n", 6);
	return n == 6 ? 0 : 1;
}
Text
hello

You wrote write(...), but write is an ordinary function from the C library, glibc here. It is not the system call itself. Its job is small: put the number 1 in rax, the file descriptor in rdi, the buffer address in rsi and the length in rdx, then execute syscall. The compiler plus glibc turn the line into roughly this:

asm
mov     edi, 1              ; fd = standard output
lea     rsi, [rip + msg]    ; buffer address
mov     edx, 6              ; length
mov     eax, 1              ; syscall number for write
syscall

When the CPU executes syscall, a lot happens in a few cycles of hardware time. It saves the address of the next instruction into rcx and the flags into r11, loads the kernel's entry address from LSTAR, and switches to ring 0. The kernel then runs its assembly entry code, entry_SYSCALL_64 in arch/x86/entry/entry_64.S. That code switches to the kernel's stack for the current task, saves all the user registers into a struct pt_regs, and calls a C function that looks up the number in a table of function pointers, sys_call_table, and calls the entry for write. The service function runs, produces a result, and the kernel returns to user mode with sysret, restoring the saved registers and putting the result in rax.

What comes back

The kernel returns one number in rax. A non-negative value is the success result, here the number of bytes written. A value from -4095 to -1 is an error, encoded as the negative of an error code. If you tried to write to a file descriptor that is not open, the kernel would return -9, which is -EBADF.

The C library then translates this for you. If the raw value is in the error range, glibc stores the positive error code in a per-thread variable, errno, and returns -1 to your program. That is why the manual pages say "returns -1 and sets errno". The negative-return convention belongs to the kernel boundary; the -1-and-errno convention belongs to libc.

You can watch all of this happen without writing any assembly by using strace, which prints each system call a program makes. Running strace ./hello shows a long preamble from the dynamic loader and then the call that matters:

Text
write(1, "hello\n", 6hello
)                  = 6
exit_group(0)                           = ?
+++ exited with 0 +++

The program's own hello appears glued into the middle of the trace because both go to the terminal. The = 6 is the return value, exactly what the kernel put in rax. The final exit_group(0) is how the process ends: glibc's exit flushes its buffers and then asks the kernel to terminate every thread in the process.

Calls that never enter the kernel

Not everything in the C library is a system call, and not every system call needs the full transition. Three cases are worth knowing from the start.

  • Pure library functions. strlen, memcpy and qsort run entirely in user mode. They never touch the kernel because they do not need anything the kernel controls.

  • Buffered I/O. printf and fwrite collect data in a user-space buffer and call write only when the buffer fills, a newline arrives on a terminal, or the program flushes. One write can carry many printf calls, and that batching is the reason the C standard library has stdio at all.

  • The vDSO. For a few calls that only read kernel-maintained data, such as clock_gettime and gettimeofday, Linux maps a small shared object into every process. Its functions read the time from memory the kernel keeps updated, so no ring switch is needed. The mapping is the "virtual dynamic shared object", described in the vdso(7) manual page.

Why a system call costs more than a function call

A system call is slower than a plain function call for reasons that follow from the design. The CPU must switch privilege levels and change stacks. The kernel saves and restores registers. Since the discovery of speculative-execution attacks, the kernel also takes extra steps on entry and exit on some CPUs, depending on the mitigations enabled for the machine. The exact cost varies by processor and kernel configuration, so measure on your own machine instead of trusting a table, and avoid unmeasured numbers when you write about it.

The practical consequence is simple. Do not call the kernel more often than you need to. Reading a file one byte at a time with read(fd, &c, 1) makes a transition per byte, while reading 64 KiB into a buffer makes one transition for the whole block. That is the entire argument for buffering, and it is why higher-level interfaces such as io_uring exist to submit many operations with one entry into the kernel.

What to remember about the trust boundary

The kernel treats everything a program hands it as untrusted. A pointer argument is not dereferenced like a normal pointer: the kernel uses helpers such as copy_from_user() and copy_to_user() that check the address is in the caller's memory and survive a fault if it is not. A file descriptor is checked against the calling process's table. A length is checked against limits. When a check fails, the call returns an error and the program carries on, instead of the machine crashing.

You can see that discipline from the program side. Passing a bad pointer to write does not crash the kernel; it returns -1 with errno set to EFAULT:

badptr.cc
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
	ssize_t n = write(1, (const void *)1, 4);

	printf("write returned %zd, errno %d (%s)\n", n, errno, strerror(errno));
	return 0;
}
Text
write returned -1, errno 14 (Bad address)

The kernel noticed that address 1 is not readable by this process, refused to touch it, and reported the problem through the return value.

When this model does not apply

On Linux, the C library is the supported way to reach system calls for most programs, and the kernel's interface is stable for the programs that use it. A few languages bypass libc: Go's runtime issues its own system calls, and static programs in assembly do the same. Even then the transition is the same instruction and the same register convention. The picture changes only for kernels that are not Linux, where the numbers, conventions and even the stable boundary differ. Some systems, such as macOS and Windows, treat the libc or system DLL as the stable interface and discourage raw system calls.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.