Per-CPU variables are quite heavily used within the Linux kernel; one interesting case is in the implementation of the current macro on the x86 architecture (we covered using the current macro in the companion guide Linux Kernel Programming - Chapter 6, Kernel Internals Essentials – Processes and Threads, in the Accessing the task structure with current section). The fact is that current is looked up (and set) every so often; keeping it as a per-CPU ensures that we keep its access lock-free! Here's the code that implements it:
// arch/x86/include/asm/current.h
[ ... ]
DECLARE_PER_CPU(struct task_struct *, current_task);
static __always_inline struct task_struct *get_current(void)
{
return this_cpu_read_stable(current_task);
}
#define current get_current()
The DECLARE_PER_CPU() macro declares the variable named current_task as a per-CPU variable of type struct task_struct *. The get_current() inline function invokes...