Re: [PATCH] sched/cpuacct: fix charge percpu cpuusage

From: Peter Zijlstra
Date: Mon Feb 14 2022 - 05:47:47 EST


On Sun, Feb 13, 2022 at 08:01:18PM +0800, Chengming Zhou wrote:
> The cpuacct_account_field() is always called by the current task
> itself, so it's ok to use __this_cpu_add() to charge the tick time.
>
> But cpuacct_charge() maybe called by update_curr() in load_balance()
> on a random CPU, different from the CPU on which the task is running.
> So __this_cpu_add() will charge that cputime to a random incorrect CPU.
>
> Reported-by: Minye Zhu <zhuminye@xxxxxxxxxxxxx>
> Signed-off-by: Chengming Zhou <zhouchengming@xxxxxxxxxxxxx>

Can I get a Fixes: tag for this?

> ---
> kernel/sched/cpuacct.c | 3 ++-
> 1 file changed, 2 insertions(+), 1 deletion(-)
>
> diff --git a/kernel/sched/cpuacct.c b/kernel/sched/cpuacct.c
> index 3d06c5e4220d..75fbc212cb71 100644
> --- a/kernel/sched/cpuacct.c
> +++ b/kernel/sched/cpuacct.c
> @@ -335,11 +335,12 @@ static struct cftype files[] = {
> void cpuacct_charge(struct task_struct *tsk, u64 cputime)
> {
> struct cpuacct *ca;
> + unsigned int cpu = task_cpu(tsk);
>
> rcu_read_lock();
>
> for (ca = task_ca(tsk); ca; ca = parent_ca(ca))
> - __this_cpu_add(*ca->cpuusage, cputime);
> + *per_cpu_ptr(ca->cpuusage, cpu) += cputime;
>
> rcu_read_unlock();
> }

Also, while we there, what about this as an additional patch?

--- a/kernel/sched/cpuacct.c
+++ b/kernel/sched/cpuacct.c
@@ -334,15 +334,13 @@ static struct cftype files[] = {
*/
void cpuacct_charge(struct task_struct *tsk, u64 cputime)
{
- struct cpuacct *ca;
unsigned int cpu = task_cpu(tsk);
+ struct cpuacct *ca;

- rcu_read_lock();
+ lockdep_assert_rq_held(cpu_rq(cpu));

for (ca = task_ca(tsk); ca; ca = parent_ca(ca))
*per_cpu_ptr(ca->cpuusage, cpu) += cputime;
-
- rcu_read_unlock();
}

/*