Skip to content

Commit eb1b4af

Browse files
Rik van Rielingomolnar
authored andcommitted
sched, time: Atomically increment stime & utime
The functions task_cputime_adjusted and thread_group_cputime_adjusted() can be called locklessly, as well as concurrently on many different CPUs. This can occasionally lead to the utime and stime reported by times(), and other syscalls like it, going backward. The cause for this appears to be multiple threads racing in cputime_adjust(), both with values for utime or stime that is larger than the original, but each with a different value. Sometimes the larger value gets saved first, only to be immediately overwritten with a smaller value by another thread. Using atomic exchange prevents that problem, and ensures time progresses monotonically. Signed-off-by: Rik van Riel <riel@redhat.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: umgwanakikbuti@gmail.com Cc: fweisbec@gmail.com Cc: akpm@linux-foundation.org Cc: srao@redhat.com Cc: lwoodman@redhat.com Cc: atheurer@redhat.com Cc: oleg@redhat.com Link: http://lkml.kernel.org/r/1408133138-22048-4-git-send-email-riel@redhat.com Signed-off-by: Ingo Molnar <mingo@kernel.org>
1 parent e78c349 commit eb1b4af

1 file changed

Lines changed: 5 additions & 2 deletions

File tree

‎kernel/sched/cputime.c‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -602,9 +602,12 @@ static void cputime_adjust(struct task_cputime *curr,
602602
* If the tick based count grows faster than the scheduler one,
603603
* the result of the scaling may go backward.
604604
* Let's enforce monotonicity.
605+
* Atomic exchange protects against concurrent cputime_adjust().
605606
*/
606-
prev->stime = max(prev->stime, stime);
607-
prev->utime = max(prev->utime, utime);
607+
while (stime > (rtime = ACCESS_ONCE(prev->stime)))
608+
cmpxchg(&prev->stime, rtime, stime);
609+
while (utime > (rtime = ACCESS_ONCE(prev->utime)))
610+
cmpxchg(&prev->utime, rtime, utime);
608611

609612
out:
610613
*ut = prev->utime;

0 commit comments

Comments
 (0)