Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Backend Development
11 min read

Linux System Calls Explained: Mechanisms, Categories & Performance Optimization

This article provides a comprehensive deep dive into Linux system calls, covering user/kernel mode transition, syscall numbers and tables, parameter passing, instruction evolution, kernel entry flow, error handling, major syscall categories, three invocation methods, a detailed write() walkthrough, performance measurement, vDSO, batching with readv/writev and io_uring, and zero-copy techniques like sendfile and splice.

What Are System Calls?

System calls are the official controlled interface for user programs to request kernel services. The CPU splits execution into two privilege levels: kernel mode (full hardware access) and user mode (restricted). This separation exists because user programs are untrusted — they may contain bugs like buffer overflows or infinite loops. If they could directly manipulate hardware or memory, the OS would be unstable.

When a user program needs to read a file, write to a socket, create a process, or map memory, it must ask the kernel via a system call. Each syscall has a fixed number, fixed parameters, a fixed calling convention, a fixed entry point, and fixed return rules.

1.1 User Mode vs Kernel Mode

The CPU enforces privilege separation. User mode code that attempts privileged operations triggers a segmentation fault. The kernel treats all user-supplied pointers as potentially malicious — it never dereferences them directly but uses helpers like copy_from_user() and copy_to_user() to safely move data between address spaces.

1.2 Core Definition

On x86_64 Linux, the write syscall number is 1. The user-space wrapper places the number in rax and arguments in rdi, rsi, rdx, r10, r8, r9, then executes the syscall instruction. The CPU switches to kernel mode, the kernel looks up the handler in the sys_call_table (a global read-only array of function pointers indexed by syscall number), and executes the corresponding kernel function (e.g., sys_write → ksys_write → vfs_write). The kernel validates the file descriptor, checks the user buffer address, copies data, and may traverse VFS, page cache, filesystem, and block layers.

1.3 Syscalls vs Library Functions

Most "syscall-like" functions are actually glibc wrappers. For example, write() in user code is a glibc function that prepares registers and executes syscall. printf() is not a syscall — it formats data and may eventually call write(), but stdio buffering means output isn't immediate. malloc() only invokes brk() or mmap() when the heap needs expansion. The key distinction: a system call always triggers a user-to-kernel transition to request a protected resource.

1.4 General Syscall Flow

User code
  ↓
glibc wrapper
  ↓
Place syscall number in register
  ↓
Place arguments in registers
  ↓
Execute syscall instruction
  ↓
CPU switches to kernel mode
  ↓
Enter kernel unified entry
  ↓
Save user context
  ↓
Lookup syscall table by number
  ↓
Call kernel handler
  ↓
Kernel executes service logic
  ↓
Place return value in register
  ↓
Restore context
  ↓
Return to user mode

Core Principles

2.1 Syscall Numbers & sys_call_table

Each syscall gets a unique integer ID. On x86_64: read =0, write =1, open =2, close =3, fork =57. Numbers are used because CPUs only understand integers; string lookup would be slower. The sys_call_table is a global function-pointer array where the index is the syscall number — O(1) dispatch. Different CPU architectures (x86_32, x86_64, ARM, RISC-V) have completely different syscall numbers and tables, which is why 32-bit binaries need a compatibility layer on 64-bit kernels. The table is read-only at runtime to prevent tampering.

2.2 Parameter Passing: Registers & Stack

Syscalls pass parameters via CPU registers, not the stack, because user and kernel stacks are isolated. On x86_64: syscall number in rax, args 1-6 in rdi, rsi, rdx, r10, r8, r9. Return value goes back in rax. For syscalls with more than six arguments, the kernel uses a hybrid approach: a pointer to a user-stack structure is passed in a register.

2.3 Instruction Evolution: int 0x80 → sysenter/sysexit → syscall/sysret

int 0x80 : Legacy 32-bit software interrupt. Full interrupt handling overhead (context save, vector table lookup) makes it slow.

sysenter/sysexit : Intel's fast system call instructions, ~2x faster than int 0x80, but lacked early AMD support.

syscall/sysret : AMD-designed, Intel-compatible, now the standard on x86_64. Further reduces context-switch cycles. glibc automatically selects the best instruction for the current CPU/kernel.

2.4 Kernel Entry: entry.S

The assembly entry point ( entry.S) handles the transition: switch to kernel stack, save registers, process security hooks (seccomp, ptrace, audit, ftrace, kprobes, eBPF), dispatch via syscall table, call the handler, handle return value, check for pending signals or scheduler needs, restore registers, return to user mode. These hooks explain why the same syscall can have different latency in different environments (containers, debugging, profiling).

2.5 Error Handling & errno

The kernel returns negative error codes (e.g., -ENOENT, -EFAULT, -EINVAL, -EACCES) in rax. glibc converts them: if the return value is in [-4095, -1], it stores the positive errno in thread-local storage and returns -1. errno is thread-local to avoid races. Successful calls do not clear errno — always check the return value first.

Syscall Categories Overview

3.1 Process Management

fork()

creates a child using copy-on-write (COW) — physical pages are shared until written. execve() replaces the current process image ("change shell"). Classic shell flow: fork() → child execve() → parent wait(). exit() terminates; wait() reaps zombies (dead children whose exit status hasn't been read). clone() is the low-level primitive behind threads — it selects which resources (address space, fd table, signal handlers) to share. In the kernel, both processes and threads are task_struct s differing only in shared resources.

3.2 File I/O

open

/ openat, read, write, lseek, close. File descriptors (fd) are small integers indexing the per-process fd table, pointing to kernel file objects. Standard fds: 0=stdin, 1=stdout, 2=stderr. The fd abstraction unifies regular files, pipes, sockets, eventfd, timerfd, signalfd, devices — enabling epoll to monitor all of them uniformly.

3.3 Filesystem Operations

stat

(metadata), mkdir, unlink (removes a directory entry; data freed only when link count hits 0 and no open fds remain — explains why df shows full disk but du finds no large files; use lsof | grep deleted), mount (attaches filesystem to the single unified directory tree, basis for containers/namespaces/chroot/overlayfs), rename, chmod, chown, getdents. Path resolution, permission checks, symlink handling, and TOCTOU prevention add significant complexity.

3.4 Memory Management

brk

adjusts heap top. mmap is more powerful: anonymous mappings (heap-like) or file-backed mappings (shared memory, dynamic libraries, large file I/O, JIT). Example anonymous mapping:

void *p = mmap(NULL, 4096, PROT_READ|PROT_WRITE,
               MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);

Physical pages are allocated lazily on first access (page fault). munmap unmaps. mprotect changes page permissions (e.g., W^X for JIT). madvise hints to the kernel (sequential, random, don't need). mlock pins pages in RAM.

3.5 Network Communication

socket

, bind, listen, accept, connect, sendmsg / recvmsg, setsockopt. Server flow: socket() → bind() → listen() → accept() → read() / write(). sendmsg / recvmsg support scatter-gather I/O, control messages, and fd passing over Unix domain sockets. send() success only means data handed to the kernel stack, not peer receipt. Partial writes, EAGAIN, epoll, half-packets, SIGPIPE are common pitfalls.

3.6 Inter-Process Communication

pipe

(shell pipelines), System V IPC ( shmget, semop, msgget), POSIX alternatives ( mmap, Unix domain sockets, eventfd, futex). futex (fast userspace mutex) is critical: uncontended lock/unlock stays in user mode; only contention triggers a syscall to sleep/wait. This avoids kernel entry on the fast path — a key principle: avoid syscalls when possible .

3.7 Signal Handling

sigaction

(reliable handler registration), kill (send signal, not necessarily kill), sigprocmask, sigreturn (restore context after handler). Signals interrupt normal flow; handlers can only call async-signal-safe functions (no printf, malloc). Many production bugs stem from unsafe signal handlers.

3.8 Time & Timers

time

, gettimeofday, clock_gettime, timer_create, timerfd_create, nanosleep. High-frequency time calls use vDSO (virtual dynamic shared object) — a kernel-mapped read-only page in each process that lets clock_gettime execute entirely in user mode for certain clocks. Check with cat /proc/self/maps | grep vdso or ldd /bin/ls (shows linux-vdso.so.1). timerfd fits the "everything is an fd" model: timer expiry makes the fd readable, integrable with epoll.

Three Ways to Invoke Syscalls

4.1 Indirect: glibc Wrappers (Daily Use)

Standard library functions ( open, write, close) handle ABI details, parameter validation, instruction selection, error conversion. Negligible overhead for most apps.

4.2 Generic Entry: syscall() Function

syscall(__NR_write, 1, buf, len)

bypasses glibc's per-syscall wrappers. Useful for newly added syscalls not yet wrapped, or cross-platform quirks. Slightly faster but requires manual syscall numbers (architecture-dependent) and argument handling.

4.3 Inline Assembly: Direct syscall Instruction

Full control, zero overhead. Example x86_64 write to stdout:

char buf[] = "hello asm syscall
";
long ret; int len = sizeof(buf);
__asm__ volatile (
  "mov $1, %%rax
"      // syscall number for write
  "mov $1, %%rdi
"      // fd = 1 (stdout)
  "mov %[buf], %%rsi
"  // buffer address
  "mov %[len], %%rdx
"  // length
  "syscall
"
  : "=a" (ret)
  : [buf] "r" (buf), [len] "r" (len)
  : "memory"
);

Used for kernel debugging, reverse engineering, extreme optimization. Not for application code.

Anatomy of a Syscall: write() Walkthrough

5.1 User Perspective

ssize_t write(int fd, const void *buf, size_t count)

— simple synchronous API.

5.2 glibc Wrapper & syscall Instruction

glibc validates fd, buf, count; loads __NR_write and args into registers; executes syscall; on return, converts negative kernel errno to errno and -1.

5.3 Kernel Path: sys_write → VFS → Filesystem

sys_write

looks up the file struct via fd, then calls VFS generic write. VFS dispatches to the filesystem-specific write (ext4, XFS, tmpfs, pipe, socket, etc.). For regular files: data copied to page cache, pages marked dirty, async writeback by kernel threads (pdflush/kworker).

5.4 Data Copy & Transparent Blocking

User buffer copied to kernel page cache via optimized memory ops with permission checks. The calling thread sleeps in kernel mode until the syscall completes; the scheduler may run other tasks. On return, user context restored — the blocking is invisible to the caller.

5.5 Tracing with strace, perf, bpftrace

Compile test program:

gcc -g trace_write.c -o trace_write
strace -e write ./trace_write

→

write(1, "trace me
", 9) = 9
strace -T -e write ./trace_write

shows syscall latency (includes strace overhead).

perf trace -e syscalls:sys_enter_write,syscalls:sys_exit_write ./trace_write

for enter/exit events. perf record -g ./trace_write; perf report for call stacks.

sudo bpftrace -e 'tracepoint:syscalls:sys_enter_write { printf("pid=%d fd=%d count=%d
", pid, args->fd, args->count); }'

for live kernel tracing.

Performance Costs & Optimization

6.1 Measuring Context-Switch Overhead

Simple syscalls ( getpid) take tens to hundreds of nanoseconds; I/O syscalls can take microseconds to milliseconds due to blocking, locks, disk/network. Don't ask "are syscalls slow?" Ask: frequency on hot path? blocking? data copy? lock contention? scheduler involvement? batchable? Microbenchmark example (not rigorous):

clock_gettime(CLOCK_MONOTONIC, &s);
for (i=0; i<1000000; i++) syscall(SYS_getpid);
clock_gettime(CLOCK_MONOTONIC, &e);
printf("avg: %.2f ns
", (double)ns_diff(s,e)/1000000);

Real analysis: strace -c ./program shows call counts and times. Example output:

% time   seconds  usecs/call   calls  errors syscall
60.00    0.012000         12    1000         read
25.00    0.005000          5    1000         write
10.00    0.002000          2    1000         futex

Common anti-pattern: calling clock_gettime multiple times per message, reading config per log line, reading /proc per request.

6.2 vDSO: Fast Path for High-Frequency Syscalls

vDSO maps a small read-only kernel page into each process. clock_gettime (for CLOCK_MONOTONIC, CLOCK_REALTIME) calls __vdso_clock_gettime in user mode, avoiding the syscall entirely. Falls back to real syscall if unsupported. Not applicable to syscalls requiring kernel state changes (I/O, memory mapping).

6.3 Reducing Frequency: Batching & io_uring

First principle: make fewer syscalls . Buffering (stdio), larger writes, readv / writev (scatter-gather) combine multiple buffers in one syscall:

struct iovec iov[3];
iov[0] = { "hello ", 6 };
iov[1] = { "writev ", 7 };
iov[2] = { "world
", 6 };
writev(1, iov, 3);
io_uring

uses shared submission/completion ring buffers (SQ/CQ) for batched async I/O — user submits batch, kernel processes batch, posts completions. Powerful for high-performance storage/network proxies/databases, but adds complexity; not worth it for ordinary services.

6.4 Zero-Copy: sendfile, splice

Traditional file-to-socket: disk → page cache → user buffer → socket buffer → NIC (two CPU copies). sendfile(out_fd, in_fd, &offset, count) moves data from file to socket inside kernel. splice generalizes pipe↔fd transfers. "Zero-copy" means fewer CPU copies; DMA still moves data. Higher-end: mmap, AF_XDP, DPDK (user-space networking). Practical checklist:

Avoid frequent small read/write

Use buffering

Batch when possible

Prefer writev over multiple write Large file transfer → sendfile High-concurrency I/O → evaluate

io_uring

Closing Thoughts

System calls are the busy boundary between user and kernel. They connect CPU privilege levels, process model, virtual memory, filesystems, network stack, scheduler, security, and performance. In daily coding they're invisible — until something breaks, then they become the clues.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Write a comment

Sign in to join the discussion

No public comments on this page. Sign in to comment