[PATCH 4/6] posix-cpu-timers: Force next_expiration recalc after timer reset

From: Frederic Weisbecker
Date: Fri Jun 04 2021 - 07:32:16 EST


A timer reset only dequeues the timer but it doesn't shutdown
the related costly process wide cputimer counter and the tick dependency.

The following code snippet keeps this overhead around for one week after
the timer reset:

void trigger_process_counter(void)
{
timer_t id;
struct itimerspec val = { };

val.it_value.tv_sec = 1;
timer_create(CLOCK_PROCESS_CPUTIME_ID, NULL, &id);
timer_settime(id, 0, &val, NULL);
val.it_value.tv_sec = 0;
timer_settime(id, 0, &val, NULL);
}

Make sure the next target's tick recalculates the nearest expiration and
clears the process wide counter and tick dependency if necessary.

Signed-off-by: Frederic Weisbecker <frederic@xxxxxxxxxx>
Cc: Oleg Nesterov <oleg@xxxxxxxxxx>
Cc: Thomas Gleixner <tglx@xxxxxxxxxxxxx>
Cc: Peter Zijlstra (Intel) <peterz@xxxxxxxxxxxxx>
Cc: Ingo Molnar <mingo@xxxxxxxxxx>
Cc: Eric W. Biederman <ebiederm@xxxxxxxxxxxx>
---
kernel/time/posix-cpu-timers.c | 20 +++++++++++++-------
1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/kernel/time/posix-cpu-timers.c b/kernel/time/posix-cpu-timers.c
index bb1f862c785e..0b5715c8db04 100644
--- a/kernel/time/posix-cpu-timers.c
+++ b/kernel/time/posix-cpu-timers.c
@@ -414,10 +414,14 @@ static int posix_cpu_timer_create(struct k_itimer *new_timer)
static void disarm_timer(struct k_itimer *timer, struct task_struct *p)
{
struct cpu_timer *ctmr = &timer->it.cpu;
+ u64 old_expires = cpu_timer_getexpires(ctmr);
struct posix_cputimer_base *base;
+ bool queued;
int clkidx;

- if (!cpu_timer_dequeue(ctmr))
+ queued = cpu_timer_dequeue(ctmr);
+ cpu_timer_setexpires(ctmr, 0);
+ if (!queued)
return;

clkidx = CPUCLOCK_WHICH(timer->it_clock);
@@ -427,7 +431,7 @@ static void disarm_timer(struct k_itimer *timer, struct task_struct *p)
else
base = p->signal->posix_cputimers.bases + clkidx;

- if (cpu_timer_getexpires(ctmr) == base->nextevt)
+ if (old_expires == base->nextevt)
base->nextevt = 0;
}

@@ -647,8 +651,6 @@ static int posix_cpu_timer_set(struct k_itimer *timer, int timer_flags,
if (unlikely(timer->it.cpu.firing)) {
timer->it.cpu.firing = -1;
ret = TIMER_RETRY;
- } else {
- cpu_timer_dequeue(ctmr);
}

/*
@@ -713,9 +715,13 @@ static int posix_cpu_timer_set(struct k_itimer *timer, int timer_flags,
* For a timer with no notification action, we don't actually
* arm the timer (we'll just fake it for timer_gettime).
*/
- cpu_timer_setexpires(ctmr, new_expires);
- if (new_expires != 0 && val < new_expires) {
- arm_timer(timer, p);
+ if (new_expires != 0) {
+ cpu_timer_dequeue(ctmr);
+ cpu_timer_setexpires(ctmr, new_expires);
+ if (val < new_expires)
+ arm_timer(timer, p);
+ } else {
+ disarm_timer(timer, p);
}

unlock_task_sighand(p, &flags);
--
2.25.1