smp_processor_id used in preemptable context ?

Valdis Kl=?utf-8?Q?=c4=93?=tnieks valdis.kletnieks at
Fri Apr 29 19:59:47 EDT 2022

On Thu, 28 Apr 2022 11:15:27 +0200, Vincent Ray said:
> Then I guess it could be preempted at any time, especially with aggressive versions of preemptions ? 
> And if so, are we not at risk that our thread is migrated to an other CPU just after smp_processor_id returned ? 

Often, we don't actually *care* if it gets migrated.  A *lot* of uses of
smp_processor_id() are just to make statistic gathering more efficient.

Rather than all the CPUs do all sorts of locking to avoid race conditions
between different threads updating the same variable, and avoid massive cache
line ping-ponging, the code just gets a pointer to a per_cpu area where we
update some statistic or counter without worrying about that stuff because we
know no other processor should be updating *this* processor's per_cpu area.
Then anything that cares about the *total* across all CPUs can iterate across
all the per_cpu numbers - and that (a) usually happens much less frequently
than updates and (b) only needs to read all the per_cpu area without updating

Yes, there's a very small chance that the "wrong" CPU's stats will be updated. But
let's be realistic - for a lot of statistics, you'll never notice. 

More information about the Kernelnewbies mailing list