Search code examples
linux-kernelpreemptive

Linux kernel: why preemption is disabled when use per-CPU variable?


Im looking at this macro from the linux kernel which has to do with handling cpu-specific variables

#define get_cpu_var(var)                                                \
(*({                                                                    \
        preempt_disable();                                              \
        this_cpu_ptr(&var);                                             \
})) 

Why do we disable preemption? Isnt preemption something that cant happen when you are in the kernel? (Since the kernel is the one doing the preemption)


Solution

  • Why do we disable preemption?

    To avoid having the thread preempted and rescheduled on a different processor core.

    Isnt preemption something that cant happen when you are in the kernel?

    This was true when there was still a big kernel lock. Having one global lock means that if you block in-kernel, no other thread may enter the kernel. Now, with the more fine-grained locking, sleeping in the kernel is possible. Linux can be configured at build-time for other preemption models, e.g. CONFIG_PREEMPT.

    While your normal desktop kernel is probably configured with CONFIG_PREEMPT_VOLUNTARY, some distributions also ship CONFIG_PREEMPT as a separate low-latency kernel package, e.g. for audio use. For real-time use cases, The preempt_rt patchset even makes most spinlocks preemptible (hence the name).