Skip to content

Commit

Permalink
anolis: sched: fix race condition when adjust guest cputime
Browse files Browse the repository at this point in the history
ANBZ: torvalds#394

Cpuacct.proc_stat_show callback will read cpuacct's per-cpu kcpustat
by `per_cpu_ptr`. the `kcpustats` is not protected by any lock. When
adjust guest cputime, it will subtract tick_user by tick_guest.
In a extreme case, the tick_user version is older than tick_guest,
if the tick_guest value close the tick_user, the result will be
negative.

cpu0					|  cpu1
__cpuacct_get_usage_result:		|
        per_cpu_ptr(ca->cpustat, 1);	|
	read tick_user			|
					|  update tick_user and tick_guest
	read tick_guest			|
	tick_user - tick_guest		|

Fixes: a1bc632 (anolis: cpuacct: fix guest cgroup usage more than user usage)
Signed-off-by: Zeng Jiahao <zengjiahao@linux.alibaba.com>
Reviewed-by: Shanpei Chen <shanpeic@linux.alibaba.com>
  • Loading branch information
Zeng Jiahao authored and shiloong committed Feb 23, 2022
1 parent b348c22 commit 2d02cc1
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions kernel/sched/cpuacct.c
Original file line number Diff line number Diff line change
Expand Up @@ -981,8 +981,13 @@ static void __cpuacct_get_usage_result(struct cpuacct *ca, int cpu,
tick_sys = kcpustat->cpustat[CPUTIME_SYSTEM];
tick_irq = kcpustat->cpustat[CPUTIME_IRQ];
tick_softirq = kcpustat->cpustat[CPUTIME_SOFTIRQ];
tick_guest = kcpustat->cpustat[CPUTIME_GUEST];
tick_guest_nice = kcpustat->cpustat[CPUTIME_GUEST_NICE];
/* Typically, the tick_guest should be small or equal than tick_user.
* But the kcpustat could be read/wrote parallelism, the tick_guest may
* newer than tick_user, which will cause the `tick_user - tick_guest`
* become negative
*/
tick_guest = min(tick_user, kcpustat->cpustat[CPUTIME_GUEST]);
tick_guest_nice = min(tick_nice, kcpustat->cpustat[CPUTIME_GUEST_NICE]);

/* Calculate system run time */
cputime.sum_exec_runtime = cpuusage->usages[CPUACCT_STAT_USER] +
Expand Down

0 comments on commit 2d02cc1

Please sign in to comment.