🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Free Linux Kernel Development Course — EmbeddedPathashala
Linux Kernel Internals: Processes, Threads, task_struct, and Kernel vs User Space Stacks
Learn how the Linux kernel organises every thread with a task_struct, why threads need two stacks (user + kernel), and how kernel threads differ from user-space threads — all updated for Linux 6.x.
What You Will Learn
- How the Linux kernel uses task_struct to represent every thread (user and kernel)
- Why the thread — not the process — is the kernel’s schedulable unit
- Why every user-space thread has two stacks: a user-space stack and a kernel-space stack
- What happens to those stacks when a thread makes a system call
- How kernel threads differ from user-space threads and why they have only one stack
- How to find and read the task_struct fields in the Linux 6.x kernel source
- The difference between user virtual address space and kernel virtual address space
Prerequisites
- You have read the previous lecture: Linux Process VAS — Segments and Memory Layout
- Basic understanding of what a process and a thread are
- Familiarity with the concept of system calls (user mode vs kernel mode)
This is part of the free Linux kernel development course at EmbeddedPathashala, targeting embedded systems engineers and students preparing for roles at semiconductor companies.
Why the Thread — Not the Process — is What Linux Schedules
When you learn about operating systems in college, textbooks often say “the OS schedules processes”. In Linux, this is not quite accurate. The correct statement is: the thread is the kernel schedulable entity (KSE). The CPU scheduler picks threads — not processes — to run on each CPU core.
A process is a container: it holds the Virtual Address Space (VAS), open file descriptors, signal handlers, credentials, and other resources. A thread is an execution flow that runs inside that container. Multiple threads in the same process share all those resources, but each thread has its own CPU registers, program counter, and stack.
This design is what allows modern multi-threaded programs (web servers, databases, media encoders) to use multiple CPU cores efficiently. The Linux kernel’s completely fair scheduler (CFS) treats each thread independently — a process with 4 threads gets 4 scheduling slots.
The task_struct — Linux’s Per-Thread Metadata Structure
For every thread that exists on a Linux system — whether it is a user-space application thread or a kernel thread — the Linux kernel maintains a corresponding in-kernel data structure called the task_struct. This is also referred to as the process descriptor.
Think of task_struct as the thread’s identity card inside the kernel. It stores everything the kernel needs to know about that thread:
/* How to access task_struct in a kernel module -- Linux 6.x */
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/module.h>
static int __init demo_init(void)
{
struct task_struct *t = current; /* 'current' macro gives the running thread's task_struct */
pr_info("My PID (TID) : %d\n", t->pid);
pr_info("My TGID (proc) : %d\n", t->tgid);
pr_info("My name : %s\n", t->comm); /* 'comm' = process name, max 16 chars */
pr_info("My state : %ld\n", t->__state);
return 0;
}
static void __exit demo_exit(void) { }
module_init(demo_init);
module_exit(demo_exit);
MODULE_LICENSE("GPL");
state. In Linux 6.x it is renamed to __state and should only be accessed through the helper macros task_is_running(t), task_is_stopped(t) etc. defined in include/linux/sched.h. Direct assignment uses set_current_state().Why Every User-Space Thread Has Two Stacks
This is one of the most important and frequently misunderstood concepts in Linux kernel internals. Let us build up to it step by step.
Modern CPUs support at least two privilege levels:
- User mode (unprivileged) — where application code runs. The CPU restricts access to hardware I/O ports, certain instructions, and kernel memory.
- Kernel mode (privileged) — where the OS kernel runs. The CPU allows full hardware access and can modify page tables, handle interrupts, etc.
On x86-64 these are called Ring 3 (user) and Ring 0 (kernel). On ARM64 they are called EL0 (user) and EL1 (kernel).
The rule is: you need one stack per privilege level per thread. This is a hardware requirement, not a Linux design choice. The reason is security and isolation — user code must never be able to read or corrupt the kernel’s execution stack.
📍 Active when the thread runs user-mode code
📍 Holds local variables, function call frames of application
📍 Default size: 8 MB (Linux default)
📍 Growable (demand paging + guard page)
system call /
exception
📍 Active when the thread runs kernel-mode code (syscall/IRQ handler)
📍 Holds kernel function call frames, local kernel vars
📍 Fixed size: 16 KB on x86-64 (4 pages)
📍 Cannot grow — overflow is fatal (kernel oops)
When your application calls read() or write(), the following happens at the hardware level:
syscall (x86-64) or svc #0 (ARM64). The CPU privilege level is raised from Ring 3 to Ring 0 (or EL0 to EL1).sys_read() / sys_write() kernel function runs on the kernel stack. The user-space stack is untouched and preserved.sysretq (x86-64). CPU drops back to Ring 3, SP switches back to the user-space stack. Application continues from where it left off./* Observe the kernel stack size on your Linux 6.x system */
/* In kernel source: arch/x86/include/asm/page_64_types.h */
#define THREAD_SIZE_ORDER (2 + KASAN_STACK_ORDER)
#define THREAD_SIZE (PAGE_SIZE << THREAD_SIZE_ORDER)
/* On non-KASAN x86-64: PAGE_SIZE=4096, order=2 => 4096*4 = 16384 bytes (16 KB) */
/* --- From a kernel module, print the kernel stack pointer --- */
#include <linux/module.h>
#include <linux/sched.h>
static int __init show_stacks_init(void)
{
pr_info("Kernel stack start : 0x%px\n", current->stack);
pr_info("THREAD_SIZE : %lu bytes\n", (unsigned long)THREAD_SIZE);
pr_info("Current SP (approx): 0x%px\n", (void *)current_stack_pointer);
return 0;
}
/* ... */
Kernel Threads — Living Entirely in Kernel Space
Not all threads in a Linux system belong to user applications. The kernel itself creates and manages its own threads called kernel threads. Examples you may have seen in ps aux output include kworker, kswapd, ksoftirqd, jbd2, and migration.
Kernel threads are fundamentally different from user-space threads in one key way: they never run in user mode. They only ever execute kernel code paths. Because of this:
- Kernel threads have no user-space VAS — their
task_struct->mmfield isNULL. - They have only one stack — the kernel-space stack. There is no need for a user-space stack.
- They cannot make system calls (they are already in kernel mode).
- They cannot access user-space memory directly.
/* Detect kernel threads vs user threads -- Linux 6.x */
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/module.h>
/* Walk all threads and identify kernel threads */
static void scan_threads(void)
{
struct task_struct *t;
rcu_read_lock();
for_each_process(t) {
if (t->mm == NULL) {
/* mm is NULL ==> this is a kernel thread */
pr_info("[kthread] PID=%d name=%s\n", t->pid, t->comm);
} else {
pr_info("[uthread] PID=%d name=%s\n", t->pid, t->comm);
}
}
rcu_read_unlock();
}
static int __init kthread_demo_init(void)
{
scan_threads();
return 0;
}
static void __exit kthread_demo_exit(void) { }
module_init(kthread_demo_init);
module_exit(kthread_demo_exit);
MODULE_LICENSE("GPL");
kswapd is the kernel’s memory reclaim daemon. It wakes up when free memory runs low and starts writing dirty pages to swap. Because it needs to access kernel data structures (page tables, LRU lists) directly and cannot afford the overhead of a user-mode context, it is implemented as a kernel thread. It runs entirely in kernel space and has no user VAS.The Complete Picture: User Space and Kernel Space Together
Now let us put everything together. On a running Linux 6.x system you have:
- Multiple user processes, each with its own VAS
- Each process containing one or more user-space threads
- Each user-space thread having a user-space stack (in its process VAS) and a kernel-space stack (in kernel virtual address space)
- Each thread represented by a task_struct in the kernel
- Additionally, several kernel threads — each with only a kernel-space stack and a task_struct, but no user VAS
The Kernel Stack Size Constraint — Critical for Kernel Developers
The kernel-space stack is much smaller than the user-space stack. On x86-64 running Linux 6.x it is typically 16 KB (4 pages of 4096 bytes each). On 32-bit ARM it is typically 8 KB. This is fixed and cannot grow — there is no guard page + demand-paging mechanism for the kernel stack the way there is for user stacks.
For Linux kernel developers and those writing Linux device drivers, this creates a hard constraint:
/* BAD -- blows the kernel stack */
static irqreturn_t my_irq_handler(int irq, void *dev)
{
char large_buf[8192]; /* 8KB on a 16KB kernel stack = DANGER */
/* ... */
}
/* GOOD -- allocate from kernel heap, not the stack */
static irqreturn_t my_irq_handler(int irq, void *dev)
{
char *large_buf = kmalloc(8192, GFP_ATOMIC); /* GFP_ATOMIC in IRQ context */
if (!large_buf)
return IRQ_NONE;
/* use large_buf ... */
kfree(large_buf);
return IRQ_HANDLED;
}
CONFIG_VMAP_STACK (virtually mapped kernel stacks with guard pages) and CONFIG_KASAN in your kernel config. These will catch stack overflows early during development. Also enable CONFIG_STACK_VALIDATION and CONFIG_LIVEPATCH for objtool-based compile-time stack frame analysis.Inspect Running Threads on Your Linux System
# List all threads on the system (each line is one thread / KSE):
ps -eLf | head -20
# NLWP = number of lightweight processes (threads) in the process:
ps -eo pid,nlwp,comm | sort -k2 -rn | head -10
# See kernel threads (those with [ ] around their name):
ps aux | grep -E '^\S+\s+\d+.*\[.+\]'
# For a specific process, see all its threads:
ls /proc/$(pgrep -n nginx)/task/
# Each subdirectory is one thread (TID):
# /proc//task// -- one per thread
# See a thread's kernel stack (requires root):
cat /proc/$(pgrep kswapd)/task/$(pgrep kswapd)/wchan
# or more detailed:
cat /proc/$(pgrep kswapd)/stack
Concept Summary Table
Key Takeaways
- The Linux kernel schedules threads (KSEs), not processes. Each thread gets its own time on the CPU.
- Every thread — user or kernel — is represented by a task_struct in kernel memory. It stores scheduling state, memory map pointer, file descriptors, credentials, and more.
- Every user-space thread has two stacks: a user-space stack (large, growable) and a kernel-space stack (small, fixed at 16KB on x86-64).
- The stack switch from user to kernel happens automatically at the hardware level during system calls and exceptions.
- Kernel threads have no user VAS and only a single kernel-space stack. Their
task_struct->mmisNULL. - The kernel-space stack is tiny — never allocate large local variables in kernel/driver code. Use
kmalloc()instead.
Frequently Asked Questions
Yes, conceptually they are the same. The Linux-specific name for the PCB is task_struct. The kernel uses one per thread (not per process), since the thread is the schedulable unit. You can explore it in the kernel source at include/linux/sched.h — it is a very large structure with 700+ members in Linux 6.x.
current is a kernel macro that always evaluates to a pointer to the task_struct of the thread currently running on that CPU. Its implementation is architecture-specific — on x86-64 (Linux 6.x) it is stored at a fixed offset in the per-CPU data area. Using current is the standard way to access the calling thread’s attributes from within a kernel module or driver.
Not directly. Kernel threads have no mm (user VAS), so user-space pointers are meaningless to them. However, a kernel thread can temporarily “borrow” another process’s mm using use_mm() — this is done by certain kernel threads like io_uring workers. Normal device drivers should never need this.
With CONFIG_VMAP_STACK enabled (the default in modern distro kernels), the guard page below the kernel stack will trigger a page fault, which the kernel detects as a stack overflow and causes a controlled kernel oops/panic with a backtrace. Without VMAP_STACK, a kernel stack overflow silently corrupts adjacent kernel data structures, leading to unpredictable and hard-to-debug corruption.
Use kthread_run(thread_fn, data, name_fmt, ...) from <linux/kthread.h>. This creates a kernel thread and starts it immediately. To stop it cleanly, call kthread_stop(task) and check kthread_should_stop() inside your thread function. Never use kernel_thread() — that is the old, deprecated API.
Square brackets in ps aux output (e.g., [kswapd0], [kworker/0:1]) indicate kernel threads. They have no command-line arguments and no executable path — just an internal name set via task_struct->comm. The brackets are added by the ps utility when it detects that /proc/<pid>/cmdline is empty (which is always true for kernel threads).
On x86-64, you can compile the kernel with CONFIG_KASAN which doubles the stack to 32KB to accommodate the additional shadow memory overhead. Beyond that, the kernel stack size is not easily user-configurable. The correct solution for needing more stack depth in kernel code is to restructure the code — reduce call chain depth and avoid large stack-allocated buffers, using kmalloc() for any significant allocations.
In the Linux kernel, each thread gets a unique PID (which userspace calls the TID — Thread ID). The TGID (Thread Group ID) is the PID of the main (first) thread of the process, and all threads in that process share the same TGID. When you call getpid() in a C program, you get the TGID. When you call gettid(), you get the thread’s own PID (TID). This distinction matters when writing kernel code that needs to identify whether two task_structs belong to the same process.
