[tip: sched/core] sched,perf,kvm: Fix preemption condition

From: tip-bot2 for Peter Zijlstra
Date: Fri Jun 18 2021 - 07:24:15 EST


The following commit has been merged into the sched/core branch of tip:

Commit-ID: 3ba9f93b12361e005dd65fcc8072b42e3189f4f4
Gitweb: https://git.kernel.org/tip/3ba9f93b12361e005dd65fcc8072b42e3189f4f4
Author: Peter Zijlstra <peterz@xxxxxxxxxxxxx>
AuthorDate: Fri, 11 Jun 2021 10:28:13 +02:00
Committer: Peter Zijlstra <peterz@xxxxxxxxxxxxx>
CommitterDate: Fri, 18 Jun 2021 11:43:07 +02:00

sched,perf,kvm: Fix preemption condition

When ran from the sched-out path (preempt_notifier or perf_event),
p->state is irrelevant to determine preemption. You can get preempted
with !task_is_running() just fine.

The right indicator for preemption is if the task is still on the
runqueue in the sched-out path.

Signed-off-by: Peter Zijlstra (Intel) <peterz@xxxxxxxxxxxxx>
Acked-by: Mark Rutland <mark.rutland@xxxxxxx>
Link: https://lore.kernel.org/r/20210611082838.285099381@xxxxxxxxxxxxx
---
kernel/events/core.c | 7 +++----
virt/kvm/kvm_main.c | 2 +-
2 files changed, 4 insertions(+), 5 deletions(-)

diff --git a/kernel/events/core.c b/kernel/events/core.c
index fe88d6e..fd89000 100644
--- a/kernel/events/core.c
+++ b/kernel/events/core.c
@@ -8682,13 +8682,12 @@ static void perf_event_switch(struct task_struct *task,
},
};

- if (!sched_in && task->state == TASK_RUNNING)
+ if (!sched_in && task->on_rq) {
switch_event.event_id.header.misc |=
PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
+ }

- perf_iterate_sb(perf_event_switch_output,
- &switch_event,
- NULL);
+ perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
}

/*
diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c
index 6a6bc7a..5f166eb 100644
--- a/virt/kvm/kvm_main.c
+++ b/virt/kvm/kvm_main.c
@@ -5025,7 +5025,7 @@ static void kvm_sched_out(struct preempt_notifier *pn,
{
struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);

- if (current->state == TASK_RUNNING) {
+ if (current->on_rq) {
WRITE_ONCE(vcpu->preempted, true);
WRITE_ONCE(vcpu->ready, true);
}